diff --git a/design/architecture/decisions/README.md b/design/architecture/decisions/README.md index 6546d807b2..6d46df38b0 100644 --- a/design/architecture/decisions/README.md +++ b/design/architecture/decisions/README.md @@ -171,7 +171,7 @@ Validation precedence is fixed: first parse every checked queue row and validate | [ADR 0072](./adr-0072-class-specific-timer-durability-and-recovery.md) | Accepted | `AS-1.4` | `GR-1.2`, `GR-2.3`, `AS-1.5`, `SF-1.4` | Class-specific timer durability and recovery | | [ADR 0073](./adr-0073-evidence-calibrated-tick-budgets-and-lock-ttls.md) | Accepted | `SF-1.4` | `GR-1.2`, `GR-1.3`, `PO-4.2`, `AR-2.3` | Evidence-calibrated tick budgets and lock TTLs | | [ADR 0074](./adr-0074-one-entity-lock-per-redis-script.md) | Accepted | `GR-1.3` | `SF-2.2`, `GR-4.1`, `PO-4.4` | One entity lock per Redis script | -| [ADR 0075](./adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md) | Accepted | `GR-4.1` | `GR-1.2`, `AS-1.2`, `PO-4.2` | Depth, cost, and count bounds for generated effect chains | +| [ADR 0075](./adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md) | Accepted | `GR-4.1` | `GR-1.2`, `AS-1.2`, `PO-4.2` | Depth, cost, and count bounds with replay-stable owner-defined child identity and lineage | | [ADR 0076](./adr-0076-failure-class-specific-durable-tick-retries.md) | Accepted | `GR-1.2` | `PO-2.4`, `PO-4.2`, `SF-2.3` | Failure-class-specific durable tick retries | | [ADR 0077](./adr-0077-durable-global-effect-fanout-and-lightweight-idle-ticks.md) | Accepted | `GR-1.2` | `GR-2.1`, `AS-1.4`, `SF-1.4`, `PO-4.2` | Durable global-effect fan-out and lightweight idle ticks | | [ADR 0078](./adr-0078-digest-bound-workflow-and-step-retry-identities.md) | Accepted | `SF-2.3` | `SF-2.4`, `SF-1.2` | Digest-bound workflow and step retry identities | @@ -277,6 +277,7 @@ Validation precedence is fixed: first parse every checked queue row and validate | [ADR 0180](./adr-0180-account-owned-hosted-terms-acceptance-gate.md) | Accepted | `AA-1.3` | `AA-1.5`, `AR-1.1`, `AR-1.4`, `AR-1.5`, `EA-3.2`, `PO-1.3`, `SF-2.3` | Account-owned hosted-terms catalog, acceptance evidence, and official-hosted creator mutation gate | | [ADR 0181](./adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md) | Accepted | `PO-1.3` | `AA-1.3`, `AA-1.4`, `AA-1.5`, `AR-1.1`, `AR-1.4`, `AR-1.5`, `EA-3.2`, `SF-2.3` | Changed hosted-terms decline, prior-terms continuity, lifecycle-reducing access, and finite transition | | [ADR 0182](./adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md) | Accepted | `PO-3.2` | `PO-3.1`, `PO-4.4`, `SF-1.3`, `PO-1.1` | Separated hosted runtime and certificate-identity lifecycles | +| [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) | Proposed - Pending Human Review | `GR-1.2` | `GR-1.4`, `GR-4.1`, `AS-1.2`, `AS-1.4`, `SF-1.4`, `SF-2.3`, `PO-4.2` | Pending command-plan ordering, `planOrdinal`, command-root allocation, UUIDv7 scalar, canonical serialization, and additional child/fan-out allocation mechanics | | [ADR 0184](./adr-0184-emergency-tcp-proxy-identity-withdrawal.md) | Accepted | `SF-1.3` | `PO-2.1`, `PO-2.2`, `PO-3.2`, `PO-4.4` | Emergency trust cutoff for a withdrawn TCP Proxy bridge identity | Capability identifiers are defined in the [FireMUD Product Capability Taxonomy](../../product/capability-taxonomy.md). diff --git a/design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md b/design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md index f2e2831bb5..c5d2e5092a 100644 --- a/design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md +++ b/design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md @@ -4,9 +4,11 @@ Superseded by [ADR 0172](./adr-0172-parent-event-and-frozen-handler-execution-identity.md) +This ADR preserves historical ingress-idempotency context, not an independent current identity contract. [ADR 0172](./adr-0172-parent-event-and-frozen-handler-execution-identity.md) owns parent-event and frozen-handler execution identity; [Scripting Normative Contract Tables](../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) owns the current endpoint-specific Trigger Identity fields and scheduler candidate preimage. + ## Implementation Status -The live `ScriptScheduleInstanceServiceImpl.TimerFiringCandidate.identity()` implementation remains narrower than the canonical scheduler preimage until the target and owner/plugin fields are carried. It currently resolves `playableStateScope` and emits `eventSchemaVersion=v1`, `isDryRun=false`, and `triggerMode=TRIGGER_MODE_CATCH_UP`; those values are explicit inputs even while they remain constant. It has no cross-producer golden-vector proof for the canonical preimage or its numeric formatting rules. See the [automation and scheduler runtime tracker](../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status). +The live `ScriptScheduleInstanceServiceImpl.TimerFiringCandidate.identity()` implementation remains narrower than the canonical scheduler preimage until the target and owner/plugin fields are carried. It currently uses resolved `playableStateScope` in the identity preimage and emits `eventSchemaVersion=v1`, `isDryRun=false`, and `triggerMode=TRIGGER_MODE_CATCH_UP`; authoritative `playableStateNamespaceId` identity and separate non-identity scope evidence are target-state. The current values remain explicit preimage inputs even while they are constant. It has no cross-producer golden-vector proof for the canonical preimage or its numeric formatting rules. See the [automation and scheduler runtime tracker](../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status). ## Context @@ -14,25 +16,26 @@ Event-ingress RPCs into the Automation & Scripting Service must be idempotent un ## Decision -Automation & Scripting treats event ingress as at-most-once per **Trigger Identity**. The exact endpoint-specific field matrix is owned by [Scripting Normative Contract Tables](../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) so the ADR and runtime contract cannot evolve as competing tuples. +The original decision treated event ingress as at-most-once per **Trigger Identity**. Current endpoint-specific identity semantics are owned by [Scripting Normative Contract Tables](../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) and [ADR 0172](./adr-0172-parent-event-and-frozen-handler-execution-identity.md); the notes below preserve context without defining a competing tuple. -- Gameplay/runtime handler identity includes the applicable `tenantId`, `gameInstanceId`, resolved `playableStateScope`, `regionId`, `regionEpoch`, `entityId`, `scriptId`, `eventType`, `eventSchemaVersion`, `scriptPatchVersion`, `scriptEventId`, and `isDryRun` fields. -- `isDryRun` is always an identity dimension so live and test execution cannot collide. -- Scheduler/timer identity additionally carries its due point and trigger mode. The canonical scheduler preimage fields are serialized in this fixed order: ``. Fields marked `when ...` are omitted, not replaced by empty or sentinel values, when their branch does not apply; `targetScopeType` makes the target selector explicit and `stableOwnerKind` makes the core/plugin owner branch explicit. Thus `scriptEventId` itself is never part of this preimage, and `resumeWindowId` is absent for non-catch-up triggers. `duePoint` is exactly one tagged value: `dueTickId:` for tick-aligned schedules or `dueAt:` for wall-clock timers. Any additional scheduler schema version or trigger mode must become an explicit deterministic-ID input before it is admitted. -- The canonical target preimage is the fixed-order, length-prefixed UTF-8 serialization that `ScriptScheduleInstanceServiceImpl.TimerFiringCandidate.identity()` must implement. Each field is encoded as its UTF-8 byte length rendered as unsigned base-10 ASCII decimal with no leading zeroes, followed by a colon and its unescaped UTF-8 value; fields are concatenated without separators. Numeric identity values therefore use their canonical base-10 ASCII spelling (for example, `0`, `7`, and `-1`), and the prefix length counts UTF-8 bytes rather than Unicode code points. Semantic validation still controls which numeric values are admissible; deterministic decimal serialization does not make an otherwise invalid value valid. Boolean values serialize canonically as lowercase `true` or `false`. Enum values serialize as the contract-declared enum symbol/name, never an ordinal, localized spelling, or other implementation-specific representation. This permits delimiters and arbitrary UTF-8 text without creating tuple collisions. Hash those bytes with SHA-256, encode the digest as lowercase hexadecimal, retain the first 60 hexadecimal characters, and prefix the result with `timer-`. Cross-producer golden vectors must cover empty values, non-ASCII values, delimiters, negative and zero numeric values, both boolean values, representative enum branches, and both tagged due-point branches before this identity is considered proven. -- Tenant-readiness `onLoad` follows the explicit non-runtime exception in the normative table and does not invent sentinel runtime, region, or entity identity. -- Plugin-trigger identity additionally carries plugin and binding identity where the invocation unit is plugin- or binding-scoped. +- Presented `playableStateScope` is exact-validated evidence, not a uniqueness discriminator. Stale or mismatched scope remains fenced until authoritative reconciliation; a namespace-keyed identity may be reused only if authority proves scope unchanged. An authority-proven transition starts a new playable-state lifecycle and namespace. +- Live/test separation, tenant-readiness `onLoad` exceptions, and plugin/binding identity follow the applicable fields and branches in the normative table and ADR 0172; this superseded ADR does not define their current schema. +- Scheduler/timer candidate identity, including its conditional branches, serialization, hash, and proof requirements, is owned by [Table 1's Scheduler Candidate Identity Preimage](../system-architecture-scripting-normative-contract-tables.md#scheduler-candidate-identity-preimage-normative). -Ordinary event-ingress callers must reuse the same full applicable Trigger Identity, including the same `scriptEventId`, when retrying a logically identical trigger. Scheduler retries instead reuse the same complete due-candidate/firing-claim identity and its deterministically derived `scriptEventId`; that derived ID is propagated into resolved handler identities but remains excluded from `TimerFiringCandidate.identity()`'s scheduler preimage. +Retry identity and handler materialization follow the current Trigger Identity and scheduler-candidate owners linked above; the original decision's retry rule is historical context rather than a separate current specification. ## Consequences -- Protos and service contracts must carry enough fields to represent the endpoint-specific Trigger Identity, including runtime scope, dry-run namespace, and due-point or plugin dimensions where applicable. -- Audit records (`script_event_audit`) must be keyed by Trigger Identity, not by `scriptEventId` alone. +- Current proto and service requirements for endpoint-specific Trigger Identity and frozen handler execution are owned by [Scripting Normative Contract Tables](../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) and [ADR 0172](./adr-0172-parent-event-and-frozen-handler-execution-identity.md); this ADR's original consequence is historical context. +- Audit records (`script_event_audit`) follow the current Trigger Identity contract, not `scriptEventId` alone. ## Implementation and Proof Obligations -Prove the endpoint-specific Trigger Identity field matrix, fixed-order scheduler preimage, length-prefixed UTF-8 serialization, canonical numeric, boolean, and enum forms, optional-branch omission, deterministic hashing, cross-producer golden vectors, and exact retry reuse without collisions or duplicate logical triggers. Select and report the required checks and evidence under [Validation and Runtime Proof](../../developer-workflows/validation-and-runtime-proof.md); record execution results in PR/CI evidence or implementation-tracking documents rather than in this decision record. +Current implementation and proof obligations are owned by [ADR 0172](./adr-0172-parent-event-and-frozen-handler-execution-identity.md) and the canonical identity matrix and scheduler-preimage requirements in [Scripting Normative Contract Tables](../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). Select and report checks under [Validation and Runtime Proof](../../developer-workflows/validation-and-runtime-proof.md); this superseded ADR is not an independent proof authority. + +## Supersession + +- Replacement ADR: [ADR 0172](./adr-0172-parent-event-and-frozen-handler-execution-identity.md) ## References diff --git a/design/architecture/decisions/adr-0002-automation-handoff-reliability-and-success-semantics.md b/design/architecture/decisions/adr-0002-automation-handoff-reliability-and-success-semantics.md index 165e689a7e..a611949339 100644 --- a/design/architecture/decisions/adr-0002-automation-handoff-reliability-and-success-semantics.md +++ b/design/architecture/decisions/adr-0002-automation-handoff-reliability-and-success-semantics.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -This decision is partially implemented. Stage-qualified outcomes exist, but the database-save/Redis-stage gap, durable per-dispatch custody, and state-sensitive duplicate handling do not yet satisfy the accepted handoff boundary. See the [automation and scheduler runtime tracker](../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status) for current implementation and proof status. +This decision is partially implemented. Stage-qualified outcomes exist, but durable outbox persistence and queue-pointer publication, durable per-dispatch custody, and state-sensitive duplicate handling do not yet satisfy the accepted handoff boundary. See the [automation and scheduler runtime tracker](../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status) for current implementation and proof status. ## Decision Record @@ -17,23 +17,21 @@ This decision is partially implemented. Stage-qualified outcomes exist, but the ## Context -Scripting produces commands that must flow into the tick system. The historical design included Redis-based staging (`automation:queue:*` and the former `automation:tick:*` path) and internal gRPC handoff to Game Session. The `automation:tick:*` path is retired and not live; current automation stages work through `automation:queue:*` and hands gameplay enqueue to Game Session. Without a clear contract, “success” can mean either “DSL ran” or “effects will happen”, which undermines rollback semantics and operator trust. +Scripting produces commands that must flow into the tick system. The historical design included Redis-based staging (the former `automation:tick:*` path), which is retired and not live; current automation stages work through `automation:queue:*` discovery pointers and hands gameplay enqueue to Game Session. The target design records script work items in a durable PostgreSQL outbox and publishes instance-aware queue pointers in Cache/Rate-Limit Redis. Queue pointers are disposable discovery indexes, not work truth; durable outbox rows and Game Session handoff custody determine recovery and success. The current implementation has narrower work-item persistence and queue-pointer paths, but does not yet prove this accepted durable publication and custody boundary. Without a clear contract, “success” can mean either “DSL ran” or “effects will happen”, which undermines rollback semantics and operator trust. ## Decision - The historical generic label `script_event_audit.finalOutcome=success` is superseded **only as a label** by [ADR 0064](adr-0064-stage-qualified-script-outcomes.md). For a live command-producing handler, `finalStage=TICK_HANDOFF` and `finalOutcome=handoff_accepted` mean every required child dispatch is in Game Session custody: each child is either durably adopted/admitted, or covered by a committed per-child durable re-drive obligation that Game Session owns for outcome convergence. This is not a claim that gameplay effects were applied. The canonical stage-qualified outcomes are defined in the [scripting normative outcome table](../system-architecture-scripting-normative-contract-tables.md#canonical-finaloutcome-values-normative). - `completed_no_commands`, `readiness_success`, and `dry_run_success` remain distinct non-handoff outcomes in their declared branches. -- Local `automation:queue:*` staging is only pending Automation work-item discovery and is not handoff acceptance. A durable remote coordinator or follow-up schedule counts as the per-child re-drive obligation only when Game Session transactionally accepts it under stable identities; acceptance never means that the target tick has executed. +- In the target state, the durable PostgreSQL outbox/work-item row is the pending-work record. An instance-aware `automation:queue:*` pointer in Cache/Rate-Limit Redis is only a disposable discovery index; it is neither handoff acceptance nor work truth. A durable remote coordinator or follow-up schedule counts as the per-child re-drive obligation only when Game Session transactionally accepts it under stable identities; acceptance never means that the target tick has executed. - The pipeline must record stage-aware outcomes so operators can see where a trigger failed to progress (DSL evaluation vs persistence vs handoff/enqueue). -- Duplicate lookup compares the immutable dispatch digest and returns accepted only from a state that proves handoff custody. A received-but-unstaged volatile row must be re-driven, reported pending or not accepted, or exposed as terminal `NOT_APPLIED`; it must never become an unconditional accepted no-op. -- If Redis staging queues are reset/lost, the system must either: - - re-drive delivery from a durable outbox of script work items, or - - record explicit “dropped before tick enqueue” outcomes and never report `handoff_accepted`. +- Duplicate lookup compares the immutable dispatch digest and returns accepted only from a state that proves handoff custody. A received-but-not-yet-handed-off durable outbox/work-item row must be re-driven, reported pending or not accepted, or exposed as terminal `NOT_APPLIED`; it must never become an unconditional accepted no-op because a discovery pointer is absent. +- If `automation:queue:*` discovery pointers in Cache/Rate-Limit Redis are reset or lost, the system must rebuild them from durable PostgreSQL outbox/work-item rows and re-drive delivery; pointer loss is not a dropped-work outcome. If durable outbox persistence fails before Game Session handoff, the system must record an explicit persistence/drop outcome and never report `handoff_accepted`. ## Consequences - The Automation & Scripting Service must have a durable representation of “pending script work items” if the target behavior is “do not drop silently”. -- Any best-effort Redis buffer (`automation:queue:*`) cannot be the sole record of admitted work if `handoff_accepted` implies tick acceptance. +- Any Cache/Rate-Limit Redis discovery pointer (`automation:queue:*`) cannot be the sole record of admitted work if `handoff_accepted` implies tick acceptance. - A handler may be `handoff_accepted` even when one of its commands later becomes `NOT_APPLIED` or `ABANDONED`; the authoritative per-command status explains that later result. ## References diff --git a/design/architecture/decisions/adr-0009-coordination-redis-ownership-boundary.md b/design/architecture/decisions/adr-0009-coordination-redis-ownership-boundary.md index 807f6542c8..98cff8f111 100644 --- a/design/architecture/decisions/adr-0009-coordination-redis-ownership-boundary.md +++ b/design/architecture/decisions/adr-0009-coordination-redis-ownership-boundary.md @@ -21,10 +21,11 @@ The architecture already distinguishes ownership from participation, but the bou Coordination Redis ownership is explicit and narrow: - Game Session Service owns gameplay coordination keyspace and schema (for example `tick:*`, `timer:*`, `retry:*`, `session:game:*`, and lease-related prefixes). -- Account Service owns authentication allowlist/session-auth prefixes (`session:auth:*`) and their lifecycle semantics, plus the already accepted `session:connect-token:*` issuance-result projection/cache defined by [ADR 0029](./adr-0029-single-use-gameplay-connect-token-carriage.md). -- Automation & Scripting Service owns automation coordination and cache families with an explicit split: - - Coordination Redis: Automation & Scripting owns the target scheduler/checkpoint boundary represented by `automation:timer:*` and `script-scheduler:*` once implemented. These are reset-tolerant projections rebuilt from durable schedules, trigger-instance rows, and heartbeat progress; durable schedules and trigger-instance de-duplication remain PostgreSQL authority. They are target-state names, not current runtime guarantees. The former `automation:tick:*` staging path is retired, not live, and is not an active owned prefix. - - Cache/Rate-Limit Redis: `automation:queue:*`, `automation:quota:*`, `automation:tenant-budget:*`, `automation:test:quota:*`, `automation:test:capacity:*`, and `automation:readiness:capacity:*` best-effort buffers/counters and owner-token leases. These remain distinct from the target Coordination Redis `automation:timer:*` and `script-scheduler:*` projections. +- Account Service owns the exact authentication/session-auth families recorded by the Redis hub: `session:auth:account:*`, `session:auth:tenant:*`, `session:auth:token:*`, and `session:auth:generation:*`, together with their lifecycle semantics. It also owns the separate exact-input `session:connect-token:tenant::account::scope::request:` issuance-result/idempotency family defined by [ADR 0029](./adr-0029-single-use-gameplay-connect-token-carriage.md). No wildcard `session:auth:*` ACL or authority grant is implied. +- Gateway Service owns the exact connect-token replay, browser-deny, readiness/fence, and recovery-probe key families in the pinned `gateway-connect-token-replay-v1` domain: `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`, `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::`, as defined by [ADR 0029](./adr-0029-single-use-gameplay-connect-token-carriage.md). These are bounded Gateway-owned replay and recovery records, not wildcard access or a broader non-owner participation grant. +- Automation & Scripting Service owns automation coordination and cache families with an explicit current-versus-target split: + - Coordination Redis: it owns the target scheduler/checkpoint boundary represented by `automation:timer:*` and `script-scheduler:*` once implemented. These are reset-tolerant projections rebuilt from durable schedules, trigger-instance rows, and heartbeat progress; durable schedules and trigger-instance de-duplication remain PostgreSQL authority. They are target-state names, not current runtime guarantees. The former `automation:tick:*` staging path is retired, not live, and is not an active owned prefix. + - Cache/Rate-Limit Redis: `automation:queue:*` discovery pointers, `automation:quota:*`, `automation:tenant-budget:*`, `automation:test:quota:*`, `automation:test:capacity:*`, and `automation:readiness:capacity:*` best-effort buffers/counters and owner-token leases; queue pointers are disposable indexes, not work truth. The test and readiness families remain unsupported for target adoption until each is centrally registered and has slot-safe keying. These remain distinct from the target Coordination Redis `automation:timer:*` and `script-scheduler:*` projections. - Non-owner services may participate only through approved shared helpers and documented prefixes/contracts. Owner-managed bridge contracts are the only approved exception to “write only your own keys”: diff --git a/design/architecture/decisions/adr-0011-gameplay-session-front-end-and-region-execution.md b/design/architecture/decisions/adr-0011-gameplay-session-front-end-and-region-execution.md index 8de7c7867b..c1070e718d 100644 --- a/design/architecture/decisions/adr-0011-gameplay-session-front-end-and-region-execution.md +++ b/design/architecture/decisions/adr-0011-gameplay-session-front-end-and-region-execution.md @@ -4,6 +4,10 @@ Superseded by [ADR 0170](./adr-0170-fenced-command-forwarding-and-authoritative-region-transition.md) +## Supersession + +- Replacement ADR: [ADR 0170](./adr-0170-fenced-command-forwarding-and-authoritative-region-transition.md) + ## Context FireMUD already makes two high-level decisions: @@ -19,51 +23,12 @@ Without an explicit answer, docs and implementations risk drifting toward incomp - silent cross-pod forwarding without fencing rules, - or forced reconnects on ordinary lease rebalancing. -## Decision - -FireMUD adopts a **session front-end + lease-owner execution** model inside the Game Session layer. - -- A connected gameplay socket is attached to a **session front-end** Game Session pod. -- Region-scoped gameplay execution remains owned by the pod that currently holds the relevant `` lease. -- The session front-end pod may accept input, authenticate the session, manage connection-local state, and stream results back to the client. -- The session front-end pod must not mutate tick-owned gameplay coordination state for a region it does not own. -- When command execution or tick-owned mutation targets a region leased by another pod, the session front-end forwards the request over internal gRPC to the current **lease owner**. -- Only the lease owner may stage or commit Redis coordination changes for that region. -- `playableStateScope` is part of the forwarded request identity and must be preserved and validated end to end because it distinguishes the gameplay state/effect scope being acted on. -- `playableStateScope` is not an additional lease-ownership dimension. Lease ownership remains keyed by ``; the current owner and its fence apply to the region, while the owner validates the forwarded playable-state scope against the authoritative gameplay binding. - -## Consequences - -- Spring Cloud Gateway remains shard-unaware and continues to route `/ws/game/**` to a stable Game Session service surface. -- Normal in-cluster lease rebalancing does not require client-visible reconnects solely because region ownership moved. -- Socket ownership and region execution ownership are decoupled; runbooks and observability must treat them as separate roles. -- Internal forwarding paths must carry enough fenced identity to prevent stale front-ends from mutating a region after lease loss. -- If internal forwarding becomes unavailable or inconsistent, Game Session may fail the affected command or close the gameplay session using the existing reconnect model; it must not invent a separate edge-visible shard-handoff taxonomy without a new design update. +## Historical Rationale -## Required Internal Forwarding Contract +This ADR separated stable socket ownership from region execution ownership so ordinary lease movement would not force player reconnects, while rejecting silent, unfenced cross-pod mutation. The detailed decision has been superseded: [ADR 0170](./adr-0170-fenced-command-forwarding-and-authoritative-region-transition.md) owns the current contract for authoritative region transitions, owner forwarding, identity, fences, retries, and failure handling. The former mandatory forwarding details in this ADR no longer define a current contract. -Any session front-end to lease-owner forwarding path must implement one canonical contract: - -- Every forwarded request carries `tenantId`, `gameInstanceId`, `playableStateScope`, `sessionId`, `characterId`, target `regionId`, command or action identifier, and a monotonic per-session sequencing token so the lease owner can preserve session-local ordering. -- Every forwarded request carries the lease/epoch fence for the target region. A lease owner must reject requests with a stale or missing fence using an application-level stale-lease error. -- The session front-end may retry only idempotent forwarded operations and must not create duplicate tick-owned mutations when a response is ambiguous. -- If lease ownership changes before execution starts, the front-end must refresh ownership and retry against the new lease owner. If ownership changes after execution has begun, the in-flight attempt is owned by the executor that accepted the fenced request and later attempts must use the new fence. -- If forwarding times out or the target lease owner is unavailable, Game Session must either fail the affected command with the documented structured error path or terminate the gameplay session using the existing reconnection contract. It must not invent a separate client-visible shard-handoff behavior. - -Service-level docs may add implementation detail, but they must not weaken these fencing, ordering, or failure rules. - -## Non-Goals +## Historical Non-Goals - This ADR does not introduce a Gateway-owned gameplay shard-routing plane. - This ADR does not define multi-cluster gameplay execution. - This ADR does not introduce a client-visible shard-handoff close category. - -## Required Documentation Alignment - -The following docs must remain aligned with this decision: - -- `design/architecture/system-architecture-overview.md` -- `design/architecture/system-architecture-reconnection.md` -- `design/architecture/system-architecture-diagram.md` -- `design/architecture/microservices/game-session-service/README.md` -- `design/architecture/microservices/spring-cloud-gateway/README.md` diff --git a/design/architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md b/design/architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md index 7821327d63..a1e8d8b985 100644 --- a/design/architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md +++ b/design/architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md @@ -54,7 +54,7 @@ Existing values such as `STAGED`, `DRAINED`, and `RETRY_QUEUED` map to lifecycle ### Authority and Convergence -- `GetGameplayCommandStatus` reads the authoritative durable record by `commandId` scoped to `tenantId` and `gameInstanceId`, or by the automation handoff identity `(tenantId, gameInstanceId, regionId, regionEpoch, automationDispatchId)`. The `regionId` and `regionEpoch` routing fields apply to the automation-identity lookup. Redis coordination state is not part of the lookup authority. +- `GetGameplayCommandStatus` reads the authoritative durable record only by the point-lookup key `{tenantId, gameInstanceId, commandId}`. The automation tuple `(tenantId, gameInstanceId, regionId, regionEpoch, automationDispatchId)` is a collection/filter correlation key only, not a point-lookup or uniqueness key: one dispatch may contain multiple emitted commands distinguished by `commandOrdinal` in the complete Command-Handoff Identity defined by the scripting normative contract table. If an automation-correlated status view is exposed, it returns an explicitly bounded collection rather than selecting one authoritative record from that tuple; `regionId` and `regionEpoch` apply only as routing/filter fields. Redis coordination state is not part of the lookup authority. - Status reads require the same caller-bound subject/actor authority recorded at ingress or an explicitly authorized internal/operator route. Possession or collision of a client-generated `commandId` is never status-read authority. - Optional outcome events or streams may reduce observation latency, but they are advisory projections of the same lifecycle. - Every accepted command converges to an explicit terminal result. An `ACCEPTED_VOLATILE` command lost before durable batch binding becomes `LOST_BEFORE_STAGING` with `NOT_APPLIED` rather than remaining indefinitely pending. diff --git a/design/architecture/decisions/adr-0029-single-use-gameplay-connect-token-carriage.md b/design/architecture/decisions/adr-0029-single-use-gameplay-connect-token-carriage.md index 8409772119..66216321cf 100644 --- a/design/architecture/decisions/adr-0029-single-use-gameplay-connect-token-carriage.md +++ b/design/architecture/decisions/adr-0029-single-use-gameplay-connect-token-carriage.md @@ -49,14 +49,14 @@ For browser logout, Gateway exposes exactly `POST /ws/game/connect-token/revoke` - Gateway atomically consumes `jti` in the player-facing Coordination Redis deployment before attempting the upstream WebSocket connection. That deployment uses Redis 7.2 or newer with AOF enabled, `noeviction`, ACLs that prevent non-replay callers from mutating replay, deny-marker, and readiness/fence keys, and reserved capacity above the bounded maximum live marker set. Replay and browser-deny markers never share a cache/rate-limit deployment or an eviction policy. Capacity alerts and an admission-readiness threshold fail new handshakes before memory exhaustion can make marker writes unreliable. The single consume script receives `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:` in that order as one Coordination Redis atomic operation; it requires `state=OPEN`, exact fence equality, the signed-`iat` quarantine-cutoff predicate, and no deny marker, then creates the replay key with its expiry at `exp + firemud.gateway.connectTokenClockSkewMs`. It returns exactly one integer: `1` when this request wins the `jti` race, `0` when the replay marker already exists, and `-1` when the browser deny marker exists. Gateway must parse that reply as exactly one integer under both RESP2 and RESP3; null, error, wrong type, wrong arity, or any value other than `-1`, `0`, or `1` is an uncertain outcome and fails closed. A `0` or `-1` result does not create or acknowledge a replay marker. For a newly created marker, Gateway immediately executes `WAITAOF requiredLocalAofCount requiredReplicaAofCount firemud.gateway.replayConsumeAckTimeoutMs` on the same pinned Redis connection that executed the marker script, without returning it to a pool, reconnecting, or issuing an intervening write. `WAITAOF` acknowledges writes sent by the current connection, so a result from another connection cannot satisfy this contract. Its reply is an array of exactly two integers under both RESP2 and RESP3: `[localAofFsyncCount, replicaAofFsyncCount]`. Gateway must reject nulls, errors, wrong arity, wrong types, overflow, and negative counts, and accept `DURABLE_REPLAY_CONSUME_ACK` only when both counts meet their configured thresholds. Configuration validation requires `requiredLocalAofCount = 1`, `requiredReplicaAofCount >= 0`, `requiredReplicaAofCount = 0` only for the explicitly supported single-node profile and at least `1` for clustered player-facing profiles, and the canonical timeout above; impossible, negative, overflowed, or profile-inconsistent thresholds fail startup/preflight. `WAITAOF` is a Redis 7.2+ AOF-fsync acknowledgement, not a claim of protection from disk or hardware destruction. A successful `SET`, `WAIT`, read-back, or client write completion alone is not sufficient. If the marker write or `WAITAOF` result is lost, times out, is malformed, or is below threshold, the outcome is uncertain and the handshake fails closed. A player-facing profile that cannot prove the Redis version, AOF configuration, capacity headroom, and acknowledgement is not eligible to admit new handshakes. - Browser revocation and connect consumption are linearized by the Coordination Redis operation. If the deny-marker write commits first, including a revocation request racing a handshake, the consume script returns `-1`, does not create the replay marker, and Gateway denies admission. If the consume script commits first, the token was already accepted and spent; a later browser revocation records the deny marker but cannot retroactively undo that accepted handshake. No implementation may split the deny-marker check from readiness/fence validation or `jti` creation into separate Redis operations. - Consumption is final. If the backend connection or protocol upgrade subsequently fails, the client obtains a new connect token rather than retrying the spent token. -- Any Coordination Redis event that affects the shared Gateway replay-marker or replay-fence continuity domain, including a cold start, reset, unexpected replay-key eviction, failover, durability-acknowledgement timeout/failure, capacity-safety breach, or any other event that cannot prove marker continuity, atomically advances a shared `replayAdmissionFence` and records `state=QUARANTINED`, `quarantineStartedAt`, a shared signed-`iat` cutoff `quarantineCutoffIat`, and a finite `quarantineUntil` in Coordination Redis. A Cache/Rate-Limit Redis event, or a tenant/region-scoped Coordination Redis reset that does not affect this shared replay domain, does not trigger this quarantine. `quarantineCutoffIat` is the recorded detection cutoff, not a pod-local receipt time; every Gateway must reject a verified token whose signed `iat` is at or before that cutoff, and the fenced consume operation must repeat that comparison against the current shared record. Every Gateway and the Account issuance path must read that shared state and fence; a pod-local circuit breaker, cache, stale Gateway, or stale issuer cannot reopen admission or mint a credential that survives the fence change. If the shared readiness record is absent and Coordination Redis is readable, one shared compare-and-set initialization may start a new quarantine from the current detection time and persist its new cutoff. If the readiness record cannot be read, admission and issuance remain closed and no initialization is permitted. A later replay-domain loss repeats that process with a new shared cutoff and restarts the complete quarantine window; recovery and reopen preserve the current persisted cutoff until the fenced transition to `OPEN`, and never infer, clear, or shorten it from local state. The quarantine deadline is at least the detection time plus the 30-second token maximum and two `firemud.gateway.connectTokenClockSkewMs` intervals: one covers the latest tolerated future `iat`, and the other covers acceptance through `exp + skew`. When the latest affected token expiry is known, the deadline also covers that expiry plus one skew interval. Tokens from an earlier fence or issued at or before the persisted quarantine cutoff are rejected, Account cannot issue while the state is `QUARANTINED`, and a token from an issuance race carries the earlier fence and is rejected after the transition. Gateways may reopen only after the shared deadline has passed, Coordination Redis is available, configuration and capacity probes pass, and a fresh disposable marker script followed by the configured `WAITAOF` thresholds proves `DURABLE_REPLAY_CONSUME_ACK`; one compare-and-set transition then records `state=OPEN` for the current fence, after which Account may issue tokens bound to that fence. An explicitly configured local test profile may use isolated replay state with visible drift telemetry; no player-facing profile silently falls back to pod memory. +- Any Coordination Redis event that affects the shared Gateway replay-marker or replay-fence continuity domain, including a cold start, reset, unexpected replay-key eviction, failover, durability-acknowledgement timeout/failure, capacity-safety breach, or any other event that cannot prove marker continuity, atomically advances a shared `replayAdmissionFence` and records `state=QUARANTINED`, `quarantineStartedAt`, a shared signed-`iat` cutoff `quarantineCutoffIat`, and a finite `quarantineUntil` in Coordination Redis. A Cache/Rate-Limit Redis event, or a tenant/region-scoped Coordination Redis reset that does not affect this shared replay domain, does not trigger this quarantine. `quarantineCutoffIat` is the recorded detection cutoff, not a pod-local receipt time; every Gateway must reject a verified token whose signed `iat` is at or before that cutoff, and the fenced consume operation must repeat that comparison against the current shared record. Every Gateway and the Account issuance path must read that shared state and fence; a pod-local circuit breaker, cache, stale Gateway, or stale issuer cannot reopen admission or mint a credential that survives the fence change. If the shared readiness record is absent and Coordination Redis is readable, one shared compare-and-set initialization may start a new quarantine from the current detection time and persist its new cutoff. If the readiness record cannot be read, admission and issuance remain closed and no initialization is permitted. A later replay-domain loss repeats that process with a new shared cutoff and restarts the complete quarantine window; recovery and reopen preserve the current persisted cutoff until the fenced transition to `OPEN`, and never infer, clear, or shorten it from local state. The quarantine deadline is at least the detection time plus the 30-second token maximum and two `firemud.gateway.connectTokenClockSkewMs` intervals: one covers the latest tolerated future `iat`, and the other covers acceptance through `exp + skew`. When the latest affected token expiry is known, the deadline also covers that expiry plus one skew interval. Tokens from an earlier fence or issued at or before the persisted quarantine cutoff are rejected, Account cannot issue while the state is `QUARANTINED`, and a token from an issuance race carries the earlier fence and is rejected after the transition. After the shared deadline, configuration/capacity probes, exact fenced recovery-probe evidence, and every other release gate succeed, the trusted recovery coordinator authorizes reopen through Gateway's existing authenticated owner-maintenance boundary; Gateway's owner-local helper alone performs the fenced compare-and-set to `state=OPEN`. The coordinator does not receive raw Redis authority, and Account may issue only after the transition for tokens bound to the current fence. An explicitly configured local test profile may use isolated replay state with visible drift telemetry; no player-facing profile silently falls back to pod memory. ### Supported Replay Topology And Promotion Proof - Player-facing replay protection is supported only on a dedicated Coordination Redis continuity domain using either a persistent single-node AOF deployment with no failover, or a `production_clustered` primary/replica or Redis Cluster deployment whose replay-marker keys and readiness fence remain within the documented continuity domain. The single-node and clustered choices may satisfy different deployment profiles, but neither may share replay state with Cache/Rate-Limit Redis, use an eviction policy, or rely on an ephemeral no-AOF profile. - `WAITAOF` acknowledges the local and configured replica AOF-fsync positions for the marker write. It does not by itself prove that a future promoted primary will contain the marker, that a replica is eligible for promotion, or that disk/hardware loss is survivable. `DURABLE_REPLAY_CONSUME_ACK` therefore means the configured write acknowledgement only; failover durability requires the separate promotion proof below. -- Before reopening admission after a primary promotion or recovery, the recovery controller must record the continuity domain and fence, the old and new Redis identities/epochs, successful AOF load or equivalent recovery completion, the promoted node's replication/AOF position relative to the last acknowledged marker write, and read-back evidence for `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`. A clustered deployment must also prove the fixed `{gateway-connect-token-replay-v1}` tag kept all three keys in the supported continuity slot. If the promoted target or evidence cannot establish that acknowledged replay markers and the readiness/fence record are preserved, the event is uncertain and follows the full quarantine path; Gateway must not infer continuity from a promoted role, Redis availability, a new `WAITAOF`, or an isolated successful read. -- A recovery that cannot prove marker continuity does not reopen early. It waits until the affected token acceptance window is dead, then passes the fresh disposable-marker and configured `WAITAOF` readiness probe before the shared compare-and-set transition to `OPEN`. This preserves single-use admission semantics even when the underlying Redis failover lost recent marker state. +- Before reopening admission after a primary promotion or recovery, the recovery controller must record the continuity domain and fence, the old and new Redis identities/epochs, successful AOF load or equivalent recovery completion, the promoted node's replication/AOF position relative to the last acknowledged marker write, and read-back evidence for `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, and the recovery-only `gateway:connect-token:{gateway-connect-token-replay-v1}:probe:*` family. A clustered deployment must also prove the fixed `{gateway-connect-token-replay-v1}` tag kept all four families in the supported continuity slot. If the promoted target or evidence cannot establish that acknowledged replay markers and the readiness/fence record are preserved, the event is uncertain and follows the full quarantine path; Gateway must not infer continuity from a promoted role, Redis availability, a new `WAITAOF`, or an isolated successful read. +- A recovery that cannot prove marker continuity does not reopen early. It waits until the affected token acceptance window is dead, then the trusted recovery coordinator invokes Gateway's separate typed recovery probe through Gateway's existing authenticated owner-maintenance boundary while shared readiness remains `QUARANTINED`. On one pinned Coordination Redis connection, Gateway conditionally writes a Gateway-generated disposable marker under `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::` only when the exact durable maintenance operation/fence, replay domain, current `replayAdmissionFence`, and quarantine state still match. The key and nonce are generated by Gateway; callers cannot supply a key, nonce, player `jti`, or marker value to redirect the probe into a normal replay/deny prefix. The probe marker has a finite bounded expiry. Gateway immediately issues the configured `WAITAOF` acknowledgement on that same pinned connection with no intervening write; readback then verifies the bound operation/fence and evidence. Only after that acknowledgement and evidence readback may cleanup run as a separate exact-fence-guarded write with readback; cleanup cannot supply or replace the acknowledgement. This probe neither accepts nor consumes a player JWT, real `jti` replay marker, or browser-deny marker, and it never writes shared readiness. Normal player consume remains `OPEN`-only and is never invoked during quarantine. A successful probe is evidence for the recovery coordinator, not admission: only the coordinator may authorize reopen after the deadline, configuration/capacity checks, all other owner release gates, and exact fenced probe evidence succeed; Gateway's owner-local helper performs the readiness compare-and-set through its authenticated maintenance boundary. If any evidence is unavailable or ambiguous, readiness remains quarantined and issuance/admission stay closed. The probe operation and its producer/consumer proof are target-only and currently unimplemented; this preserves single-use admission semantics even when the underlying Redis failover lost recent marker state. ### Scope Handoff And Proxy Exception diff --git a/design/architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md b/design/architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md index 33cdf0c1dc..9339dceab2 100644 --- a/design/architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md +++ b/design/architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md @@ -31,63 +31,71 @@ Operator writes are low-volume control-plane operations, so one durable intent r ### One Correlated Execution -ADR 0048 is the sole owning definition of `preAuthorizationReservationTuple/v1`; ADR 0047 and the Account issuance API reference this tuple exactly and must not define a variant. Logging and Admin assigns one `controlPlaneRequestId`, computes ADR 0047's versioned canonical `mutationDigest`, and atomically reserves that identifier before issuing an Account authorization reference or forwarding any mutation. `mutationDigest` is only the SHA-256 digest of the normalized action-family schema pair and typed scope, target, expected-version, mutation, and audit-reason values defined by ADR 0047; it is not the idempotency identity. The reservation actor is authority-derived and never caller supplied. For a human reservation, Logging and Admin captures the locally validated `control-ui` subject/account before reservation, sends that exact actor value with the authorization request, and Account compares it with the authenticated `control-ui` subject before issuing; retries preserve that same actor and never derive it from a later Account response. Automation uses the exact authenticated workload identity paired with its versioned automation-policy identity. Logging and Admin may carry validated evidence but may not invent, override, or accept a caller-supplied actor. The immutable `preAuthorizationReservationTuple/v1` contains `controlPlaneRequestId`, this reservation actor identity, applicable automation-policy identity or explicit human no-policy value, exact typed `scope`, normalized `actionFamily`, `actionFamilySchemaId`, `actionFamilySchemaVersion`, typed `target`, immutable typed `targetOwner`, typed `expectedVersion`, typed `mutation`, typed `auditReason`, and every schema-declared bound presence/absence value. `targetOwner` is a schema-bound typed owner-selection value, distinct from `target`; it is immutable after reservation and is not recomputed from current routing or lease ownership. It contains only values known before Account authorization: it does not contain or fabricate an `issuanceKind`, `issuanceOperationId`, authorization-reference fingerprint, authenticated authority tuple, `membershipVersion`, `issuanceFence`, authority scope, source transaction/outbox or event version, projection status/freshness, or issuance-operation identity. The canonical digest is persisted and recomputed as an integrity check and never substitutes for those stored fields. Reservation is a durable compare-and-set: exactly one caller becomes the reservation owner, and the owner token is required for every later tuple-completion write. The reservation is not authorization and does not permit forwarding. +The stable `controlPlaneRequestId` is the sole key for the ADR 0048 orchestration/reservation record and its deduplication, recovery lookup, and correlation. The tagged `actionFamilyRequestIdentity` is carried in the reservation and post-authorization tuples and is used at the applicable Account/domain action-idempotency boundary; it is not a second orchestration or reservation key. In particular, moderation may use `policyIntentRequestId` or `ownerEnforcementRequestId` to select the domain idempotency record while the ADR 0048 record remains keyed by `controlPlaneRequestId`. + +When later moderation wording calls `controlPlaneRequestId` “correlation-only,” that qualification is only for the domain mutation-idempotency lookup; it remains the required ADR 0048 orchestration, reservation, recovery-lookup, deduplication, and correlation key. + +ADR 0048 is the sole owning definition of `preAuthorizationReservationTuple/v1`; ADR 0047 and the Account issuance API reference this tuple exactly and must not define a variant. Logging and Admin assigns the action-family request identity (`controlPlaneRequestId` for non-moderation mutations, `policyIntentRequestId` for local moderation policy intent, or `ownerEnforcementRequestId` for moderation owner-enforcement commands), computes ADR 0047's versioned canonical `mutationDigest`, and atomically reserves and commits the initial `ACCOUNT_AUTHORIZATION/RESERVED` record keyed solely by `controlPlaneRequestId` before issuing an Account authorization reference or forwarding any mutation. The tagged action-family request identity is stored in that record's tuple and is used only at the applicable Account/domain action-idempotency boundary. For moderation flows, `controlPlaneRequestId` is correlation-only at that domain boundary and is never an alias for either dedicated mutation identity. `mutationDigest` is only the SHA-256 digest of the normalized action-family schema pair and typed scope, target, expected-version, mutation, and audit-reason values defined by ADR 0047; it is not the idempotency identity. The reservation actor is authority-derived and never caller-supplied. For a human reservation, Logging and Admin captures the locally validated `control-ui` subject/account before reservation, sends that exact actor value with the authorization request, and Account compares it with the authenticated `control-ui` subject before issuing; retries preserve that same actor and never derive it from a later Account response. Automation uses the exact authenticated workload identity paired with its versioned automation-policy identity. Logging and Admin may carry validated evidence but may not invent, override, or accept a caller-supplied actor. The immutable `preAuthorizationReservationTuple/v1` contains that action-family request identity, this reservation actor identity, applicable automation-policy identity or explicit human no-policy value, exact typed `scope`, normalized `actionFamily`, `actionFamilySchemaId`, `actionFamilySchemaVersion`, typed `target`, immutable typed `targetOwner`, typed `expectedVersion`, typed `mutation`, typed `auditReason`, and every schema-declared bound presence/absence value. `targetOwner` is a schema-bound typed owner-selection value, distinct from `target`; it is immutable after reservation and is not recomputed from current routing or lease ownership. It contains only values known before Account authorization: it does not contain or fabricate an `issuanceKind`, `issuanceOperationId`, authorization-reference fingerprint, authenticated authority tuple, `membershipVersion`, `issuanceFence`, authority scope, source transaction/outbox or event version, projection status/freshness, or issuance-operation identity. The canonical digest is persisted and recomputed as an integrity check and never substitutes for those stored fields. Reservation is a durable compare-and-set: exactly one caller becomes the reservation owner, and the owner token is required for every later tuple-completion write. The reservation is not authorization and does not permit forwarding. The canonical complete `postAuthorizationExecutionTuple` is the immutable tuple created only after Account authorization. It contains the complete pre-authorization tuple plus `issuanceKind`, Account-returned `authorizationReferenceFingerprint`, exact authenticated workload and actor binding, applicable workload/policy identity, exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, and the exact immutable `authorityEvidenceBundle/v1` defined by reference in ADR 0047. The bundle is complete and canonical; it is authority evidence, not an execution-tuple variant. The post-authorization tuple explicitly includes the immutable typed `targetOwner` and every schema-bound typed presence/absence value; only a value whose absence is declared by the action-family schema may be absent. Every tuple completion, recovery lookup, owner idempotency record, terminal or no-accept/no-commit proof, and conflict comparison carries and compares this exact tuple. No participant may omit, infer, or replace one of these fields from current ownership, routing, caller assertions, or a later authority read. The pre-authorization recovery lookup carries the immutable typed `targetOwner` and its schema-bound presence/absence value as part of `preAuthorizationReservationTuple`; post-authorization owner execution carries it as part of the exact canonical complete `postAuthorizationExecutionTuple`. Any later rearm is a new explicit operator request with its own authorization tuple and reference, never a pre-authorization recovery lookup, and neither path can substitute current routing or lease ownership for that value. -The reservation-owner claim is itself a durable bounded lease. The record stores `reservationOwnerId`, `reservationClaimFence`, `reservationClaimExpiresAt`, and claim state. `CAS acquire` creates the `RESERVED` record and assigns one owner with a new monotonic claim fence; `CAS renew` may extend only that bounded claim when the exact owner and fence are still current and unexpired; `CAS completion` of authorization, forwarding, or a terminal no-mutation result requires the same owner and fence; and `CAS expiry` advances the claim fence and prevents the expired owner from authorizing, forwarding, or completing. A stale owner cannot issue or redeem an Account authorization reference, forward a mutation, or write any terminal result. After claim expiry, a recovery CAS may assign exactly one fresh, unexpired reservation/recovery claim to a fenced recovery owner of the exact authenticated Logging and Admin workload. That recovery owner may perform the read-only Account lookup for `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING`; if it recovers the original issued response, it may complete the atomic enrichment to `ACCOUNT_AUTHORIZATION/AUTHORIZED` under that fresh claim. A recovery CAS may complete an expired `ACCOUNT_AUTHORIZATION/RESERVED` claim to `NOT_EXECUTED_BEFORE_AUTHORIZATION` only when durable evidence proves that no Account authorization or owner-forward call can still occur. If the Account call was dispatched or its outcome is ambiguous, the record remains `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` and is non-replayable until the original response or the independent no-authorization/no-forward proof is established. An active claim is never transferred while a call may still be in flight. +The reservation-owner claim is itself a durable bounded lease. The record stores `reservationOwnerId`, `reservationClaimFence`, `reservationClaimExpiresAt`, and claim state. `CAS acquire` creates the `RESERVED` record and assigns one owner with a new monotonic claim fence; `CAS renew` may extend only that bounded claim when the exact owner and fence are still current and unexpired; `CAS completion` of authorization, forwarding, or a terminal no-mutation result requires the same owner and fence; and `CAS expiry` advances the claim fence and prevents the expired owner from authorizing, forwarding, or completing. A stale owner cannot issue or redeem an Account authorization reference, forward a mutation, or write any terminal result. After claim expiry, a recovery CAS may assign exactly one fresh, unexpired reservation/recovery claim to a fenced recovery owner of the exact authenticated Logging and Admin workload. That recovery owner may perform the read-only Account lookup for `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING`; if it recovers the original issued response, it may complete the atomic enrichment to `ACCOUNT_AUTHORIZATION/AUTHORIZED` under that fresh claim. This CAS and enrichment preserve the original reservation claim fence as immutable tuple evidence; the fresh recovery claim/fence authorizes the transition but never replaces that stored fence. A recovery CAS may complete an expired `ACCOUNT_AUTHORIZATION/RESERVED` claim to `NOT_EXECUTED_BEFORE_AUTHORIZATION` only when durable evidence proves that no Account authorization or owner-forward call can still occur. If the Account call was dispatched or its outcome is ambiguous, the record remains `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` and is non-replayable until the original response or the independent no-authorization/no-forward proof is established. An active claim is never transferred while a call may still be in flight. The durable record has an explicit `phase` and `state`; `PENDING` is never persisted or returned without its phase. `phase=ACCOUNT_AUTHORIZATION` covers `RESERVED`, `AUTHORIZATION_PENDING`, `AUTHORIZED`, and `NOT_EXECUTED_BEFORE_AUTHORIZATION`; `phase=OWNER_EXECUTION` covers `OWNER_EXECUTION_PENDING`, `FENCE_REJECTED`, `COMMITTED`, `FAILED`, and `NOT_EXECUTED_AFTER_AUTHORIZATION`. Every acquire, renew, expiry, completion, rejection, recovery, lookup, and rearm CAS compares the expected phase and state together with the phase-appropriate tuple, attempt identity, owner identity, and applicable claim/fencing token. Pre-authorization operations compare `preAuthorizationReservationTuple`; the transition to `AUTHORIZED` atomically enriches that tuple into `postAuthorizationExecutionTuple`, and every later owner execution, result lookup, and reconciliation operation compares the post-authorization tuple. Any later rearm starts a new reservation and authorization tuple with a fresh reference. A phase mismatch is an idempotency conflict or stale-fence rejection as applicable; it is never treated as an interchangeable `PENDING` state. -An exact pre-authorization duplicate has the same `preAuthorizationReservationTuple` and reservation claim metadata; it observes the same durable record and waits for the reservation owner to complete it or for the bounded reservation attempt to reach its terminal no-mutation outcome. It must not issue another authorization reference or forward another request. A request with the same `controlPlaneRequestId` but any difference in the phase-appropriate tuple returns canonical `IDEMPOTENCY_CONFLICT` without mutation. Only the current reservation owner with an unexpired matching claim fence, including one fresh claim held by a fenced recovery owner after claim expiry, may atomically enrich the record with the Account-returned `postAuthorizationExecutionTuple`. Reservation state transitions are explicit and phase-qualified: `ACCOUNT_AUTHORIZATION/RESERVED -> ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` is the owner/fence-protected transition required before dispatching the Account authorization request; `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING -> ACCOUNT_AUTHORIZATION/AUTHORIZED` is the owner/fence-protected completion after the original Account response is received or recovered and the full post-authorization tuple is durably stored; `ACCOUNT_AUTHORIZATION/RESERVED` or `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING -> ACCOUNT_AUTHORIZATION/NOT_EXECUTED_BEFORE_AUTHORIZATION` is allowed only when durable phase evidence records that Account authorization cannot complete and durable dispatch evidence proves that no owner-forward call occurred and no owner-forward call can still occur. A `NOT_FOUND` returned by the read-only `RecoverOperatorAuthorizationReference` lookup is only read-only lookup evidence and never satisfies either proof by itself. An ambiguous Account authorization call remains `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING`; it never becomes an owner-execution state and no owner-forward call may begin from it. After the original response is recovered, the fenced recovery owner may complete `AUTHORIZED` only while its fresh recovery claim is current and unexpired, then use the bounded handoff and fresh redemption rules for the original reference. Only after the durable `ACCOUNT_AUTHORIZATION/AUTHORIZED -> OWNER_EXECUTION/OWNER_EXECUTION_PENDING` transition, written before the exact reference or mutation is dispatched to the owner, can an ambiguous owner-forward call belong to `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`. That owner-forward ambiguity remains non-replayable and cannot become a phase-inappropriate `NOT_EXECUTED` result without durable no-call/no-commit proof. A stale owner/fence may produce `OWNER_EXECUTION/FENCE_REJECTED` only after the rejecting owner atomically persists its no-accept/no-commit proof; absent or inconsistent proof leaves the request in `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`, non-replayable and non-rearmable. The rejecting owner or one fenced recovery owner may transition a valid `FENCE_REJECTED` to `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` only after validating that proof. A tuple mismatch is `IDEMPOTENCY_CONFLICT`; neither wire outcome is itself rearmable. An expired claim, lost response, missing record after dispatch, or any other ambiguous phase-specific state remains in its applicable phase-specific pending state and is never converted to a phase-inappropriate `NOT_EXECUTED` result. Recovery may not transfer an active reservation claim or issue another reference while a call may still be in flight. After the claim expires, a recovery CAS may assign a new fenced recovery owner solely to call ADR 0047's read-only `RecoverOperatorAuthorizationReference` for `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING`, with `preAuthorizationReservationTuple`. That read either returns the original durable Account response or durable absence; it cannot create or replace a reference. A recovered original response permits the atomic `AUTHORIZED` enrichment and subsequent bounded handoff only while the fresh claim is valid; durable absence permits `ACCOUNT_AUTHORIZATION/NOT_EXECUTED_BEFORE_AUTHORIZATION` only after the independent durable phase and dispatch evidence above is present. +An exact pre-authorization duplicate has the same `preAuthorizationReservationTuple` and reservation claim metadata; it observes the same durable record and waits for the reservation owner to complete it or for the bounded reservation attempt to reach its terminal no-mutation outcome. It must not issue another authorization reference or forward another request. At the ADR 0048 orchestration boundary, a request with the same `controlPlaneRequestId` but any difference in the phase-appropriate tuple returns canonical `IDEMPOTENCY_CONFLICT` without mutation. At the applicable Account/domain boundary, reuse of the same tagged action-family request identity with any difference in its domain tuple likewise returns canonical `IDEMPOTENCY_CONFLICT`; a different `controlPlaneRequestId` does not create a second ADR 0048 reservation alias or bypass that domain conflict. Only the current reservation owner with an unexpired matching claim fence, including one fresh claim held by a fenced recovery owner after claim expiry, may atomically enrich the record with the Account-returned `postAuthorizationExecutionTuple`. Reservation state transitions are explicit and phase-qualified: `ACCOUNT_AUTHORIZATION/RESERVED -> ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` is the owner/fence-protected transition required before dispatching the Account authorization request; `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING -> ACCOUNT_AUTHORIZATION/AUTHORIZED` is the owner/fence-protected completion after the original Account response is received or recovered and the full post-authorization tuple is durably stored; `ACCOUNT_AUTHORIZATION/RESERVED` or `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING -> ACCOUNT_AUTHORIZATION/NOT_EXECUTED_BEFORE_AUTHORIZATION` is allowed only when durable phase evidence records that Account authorization cannot complete and durable dispatch evidence proves that no owner-forward call occurred and no owner-forward call can still occur. A `NOT_FOUND` returned by the read-only `RecoverOperatorAuthorizationReference` lookup is only read-only lookup evidence and never satisfies either proof by itself. An ambiguous Account authorization call remains `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING`; it never becomes an owner-execution state and no owner-forward call may begin from it. After the original response is recovered, the fenced recovery owner may complete `AUTHORIZED` only while its fresh recovery claim is current and unexpired, then use the bounded handoff and fresh redemption rules for the original reference. Only after the durable `ACCOUNT_AUTHORIZATION/AUTHORIZED -> OWNER_EXECUTION/OWNER_EXECUTION_PENDING` transition, written before the exact reference or mutation is dispatched to the owner, can an ambiguous owner-forward call belong to `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`. That owner-forward ambiguity remains non-replayable and cannot become a phase-inappropriate `NOT_EXECUTED` result without durable no-call/no-commit proof. A stale owner/fence may produce `OWNER_EXECUTION/FENCE_REJECTED` only after the rejecting owner atomically persists its no-accept/no-commit proof; absent or inconsistent proof leaves the request in `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`, non-replayable and non-rearmable. The rejecting owner or one fenced recovery owner may transition a valid `FENCE_REJECTED` to `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` only after validating that proof. A tuple mismatch is `IDEMPOTENCY_CONFLICT`; neither wire outcome is itself rearmable. An expired claim, lost response, missing record after dispatch, or any other ambiguous phase-specific state remains in its applicable phase-specific pending state and is never converted to a phase-inappropriate `NOT_EXECUTED` result. Recovery may not transfer an active reservation claim or issue another reference while a call may still be in flight. After the claim expires, a recovery CAS may assign a new fenced recovery owner solely to call ADR 0047's read-only `RecoverOperatorAuthorizationReference` for `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING`, with `preAuthorizationReservationTuple`. That read either returns the original durable Account response or durable absence; it cannot create or replace a reference. A recovered original response permits the atomic `AUTHORIZED` enrichment and subsequent bounded handoff only while the fresh claim is valid; durable absence permits `ACCOUNT_AUTHORIZATION/NOT_EXECUTED_BEFORE_AUTHORIZATION` only after the independent durable phase and dispatch evidence above is present. `ACCOUNT_AUTHORIZATION` is itself the durable pre-authorization recovery record. `RESERVED` carries the reservation claim and fence, `AUTHORIZATION_PENDING` carries the phase-qualified dispatch/response ambiguity and recovery claim/proof, and `NOT_EXECUTED_BEFORE_AUTHORIZATION` is terminal only with durable proof that authorization did not commit and no owner-forward call occurred or can still occur. No Redis owner record, write-ahead record, mutation marker, or effect evidence exists before the durable `ACCOUNT_AUTHORIZATION/AUTHORIZED -> OWNER_EXECUTION/OWNER_EXECUTION_PENDING` transition; Redis presence or absence cannot prove a pre-authorization outcome. `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` has two distinct terminal-proof forms, and neither is inferred from a timeout, `NOT_FOUND`, missing Redis state, or an absent record: -- **Pre-redemption no-redemption proof:** durable handoff and owner evidence prove that the owner call could not be accepted, Account redemption did not succeed and did not consume the reference, and no owner commit or business mutation occurred or can still occur under the attempt's fence. +- **Pre-redemption no-redemption proof:** durable handoff and owner evidence prove that the owner call could not be accepted, no redemption or owner-acceptance operation is in flight or can still complete under the attempt's fence, Account redemption did not succeed and did not consume the reference, the reference is durably non-redeemable for this attempt under that fence, and no owner commit or business mutation occurred or can still occur under the attempt's fence. - **Post-redemption no-acceptance proof:** Account's successful redemption and consumed-reference result are retained, so the proof must not claim no redemption. It instead proves that the owner did not durably accept the business mutation, did not commit an owner result/effect, and did not mutate business state, and that the fenced attempt cannot accept or commit later. -If the redemption outcome, owner acceptance, owner commit, business mutation, or delayed-commit exclusion is ambiguous, the request remains `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`, non-replayable, and non-rearmable. A terminal owner-side result is read-only for the original attempt. It does not support rearm or reuse of the original reference. Repeating the business intent requires a new explicit operator request with a new `controlPlaneRequestId`, a new Logging and Admin reservation, fresh Account authorization, and a new opaque reference. The new owner attempt uses its own complete post-authorization tuple, attempt number, high-entropy `ownerMutationId`, and fenced execution token; the prior terminal result and attempt history remain immutable. A successful redemption consumes the reference, and neither that consumed reference nor a replayed redemption result from the prior attempt can authorize the new attempt. A pre-authorization `ACCOUNT_AUTHORIZATION/RESERVED -> ACCOUNT_AUTHORIZATION/NOT_EXECUTED_BEFORE_AUTHORIZATION` record has no opaque reference and likewise requires a new explicit operator request. A terminal `NOT_EXECUTED` result is proof only for the completed attempt; it is never permission to replay an indeterminate dispatch. +If the redemption outcome, owner acceptance, owner commit, business mutation, delayed-commit exclusion, or reference non-redeemability is ambiguous, the request remains `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`, non-replayable, and non-rearmable. A terminal owner-side result is read-only for the original attempt. It does not support rearm or reuse of the original reference. Repeating the business intent requires a new explicit operator request with a new action-family request identity, a new Logging and Admin reservation, fresh Account authorization, and a new opaque reference. The new owner attempt uses its own complete post-authorization tuple, attempt number, high-entropy `ownerMutationId`, and fenced execution token; the prior terminal result and attempt history remain immutable. A successful redemption consumes the reference, and neither that consumed reference nor a replayed redemption result from the prior attempt can authorize the new attempt. A pre-authorization `ACCOUNT_AUTHORIZATION/RESERVED -> ACCOUNT_AUTHORIZATION/NOT_EXECUTED_BEFORE_AUTHORIZATION` record has no opaque reference and likewise requires a new explicit operator request. A terminal `NOT_EXECUTED` result is proof only for the completed attempt; it is never permission to replay an indeterminate dispatch. ### Fenced Reference Handoff -The original opaque reference is never stored durably by Logging and Admin, the domain owner, or the owner-result record. Account remains the source-of-truth provider and retains the reference in its protected authority record. For an `ACCOUNT_AUTHORIZATION/AUTHORIZED` record produced by a fenced recovery owner, the authorized-to-owner transition must first durably enter `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`; only then may the current domain owner receive the original reference through one bounded handoff from the exact current Logging and Admin reservation owner for the initial owner execution. The request carries the unchanged canonical complete `postAuthorizationExecutionTuple`, including immutable typed `targetOwner`, Account-returned `authorizationReferenceFingerprint`, `controlPlaneRequestId`, `reservationOwnerId`, current positive `reservationClaimFence`, the current domain `ownerId` and owner/gameplay fence, and a fresh high-entropy handoff identity. +The original opaque reference is never stored durably by Logging and Admin, the domain owner, or the owner-result record. Account remains the source-of-truth provider and retains the reference in its protected authority record. For an `ACCOUNT_AUTHORIZATION/AUTHORIZED` record produced by a fenced recovery owner, the authorized-to-owner transition must first durably enter `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`; only then may the current domain owner receive the original reference through one bounded handoff from the exact current Logging and Admin reservation owner for the initial owner execution. The request carries the unchanged canonical complete `postAuthorizationExecutionTuple`, including immutable typed `targetOwner`, Account-returned `authorizationReferenceFingerprint`, the action-family request identity, `reservationOwnerId`, and the original positive `reservationClaimFence` stored in that tuple, together with the current domain `ownerId` and owner/gameplay fence and a fresh high-entropy handoff identity. If an expired `AUTHORIZATION_PENDING` claim was recovered, its fresh reservation/recovery claim and fence are separate, independently validated execution authority for the recovery CAS and handoff; they do not replace or rewrite the original tuple fence. Exact tuple comparison and current owner/fence validation remain required before evaluation, dispatch, or reference delivery. Logging and Admin is the delivery provider, not a second authority: it must hold the exact unexpired reservation owner and claim fence. Only a separately fenced replacement owner of the exact authenticated Logging and Admin mTLS workload may call Account's read-only `RecoverOperatorAuthorizationReference` with `preAuthorizationReservationTuple/v1` and that fresh fence during pre-authorization recovery. The domain owner's `recoveryOwnerId` never calls `RecoverOperatorAuthorizationReference`; it receives the original opaque reference only through this post-authorization handoff after the owner-side claim is current and fenced. When the pre-authorization recovery owner receives the original issued response, it may atomically enrich the record to `ACCOUNT_AUTHORIZATION/AUTHORIZED` under the fresh claim and invoke this bounded handoff to the current domain owner. Account checks `issuanceKind`, immutable typed `targetOwner`, authenticated workload/actor binding, automation-policy identity, authority tuple, membership version, issuance fence, all existing immutable fields, and the reservation owner/fence before returning the original reference. Logging and Admin delivers that reference only over the exact allowlisted mTLS channel to the current domain owner in a bounded, non-durable envelope bound to the handoff identity, full tuple, reference fingerprint, reservation owner/fence, current owner/fence, and an expiry no later than the Account reference expiry. The raw reference is held only in protected in-flight memory and is zeroized after successful redemption, expiry, or failed delivery; no durable recovery copy is created. This handoff is only for the initial owner execution; a consumed reference and its durable redemption result cannot start another owner attempt. -If that Logging and Admin reservation claim has expired on a terminal owner-execution result, that terminal result is not eligible for rearm. A recovery owner may retain and reconcile the historical result read-only, but it cannot transfer reservation ownership, recover or deliver the original reference, redeem it for execution, or allocate a successor owner attempt. This restriction does not apply to an expired `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` claim: a fenced recovery CAS may install a fresh valid claim, recover the original issued response, atomically enrich to `AUTHORIZED`, and use the bounded handoff/fresh redemption path for the initial owner execution. Repeating a terminal owner-execution business intent requires a new explicit operator request with a new `controlPlaneRequestId`, fresh Account authorization, and a new opaque reference; claim expiry never turns an old reference or terminal result into authorization for another actor and never creates a duplicate issuance. +If that Logging and Admin reservation claim has expired on a terminal owner-execution result, that terminal result is not eligible for rearm. A recovery owner may retain and reconcile the historical result read-only, but it cannot transfer reservation ownership, recover or deliver the original reference, redeem it for execution, or allocate a successor owner attempt. This restriction does not apply to an expired `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` claim: a fenced recovery CAS may install a fresh valid claim, recover the original issued response, atomically enrich to `AUTHORIZED`, and use the bounded handoff/fresh redemption path for the initial owner execution. Repeating a terminal owner-execution business intent requires a new explicit operator request with a new action-family request identity, fresh Account authorization, and a new opaque reference; claim expiry never turns an old reference or terminal result into authorization for another actor and never creates a duplicate issuance. -The current domain owner authenticates the delivery provider, rechecks its own current owner/gameplay fence and the unchanged reservation claim fence, and redeems the exact reference with Account before allocating the initial owner attempt. Account redemption must still validate the exact caller workload, tuple, current authority, membership, applicable privilege, and issuance fence; successful redemption consumes the reference and binds the durable redemption result to that attempt. Handoff timeout, provider/owner fence loss, tuple or fingerprint mismatch, expired or revoked reference, Account `NOT_FOUND`, delivery failure, or redemption failure after the authorized-to-owner transition remains `OWNER_EXECUTION/OWNER_EXECUTION_PENDING` until exact durable proof establishes no owner-forward call, no redemption, and no owner commit; only then may it transition to `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION`. The original authorization and consumed reference are never reused after a failed or ambiguous post-authorization handoff. An ambiguous handoff is read-only and non-replayable; it never authorizes business execution, and any later business attempt requires a new explicit operator request, fresh Account authorization, and a new reference. +The current domain owner authenticates the delivery provider, rechecks its own current owner/gameplay fence, and validates both the unchanged original reservation claim fence in the complete post-authorization tuple and, when recovery occurred, the separately current fresh reservation/recovery claim and fence before redeeming the exact reference with Account or allocating the initial owner attempt. The fresh recovery claim is never substituted into the tuple. Account redemption must still validate the exact caller workload, tuple, current authority, membership, applicable privilege, and issuance fence; successful redemption consumes the reference and binds the durable redemption result to that attempt. Handoff timeout, provider/owner fence loss, tuple or fingerprint mismatch, expired or revoked reference, Account `NOT_FOUND`, delivery failure, or redemption failure after the authorized-to-owner transition remains `OWNER_EXECUTION/OWNER_EXECUTION_PENDING` until one of the two applicable terminal-proof forms above is established durably; only then may it transition to `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION`. The original authorization and consumed reference are never reused after a failed or ambiguous post-authorization handoff. An ambiguous handoff is read-only and non-replayable; it never authorizes business execution, and any later business attempt requires a new explicit operator request, fresh Account authorization, and a new reference. -For a forwarded owner-mutation family, after the reservation owner receives the Account authorization reference, it atomically enriches the exact `preAuthorizationReservationTuple/v1` into the canonical complete `postAuthorizationExecutionTuple`. The latter contains the complete pre-authorization tuple plus `issuanceKind`, the `authorizationReferenceFingerprint` returned unchanged by Account for the exact opaque reference, exact authenticated workload and actor binding, applicable workload/policy identity, the exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, and the exact immutable `authorityEvidenceBundle/v1` defined in ADR 0047. It explicitly retains the immutable typed `targetOwner` from the reservation and every schema-bound typed presence/absence value; no declared value may be dropped during tuple completion. Logging and Admin never derives or recomputes the fingerprint or any authority evidence. Its durable record may retain the operator intent and Account-returned fingerprint; any opaque reference held by Logging and Admin is protected, bounded in-flight delivery material only, not a recovery authority record or competing copy of Account's authority. The workload identity is the exact authenticated Logging and Admin mTLS identity; an automated request also binds `automation_policy_id` and `automation_policy_version`, while a human request has an explicit no-automation-policy value. Schema-bound absent or null values represented by the digest are stored as bound values rather than omitted during tuple completion. If the reservation, initial durable record, or tuple completion cannot be written after a reference may exist, the durable record remains `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` under its applicable claim/recovery rules, and the original request tuple, Account response/reference fingerprint, reservation owner and claim fence, and all returned authority/evidence fields are retained in their owning durable records; the opaque reference itself remains only in Account's protected authority record and bounded in-flight delivery material. It must not be forwarded, reissued, or treated as `NOT_EXECUTED_BEFORE_AUTHORIZATION` until durable proof establishes that no authorization reference exists, cannot still be issued, and no owner-forward call occurred or can still occur. If no reference could have existed and the no-dispatch proof is complete, the pre-authorization terminal outcome may be recorded instead. `controlPlaneRequestId` is the canonical logical request name across HTTP, Java/domain contracts, ADRs, and audit records. Protobuf contracts may use the language-standard wire spelling `control_plane_request_id`, which maps directly to that same identifier; it is not a second idempotency key. +For a forwarded owner-mutation family, after the reservation owner receives the Account authorization reference, it atomically enriches the exact `preAuthorizationReservationTuple/v1` into the canonical complete `postAuthorizationExecutionTuple`. The latter contains the complete pre-authorization tuple plus `issuanceKind`, the `authorizationReferenceFingerprint` returned unchanged by Account for the exact opaque reference, exact authenticated workload and actor binding, applicable workload/policy identity, the exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, and the exact immutable `authorityEvidenceBundle/v1` defined in ADR 0047. It explicitly retains the immutable typed `targetOwner` from the reservation and every schema-bound typed presence/absence value; no declared value may be dropped during tuple completion. Logging and Admin never derives or recomputes the fingerprint or any authority evidence. Its durable post-authorization record must persist the Account-returned `authorizationReferenceFingerprint` unchanged as part of the canonical `postAuthorizationExecutionTuple`; this is required tuple evidence, not optional context. Any opaque reference held by Logging and Admin is protected, bounded in-flight delivery material only, not a recovery authority record or competing copy of Account's authority. The workload identity is the exact authenticated Logging and Admin mTLS identity; an automated request also binds `automation_policy_id` and `automation_policy_version`, while a human request has an explicit no-automation-policy value. Schema-bound absent or null values represented by the digest are stored as bound values rather than omitted during tuple completion. The reservation CAS and initial `ACCOUNT_AUTHORIZATION/RESERVED` record are prerequisites to issuance: if that pre-record commit fails, Account issuance must not be attempted, and the request uses the applicable pre-authorization outcome; `AUTHORIZATION_PENDING` is not recorded or returned because no phase record exists. If Account issuance has been dispatched or a reference may exist, but tuple completion cannot be written, the durable record remains `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` under its applicable claim/recovery rules, and the original request tuple, Account response/reference fingerprint, reservation owner and claim fence, and all returned authority/evidence fields are retained in their owning durable records; the opaque reference itself remains only in Account's protected authority record and bounded in-flight delivery material. It must not be forwarded, reissued, or treated as `NOT_EXECUTED_BEFORE_AUTHORIZATION` until durable proof establishes that no authorization reference exists, cannot still be issued, and no owner-forward call occurred or can still occur. If no reference could have existed and the no-dispatch proof is complete, the pre-authorization terminal outcome may be recorded instead. The action-family request identity is canonical across HTTP, Java/domain contracts, ADRs, and audit records; its action-family mapping and moderation correlation rule are defined above. Protobuf contracts may use the language-standard wire spelling `control_plane_request_id`, which maps directly to the non-moderation identifier; it is not a second idempotency key. -For a forwarded owner-mutation family, Account first issues the applicable opaque bounded operator authorization reference defined by ADR 0047. A human request uses the typed Account `IssueHumanOperatorAuthorizationReference` path and requires the current `control-ui` identity; its reference is bound to the `human_operator` issuance kind, current token `jti`, account generation, role-assurance result, applicable `tenant_generation` or `target_tenant_generation`, any required `privileged_control` predicate, exact authenticated workload and actor binding, complete applicable authority tuple, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, exact tenant/scope, immutable typed `targetOwner`, action family, `actionFamilySchemaId`, `actionFamilySchemaVersion`, actor, `controlPlaneRequestId`, `mutationDigest`, issue time, and expiry. An unattended request uses the typed Account `IssueAutomationOperatorAuthorizationReference` path with `exact_mtls_workload_plus_versioned_automation_policy`; the current automation branch is restricted to tenant-scoped action families that require no `privileged_control`, and its reference is bound to the `automation_operator` issuance kind, exact Logging and Admin workload mTLS identity, `automation_policy_id`, `automation_policy_version`, exact `tenant_generation`, complete applicable authority tuple, independent applicable `membershipVersion` when applicable, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, exact tenant/scope, immutable typed `targetOwner`, action family, `actionFamilySchemaId`, `actionFamilySchemaVersion`, `controlPlaneRequestId`, `mutationDigest`, issue time, and expiry. It carries no user account, end-user token, `control-ui` identity, global-role authority, or human elevation. Logging and Admin forwards that reference and its unchanged generation, evidence-bundle, predicate evidence, reservation owner, claim fence, immutable typed `targetOwner`, and every schema-bound typed presence/absence value with the typed request, digest, schema pair, exact scope, and same request identifier to the authoritative domain owner. The owner: +For a forwarded owner-mutation family, Account first issues the applicable opaque bounded operator authorization reference defined by ADR 0047. A human request uses the typed Account `IssueHumanOperatorAuthorizationReference` path and requires the current `control-ui` identity; its reference is bound to the `human_operator` issuance kind, current token `jti`, account generation, role-assurance result, applicable `tenant_generation` or `target_tenant_generation`, any required `privileged_control` predicate, exact authenticated workload and actor binding, complete applicable authority tuple, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, exact tenant/scope, immutable typed `targetOwner`, action family, `actionFamilySchemaId`, `actionFamilySchemaVersion`, actor, the action-family request identity, `mutationDigest`, issue time, and expiry. An unattended request uses the typed Account `IssueAutomationOperatorAuthorizationReference` path with `exact_mtls_workload_plus_versioned_automation_policy`; the current automation branch is restricted to tenant-scoped action families that require no `privileged_control`, and its reference is bound to the `automation_operator` issuance kind, exact Logging and Admin workload mTLS identity, `automation_policy_id`, `automation_policy_version`, exact `tenant_generation`, complete applicable authority tuple, independent applicable `membershipVersion` when applicable, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, exact tenant/scope, immutable typed `targetOwner`, action family, `actionFamilySchemaId`, `actionFamilySchemaVersion`, the action-family request identity, `mutationDigest`, issue time, and expiry. It carries no user account, end-user token, `control-ui` identity, global-role authority, or human elevation. Logging and Admin forwards that reference and its unchanged generation, evidence-bundle, predicate evidence, reservation owner, claim fence, immutable typed `targetOwner`, and every schema-bound typed presence/absence value with the typed request, digest, schema pair, exact scope, and same request identifier to the authoritative domain owner. The owner: - authenticates the immediate caller with the exact Logging and Admin workload mTLS identity, redeems the matching human or unattended reference with Account, and recomputes the canonical mutation digest before any new execution; -- compares the canonical complete `postAuthorizationExecutionTuple` (`controlPlaneRequestId`, `mutationDigest`, `issuanceKind`, Account-returned `authorizationReferenceFingerprint`, exact authenticated workload and actor binding, applicable workload/policy identity, exact typed `scope`, normalized `actionFamily`, `actionFamilySchemaId`, `actionFamilySchemaVersion`, typed `target`, immutable typed `targetOwner`, typed `expectedVersion`, typed `mutation`, typed `auditReason`, exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, the exact canonical `authorityEvidenceBundle/v1` by reference to ADR 0047, and every schema-bound typed presence/absence value) using `controlPlaneRequestId` only to locate a candidate record. An exact tuple match with a terminal result returns the stored result without new validation or mutation, and any mismatch returns `IDEMPOTENCY_CONFLICT`. An expired or revoked reference permits only the allowlisted read-only result lookup against this exact tuple: an exact terminal result may be returned, but if none exists the request remains non-replayable with no forward, owner mutation, or other continuation and requires a new explicit operator request plus fresh Account authorization; it never continues as a new non-replayable attempt; +- compares the canonical complete `postAuthorizationExecutionTuple` (the action-family request identity, `mutationDigest`, `issuanceKind`, Account-returned `authorizationReferenceFingerprint`, exact authenticated workload and actor binding, applicable workload/policy identity, exact typed `scope`, normalized `actionFamily`, `actionFamilySchemaId`, `actionFamilySchemaVersion`, typed `target`, immutable typed `targetOwner`, typed `expectedVersion`, typed `mutation`, typed `auditReason`, exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, the exact canonical `authorityEvidenceBundle/v1` by reference to ADR 0047, and every schema-bound typed presence/absence value) using the action-family request identity only to locate a candidate record. An exact tuple match with a terminal result returns the stored result without new validation or mutation, and any mismatch returns `IDEMPOTENCY_CONFLICT`. An expired or revoked reference permits only the allowlisted read-only result lookup against this exact tuple: an exact terminal result may be returned, but if none exists the request remains non-replayable with no forward, owner mutation, or other continuation and requires a new explicit operator request plus fresh Account authorization; it never continues as a new non-replayable attempt; - authorizes the current actor or automation policy and scope rather than trusting ingress-derived domain conclusions or Logging and Admin assertions, requires Account redemption to confirm the exact current generation and any required privileged predicate, and only then validates current domain preconditions and, where applicable, the current authority generation or gameplay fence; - atomically persists or claims the owner request as `OWNER_EXECUTION/OWNER_EXECUTION_PENDING` before dispatching any owner call or business execution, including when the preceding `ACCOUNT_AUTHORIZATION/AUTHORIZED` state was completed by a fenced recovery owner, with a durable owner claim lease and monotonic fenced execution token that prevents a superseded claimant from authorizing, forwarding, mutating, or committing; - durably commits the authoritative owner mutation and terminal result together when both reside in the same owner store, or records `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` when it can prove that no owner mutation committed; `ACCOUNT_AUTHORIZATION/NOT_EXECUTED_BEFORE_AUTHORIZATION` is reserved for the pre-authorization phase and cannot be emitted by owner execution; and -- returns the previously committed result only when a duplicate `controlPlaneRequestId` carries an exact match for the canonical complete `postAuthorizationExecutionTuple`, including `mutationDigest` integrity, `issuanceKind`, normalized `actionFamily`, schema identifier/version, typed scope, target, immutable typed `targetOwner`, expected version, mutation, audit reason, every schema-bound typed presence/absence value, `authorityTuple`, `membershipVersion`, `issuanceFence`, `reservationOwnerId`, `reservationClaimFence`, and immutable authority evidence/source versions. The same comparison includes authenticated workload/actor binding and applicable automation-policy identity. The initial attempt has its own immutable `ownerMutationId`; its durable record retains that attempt's identity, terminal evidence, claim/fence, and timestamps so later reconciliation cannot attribute an old response or effect to another attempt. A same-identifier request with any difference in digest, authorization-reference fingerprint, issuance kind, typed scope, normalized action family, schema identifier/version, target, immutable typed `targetOwner`, expected version, mutation, audit reason, workload identity, applicable automation-policy identity, `authorityTuple`, `membershipVersion`, `issuanceFence`, `reservationOwnerId`, `reservationClaimFence`, authority evidence/source version, or any bound presence/absence value fails with canonical `IDEMPOTENCY_CONFLICT` and never applies either payload again. A later owner attempt is a new explicit request with fresh Account authorization and a new opaque reference; it never reuses this consumed reference or `ownerMutationId`. A stale owner, expired lease, or fencing-token mismatch may produce `FENCE_REJECTED` only after the owner atomically persists durable no-accept/no-commit evidence proving that this attempt did not mutate the owner state; absent or inconsistent proof leaves `OWNER_EXECUTION/OWNER_EXECUTION_PENDING` and is never reported as `IDEMPOTENCY_CONFLICT` or replayed. +- returns the previously committed result only when a duplicate action-family request identity carries an exact match for the canonical complete `postAuthorizationExecutionTuple`, including `mutationDigest` integrity, `issuanceKind`, normalized `actionFamily`, schema identifier/version, typed scope, target, immutable typed `targetOwner`, expected version, mutation, audit reason, every schema-bound typed presence/absence value, `authorityTuple`, `membershipVersion`, `issuanceFence`, `reservationOwnerId`, `reservationClaimFence`, and immutable authority evidence/source versions. The same comparison includes authenticated workload/actor binding and applicable automation-policy identity. The initial attempt has its own immutable `ownerMutationId`; its durable record retains that attempt's identity, terminal evidence, claim/fence, and timestamps so later reconciliation cannot attribute an old response or effect to another attempt. A same-identifier request with any difference in digest, authorization-reference fingerprint, issuance kind, typed scope, normalized action family, schema identifier/version, target, immutable typed `targetOwner`, expected version, mutation, audit reason, workload identity, applicable automation-policy identity, `authorityTuple`, `membershipVersion`, `issuanceFence`, `reservationOwnerId`, `reservationClaimFence`, authority evidence/source version, or any bound presence/absence value fails with canonical `IDEMPOTENCY_CONFLICT` and never applies either payload again. A later owner attempt is a new explicit request with fresh Account authorization and a new opaque reference; it never reuses this consumed reference or `ownerMutationId`. A stale owner, expired lease, or fencing-token mismatch may produce `FENCE_REJECTED` only after the owner atomically persists durable no-accept/no-commit evidence proving that this attempt did not mutate the owner state; absent or inconsistent proof leaves `OWNER_EXECUTION/OWNER_EXECUTION_PENDING` and is never reported as `IDEMPOTENCY_CONFLICT` or replayed. Logging and Admin then records the correlated outcome. It reports success only after the owner confirms its durable commit. ### Canonical Evidence Reference -ADR 0048 uses the exact complete `authorityEvidenceBundle/v1` by reference to ADR 0047 and the Account API; it defines no local variant. Any compact tuple or result-lookup list below that names only authority scope, source evidence/version, projection status/freshness, or issuance-operation identity refers to that same complete bundle. The bundle never contains `reservationOwnerId`, `reservationClaimFence`, `targetOwner`, or other execution-tuple fields; those remain separately bound by `postAuthorizationExecutionTuple`. +ADR 0048 uses the exact complete `authorityEvidenceBundle/v1` by reference to ADR 0047 and the Account API; it defines no local variant. That bundle's `issuanceOperationIdentity` uses ADR 0047's single `actionFamilyRequestIdentity` representation, with exactly one action-family kind and request ID; moderation's `controlPlaneRequestId`, when carried, remains correlation-only. Any compact tuple or result-lookup list below that names only authority scope, source evidence/version, projection status/freshness, or issuance-operation identity refers to that same complete bundle. The bundle never contains `reservationOwnerId`, `reservationClaimFence`, `targetOwner`, or other execution-tuple fields; those remain separately bound by `postAuthorizationExecutionTuple`. ### Failure and Reconciliation Semantics +The pre-authorization duplicate and conflict path is located by the stable `controlPlaneRequestId`; the tagged action-family identity is an exact tuple member and is separately compared only where Account or the domain owner applies action-family idempotency. It must not be interpreted as an alternate ADR 0048 orchestration key. + Before authorization, the reservation and authorization-recovery paths compare only `preAuthorizationReservationTuple` plus the applicable claim metadata. An ambiguous Account call remains `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` during this phase. After the atomic `AUTHORIZED` enrichment, every owner identity, durable owner request, result lookup, and reconciliation path compares `postAuthorizationExecutionTuple`; a later rearm is a new request with a new pre-authorization/post-authorization tuple and fresh reference. The durable transition to `OWNER_EXECUTION/OWNER_EXECUTION_PENDING` occurs before any owner handoff or owner dispatch. Result lookup is therefore a post-authorization owner operation; no pre-authorization path may use it or fabricate the authority fields it requires. The Account-returned authorization and authority-evidence fields are immutable additions to the pre-authorization request data; all members are compared exactly and none is reconstructed from caller assertions, fabricated before issuance, or replaced by a later authority read. -A failed final audit-outcome update does not roll back an already committed domain mutation. Each owner exposes an internal, read-only request-result lookup callable only by the allowlisted Logging and Admin workload. The lookup request carries the canonical complete `postAuthorizationExecutionTuple`: `controlPlaneRequestId`, `mutationDigest`, `issuanceKind`, Account-returned `authorizationReferenceFingerprint`, exact typed `scope`, normalized `actionFamily`, `actionFamilySchemaId`, `actionFamilySchemaVersion`, typed `target`, immutable typed `targetOwner`, typed `expectedVersion`, typed `mutation`, typed `auditReason`, the exact authenticated `workloadIdentity` and actor binding, the applicable automation-policy identity, `reservationOwnerId`, positive `reservationClaimFence`, exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, the exact canonical `authorityEvidenceBundle/v1` by reference to ADR 0047, and every schema-bound typed presence/absence value, including the explicit no-policy value for a human request and any schema-bound absent or null values represented by the digest. The owner may use `controlPlaneRequestId` only to locate a candidate durable idempotency/result record; it then validates `mutationDigest` integrity and every typed tuple member, including normalized action family, schema pair, scope, target, immutable typed `targetOwner`, expected version, mutation, audit reason, workload/actor and policy identity, reservation owner/fence, `authorityTuple`, `membershipVersion`, `issuanceFence`, authority evidence/source versions, and every bound presence/absence value, before returning the result. Any mismatch returns canonical `IDEMPOTENCY_CONFLICT` without exposing the stored result or mutating state. The lookup cannot execute or reauthorize the mutation, so it remains safe after the original human or automation authorization reference expires or is revoked. +A failed final audit-outcome update does not roll back an already committed domain mutation. Each owner exposes an internal, read-only request-result lookup callable only by the allowlisted Logging and Admin workload. The lookup request carries the canonical complete `postAuthorizationExecutionTuple`: the action-family request identity, `mutationDigest`, `issuanceKind`, Account-returned `authorizationReferenceFingerprint`, exact typed `scope`, normalized `actionFamily`, `actionFamilySchemaId`, `actionFamilySchemaVersion`, typed `target`, immutable typed `targetOwner`, typed `expectedVersion`, typed `mutation`, typed `auditReason`, the exact authenticated `workloadIdentity` and actor binding, the applicable automation-policy identity, `reservationOwnerId`, positive `reservationClaimFence`, exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, the exact canonical `authorityEvidenceBundle/v1` by reference to ADR 0047, and every schema-bound typed presence/absence value, including the explicit no-policy value for a human request and any schema-bound absent or null values represented by the digest. The owner may use the action-family request identity only to locate a candidate durable idempotency/result record; it then validates `mutationDigest` integrity and every typed tuple member, including normalized action family, schema pair, scope, target, immutable typed `targetOwner`, expected version, mutation, audit reason, workload/actor and policy identity, reservation owner/fence, `authorityTuple`, `membershipVersion`, `issuanceFence`, authority evidence/source versions, and every bound presence/absence value, before returning the result. Any mismatch returns canonical `IDEMPOTENCY_CONFLICT` without exposing the stored result or mutating state. The lookup cannot execute or reauthorize the mutation, so it remains safe after the original human or automation authorization reference expires or is revoked. + +The ADR 0048 orchestration record for this lookup is located by `controlPlaneRequestId`. An owner may use the tagged action-family identity only to locate its own domain idempotency/result candidate, then must exact-compare the complete tuple; the tag never creates a second orchestration record or reservation key. Every owner result lookup carries the expected phase and state in addition to the complete authority-bound tuple. An exact tuple with the wrong phase/state is not an existing result for that request: it returns `IDEMPOTENCY_CONFLICT` or the applicable stale-fence outcome and cannot authorize a phase transition. -Logging and Admin retains the original durable intent and reconciles through the owner result lookup until the owner result can be recorded. A terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` result must satisfy one of ADR 0048's two terminal-proof forms: pre-redemption no-redemption evidence, or post-redemption evidence of no owner acceptance, owner commit, or business mutation. It is read-only evidence for the original attempt, not rearm authority. An `IDEMPOTENCY_CONFLICT`, an unconverted `FENCE_REJECTED`, or any mismatch in the complete post-authorization authority-bound tuple is not rearmable. A pre-authorization `ACCOUNT_AUTHORIZATION/NOT_EXECUTED_BEFORE_AUTHORIZATION` record is terminal and requires a new explicit operator request. Any later owner attempt requires a new `controlPlaneRequestId`, fresh Account authorization, a new opaque reference, and a new owner record; it never calls `RedeemOperatorAuthorization` with the consumed reference or reuses the prior owner attempt. Any other terminal result is replay-only through the read-only lookup. An expired `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` claim remains in that phase until a fenced recovery owner recovers the original response and atomically enriches to `AUTHORIZED`, or until the independent no-authorization/no-forward proof permits `NOT_EXECUTED_BEFORE_AUTHORIZATION`; it never becomes `OWNER_EXECUTION/OWNER_EXECUTION_PENDING` merely because the Account call was ambiguous. An expired `OWNER_EXECUTION/OWNER_EXECUTION_PENDING` claim, missing owner record after owner dispatch, or any other indeterminate owner-execution phase remains read-only and non-replayable and retains its existing `ownerMutationId`; it never allocates a successor attempt. Durable absence cannot prove that an already dispatched mutation will not commit later, and authority revocation or expiry prevents rearm rather than creating a fresh reference to replay the old write. +Logging and Admin retains the original durable intent and reconciles through the owner result lookup until the owner result can be recorded. A terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` result must satisfy one of ADR 0048's two terminal-proof forms: pre-redemption no-redemption evidence, or post-redemption evidence of no owner acceptance, owner commit, or business mutation. It is read-only evidence for the original attempt, not rearm authority. An `IDEMPOTENCY_CONFLICT`, an unconverted `FENCE_REJECTED`, or any mismatch in the complete post-authorization authority-bound tuple is not rearmable. A pre-authorization `ACCOUNT_AUTHORIZATION/NOT_EXECUTED_BEFORE_AUTHORIZATION` record is terminal and requires a new explicit operator request. Any later owner attempt requires a new action-family request identity, fresh Account authorization, a new opaque reference, and a new owner record; it never calls `RedeemOperatorAuthorization` with the consumed reference or reuses the prior owner attempt. Any other terminal result is replay-only through the read-only lookup. An expired `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` claim remains in that phase until a fenced recovery owner recovers the original response and atomically enriches to `AUTHORIZED`, or until the independent no-authorization/no-forward proof permits `NOT_EXECUTED_BEFORE_AUTHORIZATION`; it never becomes `OWNER_EXECUTION/OWNER_EXECUTION_PENDING` merely because the Account call was ambiguous. An expired `OWNER_EXECUTION/OWNER_EXECUTION_PENDING` claim, missing owner record after owner dispatch, or any other indeterminate owner-execution phase remains read-only and non-replayable and retains its existing `ownerMutationId`; it never allocates a successor attempt. Durable absence cannot prove that an already dispatched mutation will not commit later, and authority revocation or expiry prevents rearm rather than creating a fresh reference to replay the old write. `FENCE_REJECTED` is the initial wire/status outcome for a stale owner or fence and is non-rearmable only after the rejecting owner atomically persists that outcome with immutable no-accept/no-commit proof for the exact owner attempt, observed owner/gameplay fence, and complete tuple. The owner must not emit `FENCE_REJECTED` before that durable proof exists. If the proof is absent, incomplete, or inconsistent, the durable request remains `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`; it cannot be replayed, converted to `NOT_EXECUTED`, or rearmed. If the owner loses its lease afterward, exactly one CAS-selected recovery owner with a newer owner fence may validate the persisted proof, confirm that the rejecting owner can no longer commit, and transition `OWNER_EXECUTION/FENCE_REJECTED` to terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION`. Logging and Admin, a caller, or a recovery reader without the fenced owner-recovery CAS may not synthesize or advance that transition. Until the rejecting owner or qualifying recovery owner records the terminal outcome, a valid `FENCE_REJECTED` remains non-rearmable. @@ -121,13 +129,13 @@ Owner-side admission, feature-flag, and tick control RPCs are `internal_workload `/moderation/actions` and `ApplyModerationAction` are a Logging & Admin-owned policy-input/audit path, not a forwarded domain mutation. Account owns issuance of the Account authorization reference, and Logging & Admin validates and redeems it at the receiving boundary before the path can persist policy input and audit evidence. This path does not require or perform domain-owner redemption or enforcement. The separate live `EvaluateModerationPolicy` read remains input at the current Game Session and Social & Groups enforcement boundaries; Account enforces its account-wide categories from Account-owned state, while versioned propagation and domain enforcement remain target-state work. -Until its action-family schema, shared `mutationDigest/v1` vectors, Account issuance, and receiving-boundary validation/redemption are complete, this path remains unavailable/gated and these are target contract rules, not enablement. Once enabled, its durable intent uses the exact path request tuple: `controlPlaneRequestId`, `mutationDigest`, action-family schema pair, typed scope/target/expected-version/mutation/audit-reason fields, and every schema-declared presence/absence value. Before Account issuance or receiving-boundary redemption, the exact `preAuthorizationReservationTuple/v1` and its claim fence are the idempotency identity; after Account returns, the unchanged authorization fingerprint, applicable authority evidence, and reservation fields are retained through receiving-boundary redemption and policy/audit persistence. An exact duplicate returns the stored lifecycle result without a second issuance, redemption, or policy write; any tuple, digest, schema, fingerprint, evidence, or claim mismatch returns `IDEMPOTENCY_CONFLICT` without mutation. The durable intent must exist before the first Account call; if it cannot be written, the path is not attempted. A successful receiving-boundary redemption is not by itself a committed policy outcome: policy-input and audit persistence must reach the durable terminal result. If persistence fails or the response is lost after redemption, the consumed reference is never redeemed again and no replacement reference is issued; the intent remains outcome-pending and a fenced recovery owner performs only an exact read-only lookup/reconciliation of the intent and policy/audit record until the stored result is known. No domain-owner execution phase, owner mutation, owner-result store, or owner-side `NOT_EXECUTED` proof is created for this path. +Until its action-family schema, shared `mutationDigest/v1` vectors, Account issuance, and receiving-boundary validation/redemption are complete, this path remains unavailable/gated and these are target contract rules, not enablement. Once enabled, the ADR 0048 orchestration reservation is keyed by stable `controlPlaneRequestId`, and duplicate/recovery lookup exact-compares its immutable `preAuthorizationReservationTuple/v1`. That tuple carries the moderation policy-intent identity `policyIntentRequestId`, `mutationDigest`, action-family schema pair, typed scope/target/expected-version/mutation/audit-reason fields, and every schema-declared presence/absence value. `policyIntentRequestId` remains the moderation-domain idempotency identity; any carried `controlPlaneRequestId` is correlation-only at that domain boundary. The reservation claim fence is transition authority for the current owner, not a fresh intent or duplicate identity: a stale owner/fence is rejected without mutation and is not collapsed into `IDEMPOTENCY_CONFLICT` for an otherwise unchanged request tuple. After Account returns, the exact stored `postAuthorizationExecutionTuple`, including the original authorization fingerprint, applicable authority evidence, and reservation fields, is retained through receiving-boundary redemption and policy/audit persistence; a refreshed claim fence may authorize a permitted transition but does not replace that stored tuple or create a new intent. An exact duplicate returns the stored lifecycle result without a second issuance, redemption, or policy write; an actual tuple, digest, schema, fingerprint, or evidence mismatch returns `IDEMPOTENCY_CONFLICT` without mutation. The durable intent must exist before the first Account call; if it cannot be written, the path is not attempted. A successful receiving-boundary redemption is not by itself a committed policy outcome: policy-input and audit persistence must reach the durable terminal result. If persistence fails or the response is lost after redemption, the consumed reference is never redeemed again and no replacement reference is issued; the intent remains outcome-pending and a fenced recovery owner performs only an exact read-only lookup/reconciliation of the intent and policy/audit record until the stored result is known. No domain-owner execution phase, owner mutation, owner-result store, or owner-side `NOT_EXECUTED` proof is created for this path. ### Redis-Backed Owner Mutations The Redis-backed owner record, write-ahead evidence, effect/outcome evidence, and Redis projection are created only after the durable `ACCOUNT_AUTHORIZATION/AUTHORIZED -> OWNER_EXECUTION/OWNER_EXECUTION_PENDING` transition. They use the canonical complete `postAuthorizationExecutionTuple` defined above; Redis markers, key presence, and command responses never replace its `issuanceKind`, immutable typed `targetOwner`, `authorityTuple`, `membershipVersion`, `issuanceFence`, `reservationOwnerId`, `reservationClaimFence`, or immutable authority evidence/source versions. The `ACCOUNT_AUTHORIZATION/RESERVED`, `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING`, and `ACCOUNT_AUTHORIZATION/AUTHORIZED` states remain in the Logging and Admin reservation record until the durable owner-execution transition; no Redis owner record or projection is created for them, and no post-authorization field is fabricated before Account authorization. -Coordination Redis is a volatile projection, not the durable owner of an operator mutation. After the durable authorized-to-owner transition, any supported action that materializes state in Redis must first create or claim a durable owner request record containing the canonical complete `postAuthorizationExecutionTuple` (`controlPlaneRequestId`, `mutationDigest`, `issuanceKind`, Account-returned `authorizationReferenceFingerprint`, exact typed `scope`, normalized `actionFamily`, `actionFamilySchemaId`, `actionFamilySchemaVersion`, typed `target`, immutable typed `targetOwner`, typed `expectedVersion`, typed `mutation`, typed `auditReason`, exact `workloadIdentity`, applicable workload/policy identity, exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, the exact canonical `authorityEvidenceBundle/v1` by reference to ADR 0047, and every schema-bound typed presence/absence value), desired mutation, `phase=OWNER_EXECUTION`, `state=OWNER_EXECUTION_PENDING`, `ownerMutationId`, current owner/lease identity, fencing token, lease expiry, and terminal result, together with durable write-ahead and effect evidence sufficient to distinguish a committed effect, an unstarted attempt, and an indeterminate attempt. Atomic mutation-plus-result commit applies within the authoritative durable owner store; it does not imply a distributed transaction with Redis. The Logging and Admin reservation record remains the sole durable record for `ACCOUNT_AUTHORIZATION/RESERVED`, `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING`, and `ACCOUNT_AUTHORIZATION/AUTHORIZED`; the owner record and effect evidence are the source of truth only for `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`, `COMMITTED`, `FAILED`, `FENCE_REJECTED`, and `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION`. Redis key presence or a Redis command response alone is never a terminal result. +Coordination Redis is a volatile projection, not the durable owner of an operator mutation. After the durable authorized-to-owner transition, any supported action that materializes state in Redis must first create or claim a durable owner request record containing the canonical complete `postAuthorizationExecutionTuple` (the action-family request identity, `mutationDigest`, `issuanceKind`, Account-returned `authorizationReferenceFingerprint`, exact typed `scope`, normalized `actionFamily`, `actionFamilySchemaId`, `actionFamilySchemaVersion`, typed `target`, immutable typed `targetOwner`, typed `expectedVersion`, typed `mutation`, typed `auditReason`, exact authenticated `workloadIdentity` and actor binding, applicable workload/policy identity, exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, the exact canonical `authorityEvidenceBundle/v1` by reference to ADR 0047, and every schema-bound typed presence/absence value), desired mutation, `phase=OWNER_EXECUTION`, `state=OWNER_EXECUTION_PENDING`, `ownerMutationId`, current owner/lease identity, fencing token, lease expiry, and terminal result, together with durable write-ahead and effect evidence sufficient to distinguish a committed effect, an unstarted attempt, and an indeterminate attempt. Atomic mutation-plus-result commit applies within the authoritative durable owner store; it does not imply a distributed transaction with Redis. The Logging and Admin reservation record remains the sole durable record for `ACCOUNT_AUTHORIZATION/RESERVED`, `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING`, and `ACCOUNT_AUTHORIZATION/AUTHORIZED`; the owner record and effect evidence are the source of truth only for `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`, `COMMITTED`, `FAILED`, `FENCE_REJECTED`, and `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION`. Redis key presence or a Redis command response alone is never a terminal result. The owner-execution durable record is written ahead of Redis in this order: persist the exact `ownerMutationId`, originating owner fence, target-state digest, intended effect, and `dispatchState=NOT_DISPATCHED`; persist `dispatchState=DISPATCHED` before any call that could reach Redis; then, only after a successful script result or an exact read-only marker/state proof, persist effect evidence bound to that attempt, marker identity, originating fence, target version, and canonical tuple. A durable terminal result is written only from that evidence and with the current durable owner fence. A crash with `NOT_DISPATCHED` and durable proof that the old claimant can no longer dispatch reconciles to `UNSTARTED`; a crash after `DISPATCHED` and before a script result is `INDETERMINATE` unless exact durable evidence proves no dispatch could occur; a crash after an accepted script and before effect/terminal persistence reconciles to `COMMITTED` only when the marker and target state exactly match the attempt and tuple, after which the durable effect and result are recorded. If the Redis marker is lost, durable committed effect evidence still supports `COMMITTED`; a missing marker with only write-ahead or dispatch evidence is `INDETERMINATE`, never `UNSTARTED`, and is never replayed. These classifications are produced by read-only reconciliation of durable owner evidence and current Redis state; reconciliation does not call the business mutator or Lua script, and an indeterminate attempt remains non-replayable. @@ -172,7 +180,7 @@ Rejected because the front end is not the lease owner and cannot safely serializ The current implementation is partial. Each supported operator-action family must demonstrate: -- Wherever the proof refers to a full or complete authority-bound identity, it must name and compare the canonical complete `postAuthorizationExecutionTuple`, including `controlPlaneRequestId`, `mutationDigest` integrity, `issuanceKind`, exact authenticated workload and actor/policy binding, normalized `actionFamily`, schema identifier/version, typed scope/target, immutable typed `targetOwner`, typed expected-version/mutation/audit-reason fields, every schema-bound typed presence/absence value, the exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, and immutable authority evidence/source versions. No complete-authority proof may substitute a digest, current owner lookup, or partial identity for this tuple. +- Wherever the proof refers to a full or complete authority-bound identity, it must name and compare the canonical complete `postAuthorizationExecutionTuple`, including the action-family request identity, `mutationDigest` integrity, `issuanceKind`, exact authenticated workload and actor/policy binding, normalized `actionFamily`, schema identifier/version, typed scope/target, immutable typed `targetOwner`, typed expected-version/mutation/audit-reason fields, every schema-bound typed presence/absence value, the exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, immutable authority evidence/source versions, and the Account-returned `authorizationReferenceFingerprint`. No complete-authority proof may substitute a digest, current owner lookup, or partial identity for this tuple. - Current WorldLifecycle evidence is not full support for this ADR. `WorldLifecycleCommandServiceImpl.prepareWorldInstance` looks up by `(tenantId, gameInstanceId)` and compares the prepared fields, including `controlPlaneRequestId`; an exact prepared duplicate returns the existing snapshot, while a mismatch currently returns `INVALID_ARGUMENT`, not request-keyed `IDEMPOTENCY_CONFLICT`. Activation and failure are guarded by lifecycle epoch/state but have no complete request-tuple record. Termination uses `terminationRequestId` for state transitions and repeated terminal reads, but does not yet provide a durable terminal result/fingerprint for every retry or prove that a same-request retry cannot repeat cleanup. `TemporalWorldLifecycleOrchestrator` uses a deterministic tenant/game-instance workflow ID and queries an existing workflow after `WorkflowExecutionAlreadyStarted`, but does not compare a full request digest on prepare; its lifecycle read attaches Temporal describe metadata to a fallback domain snapshot rather than proving domain-state and workflow-status equivalence. The workflow signals also do not enforce a durable request identity/digest. These paths remain partial and must not be reported as satisfying the target idempotency contract. - For WorldLifecycle to satisfy this ADR, each lifecycle command must use a stable request identity and canonical digest for the complete typed request tuple, with durable same-tuple replay and `IDEMPOTENCY_CONFLICT` on mismatch; deterministic workflow identity alone is insufficient. A status response must separately identify the authoritative domain snapshot and Temporal execution metadata, and may claim convergence only after proof that both represent the same lifecycle state and epoch. @@ -181,7 +189,7 @@ The current implementation is partial. Each supported operator-action family mus - for `/moderation/actions` and `ApplyModerationAction`, Account authorization-reference issuance plus Logging & Admin receiving-boundary validation/redemption, without treating domain-owner redemption or enforcement as part of the policy-input/audit path; - atomic owner mutation and result persistence with duplicate delivery returning the original result only on a full tuple match, and every mismatch returning canonical `IDEMPOTENCY_CONFLICT` without mutation; - for Redis-backed owner state, a durable reservation-owner claim lease with CAS acquire/renew/expiry/completion and a monotonic fence, explicit phase/state in every CAS, durable claim/state/result and effect-evidence records, marker-based Lua mutation, atomic no-accept/no-commit proof with `FENCE_REJECTED`, lease-owner fencing for new writes and terminal commits, and non-replayable read-only reconciliation that validates the prior `ownerMutationId` and originating fence after a crash or lease transfer; -- an allowlisted read-only owner result lookup that locates by `controlPlaneRequestId` but validates the canonical complete `postAuthorizationExecutionTuple`, including `mutationDigest` integrity, `issuanceKind`, normalized `actionFamily`, typed scope/target, immutable typed `targetOwner`, typed expected-version/mutation/audit-reason fields, every schema-bound typed presence/absence value, the exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, immutable authority evidence/source versions, Account-returned authorization-reference fingerprint, schema identifier/version, exact workload/policy identity, and actor binding, returning `IDEMPOTENCY_CONFLICT` for any mismatch and recovering only the durable terminal outcome after authorization expiry or revocation without executing, forwarding, or reauthorizing the mutation; if no exact terminal result exists, the request remains non-replayable and requires a new explicit operator request plus fresh Account authorization; +- an allowlisted read-only owner result lookup that locates by the action-family request identity but validates the canonical complete `postAuthorizationExecutionTuple`, including `mutationDigest` integrity, `issuanceKind`, normalized `actionFamily`, typed scope/target, immutable typed `targetOwner`, typed expected-version/mutation/audit-reason fields, every schema-bound typed presence/absence value, the exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, immutable authority evidence/source versions, Account-returned authorization-reference fingerprint, schema identifier/version, exact workload/policy identity, and actor binding, returning `IDEMPOTENCY_CONFLICT` for any mismatch and recovering only the durable terminal outcome after authorization expiry or revocation without executing, forwarding, or reauthorizing the mutation; if no exact terminal result exists, an `OWNER_EXECUTION/OWNER_EXECUTION_PENDING` attempt remains non-replayable and no fresh request identifier may be accepted until durable terminal commit/no-commit evidence, or an equivalent owner-fenced proof that the prior attempt cannot commit, is recorded; only then may a new explicit operator request plus fresh Account authorization be used; - recovery from crashes before forwarding, during owner execution, after owner commit, and before final outcome recording; - truthful operator outcomes for rejection, timeout, lost response, duplicate delivery, authorization expiry, and reconciliation; - no successful mutation when the initial intent store is unavailable; diff --git a/design/architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md b/design/architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md index 8d504a0b3e..4ea6d9ddfc 100644 --- a/design/architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md +++ b/design/architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md @@ -46,11 +46,11 @@ The existing split is sound, but two contracts are too weak. Reusing an `EffectI ### Effect Identity and Participant Guards -Game Session assigns one stable root `EffectId` to the logical effect and persists intended pre/post state and required participants. Each participant derives a deterministic guard identity from the root effect, typed operation, and target aggregate. Its durable guard binds that identity to an immutable request digest and stored outcome. +For a root mutation, Game Session assigns one stable root `EffectId` to the logical effect and persists intended pre/post state and required participants. Each participant resolves its owner-local guard using the persisted mutation `EffectId` as the stable collision key for that participant (the root `EffectId` for a root mutation or the persisted child `EffectId` for a generated child). An existing candidate is reusable only after separately exact-comparing the typed operation, exact target aggregate, owner-declared runtime-family partition—S1/S2 use `(tenantId, playableStateNamespaceId)`, explicit S3 uses `(tenantId, gameInstanceId)`, and an unknown or unclassified family fails closed—and immutable `requestDigest`; any mismatch fails closed. Where one mutation has multiple participants, the owner-local participant/target slot keeps those sibling guards distinct. A generated child retains its enclosing root only as lineage and reconciliation context. The durable guard stores the binding and outcome. The separate [ADR 0183 proposal](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is not accepted target state and may not be used as an implementation requirement. - Same identity plus the same request returns the prior durable result. - Same identity with a different operation, target, or request digest fails closed. -- Derived reactions use deterministic child effect identities rather than accidental reuse. +- Derived reactions retain their owner-defined child ordinal and durably persist the complete owner-scope/root/parent/ordinal-to-child-`EffectId` mapping before enqueue/apply; retries and replay reuse that mapping. This accepted child-identity contract is owned by [ADR 0075](./adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md). Pending [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) concerns additional command-plan ordering, command-root, scalar-format, and allocation mechanics; it does not gate or redefine the accepted child mapping. - Participant acknowledgement means the guard and effect-visible domain rows committed together. - Player success waits for all declared required participants under ADR 0053. diff --git a/design/architecture/decisions/adr-0061-single-owner-spatial-mutations-across-split-authority.md b/design/architecture/decisions/adr-0061-single-owner-spatial-mutations-across-split-authority.md index 357ffee08e..167fbb5d44 100644 --- a/design/architecture/decisions/adr-0061-single-owner-spatial-mutations-across-split-authority.md +++ b/design/architecture/decisions/adr-0061-single-owner-spatial-mutations-across-split-authority.md @@ -48,7 +48,7 @@ The canonical Game Session root binding is authenticated and exact-compared befo - `MOVE` mutates World location/occupancy in one World transaction. Pure movement has no Entity mutation participant. - `DROP` and `PICKUP` mutate the item's holder in one Entity transaction. They use the existing World `TargetingFactSnapshot` actor-location/location-version token, admitted under the Game Session actor/executor fence and passed to Entity as owner-issued location evidence. Before committing, Entity atomically validates that token for the same room/epoch together with the expected holder and Entity aggregate version; stale or mismatched World location evidence fails admission and re-resolves under the same root `EffectId` and immutable request digest, without transferring item authority to World. -Every owner derives a participant guard identity from the root `EffectId`, typed operation, and target aggregate, and binds it to an immutable request digest and durable result. Same guard and same request replays the prior result; the same guard with a different operation, target, or digest fails closed. +Every owner resolves its participant guard using the persisted mutation `EffectId` as the stable collision key for that participant (the root `EffectId` for a root mutation or the persisted child `EffectId` for a generated child). An existing candidate is reusable only after separately exact-comparing the typed operation, exact target aggregate, owner-declared runtime-family partition—S1/S2 use `(tenantId, playableStateNamespaceId)`, explicit S3 uses `(tenantId, gameInstanceId)`, and an unknown or unclassified family fails closed—and immutable `requestDigest`; any mismatch fails closed. Where one mutation has multiple participants, the owner-local participant/target slot keeps those sibling guards distinct. A generated child retains its enclosing root only as lineage and reconciliation context. Same guard and same request replays the prior result. The owner-scope/root/parent/ordinal-to-child-`EffectId` mapping and enclosing-root lineage required by ADR 0075 are accepted independently of ADR 0183. Command-plan ordering, root allocation, and identity-format or allocation mechanics not defined by that mapping remain subject to the non-authoritative [ADR 0183 proposal](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). Correctness mutations carry exact scope, epoch, and relevant expected state: @@ -56,7 +56,7 @@ Correctness mutations carry exact scope, epoch, and relevant expected state: - drop and pickup include World-authoritative actor-location evidence plus expected current holder and Entity aggregate version; and - ambient changes include the owning World aggregate and expected version. -Derived ambient or gameplay reactions use deterministic child effect identities and declare whether they are required or optional. Only declared required participants delay logical player success. Presentation reads use ADR 0059's causal floor and distinct component versions, never service-local snapshot equality; that presentation causal floor is not a mutation guard and is never substituted for the World targeting token. +Derived ambient or gameplay reactions use deterministic child effect identities and declare whether they are required or optional. Only declared required participants delay logical player success. Presentation reads use ADR 0059's causal floor and distinct component versions, never service-local snapshot equality; that presentation causal floor is not a mutation guard and is never substituted for the World targeting token. The non-authoritative [ADR 0183 proposal](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) concerns command-plan and root allocation mechanics beyond ADR 0075's accepted generated-child mapping. ## Consequences @@ -90,7 +90,7 @@ Rejected because at-least-once delivery and stale room evidence could duplicate ## Implementation and Proof Obligations -Proof must cover digest-conflict rejection, duplicate replay, stale epoch/location/holder/version, move without an Entity mutation, drop/pickup without World item ownership, no double location or holder, deterministic required and optional child effects, crash and reconciliation, and causal-floor room presentation. The effect catalog is the required inventory for new spatial and ambient effect families. +Proof must cover digest-conflict rejection, duplicate replay, stale epoch/location/holder/version, move without an Entity mutation, drop/pickup without World item ownership, no double location or holder, deterministic required/optional child admission and outcome classification, crash and reconciliation, and causal-floor room presentation. Command-plan and root-allocation proof for the pending [ADR 0183 proposal](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is not claimed here. The effect catalog is the required inventory for new spatial and ambient effect families. ## Reversibility and Revisit Triggers diff --git a/design/architecture/decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md b/design/architecture/decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md index 98361054af..9274e1f18d 100644 --- a/design/architecture/decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md +++ b/design/architecture/decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md @@ -47,9 +47,9 @@ Within one entity's eligible queue, work uses persisted deterministic ordering: `(priority, due_tick_id, entity_enqueue_seq, source_kind, commandId_or_effectKey)` -`entity_enqueue_seq` is monotonic within the entity's current region epoch and assigned by the owning Game Session admission/scheduling path. Same-tick derived children use the persisted parent order plus deterministic child ordinals rather than completion timing. New sources map into this tuple and do not introduce private tie-breakers. +`entity_enqueue_seq` is monotonic within the entity's current region epoch and assigned by the owning Game Session admission/scheduling path. Same-tick derived children use the persisted parent order plus recorded owner-allocated child ordinals rather than completion timing. New sources map into this tuple and do not introduce private tie-breakers. -The historical final tuple label `commandId_or_effectKey` is one normalized, persisted, source-specific stable identity slot: `command` uses `commandId`; `timer` uses the timer member ID; `retry` uses the persisted retry member/effect identity required by its owning contract; `remote_followup` uses the durable follow-up row ID; and `generated_effect` uses its recorded deterministic child `EffectId`, derived under the immutable parent/root identity and child ordinal contract. The selected manifest retains this exact source-to-slot mapping for each item; this does not introduce a second tuple or schema field. +The historical final tuple label `commandId_or_effectKey` is one normalized, persisted, source-specific stable identity slot: `command` uses `commandId`; `timer` uses the timer member ID; `retry` uses the persisted retry member/effect identity required by its owning contract; `remote_followup` uses the durable follow-up row ID; and `generated_effect` uses its recorded child `EffectId` as the slot value. Parent/root identity and child ordinal remain recorded audit and ordering context; they do not replace the child effect identity. The selected manifest retains the source-to-slot mapping and that context for each item; this does not introduce a second tuple or schema field. For generated children, the owner-defined ordinal and durable owner-scope/root/parent/ordinal-to-child-`EffectId` mapping are mandatory and replay-stable under accepted [ADR 0075](./adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md). Only scalar choices and additional allocator mechanics remain pending in [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); that proposal does not defer the accepted child identity or mapping requirement. Across eligible entities, each lane uses persisted deterministic rotating/deficit scheduling. The scheduler accounts for declared work cost, advances only with the durable selected batch, and ensures a permanently eligible entity eventually receives capacity within a healthy epoch. Non-best-effort priority classes declare bounded aging or `maxDeferralTicks`; work explicitly classified as best effort follows its declared delay/drop policy. @@ -87,7 +87,7 @@ Deferred because entity locks do not prove independence from shared room or mult ## Implementation and Proof Obligations -Proof must cover one actor action plus bounded effects, per-entity ordering, deterministic child ordinals, cost-aware rotating/deficit fairness, bounded non-best-effort deferral, reserved lane budgets, source-flood resistance, crash before and after batch persistence, replay from the recorded manifest, epoch reset, scheduler-state recovery, and the prohibition on staging tick `N+1` before matching cleanup of tick `N`. +Proof must cover one actor action plus bounded effects, per-entity ordering, owner-allocated persisted child ordinals and replay-stable mappings, cost-aware rotating/deficit fairness, bounded non-best-effort deferral, reserved lane budgets, source-flood resistance, crash before and after batch persistence, replay from the recorded manifest, epoch reset, scheduler-state recovery, and the prohibition on staging tick `N+1` before matching cleanup of tick `N`. The current runtime remains narrower and game-instance scoped; this decision does not claim the region scheduler or proof exists. diff --git a/design/architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md b/design/architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md index 72ec754ff6..a9abacab18 100644 --- a/design/architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md +++ b/design/architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md @@ -6,13 +6,14 @@ Accepted ## Implementation Status -The command/effect boundary and single logical terminal outcome are target state; complete durable identity guards, evidence-based reconciliation, and focused crash/replay proof remain incomplete. +The command/effect boundary and single logical terminal outcome are accepted target state; complete durable identity guards, evidence-based reconciliation, and focused crash/replay proof remain incomplete. Deterministic command-plan ordering, `planOrdinal`, and root-allocation details are proposed separately in [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) and are not accepted by this decision. ## Canonical Design - [Tick Execution Flows](../system-architecture-tick-execution-flows.md) - [Tick Failure and Operations](../system-architecture-tick-failures-and-operations.md) - [Transaction Strategies](../system-architecture-transactions.md) +- [Identifier Glossary](../system-architecture-identifier-glossary.md#cross-service-effect-identity) ## Decision Record @@ -35,18 +36,24 @@ Describing this as “exactly-once execution” would wrongly imply one physical ## Decision -An accepted command lost before durable staging terminates at the command lifecycle with: +An `ACCEPTED_VOLATILE` command may terminate as lost before durable staging only when an atomic owner-defined CAS/version-fenced transition on the authoritative command record wins from the eligible `RECEIVED` or `ENQUEUED` state; if concurrent staging wins, the loss transition affects zero rows. The owner must also provide positive authoritative evidence that no batch committed, no effect was materialized, and no domain application occurred; ingress status or a missing batch/effect identifier alone is insufficient. The current purge path does not prove this target boundary. See the evidence owner contracts in [Transactions](../system-architecture-transactions.md) and [Tick Failures and Operations](../system-architecture-tick-failures-and-operations.md). - `executionOutcome = LOST_BEFORE_STAGING`; and - `gameplayResult = NOT_APPLIED`. -No effect ledger row is invented for a command that never produced a durably claimed or staged effect. +An `ACCEPTED_DURABLE` command follows its feature-specific durable intake and recovery contract instead; it is not classified as `LOST_BEFORE_STAGING` by this rule. No effect ledger row is invented for a command that never produced a durably claimed or staged effect. -Before any participant verification, the canonical Game Session context binds each durably claimed or staged effect's root `EffectId` to its typed operation, immutable request digest, required-participant context, and sealed manifest. Participants validate that sealed binding before their local guard/effect work; a conflicting operation, digest, or participant binding fails closed. Before terminal aggregation, Game Session must also verify that the returned participant projections exactly equal the sealed expected participant set and that every projection matches that same root, operation, digest, participant context, and manifest binding. A missing, extra, duplicate, partial, or conflicting projection fails closed and remains reconciliation-required rather than producing a terminal aggregate. Physical execution is at least once: retries may invoke the handler multiple times after crashes, lost acknowledgements, or replay. +Before any participant verification, the canonical Game Session context binds each durably claimed or staged effect's persisted mutation `EffectId`—the root `EffectId` for a root effect or the generated child's persisted `EffectId` for a child effect—to its typed operation, immutable request digest, required-participant context (including applicable `playableStateNamespaceId` identity evidence and separately persisted `playableStateScope` fence evidence), and sealed manifest. When applicable, the enclosing `rootEffectId` is retained only as lineage and reconciliation context. Participants exact-validate that sealed binding before their local guard/effect work; a conflicting operation, digest, namespace, scope, or participant binding fails closed. Before terminal aggregation, Game Session must also verify that the returned participant projections exactly equal the sealed expected participant set and that every projection matches that same persisted mutation `EffectId`, operation, digest, participant context, namespace, scope, and manifest binding. A missing, extra, duplicate, partial, or conflicting projection fails closed and remains reconciliation-required rather than producing a terminal aggregate. Physical execution is at least once: retries may invoke the handler multiple times after crashes, lost acknowledgements, or replay. The owning domain's durable idempotency guard permits at most one logical authoritative state mutation for that identity and digest. Reuse of the identity with a conflicting digest fails closed. -Every staged effect ledger row reaches exactly one terminal status: +The owner-defined child ordinal and durable owner-scope/root/parent/ordinal-to-child-`EffectId` admission mapping required by ADR 0075 are accepted. The exact scalar format and root, command-plan, or other identity-allocation mechanics not defined by that mapping remain unresolved and are proposed in [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). This decision requires retries and replay to preserve the persisted mutation identity and immutable request digest; it does not define command-plan ordering, `planOrdinal`, or a root-allocation key. + +Command receipts, tick batches, and selected-work manifests are S3 instance-scoped operational evidence: they may be cleaned up only after linked source claims and effects are terminal, replay/restore and reconciliation horizons have elapsed, and the owner cleanup fence permits it. Participant guards remain owner-domain durable evidence, with their own namespace/state classification and retention contract; they are not disposable Redis coordination state. A reset or replacement alone never authorizes bulk deletion or abandonment. + +An ordinary retry or replay preserves the original persisted mutation identity and digest. A post-abandon re-drive is permitted only under conclusive `ABANDONED` and source-terminalization rules and follows the source owner's admission and identity contract, linked to the abandoned command/effect lineage. This decision does not define command-root allocation for that re-drive. + +Every staged effect ledger row reaches at most one terminal status, and terminalization occurs only when the applicable evidence policy permits it: - `APPLIED` when authoritative domain evidence proves that the logical mutation committed; or - `ABANDONED` only when authoritative evidence proves the effect was unapplied and any already-declared applicable feature rule permits it to be no longer valid, with an explicit reason. Inconclusive execution remains `SCHEDULED`/reconciliation-required; timeout, retry exhaustion, missing coordination, age, or technical failure alone never proves `ABANDONED`. @@ -65,6 +72,7 @@ The system does not silently drop staged effects, leave them permanently ambiguo - Recovery may retry physical work without duplicating authoritative gameplay state. - Operators and callers can distinguish command results, effect terminal states, and replay reasons. - Owner services require durable identity-and-digest guards and authoritative evidence queries. +- Multi-participant conservation remains governed by command atomicity/co-location or reservation semantics; a shared root is not a distributed transaction. - The ledger and recovery controller must retain unresolved staged effects until they reach a justified terminal outcome. - Presentation output can duplicate even while authoritative state remains logically single-apply. @@ -88,7 +96,7 @@ Rejected as the normal contract because unresolved effects could remain ambiguou ## Implementation and Proof Obligations -Proof must cover accepted-command loss before staging without an invented effect row; sealed root/operation/digest/participant/manifest binding before participant verification and conflict rejection; crashes before and after domain commit; lost acknowledgements; duplicate physical invocation with one logical mutation; authoritative `REPLAY_NOOP` evidence terminalizing as `APPLIED`; evidence-qualified `ABANDONED` outcomes with timeout, retry-exhaustion, missing-coordination, age, and technical-failure rejection; command-result derivation across zero, one, and multiple required effects; duplicate presentation feedback without duplicate state; replay and reset convergence; and absence of silent drop or permanently ambiguous staged rows. +Proof must cover accepted-command loss before staging without an invented effect row; sealed mutation identity/operation/digest/participant/manifest binding before participant verification and conflict rejection; crashes before and after domain commit; lost acknowledgements; duplicate physical invocation with one logical mutation; authoritative `REPLAY_NOOP` evidence terminalizing as `APPLIED`; evidence-qualified `ABANDONED` outcomes with timeout, retry-exhaustion, missing-coordination, age, and technical-failure rejection; command-result derivation from required-effect terminal outcomes; duplicate presentation feedback without duplicate state; replay and reset convergence; and absence of silent drop or permanently ambiguous staged rows. Command-plan ordering, `planOrdinal` allocation, and root-allocation proof belong to ADR 0183 only if that proposal is accepted; child-ordinal and generated-child mapping proof remains under ADR 0075. The current implementation and runtime proof are not claimed to satisfy this decision. diff --git a/design/architecture/decisions/adr-0072-class-specific-timer-durability-and-recovery.md b/design/architecture/decisions/adr-0072-class-specific-timer-durability-and-recovery.md index a222f72559..d9f1a5d9c5 100644 --- a/design/architecture/decisions/adr-0072-class-specific-timer-durability-and-recovery.md +++ b/design/architecture/decisions/adr-0072-class-specific-timer-durability-and-recovery.md @@ -54,11 +54,11 @@ Recovery classes are: Redis timer keys, due indexes, leader checkpoints, and wake-up hints are rebuildable and disposable for every class. Durable timer identity, due state, recovery policy, resume-window identity, and terminal or skipped outcomes live outside Redis whenever the class requires recovery or audit. -For target-state `COALESCE_ONE` recovery, Automation owns one durable timer-recovery resume-window record per runtime scope, epoch, and `isDryRun` mode. Its `resumeWindowId` is the exact tuple ``. A durable compare-and-set creates or returns the one `OPEN` window for that scope, epoch, and mode; leader, worker, takeover, and attempt IDs never participate in the identity. At creation, the durable record binds the exact `(scriptPatchVersion, scriptPinEpoch)` tuple as immutable execution-fence evidence without adding it to `resumeWindowId`, freezes the effective numeric tenant-local cap and the selection-policy revision, and persists a frozen pre-window `recoveryStart` watermark plus a monotonic `lastObservedThrough` watermark for each applicable clock domain. Each observation supplies an `observedThrough` watermark, which is durably recorded as the new `lastObservedThrough` only with settlement under that `resumeWindowId`. `recoveryStart` is the exclusive lower bound for the first scan, the prior `lastObservedThrough` is exclusive for every later scan, and the current `observedThrough` is inclusive, so the ranges are `(recoveryStart, observedThrough]` initially and `(lastObservedThrough, observedThrough]` thereafter. A candidate exactly at the inclusive through point is eligible once; a candidate at an exclusive lower bound is not rediscovered. Same-window retries, observations, and takeovers re-read and compare those persisted watermarks and reuse the record, its mode-specific `resumeWindowId`, and its frozen cap and selection-policy revision unchanged; each `CATCH_UP` firing claim and candidate audit includes that ID in uniqueness and comparison. A cap or selection-policy change applies only to a later window allocated after this one reaches `COMPLETE`. The current window becomes `COMPLETE` only after the selected candidates' firing or shared-admission-denial outcomes and all cap-excluded candidate outcomes governed by its frozen values are durable. Only a later recovery episode after completion allocates the next `resumeGeneration`, producing a distinct mode-specific `resumeWindowId`. +For target-state `COALESCE_ONE` recovery, Automation owns one durable timer-recovery resume-window record per playable-state namespace/runtime scope, epoch, and `isDryRun` mode. Its `resumeWindowId` is the exact tuple ``. A durable compare-and-set creates or returns the one `OPEN` window for that namespace/runtime scope, epoch, and mode; the server-derived `playableStateScope` is retained and exact-validated as immutable policy/routing/authorization/fence evidence, not as a uniqueness input. An authority-proven scope transition starts a new playable-state lifecycle and namespace. Stale or mismatched presented scope remains fenced until authoritative reconciliation; the namespace-keyed resume-window identity may be reused only when authority proves the scope unchanged. Leader, worker, takeover, and attempt IDs never participate in the identity. At creation, the durable record binds the exact `(scriptPatchVersion, scriptPinEpoch)` tuple as immutable execution-fence evidence without adding it to `resumeWindowId`, freezes the effective numeric tenant-local cap and the selection-policy revision, and persists a frozen pre-window `recoveryStart` watermark plus a monotonic `lastObservedThrough` watermark for each applicable clock domain. Each observation supplies an `observedThrough` watermark, which is durably recorded as the new `lastObservedThrough` only with settlement under that `resumeWindowId`. `recoveryStart` is the exclusive lower bound for the first scan, the prior `lastObservedThrough` is exclusive for every later scan, and the current `observedThrough` is inclusive, so the ranges are `(recoveryStart, observedThrough]` initially and `(lastObservedThrough, observedThrough]` thereafter. A candidate exactly at the inclusive through point is eligible once; a candidate at an exclusive lower bound is not rediscovered. Same-window retries, observations, and takeovers re-read and compare those persisted watermarks and reuse the record, its mode-specific `resumeWindowId`, and its frozen cap and selection-policy revision unchanged; each `CATCH_UP` firing claim and candidate audit includes that ID in uniqueness and comparison. A cap or selection-policy change applies only to a later window allocated after this one reaches `COMPLETE`. The current window becomes `COMPLETE` only after the selected candidates' firing or shared-admission-denial outcomes and all cap-excluded candidate outcomes governed by its frozen values are durable. Only a later recovery episode after completion allocates the next `resumeGeneration`, producing a distinct mode-specific `resumeWindowId`. A scope-level durable atomic epoch transition must move each prior epoch's `OPEN` resume window, independently for each `isDryRun` mode, out of `OPEN` before any corresponding new-epoch `OPEN` window can be created. Claims from the prior window remain fenced to, and are reconciled under, their original `regionEpoch`, `isDryRun`, and resume-window identity; they cannot be admitted through the new window. The transition follows the existing evidence-based completion and terminalization rules and does not invent a new terminal status or recovery policy. -Every exact script-pin selection change is also a resume-window transition, including a same-patch repin that advances `scriptPinEpoch`, even when the runtime region and region epoch are unchanged. Before any new exact-pin timer admission, durable reconciliation must move every prior mode-specific `OPEN` window for the affected scope out of `OPEN`, fence its claims to the prior exact pin and `resumeWindowId`, and preserve those claims and candidate audits for settlement under their original identities. They cannot consume the next window's cap or be rewritten for the target pin. After the target exact `(scriptPatchVersion, scriptPinEpoch)` and its schedules reconcile, a still-required catch-up episode allocates the next monotonic `resumeGeneration` independently for each mode and therefore a distinct mode-specific `resumeWindowId`; retries of this transition are idempotent under the initiating `controlPlaneRequestId`. +Every exact script-pin selection change is also a resume-window transition, including a same-patch repin that advances `scriptPinEpoch`, even when the runtime region and region epoch are unchanged. Before any new exact-pin timer admission, durable reconciliation must move every prior mode-specific `OPEN` window for the affected namespace/runtime scope out of `OPEN`, fence its claims to the prior exact pin and `resumeWindowId`, and preserve those claims and candidate audits for settlement under their original identities. Existing prior-window claims and their captured candidate identities remain selectable only by reconciliation under that original `resumeWindowId`; the target window must exclude them and cannot rediscover or remint their pending work under new candidate, firing-claim, or event identities. Settlement uses the original candidate, firing-claim, and work identities. This does not prevent the target window from selecting independently reconciled candidates under the new exact pin or later ordinary future occurrences under their own identities. Prior claims cannot consume the next window's cap or be rewritten for the target pin. After the target exact `(scriptPatchVersion, scriptPinEpoch)` and its schedules reconcile, a still-required catch-up episode allocates the next monotonic `resumeGeneration` independently for each mode and therefore a distinct mode-specific `resumeWindowId`; retries of this transition are idempotent under the initiating `controlPlaneRequestId`. `COALESCE_ONE` never replays a burst of missed cadence boundaries. One configurable tenant-local cap bounds synthetic firings across complete stable schedule-instance identities within one mode-specific resume window, which is already scoped to one tenant and one `isDryRun` mode. Selection is deterministic and fair across those identities, including target-scope and plugin-binding dimensions. Candidates excluded by the cap are not deferred into an unbounded backlog; their skipped outcomes and reasons are audited. Candidates selected within the tenant-local cap still enter the shared scheduler/cluster admission layer, where [ADR 0166](./adr-0166-attributable-script-breakers-and-tenant-first-fairness.md) tenant-first fairness precedes priority; catch-up cannot bypass per-tenant or cluster ceilings. A selected catch-up candidate denied there by a tenant or cluster capacity ceiling is terminally skipped for that due candidate and mode-specific `resumeWindowId`: it consumes its deterministic selection slot, records the applicable bounded capacity-denial reason in the candidate audit, creates no firing claim or `scriptEventId`, and is not deferred, retried, backfilled, or reminted in that or a later mode-specific resume window. This candidate-level ceiling gate is distinct from later handler-scoped Table 3 decisions: a per-script quota or materialized sandbox/dry-run capacity denial follows that table under the identity established at its stage, including any firing claim, `scriptEventId`, or work item already created, and is not reminted as catch-up. This terminal skip does not suppress the schedule's next ordinary future occurrence. @@ -75,7 +75,7 @@ else: else resumeTick + intervalTicks - remainder ``` -During a version transition, due state may be carried forward only when `scheduleDefinitionId`, resolved `playableStateScope`, and `scheduleSemanticsHash` match. The replacement version-owned schedule row must be created or confirmed before the prior row is retired, as one atomic durable reconciliation or a resumable idempotent operation keyed by `controlPlaneRequestId`. +During a version transition, due state may be carried forward only when `scheduleDefinitionId`, the exact `(scriptPatchVersion, scriptPinEpoch)` tuple selected for the preserved schedule, exact `playableStateNamespaceId`, resolved `playableStateScope`, and `scheduleSemanticsHash` match. The replacement version-owned schedule row must be created or confirmed before the prior row is retired, as one atomic durable reconciliation or a resumable idempotent operation keyed by `controlPlaneRequestId`. This preserved-schedule calculation maintains cadence and permits an occurrence exactly on the resume boundary. Reload or rollback preservation is distinct from downtime catch-up: preservation chooses the next valid due point for the retained schedule, while downtime recovery separately applies the declared `SKIP_MISSED` or `COALESCE_ONE` policy under a durable resume-window identity. diff --git a/design/architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md b/design/architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md index f5f0bef74c..4e88cad770 100644 --- a/design/architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md +++ b/design/architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md @@ -43,7 +43,9 @@ The platform retains a hard generated-effect depth ceiling with `8` as the share Platform hard ceilings bound every setting. Operators may configure lower environment bounds, and an authored feature may lower its own limits further, but a feature can never exceed the resolved operator or platform bounds. -Every generated child carries an immutable parent identity, immutable root identity, depth equal to `parent.depth + 1`, and a deterministic child ordinal. The immutable root identity is the existing ADR 0069 canonical Game Session root `EffectId` binding to the typed operation, immutable request digest, required participant context, and sealed manifest; this decision introduces no second root authority. The sealed root manifest also persists the resolved platform, operator, and feature depth/count/cost/per-target limits, cost weights, and cost-model version. The ordinal is covered by the request digest. Retry, replay, and reconciliation reuse those persisted resolved values and never re-resolve them. Replay reuses the recorded child identity, lineage, ordinal, and budget accounting; it does not increment them again or mint a replacement identity. +Every generated child carries an immutable parent identity, immutable enclosing-root lineage, depth equal to `parent.depth + 1`, and an owner-defined child ordinal allocated and persisted by the owning contract for replay-stable reuse. This decision does not define command-plan roots or `planOrdinal`; those allocation choices remain pending in [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). The sealed chain manifest also persists the resolved platform, operator, and feature depth/count/cost/per-target limits, cost weights, and cost-model version. Retry, replay, and reconciliation reuse those persisted resolved values and never re-resolve them. Replay reuses the recorded child identity, lineage, ordinal, and budget accounting; it does not increment them again or mint a replacement identity. + +Independent of pending ADR 0183, the owner-scope/root/parent/ordinal mapping to each child `EffectId` is one atomic durable admission record. The owning contract must persist the child `EffectId` and complete mapping before enqueue/apply; retry, replay, and reconciliation read and reuse that mapping and its sealed accounting, while a missing or conflicting mapping fails closed rather than allocating another child identity. Count, cost, per-target, and depth admission are evaluated deterministically for the root chain. When admitting a new child would exceed a limit, only that child is suppressed. A suppressed child is not enqueued or applied, and no already committed parent or earlier child is rolled back. @@ -53,7 +55,7 @@ Every suppression produces durable evidence containing: - root and parent identities; - authored feature, script, and version identity; -- deterministic child ordinal; +- recorded owner-allocated child ordinal, with its persisted replay-stable mapping; - limit reason: depth, count, cost, or per-target; - actual and configured limit values; - required or optional classification; and @@ -71,7 +73,7 @@ Alerting follows the impact class: ## Consequences - Runaway depth, broad fan-out, excessive aggregate cost, and repeated concentration on one target are all bounded. -- Deterministic lineage, ordinals, digests, and accounting make admission and suppression replay-stable. +- Persisted lineage, owner-defined ordinals, digests, and accounting make admission and suppression replay-stable. - Already committed gameplay remains authoritative when a later child is suppressed. - Required and optional classifications make player outcomes and alerts reflect actual gameplay impact. - Durable per-suppression evidence supports precise investigation while bounded metrics avoid cardinality growth. @@ -94,9 +96,9 @@ Rejected because the parent may already be durably committed across authoritativ ## Implementation and Proof Obligations -Implement one canonical generated-chain admission and accounting path with the platform hard depth ceiling, shared depth bootstrap default of `8`, deterministic total count and cost budgets, per-target caps, operator bounds, and feature-lowering rules. Persist immutable parent and root identities, `parent.depth + 1`, digest-covered deterministic ordinals, required or optional classification, and the complete suppression evidence. +Implement one canonical generated-chain admission and accounting path with the platform hard depth ceiling, shared depth bootstrap default of `8`, deterministic total count and cost budgets, per-target caps, operator bounds, and feature-lowering rules. Preserve the persisted enclosing-root identity under its owning contract; command-plan and root allocation details remain pending in ADR 0183. Persist immutable parent and root identities, `parent.depth + 1`, owner-defined child ordinals allocated and persisted for replay-stable reuse, required or optional classification, and the complete suppression evidence. -Prove hard-ceiling and lower-bound resolution; depth, count, cost, and per-target suppression at each boundary; deterministic admission order; cost accounting; immutable lineage and ordinals; request-digest validation; crash and replay without re-incrementing accounting or reminting identity; suppression of only the new child; preservation of committed parents and earlier children; truthful `SUCCESS`, `PARTIAL`, and `FAILED` derivation; complete durable evidence; bounded metric labels and bands; raw-identity exclusion from Prometheus; audit-query retrieval; one-off optional audit behavior; repeated optional designer warnings; prompt required-suppression alerts; and operational paging for sustained aggregate suppression or tick degradation. +Prove hard-ceiling and lower-bound resolution; depth, count, cost, and per-target suppression at each boundary; deterministic admission order; cost accounting; immutable lineage and ordinals; request-digest validation; crash and replay without re-incrementing accounting or reminting identity; suppression of only the new child; preservation of committed parents and earlier children; truthful `SUCCESS`, `PARTIAL`, and `FAILED` derivation; complete durable evidence; bounded metric labels and bands; raw-identity exclusion from Prometheus; audit-query retrieval; one-off optional audit behavior; repeated optional designer warnings; prompt required-suppression alerts; and operational paging for sustained aggregate suppression or tick degradation. The pending [ADR 0183 proposal](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is not proved or accepted by this ADR. The current implementation, configuration resolution, authored classification, observability, alerting, and focused proof are not claimed by this decision. diff --git a/design/architecture/decisions/adr-0077-durable-global-effect-fanout-and-lightweight-idle-ticks.md b/design/architecture/decisions/adr-0077-durable-global-effect-fanout-and-lightweight-idle-ticks.md index 778f578d81..c7d8e3fcf6 100644 --- a/design/architecture/decisions/adr-0077-durable-global-effect-fanout-and-lightweight-idle-ticks.md +++ b/design/architecture/decisions/adr-0077-durable-global-effect-fanout-and-lightweight-idle-ticks.md @@ -41,6 +41,8 @@ Every global or multi-region effect first creates one durable parent identity. A Fan-out creates an idempotent durable child or injection row for every affected region before publishing any wake signal for that region. The parent and children expose pending, injected, terminal, and feature-specific outcome information sufficient to show partial injection. Game Session owns fan-out reconciliation. A feature may not casually assign another durable coordinator: any transfer must follow [ADR 0057](./adr-0057-game-session-owned-reconciliation-with-isolated-workers.md)'s complete authority-transfer model and a new accepted ADR defining the new owner's ledger/backlog, frozen participant set, retry/reconciliation, outcome, audit, retention, and worker controls. The owner retries missing injections, reconciles duplicate attempts to the same child identity, and derives the visible parent outcome. +The owner-defined child ordinal and durable owner-scope/root/parent/ordinal-to-child-`EffectId` admission mapping are accepted target contract under [ADR 0069](./adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md) and [ADR 0075](./adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md). Only the exact ordinal scalar format and any additional allocator mechanics or manifest schema remain unresolved proposal-only details in [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); that proposal does not change the accepted mapping or establish implementation. + Redis markers, notifications, or equivalent wake signals are disposable latency hints. Losing a hint cannot erase a child, and duplicating one cannot create another logical regional effect. Each child enters the target region's ordinary durable inbound-effect path and remains subject to that region's lease, executor fence, epoch checks, lane budgets, and idempotency rules. Global effect admission has a bounded global outstanding-work cap and explicit backpressure. Within that capacity, per-region child admission is deterministic and fair so a hot region or large fan-out cannot indefinitely exclude another eligible region. Rejected, delayed, or terminalized children remain visible on the durable parent rather than disappearing behind wake delivery. diff --git a/design/architecture/decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md b/design/architecture/decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md index 8369afa4c3..8cb3658652 100644 --- a/design/architecture/decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md +++ b/design/architecture/decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md @@ -51,7 +51,7 @@ Workflow run IDs, process or JVM execution IDs, retry-attempt IDs, and message o ### Current Automation Adopter Mapping -The Temporal mapping for `script-patch-readiness` is `workflowFamily=script-patch-readiness`, `tenantId=`, `scopeKey=script-patch-version`, and `businessKey=`, yielding `workflowId=script-patch-readiness::script-patch-version:`. Each readiness `onLoad` step uses the stable `onLoad` step name and the `FORWARD` execution role. Its deterministic occurrence key is the canonical ordered serialization of the complete applicable handler-scoped tenant-readiness Trigger Identity: ``. The optional plugin fields are included exactly when applicable and remain absent otherwise; `scriptId` and, for a plugin handler, `bindingId` identify the resolved handler occurrence, so no attempt, delivery, worker, or runtime ordinal participates. +The Temporal mapping for `script-patch-readiness` is `workflowFamily=script-patch-readiness`, `tenantId=`, `scopeKey=script-patch-version`, and `businessKey=`, yielding `workflowId=script-patch-readiness::script-patch-version:`. Each readiness `onLoad` step uses the stable `onLoad` step name and the `FORWARD` execution role. Its deterministic occurrence key is the canonical ordered serialization of the complete applicable embedded-script-only tenant-readiness Trigger Identity: ``. `pluginId`, `pluginVersionId`, and `bindingId` are absent and not applicable because linked-plugin bindings do not participate in tenant-readiness `onLoad`; plugin initialization remains in the independently versioned, instance-scoped plugin lifecycle. No attempt, delivery, worker, or runtime ordinal participates. The immutable request digest covers those admitted identity fields plus immutable handler descriptor content/version. Runtime-only game, playable-state, region, epoch, and entity fields are absent. Adopter proof must show that the same complete guard and digest replays the recorded readiness step across Temporal run replacement without repeating its logical effect, while the same guard with any different digest fails closed without execution or false replay. diff --git a/design/architecture/decisions/adr-0091-class-specific-script-timer-clocks-and-recovery.md b/design/architecture/decisions/adr-0091-class-specific-script-timer-clocks-and-recovery.md index 9513a7427d..4b0bee93e5 100644 --- a/design/architecture/decisions/adr-0091-class-specific-script-timer-clocks-and-recovery.md +++ b/design/architecture/decisions/adr-0091-class-specific-script-timer-clocks-and-recovery.md @@ -47,11 +47,11 @@ Durable recurring schedules declare exactly one missed-firing policy: - `SKIP_MISSED` emits no synthetic firing for missed boundaries. - `COALESCE_ONE` may emit at most one synthetic firing for one logical schedule in a durable resume window. -One durable, mode-scoped resume-window identity covers the complete recovery attempt across repeated scans or progress observations: live and dry-run/test recovery use separate windows and separate caps, with `isDryRun` included in the window identity and every candidate-selection, firing-claim, candidate-audit, and proof comparison. Each window also binds the exact `(scriptPatchVersion, scriptPinEpoch)` as immutable execution-fence evidence without adding the pin tuple to `resumeWindowId`, and at creation freezes the effective numeric tenant-local cap plus the selection-policy revision that defines grouping, ordering, round-robin passes, and tie breaks. Repeated observations, retries, and takeovers reuse those frozen values unchanged and cannot remint another catch-up firing for the same schedule and window; a cap or policy change applies only to a later window after the current one reaches `COMPLETE`. The deterministic fair tenant-local cap applies within each mode-specific resume window, which is already scoped to one tenant, and selects coalesced candidates across complete stable schedule-instance identities; cap-excluded candidates are dropped with bounded audit and metrics under that window's frozen policy rather than deferred into an unbounded backlog. Selected candidates still enter the shared scheduler/cluster admission layer, where [ADR 0166](./adr-0166-attributable-script-breakers-and-tenant-first-fairness.md) tenant-first fairness precedes priority; catch-up cannot bypass per-tenant or cluster ceilings. A selected candidate denied by a tenant or cluster capacity ceiling is terminally skipped under the same due-candidate, `isDryRun`, and `resumeWindowId` identity with bounded audit, consumes its deterministic selection slot, creates no firing claim or `scriptEventId`, and is never deferred, retried, backfilled, or reminted as catch-up. Its next ordinary future cadence remains eligible. +One durable, mode-scoped resume-window identity covers the complete recovery attempt across repeated scans or progress observations: live and dry-run/test recovery use separate windows and separate caps, with `isDryRun` included in the window identity and every candidate-selection, firing-claim, candidate-audit, and proof comparison. The authoritative `playableStateNamespaceId` is part of the due and resume-window identity; server-derived `playableStateScope` remains immutable policy/routing/authorization/migration-fence evidence, is exact-validated alongside that identity, and is not a uniqueness discriminator, as defined by the [normative Trigger Identity contract](../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) and [Timer Resume Rule](../system-architecture-scripting-scheduler-and-timers.md#timer-resume-rule-normative). A stale or mismatched presented scope fails closed for reuse until authoritative evidence is reconciled and exact validation succeeds. Only reconciled matching scope with unchanged authority may reuse the existing namespace-keyed identity; an authority-proven scope transition starts a new playable-state lifecycle and namespace. Each window also binds the exact `(scriptPatchVersion, scriptPinEpoch)` as immutable execution-fence evidence without adding the pin tuple to `resumeWindowId`, and at creation freezes the effective numeric tenant-local cap plus the selection-policy revision that defines grouping, ordering, round-robin passes, and tie breaks. Repeated observations, retries, and takeovers reuse those frozen values unchanged and cannot remint another catch-up firing for the same schedule and window; a cap or policy change applies only to a later window after the current one reaches `COMPLETE`. The deterministic fair tenant-local cap applies within each mode-specific resume window, which is already scoped to one tenant, and selects coalesced candidates across complete stable schedule-instance identities; cap-excluded candidates are dropped with bounded audit and metrics under that window's frozen policy rather than deferred into an unbounded backlog. Selected candidates still enter the shared scheduler/cluster admission layer, where [ADR 0166](./adr-0166-attributable-script-breakers-and-tenant-first-fairness.md) tenant-first fairness precedes priority; catch-up cannot bypass per-tenant or cluster ceilings. A selected candidate denied by a tenant or cluster capacity ceiling is terminally skipped under the same due-candidate, `isDryRun`, and `resumeWindowId` identity with bounded audit, consumes its deterministic selection slot, creates no firing claim or `scriptEventId`, and is never deferred, retried, backfilled, or reminted as catch-up. Its next ordinary future cadence remains eligible. Every exact script-pin selection change is a resume-window transition, including a same-patch repin that advances `scriptPinEpoch`, even when the runtime region and region epoch are unchanged. Before any new exact-pin timer admission, durable reconciliation must move every prior mode-specific `OPEN` window for the affected scope out of `OPEN`, fence its claims to the prior exact pin and `resumeWindowId`, and preserve those claims and candidate audits for settlement under their original identities. They cannot consume the next window's cap or be rewritten for the target pin. After the target exact `(scriptPatchVersion, scriptPinEpoch)` and its schedules reconcile, a still-required catch-up episode allocates the next monotonic `resumeGeneration` independently for each mode and therefore a distinct mode-specific `resumeWindowId`; retries of this transition are idempotent under the initiating `controlPlaneRequestId`. -Preserved schedules across reload, rollback, or an allowed owner-version transition use the canonical modulo resume formula. If the previous due point is at or after the resume point it is retained. If the resume point lands exactly on a later cadence boundary, the schedule fires at that boundary at most once under the durable schedule-instance plus resume-window identity; otherwise it advances to the first cadence boundary strictly after resume. Version and runtime-scope fencing remains part of the due identity. +Preserved schedules across reload, rollback, or an allowed owner-version transition use the canonical modulo resume formula. If the previous due point is at or after the resume point it is retained. If the resume point lands exactly on a later cadence boundary, the schedule fires at that boundary at most once under the durable schedule-instance plus tagged due-point identity, adding `resumeWindowId` only when `triggerMode=CATCH_UP`. Otherwise, it advances to the first cadence boundary strictly after resume. The exact `(scriptPatchVersion, scriptPinEpoch)` tuple and `playableStateNamespaceId` remain part of the due identity, while runtime scope remains separately captured and exact-validated as fence evidence. The lack of an eventual-execution guarantee applies to each best-effort recurring firing. It does not mean that the recurring schedule disappears: after recovery, future eligible boundaries continue under the preserved cadence unless the schedule is removed, disabled, fenced, or terminally invalid. diff --git a/design/architecture/decisions/adr-0170-fenced-command-forwarding-and-authoritative-region-transition.md b/design/architecture/decisions/adr-0170-fenced-command-forwarding-and-authoritative-region-transition.md index 7b7c826e8f..09a5ade09b 100644 --- a/design/architecture/decisions/adr-0170-fenced-command-forwarding-and-authoritative-region-transition.md +++ b/design/architecture/decisions/adr-0170-fenced-command-forwarding-and-authoritative-region-transition.md @@ -31,7 +31,7 @@ ADR 0011 correctly separates session front-end socket ownership from lease-owner A Game Session front-end owns the edge-facing socket, connection-local protocol state, bounded input/output queues, and presentation delivery. The current fenced lease owner for a target region is the only Game Session executor allowed to admit and mutate region-scoped tick work. -The front-end resolves an owner through a directory or lease projection and forwards a request carrying complete gameplay scope, `commandId`, target region, expected executor fence, session identity, front-end generation, and `sessionSequence`. The directory is a routing hint, not authority. The receiving executor validates current ownership and fence at admission and rejects stale or missing authority. +The front-end resolves an owner through a directory or lease projection and forwards a request carrying complete gameplay scope: `tenantId`, `gameInstanceId`, `playableStateNamespaceId`, and separately validated server-derived `playableStateScope`; it also carries `commandId`, target region, expected executor fence, session identity, front-end generation, and `sessionSequence`. The namespace is the durable gameplay identity dimension; scope is separately validated routing/authorization/migration-fence evidence and is not a uniqueness key. The directory is a routing hint, not authority. The receiving executor validates current ownership and fence at admission and rejects stale or missing authority. `sessionSequence` preserves FIFO for commands from one live connection generation. It is not a dedupe key, effect identity, transaction fence, or cross-connection global order. `commandId`, effect identity, and owning domain request identities provide idempotency and ambiguous-result reconciliation. A stale-owner rejection before admission may refresh routing and retry the same logical identity; an ambiguous response never creates a new identity and is reconciled through the authoritative command-status surface. diff --git a/design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md b/design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md new file mode 100644 index 0000000000..432a1f791c --- /dev/null +++ b/design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md @@ -0,0 +1,123 @@ +# ADR 0183: Deterministic Command-Plan and Generated-Child EffectId Allocation + +## Status + +Proposed - Pending Human Review + +## Implementation Status + +All allocation requirements in this proposal are pending and do not define current target state or accepted implementation requirements. ADR 0069 accepts persisted mutation identity and digest-bound replay, together with evidence-qualified terminal outcomes; it does not select deterministic command-plan ordering, `planOrdinal`, a command-root owner or key, or an ordered plan manifest/allocation binding. No implementation or proof may treat this proposal as approved before human review. + +The move from the conflicting draft number ADR 0182 to ADR 0183 is mechanical preservation only. It neither accepts this allocator decision nor authorizes proposal-dependent implementation; independently authoritative effect and replay obligations continue to apply on their own authority. + +## Decision Record + +- Human review status: Pending +- Human review date: Not yet reviewed +- Human review disposition: Pending +- Review source: `AI-AUTHORED-PENDING` +- Decision date: 2026-08-31 +- Decision key: `TICK-20` +- Primary capability: `GR-1.2` effect execution and reconciliation +- Affected capabilities: `GR-1.4`, `GR-4.1`, `AS-1.2`, `AS-1.4`, `SF-1.4`, `SF-2.3`, `PO-4.2` +- Decision owner: FireMUD human product and architecture owner +- Consultation: AI-authored proposal requiring explicit human review of identity format, persistence, ownership, compatibility, security, and operational proof + +## Context + +[ADR 0069](./adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md) establishes the at-least-once effect, persisted mutation identity, immutable request-digest, replay, and terminal-outcome rules. It does not select command-plan ordering, `planOrdinal`, a command-root allocation owner or key, or a plan manifest/allocation binding. This proposal presents those command-root choices alongside generated-child and fan-out allocation. It also proposes an exact scalar format, versioned canonical serialization, and atomic manifest/allocation behavior. The current implementation derives effect IDs from batch or effect-key material and exposes narrower service-local replay tables. Those paths are implementation gaps and cannot determine the pending design by inference. + +Generated chains and global fan-out need an identity that survives retries, crashes, replay, runtime replacement, and reconciliation without turning semantic fields into an ID. This proposal considers a durable semantic command plan, stable `planOrdinal`, and command-root binding, as well as generated-child and fan-out allocation. Candidate suppression must remain auditable without inventing an ID for work that never entered execution. + +This proposal records design options for command-plan ordering and `planOrdinal`, command-root identity/allocation owner and key, exact `EffectId` scalar format, versioned canonical serialization, additional allocator mechanics, command-plan/manifest binding, and atomic allocation; these remain pending human approval. Separately, [ADR 0069](./adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), [ADR 0075](./adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md), and [ADR 0077](./adr-0077-durable-global-effect-fanout-and-lightweight-idle-ticks.md) establish the accepted owner-defined child ordinal and durable owner-scope/root/parent/ordinal-to-child-`EffectId` mapping. Those child-identity requirements remain target contract independently of this proposal; ADR 0183 does not replace them or make its additional format, allocator, or manifest choices current. The independently accepted identity, replay, and terminal-outcome rules of ADR 0069 also continue to apply. + +## Decision + +Every clause in this Decision section is a proposal, conditional on human acceptance. In particular, the exact UUIDv7 scalar format and the additional command-plan, candidate-manifest, allocator, and fan-out-manifest mechanisms below do not extend the independently accepted owner-defined child ordinal and durable owner-scope/root/parent/ordinal-to-child-`EffectId` mapping in ADR 0069, ADR 0075, and ADR 0077. + +### Proposed scalar identity and allocation authority + +If accepted, this proposal would define the scalar `EffectId` as opaque, lowercase, hyphenated UUIDv7 text of exactly 36 characters. Producers and participants would treat it as an opaque scalar and would not derive it from command text, batch IDs, effect keys, participant fields, ordinals, operation names, targets, or mutable payloads. This exact scalar format is not an accepted cross-service requirement today. + +If accepted, Game Session would own command-root allocation, while the owner of a generated child, non-command root, or remote/fan-out leg would own its corresponding allocation boundary. Each boundary would allocate once, durably persist the value, and atomically bind it to the complete immutable owner scope, operation, exact target where applicable, request digest, enclosing root, parent, and stable ordinal. Insert-if-absent uniqueness would cover the logical mapping and scalar claim. A collision or conflicting binding would fail closed without reminting or substituting an ID. + +Under this proposal, a command root's enclosing root would be its own persisted `EffectId`, and its parent would be explicitly absent (`null`). Its first allocation would durably bind that root mapping; retry and replay would reuse the same scalar and binding. Participants would receive the persisted mutation identity for their guard, ledger, response, and terminal outcome. The enclosing root would remain lineage and reconciliation context for a child without replacing its identity or collapsing siblings. A post-abandon re-drive would receive a new explicitly linked identity under its own admission contract. + +### Proposed command-root serialization refinements + +The proposal assigns each logical command root a stable `planOrdinal` in semantic order and binds an opaque root `EffectId` to a frozen command/runtime context and ordered plan manifest. It further proposes an explicit manifest schema version, registered canonical serialization identifier, canonical bytes, and serialized ordered logical operations and request/runtime/namespace binding. These command-plan, ordinal, and root-allocation choices are all pending; they are not requirements of ADR 0069. Under this proposed model, a zero-effect plan allocates neither an ordinal nor a root `EffectId`. + +The proposed durable allocation row is unique on `(tenantId, gameInstanceId, commandId, planOrdinal)` and binds the frozen command context and ordered plan-manifest digest. This proposal also binds the manifest schema version, serializer, canonical bytes, and exact root scalar claim, requiring exact matches on replay. Unknown, duplicate, ambiguous, noncanonical, or changed order/manifest evidence fails before staging or side effects if this design is accepted. Automation handoff identity would map exactly to one durable target command before this command-root allocation; trigger and correlation identities would not be allocation inputs. + +### Proposed generated-child candidates and suppression + +If accepted, the owning chain boundary would seal a versioned child-candidate manifest before enqueue or apply. Each candidate would record root/parent lineage, stable ordinal, typed operation, exact target, depth, required/optional classification, immutable request or plan digest, and resolved count/cost/per-target budget revisions. The manifest schema version, serializer, canonical digest, and ordered candidate set would be immutable replay evidence. + +Under this proposed mechanism, candidates would receive no child `EffectId` at manifest creation. For an admitted candidate, one serializable transaction or explicitly equivalent locked multi-key atomic boundary would validate the manifest, reserve the ordinal, check and charge only the admitted candidate's count/cost/per-target budgets, allocate and persist the scalar mapping with the manifest schema version, registered serializer identifier, and canonical digest (or an immutable reference resolving to those fields), then commit the mapping before enqueue/apply. Replay and retry would exact-compare that schema version, serializer, digest/reference, candidate ordinal, and other immutable bindings before reusing the mapping or enqueueing work. Concurrent sibling admission would not double-charge, reserve two mappings for one ordinal, or leave partial budget, ordinal, mapping, or suppression state. Exact retries would reuse the committed mapping. + +If accepted, an over-limit candidate would be suppressed without a child ID. The same atomic boundary would record immutable ID-free suppression evidence containing root/parent identity, the sealed candidate-manifest schema/serializer/digest, candidate ordinal, operation and exact target, feature/script/version, required/optional classification, reason, configured and actual limits, and outcome. Suppressed candidates would not be enqueued or applied; committed parents and earlier children would remain authoritative. + +### Proposed global fan-out and regional child binding + +If accepted, the fan-out parent would freeze the affected region set and topology generation at acceptance. Each regional child or leg would be one member of that sealed set and receive its own one-time allocated child `EffectId` before its wake signal. The durable child row would bind root and parent lineage, child ordinal, exact operation, target region/aggregate, request digest, and the proposed child-manifest schema, registered serializer, canonical bytes/digest, and expected-participant projection. It would retain the root binding needed for reconciliation. + +Under this proposal, the child scalar and all binding fields would be persisted before wake delivery. Retry, duplicate wake, late result, and reconciliation would look up the same row and scalar. A missing, extra, duplicate, reordered, schema/serializer/digest-conflicting, target-conflicting, ordinal-conflicting, or identity-conflicting child would fail closed. Wake markers would remain disposable latency hints and could not create, expand, or replace a child. + +## Rationale + +The proposed exact scalar format makes wire and storage compatibility testable while keeping identity opaque. Durable allocation separates identity from semantic derivation and allows a participant or coordinator to prove that a replay is the same logical mutation. The proposed versioned canonical manifests make plan and fan-out interpretation stable across deployments, while ID-free suppression evidence prevents rejected work from appearing to have executed. The proposed serializable allocation/budget boundary preserves chain accounting under concurrency, and a frozen fan-out set prevents topology changes from creating new work during recovery. + +## Alternatives Considered + +### Derive IDs from command, batch, ordinal, or payload fields + +This proposal rejects deriving IDs from mutable or replay-order-dependent fields because they can collide, change identity, or allow a participant to invent a value. In the proposed design, derivation would also make fan-out and generated-child reuse depend on semantics rather than durable allocation. + +### Permit UUID/ULID producer choice without an exact scalar contract + +This proposal rejects caller-selected UUID/ULID formats for its proposed cross-service boundary because callers could disagree on casing, width, textual form, or parser behavior. Its pending candidate is lowercase hyphenated UUIDv7 text with opaque semantics; this is not the accepted canonical format. + +### Allocate at manifest creation for every candidate + +This proposal rejects allocating at manifest creation for every candidate because suppressed work would acquire an execution identity and could be mistaken for an admitted mutation. Under the proposal, allocation would belong to the atomic admission boundary after budget and ordinal checks. + +### Use a best-effort global fan-out allocator or wake message identity + +This proposal rejects a best-effort global fan-out allocator or wake message identity because notifications can be lost or duplicated and cannot own durable correctness. If accepted, the parent-owned child row and sealed manifest binding would be authoritative. + +## Consequences + +- If accepted, the command-plan, `planOrdinal`, command-root ownership/key/binding, and manifest-digest requirements proposed here would join ADR 0069's identity, replay, and terminal-outcome rules. +- Each generated-effect or fan-out owner would need the proposed durable allocation rows, manifest bindings, and conflict-safe atomic replay behavior if this proposal is accepted. +- If accepted, this proposal would require root and child manifests to use registered schema versions and canonical serializers whose bytes and digests are stable across supported readers. +- If accepted, chain admission would use a serializable or explicitly equivalent atomic boundary and retain ID-free suppression evidence. +- The proposed 36-character scalar appears to fit existing string protobuf and database fields. Current ID derivation and replay paths are implementation facts; they do not accept or prove the pending scalar, allocator, or manifest choices. +- If accepted, participants, ledgers, coordinators, and operational reconciliation would carry both mutation identity and enclosing-root lineage where applicable. +- If accepted, adoption would be a breaking target convergence for identity allocation; compatibility shims would not preserve semantic derivation or silently accept conflicting formats. + +## Reversibility and Revisit Triggers + +Before acceptance, human review may change the proposed command-plan ordering, `planOrdinal`, root owner/key/binding, scalar format, generated-child/fan-out ownership, or serialization boundary without a migration obligation. After acceptance and persisted use, changing the scalar or canonical serialization requires a versioned migration and explicit old/new binding and replay policy; it must not reinterpret existing IDs. Revisit UUIDv7 only if a reviewed cross-service identity standard provides equal exact textual compatibility, opaque semantics, collision handling, and operational proof. + +## Security and Privacy + +If accepted, opaque UUIDv7 values would not encode tenant, account, character, target, operation, or authorization meaning. Exact scope, namespace, runtime-fence, target, and request-digest validation would remain separate evidence. Collision, parser, schema, digest, or binding conflicts would fail closed before domain mutation. Raw IDs would remain durable audit/reconciliation fields but be excluded from bounded metric labels and player-facing messages. Suppression and replay evidence would not expose unauthorized target or tenant data across scope boundaries. + +## Operations and Recovery + +If accepted, Game Session or the owning allocation boundary would expose durable allocation, collision, manifest-mismatch, budget-suppression, fan-out-injection, and reconciliation outcomes with bounded reason labels. Recovery would retry the same persisted mapping and manifest; it would not regenerate an ID or expand a frozen candidate/region set from current topology. An unresolved binding, partial participant set, or uncertain old-epoch effect would remain reconciliation-required and non-terminal under the original mutation identity until the accepted evidence policy permits terminalization. + +## Implementation and Proof Obligations + +Implementation and focused proof must cover: + +- if accepted, lowercase, hyphenated, exactly 36-character UUIDv7 scalar validation and opaque treatment at every supported wire/storage boundary; +- if accepted, command-plan ordering; zero-, one-, and multi-root plans; `planOrdinal`; command-root owner/key/binding; ordered manifest digest; mismatch rejection; one-time scalar claims; insert-if-absent uniqueness; collision/conflict failure; crash recovery; concurrent allocation races; and exact replay/reconciliation reuse; +- if accepted, the proposed root manifest schema version, serializer, canonical bytes, exact scalar claim, and their mismatch rejection; +- if accepted, child-candidate schema version/serializer/digest, candidate ordering, depth and budget revisions, serializable sibling admission, no double charge, and no partial commit; +- if accepted, ID-free suppression evidence proving no enqueue/apply and preserving committed parent/earlier-child outcomes; +- if accepted, fan-out frozen region/topology set, exact child ordinal and target binding, child-manifest schema/serializer/digest, request digest, pre-wake durability, duplicate wake, late result, and topology-conflict handling; +- if accepted, participant guard, ledger, coordinator, and terminal projection exactness across root/child identity and enclosing-root lineage; and +- if accepted, current protobuf/database compatibility, rejected blank/invalid IDs, migration/replay behavior, bounded observability, tenant isolation, and old-epoch recovery. + +The focused proof must be added only after human acceptance of this proposal and must include the existing [tick failure and operations proof obligations](../system-architecture-tick-failures-and-operations.md), [transaction contract](../system-architecture-transactions.md), [tick execution flows](../system-architecture-tick-execution-flows.md), [tick incident runbook](../system-architecture-tick-incident-runbook.md), [Entity Management API contract](../microservices/entity-management-service/api-contracts.md), and [gameplay implementation tracker](../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md). diff --git a/design/architecture/infrastructure/deployment-environments.md b/design/architecture/infrastructure/deployment-environments.md index e04fdcb902..781efc69a9 100644 --- a/design/architecture/infrastructure/deployment-environments.md +++ b/design/architecture/infrastructure/deployment-environments.md @@ -192,7 +192,7 @@ In production, FireMUD is deployed into Kubernetes (e.g., AWS EKS, Google GKE, o - Redis is deployed as **two logical roles** in both Kubernetes and Docker Compose (see [Redis Architecture](../system-architecture-redis.md)): - A **Coordination Redis** deployment runs as a clustered StatefulSet with automatic failover in production and smaller clusters in non-production. It uses AOF, persistent volumes, and `noeviction` in player-facing environments to preserve volatile coordination state across normal rollouts and pod restarts within the documented tail-loss envelope; Redis is not the authoritative recovery or audit log. AOF, persistent volumes, and `noeviction` alone are insufficient for player-facing replay safety: the deployment must also satisfy the [ADR 0029 replay-readiness contract](../decisions/adr-0029-single-use-gameplay-connect-token-carriage.md), including Redis 7.2+, ACL isolation, reserved capacity and an admission-readiness threshold, atomic marker consumption, configured `WAITAOF` local/replica acknowledgement thresholds, and a shared reset/uncertain-durability quarantine fence. A profile that cannot prove those controls is not eligible to admit new player handshakes. - A **Cache/Rate-Limit Redis** deployment runs as a separate StatefulSet or Deployment tuned for eviction-driven workloads (for example using `allkeys-lru`), with sizing independent of Coordination Redis. It may use lighter durability (RDB snapshots or even ephemeral volumes) because its keys are best-effort and recomputable. - - Local development runs **two Redis containers** under Docker Compose with the same role split: a Coordination Redis service and a Cache/Rate-Limit Redis service, with Coordination Redis durable via AOF and Cache/Rate-Limit Redis configured for eviction-driven workloads. When operators want to **reset** coordination state (for example, to test reset-tolerant behavior or remediate mis-keyed data), they use the explicit coordination-reset Job or script described in the Redis Operations runbook rather than relying on Helm to clear data automatically on every deploy. A reset that affects connect-token replay state must advance `replayAdmissionFence`, record shared `QUARANTINED` readiness, reject affected tokens for the complete ADR 0029 barrier, and reopen only after the disposable-marker plus configured `WAITAOF` proof succeeds; wiping the AOF volume alone never restores admission readiness. +- Local development runs **two Redis containers** under Docker Compose with the same role split: a Coordination Redis service and a Cache/Rate-Limit Redis service, with Coordination Redis durable via AOF and Cache/Rate-Limit Redis configured for eviction-driven workloads. The existing `redis-coord-wipe-aof` Helm hook and `restore-redis-aof.sh` helper are isolated local/test fixture tooling only; neither is a supported Coordination Redis reset path for shared or player-facing environments, and neither proves the durable maintenance lock, fencing, Account projection repair, replay quarantine, or post-reset verification required by the owner contract. The target coordination-maintenance reset sequence is unavailable today. Current operators must preserve evidence, keep the affected scope fenced, use the shipped pause/status and read-only inspection surfaces, and escalate through the [Current Operator Fallback](../system-architecture-redis-reset-and-recovery.md#current-operator-fallback). A future reset that affects connect-token replay state must advance `replayAdmissionFence`, record shared `QUARANTINED` readiness, reject affected tokens for the complete ADR 0029 barrier, and reopen only after the disposable-marker plus configured `WAITAOF` proof succeeds; wiping the AOF volume alone never restores admission readiness. - PostgreSQL is deployed within the cluster (or provided as a managed database service) to store persistent domain data. See [System Architecture Overview](../system-architecture-overview.md#data-and-state-management). Backup and restore procedures are outlined in [Backup & Disaster Recovery](../system-architecture-backup-recovery.md) and the [operations recovery index](../../operations/README.md#recovery). - **Hosted dev/demo Kubernetes environments** use [`dev-demo.yml`](../../../.github/workflows/dev-demo.yml) for the fixed environment and [`preview.yml`](../../../.github/workflows/preview.yml) for credential-free per-PR rendering. The trusted default-branch [`hosted-identity-request.yml`](../../../.github/workflows/hosted-identity-request.yml) validates the render artifact and deploys the per-PR runtime. These workflows use the full-stack chart under [`k8s/helm/firemud`](../../../k8s/helm/firemud) with environment-specific example values and deployment metadata. These environments are intentionally excluded from the staging → production promotion chain and must not emit attestation artifacts. - **Staging and production** deployments are applied from a secure operator environment using **Kustomize overlays** (for example `kubectl apply -k k8s/overlays/stage` and `kubectl apply -k k8s/overlays/prod`). Immutable image digest changes for these overlays are the promotion model, and the player-facing bootstrap contract is now intentionally expressed through environment-owned bindings plus preflight rather than through checked-in placeholder Secret content. See [Deployment Runbook](../system-architecture-deployment-runbook.md) and [CI/CD Pipeline](../system-architecture-cicd.md#promotion--rollback-model). diff --git a/design/architecture/microservices/automation-scripting-service/README.md b/design/architecture/microservices/automation-scripting-service/README.md index 9dd4f1f23e..7a76c040ad 100644 --- a/design/architecture/microservices/automation-scripting-service/README.md +++ b/design/architecture/microservices/automation-scripting-service/README.md @@ -42,7 +42,7 @@ The current Automation pin projection and wire contract now retain the observed - Faction reputation influences NPC aggression states. NPCs may become `FLEEING` or `SURRENDERED` when low on health or morale, allowing players to resolve encounters non-lethally. - Web UI for creating and testing scripts using a component-based DSL. - Advanced AI modules support formations, squads, and complex behaviors. -- Bounded procedural encounter generation is present: the current population hook invokes seeded encounter generation, but its result is discarded; it does not spawn or persist NPCs/loot or emit tick-driven commands. Full World-owned generation and tick handoff remain target work; see [Automation and Scheduler Runtime tracker](../../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#active-gaps). Scripts do not persist world topology or directly mutate World Management instance rows. +- Procedural population is not a live NPC/loot handoff: the current population hook calls seeded `PveEncounterService.generateEvent(...)` for each generated room, selecting an event from small in-memory region lists and discarding the returned event. It does not spawn or persist NPCs/loot or emit tick-driven commands. Full World-owned generation and tick handoff remain target work; see [Automation and Scheduler Runtime tracker](../../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#active-gaps). Scripts do not persist world topology or directly mutate World Management instance rows. - `ScriptQuotaService` enforces fairness quotas and per-script resource limits. ## Document Map diff --git a/design/architecture/microservices/automation-scripting-service/api-contracts.md b/design/architecture/microservices/automation-scripting-service/api-contracts.md index 70d6c2465f..6839cc3dc8 100644 --- a/design/architecture/microservices/automation-scripting-service/api-contracts.md +++ b/design/architecture/microservices/automation-scripting-service/api-contracts.md @@ -85,8 +85,8 @@ On the current public Automation & Scripting API, `workItemId` and `workItemIds` Domain services such as Game Session and Game Logic deliver automation events through event-ingress RPCs (for example `TriggerScriptEvent`). The required identity fields, endpoint ownership, and audit behavior are defined in the [normative scripting contract tables](../../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields); the following list describes the service-local wire envelope: -- `tenantId`, `gameInstanceId`, `regionId`, and `entityId` for the target runtime context. -- resolved `playableStateScope` for gameplay-originated events so shared versus isolated realm state stays explicit through durable trigger identity, timer follow-up work, and operator read models. +- The current `TriggerScriptEventRequest` carries `tenantId`, `gameInstanceId`, `regionId`, and `entityId` when applicable. `playableStateNamespaceId` is part of the target runtime identity but is absent from the current proto; see the canonical [normative scripting contract tables](../../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) for target identity requirements. +- `playableStateScope` is carried for gameplay-originated events and persisted in ingress and work records as policy/routing/authorization/migration-fence evidence. Current ingress compares the request scope with runtime-owner state only when both values are present, so this evidence does not prove the complete target namespace/scope tuple or owner binding. It stays explicit for handler/work fencing and operator read models but is excluded from Trigger Identity, timer-follow-up identity, uniqueness, and deduplication keys; see the [normative identity tables](../../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). - `regionEpoch` for gameplay/runtime triggers and scheduler triggers so Trigger Identity is fenced across scoped coordination resets. - `scriptEventId` in the normalized applicable Trigger Identity. Its wire requirement follows the [ingress ownership matrix](../../system-architecture-scripting-normative-contract-tables.md#table-1a-event-ingress-scripteventid-ownership-matrix), and it is not a complete idempotency key by itself. - `isDryRun` so live and dry-run/test traffic are always in separate idempotency namespaces. @@ -240,7 +240,7 @@ Target-state replay claim and scope rules for `ReplayDeadLetteredWorkItems`: - **Current admission implementation boundary:** direct V1 schema changes and focused unit proof cover normalized exact-scope/mode/request identity, length-delimited SHA-256 fingerprints, immutable `APPLIED`/`ALREADY_APPLIED` history, exact retry readback, changed-input conflict, read-only `NOT_FOUND`/`ACKNOWLEDGEMENT_UNAVAILABLE` diagnostics, and response fields. Missing durable history remains fail-closed and is never reconstructed from mutable state. Exact-head hosted CI, Automation service checks, and generic full-stack smoke passed. Hosted `integrationTest` executed against Docker/PostgreSQL and passed, but the hosted logs/artifact do not expose a trustworthy exact test count; the local exact-head integration run discovered 33 tests and skipped all 33 because Docker/Testcontainers was unavailable. Generic full-stack smoke did not exercise admission behavior and is not claimed as admission proof. The separate preview endpoint was unavailable at capacity. Unrelated admission, queue, and workflow gaps remain partial. - `GetAutomationPinConvergence(tenantId, gameInstanceId)` – read-only operator surface for the latest exact pin observation (`observedPinnedScriptPatchVersion`, `observedScriptPinEpoch` as a nullable pair, `lastObservedControlPlaneRequestId` nullable/absent only for a never-pinned semantic `UNPINNED` and atomically associated with that pair, `observedAt`) used as input by admission and scheduler logic, plus freshness flags (`projectionAsOfMs`, `projectionLagMs`, `isProjectionStale`). A stored observation retains its pair and request identity when marked stale. It does not return an admission decision or handler outcome and never replaces the Game Session owner read. Current publication-link readback has the observed patch identity but not its `base_version_id`, which is required for an exact Game Design publication lookup; that link therefore reports `PUBLICATION_SCOPE_UNAVAILABLE` with a message identifying the missing projection field. A genuinely absent `script_patch_version` remains `INVALID_ARGUMENT`. - `GetScriptBreakerStatus`, `ListScriptBreakerEvents`, and `ResetScriptBreaker` use the exact tuple, monotonic breaker revision/sample generation, and evidence contract defined by the control-plane API. A new exact patch/script selection starts `CLOSED`; only the operator-authorized, digest-bound, expected-state/revision reset clears that tuple, advances its sample generation, and makes prior samples history-only, with no automatic half-open state. Current status and immutable reset history retain the bounded reset reason beside actor, request, and validation evidence. Exact retries return the stored reset result; the breaker revision fence serializes concurrent trip/reset attempts, and a trip additionally binds the observed sample generation. These breaker surfaces do not alter `GetScriptPatchStatus` readiness or `GetScriptStatus` pre-DSL work semantics. The current proto/implementation exposes none of them. -- `ListScriptScheduleInstances(tenantId, gameInstanceId, ...)` currently returns the resolved `playableStateScope` used when the schedule row was materialized. Target schedule rows, due candidates and claims, timer-audit rows, and any derived scheduler work/dead-letter/replay evidence additionally retain and expose stable `playableStateNamespaceId` as non-identity evidence, revalidate it with the exact namespace/scope and active-instance/region owner binding on materialization, claim, replay, and readback, and fail closed on missing or mismatched evidence. The current schema, proto, implementation, and dead-letter/replay path do not persist or expose that namespace field. +- `ListScriptScheduleInstances(tenantId, gameInstanceId, ...)` currently returns the resolved `playableStateScope` used when the schedule row was materialized. Target schedule rows, due candidates and claims, timer-audit rows, and any derived scheduler work/dead-letter/replay evidence additionally retain and expose stable `playableStateNamespaceId` as the applicable gameplay/runtime namespace identity component; `playableStateScope` remains separately persisted exact-validated policy/routing/authorization/migration-fence evidence and is excluded from schedule, candidate, firing-claim, event-scope, and handler uniqueness/deduplication. Revalidate both with the active-instance/region owner binding on materialization, claim, replay, and readback, and fail closed on missing or mismatched evidence. The current schema, proto, implementation, and dead-letter/replay path do not persist or expose that namespace field. - `GetPluginStatus(tenantId, gameInstanceId, pluginId)` – **target-state read:** returns plugin runtime state (`ENABLED`, `DISABLED`, `DRAINING`, `RELOADING`, `FAILED`), active and pending version IDs, the current committed `pluginActivationEpoch` and `lifecycleRevision`, the last control-plane request id, the last recorded actor principal for the runtime row, separate failure-rate breaker outputs (`breakerState`, bounded `breakerReason`, monotonic `breakerRevision`, and monotonic `breakerSampleGeneration`) for the exact active version/runtime scope, nullable current breaker-reset evidence including bounded immutable `lastResetReason` distinct from lifecycle `statusReason`, and current policy-check freshness (`lastPolicyCheckedAtMs`, `policyCheckStale`). The current proto/implementation returns the state/version and policy/publication fields but does not persist or expose the target activation epoch/lifecycle revision or breaker/reset outputs. - `ListPluginRuntimeEvents(tenantId, gameInstanceId?, pluginId?, pluginState?, breakerState?, activePluginVersionId?, changedAfterMs?, changedBeforeMs?, limit?)` – **target-state read:** returns append-only instance-scoped plugin lifecycle history for activation, drain, disable, policy-reconcile fail-closed transitions, and breaker trip/reset transitions. Breaker trip rows retain exact active-version, policy/window/threshold/count/sample evidence; reset rows retain actor, bounded immutable `resetReason`, request, validation, and sample-generation evidence; lifecycle rows omit those transition-only fields and use separate lifecycle `statusReason`. The current event proto/implementation has no epoch/revision or breaker/reset evidence and remains a narrower history projection. - `GetPluginPolicyConvergence(tenantId, gameInstanceId?, maxResults?)` – the current read inspects enabled plugin runtime states with an active version, optionally narrows them to one game instance, filters them against the current runtime region/region-epoch scope when that scope is available, and reports publication, signer, or component-policy violations plus freshness. The response has no `pluginActivationEpoch` or `lifecycleRevision` fields and cannot serve as ADR 0119 lifecycle-fence proof. diff --git a/design/architecture/microservices/automation-scripting-service/configuration.md b/design/architecture/microservices/automation-scripting-service/configuration.md index 752b660a3f..c2ccca9f24 100644 --- a/design/architecture/microservices/automation-scripting-service/configuration.md +++ b/design/architecture/microservices/automation-scripting-service/configuration.md @@ -27,7 +27,7 @@ For day-to-day operations, environment variables fall into three broad categorie **Target-state retention and recovery:** [ADR 0107](../../decisions/adr-0107-stage-aware-script-dead-letter-recovery.md) requires that a row advertised as recoverable and all of its stage, manifest, evaluated-output, and child-dispatch evidence form one coherent retention bundle. Age/capacity cleanup or explicit purge may remove the whole bundle when eligible, but must not delete supporting evidence independently while leaving the row advertised recoverable; configuration validation covers settings only, while runtime cleanup and explicit purge fail closed on incoherent retained evidence. Any retained `script_dead_letter_replay_results` row is an unconditional hold on deleting its parent, regardless of the row's age; the age/capacity controls never override that hold. The bounded `SCRIPT_DEAD_LETTER_MAX_AGE_SECONDS` and `SCRIPT_DEAD_LETTER_MAX_ROWS` controls select cleanup candidates rather than guaranteeing deletion of an ineligible bundle or authorizing partial evidence removal; there is no additional numeric floor. [ADR 0110](../../decisions/adr-0110-explicit-opt-in-schedule-continuity-across-script-transitions.md) keeps timer continuity declarations in authored artifact data rather than a service-wide configuration switch: `SCRIPT_TIMER_CATCH_UP_MAX_FIRINGS_PER_RESUME` applies only to interval schedules, while one-shot recovery uses its durable intent/outcome semantics. -These knobs are the authoritative defaults referenced by the scripting architecture docs: +These knobs are the authoritative settings referenced by the scripting architecture docs. Each row distinguishes a live default from a required target-only setting: - publish-time validation and runtime enforcement share `SCRIPT_OUTPUT_MAX_COMMANDS_PER_RUN`, `SCRIPT_OUTPUT_MAX_COMMANDS_PER_ENTITY_PER_TRIGGER`, and `SCRIPT_OUTPUT_MAX_SERIALIZED_WORK_ITEM_BYTES` as the runtime-cap ceilings, while the artifact-pinned cost metadata/digests determine whether a component graph may publish or run; - the durable quota owner records one full-Trigger-Identity handler admission charge and a separate execution-start marker; `SCRIPT_QUOTA_LIMIT` / `SCRIPT_QUOTA_WINDOW_SECONDS` and the live tenant-tier settings are inputs to those decisions. Queued work holds no capacity; execution uses a separately fenced/reclaimable lease, and `PUBLISH_READINESS` `onLoad` work is isolated; @@ -36,7 +36,7 @@ These knobs are the authoritative defaults referenced by the scripting architect - pin and rollout convergence reads use `SCRIPT_PIN_PROJECTION_STALE_THRESHOLD_MS` to derive the public `isProjectionStale` wire field; internal Java projection summaries use `projectionStale` and map it to that public field rather than exposing a second public field or relying on hardcoded local thresholds; - enabled plugin runtime states are rechecked against current publication, signer-revocation, and component-policy metadata using `SCRIPT_PLUGIN_POLICY_RECONCILE_INTERVAL_SECONDS` and `SCRIPT_PLUGIN_POLICY_RECONCILE_BATCH_SIZE`; plugin-trigger ingress fails closed when the last successful policy check is older than `SCRIPT_PLUGIN_POLICY_STALE_THRESHOLD_SECONDS`; - outbox cleanup and diagnosis for `HANDED_OFF`, `CANCELED`, and `DEAD_LETTERED` rows must follow the documented retention knobs above rather than ad hoc cleanup windows; and -- **Target state only:** an owner-gated queue rebuild may define bounded cadence and scan limits for the derived `automation:queue:*` projection; no current queue-rebuild execution or configuration is bound until that owner/serialization gate exists; and +- **Target state only:** an owner-gated queue rebuild may define bounded cadence and scan limits through `SCRIPT_OUTBOX_QUEUE_REBUILD_INTERVAL_SECONDS` and `SCRIPT_OUTBOX_QUEUE_REBUILD_BATCH_SIZE`, and atomically enforce positive pointer TTL/cap settings through `SCRIPT_OUTBOX_QUEUE_POINTER_TTL_SECONDS` and `SCRIPT_OUTBOX_QUEUE_MAX_POINTERS_PER_KEY`; no current queue-rebuild execution or configuration is bound until that owner/serialization gate exists, and the live RPUSH-only path does not enforce those pointer bounds; and - the durable evaluator cadence and claim bounds must follow `SCRIPT_OUTBOX_EXECUTION_INTERVAL_SECONDS` and `SCRIPT_OUTBOX_EXECUTION_BATCH_SIZE` rather than ad hoc polling loops. ## Implementation Status @@ -85,6 +85,8 @@ Current live bindings in the service are narrower than the full target-state scr | `SCRIPT_OUTBOX_TERMINAL_CLEANUP_INTERVAL_SECONDS` | Cleanup sweep interval for terminal outbox rows (`HANDED_OFF`, `CANCELED`, `DEAD_LETTERED`) | `300` | Stable operator knob | | `SCRIPT_OUTBOX_QUEUE_REBUILD_INTERVAL_SECONDS` | Target-state-only cadence for an owner-gated bounded rebuild; no current scheduled rebuild is bound | `60` | Internal implementation detail | | `SCRIPT_OUTBOX_QUEUE_REBUILD_BATCH_SIZE` | Target-state-only maximum durable work items inspected per owner-gated rebuild sweep | `200` | Internal implementation detail | +| `SCRIPT_OUTBOX_QUEUE_POINTER_TTL_SECONDS` | Target liveness TTL for each disposable `automation:queue:*` pointer list; the live RPUSH-only path currently ignores this setting | Required; no default | Target-only, not currently consumed; each environment must provide a validated positive value before adoption | +| `SCRIPT_OUTBOX_QUEUE_MAX_POINTERS_PER_KEY` | Target maximum pointers retained in one disposable `automation:queue:*` list; the live RPUSH-only path currently ignores this setting | Required; no default | Target-only, not currently consumed; each environment must provide a validated positive value before adoption | | `SCRIPT_OUTBOX_EXECUTION_INTERVAL_SECONDS` | Scheduled interval for the durable work-item execution loop that claims and evaluates pending work | `5` | Stable operator knob | | `SCRIPT_OUTBOX_EXECUTION_BATCH_SIZE` | Maximum claimed work items processed per execution sweep | `50` | Stable operator knob | | `SCRIPT_DEAD_LETTER_MAX_ROWS` | Maximum dead-lettered automation work items retained before cleanup | `100000` | Stable operator knob | diff --git a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md index d1b0b47074..0048d2555f 100644 --- a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md +++ b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md @@ -1,6 +1,6 @@ # Automation & Scripting Service Runtime and Data -This document defines the Automation & Scripting Service runtime model, persistence boundaries, reload semantics, Redis usage, and script work-item lifecycle. +This document defines the Automation & Scripting Service runtime model, persistence boundaries, reload semantics, Redis usage, and pre-DSL trigger/evaluated script work-item lifecycle. ## Implementation Status @@ -10,7 +10,9 @@ The unsupported NPC formation REST handlers and OpenAPI paths have been removed. **Target formation boundary:** keep the external public route absent, require exact tenant-bound internal `tenantAdmin` authorization without a global-role override, derive the tenant from that authority, and validate formation plus leader/member NPC ownership against the Entity Management owner read before every mutation/read. A missing or unavailable owner read, tenant/namespace mismatch, or caller-selected cross-tenant identifier fails closed before persistence or disclosure. Negative proof must cover unauthenticated access, tenant A selecting tenant B, and tenant A attaching tenant B's NPC to an otherwise tenant-A formation. The owning [API contract](./api-contracts.md#normative-target-contract) defines the complete target rule. -The current service validates and resolves handlers during admission, persists each admitted handler as pre-DSL `PENDING_EVALUATION` work, and later lets a scheduled executor claim the work and evaluate the sandboxed DSL; it carries only the narrower read-snapshot token field, does not yet seal the complete handler input manifest, and does not persist the separate evaluated-descriptor layer. Admission, runtime projection, schedule rows, and runtime replay now carry the authoritative exact `(scriptPatchVersion, scriptPinEpoch)` pair plus associated owner `controlPlaneRequestId` evidence, compare that captured evidence with owner and observed state, and fail closed on absent, stale, partial, or mismatched evidence. Automation now persists `pluginActivationEpoch` and `lifecycleRevision` in plugin runtime state and captures them on plugin-backed ingress, work, audit, schedule, and handoff rows. Admission and downstream evaluation reject absent or stale captured fence evidence, including same-version re-enable and same-epoch lifecycle changes. A timer due candidate snapshots `pluginId`, `pluginVersionId`, applicable `bindingId`, `pluginActivationEpoch`, and `lifecycleRevision`, then rechecks that snapshot against the schedule row and local plugin-owner state before emission. Durable winning-admission CAS/barrier ordering, retained firing claims, and the final Game Session effect fence remain gaps; this candidate check does not establish complete timer lifecycle-tuple validation. Pending-transition ownership, Game Session fence-install acknowledgement, complete retry/replay/recovery propagation, and final gameplay-effect enforcement remain implementation and proof gaps; the target lifecycle and manifest contracts below remain normative. +The current service validates and resolves handlers during admission, persists each admitted handler as pre-DSL `PENDING_EVALUATION` work, and later lets a scheduled executor claim the work and evaluate the sandboxed DSL; it carries only the narrower read-snapshot token field, does not yet seal the complete handler input manifest, and does not persist the separate evaluated-descriptor layer. For evaluated child commands, Automation commits a deterministic `HANDOFF_IN_FLIGHT` intent in a short local transaction before invoking Game Session with no Automation transaction active, then records a definitive response in a separate local transaction guarded by the work-item version. A dispatch or post-dispatch persistence ambiguity retains the intent for recovery, while a failure before the intent commits performs no RPC and returns a retryable rejection rather than falsely claiming an in-flight dispatch. Each child intent also reacquires the local admission lock and rereads the current admission state before it becomes dispatchable. The service still lacks the durable evaluated descriptor and reconciliation owner needed to resume every ambiguous handoff without re-evaluating the DSL, so the complete crash/restart contract remains unimplemented. + +Admission, runtime projection, schedule rows, and runtime replay now carry the authoritative exact `(scriptPatchVersion, scriptPinEpoch)` pair plus associated owner `controlPlaneRequestId` evidence, compare that captured evidence with owner and observed state, and fail closed on absent, stale, partial, or mismatched evidence. Automation now persists `pluginActivationEpoch` and `lifecycleRevision` in plugin runtime state and captures them on plugin-backed ingress, work, audit, schedule, and handoff rows. Admission and downstream evaluation reject absent or stale captured fence evidence, including same-version re-enable and same-epoch lifecycle changes. A timer due candidate snapshots `pluginId`, `pluginVersionId`, applicable `bindingId`, `pluginActivationEpoch`, and `lifecycleRevision`, then rechecks that snapshot against the schedule row and local plugin-owner state before emission. Durable winning-admission CAS/barrier ordering, retained firing claims, and the final Game Session effect fence remain gaps; this candidate check does not establish complete timer lifecycle-tuple validation. Pending-transition ownership, Game Session fence-install acknowledgement, complete retry/replay/recovery propagation, and final gameplay-effect enforcement remain implementation and proof gaps; the target lifecycle and manifest contracts below remain normative. Plugin lifecycle mutations use immutable request history keyed by `(tenantId, gameInstanceId, pluginId, controlPlaneRequestId)`, with the operation and canonical request fingerprint stored as bound payload. An exact retry returns the recorded result, while reuse for another operation or changed input fails before state, epoch, revision, lifecycle history, schedule, or notification mutation. Fresh same-target activation, already-`DRAINING`, already-`DISABLED`, and never-active `DISABLE` no-ops store one immutable successful request receipt while leaving runtime state, lifecycle event history, notifications, schedules, and counters unchanged. A new `DRAIN` against a plugin with no active `ENABLED` lifecycle records one immutable `FAILED_PRECONDITION` receipt without changing plugin state. Transient transition or fence-install failures are not terminalized by this receipt slice. V3 assigns a founding `(pluginActivationEpoch, lifecycleRevision)=(1,1)` only to retained runtime rows with a nonblank active version and to retained schedules whose tenant, instance, plugin, version, runtime region, and region epoch match exactly; contradictory executable rows fail migration, and schema/repository guards reject incoherent pairs or an active version at `0/0`, while historical work/audit/handoff evidence remains `0/0` and fenced because its winning admission cannot be reconstructed. Generic plugin-owned ingress also requires the later fence read to remain `ENABLED` before persisting work. Focused service and migration-shape proof executes locally; PostgreSQL receipt/concurrency and retained-data cases require Docker/Testcontainers. @@ -25,7 +27,17 @@ The same V2 migration replaces handler work-item and audit identities so authent The current `script_event_ingress_audit` event-scope claim uses branch-specific `INSERT ... ON CONFLICT` claims: instance-scoped rows include their exact runtime identity and positive pin tuple, while pre-instance tenant-readiness `onLoad` rows use the nullable branch without inventing absent optional identity fields. The V5 indexes provide the corresponding positive-epoch instance and pre-instance uniqueness branches. Retained pre-fencing instance rows may keep a null epoch as historical evidence, but no live repository claim can create that shape; duplicate retained identities fail migration preflight for operator reconciliation rather than being deleted. The claim row carries a row-version/lease token. Before quota acquisition, work-item or projection fan-out, and handler-audit persistence, the owner renews that token with an atomic row-version/state check; stale reclaim advances the same fence, so a reclaimed slow owner fails before those effects. The implementation has unit and deterministic mocked concurrency proof for claim/reclaim fencing, but does not yet provide a full database-backed slow-owner/reclaim proof or rollback compensation for external quota counters; those remain implementation and proof gaps. -The command-plan preview boundary in [ADR 0114](../../decisions/adr-0114-command-plan-preview-dry-run-isolation.md) is non-committing: a preview must not persist live `script_work_items`, populate the live automation queue, hand off commands, or perform external side effects. It may persist isolated audit/result evidence containing the exact input identity, fenced snapshot/fixture reference, and ordered plan. The current materialized dry-run path may use the internal pre-DSL work-item/queue shape and persists that dry-run work item, but its live implementation records `finalStage=DSL_EVAL`, `finalOutcome=dry_run_completed`, and `finalReason=dry_run_no_handoff`; the shared terminal-success helper marks its internal `script_work_items.status=HANDED_OFF` even though no Game Session handoff or gameplay-work acceptance occurs. It has not converged on target `DRY_RUN_RESULT` terminology; that internal marker is not target live-work persistence or downstream-handoff evidence, and complete plan-result/input proof is still absent. This is an implementation handoff, not a competing contract. +The live `faction`/`faction_standing` schema and `FactionServiceImpl` currently make Automation the player-reputation writer and derive isolated standing identity from `gameInstanceId`. The target owner is Social & Groups under a stable playable-state namespace; Automation remains a consumer for NPC behavior. Owner migration, retained-row disposition, namespace-stable identity, and focused owner-read proof remain unimplemented. + +The live `script_event_audit` and `script_work_items` schema uniqueness constraints omit plugin provenance, and neither current row shape nor repository identity lookup carries the resolved `bindingId` required by the target full Trigger Identity. Distinct plugin handlers can therefore alias or collide even though the target full Trigger Identity requires `pluginId`, `pluginVersionId`, and `bindingId` where applicable. A new owner-local migration, aligned jOOQ/repository identity, and focused multi-handler retry/concurrency proof are required; this is current implementation drift, not a change to Trigger Identity authority. + +The command-plan preview boundary in [ADR 0114](../../decisions/adr-0114-command-plan-preview-dry-run-isolation.md) is non-committing: a preview must not persist live evaluated script work items, populate the live automation queue, hand off commands, or perform external side effects. It may persist isolated audit/result evidence containing the exact input identity, fenced snapshot/fixture reference, and ordered plan. The current materialized dry-run path may use the internal pre-DSL trigger-record/queue shape and persists that current pre-DSL trigger record, but its live implementation records `finalStage=DSL_EVAL`, `finalOutcome=dry_run_completed`, and `finalReason=dry_run_no_handoff`; the shared terminal-success helper marks its internal `script_work_items.status=HANDED_OFF` even though no Game Session handoff or gameplay-work acceptance occurs. It has not converged on target `DRY_RUN_RESULT` terminology; that internal marker is not target live-work persistence or downstream-handoff evidence, and complete plan-result/input proof is still absent. This is an implementation handoff, not a competing contract. + +Redis adoption has separate current gaps: the live `automation:test:quota:*`, `automation:test:capacity:*`, and `automation:readiness:capacity:*` builders are named in the cache catalog but are not yet all represented in the central reset/ACL ownership inventory. Readiness and dry-run capacity reservations invoke the shared two-key counter/lease script with one documented hash tag shared by each pair, so the current pairs are not inherently cross-slot; central ownership registration, canonical key encoding, durable charge/admission, reset, retention, and idempotent lease-accounting proof remain incomplete. The live `automation:queue:{tenantInstanceTag}:*` projection also appends to lists without a pointer TTL or maximum-length bound, so it is not yet proven TTL-only; its current `AutomationRedisKeys` builder accepts raw nonblank IDs and does not prove canonical opaque tuple encoding, delimiter/brace rejection, or collision safety. These are current implementation/proof gaps, not new authority. In the target state, PostgreSQL owns durable automation work, definitions, and persisted charge/admission truth, but the current implementation has no durable charge/admission markers or charge record: `ScriptQuotaServiceImpl`, `ScriptTenantBudgetServiceImpl`, and the readiness/dry-run capacity services make best-effort Redis counter/lease decisions. Current quota, tenant-budget, readiness, capacity, and queue-pointer decisions are therefore Redis best-effort and reset-sensitive; their loss may relax or tighten admission fairness or delay discovery, but cannot change the durable work and definition rows that currently exist. Before claiming the target boundary, register each family with its owner/class/reset behavior, define and enforce the queue retention policy, and either use one canonical encoded tuple builder for every key or prove canonical UUID parsing at every boundary, then add focused retention, collision/brace, same-scope slot, cluster, reset, and durable charge/admission proof. + +The current dry-run and readiness capacity reservations also are not idempotent by work item: each retry generates a new lease token, increments the same counter, and overwrites the prior `(tenantId, workItemId)` lease. Releasing the earlier reservation then fails its token check and leaves one count occupied until expiry. The counters remain heuristic and reset-tolerant, but lease accounting must not leak on repeated reservation attempts; duplicate/retry and release-order proof is absent. + +The current queue consumer has an additional bounded-drain limitation that must remain explicit: `drainWorkItems` and `drainIndexedWorkItemPointers` consume pointers with atomic Redis `LPOP`, so a producer's concurrent `RPUSH` is not discarded by a range/read followed by deletion. The indexed path still uses database-wide `KEYS("automation:queue:*")`, and the current lists have no pointer TTL or maximum-length bound, so the path is not a cluster-safe discovery or retention proof. Durable claim fallback can process pending PostgreSQL rows independently, but it does not establish a reset/rebuild recovery gate. Target enqueue/rebuild must atomically apply `SCRIPT_OUTBOX_QUEUE_POINTER_TTL_SECONDS` and `SCRIPT_OUTBOX_QUEUE_MAX_POINTERS_PER_KEY`, preserve or durably account for unreturned tails and concurrent appends, use an owner-maintained/cursor-based cluster-safe queue index rather than database-wide `KEYS`, and trigger bounded durable re-drive with exact identity/readback before reset-gate release. The two settings remain environment/service configuration (currently `TBD`); no target support claim is valid until each environment supplies validated positive bounds and focused concurrent-drain, truncation/expiry, cluster, and re-drive proof. ## Architecture and Design Notes @@ -42,7 +54,7 @@ The command-plan preview boundary in [ADR 0114](../../decisions/adr-0114-command - **Target plugin lifecycle state:** Automation persists the current `(pluginVersionId, pluginActivationEpoch, pluginState, lifecycleRevision)` and at most one pending transition with the captured current tuple and fixed target values. The same runtime row separately persists `breakerState` (`CLOSED` or `DISABLED_DUE_TO_ERRORS`), bounded `breakerReason`, monotonic `breakerRevision`, and monotonic `breakerSampleGeneration` for the exact active version/runtime scope; a new active version starts at sample generation `0`, and each reset advances that generation exactly once. Breaker trip transactions compare-and-set the exact active version, observed closed-state revision, and sample generation while atomically appending immutable sample/transition evidence and advancing `breakerRevision` once. Reset transactions compare-and-set the expected disabled state/revision, clear the breaker, advance both `breakerRevision` and `breakerSampleGeneration` once, and atomically append immutable reset evidence; prior-generation samples remain history-only. Breaker transitions do not mutate lifecycle state or counters. Every state-changing lifecycle transition persists/reserves `targetLifecycleRevision = current lifecycleRevision + 1`; epoch-advancing transitions additionally persist/reserve `targetPluginActivationEpoch = current pluginActivationEpoch + 1`. Same-epoch entry to `DRAINING` retains the current `pluginActivationEpoch` while advancing/reserving the next lifecycle revision. The fixed target epoch/revision are bound into the canonical request digest, initiation and completion compare-and-set, idempotent Game Session fence-install command and durable acknowledgement, exact retry, and commit; they are never recomputed after initiation and become current exactly once on commit. - Patch reload now also persists a first durable `script_schedule_definitions` catalog for scheduler-owned handlers such as `onInterval` / `onTimerExpire`. Its current live uniqueness key is `(tenantId, scriptPatchVersion, pluginId, pluginVersionId, scheduleDefinitionId)` with cadence/unit metadata and normalized schedule hash; because core scripts use empty plugin fields, their `scheduleDefinitionId` values are currently patch-wide unique. Observed Game Session pins create durable `script_schedule_instances` rows for the matching `(tenantId, gameInstanceId)` scope, retaining the current exact owner tuple `(scriptPatchVersion, scriptPinEpoch, scriptPinControlPlaneRequestId)`, schedule identity, binding target, and mutable due-point state; schedule reconciliation and firing fail closed on absent or mismatched pin/owner evidence. The pin-owner request ID is retained as owner evidence/correlation and is distinct from any reconciliation operation request ID. `ObserveRuntimeTickProgress` updates the runtime region and due-point fields for tick-aligned schedules, including the next future due tick; wall-clock schedules currently expose `nextDueAt`, which maps to target durable `dueAt` plus projected `nextRunAt`, not to independent deadlines. Current live schedule rows retain `playableStateScope` but not the stable `playableStateNamespaceId`; target rows must retain both, and a missing namespace fails closed rather than being inferred. Target schedule rows also retain the exact pin tuple, and target scheduler identity is scoped by stable owner kind/id as defined by [Scripting Scheduler and Timer Lifecycle](../../system-architecture-scripting-scheduler-and-timers.md#stable-schedule-instance-row-identity), while live region ownership remains a transitional non-empty scope marker and core-script owner identity remains narrower than that target. Richer recovery guarantees and their proof remain implementation gaps. - Authoritative gameplay reads use the durable handler-scoped input manifest owned by the [DSL lifecycle contract](../../system-architecture-scripting-dsl-reference-and-lifecycle.md#read-consistency-contract). The manifest records bounded trigger facts, pinned artifacts, owner versions/values, causal floor, and seed version for each resolved handler. A `readSnapshotToken` may remain as one owner-specific manifest input or correlation value where the owner contract requires it; it is not universal authority, and retries/recovery must never fetch a fresher value. -- **Target state:** For gameplay-originated events, ingress and durable runtime state must persist the resolved `playableStateScope` and stable `playableStateNamespaceId` alongside `tenantId`, `gameInstanceId`, `regionId`, `regionEpoch`, and `entityId`, so shared-state and isolated-state realms remain distinct through work-item identity, timer/schedule materialization, replay checks, dead letters, and operator reads even when they share the same tenant. `playableStateNamespaceId` is durable playable-state identity; `gameInstanceId` remains the active runtime fence and S3 scope. At the Game Session-to-Automation handoff, Game Session must resolve `playableStateNamespaceId` and `playableStateScope` from the scoped runtime context and the receiving owner must validate the exact `{tenantId, playableStateNamespaceId, playableStateScope, gameInstanceId, regionId, regionEpoch}` atomically with the enqueue/claim transition before enqueue or execution. The current `script_work_items` schema/model and live ingress/handoff wire carry only `playableStateScope`; they do not yet persist or guarantee `playableStateNamespaceId` or its owner proof, so missing or mismatched authority remains an implementation gap and must fail closed. This namespace/scope evidence is separate from the canonical Command-Handoff Identity and does not redefine that identity. `regionEpoch` is an explicit Trigger Identity dimension and replay fence, not metadata that may be refreshed from the current region later. A retry is the same trigger only when it carries the same epoch. Admission, ownership transfer, handoff, and execution must not rely on a detached compare-then-apply check: the owner that durably claims or applies the work must validate the supplied epoch atomically with that transition, or the handoff must carry an authoritative fence token that the downstream execution owner validates immediately before application. A stale or mismatched event is rejected or made a fenced no-op under its original identity, recorded with a bounded `runtime_scope_changed` reason where an admitted run is canceled, and is never evaluated or reminted under the newer epoch. A producer must emit a new identity against the current epoch when the event is still valid. +- **Target state:** For gameplay-originated events, ingress and durable runtime state persist the resolved `playableStateScope` and stable `playableStateNamespaceId` alongside `tenantId`, `gameInstanceId`, `regionId`, `regionEpoch`, and `entityId`, so shared-state and isolated-state realms remain distinct through trigger/descriptor identity, timer/schedule materialization, replay checks, dead letters, and operator reads even when they share the same tenant. `playableStateNamespaceId` is the durable playable-state uniqueness component; `playableStateScope` is separately retained and exact-validated policy/routing/authorization/migration-fence evidence. `gameInstanceId` remains the active runtime fence and S3 scope. At the Game Session-to-Automation handoff, Game Session resolves `playableStateNamespaceId` and `playableStateScope` from the scoped runtime context and the receiving owner validates the exact `{tenantId, playableStateNamespaceId, playableStateScope, gameInstanceId, regionId, regionEpoch}` atomically with the enqueue/claim transition before enqueue or execution. The namespace participates in the canonical Trigger and Command-Handoff identities; scope evidence is separate from those uniqueness keys and does not redefine them. **Current implementation gap:** The live ingress/handoff wire does not yet guarantee the namespace/scope fields or their owner proof, so missing or mismatched authority must fail closed. `regionEpoch` is an explicit Trigger Identity dimension and replay fence, not metadata that may be refreshed from the current region later. A retry is the same trigger only when it carries the same epoch. Admission, ownership transfer, handoff, and execution must not rely on a detached compare-then-apply check: the owner that durably claims or applies the work must validate the supplied epoch atomically with that transition, or the handoff must carry an authoritative fence token that the downstream execution owner validates immediately before application. A stale or mismatched event is rejected or made a fenced no-op under its original identity, recorded with a bounded `runtime_scope_changed` reason where an admitted run is canceled, and is never evaluated or reminted under the newer epoch. A producer must emit a new identity against the current epoch when the event is still valid. - Each game’s scripts live in tables keyed by `tenantId`, ensuring automation for one game cannot access another’s data. Derived Redis coordination and index keys must preserve runtime instance isolation as well, not just tenant isolation. - Utilizes the [Shared Libraries](../../system-architecture-shared-libraries.md) for DTO definitions, logging interceptors, and Micrometer metrics. @@ -59,16 +71,16 @@ Tick-driven automation and event handling never use synchronous sagas or Tempora - `script` holds compiled component definitions and version metadata. - `npc_memory` is a live but latent NPC-behavior state family. The baseline schema and repository key it only by `tenantId`, `npcId`, and `key`; they do not carry a stable playable-state namespace or a typed runtime-actor identity. Owner classification and any required mapping/application evidence are not established, so no S1/S2/S3 selection is made. The path is non-admissible for replacement until its owner classification, identity mapping, and focused proof exist; this is not a claim that it is S3 or disposable. -- **Target-state:** Admitted script work items are persisted durably in a PostgreSQL-backed outbox in `PENDING_EVALUATION`, keyed only by the full canonical Trigger Identity plus sequencing fields as needed, including `playableStateScope` and `regionEpoch`; the exact observed `(scriptPatchVersion, scriptPinEpoch)` tuple, captured plugin `pluginActivationEpoch` and owner `lifecycleRevision` where applicable, resolved binding `priorityTag`/`quotaClass`, immutable `lane`, and bounded `cost_class` are execution evidence used for the canonical charge lifecycle. The owner-committed `controlPlaneRequestId` is persisted separately as owner-grounded projection/correlation evidence and retained through reload, convergence, handoff, and recovery; it is not part of Trigger Identity, sequencing, uniqueness, or deduplication. Pre-DSL records retain the sealed immutable handler input manifest, including `priorityTag`, `quotaClass`, `lane`, `cost_class`, `componentCostRegistryDigest`, and `artifactRuntimeCapDigest` where applicable. Gameplay/runtime persistence, handoff, retry/replay, and recovery preserve these values unchanged; missing, changed, or contradictory lane/cost or plugin lifecycle-fence evidence fails closed rather than being inferred or refreshed. +- **Target-state:** Admitted pre-DSL trigger records are persisted durably in a PostgreSQL-backed outbox in `PENDING_EVALUATION`, keyed only by the full canonical Trigger Identity plus sequencing fields as needed, including `playableStateNamespaceId` and `regionEpoch`; the exact observed `(scriptPatchVersion, scriptPinEpoch)` tuple, captured plugin `pluginActivationEpoch` and owner `lifecycleRevision` where applicable, resolved binding `priorityTag`/`quotaClass`, immutable `lane`, and bounded `cost_class` are execution evidence used for the canonical charge lifecycle. The owner-committed `controlPlaneRequestId` is persisted separately as owner-grounded projection/correlation evidence and retained through reload, convergence, handoff, and recovery; it is not part of Trigger Identity, sequencing, uniqueness, or deduplication. `playableStateScope` is persisted and exact-validated alongside the namespace as policy/routing/authorization/migration-fence evidence, but is excluded from Trigger Identity, schedule, and Command-Handoff uniqueness. Where the current repository/schema includes scope in uniqueness, that is current implementation drift and not target identity authority. Pre-DSL records retain the sealed immutable handler input manifest, including `priorityTag`, `quotaClass`, `lane`, `cost_class`, `componentCostRegistryDigest`, and `artifactRuntimeCapDigest` where applicable. Gameplay/runtime persistence, handoff, retry/replay, and recovery preserve these values unchanged; missing, changed, or contradictory lane/cost or plugin lifecycle-fence evidence fails closed rather than being inferred or refreshed. - For scheduler-derived plugin work, the captured `pluginActivationEpoch` is also a tagged input to the durable schedule-candidate/firing-claim identity and therefore transitively to the derived event-scope `scriptEventId`; it remains excluded from handler Trigger Identity and Command-Handoff Identity, while `lifecycleRevision` remains fence-only. Ordinary producer ingress must not fabricate either scheduler-owned field. -- `automation:queue:{tenantInstanceTag}:` keys in Redis buffer indexes or pointers for admitted handler work after its durable `PENDING_EVALUATION` work item is persisted. Each entry includes enough identity to locate the durable work item and must not be treated as an authoritative log of commands. +- `automation:queue:{tenantInstanceTag}:` keys in Redis buffer indexes or pointers for admitted handler work after its durable `PENDING_EVALUATION` pre-DSL trigger record is persisted. Each entry includes enough identity to locate the durable trigger record and must not be treated as an authoritative log of commands. - Queue activity must be surfaced through the canonical observability contract metric families rather than through an unsupported parallel metric surface. - **Current migration drift:** The unauthenticated `PATCH /factions/{id}/reputation` route has been removed from the service-local HTTP port and OpenAPI. The remaining `FactionServiceImpl` is not an exposed route, but it still contains an Automation-owned `faction_standing` writer keyed from `gameInstanceId`; its faction lookup is now tenant-qualified. Removal of the public route does not prove Social ownership, character binding, a null-safe unique standing identity for `{tenantId, playableStateNamespaceId, characterId, factionId}`, or concurrent first-write safety. Before any new caller reaches this service method, the owner migration must converge it on an authenticated, caller-bound Social contract rather than resume Automation standing writes. **Target state:** Social owns durable player faction standing under `{tenantId, playableStateNamespaceId, characterId, factionId}`; see the [Social & Groups runtime/data owner contract](../social-groups-service/runtime-and-data.md#data-model). Automation is read-only for standing and consumes Social's owner read contract to drive NPC morale and aggression behavior. ## Script Lifecycle - Scripts reside in the service database and are versioned along with other game data as described in the design-service versioning process. -- **Target-state lifecycle:** Events from Game Session and other domain services trigger script admission via gRPC. Event/handler admission seals the handler input manifest and durably creates each admitted handler's `PENDING_EVALUATION` work item, then queues its rebuildable pointer; DSL evaluation is later, only after the executor claims the work and the lease/executor-acceptance transaction advances it to `EXECUTING`. +- **Target-state lifecycle:** Events from Game Session and other domain services trigger script admission via gRPC. Event/handler admission seals the handler input manifest and durably creates each admitted handler's `PENDING_EVALUATION` pre-DSL trigger record, then queues its rebuildable pointer; DSL evaluation is later, only after the executor claims the record and the lease/executor-acceptance transaction advances it to `EXECUTING`. - The sandboxed engine limits CPU time and memory for each script to prevent runaway behavior. - After evaluation, bounded command descriptors are staged into the already admitted durable handler work item and handed off for tick enqueue; the `automation:queue:{tenantInstanceTag}:` entry remains a rebuildable pointer rather than a post-evaluation source of truth. - A scheduled durable executor claims persisted `PENDING_EVALUATION` work items, evaluates the current command-emission format, and hands off commands to Game Session for tick enqueue. `automation:queue:*` remains a rebuildable pointer projection rather than the driver of authoritative execution state. In the current legacy materialized dry-run path, the work-item storage status is nevertheless set to `HANDED_OFF` as a terminal compatibility marker even though no Game Session handoff occurs; the authoritative audit remains `finalStage=DSL_EVAL`, `finalOutcome=dry_run_completed`, and `finalReason=dry_run_no_handoff`. This is current implementation drift, not target `TICK_HANDOFF`/`handoff_accepted` semantics; target ADR 0114 previews use an isolated preview result and do not create a live work item. @@ -93,6 +105,8 @@ This behavior ensures that a script patch either becomes the new active version **Target-state recovery evidence:** Automation owns a monotonic `failureGeneration` per `(tenantId, outboxWorkItemId)` and initializes/advances it exactly once in the same atomic transition that enters `DEAD_LETTERED`; exact transition retries/no-ops do not advance it. Dead-letter rows retain the immutable failure stage and current `failureGeneration`, original Trigger Identity, exact patch/epoch, immutable `lane` and bounded `cost_class`, owner-committed `controlPlaneRequestId`, plugin provenance and captured `pluginActivationEpoch`/`lifecycleRevision` where applicable, frozen manifest, immutable evaluated output, and a complete descriptor/child-dispatch ledger keyed by the full Command-Handoff Identity. Per-item request results, recovery claims/attempts, successful-recovery evidence, and `already_recovered` readback bind `(tenantId, outboxWorkItemId, failureGeneration)`; one active claim exists per current generation and stale owners/generations fail CAS. A new request resolves the current failure generation atomically, so older-generation evidence remains immutable and cannot satisfy or block a newer current generation. Per-child recovery state records each child status, its persisted `handoffRequirement`, attempt/claim information, and durable downstream acknowledgement or outcome. The evaluated output and complete ledger are replay input; an evaluated-output or command digest is integrity evidence only and cannot substitute for the retained output or descriptor identity. `outboxWorkItemId`, the parent Trigger Identity, and `scriptEventId` remain correlation-only identifiers and are not child identity. The frozen manifest retains `priorityTag`, `quotaClass`, `lane`, `cost_class`, `componentCostRegistryDigest`, and `artifactRuntimeCapDigest` where applicable; evaluation-stage and post-evaluation recovery reuse that evidence verbatim without recomputing mutable registry, cap, scheduler-policy, or required/optional classification values. Evaluation-stage recovery may retry the original graph; post-evaluation recovery only resumes unfinished children. Missing or contradictory evidence, including missing or changed lane/cost, plugin lifecycle-fence, or handoff-requirement values at handoff, replay, or recovery, remains dead-lettered and fails closed. Schedule reconciliation defaults to cancel-and-recreate, with continuity only when the authored stable identity and compatibility declaration explicitly match. +Ordinary owner-local dead-letter recovery/retry is non-conflicting routine replay only when complete stage-specific recovery evidence proves the eligible transition and, for post-evaluation work, the persisted child ledger records each child disposition; ambiguous states such as `EVALUATING` or `HANDOFF_IN_FLIGHT` do not qualify merely because PostgreSQL contains a work item. Apply the canonical stage-aware eligibility and recovery rules in [Scripting & Automation: Control Plane API](../../system-architecture-scripting-control-plane-api.md#replaydeadletteredworkitems). Target `automation:queue:*` queue-pointer rebuild is non-conflicting routine reprojection only through the owner-reconciled `PENDING_EVALUATION` status/owner/CAS gate; current reset/rebuild/resume remains unavailable and must fail closed because the implementation cannot distinguish safe from stale claims. Automation records the owner classification and the evidence for that exemption, including the exact durable identity, source snapshot/cursor, request or output digest, and affected scope; this does not grant maintenance authority. Any maintenance or reset mutation, including one reached from dead-letter recovery or pointer rebuild, must instead carry the unchanged ADR-0085 external maintenance handoff with its exact `operationId`, external maintenance fence/lock binding, classifier, immutable evidence digest, and complete affected scope, or fail closed. + ## Redis Roles and Prefixes - **Coordination Redis participation** @@ -101,13 +115,15 @@ This behavior ensures that a script patch either becomes the new active version - **Cache/Rate-Limit Redis usage** - Stores script quota counters and similar best-effort aggregates in Cache/Rate-Limit Redis using prefixes such as `automation:quota::`, `automation:tenant-budget::tier:`, the dry-run/test quota families `automation:test:quota::script::tenant` and `automation:test:quota::script::principal:`, the dry-run capacity families `automation:test:capacity:{}:tenant`, `automation:test:capacity:{}:lease:`, `automation:test:capacity:{automation-test-capacity}:cluster`, and `automation:test:capacity:{automation-test-capacity}:cluster:lease::`, the readiness capacity families `automation:readiness:capacity:{}:tenant`, `automation:readiness:capacity:{}:lease:`, `automation:readiness:capacity:{automation-readiness-capacity}:cluster`, and `automation:readiness:capacity:{automation-readiness-capacity}:cluster:lease::`, and `automation:queue:{tenantInstanceTag}:*`. - Treats these keys as transient operational data; PostgreSQL remains authoritative for script definitions and long-lived automation state. - - Quota and queue-oriented prefixes are best-effort TTL-only caches unless explicitly documented as strongly validated caches with versioned payloads and stricter invalidation semantics. + - Quota prefixes are best-effort TTL-only caches unless explicitly documented as strongly validated caches with versioned payloads and stricter invalidation semantics. `automation:queue` is an explicit exception: current RPUSH-only pointer lists have neither TTL nor a bound, and the target pointer-liveness TTL and maximum list length apply only once implemented, as detailed in the ownership table below. Ownership and durability expectations for Automation & Scripting prefixes: | Prefix | Redis role | Durability / reset tolerance | | --- | --- | --- | -| `automation:queue:{tenantInstanceTag}:*` | Cache/Rate-Limit | Reset-tolerant only in the target state; best-effort cache or queue of automation work-item indexes. **Target state:** loss is recoverable from durable work through the accepted owner/status/CAS gate for `PENDING_EVALUATION` plus only an `EVALUATING` row whose owner has proved the lease stale or explicitly released ownership through one fenced compare-and-set. **Current state:** reset/rebuild and resume are unavailable and must fail closed because the implementation cannot distinguish safe from stale claims; a non-atomic status preflight cannot authorize recovery. | +| `automation:timer:{tenantRegionTag}` | Coordination (target-only, once implemented) | Once implemented, this will be a reset-tolerant derived timer index. Entries retain and exact-validate the complete durable schedule identity in their payload, including `gameInstanceId` and `playableStateNamespaceId` (plus plugin identity when applicable), despite the region-scoped key; loss is repaired from PostgreSQL schedule/claim state and authoritative tick progress. There is no current projection or supported current reset/rebuild guarantee. | +| `script-scheduler:{tenantRegionTag}:lastTickId` | Coordination (target-only, once implemented) | Once implemented, this will be a reset-tolerant scheduler progress hint. The value carries `regionEpoch` and `latestTickId` only; an epoch mismatch is rejected and rebuilt from the authoritative tick heartbeat/progress, and it never owns `streamOffset` or durable schedule identity. There is no current projection or supported current reset/rebuild guarantee. | +| `automation:queue:{tenantInstanceTag}:*` | Cache/Rate-Limit | Reset-tolerant only in the target state; best-effort index of pre-DSL trigger records. **Target state:** recovery indexes safe `PENDING_EVALUATION` work and may include an `EVALUATING` row only after its owner proves the lease stale or explicitly releases ownership through one fenced compare-and-set covering status, owner, freshness, and fence transition. The target applies the configured pointer-liveness TTL and maximum list length atomically on enqueue/rebuild; truncation or expiry never settles or drops durable work. **Current state:** the helper selects only `PENDING_EVALUATION`, but has no owner/CAS gate; RPUSH-only lists have no TTL or bound. Reset/rebuild and resume remain unavailable and fail closed; a non-atomic status preflight cannot authorize even a PENDING-only recovery path. | | `automation:quota::` | Cache/Rate-Limit | Reset-tolerant, best-effort quota counters. Dropping these keys temporarily resets budgets but does not affect script correctness or long-term state. | | `automation:tenant-budget::tier:` | Cache/Rate-Limit | Reset-tolerant, best-effort tenant budget counters for live automation execution reservations. Dropping these keys temporarily relaxes tenant fairness but does not affect durable work truth. | | `automation:test:quota::script::tenant`, `automation:test:quota::script::principal:` | Cache/Rate-Limit | Reset-tolerant one-minute dry-run/test admission counters, respectively per tenant/script and per principal/script. They are isolated from live quota and budget families; expiry or reset may temporarily allow another test window but cannot change durable work truth. The Automation service owns both families and only its Cache/Rate-Limit ACL may access them; there is no rebuild because the counters are disposable windows. | @@ -124,17 +140,20 @@ Quota and queue-related caches are best-effort TTL-only caches unless this servi ## Durable Script Work-Item Outbox -To avoid “DSL evaluated successfully but effects were silently dropped”, the service must durably persist and queue each admitted handler's `PENDING_EVALUATION` work item before DSL evaluation or execution acceptance: +To avoid “DSL evaluated successfully but effects were silently dropped”, the service must durably persist and queue each admitted handler's `PENDING_EVALUATION` pre-DSL trigger record before DSL evaluation or execution acceptance: -- **Target state:** Admitted triggers seal the handler input manifest and produce `PENDING_EVALUATION` script work items written to a PostgreSQL-backed outbox table keyed by Trigger Identity plus sequencing fields as needed. -- Target materialized `script_schedule_instances`, resume windows, due candidates, firing claims/audits, timer-generated work items, handoff events, and dead-letter rows preserve the same stable `playableStateNamespaceId` and gameplay `playableStateScope` evidence so scheduler-driven follow-up work stays in the same shared-versus-isolated state namespace as the original admitted event. Namespace evidence remains separate from canonical schedule, Trigger, and Command-Handoff identities; missing or mismatched evidence fails closed rather than being inferred or refreshed. Current schedule rows still lack `playableStateNamespaceId`, as recorded in the implementation-status boundary above. +- **Target state:** Admitted triggers seal the handler input manifest and produce `PENDING_EVALUATION` pre-DSL trigger records written to a PostgreSQL-backed outbox table keyed by the canonical Trigger Identity plus sequencing fields as needed. `playableStateNamespaceId` is the playable-state uniqueness dimension; `playableStateScope` is separately persisted and exact-validated policy/routing/authorization/migration-fence evidence and is excluded from Trigger Identity, schedule, and Command-Handoff uniqueness. Where the current repository/schema includes scope in uniqueness, that is current implementation drift and not target identity authority. +- Target materialized `script_schedule_instances`, resume windows, due candidates, firing claims/audits, timer-generated pre-DSL trigger records, evaluated script work items, handoff events, and dead-letter rows preserve the same stable `playableStateNamespaceId` and gameplay `playableStateScope` evidence so scheduler-driven follow-up work stays in the same shared-versus-isolated state namespace as the original admitted event. The namespace participates in canonical schedule, Trigger, and Command-Handoff identities; `playableStateScope` evidence remains separate from those identities. Missing or mismatched evidence fails closed rather than being inferred or refreshed. Current schedule rows still lack `playableStateNamespaceId`, as recorded in the implementation-status boundary above. - `automation:queue:*` keys are derived coordination indexes that accelerate draining and batching, not the authoritative record of pending work. -- On restart, failover, or Cache/Rate-Limit Redis resets, the target service rebuilds `automation:queue:*` indexes from durable pending items. The current `rebuildPendingWorkItemIndex` selects only `PENDING_EVALUATION` rows but has no stale, owner, or compare-and-set gate, so queue reset/rebuild and resume are unavailable and must fail closed; a non-atomic status preflight cannot authorize the target path for `PENDING_EVALUATION` plus only owner-reconciled `EVALUATING` rows. This implementation/proof gap is recorded in the [scripting runtime rebuild contract](../../system-architecture-scripting-runtime-execution.md#rebuild-and-deduplication-rules). +- On restart, failover, or Cache/Rate-Limit Redis resets, the target service rebuilds `automation:queue:*` indexes from durable eligible work under the [Redis Operations owner/CAS gate](../../system-architecture-redis-operations.md#cacherate-limit-redis-reset). The current `rebuildPendingWorkItemIndex` selects only `PENDING_EVALUATION` rows, but has no owner or compare-and-set gate; its Redis-existence check and append are separate operations. Queue reset/rebuild and resume are therefore unavailable and must fail closed, and a status preflight cannot establish a safe disposition for `EVALUATING` rows. The helper also uses `PageRequest.of(0, maxItems)` for each rebuild batch, so later eligible rows with missing pointers can be starved when earlier rows already have pointers; this bounded page-0 scan is not completeness or readback proof. The durable claim fallback can process pending PostgreSQL rows independently. Target reset/rebuild requires a cursor- or owner-maintained index with complete eligible-row coverage and the atomic status/owner/CAS gate before the external maintenance gate is released. This gap is recorded in the [scripting runtime rebuild contract](../../system-architecture-scripting-runtime-execution.md#rebuild-and-deduplication-rules). This enables stage-aware outcomes in `script_event_audit`: the system can distinguish “DSL evaluation succeeded” from “handoff or enqueue succeeded”, and can re-drive delivery where appropriate without re-executing the DSL body for the same trigger. ## Redis Cluster Slotting Rules +- Every Automation-owned multi-key operation must use keys carrying one canonical scope hash tag and therefore resolve to one Redis Cluster slot. Key families without a canonical shared tag are unsupported for atomic multi-key operations. Queue discovery must also avoid database-wide `KEYS`; it must use an owner-maintained index or bounded cursor/read path whose completeness and per-scope coverage are proven across cluster nodes. +- The target `tenantInstanceTag` is an opaque, collision-safe encoding of the complete `(tenantId, gameInstanceId)` tuple. The live builder concatenates raw nonblank strings, so it must not be described as canonical until it either uses the shared encoded/length-prefixed tuple helper or proves canonical lowercase UUID parsing and rejection of separators/braces at every boundary. Focused tests must cover delimiter/brace inputs, collision vectors, and same-scope slot equality. +- The current `automation:test:quota:*`, `automation:test:capacity:*`, and `automation:readiness:capacity:*` capacity families are unsupported until their central ownership/reset/ACL registration is complete and their keys use one canonical scope hash tag/Redis Cluster slot, or the cross-key reservation is replaced with a single-key design. - Automation Redis usage must never perform multi-key operations that span both `automation:*` and `tick:*` keys in a single invocation. - Allowed examples: - A Redis operation that touches only `automation:queue:{tenantInstanceTag}:*` keys for one runtime scope. diff --git a/design/architecture/microservices/automation-scripting-service/sandbox-runtime-design.md b/design/architecture/microservices/automation-scripting-service/sandbox-runtime-design.md index 8e92c5c90c..9e5a9c574c 100644 --- a/design/architecture/microservices/automation-scripting-service/sandbox-runtime-design.md +++ b/design/architecture/microservices/automation-scripting-service/sandbox-runtime-design.md @@ -82,7 +82,7 @@ For the [ADR 0114](../../decisions/adr-0114-command-plan-preview-dry-run-isolati 2. **Sandbox setup and executor acceptance** - The scheduler allocates a **sandbox context** from the sealed handler manifest. The following locally useful categories are not an exhaustive schema; the [canonical read-consistency contract](../../system-architecture-scripting-dsl-reference-and-lifecycle.md#read-consistency-contract) defines every required field and evidence: - - For instance-bound gameplay/runtime runs, the complete applicable owner/runtime scope (`tenantId`, `gameInstanceId`, `playableStateScope`, `regionId`, `regionEpoch`, and `entityId` when applicable) + - For instance-bound gameplay/runtime runs, the complete applicable owner/runtime scope (`tenantId`, `gameInstanceId`, `playableStateNamespaceId`, `playableStateScope`, `regionId`, `regionEpoch`, and `entityId` when applicable) - Tenant/script identity (`scriptId`, `eventType`, `eventSchemaVersion`, `scriptEventId`, and `isDryRun`) - The exact pinned `(scriptPatchVersion, scriptPinEpoch)` tuple for instance-bound gameplay/runtime runs - The applicable component-revocation security-policy fence under [ADR 0116](../../decisions/adr-0116-routine-component-migration-and-explicit-emergency-revocation.md) for any work referencing a revocable component, including embedded/core-script and plugin-backed work @@ -103,7 +103,7 @@ For the [ADR 0114](../../decisions/adr-0114-command-plan-preview-dry-run-isolati 4. **Command staging** - For eligible instance-bound gameplay/runtime runs, successful emitted commands are bounded descriptors staged into the already admitted per-handler durable work item and persisted atomically, then follow the separate durable Game Session handoff path. The already admitted `automation:queue:*` projection remains the pre-evaluation discovery pointer and is not a handoff queue. - Tenant-readiness `onLoad` is outside this descriptor-staging and handoff path. After readiness validation/evaluation it terminates with only platform-owned readiness, audit, and fencing evidence: it emits no gameplay descriptors or dispatch identity, creates no gameplay work, and never calls `EnqueueAutomationCommandIfAbsent`. This is the local sandbox consequence of the canonical [`onLoad` runtime contract](../../system-architecture-scripting-runtime-execution.md#onload-semantics-and-failure-handling). - - For those eligible instance-bound gameplay/runtime runs, target-state handoff through `EnqueueAutomationCommandIfAbsent` gives each emitted command child the complete Command-Handoff Identity: source `(tenantId, gameInstanceId, playableStateScope, regionId, regionEpoch)`, optional distinct target `(targetGameInstanceId, targetPlayableStateScope, targetRegionId, targetRegionEpoch)`, the `automationDispatchId` allocated and persisted by the first atomic durable evaluated-descriptor/outbox commit only when commands are emitted, and a deterministic `commandOrdinal` starting at `0` in canonical emitted-command order. Pre-commit evaluation retries preserve the Trigger/work-item/frozen-input identity and allocate no command-child identity; retries after a winning commit reuse its dispatch ID and ordinals. A valid zero-command evaluation creates no dispatch identity. Game Session deduplicates the complete child identity. The parent Trigger Identity and `outboxWorkItemId` are correlation-only and are excluded from command-child uniqueness and deduplication; they are not substitutes for the complete child identity. The live handoff remains narrower and is not complete child-identity proof; see the [current runtime handoff status](../../system-architecture-scripting-runtime-execution.md#current-implementation-status) and [normative Command-Handoff Identity](../../system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state). + - For those eligible instance-bound gameplay/runtime runs, target-state handoff through `EnqueueAutomationCommandIfAbsent` uses the [normative Command-Handoff Identity](../../system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state): source tenant/game-instance ownership (`tenantId`, `gameInstanceId`) and `playableStateNamespaceId`/region identity, optional distinct target game-instance ownership and namespace/region identity, the `automationDispatchId` allocated and persisted by the first atomic durable evaluated-descriptor/outbox commit only when commands are emitted, and a deterministic `commandOrdinal` starting at `0` in canonical emitted-command order. Source and target `playableStateScope` values are separately validated routing/fence evidence, not identity fields. Pre-commit evaluation retries preserve the Trigger/work-item/frozen-input identity and allocate no command-child identity; retries after a winning commit reuse its dispatch ID and ordinals. A valid zero-command evaluation creates no dispatch identity. Game Session deduplicates the complete child identity. The parent Trigger Identity and `outboxWorkItemId` are correlation-only and are excluded from command-child uniqueness and deduplication; they are not substitutes for the complete child identity. The live handoff remains narrower and is not complete child-identity proof; see the [current runtime handoff status](../../system-architecture-scripting-runtime-execution.md#current-implementation-status). - Before constructing each generated command or data-dependent collection for an eligible instance-bound gameplay/runtime run, the engine applies the artifact-pinned conservative prospective serialized-byte bound together with command-count, per-entity, and data-dependent caps. Before atomic persistence, it checks the exact bounded serialized size of the staged descriptors against the pinned ceiling. Any cap exceed is a non-success outcome; all staged output for that handler is discarded and no partial work item or handoff is committed. The evaluator accepts only the artifact-pinned `componentCostRegistryDigest` and `artifactRuntimeCapDigest` plus their embedded payloads as validated by the runtime owner; it does not estimate from a newer local registry. - Eligible instance-bound gameplay/runtime work reaches this stage only after the earlier execution-scheduler selection over queued work. Target-state handoff uses the event-count ceiling (`AUTOMATION_TICK_MAX_EVENTS`) and only documented `automation:*` Redis prefixes for projection and quotas. The Automation & Scripting Service never writes `tick:*` keys directly; it hands off commands to Game Session over internal gRPC so Game Session can enqueue tick commands under its own tick and locking model. Current live capacity enforcement is the aggregate per-tenant, priority-tier reservation described below. diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 3e05ec4ab5..a592a0d3cf 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -49,7 +49,7 @@ curl http://localhost:8080/ping - `ListRoomEntities(ListRoomEntitiesRequest) returns (ListRoomEntitiesResponse)` (target-state namespace-carrying response) – returns players, NPCs, and visible items present in a room, scoped by `RoomInstanceRef` and the resolved `playableStateNamespaceId`; PLAYER projections/lookups carry that namespace alongside the current `gameInstanceId` runtime fence. The current adapter remains floor-free and its response lacks `playableStateNamespaceId`, so this namespace boundary is not implemented or proved. - `GetDraftDesignDigest` – returns publish-gating digest for Draft entity templates using typed scope request `GetDraftDesignDigestRequest { tenantId, scope: oneof { versionId, scriptPatchVersion } }`. Entity Management supports `versionId` scope only and must return `UNSUPPORTED_SCOPE` for `scriptPatchVersion`. Minimum response fields are `{tenantId, scope, appliedCommitId, contentDigest, digestSchemaVersion}`. `appliedCommitId` means the highest Game Design commit whose full revision set has been durably applied to the target Draft entity scope. `contentDigest` must cover only version-scoped entity template/binding rows and must exclude live runtime entities and audit/history metadata. -Target-state gameplay mutation RPCs that change item, equipment, or container state accept the canonical `effectId` and its complete structured identity supplied by Game Session durable effect execution. Entity Management validates the `{tenantId, playableStateNamespaceId, gameInstanceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId}` projection before applying the mutation; `{tenantId, effectId}` alone is not a sufficient substitute for the scoped identity. `ApplyActorCondition` requires a dedicated `effectId` as the operation-level replay identity, while `sourceId` remains separate authored/source provenance. Duplicate delivery returns the stored applied/no-op response instead of applying the mutation again. Read-only query RPCs do not require an `effectId`. Equipment occupancy and compatibility additionally require the complete published game-authored vocabulary/body-layout schema and digest; missing, partial, or mismatched schema/mapping evidence fails closed. Current live mutation surfaces may still expose an optional or narrower effect field; that is an implementation gap, not permission to define a competing idempotency contract. +Target-state gameplay mutation RPCs that change item, equipment, or container state accept the canonical `effectId` and its complete structured identity supplied by Game Session durable effect execution. Entity Management validates the `{tenantId, playableStateNamespaceId, gameInstanceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId}` projection before applying the mutation; `{tenantId, effectId}` alone is not a sufficient substitute for the scoped identity. The participant guard also exact-compares the typed operation and immutable `requestDigest`; an enclosing `rootEffectId`, when carried for a generated child, is lineage/reconciliation context only and is not an additional uniqueness dimension. `ApplyActorCondition` requires a dedicated `effectId` as the operation-level replay identity, while `sourceId` remains separate authored/source provenance. Duplicate delivery returns the stored applied/no-op response instead of applying the mutation again. Read-only query RPCs do not require an `effectId`. Equipment occupancy and compatibility additionally require the complete published game-authored vocabulary/body-layout schema and digest; missing, partial, or mismatched schema/mapping evidence fails closed. Current live mutation surfaces may still expose an optional or narrower effect field; that is an implementation gap, not permission to define a competing idempotency contract. Exact allocator and scalar-format details remain non-authoritative in the pending [ADR 0183 proposal](../../decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). The actor-entry contract deliberately does not make `race`, `class`, attributes, abilities, ship configuration, or other RPG-shaped columns platform requirements. Such values are authored components validated against the exact published descriptor/template. A playtest copy has a new fork-local `characterId`; when `sourceCharacterId` is retained, it must carry the immutable `{sourceTenantId, sourcePlayableStateNamespaceId}` binding and remains provenance-only, never authorizing cross-namespace reads or writes or any other identity, ownership, mutation, controller, reconnect, or merge operation. @@ -171,7 +171,7 @@ Only entities approved by the `EntityVisibilityPolicy` are returned; hidden NPCs Under [ADR 0112](../../decisions/adr-0112-typed-bounded-gameplay-effect-extension.md), Entity Management is the canonical owner of actor/effect mutation, resource costs, and cooldown state. It accepts only a validated typed plan or registered effect operation resolved by the owning server-side gameplay path from the exact release-pinned typed effect declaration/reference and digest, preserves the operation/effect replay identity and request digest, and never parses script text, executes caller-supplied DML, or reconstructs targeting policy from a partial request. -`ApplyActorCondition` is the first mutation contract for the same actor-state table. The current implementation validates the concrete mTLS caller and method allowlist, `PlayerExecutionContext`, and playable-state scope before creating an `actor_active_conditions` row with `conditionKey`, `stackCount`, `sourceType`, `sourceId`, optional `expiresAt`, and optional caller-supplied `effectPayloadJson`; accepting that payload directly, and allowing `QueryActorState` to evaluate it into gameplay-visible state, is the transitional gap identified above. Until the target typed request exists, callers using the current wire contract must keep a supplied `sourceId` unique tenant-wide per intended operation/effect because it is also the durable replay marker key. Within that operation, the actor-condition table lookup is narrower—`{tenantId, playableStateKey, characterId, sourceType, sourceId}`—and returns the first matching source row without comparing changed `effectPayloadJson` values. The target contract carries a dedicated `effectId` as the operation-level replay identity under `{tenantId, effectId}`, while `sourceId` remains authored/source provenance and may legitimately recur across separate applications. Target-state replay behavior (not currently enforced by this transitional request) is: a completed duplicate with the same canonical request payload returns the original serialized `ApplyActorConditionResponse` without another condition mutation; an in-progress duplicate returns conflict, payload or operation reuse returns invalid argument, and an unreadable stored response fails internally. Until dedicated `effectId`, canonical request-digest, and stored-response enforcement are live, clients must not rely on those outcomes or on changed-payload conflict detection. This is intended for gameplay-owned actions such as the first transient `blocking` state as well as later spells, consumables, and scripted effects. Reads ignore expired rows, so an expired effect is not restored; the scheduled sweep uses a 30-second default fixed delay measured after the previous invocation completes, then globally and without a batch bound deletes elapsed `actor_active_conditions` rows. The sweep does not delete separate `entity_mutation_effects` receipts, which `ApplyActorCondition` checks before mutation, but a receipt-retention guarantee across the replay/restore horizon remains unproved. Current behavior makes no concrete duplicate-application or S2-loss claim; target proof still requires explicit S1/S2 classification, dependent-reference/hold checks, and typed target, request-digest, and concurrency enforcement. Callers must still treat the mutation response as the authoritative applied state for that request. +`ApplyActorCondition` is the first mutation contract for the same actor-state table. The current implementation validates the concrete mTLS caller and method allowlist, `PlayerExecutionContext`, and playable-state scope before creating an `actor_active_conditions` row with `conditionKey`, `stackCount`, `sourceType`, `sourceId`, optional `expiresAt`, and optional caller-supplied `effectPayloadJson`; accepting that payload directly, and allowing `QueryActorState` to evaluate it into gameplay-visible state, is the transitional gap identified above. Until the target typed request exists, callers using the current wire contract must keep a supplied `sourceId` unique tenant-wide per intended operation/effect because it is also the durable replay marker key. Within that operation, the actor-condition table lookup is narrower—`{tenantId, playableStateKey, characterId, sourceType, sourceId}`—and returns the first matching source row without comparing changed `effectPayloadJson` values. The target contract carries a dedicated `effectId` as the operation-level replay identity under `{tenantId, effectId}`, while `sourceId` remains authored/source provenance and may legitimately recur across separate applications. Target-state replay behavior (not currently enforced by this transitional request) accepts a completed duplicate only when the persisted participant guard exact-matches the owner-resolved partition, mutation `effectId`, typed operation, exact actor target, and immutable canonical `requestDigest`; an enclosing `rootEffectId` is lineage/reconciliation context rather than a uniqueness dimension. Such a match returns the original serialized `ApplyActorConditionResponse` without another condition mutation; an in-progress duplicate returns conflict, payload or operation reuse returns invalid argument, and an unreadable stored response fails internally. Until dedicated `effectId`, canonical request-digest, and stored-response enforcement are live, clients must not rely on those outcomes or on changed-payload conflict detection. This is intended for gameplay-owned actions such as the first transient `blocking` state as well as later spells, consumables, and scripted effects. Reads ignore expired rows, so an expired effect is not restored; the scheduled expiry sweep uses a 30-second default fixed delay measured after the previous invocation completes, then globally and without a batch bound deletes elapsed `actor_active_conditions` rows. The sweep does not delete separate `entity_mutation_effects` receipts, which `ApplyActorCondition` checks before mutation, but a receipt-retention guarantee across the replay/restore horizon remains unproved. Current behavior makes no concrete duplicate-application or S2-loss claim; target proof still requires explicit S1/S2 classification, dependent-reference/hold checks, and typed target, request-digest, and concurrency enforcement. Callers must still treat the mutation response as the authoritative applied state for that request. Condition and item-template effect payloads are an internal persisted contract in this first slice. They may contain a top-level `modifiers` array whose entries include `operation`, `target_key`, `value`, optional `scope_kind`, optional `scope_key`, and optional `priority`; supported operations currently match the shared evaluator primitives: `ADD`, `MULTIPLY`, `CLAMP_MIN`, `CLAMP_MAX`, `GRANT_FLAG`, and `GRANT_CONDITION`. diff --git a/design/architecture/microservices/entity-management-service/operations.md b/design/architecture/microservices/entity-management-service/operations.md index 01ba084089..0be0214be6 100644 --- a/design/architecture/microservices/entity-management-service/operations.md +++ b/design/architecture/microservices/entity-management-service/operations.md @@ -4,7 +4,7 @@ This document collects Entity Management’s readiness model, tick-lock/tick-ide ## Implementation Status -The complete participant-guard contract described here—root `EffectId`, typed operation and target, immutable `requestDigest`, and complete replay verification—is target-state. The current `EntityMutationEffectReplayService` and schema provide narrower effect/operation replay and do not yet enforce or prove the target mutation-boundary contract. Its duplicate-marker catch also runs inside the surrounding transaction, so a PostgreSQL unique-race loser can inherit an aborted/rollback-only transaction rather than reliably replaying or returning conflict; a conflict-safe insert or isolated marker transaction plus real PostgreSQL concurrent proof is required. [Transaction Strategies](../../system-architecture-transactions.md) is the canonical owner of participant-guard and replay-verification semantics. +The complete participant-guard contract described here—persisted mutation `EffectId` (the root `EffectId` for a root operation or the generated operation's persisted child `EffectId`, with the enclosing `rootEffectId` retained as lineage), typed operation and target, immutable `requestDigest`, and complete replay verification—is target-state. The current `EntityMutationEffectReplayService` and schema provide narrower effect/operation replay and do not yet enforce or prove the target mutation-boundary contract. Its duplicate-marker catch also runs inside the surrounding transaction, so a PostgreSQL unique-race loser can inherit an aborted/rollback-only transaction rather than reliably replaying or returning conflict; correction must use a conflict-safe insert or a same-transaction savepoint around marker handling while keeping the marker and mutation atomic, never an isolated marker transaction. Actual PostgreSQL concurrent proof remains unavailable. [Transaction Strategies](../../system-architecture-transactions.md) is the canonical owner of participant-guard and replay-verification semantics. The pending [ADR 0183 proposal](../../decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is non-authoritative. The current replacement-validation path is also narrower than the target contract: `ValidateEntityUpgradeMappings` does not yet bind the stable `playableStateNamespaceId`, owner-resolved `playableStateScope`, and active-instance authorization to the exact source/target versions, and the live result may echo a supplied `remapSetId` without locally validating or applying its mapping. This is an implementation/proof gap; the echo is not compatibility or cleanup evidence. @@ -24,23 +24,23 @@ Replacement operations use the stable `playableStateNamespaceId` and owner-resol ## Tick Locking -Target-state Entity Management tick processing acquires Redis locks before mutating entity state using the `tick:{tenantRegionTag}:lock:` key described in the [Redis Architecture](../../system-architecture-redis.md) document, so lock keys share a hash tag with tick queues and pending state. The live implementation remains drift: `TickLockServiceImpl` writes the legacy `tick:lock::` key and derives a private 500–5,000 ms TTL from `game.tick-duration-ms`, without `gameInstanceId`, `regionId`, or the canonical mutation fence. This is not a second lock authority and cannot authorize canonical mutation; see [Runtime and Data](./runtime-and-data.md#redis-role-and-prefixes) for the current/target boundary. The target settings contract in [Tick Concepts & Invariants](../../system-architecture-tick-concepts-and-invariants.md#tick-budget-ttls-and-region-health-conceptual) and [ADR 0073](../../decisions/adr-0073-evidence-calibrated-tick-budgets-and-lock-ttls.md) is owned by the shared resolver: +Target-state tick processing uses the canonical `tick:{tenantRegionTag}:lock:` key described in the [Redis Architecture](../../system-architecture-redis.md) document so lock keys share a hash tag with tick queues and pending state. The live `TickLockServiceImpl` remains implementation drift: it writes the unscoped `tick:lock::` key, derives a private TTL, and does not carry `gameInstanceId`, `regionId`, a shared resolver value, or the canonical mutation fence. This family is registered as current legacy Coordination state in the [Redis reset policy matrix](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary); it cannot authorize canonical mutation and must remain fenced from target reset/admission until the writer is removed or routed through the Game Session/shared helper. Entity Management must not define or retain a second lock authority. The settings contract in [Tick Concepts & Invariants](../../system-architecture-tick-concepts-and-invariants.md#tick-budget-ttls-and-region-health-conceptual) and [ADR 0073](../../decisions/adr-0073-evidence-calibrated-tick-budgets-and-lock-ttls.md) is owned by the shared resolver: - The Game Session Service exposes `game.tick-interval-ms` as the primary pacing knob. - The shared resolver supplies opaque effective values from measured execution, dependency latency, runtime pauses, and recovery evidence. Numeric bounds for those shared values remain pending the owner/settings decision; Entity Management must consume the resolved value and must not introduce `500`/`5_000` bounds or another private formula. -At target, Entity Management treats `lock_ttl_ms` as an opaque value supplied by shared helpers; it does not define its own lock TTL configuration. This keeps locks alive long enough for normal ticks to complete while still bounding the recovery window for stalled ticks. +Target Entity operations treat `lock_ttl_ms` as an opaque value supplied by shared helpers; they do not define a private lock TTL configuration. The current implementation's `game.tick-duration-ms` formula and 500–5,000 ms bounds are not evidence-calibrated and are not proof of the target contract. Whether shared-resolver values cover normal tick execution while bounding lock hold after a stall remains unproved pending the resolver's evidence-backed inputs and outputs; Entity Management must not infer that guarantee from the opaque value alone. At target runtime, the Game Session Service compares observed tick execution time to the mode-specific TTL: `tick_lock_ttl_ms{scope_class}` (derived from `lock_ttl_ms`) for `tick_mode="normal"` and `solo_lock_ttl_ms{scope_class}` (derived from `solo_tick_budget_ms`) for `tick_mode="solo"`, as described in the [Tick System design](../../system-architecture-ticks.md#timeout-and-fairness-policy). A bounded `scope_class` p99 ratio that approaches or exceeds a configured fraction of its selected TTL is a detection/escalation signal; it does not identify or classify an individual region. Exact region health and any degraded actionability are resolved from authoritative runtime-health/control-plane records, after which operators may increase the tick interval or simplify per-tick work. Entity Management does not adjust TTLs itself; it relies on the shared helpers and scheduler behavior to keep lock usage within safe bounds. -Entity Management follows the per-command execution phases in the [Tick System design](../../system-architecture-ticks.md#per-command-execution-phases), but each Redis Lua invocation acquires at most one `tick:{tenantRegionTag}:lock:` lock under [ADR 0074](../../decisions/adr-0074-one-entity-lock-per-redis-script.md). Multi-entity invariants use one owning PostgreSQL transaction where a single owner can enforce them, or durable effect/workflow legs with explicit reconciliation across owners; they never use piecemeal multi-lock Redis scripts. If an eligible entity lock is unavailable, Game Session reschedules the work through the canonical failure-class retry path. +Target Entity Management follows the per-command execution phases in the [Tick System design](../../system-architecture-ticks.md#per-command-execution-phases), but each Redis Lua invocation acquires at most one canonical `tick:{tenantRegionTag}:lock:` lock under [ADR 0074](../../decisions/adr-0074-one-entity-lock-per-redis-script.md). Multi-entity invariants use one owning PostgreSQL transaction where a single owner can enforce them, or durable effect/workflow legs with explicit reconciliation across owners; they never use piecemeal multi-lock Redis scripts. If an eligible entity lock is unavailable, Game Session reschedules the work through the canonical failure-class retry path. The live `TickLockServiceImpl` does not yet prove these target phases, scope, or fencing rules. ## Tick Idempotency Target-state Entity Management tick idempotency uses the per-aggregate last-tick state pattern described in the [Tick System and Runtime Design](../../system-architecture-ticks.md#domain-idempotency-rules-timeline-context--owner-guards) document. The live schema does not yet implement this watermark; its current domain-local replay table is `entity_mutation_effects` as recorded in [Runtime and Data](./runtime-and-data.md#implementation-status). - The target-only `entity_tick_state` shadow table is an `S3` instance/region timeline projection. It uses `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, targetAggregateType, entityId)` as its complete lookup key and tracks `(last_region_epoch, last_tick_id)` for that concrete runtime timeline; `playableStateScope` is separately persisted and exact-validated evidence, not a key dimension. For this table, `entityId` is the `targetAggregateId`; entity handlers supply the canonical entity aggregate type. Entity must exact-validate both the owner-resolved namespace and immutable scope evidence before reading or writing this future row; neither is inferred from the entity or instance id. -- `gameInstanceId`, `regionEpoch`, and `tickId` in this projection are runtime and fencing context; they do not define the durable uniqueness of a namespace-backed effect. Replacement replay retains the stable playable-state namespace/scope, the same root `EffectId`, and the same S1/S2 operation and target identity; the disposable watermark is only the concrete runtime timeline guard. +- `gameInstanceId`, `regionEpoch`, and `tickId` in this projection are runtime and fencing context; they do not define the durable uniqueness of an effect. Replacement replay retains the stable playable-state namespace/scope, the same persisted mutation `EffectId` (root or generated child), its enclosing root `EffectId` lineage, and the same S1/S2 operation and target identity; the disposable watermark is only the concrete runtime timeline guard. - Tick-driven handlers that mutate an entity: - resolve and read the target `entity_tick_state` row using the complete `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, targetAggregateType, entityId)` key, exact-validate the separately stored current namespace/scope evidence, and validate active-instance mutation authorization; an aggregate-only, namespace-free, scope-free, or instance-free watermark lookup is invalid; - compare `(last_region_epoch, last_tick_id)` from that exact row with `(currentRegionEpoch, currentTickId)` and treat `>=` as a replay/out-of-order no-op (or validation-only check); and @@ -48,18 +48,18 @@ Target-state Entity Management tick idempotency uses the per-aggregate last-tick The `entity_tick_state` watermark is a single-aggregate claim only. It must not coordinate a multi-aggregate or multi-effect operation by claiming several watermark rows; those operations use the structured operation-level `tick_effect_guard` participant set below. For one aggregate, Entity resolves and claims its watermark row and applies the mutation in the same local transaction. Multiple legitimate effects for one aggregate in one tick must use distinct structured participant guards rather than treating the watermark as an at-most-one-effect gate. -Complex multi-entity operations (for example trades that touch two inventories) use the operation-level effect guard pattern owned by [Transaction Strategies](../../system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory) and referenced by the tick document. They derive the complete target guard set from one stable root `EffectId` and its typed operation/target projections, while retaining the operation’s stable `effectKey` in the explicit ledger/guard projection; they insert or verify every participant guard in the same transaction before applying changes, and treat a conflict as completion only after the complete expected guard set and authoritative target state are present. Those root effect and target guards, not the disposable `entity_tick_state` watermark, own durable S1/S2 replay safety across runtime replacement. A partial conflict must reconcile the original root effect and its participant guard identities or fail closed; it must not be treated as proof that the whole operation already applied. +Complex multi-entity operations (for example trades that touch two inventories) use the operation-level effect guard pattern owned by [Transaction Strategies](../../system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory) and referenced by the tick document. A root operation derives its complete target guard set from one stable root `EffectId`; a generated or derived operation uses its persisted child `EffectId` and retains the enclosing root `EffectId` lineage. In either case, the guard uses the mutation identity and typed operation/target projections while retaining the operation’s stable `effectKey` in the explicit ledger/guard projection; Entity inserts or verifies every participant guard in the same transaction before applying changes, and treats a conflict as completion only after the complete expected guard set and authoritative target state are present. Those mutation effect and target guards, not the disposable `entity_tick_state` watermark, own durable S1/S2 replay safety across runtime replacement. A partial conflict must reconcile the original mutation identity, its enclosing root `EffectId`, and participant guard identities or fail closed; it must not be treated as proof that the whole operation already applied. Examples: - **Damage application** – when a tick instructs Entity Management to apply damage to `entityId`, the handler: - - uses the stable root `EffectId`, derives the typed damage operation/target guard identity, and inserts/verifies the corresponding `tick_effect_guard` row in the same transaction as the HP mutation; the stable `effectKey` remains in the explicit guard/ledger projection; - - treats a guard conflict as a replay only after verifying the complete effect and target state, and otherwise reconciles or fails closed with the original EffectId. Damage does not assume an at-most-one-damage-per-aggregate-per-tick invariant, so the per-aggregate `entity_tick_state` watermark is not sufficient for this path. + - uses the mutation's persisted `EffectId` (the root identity for a root damage mutation or a persisted child identity for a generated/derived damage mutation), derives the typed damage operation/target guard identity, and inserts/verifies the corresponding `tick_effect_guard` row in the same transaction as the HP mutation; the stable `effectKey` remains in the explicit guard/ledger projection; + - treats a guard conflict as a replay only after verifying the complete effect and target state, and otherwise reconciles or fails closed with the original mutation identity and its enclosing root `EffectId` lineage. Damage does not assume an at-most-one-damage-per-aggregate-per-tick invariant, so the per-aggregate `entity_tick_state` watermark is not sufficient for this path. - **Trade between two entities** – when a tick performs a trade between `fromEntityId` and `toEntityId`: - - **Target state:** the complete Command-Handoff Identity identifies an admitted automation command and is an input to allocating or looking up that command's stable root `EffectId`; it does not replace the effect identity or participant guards. `(automationDispatchId, commandOrdinal)` is only that command identity's dispatch-group suffix and must be interpreted with the complete source/target scope; a non-automation command instead uses its admitted `commandId`. `scriptEventId`, participant/item fields, and mutable payload text are never fallback identities. Every retry and owner commit preserves the resulting root `EffectId`, typed operation/target projections, and immutable request digest. The live Game Session handoff does not yet carry the full automation command identity end to end, so the current path uses the admitted `commandId` and available persisted work-item/dispatch fields; it must reject a missing command identity rather than synthesize one from the participants. This target gap is tracked under `AS-1.5` in the [automation and scheduler runtime tracker](../../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status); - - before encoding, the handler validates every identity-bearing and typed field against its declared type and domain; it does not encode malformed input, fallback identities, or alternate textual spellings. Quantity is parsed as its declared numeric type and rendered as canonical base-10 decimal, so semantically equal values such as `1` and `01` produce identical bytes; - - the handler serializes the admitted identity, the stable per-effect trade discriminator, and the validated canonical fields in a fixed versioned order using canonical UTF-8 length-prefixed fields, for example `trade:v1|:|:|:|:|:|:`; the exact resulting bytes are the retry identity and must be reused unchanged, while sibling effects from one command and separate admitted trades remain distinct; + - **Target state:** retain the admitted command/source identity for source evidence, and use the complete Command-Handoff Identity for automation handoff and deduplication; the handoff identity is not a mandatory input to root `EffectId` allocation or lookup. Root allocation and lookup details remain proposal-only under pending [ADR 0183](../../decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md), not accepted target state. `(automationDispatchId, commandOrdinal)` is only that command identity's dispatch-group suffix and must be interpreted with the complete source/target scope; a non-automation command instead has its admitted `commandId`. `scriptEventId`, participant/item fields, and mutable payload text are never fallback identities. Every retry and owner commit preserves the resulting root identity, typed operation/target projections, and immutable request digest. The live Game Session handoff does not yet carry the full automation command identity end to end, so the current path uses the admitted `commandId` and available persisted work-item/dispatch fields; it must reject a missing command identity rather than synthesize one from the participants. This target gap is tracked under `AS-1.5` in the [automation and scheduler runtime tracker](../../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status); + - **Illustrative proposal only (not an accepted canonical encoding):** before encoding, the handler would validate every identity-bearing and typed field against its declared type and domain; it would not encode malformed input, fallback identities, or alternate textual spellings. Quantity would be parsed as its declared numeric type and rendered as canonical base-10 decimal, so semantically equal values such as `1` and `01` produce identical bytes. The exact scalar/encoding contract remains pending human review in [ADR 0183](../../decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); + - **Illustrative proposal only (not an accepted canonical encoding):** the handler would serialize the admitted identity, the stable per-effect trade discriminator, and the validated canonical fields in a fixed versioned order using canonical UTF-8 length-prefixed fields, for example `trade:v1|:|:|:|:|:|:`. If later accepted, the exact resulting bytes would be the retry identity and would be reused unchanged, while sibling effects from one command and separate admitted trades would remain distinct; the pending ADR 0183 proposal is not an implementation or target-state requirement; - no canonical one-trade-per-`(fromEntityId,toEntityId,itemId)`-per-tick invariant exists, so the participant/item tuple alone cannot be the effect key; - - it inserts one complete `(tenantId, gameInstanceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType=INVENTORY, targetAggregateId)` `tick_effect_guard` storage projection, linked to the root `EffectId` and participant guard identity, for each affected inventory aggregate before moving items between inventories; and - - on any primary-key conflict, it verifies that guard projections for both affected inventories and the corresponding inventory state are complete and consistent; only then is the trade an already-applied no-op. A partial guard set reconciles the original root effect and both participant guard identities rather than being accepted as completion. + - it inserts one complete `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, effectId, rootEffectId, typedOperation, targetAggregateType=INVENTORY, targetAggregateId)` `tick_effect_guard` storage projection, linked to the mutation's persisted root-or-child `EffectId` and its enclosing root lineage, for each affected inventory aggregate before moving items between inventories. The S1/S2 participant-guard uniqueness tuple is `(tenantId, playableStateNamespaceId, effectId, typedOperation, targetAggregateType, targetAggregateId)`; `playableStateNamespaceId` is its canonical partition/key component, while `playableStateScope` is separately persisted immutable and exact-validated policy/routing/authorization/migration-fence evidence. `gameInstanceId`, `regionId`, `regionEpoch`, `tickId`, `effectKey`, and `rootEffectId` are active-runtime, descriptor, timeline, or lineage evidence, not uniqueness dimensions; and + - on any primary-key conflict, it verifies that guard projections for both affected inventories and the corresponding inventory state are complete and consistent; only then is the trade an already-applied no-op. A partial guard set reconciles the original mutation identity, its enclosing root `EffectId`, and both participant guard identities rather than being accepted as completion. diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 28a847560a..b9eaa2b9eb 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -10,7 +10,7 @@ This document defines Entity Management’s runtime model, persistence ownership - Current runtime item/equipment/container mutation RPCs that carry an `effectId` use `entity_mutation_effects` as the domain-local replay table. Entity Management records the applied protobuf response for `{tenantId, effectId}` and returns that stored response on duplicate delivery so `GET`, `DROP`, `PUT`, `TAKE`, `WEAR`, and `REMOVE` do not double-apply after Game Session replay or retry. Requests with a blank `effectId` bypass this table and execute directly; that fallback is current compatibility behavior, not a safe gameplay admission path. This is the current durable effect-replay guard, not a replacement tick-watermark implementation. - The `entitymanagement.mutation.effect.execution{operation,effect_status}` metric distinguishes first apply, replay/no-op, in-progress conflict, reported reuse outcome, and unreadable stored-response outcomes. - This current `{tenantId,effectId}` identity is not the target ADR 0054 participant guard: the replay record persists only the operation/status/payload result and reuse checks only the operation name. It does not yet persist or validate the typed target, namespace/scope/fence, or immutable request digest, and changed operation, target, or request reuse is not yet proven fail-closed. -- The current concurrent first-apply path catches a duplicate-marker `DataIntegrityViolationException` inside the outer replay transaction and then attempts the loser read in that same transaction. PostgreSQL transaction-abort/rollback-only behavior means this is not a reliable replay or conflict result; the target requires a conflict-safe marker insert or isolated marker transaction, followed by real PostgreSQL concurrent first-apply/replay proof. Until then replay readiness remains blocked. +- The current concurrent first-apply path catches a duplicate-marker `DataIntegrityViolationException` inside the outer replay transaction and then attempts the loser read in that same transaction. PostgreSQL transaction-abort/rollback-only behavior means this is not a reliable replay or conflict result; the target requires a conflict-safe marker insert or a same-transaction savepoint around marker handling, preserving marker/mutation atomicity and never isolating marker insertion in a separate transaction. The [Entity Management Operations implementation status](./operations.md#implementation-status) records this local correction under the canonical [Transaction Strategies](../../system-architecture-transactions.md) participant contract. Real PostgreSQL concurrent first-apply/replay proof remains unavailable, so replay readiness remains blocked. - Character updates are also not currently optimistic CAS: `CharacterRepository` increments `version` but updates by row ID without the old-version and tenant predicates or an affected-row conflict check. Concurrent progression/last-login writes can therefore overwrite each other. The target requires tenant- and namespace-bound version CAS with stale-write failure and focused concurrent proof; the current `@Transactional` service methods do not establish that invariant. - Current `jOOQ + Flyway` adoption and focused persistence proof remain implementation work. - The current actor-condition expiry job uses Spring fixed-delay scheduling, with a 30-second default delay after the previous invocation completes, and invokes a global, unbounded delete for rows whose `expires_at` has elapsed, without tenant/namespace/instance predicates or a batch bound. Reads filter expired rows before evaluating state, so expired gameplay effects are not restored. The deletion targets only `actor_active_conditions`; it does not delete the separate `entity_mutation_effects` receipt that `ApplyActorCondition` checks before mutation. No concrete duplicate-application or S2-loss claim is made from this path. The target still requires explicit S1/S2 classification, a replay/restore horizon, dependent-reference/hold checks, a receipt-retention guarantee, a safe watermark, and typed target, request-digest, and concurrency proof under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md); expiry is not itself disposal eligibility. @@ -29,13 +29,13 @@ This document defines Entity Management’s runtime model, persistence ownership - The target persistence design applies tenant- and namespace-bound optimistic version CAS to avoid conflicting updates on the same entity; the current character update path is not proof of that invariant (see Implementation Status). - Entity Management instances are intended to be replaceable workers over authoritative persistent state and documented caches. Item, inventory, containment, and character data that must survive instance loss belongs in the service-owned database rows and cache invalidation model, not as the sole authoritative copy in one process. - Database writes are deferred and batched for ordinary entity updates, not triggered on every gameplay action. The Game Session Service coordinates real-time updates using Redis; the database is normally updated when ticks complete. -- Spatial containment mutations that participate in cross-service effects are the exception: before Entity Management acknowledges a spatial `EffectId` back to Game Session, it must durably flush the effect’s idempotency guard plus the affected containment/container rows for that effect within the same local transaction. A participant acknowledgement must never be emitted for Redis-only staged state. -- Target-state cross-service participant guards use a structured root `EffectId`, typed operation, target aggregate, and immutable request digest; matching retries return the durable result, while an operation, target, or digest mismatch fails closed. This target guard is not the current domain-local replay table described above. +- Spatial containment mutations that participate in cross-service effects are the exception: before Entity Management acknowledges a spatial mutation's persisted `EffectId` (the root `EffectId` for a root effect or the persisted child `EffectId` for a generated child effect) back to Game Session, it must durably flush the effect’s idempotency guard plus the affected containment/container rows for that effect within the same local transaction. A participant acknowledgement must never be emitted for Redis-only staged state. +- Target-state cross-service participant guards follow the owner-declared runtime-family partition: `(tenantId, playableStateNamespaceId)` for S1/S2 or `(tenantId, gameInstanceId)` only for explicitly classified S3, together with the persisted mutation `EffectId`, typed operation, and exact target aggregate. `requestDigest` is separately persisted and exact-validated conflict metadata, not a uniqueness dimension; S1/S2 scope and active-instance evidence are validated separately, and any enclosing `rootEffectId` is lineage and reconciliation context. A mismatch fails closed. This target guard is not the current domain-local replay table described above; see [Transaction Strategies](../../system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory). - The target design reduces write frequency and contention, making optimistic version CAS a natural fit because most entities are updated by only one process at a time and conflicts are rare; it remains target-only until the predicates, affected-row checks, and concurrent proof exist. - Item transfers and other gameplay actions span services but execute within ticks using Redis scripts for rollback. Sagas are reserved for non-gameplay workflows. See [Transaction Strategies](../../system-architecture-transactions.md). - For long-running, non-gameplay workflows such as publishing a game version, this service participates as a domain step in durable publish workflows coordinated by the Game Design Service as described in [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md). - **Target state:** Entity-owned tables carry a `tenantId` column wherever the row is a tenant-isolation boundary, and service methods enforce that tenant predicate; Redis keys mirror this prefix. **Current exceptions:** the live `inventory` and `character_equipment` tables have no `tenant_id` and obtain isolation by joining their `character_id` to `characters.tenant_id`; `crafting_ingredients` has no `tenant_id` and is reached through its tenant-owned `crafting_recipes` parent. The current `CraftingRecipeRepository.findWithIngredientsById` lookup is ID-only, so it does not itself prove a tenant predicate even though tenant-scoped list methods select recipe IDs first. These exceptions and the holder/containment cleanup gaps above mean the target all-table/filtering claim is not current proof. Details are in [Multi-Tenancy](../../system-architecture-multi-tenancy.md). -- Durable playable state that survives runtime replacement is keyed by `(tenantId, playableStateNamespaceId)` plus the applicable domain object identity and is authorized against the separately validated immutable `playableStateScope` and currently active `gameInstanceId`; `gameInstanceId` alone is reserved for explicitly disposable S3 runtime families. At target, S1/S2 durable storage identity is `{tenantId, playableStateNamespaceId, domainObjectId}` and omits both routing scope and `gameInstanceId`. This storage identity is distinct from cross-service effect participant replay/deduplication identity, which uses a structured root `EffectId`, typed operation, exact target aggregate, and immutable request digest. Within that participant record, `playableStateScope`, `gameInstanceId`, and `effectKey` are projection/validation metadata, not participant uniqueness; other service-local idempotency keys remain operation-specific. Only explicitly S3 rows use `gameInstanceId` as part of durable identity. The namespace is resolved by the realm/lifecycle contract and is never inferred from an entity id, Redis key, or caller-supplied remap identifier. See [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md). +- Durable playable state that survives runtime replacement is keyed by `(tenantId, playableStateNamespaceId)` plus the applicable domain object identity and is authorized against the separately validated immutable `playableStateScope` and currently active `gameInstanceId`; `gameInstanceId` alone is reserved for explicitly disposable S3 runtime families. At target, S1/S2 durable storage identity is `{tenantId, playableStateNamespaceId, domainObjectId}` and omits both routing scope and `gameInstanceId`. Cross-service effect participant replay/deduplication follows the owner-declared partition: namespace-backed S1/S2 uses `(tenantId, playableStateNamespaceId)`, while explicitly classified S3 uses `(tenantId, gameInstanceId)`. For S1/S2, `playableStateScope` and active `gameInstanceId` are separately validated evidence, not participant uniqueness; the explicit S3 `gameInstanceId` is part of its partition. `requestDigest` is separately exact-validated conflict metadata, not a uniqueness dimension. Other service-local idempotency keys remain operation-specific. The namespace is resolved by the realm/lifecycle contract and is never inferred from an entity id, Redis key, or caller-supplied remap identifier. See [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) and [Transaction Strategies](../../system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory). - `playableStateScope` is accepted only as the realm/lifecycle owner's authoritative resolved snapshot or attestation. Callers cannot select or derive it, and Entity validates the exact immutable `{playableStateNamespaceId, playableStateScope}` pair before create or update; a scope change for an existing namespace is rejected rather than reinterpreting or splitting durable state. The `{tenantId, playableStateNamespaceId, characterId}` key is the stable actor storage identity, while `{tenantId, accountId, playableStateNamespaceId}` is the auto-provision actor-uniqueness identity; the separate operation replay guard uses `{tenantId, playableStateNamespaceId, accountId, autoProvisionRequestId}` and binds the exact `mutationDigest`. Neither identity reinterprets scope. `gameInstanceId` remains only the active-instance authorization fence. See [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md). - Gameplay-facing gRPC endpoints do not parse JWT tokens. The Game Session Service injects identity context using `SessionContext` and may request a new JWT from the Account Service if a player's roles change. It does not validate tokens for gameplay. Traffic between services still uses mutual TLS certificates as outlined in the [Security Architecture](../../system-architecture-security.md). - Design-time writes are a separate surface: @@ -73,7 +73,7 @@ Entity Management must classify its runtime persistence surface for cutover and - `S3` entity-owned ephemeral state: - synthetic room-ground containers and their contents keyed by `(tenantId, gameInstanceId, roomInstanceId)`; - transient containment, encounter-specific entities, corpses, summons, or equivalent rows whose lifecycle is tied to the source `gameInstanceId`; - - Target-only `entity_tick_state` watermark rows keyed by `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, targetAggregateType, entityId)` for the concrete instance/region timeline; `playableStateScope` is separately persisted and exact-validated evidence, not a key dimension. No such live table or projection is currently implemented: the live schema has `entity_mutation_effects` for narrower effect/operation replay instead. Entity exact-validates the owner-resolved `playableStateNamespaceId` and immutable `playableStateScope` pair before reading or writing this future disposable watermark; neither value is inferred from an entity or instance id. Replay reads that exact row and compares `(last_region_epoch, last_tick_id)`, while durable S1/S2 effect replay continues to use the stable namespace plus structured `EffectId`/operation/target/request-digest guard rather than this watermark; + - Target-only `entity_tick_state` watermark rows keyed by `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, targetAggregateType, entityId)` for the concrete instance/region timeline; `playableStateScope` is separately persisted and exact-validated evidence, not a key dimension. No such live table or projection is currently implemented: the live schema has `entity_mutation_effects` for narrower effect/operation replay instead. Entity exact-validates the owner-resolved `playableStateNamespaceId` and immutable `playableStateScope` pair before reading or writing this future disposable watermark; neither value is inferred from an entity or instance id. Replay reads that exact row and compares `(last_region_epoch, last_tick_id)`, while current durable effect replay uses the `{tenantId, effectId}` table with operation-name-only matching; the namespace/scope/fence, typed-target, and request-digest guard remains target-only; - any row family explicitly documented as instance-scoped only. ### Conservative Current Implementation Inventory @@ -360,7 +360,7 @@ Equipment is intentionally not modeled as "just another bag position": - The complete-schema and fail-closed behavior in the following contract is target state, not current implementation; current missing-schema and unknown-layout bootstrap fallback gaps are recorded in the [Entity Management README](./README.md) and [Item & Equipment Balancing Tools](../game-design-service/item-equipment-balancing.md#target-equipment-schema-requirements). - Game Design owns the complete published equipment vocabulary/body-layout schema and its digest. Entity Management consumes that exact schema for occupancy and compatibility checks; all missing, partial, or mismatched vocabulary or mapping evidence is rejected and validation fails closed. It does not provide a platform-global slot fallback. Replacement cutover remaps bindings only through the owner-validated mapping contract; profiles materialize authored equipment content rather than supplying runtime defaults. See [ADR 0127](../../decisions/adr-0127-game-authored-equipment-layouts-with-fail-closed-publication.md). -The target inventory/equipment operation context for a durable holder or binding is `{tenantId, playableStateNamespaceId, playableStateScope, gameInstanceId, holderRef, itemInstanceId, itemDefinitionId, equipmentBindingId?, slotKey?}`, with one typed `holderRef` for each source, destination, or equipment owner required by the operation. A holder reference is a closed tagged union: character inventory or equipment carries `CHARACTER {characterId}`; NPC, pet, or summon ownership carries `ACTOR {actorId}`; an ordinary bag, chest, corpse, bank, vendor stock, or nested holder carries `CONTAINER {containerInstanceId}`; and room-ground storage carries `ROOM_GROUND {roomInstanceId, containerInstanceId}`. `characterId` is therefore required only for character-owned inventory or equipment and must not be fabricated for another holder kind. For namespace-backed S1/S2 inventory, character, and equipment state, durable storage identity is `{tenantId, playableStateNamespaceId, ...domainObjectId}` and omits both `playableStateScope` and `gameInstanceId`; those two values are validated separately as immutable routing/authorization evidence and the active-instance fence. Cross-service effect participant replay/deduplication identity is separate and uses a structured root `EffectId`, typed operation, exact target aggregate, and immutable request digest; `playableStateScope`, `gameInstanceId`, and `effectKey` are projection/validation metadata, not participant uniqueness. Other service-local idempotency keys remain operation-specific. Explicitly instance-scoped S3 holders instead include `gameInstanceId` in durable identity. Future proto and OpenAPI surfaces must carry the same typed holder-reference union consistently, but current surfaces do not yet carry this complete operation context on every inventory/equipment read or mutation, so this is a target contract only: this ADR parcel does not add wire fields, regenerate protos, or change runtime lookup behavior. +The target inventory/equipment operation context for a durable holder or binding is `{tenantId, playableStateNamespaceId, playableStateScope, gameInstanceId, holderRef, itemInstanceId, itemDefinitionId, equipmentBindingId?, slotKey?}`, with one typed `holderRef` for each source, destination, or equipment owner required by the operation. A holder reference is a closed tagged union: character inventory or equipment carries `CHARACTER {characterId}`; NPC, pet, or summon ownership carries `ACTOR {actorId}`; an ordinary bag, chest, corpse, bank, vendor stock, or nested holder carries `CONTAINER {containerInstanceId}`; and room-ground storage carries `ROOM_GROUND {roomInstanceId, containerInstanceId}`. `characterId` is therefore required only for character-owned inventory or equipment and must not be fabricated for another holder kind. For namespace-backed S1/S2 inventory, character, and equipment state, durable storage identity is `{tenantId, playableStateNamespaceId, ...domainObjectId}` and omits both `playableStateScope` and `gameInstanceId`; those values are validated separately as immutable routing/authorization evidence and the active-instance fence. Cross-service effect participant replay/deduplication follows the owner-declared partition: S1/S2 uses `(tenantId, playableStateNamespaceId)`, while explicitly classified S3 uses `(tenantId, gameInstanceId)`. `requestDigest` is separately exact-validated conflict metadata, not a uniqueness dimension; for S1/S2, `playableStateScope` and active `gameInstanceId` are validation evidence rather than participant uniqueness. Other service-local idempotency keys remain operation-specific. Explicitly instance-scoped S3 holders include `gameInstanceId` in durable identity. Future proto and OpenAPI surfaces must carry the same typed holder-reference union consistently, but current surfaces do not yet carry this complete operation context on every inventory/equipment read or mutation, so this is a target contract only: this ADR parcel does not add wire fields, regenerate protos, or change runtime lookup behavior. See [Transaction Strategies](../../system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory) for the canonical participant-guard contract. This keeps the platform compatible with games that need unusual body plans or attachment models such as horns instead of hands, asymmetric limbs, species-specific slot topologies, or non-humanoid wearable layouts. diff --git a/design/architecture/microservices/game-design-service/modding-framework.md b/design/architecture/microservices/game-design-service/modding-framework.md index 2f254424d4..91d5767eb1 100644 --- a/design/architecture/microservices/game-design-service/modding-framework.md +++ b/design/architecture/microservices/game-design-service/modding-framework.md @@ -178,7 +178,7 @@ The exact Trigger Identity, evaluated-descriptor recovery, Command-Handoff Ident - Each plugin trigger has one logical evaluation per full applicable Trigger Identity. Before `EVALUATED_COMMITTED`, infrastructure recovery may re-enter the DSL only under that same identity and must converge on the same durable work item and command-child identities; after that boundary, recovery replays durable descriptors without re-entering the graph. `scriptEventId` is one field of Trigger Identity, not the complete key. Each resolved live handler invocation has one `script_event_audit` row, and the current legacy materialized dry-run/test handler path likewise records one handler row for its terminal result. Target ADR 0114 command-plan previews use the isolated preview result/audit surface or return the result directly and do not create a handler audit row; command attempts and outcomes are child handoff records keyed by the complete Command-Handoff Identity. - Recurring and advisory plugin timers such as `onInterval` (or an advisory `onTimerExpire`) are **best-effort** under their declared recovery policy. Individual firings may be skipped or delayed when per-script quotas, per-tenant budgets, or cluster ceilings are reached, and skipped firings are not backfilled beyond bounded `COALESCE_ONE` behavior. A correctness-bearing one-shot timer instead persists durable intent outside Redis; physical execution may be at least once and replay-safe, while the same logical identity converges to one logical terminal outcome. -- Recurring/advisory plugin logic must therefore tolerate missed or delayed events (for example, by recomputing from current world state rather than assuming every interval executed). Every emitted command remains deduplicated and replay-selectable at child handoff under the complete Command-Handoff Identity: complete source runtime scope, optional `targetGameInstanceId`, `targetPlayableStateScope`, `targetRegionId`, and `targetRegionEpoch` only when the command targets a distinct runtime scope, persisted `automationDispatchId`, and deterministic `commandOrdinal`; same-instance handoffs omit every optional target field. The complete parent Trigger Identity, including plugin `bindingId` when applicable, is retained for correlation only. Downstream authoritative effect idempotency instead uses the stable root `EffectId`, typed operation, and exact target aggregate, with the immutable request digest stored and compared; a conflicting operation, target, or digest fails closed. `automationDispatchId` is reused across retries but is not globally unique, and `scriptEventId` alone is insufficient for fan-out commands; follow the [canonical scripting contract tables](../../system-architecture-scripting-normative-contract-tables.md). +- Recurring/advisory plugin logic must therefore tolerate missed or delayed events (for example, by recomputing from current world state rather than assuming every interval executed). Every emitted command remains deduplicated and replay-selectable at child handoff under the [canonical Command-Handoff Identity](../../system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state), whose source and applicable distinct target namespace/region identity is separate from the server-derived scope evidence; same-instance handoffs omit every optional target field. The complete parent Trigger Identity, including plugin `bindingId` when applicable, is retained for correlation only. Downstream authoritative effect idempotency instead uses the persisted mutation `EffectId` (the root `EffectId` for a root mutation or the generated child's persisted `EffectId` for a child mutation), under the owner-declared participant-guard partition (S1/S2: tenant plus `playableStateNamespaceId`; explicitly classified S3: tenant plus `gameInstanceId`), with separately validated `playableStateScope` and active-instance fence evidence, together with the complete owner-defined participant binding, typed operation, exact target aggregate, and immutable request digest stored and compared. Any participant-binding, operation, target, or digest conflict fails closed; the canonical [Transactions guard contract](../../system-architecture-transactions.md) and [ADR 0069](../../decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md) own the complete binding and proof. `automationDispatchId` is reused across retries but is not globally unique, and `scriptEventId` alone is insufficient for fan-out commands. - Before plugin work is evaluated and again before handoff, Automation revalidates the captured exact Game Session `(scriptPatchVersion, scriptPinEpoch)` tuple against current authoritative state for the same `(tenantId, gameInstanceId)` runtime scope, together with the exact `(pluginId, pluginVersionId, bindingId)` and scoped Automation-owned `(pluginActivationEpoch, lifecycleRevision)` fence; see [Scripting Contracts §8](../../system-architecture-scripting-contracts.md#8-plugin-version-fencing-and-control-plane-scope). Already-terminal work is unaffected; no new admission proceeds without fresh signer-policy and Game Session authority, and immediately before any final side effect the applicable execution owner revalidates the exact plugin provenance, current activation/lifecycle, component policy, capability grant, signer/publication evidence, `(pluginActivationEpoch, lifecycleRevision)`, and Game Session tuple. Routine component-policy reclassification uses the captured admission decision for already-admitted work and does not invalidate it; final-fence rejection or containment of admitted work requires the independent component-revocation fence and explicit audited emergency workflow. Missing, stale, contradictory, or unavailable authority remains a separate fail-closed condition under the stage-specific dispositions below. Specifically unavailable signer policy/evidence retains `signer_policy_unavailable` on its stage-specific response/audit surface, while an unavailable authoritative runtime/fence read keeps unresolved work fenced and retryable as `authority_unavailable`. A present-but-different activation epoch fails closed with `plugin_activation_epoch_mismatch`; a proven plugin tuple/binding or lifecycle-evidence mismatch uses `plugin_binding_mismatch`; signer or revocation mismatches remain durably terminal/ineligible with their specific canonical dispositions. See [Scripting Runtime Execution](../../system-architecture-scripting-runtime-execution.md#version-fencing-and-rollback-safety), the [scripting outcome contracts](../../system-architecture-scripting-normative-contract-tables.md#table-2-script_event_audit-stages-and-outcomes), and the [Command-Handoff Identity](../../system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state) owner contracts. These guarantees ensure that plugins do not rely on stronger delivery semantics than the underlying scripting engine provides and that their behavior remains predictable under load. @@ -354,7 +354,7 @@ Design-time publication and runtime activation are separate: - **Disable after drain** – reserves a same-epoch `targetLifecycleRevision = current lifecycleRevision + 1` for `DRAINING` without making it current, installs that exact target through Game Session, and waits for durable acknowledgement before committing the Automation owner state/history/revision. Once `DRAINING` is committed, only already-admitted work whose winning admission/fence CAS durably committed the immediately preceding `ENABLED` revision before the durable Automation-owned `DRAINING` admission barrier was created may complete within the bounded drain policy; capture or observation alone is insufficient. At bounded completion or forced timeout, it independently reserves `targetPluginActivationEpoch = current pluginActivationEpoch + 1` and `targetLifecycleRevision = current lifecycleRevision + 1` from the committed owner row for `DISABLED`, installs and durably acknowledges that exact target through Game Session, then commits the Automation owner state/history/epoch/revision. New triggers are rejected once draining begins and cleanup remains asynchronous. See [ADR 0119](../../decisions/adr-0119-epoch-fenced-per-instance-plugin-activation.md) for the single canonical drain exception rather than repeating its full fence contract here. - Updating a plugin involves setting a new `pendingVersionId`, loading and validating the new plugin graphs and bindings, reconciling plugin-owned timers and other derived scheduler state, and then atomically switching `activeVersionId` if validation succeeds. If validation or activation-state reconciliation fails, the new version is marked `FAILED`, `activeVersionId` remains unchanged, and triggers for the failed version are rejected at admission with an appropriate `finalOutcome` (for example, `version_unavailable` or `plugin_version_failed`). -Plugin triggers share the same Trigger Identity and `scriptEventId` lifecycle as regular scripts. Pre-handler admission outcomes are recorded in `script_event_ingress_audit` and create no handler row. Each resolved live handler invocation has one `script_event_audit` row with the required Trigger Identity fields (including `tenantId`, `gameInstanceId`, and for gameplay/runtime triggers `regionEpoch`) plus `pluginId` / `pluginVersionId` and stage-aware outcome fields (`finalStage`, `finalOutcome`, `finalReason`) so operators can correlate plugin behavior with publish and enable/disable operations and still distinguish “DSL evaluated” from “accepted into tick queues”. The current legacy materialized dry-run/test handler path also records one handler audit row for its terminal result. Target ADR 0114 command-plan previews instead use the isolated preview result/audit surface or direct authorized result path and never create a handler row. Per-command acceptance, retry, and downstream outcomes belong in handoff child records keyed by the complete Command-Handoff Identity (source/target runtime scope plus `automationDispatchId` and `commandOrdinal`), not by dispatch ID alone and not in extra handler audit rows. The parent Trigger Identity and `outboxWorkItemId` remain correlation-only. +Plugin triggers share the same Trigger Identity and `scriptEventId` lifecycle as regular scripts. Pre-handler admission outcomes are recorded in `script_event_ingress_audit` and create no handler row. Each resolved live handler invocation has one `script_event_audit` row with the required Trigger Identity fields: `tenantId` is required for every handler, while `gameInstanceId` is required for instance-bound handlers and omitted for tenant-readiness `onLoad` (see normative [Table 1](../../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields)). Gameplay/runtime handlers also carry `playableStateNamespaceId` and `regionEpoch`, plus separately persisted exact-validated `playableStateScope` policy/routing/authorization/migration-fence evidence, `pluginId` / `pluginVersionId`, and stage-aware outcome fields (`finalStage`, `finalOutcome`, `finalReason`) so operators can correlate plugin behavior with publish and enable/disable operations and still distinguish “DSL evaluated” from “accepted into tick queues”. The current legacy materialized dry-run/test handler path also records one handler audit row for its terminal result. Target ADR 0114 command-plan previews instead use the isolated preview result/audit surface or direct authorized result path and never create a handler row. Per-command acceptance, retry, and downstream outcomes belong in handoff child records keyed by the complete Command-Handoff Identity (source/target runtime scope plus `automationDispatchId` and `commandOrdinal`), not by dispatch ID alone and not in extra handler audit rows. The parent Trigger Identity and `outboxWorkItemId` remain correlation-only. At handler admission, before evaluation or handoff, a plugin handler must prove and capture `breakerState=CLOSED` for the exact active `pluginVersionId` and runtime scope. That captured admission decision remains valid through evaluation and handoff; a later breaker trip blocks only newly resolved handlers and does not retroactively cancel accepted work. A disabled breaker is recorded as the bounded handler admission outcome above; it cannot be inferred from or folded into the lifecycle `pluginState`. @@ -389,7 +389,7 @@ Handler identity and ordering: - Trigger Identity, dedupe, audit, quota attribution, timer ownership, and drain/disable cleanup must retain `bindingId` alongside `pluginId` and `pluginVersionId` whenever the unit of work is binding-scoped. - Runtime ordering delegates to the shared [canonical stable handler-order identity and field-wise comparator](../../system-architecture-scripting-dsl-reference-and-lifecycle.md#canonical-stable-handler-order-identity): the total key is `(orderIndex, normalized finite handler-kind rank, canonical stable handler-order identity)`, with `SCRIPT` before `PLUGIN` by default unless an operator-controlled policy places `PLUGIN` ahead; designers cannot control that rank. For plugin handlers, that shared identity includes `(pluginId, pluginVersionId, bindingId)`; `bindingId` is the immutable manifest binding identity. Duplicate identical normalized total keys are rejected before `handlerSequence` assignment. - For non-exclusive fan-out, Automation assigns a durable `handlerSequence` from that order and preserves it through handler work, command handoff, and final application. Plugin execution priority and worker timing do not override semantic handler order. -- At most one binding in the complete resolved handler set for the full applicable [Trigger Identity scope](../../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) may have `requiresExclusiveEvent=true`. For instance-bound events, that scope includes `tenantId`, `gameInstanceId`, `playableStateScope`, `regionId`, `regionEpoch`, concrete target identity, `eventType`, and `eventSchemaVersion` as applicable. Tenant-readiness `onLoad` uses the explicit pre-instance exception: it is tenant-scoped and omits instance, playable-state, region, and entity fields. An authorized exclusive binding is selected before fan-out and becomes the sole handler; no core-script or plugin sibling runs before or after it, and failure does not cause sibling fallback. +- At most one binding in the complete resolved handler set for the full applicable [Trigger Identity scope](../../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) may have `requiresExclusiveEvent=true`. For instance-bound events, that scope includes `tenantId`, `gameInstanceId`, `playableStateNamespaceId`, `regionId`, `regionEpoch`, concrete target identity, `eventType`, and `eventSchemaVersion` as applicable. `playableStateScope` remains separately persisted and exact-validated as policy/routing/authorization/migration-fence evidence, not an identity or exclusivity-uniqueness dimension. Tenant-readiness `onLoad` uses the explicit pre-instance exception: it is tenant-scoped and omits instance, playable-state, region, and entity fields. An authorized exclusive binding is selected before fan-out and becomes the sole handler; no core-script or plugin sibling runs before or after it, and failure does not cause sibling fallback. - Game Design rejects publish-time-known multiple-exclusive or unauthorized plugin claims against the exact `baseVersionId`. Automation & Scripting re-checks the complete resolved base-script plus active-plugin set during instance activation because active selections and bindings from different declared scopes may converge on the same concrete target. - Plugin exclusivity requires an explicit operator grant and audit evidence bound to the exact `pluginVersionId`, `bindingId`, target policy scope, and granting actor. Manifest intent alone grants no exclusivity. Automation must revalidate the current exclusivity grant both when activating a plugin and when resolving handlers; it persists the grant version and canonical grant digest with the activation/resolution evidence. Missing, stale, revoked, narrowed, or contradictory grant evidence fails closed at that boundary. @@ -449,9 +449,9 @@ Plugin rollback/disable/revocation flows must also invoke Automation's `CancelPe Rollback/disable/revocation flows must also reconcile durable plugin-owned timers: -- The timer-reconciliation operation identity includes `` plus the same `controlPlaneRequestId` used by the surrounding control-plane operation. Each schedule is a separate durable child reconciliation identified by that full tuple; one parent control-plane request must not collapse distinct schedules into one child result. Each owner row retains its own `pluginVersionId`; the operation-level displaced and optional replacement owner versions must not be inferred from whichever row happens to be read first. +- The timer-reconciliation operation identity includes `` plus the same `controlPlaneRequestId` used by the surrounding control-plane operation. `playableStateScope` is retained separately as exact-validated policy/routing/authorization/migration-fence evidence and is excluded from this identity, schedule uniqueness, and deduplication. Each schedule is a separate durable child reconciliation identified by that full tuple; one parent control-plane request must not collapse distinct schedules into one child result. Each owner row retains its own `pluginVersionId`; the operation-level displaced and optional replacement owner versions must not be inferred from whichever row happens to be read first. - For rollback or repin to a replacement `pluginVersionId`, any timer or interval owned by the displaced version must follow the scheduler continuity contract: on the default, reset, or incompatible path, reconciliation fences and tombstones the displaced owner before creating or confirming the replacement owner entry, as one atomic durable result or a resumable idempotent operation; a valid explicit typed-compatible continuity transition instead rewrites the existing stable row in place with the target ownership and pin metadata and creates no replacement row. The operation must persist and reuse the same `controlPlaneRequestId` across the applicable ownership update and displaced-row retirement, while each schedule child retains its own `scheduleDefinitionId` and full reconciliation identity; it must not generate a new request identity per timer or phase. No normal scheduling or trigger admission resumes for the plugin until ownership and durable timer reconciliation complete; queued-work cancellation remains bounded asynchronous cleanup and is not a resumption gate because exact pin/runtime fences remain authoritative. -- For disablement or revocation without a replacement version, the control plane must atomically fence admission and tombstone the displaced timer owner without creating a replacement entry, as one durable result or a resumable idempotent operation. It must persist and reuse the same `controlPlaneRequestId` across fencing and tombstoning, while each schedule child remains keyed by ``; no normal scheduling or trigger admission resumes for the disabled or revoked plugin until durable timer tombstoning/reconciliation completes. Queued-work cancellation must be launched and tracked as bounded asynchronous cleanup under the same surrounding operation and remains non-gating because the exact plugin/runtime fence remains authoritative. +- For disablement or revocation without a replacement version, the control plane must atomically fence admission and tombstone the displaced timer owner without creating a replacement entry, as one durable result or a resumable idempotent operation. It must persist and reuse the same `controlPlaneRequestId` across fencing and tombstoning, while each schedule child remains keyed by ``; its separately persisted exact-validated `playableStateScope` evidence is not part of the child key. No normal scheduling or trigger admission resumes for the disabled or revoked plugin until durable timer tombstoning/reconciliation completes. Queued-work cancellation must be launched and tracked as bounded asynchronous cleanup under the same surrounding operation and remains non-gating because the exact plugin/runtime fence remains authoritative. - Canceling queued work items alone is insufficient; otherwise an old plugin version could continue minting new timer-driven triggers after disablement or rollback. - If a newer plugin version preserves the same schedule, carry-forward is allowed only when both the old and new definitions explicitly declare continuity for the same stable logical key and typed compatibility holds for interval kind/cadence, trigger conditions, handler identity, target and binding, playable scope, dry-run namespace, and runtime ownership/fences. If either the source or target continuity declaration is absent or false, reconciliation uses the reset/tombstone path. On that reset/incompatible path, reconciliation must fence and tombstone the old owner before creating or confirming the new `pluginVersionId` entry; on a valid continuity path, it rewrites the existing stable row in place with the target ownership and pin metadata and creates no replacement row. Both paths must explicitly rewrite ownership without reusing old trigger claims. `scheduleSemanticsHash` remains diagnostic evidence only: equality does not grant continuity and inequality does not deny an otherwise valid declaration. @@ -468,7 +468,7 @@ For operator verification during rollback, disablement, or signer revocation, us Live plugin executions (`isDryRun=false`) participate in the same observability pipeline as live core scripts and use shared identifiers and live metric families. The current legacy materialized dry-run/test handler path records a terminal `finalStage=DSL_EVAL`, `finalOutcome=dry_run_completed`, and `finalReason=dry_run_no_handoff` in `script_event_audit`; target ADR 0114 command-plan previews remain isolated to the preview result/audit surface or direct authorized result path. Preview/test executions use the corresponding test-only metric families and do not increment live families: -- Each resolved live plugin handler is recorded in `script_event_audit` with the required Trigger Identity fields (including `tenantId`, `gameInstanceId`, and for gameplay/runtime triggers `regionEpoch`), plus `pluginId` / `pluginVersionId` and stage-aware outcome fields (`finalStage`, `finalOutcome`, `finalReason`). Pre-handler admission outcomes are recorded in `script_event_ingress_audit` and create no handler row. +- Each resolved live plugin handler is recorded in `script_event_audit` with the applicable required Trigger Identity fields, including `tenantId` for every handler and `regionEpoch` for gameplay/runtime events; `gameInstanceId` is required for instance-bound handlers and omitted for tenant-readiness `onLoad` (see normative [Table 1](../../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields)). The audit also records `pluginId` / `pluginVersionId` and stage-aware outcome fields (`finalStage`, `finalOutcome`, `finalReason`). Pre-handler admission outcomes are recorded in `script_event_ingress_audit` and create no handler row. - The shared Automation trigger, skip, drop, sandbox-failure, and runtime metric families expose plugin behavior alongside core automation using only the finite `script_kind`, `plugin_origin`, `event_class`, and other bounded dimensions defined by [normative Table 4](../../system-architecture-scripting-normative-contract-tables.md#table-4-metrics-label-matrix). Exact plugin and version identities never become Prometheus labels. Logging & Admin may surface exact plugin and version identities only through explicitly approved audit records, protected logs, named span families whose documented incident query requires them, and authorized control-plane or diagnostic queries. Trace use follows [ADR 0167](../../decisions/adr-0167-allowlisted-sensitive-trace-attributes.md): producer-side span-family allowlists, least-privilege environment-scoped access with audited queries, finite profile-defined retention, and declared export/privacy/erasure handling apply; availability in all logs, traces, or queries is not implied. On those approved surfaces, operators can: diff --git a/design/architecture/microservices/game-design-service/operations.md b/design/architecture/microservices/game-design-service/operations.md index 3ad84d632c..1a1ebe9174 100644 --- a/design/architecture/microservices/game-design-service/operations.md +++ b/design/architecture/microservices/game-design-service/operations.md @@ -6,6 +6,26 @@ - Logging, metrics, and tracing follow the standard [Logging & Monitoring](../../system-architecture-logging-monitoring.md) pipeline. - Publishing a game version is coordinated through the Temporal-backed `publish` workflow family. The synchronous `PublishVersion` API now requires a stable `publish_request_id`, while the durable workflow performs version metadata creation, participant digest gating, release attestation, and publish reconciliation under one caller-visible workflow identity. See [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md) for the overall flow. +### Publish request identity and digest binding + +The target publish contract binds the stable `publish_request_id` to one canonical request digest. Game Design normalizes the complete preallocation caller intent, including `tenantId`, publish type, `notes`, and any other actual request inputs, before computing and durably recording that digest with the workflow/attempt identity. The owner-allocated `versionId` is not an input to that original digest because it does not exist at request admission; after allocation, it is immutable attempt/result evidence bound durably to the same workflow identity and exact replay/readback. A retry with the same `publish_request_id` and the same preallocation-intent digest may attach to or replay the existing workflow and recorded outcome. Reuse of that identity with a different digest is an identity conflict: it must fail closed without executing the new request or returning the prior outcome as though the requests matched. This is the Game Design adopter mapping of [ADR 0078](../../decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md). + +**Current implementation status:** the full-version `publish_attempt` stores and exact-validates `publicationDigestRequest/v1`, binding tenant, allocated version scope, stable publish request, and derived workflow identity. That is the owner-to-owner publication-read binding and intentionally excludes notes and content. Game Design does not yet persist and compare the separate preallocation control-plane content digest that binds notes and every other caller input before version allocation. Temporal `AlreadyStarted` handling can therefore attach a changed-notes request to the same workflow identity even though its publication-read digest still matches. The current implementation proves the scoped owner-read binding, not the target different-control-plane-content conflict behavior. + +### Publication terminality and attempt ownership + +The publication artifact/release-bundle state, allocated version state, participant/release evidence, and publish-attempt terminal state must commit atomically in one Game Design owner-local transaction. If the workflow boundary cannot provide that transaction, the adopter must use an explicit durable state machine with readback reconciliation; it must never expose `SUCCEEDED` until the artifact and version commit is durably readable and bound to the same immutable request and attempt evidence. A terminal attempt is therefore not an acknowledgement that a separate transaction was started: it is the commit/readback proof of the publication state. + +**Current implementation status:** full-version publication reserves its Draft version and PENDING attempt in one owner-local transaction. After participant reads and object export, its final owner-local transaction records participant evidence, artifact state, release bundle, Published version, verified digests, and the SUCCEEDED attempt together. An ambiguous final commit is resolved by exact attempt/version/bundle/artifact readback rather than an independent terminal-success transaction. This implemented success path is behind the required participant digest gate: ordinary full-version requests currently cannot reach it because Game Logic rejects the required full-version participant request without an owner-local manifest/provenance digest. The canonical participant gate and current availability are documented in [Version Control](./version-control.md#owner-to-owner-digest-authorization-and-tenant-identity); script-patch publication does not require the Game Logic participant. The remaining gap is the external phase: participant collection and mutable object-key export occur before that final transaction without a durable external-phase owner, private candidate namespace, or export deduplication. Same-request retries can therefore race before the final Game row lock; a late exporter can overwrite bytes after another attempt's release attestation, while definite-failure cleanup can race an active exporter. The final local transaction does not prove safe external-write ownership, cleanup, or ambiguous object-store recovery. + +The target attempt record must immutably bind the normalized preallocation request digest, workflow/request identity, allocated version, artifact/release identity, and owner evidence. Every attempt transition must CAS both the expected status and monotonic attempt revision; only the still-current attempt owner may publish a terminal result. Failure cleanup may delete or mark provisional state only when it conditionally owns the same still-current nonterminal attempt and the target has not been won or published. Same-identity/same-digest retries must read back and replay the existing state; a different digest, stale revision/status, or contradictory artifact/version readback fails closed. Focused proof must cover crashes before and after each commit/readback boundary, concurrent exact retries, different-digest reuse, and a losing failure cleanup racing a winning publisher. + +### External artifact recovery + +The target publication boundary treats object-store export as a durable candidate operation: persist `STAGED` export intent before any write, retain a deterministic candidate manifest or incremental durable key evidence, make writes and deletes idempotent, and use a durable cleanup retry/outbox with exact object/readback verification. An ambiguous external result remains nonterminal and reconciliation-required until the candidate and release state are proven; it must not be reported as terminal `FAILED` merely because a storage call timed out. `version_asset_artifact` and the immutable release attestation remain the Game Design authorities; object-store listings alone cannot authorize publication or purge. + +**Current implementation gap:** `AssetExportServiceImpl` writes directly to S3-compatible storage before the artifact row receives the exported manifest. If an asset or manifest write fails, `VersionPublishCommandServiceImpl` has no manifest to record or clean up; if later cleanup fails, it is only logged. `VersionPublishCommandServiceImpl` normally records terminal `FAILED` and returns the attempt snapshot for publication failures; `TemporalVersionPublishActivitiesImpl` catches only `PendingReconciliationException` and returns `PENDING`. A partial export before manifest persistence can therefore lack durable cleanup and failure evidence. The current direct-prefix implementation is not proof of the target `STAGED`/candidate/reconciliation contract described in [Asset Storage](./asset-storage.md). + ## Local Development Notes `TestDataSeeder` populates a demo game, template, revision and version only when explicit smoke/runtime seeding is enabled through deployment config (`FIREMUD_SMOKE_SEED_DEMO_RUNTIME_ENABLED=true` in the local Compose smoke stack). Run `services/game-design-service/smoke-test.sh` to verify both REST and gRPC endpoints. The lightweight maintained application smoke now lives under `src/test/java/integration`; the old disabled GHCR-based cross-service placeholder was removed because it did not prove a meaningful current contract. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 8881e832b5..921444e405 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -20,8 +20,8 @@ Current cross-seam security status is also blocked: Account's runtime membership - Publishing a version creates an immutable snapshot identified by `version_id`. Script-only fixes use a `scriptPatchVersion` tied to a `baseVersionId` so minor automation updates can go live without republishing all assets. -- **Target state:** To provide Git-style history, revisions will be grouped under explicit branches and commits stored in a durable Game Design history model. No branch/commit tables or current APIs exist in the first slice; current history is limited to service-owned revision/version rows and publish metadata. -- **Target state:** A future service contract may expose branch creation and commit-history reads; no such branch/commit APIs are currently exposed by the Game Design proto/service. Canonical multi-branch merge semantics require an explicit validated conflict contract. +- **Target state:** To provide Git-style history, revisions will be grouped under explicit durable branches and commits stored in the Game Design history model. This branch/commit model is not implemented by the current schema or service; current history is limited to service-owned revision/version rows and publish metadata. +- **Target state:** A future service contract may expose branch creation and commit-history reads, but no such branch/commit APIs are currently exposed by the Game Design proto/service. The current proto exposes version-scoped revision, publication, and version-read APIs instead. Canonical multi-branch merge semantics require an explicit validated conflict contract. - Any future external Git webhook or repository integration must submit changes through Game Design-owned revision APIs and must not become a second content authority. ### History and Provenance Across Services @@ -29,8 +29,7 @@ Current cross-seam security status is also blocked: Account's runtime membership The Game Design Service is the canonical history store for world and entity content even though domain services own the runtime templates: -- Each revision and commit references concrete domain objects (rooms, regions, - NPCs, items, templates) via stable identifiers maintained by the owning domain services. +- Current Game Design revision rows reference concrete domain objects (rooms, regions, NPCs, items, templates) through stable identifiers maintained by the owning domain services. Target durable commits will group those revisions and retain their domain-object references in the branch/commit history model; that branch/commit model and its APIs are not implemented, while current version-scoped revision history remains available through the existing revision/version surfaces. - **Target state:** During authoring, design tools apply revisions incrementally to domain services’ **Draft** template rows via idempotent design APIs bound to the complete commit/revision identity and affected-epoch set. Draft template graphs in World Management, Entity Management, and related services are then the authoritative snapshots of world and entity data for each version. In this document, a **remote `Draft` state** means the authoritative Game Design `GetVersionState` response for the target `(tenantId, versionId)` reports `versionState=DRAFT`; it does not mean that a remote service-layer read proves a WMS transaction is serialized with publication. - **Current first slice:** `SaveRevision` optionally calls World Management to apply a mutation and only afterward unconditionally inserts the Game Design revision; Game Design has no matching deduplication lookup or uniqueness constraint. This ordering is therefore not idempotent shared-Draft proof; the current partial-application and retry gap is recorded in Implementation Status. - **Target state:** When a version is published, the service coordinates the durable Temporal `publish` workflow that validates and finalizes the existing Draft data in each domain service and transitions the version to Published as described in [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md). Full-version publication is not satisfied by a short synchronous `common-saga`; that substrate is limited to caller-owned retry/compensation operations that do not make a release publish-complete. No separate design database is copied into domain services at publish time. **Current implementation:** the Temporal-disabled synchronous fallback remains active and does not establish that durability contract. The former Automation admin-guard denial is closed by the distinct Game Design workload peer and exact publication-read guards, but the Temporal-enabled path is still not proved end to end because Automation's full-version content selection remains tenant-wide and live mounted-certificate, activity, and multi-version proof remain absent. @@ -41,7 +40,7 @@ content even though domain services own the runtime templates: - Domain services do not maintain their own commit histories; they expose only the current and historical versioned templates keyed by `(tenantId, versionId)`. -To audit current history for a room, NPC, or item, contributors make a best-effort audit by querying the Game Design Service’s revision/version rows and correlating those revisions with the owning domain’s versioned templates and, where available, its applied-revision ledger (currently World Management’s ledger; Entity Management’s ledger remains future work). This cross-service view is not a canonical branch/commit audit because synchronized branch/commit read APIs do not exist yet. **Target state:** once the durable branch/commit model and synchronized read APIs exist, those surfaces will provide the canonical branch/commit audit view. +To audit current history for a room, NPC, or item, contributors make a best-effort audit by querying the Game Design Service’s revision/version rows and correlating those revisions with the owning domain’s versioned templates and, where available, its applied-revision ledger (currently World Management’s ledger; Entity Management’s ledger remains future work). This cross-service view is not a canonical branch/commit audit because synchronized branch/commit read APIs do not exist yet. In the target state, contributors will audit through Game Design branches and commits and correlate the resulting revisions with domain-service versioned templates once those durable branch/commit and synchronized read APIs exist; the current service exposes only version-scoped revisions and version reads. **Target state:** those surfaces will provide the canonical branch/commit audit view. ### Design-Time Synchronization diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index c173df0fe1..df49923dd2 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -8,7 +8,7 @@ Target state makes Game Session the authoritative owner of region/tick coordinat ## Implementation Status -- `EnqueueAutomationCommandIfAbsent` and `ScheduleRemoteFollowup` currently fail closed at their authenticated internal receiving boundary with `FAILED_PRECONDITION` / `automation_admission_receiver_fence_unavailable`, before command, coordinator, follow-up, or queue mutation. The retained lower-level admission implementation does not prove the cross-service Automation admission-epoch fence required by [ADR 0106](../../decisions/adr-0106-epoch-fenced-script-rollback-without-routine-gameplay-pause.md). A separate receiver-fence successor must durably serialize installation against receiving admission, preserve exact retry outcomes, and prove that a handoff whose intent committed before an Automation pause cannot create live work under the displaced admission epoch afterward. This gate preserves ordinary gameplay APIs and does not claim the successor implemented. +`EnqueueAutomationCommandIfAbsent` and `ScheduleRemoteFollowup` currently fail closed at their authenticated internal receiving boundary with `FAILED_PRECONDITION` / `automation_admission_receiver_fence_unavailable`, before command, coordinator, follow-up, or queue mutation. The retained lower-level admission implementation does not prove the cross-service Automation admission-epoch fence required by [ADR 0106](../../decisions/adr-0106-epoch-fenced-script-rollback-without-routine-gameplay-pause.md). A separate receiver-fence successor must durably serialize installation against receiving admission, preserve exact retry outcomes, and prove that a handoff whose intent committed before an Automation pause cannot create live work under the displaced admission epoch afterward. This gate preserves ordinary gameplay APIs and does not claim the successor implemented. This document mixes live and target-state control-plane surfaces. Current live behavior is narrower: @@ -18,6 +18,7 @@ This document mixes live and target-state control-plane surfaces. Current live b - The live `/actuator/settings/effective` endpoint is guarded only by the shared HTTP `PRIVILEGED` requirement. `SessionClaims.hasPrivilegedRole()` treats a role scoped to any tenant as sufficient, while `EffectiveSettingsController` accepts caller-supplied `tenantId`, `gameInstanceId`, `bootstrapGameInstanceId`, or a `sessionId` and does not bind those selectors to the scoped role or compare persisted-session ownership. A tenant-scoped operator for tenant A can therefore request effective settings for tenant B (or a tenant-B session). Existing proof covers malformed selectors and a global privileged token, not this cross-tenant denial boundary. - **Target effective-settings boundary:** a tenant-scoped `tenantAdmin`/operator role may read only the exact requested tenant, and a persisted `sessionId` must resolve to that same tenant; a missing tenant selector is allowed only when it is unambiguously derived from the session. A global `platformAdmin` operator may select another tenant only through the explicit global branch with current operator authorization, target-tenant generation, and required `privileged_control` assurance. Tenant/session mismatch, absent or unavailable authority, and a scoped role selecting another tenant fail closed before settings resolution. Focused negative proof must cover tenant A versus tenant B for both synthetic and persisted-session reads, plus the global branch without privileged control. - the live script-transition proto/runtime now persists and exposes the exact owner `{scriptPatchVersion, scriptPinEpoch, controlPlaneRequestId}` tuple on `GetPinnedScriptPatchVersion` and the corresponding observed tuple on `GetGameSessionPinConvergence`; pin/rollback requests carry the tagged `expectedCurrentPin` precondition. The owner persists a request digest/result ledger and commits the pin tuple under a row lock with deterministic replay/conflict and expected-tuple failure results. It does not expose target `GetScriptPinTransitionWorkflowStatus`; commit-time revalidation of external Game Design publication and Automation readiness evidence (or an immutable preparation attestation) is not live, so that cross-service authority proof remains an implementation gap alongside atomic history proof and complete rollout semantics. Local instance-scoped Automation admission, duplicate replay, durable tick staging/replay, and final Game Session execution now enforce the complete tuple; complete source/target remote tuple binding and remote final-effect fencing remain tracked in the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md) and the [canonical runtime-execution owner](../../system-architecture-scripting-runtime-execution.md#normative-target-contract). A missing epoch never matches a pinned target tuple. Semantic `UNPINNED` matching is defined separately below; +- the target spatial/ambient `effect_reconciliation_backlog`, typed `EffectReconciliationAuthority`, and `ListEffectReconciliationBacklog` / `RetryEffectReconciliation` / `AcknowledgeEffectDeadLetter` surfaces are not implemented. Current Game Session has `tick_batch` and `tick_effect` persistence plus narrower domain and remote-follow-up reconciliation, but no backlog schema, immutable effect-guard/action-ledger schema, or API; those current seams must not be presented as this target cross-service reconciliation surface. The normative owner, guard, CAS, action-idempotency, and authority-branch requirements remain in [Transaction Strategies](../../system-architecture-transactions.md#reconciliation-owner-of-record-spatialambient-effects); Read the pause/status/recovery APIs below as the target-state contract unless the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md) explicitly records them as live. @@ -89,7 +90,7 @@ The internal front-end to lease-owner path is a **target-state** fenced gameplay - A dispatcher reconciles the durable work item after commit and retries delivery until source cleanup-work dispatch and the World lifecycle request are acknowledged by their authoritative readbacks. Lost responses, dispatcher restarts, and duplicate deliveries are recovered by the stable work-item identity, source instance binding, and acknowledgement state; delayed reconciliation does not delay deadline-based command rejection, and the cutover result is not reported as fully completed merely because an in-memory termination request was sent. Final `TERMINATED` readback is World’s authoritative all-owner cleanup result. - `EnqueueAutomationCommandIfAbsent` – current authenticated receiver behavior is `FAILED_PRECONDITION` / `automation_admission_receiver_fence_unavailable`, before command or queue mutation; the lower-level dispatch, admission, and staging behavior described below is unavailable through this receiver. The retained internal Automation & Scripting handoff API records or replays a durable automation dispatch row keyed by the complete [Command-Handoff Identity](../../system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state) before staging the generated command into the normal Game Session tick queue. For non-exclusive fan-out, the target handoff also retains, as non-identity evidence, the already-assigned `handlerSequence` and the event resolution record (or equivalent durable manifest) identifying the complete ordered handler set, plus the handler-local command order; Game Session carries and reuses those facts through admission, retry/recovery, and final application, and fails closed on missing or contradictory sequence/completeness evidence rather than falling back to arrival order. An authorized exclusive event has only its selected handler and no sibling admission. The live `EnqueueAutomationCommandIfAbsentRequest` carries `script_patch_version`, `script_patch_base_version_id`, `script_pin_epoch`, and `script_pin_control_plane_request_id`. For local instance-scoped Automation, Game Session compares this complete tuple with the locked current `GameInstance` while durably admitting fresh work or checking a duplicate, commits that admission before Redis materialization or an immediate tick, locks and rechecks the tuple while sealing fresh or replayed tick work, persists the tuple on `gameplay_command` and the selected-work manifest, and compares it again before final execution; a same-patch/different-base/epoch or owner-request mismatch fails closed. These local consequences are owned normatively by [Scripting Runtime Execution](../../system-architecture-scripting-runtime-execution.md#normative-target-contract). Remote Automation follow-ups retain their separate legacy source/target path and are not widened by this local boundary. Only an already-staged or downstream-confirmed dispatch returns `DUPLICATE_NOOP` with the existing `commandId`; a matching pre-Redis `ACCEPTED` row is not a duplicate. Target behavior retries materialization from that durable row or converges it to a terminal non-applied outcome under the command-status rules. The current implementation returns `UNAVAILABLE` for an existing `ACCEPTED` row, and later recovery may mark stale accepted-but-unstaged work `LOST_BEFORE_STAGING`; it does not introduce a separate staging state. New same-scope dispatches validate and persist one current durable owner/epoch fence, while a dispatch with a distinct target reads and locks the source and target owner rows in one stable canonical owner-identity order, validates each against its source or target role, and persists both owner/epoch fences before Redis mutation. Missing source/target ownership returns `OWNERSHIP_UNAVAILABLE`, a stale source/target `regionEpoch` returns `STALE_TIMELINE`, and paused ownership returns `RUNTIME_PAUSED` without staging into Redis. `dueTickId` is still carried for scheduler/timer-derived automation, but immediate event-driven automation may omit it and rely on immediate enqueue semantics. - At the Game Session-to-Automation handoff, Game Session first resolves `playableStateNamespaceId` and `playableStateScope` from the authoritative admission-pointer/world-lifecycle snapshot; neither Automation nor the caller supplies namespace authority. The owner-side admission/CAS validates the exact `{tenantId, playableStateNamespaceId, playableStateScope, gameInstanceId, regionId, regionEpoch}` tuple atomically before staging. The current handoff wire carries only a narrower tenant/instance/region fence in some paths and lacks complete namespace/scope plus active-instance proof, so this is an explicit current wire/implementation gap rather than a claim that the target handoff is live. -- `GetGameplayCommandStatus` – returns the durable command status by the canonical current lookup key `{tenantId, gameInstanceId, commandId}`, including accepted/staged/completed timestamps, attempt count, failure code/message, source type, automation dispatch/work-item ids, script/plugin provenance, target entity, `regionId`, `regionEpoch`, `dueTickId`, and the full remote origin/target game-instance, `playableStateNamespaceId`, and region scope when the command has entered the cross-region follow-up path. That same status read now also exposes the durable remote follow-up contract itself when present: follow-up status, payload kind, requested command, solo-tick requirement, origin-source tuple, target entity/effect/failure summary, and trigger-script-event identity. `regionId`, `regionEpoch`, and `automationDispatchId` are correlation or filter fields for that read, not replacements for its lookup key. Automation handoff deduplication, replay, and fence diagnostics instead use the complete [Command-Handoff Identity](../../system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state), including `playableStateNamespaceId`, `playableStateScope`, optional distinct target-scope fields, and `commandOrdinal`; they do not change the status resolver's required `{tenantId, gameInstanceId, commandId}` lookup tuple, which is never reduced to a single `commandId`. For commands with a script patch, the publication link is looked up using the durable base admitted with that command, never its unrelated admitted content-version ID or the instance's mutable current base; historical commands without that base report a lookup error rather than a guessed link. +- `GetGameplayCommandStatus` – returns the durable command status by the canonical current lookup key `{tenantId, gameInstanceId, commandId}`, including accepted/staged/completed timestamps, attempt count, failure code/message, source type, automation dispatch/work-item ids, script/plugin provenance, target entity, `regionId`, `regionEpoch`, `dueTickId`, and the full remote origin/target game-instance, `playableStateNamespaceId`, and region scope when the command has entered the cross-region follow-up path. That same status read now also exposes the durable remote follow-up contract itself when present: follow-up status, payload kind, requested command, solo-tick requirement, origin-source tuple, target entity/effect/failure summary, and trigger-script-event identity. `regionId`, `regionEpoch`, and `automationDispatchId` are correlation or filter fields for that read, not replacements for its lookup key. Automation handoff deduplication, replay, and fence diagnostics instead use the complete [Command-Handoff Identity](../../system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state), including `playableStateNamespaceId`, optional distinct target-scope fields, and `commandOrdinal`; source `playableStateScope` and target `targetPlayableStateScope` values are separately persisted and exact-validated policy/routing/authorization/migration-fence evidence, not Command-Handoff Identity or uniqueness inputs. They do not change the status resolver's required `{tenantId, gameInstanceId, commandId}` lookup tuple, which is never reduced to a single `commandId`. For commands with a script patch, the publication link is looked up using the durable base admitted with that command, never its unrelated admitted content-version ID or the instance's mutable current base; historical commands without that base report a lookup error rather than a guessed link. - `ListRemoteCommandCoordinators` – returns bounded remote coordinator rows for a tenant, filterable by persisted origin/target game-instance, `playableStateNamespaceId`, and region scope, state, linked `followupId`, script/plugin/dispatch/command provenance, the admitted routing bundle, linked follow-up target-leg traits (`targetEntityId`, `effectKey`, `payloadKind`, `originSourceKind`, `automationWorkItemId`), and first-class trigger-event identity (`eventType`, `scriptEventId`) instead of requiring point lookup by one coordinator id. The target admitted routing bundle is (`realmId`, `playableStateScope`, `worldSlug`, `realmSlug`, `pointerVersion`); `playableStateScope` remains separately validated evidence and is not a substitute for namespace identity. The current selector-based model does not yet carry durable `realmId` or namespace fields. - `ListRemoteFollowups` – returns bounded remote target-leg rows for a tenant, filterable by persisted origin/target `playableStateNamespaceId` and scope, follow-up status/id, script/plugin/dispatch/command provenance, the admitted routing bundle, current live payload/source classifiers (`payloadKind`, `originSourceKind`), direct target-leg identity/terminal fields (`automationWorkItemId`, `targetEntityId`, `effectKey`, `failureCode`, `requiresSoloTick`), and first-class trigger-event identity (`eventType`, `scriptEventId`) instead of requiring operators to scrape one entire target-region stream. - `ListRemoteFollowupResults` – returns bounded origin-addressed remote result rows for a tenant, filterable by coordinator/follow-up identity, origin/target game-instance, `playableStateNamespaceId`, and region scope, outcome, script/plugin/dispatch/command provenance, the admitted routing bundle, and durable result identity/failure fields (`resultErrorCode`, `resultCommandId`, `automationWorkItemId`). Result admission compares the complete persisted origin and target namespace/timeline tuples, while separately validating `playableStateScope`; it does not accept a result based on region/epoch or scope alone. diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 27e0bfe0da..c4e61237ca 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -19,11 +19,22 @@ The sections below define the target-state runtime contract. Current implementat - The live `startSession` path keeps the Game Session row and runtime projection `STARTING` until World confirms its fenced `PREPARING -> ACTIVE` transition, then records `RUNNING`; failures before an activation attempt use the existing pre-activation cleanup. Once activation may have been issued or committed, an activation error or ambiguous result, or a later local runtime-state save/finalization failure, retains both the runtime projection and local owner row as `STARTING`, and never calls stale-epoch `failPrepared` or deletes either record. A failure proven before any World termination request is issued may restore the prior `RUNNING` row and runtime state while the World remains `ACTIVE`; once a termination request may have been issued, an error or ambiguous result leaves the local row `STOPPING` and runtime projection absent. Confirmed World termination retries local `STOPPED` finalization and never restores `RUNNING`. Durable stable lifecycle-operation identity and lifecycle readback/reconciliation remain unimplemented, so these local fail-closed quarantines are not a replacement for the target durable lifecycle cleanup workflow. - Current `onCommand` ingress uses the live `{tenantId, gameInstanceId}` boundary as a region surrogate until true region partitioning is shipped; it carries the current `regionEpoch` and a producer-supplied `readSnapshotToken` derived from the command and ownership fence. That token is retained only as an owner-specific manifest input or correlation value, not universal evaluation authority. The target handler-scoped input manifest is owned by the [DSL lifecycle contract](../../system-architecture-scripting-dsl-reference-and-lifecycle.md#read-consistency-contract); current producer/storage behavior is narrower and does not yet seal the complete manifest. - Durable command/effect execution currently covers movement and `PUT`, `TAKE`, `WEAR`, and `REMOVE` fully at the existing boundary. Current `GET` is the command spelling for the target `PICKUP`/`PickupVisibleRoomItem` family, and `GET` plus `DROP` also enqueue and execute on that durable command path, but their ADR 0054 spatial correctness remains incomplete until World `TargetingFactSnapshot` attestation/location-version propagation, the shared actor-lock/executor-fence critical section and durable barrier/handoff path, and stale-race proof are implemented. Current movement/item replay rows do not yet prove the ADR 0054 participant guard bound to root `EffectId`, typed operation, target, and request digest, or fail-closed changed reuse. +- The target spatial/ambient reconciliation contract is not a current Game Session surface: the typed `EffectReconciliationAuthority`, durable `effect_reconciliation_backlog`/authority schema, immutable effect guards, durable action ledger/results, and list/retry/acknowledgement APIs remain unimplemented. Current persistence is limited to `tick_batch`/`tick_effect` and narrower domain/remote-follow-up reconciliation; see [Game Session API status](./api-contracts.md#implementation-status) and the normative [transaction reconciliation owner](../../system-architecture-transactions.md#reconciliation-owner-of-record-spatialambient-effects). +- The target remote-follow-up contract makes terminal timeout/late outcomes immutable under the original identity: exact retries return the stored terminal outcome, and a late-applied result requires a separately documented feature-specific compensation flow. The current `scheduleFollowup` replay path returns an existing retryable-timeout pair or valid terminal pair without mutation, with focused unit proof for terminal-pair replay. This does not establish exact serialized timeout/result arbitration under concurrency, complete terminal-failure mirroring, missing-coordinator recovery, or late-result compensation. The live `late_result_requires_reconciliation` path also writes `LATE_RESULT_RECONCILED`/`PARTIAL` and mirrors `APPLIED`/`PARTIAL` to the origin without a separately identified compensation/saga flow; post-abandon re-drive and compensation ownership remain unproved. +- Current tick staging has Redis-first windows that are not the target durable-first boundary: ingress pushes the queue payload before marking the durable command `STAGED`, while tick processing moves queue entries to Redis `pending` before creating the durable `tick_batch`/`tick_effect` rows. Failures before the durable `STAGED` update leave the command `ACCEPTED`; failures after that update and before durable `tick_batch`/`tick_effect` creation can leave `STAGED` without a batch/effect. Startup recovery only handles `ACCEPTED` rows with no staging timestamp, and purge can classify a no-effect row as `LOST_BEFORE_STAGING`. Current crash recovery is limited to durable records that exist; there is no recovery path for a `STAGED` command without a corresponding `tick_batch`/`tick_effect`, and missing staging or effect evidence does not prove that materialization or application did not occur. Only explicitly classified volatile ingress may receive that evidence-qualified outcome; durable accepted work needs a durable source claim/materialization recovery path and its feature-specific replay/re-drive contract. The target boundary creates the durable batch/effect/source claim before `pending` staging and treats Redis-only residue as reconstructible coordination state; the current ordering and no-batch recovery are implementation drift. +- The target stale-fence contract preserves a drained effect under its original mutation `EffectId` and enclosing root lineage while evidence-fenced reconciliation determines whether it is `APPLIED` or safely unapplied. A new identity may be re-driven only after authoritative participant/domain evidence conclusively terminalizes the original effect as `ABANDONED` and the owning source command/claim is terminalized; ordinary retry/replay retains the original command/effect identity. Root allocation details remain proposal-only under [ADR 0183](../../decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). The current implementation instead marks stale drained batches/effects `ABANDONED` on the fence/technical signal alone and requeues the same command, after which a later batch derives a new effect identity. This is unsafe implementation drift: a crash after participant mutation but before ledger terminalization can permit duplicate logical application or false abandonment. - `BLOCK` is also on the current durable effect replay/no-op seam; other state-changing command families still need to migrate onto it. - Current Game Session code still defaults `FIREMUD_AUTH_SESSION_EXPIRATION_MS` to one hour and does not enforce the target five-minute continuity cap. - Current Game Session code has not converged on the canonical bounded `session:game:*` index families or proved their repair protocol: it still uses transitional `sessionctx:*` and tenant/identity lookup records and does not implement/prove the generation-safe global `accountIndexMember` set, the partitioned global issuer index, or their cross-slot repair/acknowledgement flows. This is implementation/proof drift, not a transfer of ownership or a different member shape. -- Current Game Session Redis-backed per-session rate limiting under the legacy `ratelimit:` key remains implementation drift from ADR 0034's target in-process ordinary gameplay limiter; its Cache/Rate-Limit role isolation, eviction behavior, and loss semantics are not yet proved. Migration must stop legacy writers and drain the maximum key TTL before unversioned target helpers consume `ratelimit:*`, or use a distinct versioned namespace. +- Current Game Session Redis-backed per-session rate limiting under the legacy `ratelimit:` key remains implementation drift from ADR 0034's target in-process ordinary gameplay limiter. `SessionRateLimiterImpl` uses the generic Game Session Redis client and a one-second counter/TTL; its Cache/Rate-Limit endpoint, ACL/admission, eviction behavior, and loss semantics are not yet proved. The exact family is registered in the [Cache/Rate-Limit key catalog](../../system-architecture-redis-cache-reference.md#cache-rate-limit-key-catalog) and [reset policy matrix](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). Migration must stop legacy writers and drain the maximum key TTL with readback before unversioned target helpers consume `ratelimit:*`, or use a distinct versioned namespace. +- Current hosted wiring still exposes one generic `firemud.redis` connection to Game Session while the shared Helm profile sets `FIREMUD_REDIS_HOST=redis-cache`; the role-specific `FIREMUD_REDIS_COORD_*` and `FIREMUD_REDIS_CACHE_*` variables are not consumed by the common Redis auto-configuration. Consequently, the live Game Session tick/session coordination path is not proven to reach Coordination Redis in that profile and may share the Cache/Rate-Limit endpoint. This is implementation drift against ADR 0171, not a target-state role assignment; named role clients, endpoint-collision failure, and role-specific health/eviction proof remain required. +- Current tick/session coordination also bypasses the target key/script boundary: `TickQueueControlService`/`TickServiceImpl` build untagged `gamesession:tick:*` keys and pass queue, pending, and lock keys together to Lua, while `RedisSessionContextService` performs watched multi-key writes across untagged `sessionctx:*` families. Those calls are not proven same-slot and can fail with `CROSSSLOT` on a supported Redis Cluster profile; the live families are not represented by the canonical builder/registry contract. This records current implementation/proof drift only; migration must use the canonical tagged builders, registered scripts, reset inventory, and fenced readback before claiming cluster support. +- The current `IpConnectionLimiter` stores the source address directly in `ipconn:
` keys and `sessionip:` values, and registration passes both keys to one Lua invocation without a shared hash slot, so it fails with `CROSSSLOT` on Redis Cluster. This is not the ADR 0087 opaque-HMAC subject contract and has no evidenced tenant/policy scope or current Cache/Rate-Limit loss profile. The limiter remains a current heuristic seam; convergence requires one mutation on one opaque subject bucket, session lifecycle correlation outside exact cross-key atomicity, an owner-declared subject scope, opaque full-digest mapping, and focused privacy, isolation, eviction, reset, clustered, and unavailable-store proof; no final reverse-index design is implied. +- The current `LOGIN` path receives Account's `game-session-account-delegation` JWT and places it in the persisted `SessionContext.jwt` value, which is serialized into Redis by `RedisSessionContextService`. This contradicts the process-local/no-raw-delegation-JWT boundary in ADR 0031. The target binding must persist only bounded non-secret evidence such as the token hash or opaque rebind handle; stripping the token, fenced cleanup of existing values, and focused no-secret serialization proof remain implementation work. - Bounded durable semantic reconnect-context persistence is partial: ordered `resume_transcript_entry` rows and best-effort Redis caching are live, while namespace-key migration to `{tenantId, playableStateNamespaceId, characterId}`, the distinct durable `resumeContextGeneration` episode fence and termination protocol, complete-envelope hard-bound accounting and omission-marker convergence, and post-logout replay suppression remain implementation/proof gaps. +- Current live/recent presence projection wiring is implementation drift: `gameplaypresence:session:`, its game-instance/account set indexes, and `accountrecentpresence::` are written with untagged, separate Redis value/index operations. Game Session remains the target owner, but the physical shapes, storage-role classification, exact scope, partial-write handling, reset/rebuild/readback behavior, and private-by-failure contract are unproved; the [Redis owner and reset catalog](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary) records these current families without accepting them as target authority. +- Current LOOK handling writes the legacy `lookcache::` projection even though reads remain authoritative/uncached. Its ten-minute, session-or-instance-only scope lacks the target viewer, policy, and causal read-fence identity; it is disposable implementation drift and must not be treated as the target `view:room-look:*` cache. See the [Redis cache catalog](../../system-architecture-redis-cache-reference.md#cache-rate-limit-key-catalog). +- The current Flyway history also contains the Java/nontransactional `V8__remote_followup_target_instance_effect_identity` migration (`CREATE INDEX CONCURRENTLY`, `canExecuteInTransaction() = false`). This is outside the SQL migration input used by shared jOOQ generation and is not yet inventoried or proved as a narrow exception to the SQL-only persistence lineage. ## Runtime Details @@ -92,7 +103,7 @@ Game Session treats Redis Coordination and Cache/Rate-Limit roles as separate co ### Redis role and prefix details -- Coordination prefixes are reset-tolerant in line with [Redis Reset & Recovery](../../system-architecture-redis-reset-and-recovery.md), except for reset-sensitive gameplay session bindings under `session:game:*`. That document owns reset lifecycle and session policy; Game Session retains only local consequences: the canonical session record is the policy-selected binding, while derived gameplay indexes reconcile independently under either policy. Account token and generation authority remains outside session policy. Game Session’s coordination design must therefore remain safe under the documented Redis tail-loss envelope rather than assuming perfect recovery of every transient coordination key. +- Coordination prefixes follow the reset policies in the complete [Redis Reset & Recovery matrix](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). Region-scoped tick queues, pending state, locks, leases, timers, retries, and session-binding projections are reset-tolerant (with preserved-session rebind fencing where specified), while gameplay session records, all derived gameplay indexes, `sessionctx:*`, presence projections, disconnect deduplication, and pre-auth transport context are reset-sensitive or unavailable-by-failure under that matrix. Account token and generation authority remains outside session policy. Game Session’s coordination design must therefore preserve the matrix’s fences and remain safe under the documented Redis tail-loss envelope rather than assuming perfect recovery of every transient coordination key. - The canonical opaque `{tenantRegionTag}` is derived by the shared key builders from the full `` tuple. It is the region scope for lease, queue, timer, retry, pending, and lock keys below; key examples must retain `{tenantRegionTag}` rather than substituting a differently named or partial tag. - Coordination ownership includes registered Lua-script access to prefixes such as: - `tick:{tenantRegionTag}:queue:` @@ -108,12 +119,13 @@ Game Session treats Redis Coordination and Cache/Rate-Limit roles as separate co - Changes to Game Session Redis usage must also be reviewed against the [Redis Design Checklist](../../system-architecture-redis-design-checklist.md) in addition to the core Redis architecture docs. - Game Session may rely on Cache/Rate-Limit Redis for read-side caches that help serve hot-path session views, most notably pre-rendered room LOOK aggregates under `view:room-look:::::::` as defined in [Redis Cache & Rate Limiting](../../system-architecture-redis-cache.md#key-naming-and-overwrite-expectations). - `view:room-look:*` entries are Class B, TTL-only caches. They may become stale briefly, but gameplay correctness still comes from authoritative reads and tick execution rather than cache contents. The key must remain bound to the exact room, viewer/session, policy context, and applicable read-fence context; use the [canonical Class-B contract](../../system-architecture-redis-cache.md#canonical-viewroom-look-class-b-contract) for the fence-hash derivation and the uncached fallback when the complete fence is unavailable. Underlying world or entity changes do not require synchronous invalidation of these keys; recomputation happens on cache miss or TTL expiry, and correctness-critical flows must not treat the cache as authoritative. +- The current LOOK writer uses legacy `lookcache::` keys with a ten-minute TTL. This projection is disposable and non-authoritative, but its incomplete scope cannot support target causal room-read semantics; current composition remains authoritative/uncached until the registered `view:room-look:*` contract is implemented and proved. The legacy writer must be removed/drained or explicitly isolated before target cache helpers consume the family. - Cache prefixes must never be silently repurposed onto Coordination Redis, and new cache usage should be introduced only through the central cache-key catalog rather than ad-hoc per-service naming. - Game Session must not read or write Social & Groups history caches such as `chat:say:*`, `chat:tell:*`, `chat:guild:*`, or `chat:account:*`. Chat history ownership stays behind Social & Groups APIs. -Crash recovery replays ticks stored in Redis using AOF persistence and the idempotent replay rules described in [Tick System and Runtime Design](../../system-architecture-ticks.md#crash-recovery-and-replay). Replication remains asynchronous, and Redis is treated as a volatile coordination layer rather than a durable source of truth. +**Target-state crash recovery:** recovery is driven by durable PostgreSQL commands, tick batches, effects, and participant guards, using the idempotent replay rules described in [Tick System and Runtime Design](../../system-architecture-ticks.md#crash-recovery-and-replay). Redis `pending` entries and AOF state remain volatile coordination hints subject to measured exposure; they may assist recovery only after durable reconciliation and never supply recovery authority or the sole source of replayable work. Replication remains asynchronous. -When Redis becomes slow or unavailable, Game Session applies the graceful degradation and halt behavior defined in [Redis Architecture – Graceful Degradation & Redis Outage Policy](../../system-architecture-redis.md#graceful-degradation--redis-outage-policy) instead of buffering authoritative commands only in memory. If coordination state must be cleared or repaired, operators follow the scoped reset flows in [Redis Operations & Migrations](../../system-architecture-redis-operations.md) rather than issuing ad-hoc key deletions. +When Redis becomes slow or unavailable, Game Session applies the graceful degradation and halt behavior defined in [Redis Availability, Consistency, and Safety Guarantees](../../system-architecture-redis.md#redis-availability-consistency-and-safety-guarantees) instead of buffering authoritative commands only in memory. Current operators do not clear or repair Coordination Redis through ad-hoc key deletion or the target-state scoped reset flows, which remain unavailable; they preserve evidence, keep the affected scope fenced, use shipped pause/status and read-only inspection surfaces, and follow the [current operator fallback](../../system-architecture-redis-reset-and-recovery.md#current-operator-fallback) and escalation path. ## Session Keys and Indexes @@ -140,7 +152,7 @@ Target-state Game Session maintains the bounded active-binding index families ow - `session:game:index:realm-grant:{tenantGameplayTag}:` -> active `sessionId` set for lifecycle-bound private/playtest grant-gated realms, where `grantScopeId` is the exact canonical `grant/v1` scope ID for the complete Account-owned tuple; public-production and unscoped bindings have no entry - `session:game:index:issuer:{issuerIndexLayoutTag}::` -> partitioned global issuer active-binding hash, using the immutable layout and `bindingRef` fields defined by the [Redis issuer-index contract](../../system-architecture-redis.md#issuer-active-binding-index) across all tenants -These indexes are derived gameplay projections, not preserved-session state or Account authority. Game Session is the target-state local writer and reconciler for them under the reset consequences in [Redis Reset & Recovery](../../system-architecture-redis-reset-and-recovery.md); affected tenant-owned indexes may be dropped and rebuilt under either explicit session policy, while the global account index and partitioned global issuer index require their separate account-wide or issuer-wide owner-defined coverage before replacement. A region/tenant parent may repair only its local binding consequences and consume a complete issuer-wide child or standalone issuer-wide recovery result; it may not claim issuer coverage from a local snapshot. Binding transitions use the owner-defined generation/fence and repair protocol; this service must not use wildcard scans or treat index presence as authorization. Missing or ambiguous index/coordination state fails closed for admission and reconnect, while local cleanup remains idempotent. +These indexes are derived gameplay projections, not preserved-session state or Account authority. Game Session is the target-state local writer and reconciler for them under the reset consequences in [Redis Reset & Recovery](../../system-architecture-redis-reset-and-recovery.md); at tenant scope, affected tenant-owned index families may be dropped and rebuilt under either explicit session policy, while a region scope updates or reconciles only exact affected index entries from durable inventory and preserves unrelated keys, members, regions, and tenants. The global account index and partitioned global issuer index require their separate account-wide or issuer-wide owner-defined coverage before replacement. A region/tenant parent may repair only its local binding consequences and consume a complete issuer-wide child or standalone issuer-wide recovery result; it may not claim issuer coverage from a local snapshot. Binding transitions use the owner-defined generation/fence and repair protocol; this service must not use wildcard scans or treat index presence as authorization. Missing or ambiguous index/coordination state fails closed for admission and reconnect, while local cleanup remains idempotent. Gameplay session bindings persist the local identity and receiver-validation fields required by the owner contract: @@ -158,23 +170,23 @@ The target transition's durable identity spans the target session record and cha Game Session acts as the authoritative tick executor for each `` region scope it owns: -- It participates in region leadership using the Redis lease key `tick-executor-lease:{tenantRegionTag}` described in [Redis Architecture](../../system-architecture-redis.md#region-leadership-and-tick-executor-lease). +- It participates in region leadership using the Redis lease key `tick-executor-lease:{tenantRegionTag}` described in [Tick System: Region Authority and Tick Executor](../../system-architecture-ticks.md#region-authority-and-tick-executor). - While it holds the lease for a region, it is the only instance allowed to consume commands from that region’s queues and timers, drive `tick:{tenantRegionTag}:pending`, and issue tick-scoped gRPC calls on behalf of that region’s commands. -- On crash or deliberate handoff, another instance acquires the lease and resumes tick processing from Redis using the epoch-scoped `(regionEpoch, tickId)` timeline and EffectId/effect-guard rules from the tick-system design. +- **Target state:** on crash or deliberate handoff, another instance acquires the lease and resumes tick processing from durable PostgreSQL commands, tick batches, effects, and participant guards, using surviving Redis queues, timers, retries, `pending`, or AOF state only as reconciled coordination hints after that durable baseline is established. Redis state never supplies recovery authority or the sole source of replayable work; the successor preserves the epoch-scoped `(regionEpoch, tickId)` timeline and EffectId/effect-guard rules from the tick-system design. - Tick execution correctness must not depend on process-local executor memory surviving restart. Lease acquisition, staged tick state, retry metadata, and resumable session bindings are all externalized specifically so another Game Session instance can continue work from shared state. - **Target state:** The executor monitors mode-aware `tick_execution_time_ms_p99{scope_class,tick_mode}` and selects `tick_lock_ttl_ms{scope_class}` for `tick_mode="normal"` or `solo_lock_ttl_ms{scope_class}` for `tick_mode="solo"`. A repeated over-TTL class-level signal is for detection and escalation only; it does not identify or classify an individual region. The executor resolves the exact region and current health from authoritative runtime-health/control-plane records before reducing tick fan-out, marking a region degraded, halting new ticks, or rejecting new commands for that region until operators intervene. - Changing `tick_interval_ms` is not part of this in-place degradation path. Any live cadence change that alters timer ordering must run as an epoch-bumped maintenance operation with pause, timer re-derivation, and resume on the new `regionEpoch`, as defined in the tick and scaling docs. - The staging Lua script only moves a bounded number of commands each tick, governed by `GAME_TICK_MAX_COMMANDS`, so one player cannot starve others. Commands marked `requiresSoloTick: true` are dequeued into isolated ticks so expensive operations such as runtime procedural generation do not share time with normal actions. - Each tick-staging or entity-lock-acquiring Lua invocation uses a registered script governed by [ADR 0074](../../decisions/adr-0074-one-entity-lock-per-redis-script.md), acquires at most one entity lock, and fails closed if the operation would require more. Multi-entity correctness is enforced by one owning PostgreSQL transaction when the invariant is co-located, or by durable effect/workflow legs with [ADR 0076](../../decisions/adr-0076-failure-class-specific-durable-tick-retries.md) retry and reconciliation when authority is split. Redis locks are coordination only: Game Session does not assemble entity lock sets or use Redis rollback as a transaction boundary. Each retryable outcome maps to ADR 0076's declared failure class, whose policy owns its deterministic cadence, attempt and age bounds, and exhaustion disposition; only authoritative pre-dispatch lock contention uses capped exponential tick backoff. An unstaged command may surface an explicit retry-budget failure, while a staged or ambiguously dispatched effect remains unresolved for owner reconciliation, dead-letter, quarantine, or verified terminal evidence rather than being logged as permanently unapplied merely because automation exhausted. -These degraded and halt transitions follow the same thresholds and policies captured under [Redis Architecture – Operational SLOs & Alert Thresholds](../../system-architecture-redis.md#operational-slos--alert-thresholds) so operators and implementations share a single set of red lines for coordination health. +These degraded and halt transitions follow the same thresholds and policies captured under [Redis Operations & Migrations – Redis SLOs & Budgets](../../system-architecture-redis-operations.md#redis-slos--budgets) so operators and implementations share a single set of red lines for coordination health. -For `DROP` and `PICKUP`, Game Session acquires the actor lock keyed by the complete gameplay scope, including `regionId`, and `actorEntityId`, captures the current `(regionId, regionEpoch, executorFence)` from its durable region-status snapshot after authority validation, and durably records an in-flight barrier keyed by the existing scoped root identity `(tenantId, gameInstanceId, EffectId)` and bound to the actor, `regionId`, `RoomInstanceRef`, epoch, fence, and canonical immutable `requestDigest` before World validation. `regionId` propagates unchanged through World validation and any Game Logic re-resolution and is checked with the same root `EffectId` and unchanged `requestDigest` at Entity commit. It owns lock/retry orchestration, renews the actor-lock lease through Entity commit acknowledgement, and invokes Game Logic to re-resolve stale evidence under the same root `EffectId`, preserving that `requestDigest`; Entity verifies the attestation, guard, and `requestDigest` at local commit. A changed request is rejected rather than reusing the root. Lock-renewal failure, owner crash, or fence change fences the old orchestrator and leaves the barrier reconciliation-required. Handoff/recovery may reconcile the exact root but MOVE admission must pass the same actor lock/barrier gate and cannot authorize a conflicting move merely because Redis lock state expired; a later valid `MOVE` is allowed only after terminal barrier evidence. The detailed local-transaction and proof contract is in [Transaction Strategies](../../system-architecture-transactions.md#drop-pickup-targeting-and-actor-fence-critical-section). +**Target-state `DROP`/`PICKUP` critical section:** Game Session acquires the actor lock keyed by the complete gameplay scope, including `regionId`, and `actorEntityId`, captures the current `(regionId, regionEpoch, executorFence)` from its durable region-status snapshot after authority validation, and durably records an in-flight barrier keyed by the canonical scoped root identity `(tenantId, gameInstanceId, EffectId)` before World validation. The barrier binds the exact `playableStateNamespaceId`, `playableStateScope`, actor, `regionId`, `RoomInstanceRef`, epoch, fence, and canonical immutable `requestDigest` as evidence that must match and fail closed, not as alternate uniqueness inputs. `regionId` propagates unchanged through World validation and any Game Logic re-resolution and is checked with the same root `EffectId` and unchanged `requestDigest` at Entity commit. It owns lock/retry orchestration, renews the actor-lock lease through Entity commit acknowledgement, and invokes Game Logic to re-resolve stale evidence under the same root `EffectId`, preserving that `requestDigest`; Entity verifies the attestation, guard, and `requestDigest` at local commit. A changed request is rejected rather than reusing the root. Lock-renewal failure, owner crash, or fence change fences the old orchestrator and leaves the barrier reconciliation-required. Handoff/recovery may reconcile the exact root but MOVE admission must pass the same actor lock/barrier gate and cannot authorize a conflicting move merely because Redis lock state expired; a later valid `MOVE` is allowed only after terminal barrier evidence. The detailed local-transaction and proof contract is in [Transaction Strategies](../../system-architecture-transactions.md#drop-pickup-targeting-and-actor-fence-critical-section). -Tick coordination is region-scoped, not session-scoped. Tick queues, locks, timers, retry metadata, and `tick:{tenantRegionTag}:pending` use the `tick:{tenantRegionTag}:...` prefix described in [Redis Architecture](../../system-architecture-redis.md#tick-integration-resilience-locking-staging). Region keys follow region lifecycle and crash-recovery rules: +Tick coordination is region-scoped, not session-scoped. Tick queues, locks, timers, retry metadata, and `tick:{tenantRegionTag}:pending` use the `tick:{tenantRegionTag}:...` prefix described in [Tick System: Tick Staging and Commit Flow](../../system-architecture-ticks.md#tick-staging-and-commit-flow). Region keys follow region lifecycle and crash-recovery rules: - `tick:{tenantRegionTag}:pending` is created without a TTL so it survives process crashes and failover. -- It is cleared only when the tick is successfully committed or an operator-driven recovery flow explicitly marks the tick as skipped/failed and removes the key. +- It is cleared only when the tick is successfully committed or a named owner recovery flow (target-state) durably reconciles the authoritative PostgreSQL command/batch/effect state and explicitly marks the tick as skipped/failed under the exact ADR 0085 handoff (`operationId`, fence/lock binding, classifier decision, evidence digest, and complete affected scope), or under an explicitly recorded owner-classified non-conflicting routine replay/cleanup exemption. Missing or incomplete handoff/classification fails closed. Current operators do not have this reset/repair flow; they preserve evidence, keep the affected scope fenced, and use the current fallback and escalation path described above. Session shutdown therefore cleans up session keys but does not implicitly delete region-level tick coordination keys. @@ -182,7 +194,7 @@ Session shutdown therefore cleans up session keys but does not implicitly delete Game Session restores player sessions after disconnects and enforces single-session control as outlined in the [Reconnection Strategy](../../system-architecture-reconnection.md). For Telnet clients, it also consumes best-effort, at-least-once `NotifyDisconnect` events emitted by the TCP Proxy Service over an internal gRPC link and treats them as idempotent hints keyed by `` rather than a guaranteed source of truth. -Game Session persists the latest processed `disconnectSequence` per `` and ignores older or duplicate events so retry behavior at the proxy can remain simple while consumption stays idempotent. Any `{tenantId, gameInstanceId}` values coming from proxy-owned bootstrap metadata or future hidden MCP-carried smart-client hints remain advisory context that may be used for logging and audit, but they are not trusted as authorization claims or binding directives. Game Session still validates any game-instance ownership claims against Redis and its authenticated session state before rebinding the transport. **Current implementation gap:** the live Redis sequence-dedupe path fails open on Redis errors and is reset-loss-vulnerable; no current connection/generation binding guard runs before `NotifyDisconnect` presence or region-exit effects or `GameInstance` suspension. The live path therefore does not yet satisfy the target advisory safety contract; the eventual binding design remains unspecified. +Game Session persists the latest processed `disconnectSequence` per `` and ignores older or duplicate events so retry behavior at the proxy can remain simple while consumption stays idempotent. Any `{tenantId, gameInstanceId}` values coming from proxy-owned bootstrap metadata or future hidden MCP-carried smart-client hints remain advisory context that may be used for logging and audit, but they are not trusted as authorization claims or binding directives. Game Session still validates any game-instance ownership claims against Redis and its authenticated session state before rebinding the transport. **Current implementation gap:** the live `gamesession:notifydisconnect:dedup:` path fails open on Redis errors and is reset-loss-vulnerable; no current connection/generation binding guard runs before `NotifyDisconnect` presence or region-exit effects or `GameInstance` suspension. The live path therefore does not yet satisfy the target advisory safety contract. Until exact connection/generation binding and durable sequencing are proven, Redis loss/error must not authorize stale effects; see the [Redis reset catalog](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). Recent/offline account-presence state should preserve the last admitted routing bundle too. In target state, when live presence drops to recent presence after transport loss, takeover, or logout, the bounded recent-presence record keeps the last admitted `tenantId`, `gameInstanceId`, `realmId`, `worldSlug`, `realmSlug`, and `pointerVersion` so account-presence and friend-presence reads can continue to describe the last resolved durable realm target directly instead of collapsing immediately to a routing-less timestamp. The current selector-based record does not yet prove durable `{tenantId, realmId}` propagation. @@ -203,6 +215,7 @@ Each running game instance has durable pin state alongside its `runtimeVersion`, - For target remote-follow-up delivery, Game Session revalidates source authority and race-safely captures the target instance's current exact tuple in the durable target delivery/claim. For an authoritative target semantic `UNPINNED`, the existing Game Session result transaction owns exactly one terminal `remote_followup_result` row under `resultId=remote-result:`, with `outcome=ABANDONED`, `resultErrorCode=REMOTE_TARGET_UNPINNED`, canonical empty `resultPayloadJson={}`, and no result command or Automation event/work/command; it updates the existing follow-up/coordinator identities atomically. Exact retries return that row without work, while a changed scope, tuple/identity, outcome, or normalized result-authority fingerprint conflicts without overwrite. This uses existing persisted fields and identities, with no new digest column or outcome family. `authority_unavailable` persists no terminal result and remains non-admitted/retryable under the same follow-up identity after authority recovers. When source and target are the same game instance, including a cross-region follow-up, one authoritative tuple serves both roles. - For each recognized player command, durable staging validates the required gameplay session and current runtime ownership row and reads the exact Game Session-owned current pin state, including `{scriptPatchVersion, scriptPinEpoch, scriptPinControlPlaneRequestId}`, in that same staging transaction. Only an authoritative instance row with all three owner fields absent (`UNPINNED`) means that no script is configured: in that case the transaction creates no `onCommand` outbox/event record and no later tuple is synthesized. When an exact pin exists, it creates one retryable/idempotent `onCommand` outbox/event record keyed by the durable command/event identity; same-identity retries reuse that record, and the post-commit tick kick is only a wake-up/retry hint, not the durability proof. A missing, unreadable, partial, or ambiguous pin-authority result is not `UNPINNED`; staging must retain/retry the command or reject it with bounded `pin_state_unavailable`, never silently suppressing the `onCommand` record. - Scripting availability is not a gameplay admission dependency beyond the normal session and runtime-ownership checks: a scripting outage leaves the staged `onCommand` record retryable while ordinary gameplay and tick processing continue. +- **Current implementation/proof gap:** The live path persists the accepted command and then invokes Automation through an asynchronous best-effort publisher; publisher submission/RPC failures are logged without a durable producer retry or reconstruction record. This is nonconformant with [ADR 0083](../../decisions/adr-0083-no-general-event-broker-until-measured-adoption-gates.md)'s atomic producer-outbox and recoverable consumer-delivery requirements, so an admitted command can currently lose its `onCommand` trigger. The target outbox and per-consumer delivery boundary is not shipped or proven here. - Script-generated commands enter only through the canonical handoff contract. For plugin-originated binding-scoped work, final validation uses the exact tuple `(pluginId, pluginVersionId, bindingId, pluginActivationEpoch, lifecycleRevision)`. The activation epoch and lifecycle revision are execution-fence evidence, not child identity; Game Session enforces them at its owned boundaries and fails closed when any field or its authoritative lifecycle/policy evidence is missing, unavailable, stale, changed, or mismatched. Automation remains the plugin lifecycle and policy authority, and plugin-only changes do not advance `scriptPinEpoch` but do advance the independent lifecycle fence as defined by ADR 0119. - At final execution, any command/work referencing a revocable component, including embedded/core-script and plugin-backed work, carries the applicable component-revocation security-policy fence. Game Session validates current applicable evidence immediately before gameplay effects; missing, stale, unavailable, or mismatched evidence fails closed and records the established bounded component/authority disposition. Plugin-backed work additionally carries the independent `pluginActivationEpoch` and `lifecycleRevision` fences; neither lifecycle fence substitutes for the other or for component policy. @@ -221,7 +234,7 @@ Game Session now has a real current-boundary durable gameplay execution seam ins - accepted gameplay commands persist a durable command ledger row with both a human-safe sanitized text projection and the canonical raw command payload used for later execution; - the tick runtime stages Redis queue work into durable `tick_batch` / `tick_effect` rows before drain commit, including the current-boundary selected-work manifest, expected effect count, and manifest digest on the batch row; - after drain commit, Game Session resumes from any durable `DRAINED` effects for that queue boundary and executes the supported command families from the ledger itself rather than assuming Redis drain already implies terminal gameplay work; -- drained effects re-check the durable runtime owner row before application. If the batch fence is stale, unapplied drained effects are marked `ABANDONED`, their durable commands are requeued for a fresh fenced batch, and the old executor does not invoke the effect handler. +- drained effects re-check the durable runtime owner row before application. In the target contract, a stale fence preserves the effect under its original mutation `EffectId` and enclosing root lineage for evidence-fenced reconciliation; only authoritative evidence that the effect was unapplied may permit `ABANDONED`. A new identity may be re-driven only after that conclusive terminalization and terminalization of the owning source command/claim; ordinary retry/replay must retain the original command/effect identity. Root allocation details remain proposal-only under [ADR 0183](../../decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). The current implementation instead marks stale drained effects/batches `ABANDONED` from the fence/technical signal alone, requeues the same command, and lets a later batch derive a new effect identity; this is unsafe implementation drift that can duplicate a mutation or falsely terminalize an uncertain effect. The live ledger does not yet prove the target retention boundary. Game Session owns cleanup for its command receipts, batches, effects, manifests, and its `tick_effect` ledger/projection. Each domain service owns its participant guards and local cleanup; Game Session retains cross-service blocker references and safe-watermark consequences until those owners provide the evidence that permits ledger cleanup. The family-specific application of [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) is: @@ -252,9 +265,11 @@ Fairness-critical automation enters gameplay through the same durable command/ad The current live `EnqueueAutomationCommandIfAbsent` implementation compares the complete set of immutable fields carried by its request against an existing `gameplay_command` row before returning a duplicate outcome. This includes the command payload and derived name/sanitized text, target, solo-tick and due fields, current routing bundle and region fence, all currently carried source/provenance fields, and the local Automation tuple `(scriptPatchVersion, scriptPinEpoch, scriptPinControlPlaneRequestId)`. The same comparison runs after an atomic insert loses an `ON CONFLICT` race; an exact match may return the existing bounded outcome, while any mismatch—including same-patch epoch drift or owner-request mismatch—returns `REJECTED` with `IDEMPOTENCY_CONFLICT` and does not enqueue. The persisted local tuple is compared again at final execution. Non-script player commands retain their existing admission path and do not acquire these Automation-only fields. Remote Automation follow-ups retain their separate legacy source/target path; this local boundary does not widen remote tuple behavior. See [Scripting Runtime Execution](../../system-architecture-scripting-runtime-execution.md#normative-target-contract) for the owner contract. -- Target-state handoff uses one complete Command-Handoff Identity for each emitted command: source `(tenantId, gameInstanceId, playableStateScope, regionId, regionEpoch)`, optional distinct target `(targetGameInstanceId, targetPlayableStateScope, targetRegionId, targetRegionEpoch)`, the `automationDispatchId` allocated and persisted at the first durable evaluated-descriptor/outbox commit when commands are emitted (not reserved before DSL evaluation), and deterministic `commandOrdinal` in canonical emitted-command order starting at `0`. Optional target fields are present only when the command is routed to a distinct runtime scope, including its own `targetPlayableStateScope` when applicable; same-instance handoffs keep every optional target field absent. Replay selection and child uniqueness use only the complete source runtime scope, any applicable distinct target runtime scope, `automationDispatchId`, and `commandOrdinal`; the parent Trigger Identity, `outboxWorkItemId`, and `scriptEventId` are correlation-only and are excluded from child uniqueness, deduplication, and replay selection. +- Target-state handoff uses one complete Command-Handoff Identity for each emitted command: source `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch)`, optional distinct target `(targetGameInstanceId, targetPlayableStateNamespaceId, targetRegionId, targetRegionEpoch)`, the `automationDispatchId` allocated and persisted at the first durable evaluated-descriptor/outbox commit when commands are emitted (not reserved before DSL evaluation), and deterministic `commandOrdinal` in canonical emitted-command order starting at `0`. The server-derived source and, when applicable, target `playableStateScope` values are separately persisted and exact-validated as policy/routing/authorization/fence evidence, not identity fields. Optional target fields are present only when the command is routed to a distinct runtime scope; same-instance handoffs keep every optional target field absent. Replay selection and child uniqueness use only the complete source runtime scope, any applicable distinct target runtime scope, `automationDispatchId`, and `commandOrdinal`; the parent Trigger Identity, `outboxWorkItemId`, and `scriptEventId` are correlation-only and are excluded from child uniqueness, deduplication, and replay selection. - For a non-exclusive multi-handler event, each emitted child also retains, as non-identity evidence, the already-assigned `handlerSequence` and the event resolution record (or equivalent durable manifest) that identifies the complete ordered handler set, together with that handler's local command order. Game Session preserves and reuses those facts through durable admission, Redis materialization/recovery, retries, and final application; missing or contradictory sequence/completeness evidence fails closed rather than permitting higher-sequence application or arrival-order fallback. An authorized exclusive event carries Automation's sealed complete-resolution proof and sole-handler selection and creates no sibling admission or application; Game Session validates that sealed proof but does not independently resolve bindings or select the handler. - In target state, Game Session records or reads a durable `gameplay_command` admission row through `EnqueueAutomationCommandIfAbsent` using that complete child identity before mutating Redis. Existing child dispatches are classified by durable state: only rows with proven Redis staging or downstream application return duplicate/no-op from the durable key; matching pre-Redis `ACCEPTED` rows enter materialization recovery and may converge to terminal non-applied only after durable proof that neither staging nor application occurred. Without a durable materialization marker or authoritative downstream evidence, the row remains indeterminate and retryable under the same identity. Same-scope dispatches validate and persist one current durable owner/epoch fence; dispatches with a distinct target read and lock the source and target owner rows in one stable canonical owner-identity order, validate each row against its source or target role, and persist both owner/epoch fences before Redis mutation. Missing or paused source/target ownership, or a mismatched source/target `regionEpoch`, returns a non-mutating rejection. The admission row retains the validated source and, when distinct, target owner/epoch fences so retry, Redis materialization, and final execution recheck the stored fences and fail closed on displacement. The row stores optional `dueTickId`, target entity, parent/work-item correlation fields, command payload, and current execution outcome. Target-state action execution persists a structured `GameplayActionOutcome` rather than relying on one free-form result string; Game Session renders its separate semantic presentation events without interpreting target-leg state itself. +- Current live handoff wording retains an optional `dueTickId` for scheduler/timer work; this is not the target wire or storage contract and must not encode a wall-clock due point as a tick value. +- In target state, scheduled admission rows carry exactly one tagged due point, `dueTickId:` or `dueAt:`, with the alternate physical due column `NULL`; immediate event-driven rows use a separate branch, omit scheduler-only fields and `duePoint`, and keep both physical due columns `NULL`. The branch and due point are retained as immutable comparison/readback evidence through materialization, retry, replay, and final execution. - Conflicting payloads for the same key are validation failures and must not enqueue. - Only after durable admission succeeds does Game Session invoke the region-lease Redis script that materializes the command into `tick:{tenantRegionTag}:queue:`. - If Redis enqueue times out or returns an unknown outcome after durable admission, a missing acknowledgement is not terminal evidence: Game Session reconciles materialization under the same durable child identity using a durable materialization marker or equivalent authoritative staging/downstream-application evidence before choosing an outcome. Only a proven pre-materialization failure with proof that no staging or application occurred may converge to terminal non-applied; otherwise the retry/idempotency path remains active. Redis queue contents are never the sole proof that the automation action existed. @@ -264,7 +279,7 @@ Current implementation/proof gap: the live recovery path still terminalizes stal ## Saga Participation -Game Session includes the `common-saga` module and its migrations as a normal service dependency; the optional element is the `SagaRunner` bean and the dependency check that uses it. The current start hook uses that check only to ping Entity Management and Game Logic when those clients and the `SagaRunner` are available; when the optional bean is unavailable, the check is skipped. The saga runner is not the authority for game startup or shutdown, does not coordinate World Management's lifecycle, and is not the cross-service lifecycle-compensation mechanism. Target start-failure cleanup follows Game Session's explicit local cleanup and fenced World lifecycle calls; current implementation status is that the failed-preparation call stops at the World `FAILED_PRE_ACTIVATION` state and does not yet initiate the durable termination and owner-cleanup flow. World Management's durable lifecycle row and epoch remain authoritative, with Temporal coordinating the restart-safe lifecycle workflow; Game Session consumes that evidence and performs its owner-local session-state consequences. See [Transaction Strategies](../../system-architecture-transactions.md) and [Database-Authoritative, Temporal-Coordinated World Lifecycle](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md). +Game Session includes the `common-saga` module and its migrations as a normal service dependency; the optional element is the `SagaRunner` bean and the dependency check that uses it. The current start hook uses that check only to ping Entity Management and Game Logic when those clients and the `SagaRunner` are available; when the optional bean is unavailable, the check is skipped. Short synchronous Saga use in Game Session is limited to caller-owned dependency/startup checks; session stop uses the direct World termination seam. The saga runner is not the authority for game startup or shutdown, does not coordinate World Management's lifecycle, and is not the cross-service lifecycle-compensation mechanism. Target start-failure cleanup follows Game Session's explicit local cleanup and fenced World lifecycle calls; current implementation status is that the failed-preparation call stops at the World `FAILED_PRE_ACTIVATION` state and does not yet initiate the durable termination and owner-cleanup flow. World Management's durable lifecycle row and epoch remain authoritative, with Temporal coordinating the restart-safe lifecycle workflow; Game Session consumes that evidence and performs its owner-local session-state consequences. See [Transaction Strategies](../../system-architecture-transactions.md) and [Database-Authoritative, Temporal-Coordinated World Lifecycle](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md). ## Runtime Data Notes diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index f91d573a40..15a1dc4990 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -47,7 +47,7 @@ The local API surface retains only Logging & Admin consequences of the owner con ## REST -- `GET /ping` – basic health check returning `"pong"`. +- Current `GET /ping` – privileged Bearer JWT-protected basic health check returning an `ApiResponse` with `data: "pong"`. HTTP access accepts either a global privileged role or an applicable tenant-scoped privileged role; missing/invalid credentials return `401`, and authenticated callers without either role return `403`. The gRPC `Ping` Bearer-JWT interceptor remains unchanged. The target classification remains Public/infra health under platform health policy; the HTTP route has not converged to that target. - `GET /game-session-pins/{tenantId}/{gameInstanceId}` (`getPinnedScriptPatchVersion`) – live tenant-scoped bounded read returning `PinnedScriptPatchVersionDto` through the internal Game Session `GetPinnedScriptPatchVersion` RPC; it is not a Logging & Admin gRPC operation, and the current DTO omits `scriptPinEpoch`. - `GET /game-session-pins/{tenantId}/{gameInstanceId}/convergence` (`getGameSessionPinConvergence`) – live tenant-scoped bounded read returning `GameSessionPinConvergenceDto` through the internal Game Session `GetGameSessionPinConvergence` RPC; it is not a Logging & Admin gRPC operation, and the current DTO omits `observedScriptPinEpoch`. @@ -112,13 +112,24 @@ The internal admission-pointer service/owner paths represent exactly one of two - Replacing or rolling back `OPEN(old)` to `OPEN(new)` is a prepared cutover, not a generic open. It must use the internal `ExecutePreparedVersionCutover` control-plane operation with one durable `preparedVersionUpgradeId`; that operation revalidates the preparation, source and target identities, and CAS version before atomically swapping the route. Preparation is proof for cutover, not a substitute for route-version concurrency control. - Game Session remains the sole routing-state writer and audits the transition under the same identity and CAS result. Internal callers must not maintain a competing pointer or infer `tenantId` from `worldSlug` or `realmSlug`; Logging & Admin's public REST surface reads the resulting state and audit evidence only. +The deployed Gateway URL and listener are environment-owned; this document does not assign an HTTPS port. For an HTTPS route, set the URL to the environment's published Logging & Admin `/ping` URL and provide the issuing CA bundle so curl verifies the server certificate. The route continues to use its current privileged-JWT authentication; TLS does not imply that the target health authorization policy is implemented. + ```bash -curl http://localhost:8080/ping +curl --cacert "$FIREMUD_HTTPS_CA_CERT_PATH" \ + -H 'Authorization: Bearer ' \ + "$FIREMUD_LOGGING_ADMIN_HTTPS_URL" +``` + +The current local HTTP harness listens on `localhost:8080` without TLS. Use only a disposable, non-production privileged JWT with that loopback-only harness; never send a real operator token over it. Gateway TLS termination and the current in-cluster HTTP forwarding exception are described in [Security Architecture](../../system-architecture-security.md#tls-termination-for-gateway) and [Cross-Service Trust](../../system-architecture-security.md#cross-service-trust). + +```bash +curl -H 'Authorization: Bearer ' \ + http://localhost:8080/ping ``` ## gRPC -- `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in [`logging_admin_service.proto`](../../../../protos/logging-admin/v1/logging_admin_service.proto). +- `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in [`logging_admin_service.proto`](../../../../protos/logging-admin/v1/logging_admin_service.proto); the current gRPC interceptor requires a Bearer JWT, while the target classification remains platform health policy. - `QueryLogs(QueryLogsRequest) returns (QueryLogsResponse)` – queries the service-owned PostgreSQL `log_events` table for the exact tenant and case-insensitive message containment and returns matching stored messages; it does not query the deployed structured-log pipeline. - `ApplyModerationAction(ApplyModerationActionRequest) returns (ApplyModerationActionResponse)` – unavailable/gated implementation contract for moderation policy input/audit until the action-family schema, shared cross-language `mutationDigest/v1` golden vectors, Account authorization-reference issuance, and receiving-boundary validation/redemption exist; it now hard fails closed with an application-level `UNAVAILABLE` error before dispatch or persistence, while separate fixed-category policy/audit evidence and owner enforcement are absent, and it is not current supported external operator mutation. Target behavior uses one Account reference bound to the exact request identity/digest and redeemed exactly once by Logging & Admin for local policy-input/audit persistence; that reference is never forwarded or reused. Any future owner-enforcement command uses a separate Account reference redeemed once by its receiving owner. `EvaluateModerationPolicy` remains the live read contract used at owner enforcement boundaries and carries no mutation authorization reference. - `CreateModerationAppeal` / `GetModerationAppeal` – target-only bounded case submission and status reads. Logging & Admin owns case/evidence/jurisdiction/review state; Account supplies authenticated browser handoff and notifications, while any modified or overturned result returns a separate owner-command outcome rather than mutating enforcement locally. `DECIDED` is the terminal case fact; owner execution uses ADR 0048's phase-qualified states, and `RETRYABLE` is guidance to poll/retry reconciliation for the same command identity/digest only. No current implementation or proof is claimed. @@ -148,12 +159,23 @@ curl http://localhost:8080/ping - `ToggleFeatureFlag(ToggleFeatureFlagRequest) returns (ToggleFeatureFlagResponse)` – target owner-forwarding contract, unavailable until the minimum schema/authorization gate above and the complete [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md) durable, idempotent, fenced owner-execution contract are implemented and proved. The current gRPC ingress preserves admin-role, positive-tenant, and feature-name validation, then returns an application-level `UNAVAILABLE` error without invoking a service or owner. Once enabled, Logging & Admin is the audited forwarding ingress; Game Session owns the feature-flag mutation and its durable result. - Tick-remediation is not a Logging & Admin-owned state-mutation gRPC surface. Its HTTP ingress is hard fail closed and no Logging & Admin pause/resume forwarding method remains callable internally; the target owner contract remains unavailable until the minimum schema/authorization gate above and the complete [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md) durable, idempotent, fenced owner-execution contract are implemented and proved. Once enabled, Logging & Admin audits and forwards to Game Session, which owns tick state, fencing, idempotency, and the durable result. Future recovery operations require separate named typed owner contracts; no generic `remediate` RPC is reserved. -```bash -grpcurl -plaintext localhost:6565 logging_admin.v1.LoggingAdminService/Ping +Internal gRPC examples use the configured CA and workload certificate to verify the server and present a client identity. The target for the command is supplied by the environment; this transport example does not claim that current receiver-side workload/method authorization is implemented. The JWT shown for `CreateReport` reflects the current interim receiver contract and must be disposable/non-production. -# Non-production local harness only; production callers require the target internal workload/method authorization, which remains unproved by the current transport configuration. -grpcurl -plaintext -d '{"tenant_id":"1","reporter_account_id":"1","target_account_id":"2","type":"BUG","description":"example"}' \ - localhost:6565 logging_admin.v1.ReportService/CreateReport +```bash +grpcurl -cacert "$FIREMUD_GRPC_CA_CERT_PATH" \ + -cert "$FIREMUD_GRPC_CERT_CHAIN_PATH" \ + -key "$FIREMUD_GRPC_PRIVATE_KEY_PATH" \ + -H 'Authorization: Bearer ' \ + "$FIREMUD_LOGGING_ADMIN_GRPC_TARGET" \ + logging_admin.v1.LoggingAdminService/Ping + +grpcurl -cacert "$FIREMUD_GRPC_CA_CERT_PATH" \ + -cert "$FIREMUD_GRPC_CERT_CHAIN_PATH" \ + -key "$FIREMUD_GRPC_PRIVATE_KEY_PATH" \ + -H 'Authorization: Bearer ' \ + -d '{"tenant_id":"1","reporter_account_id":"1","target_account_id":"2","type":"BUG","description":"example"}' \ + "$FIREMUD_LOGGING_ADMIN_GRPC_TARGET" \ + logging_admin.v1.ReportService/CreateReport ``` ## Endpoint Authentication Classes @@ -162,7 +184,7 @@ Operator authentication and receiving-boundary rules are canonical in the [Autho | Surface | Examples | Required auth path | Notes | | --- | --- | --- | --- | -| Public/infra health | `GET /ping`, `Ping` | Internal network + platform health policy | Not a user-authenticated business operation. | +| Public/infra health (target; current HTTP/gRPC drift) | `GET /ping`, `Ping` | Target: internal network + platform health policy. Current HTTP `/ping`: privileged Bearer JWT; current gRPC `Ping`: Bearer JWT via interceptor. | The current HTTP route is not public: the shared interceptor returns `401` for missing/invalid credentials and `403` when the caller lacks either a global or applicable tenant-scoped privileged role. The current gRPC interceptor rejects missing/invalid credentials with `UNAUTHENTICATED`. | | Administrative report persistence (HTTP) | Unavailable; the unsafe former `POST /reports` controller and `/api/admin/reports/**` exposure were removed, and any restored administrative route uses `POST /admin/reports` | [Operator route authentication](../../system-architecture-authz-route-matrix.md#operator-delegation) | The administrative route remains unavailable until tenant scope, reporter relationship, optional target relationship, report policy, and authorization-reference checks are implemented. This is not player ingress. `POST /reports` is reserved for a separate player-bootstrap contract and must bind `player-bootstrap` authority independently. | | Read/investigation APIs (HTTP) | `/logs/query`, `/sagas*`, `GET /admission-pointers`, `GET /admission-pointers/{tenantId}/{worldSlug}/{realmSlug}/audit`, `GET /admission-pointers/version-upgrades/{tenantId}/{preparationId}`, `GET /game-session-pins/{tenantId}/{gameInstanceId}`, `GET /game-session-pins/{tenantId}/{gameInstanceId}/convergence` | The exact route-declared read auth path, normally `control-ui` plus current role and route classification | These surfaces do not mutate domain or policy state and do not receive an operator mutation reference. The two game-session-pin reads are current tenant-scoped controller routes: the REST path variables are positive decimal numeric text parsed to `long`; the controller validates positive decimal numeric `tenantId`/`gameInstanceId` values and authorized tenant scope before the internal Game Session RPC. The internal proto fields are strings carrying the same decimal numeric text, and `GameSessionPinConvergenceDto` currently emits the identifiers as JSON integer values; exact client round-trip above JavaScript's safe-integer limit is an explicit implementation gap, not a supported contract. Canonical UUID strings remain the target migration state per the [Identifier Glossary](../../system-architecture-identifier-glossary.md). They are not currently Gateway-forwarded. The other listed routes are the live admission-pointer read/audit/proof-read boundary; admission-pointer and preparation writes have no public HTTP route. | | Gated human mutation (HTTP) | Service-local `/moderation/actions` | [Operator route authentication](../../system-architecture-authz-route-matrix.md#operator-delegation) plus the action-family schema, shared `mutationDigest/v1` vectors, Account-issued authorization reference, and Logging & Admin validation/redemption | Unavailable at external Gateway ingress until the minimum schema/authorization gate and local durable intent/audit execution contract are implemented. The current service-local controller hard fails closed after its tenant-access check with HTTP `503 Service Unavailable`, without dispatch or persistence, and has no separate fixed-category audit evidence or owner enforcement. Once conformant, Logging & Admin redeems the intent reference and records durable policy intent/case/audit evidence locally; it does not forward that reference. A future owner-enforcement command is a separate contract with a separately issued reference redeemed by the receiving owner. | diff --git a/design/architecture/microservices/logging-admin-service/runtime-and-data.md b/design/architecture/microservices/logging-admin-service/runtime-and-data.md index a8953c8b6f..f58464631b 100644 --- a/design/architecture/microservices/logging-admin-service/runtime-and-data.md +++ b/design/architecture/microservices/logging-admin-service/runtime-and-data.md @@ -55,7 +55,7 @@ In addition to log and moderation tooling, the service acts as a control-plane c Game Session remains the only service allowed to mutate gameplay coordination state or execute tick pause/resume behavior. Logging & Admin owns operator UX, automation policy, and audit only; it does not become the runtime state owner for remediation. -There is no generic remediation command language. Ordinary actions use named owner contracts. Composed recovery exposes only a small high-level vocabulary such as pause, status, recover or reset, and resume through one durable workflow owner. Exceptional direct Redis maintenance remains separate version-matched break-glass tooling with dedicated narrow credentials, forced verification, and recovery evidence; Logging & Admin may invoke that owner or tool but never receives those credentials itself. +There is no generic remediation command language. Ordinary actions use named owner contracts. Composed recovery exposes only a small high-level vocabulary such as pause, status, recover or reset, and resume through one durable workflow owner. The evidence-qualified `replay_first`/`reset_first` selection and external durable maintenance operation/fence remain owned by [Redis Reset & Recovery](../../system-architecture-redis-reset-and-recovery.md); the named maintenance operation is target-state-only and unavailable for current invocation until its owner contract and complete evidence and release gates are implemented and proved. Logging & Admin may display that owner's projection and, once available under the owner's gates, request the named operation, but neither its projection nor its coordinator role is runtime authority or the maintenance fence. Exceptional direct Redis maintenance remains separate version-matched, incident-only break-glass tooling with dedicated narrow credentials, forced verification, and recovery evidence; without the target tooling, the current path is evidence preservation, fencing, and escalation, and Logging & Admin never receives or holds those credentials. Operator and support diagnostics do not impersonate a player, attach to a live player session, or observe gameplay through a hidden actor. They use purpose-built, minimized support-safe reads, logs, dashboards, reports, moderation records, and explicit control-plane operations. Break-glass controls remain separately authorized and audited and must not create a player actor, gameplay session, or tenant-scoped gameplay capability. @@ -130,6 +130,6 @@ When enabled, policy intent, case, appeal, owner-result, and audit records are r ## Saga Dashboard -The service exposes `/sagas` and `/sagas/{id}/steps` endpoints for operators to inspect short synchronous orchestration coordinated via the shared Saga library. These routes read Logging & Admin-local rows only, do not aggregate adopter-local state, return `404 NOT_FOUND` for an unknown Saga instance, and preserve `200` with an empty list for a known instance with no steps. If the conditional Saga/database beans are unavailable, they fail closed with `503 SAGA_DASHBOARD_UNAVAILABLE`. Durable long-running workflow inspection belongs on the corresponding Temporal adopter read surfaces, not on the shared saga dashboard. The dashboard reads from the `saga_instance` and `saga_step` tables and publishes a `sagas.active` Prometheus gauge. +The service exposes `/sagas` and `/sagas/{id}/steps` as local-schema-only read surfaces for short synchronous orchestration coordinated via the shared Saga library. They read only this service's `${serviceSchema}.saga_instance` and `${serviceSchema}.saga_step` tables, expose no foreign-service state, acquire no execution authority, return `404 NOT_FOUND` for an unknown Saga instance, and preserve `200` with an empty list for a known instance with no steps. If the conditional Saga/database beans are unavailable, they fail closed with `503 SAGA_DASHBOARD_UNAVAILABLE`. A future cross-service dashboard must fan out through read-only per-service Saga status APIs rather than read foreign databases or execute Saga actions. Durable long-running workflow inspection belongs on the corresponding Temporal adopter read surfaces, not on the shared saga dashboard. The local dashboard publishes a `sagas.active` Prometheus gauge. See [Transaction Strategies](../../system-architecture-transactions.md) for an overview of Saga usage across FireMUD. diff --git a/design/architecture/microservices/world-management-service/world-creation-workflow.md b/design/architecture/microservices/world-management-service/world-creation-workflow.md index f4a18ea950..742fb1afaa 100644 --- a/design/architecture/microservices/world-management-service/world-creation-workflow.md +++ b/design/architecture/microservices/world-management-service/world-creation-workflow.md @@ -1,6 +1,6 @@ # World Creation Workflow -World creation is a long-running process that prepares the initial world state for a new **game instance** using already-published world data for a given `tenantId`. The workflow now runs on the shared **Temporal** substrate so prepare/activate/fail/terminate orchestration survives service restarts, keeps deterministic workflow identity, and exposes operator-visible execution status without pulling gameplay runtime onto the workflow engine. [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) owns lifecycle authority and all-owner cleanup convergence; this document records the World workflow consequence. [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) owns stable playable identity and replacement classification. World Management's activation lifecycle surface is invoked when the platform provisions a new game instance for an existing tenant, typically from the Game Session Service. The identifiers involved are: +Target state: World creation is a long-running process that prepares the initial world state for a new **game instance** using already-published world data for a given `tenantId`. The target workflow runs on the shared **Temporal** substrate so prepare/activate/fail/terminate orchestration survives service restarts, keeps deterministic workflow identity, and exposes operator-visible execution status without pulling gameplay runtime onto the workflow engine. The current implementation/proof is partial: extracted prepare/activate/status and a synchronous termination seam exist, but complete restart-safe lifecycle, durable step guards, frozen all-owner cleanup, and termination proof remain incomplete. [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) owns lifecycle authority and all-owner cleanup convergence; this document records the World workflow consequence. [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) owns stable playable identity and replacement classification. World Management's activation lifecycle surface is invoked when the platform provisions a new game instance for an existing tenant, typically from the Game Session Service. The identifiers involved are: - `tenantId` – identifies the game (tenant) as described in [Multi-Tenancy](../../system-architecture-multi-tenancy.md). @@ -11,7 +11,7 @@ World creation is a long-running process that prepares the initial world state f the Game Session Service. - `playableStateNamespaceId` – identifies durable playable state independently of the replaceable runtime instance. World retains the resolved namespace across replacement and uses the instance id only for topology and other explicitly instance-scoped state. -The cross-platform workflow placement and adopter-proof requirements are owned by [Transaction Strategies](../../system-architecture-transactions.md#mandatory-workflow-adopter-classification) and [Temporal Control-Plane Workflows](../../system-architecture-temporal-workflows.md). This document records the World Management consequences: the target `world-lifecycle` workflow coordinates the local lifecycle commands and read surface, while World Management's durable lifecycle row and epoch remain authoritative, with durable launch/workflow identity plus shared digest-bound step identity (stable step name, deterministic occurrence, execution role, and immutable request digest; see [ADR 0078](../../decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md)). Gameplay ticks and live in-world mutations remain outside this workflow. Current lifecycle proof covers the extracted command path and Temporal-backed status surface, while full durable step-guard and restart/failure proof remains an implementation gap noted below. +The cross-platform workflow placement and adopter-proof requirements are owned by [Transaction Strategies](../../system-architecture-transactions.md#mandatory-workflow-adopter-classification) and [Temporal Control-Plane Workflows](../../system-architecture-temporal-workflows.md). This document records the World Management consequences: the target `world-lifecycle` workflow coordinates the local lifecycle commands and read surface, while World Management's durable lifecycle row and epoch remain authoritative. Its canonical Temporal workflow ID is `world-lifecycle::game-instance:`, stable per `(tenantId, gameInstanceId)` across workflow run replacement, and retries use that workflow identity plus durable launch/workflow identity and the shared digest-bound step identity (stable step name, deterministic occurrence, execution role, and immutable request digest; see [ADR 0078](../../decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md)). Gameplay ticks and live in-world mutations remain outside this workflow. Current lifecycle proof covers the extracted command path and Temporal-backed status surface, while full durable step-guard and restart/failure proof remains an implementation gap noted below. The current `TemporalWorldLifecycleOrchestrator` also treats `WorkflowExecutionAlreadyStarted` as reuse and returns the existing snapshot without exact-comparing its complete immutable prepared-launch identity with the incoming request. Until that race path validates at least the exact `controlPlaneRequestId` and `launchDescriptorId` plus every other immutable `PreparedWorldInstanceRequest` field, a conflicting request can observe the existing workflow as a successful retry; this is an implementation and race-proof gap, not target authorization to reuse a mismatched workflow. ## Implementation Status @@ -32,7 +32,7 @@ World creation consumes a previously resolved immutable launch descriptor for th For replacement-instance launches, World Management now persists the frozen `remapSetId` on `world_instance` so later cutover/termination consumers can prove they are still operating on the same approved cross-version remap identity that launch resolution selected. -Game Design owns the immutable mapping from `` to `launchDescriptorId`. After validating that descriptor, the Game Session instance-creation orchestrator owns the durable mapping from the same launch attempt and `launchDescriptorId` to one `gameInstanceId`; an exact retry reuses both mappings, while a conflicting descriptor, template, or instance fails closed. World workflow execution consumes those identities under the distinct business scope ``, while each lifecycle step uses the shared digest-bound workflow/step guards and its deterministic occurrence and role. `controlPlaneRequestId` is the sole launch/workflow request identity; neither a separate world-creation request ID, a Temporal run/attempt identity, nor a generated instance may replace it. +Game Design owns the immutable mapping from `` to `launchDescriptorId`. After validating that descriptor, the Game Session instance-creation orchestrator owns the durable mapping from the same launch attempt and `launchDescriptorId` to one `gameInstanceId`; an exact retry reuses both mappings, while a conflicting descriptor, template, or instance fails closed. The canonical Temporal workflow ID is `world-lifecycle::game-instance:`, stable across workflow run replacement. `controlPlaneRequestId` and `launchDescriptorId` remain immutable launch/request and digest/step evidence bound to that workflow; they are not workflow-ID components. Each lifecycle step uses the shared digest-bound workflow/step guards and its deterministic occurrence and role. The target workflow uses the published world topology for the chosen `tenantId` and `version_id`, inserts a starter region instance, and can generate terrain chunks and materialize instance-scoped population schedules for expansive worlds. Any initial event scheduling remains subject to the owning typed effect contract; while the Weather aggregate selector is unresolved, initial Weather scheduling is explicitly deferred and non-mutating. Activation-time topology must be derived only from the attested published template graph plus runtime generation runs whose canonical inputs are covered by the same published `generationConfigRevision`. Throughout the workflow, the Temporal workflow and its activities: @@ -130,7 +130,7 @@ Illustrative operator-facing workflow status fragment: ```json { "workflowFamily": "world-lifecycle", - "workflowId": "world-lifecycle:7b3b074e-d597-4e9b-b96f-4f5946d26120:world-instance:9a2bb6d1-74c7-4f81-a9e8-418e65f6ad78:request:wc-77", + "workflowId": "world-lifecycle:7b3b074e-d597-4e9b-b96f-4f5946d26120:game-instance:9a2bb6d1-74c7-4f81-a9e8-418e65f6ad78", "workflowStatus": "RUNNING", "tenantId": "7b3b074e-d597-4e9b-b96f-4f5946d26120", "gameInstanceId": "9a2bb6d1-74c7-4f81-a9e8-418e65f6ad78", @@ -150,7 +150,7 @@ Illustrative operator-facing workflow status fragment: World creation steps write durable instance rows and must be safely retryable under the general workflow/request and step-guard contract owned by [Transaction Strategies](../../system-architecture-transactions.md) and explained by [ADR 0078](../../decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md). This adopter document supplies workflow-local inputs without redefining the guard policy: -- Stable business scope is the resolved launch attempt for `` and its immutable `launchDescriptorId`. +- Stable business scope is the resolved world instance for ``. The immutable `controlPlaneRequestId` and `launchDescriptorId` remain bound launch/request and digest/step evidence for that workflow identity. - The stable step name identifies the lifecycle operation, while a deterministic occurrence key distinguishes each logical occurrence of that operation; for generation stages, the target-state `generationRequestId` is part of that occurrence input so retries across workflow runs converge on the same logical generation result. Its allocation and propagation remain unimplemented as noted above. - The execution role distinguishes forward preparation/activation work from applicable pre-activation compensation; it is not inferred from a Temporal run, process, retry attempt, or message/delivery identifier. - The immutable request-digest input covers the exact resolved launch descriptor and step request values used by the operation, including `expectedGenerationConfigRevision` and, where applicable, `generationRequestId`. Digest construction, persistence, comparison, and guard storage remain governed by the shared contract and are not specified here. @@ -172,6 +172,12 @@ The current `TemporalWorldLifecycleOrchestrator` workflow ID is derived only fro Temporal owns orchestration and workflow progress using the canonical `world-lifecycle` workflow identity; World Management's durable lifecycle row and epoch remain authoritative for lifecycle state. Operators can inspect progress through the normal lifecycle read surface and any Temporal-backed operator tooling that projects the same `workflowId`. +### Lifecycle signal identity and serialization + +The target workflow must represent each activate, fail, or terminate request as a durable queued signal/update envelope carrying a stable operation identity, normalized request digest, and expected lifecycle epoch/status. Owner-generated CAS evidence is recorded in the result only after the local lifecycle CAS commits as the winner; it is not request-envelope authority. Exact retries read back one logical result; changed identity, digest, status, or epoch fails closed, and conflicting lifecycle operations follow explicit precedence/conflict rules rather than last-writer-wins behavior. A signal may not be combined with or overwrite another logical operation whose outcome is still unresolved. + +**Current implementation gap:** `TemporalWorldLifecycleWorkflowImpl` stores only one pending epoch/reason per signal type and has no operation identity or digest. Repeated same-type signals overwrite one another, while an activate and terminate received together are both processed sequentially; termination then reuses the pre-activation epoch after activation has advanced it, with stale-epoch retries bounded to five termination-activity attempts. The current `TemporalWorldLifecycleOrchestrator`/workflow path therefore does not provide one durable lifecycle result for concurrent or lost signal requests. This is in addition to the existing `AlreadyStarted` identity-comparison gap above and remains unproved until the queued envelope, owner lifecycle CAS, conflict handling, and readback result are implemented. + See [World Management Service](README.md) for additional service context. See [Transaction Strategies](../../system-architecture-transactions.md) for the canonical boundary between ticks, short synchronous saga orchestration, and durable Temporal workflows. @@ -181,7 +187,7 @@ See [Transaction Strategies](../../system-architecture-transactions.md) for the Instance expiry and operator-driven shutdown must use an explicit cross-service termination workflow rather than independent cleanup jobs. - Game Session must first mark the target instance non-admissible/draining before World starts termination. -- World Management starts or resumes the canonical `world-lifecycle` Temporal workflow and performs a storage-level compare-and-set from `PREPARING`, `FAILED_PRE_ACTIVATION`, or `ACTIVE` to `TERMINATING` under the expected lifecycle epoch. A stale activation cannot reopen the instance. +- World Management starts or resumes the canonical `world-lifecycle` Temporal workflow and performs a storage-level compare-and-set from `PREPARING`, `FAILED_PRE_ACTIVATION`, or `ACTIVE` to `TERMINATING` under the expected lifecycle epoch. A stale activation cannot reopen the instance; a stale termination epoch fails closed and may be retried only from fresh lifecycle state, bounded to five termination-activity attempts. - When a stable `terminationRequestId` begins, the workflow freezes and persists the exact required cleanup-owner set together with the matching ownership-registry revision as that termination's owner snapshot, with separate per-owner cleanup acknowledgement state. Every retry of that exact request, per-owner cleanup request/acknowledgement, and final `TERMINATING -> TERMINATED` compare-and-set must bind and exact-compare the same snapshot; only owners in it are required for that termination attempt. A mid-flight ownership-registry change cannot silently add or drop owners or claim completion. Each owner runs an idempotent local cleanup step under its own durable guard; Temporal workflow/run identity is execution trace only. A `TERMINATED` fast path must first exact-compare the supplied `terminationRequestId` with the retained terminal identity: a matching retry returns the stored terminal success, while a mismatch returns `IDEMPOTENCY_CONFLICT` without changing lifecycle state. The focused proof must cover that comparison and the failure/retry path that leaves the instance in `TERMINATING` until all frozen owners acknowledge. - World Management finalizes world-side cleanup and marks the instance `TERMINATED` only after every owner in the frozen snapshot acknowledges cleanup and the final compare-and-set succeeds against that same snapshot. The target World acknowledgement covers completion of every registered World-owned S3 family applicable to the terminating modern `world_instance`/`gameInstanceId` scope in the canonical [replacement-instance state classification](runtime-and-data.md#replacement-instance-state-classification). The legacy zone-child `instance` family is explicitly excluded from this parent acknowledgement and follows its separate scoped, idempotent cleanup operation; it does not gate parent `InstanceTermination`. Entity Management removes its synthetic room-ground containers and containment rows. World-owned local cleanup must complete before World acknowledges its participant obligation; it does not replace the other owners' acknowledgements. - If preparation reaches `FAILED_PRE_ACTIVATION`, its admission remains closed while the separate owner-scoped cleanup state can continue or be repaired; the failure result is not cleanup proof. diff --git a/design/architecture/system-architecture-gateway.md b/design/architecture/system-architecture-gateway.md index 676d374abe..77862649dc 100644 --- a/design/architecture/system-architecture-gateway.md +++ b/design/architecture/system-architecture-gateway.md @@ -398,10 +398,12 @@ This section is the canonical source of truth for connect-token enforcement and - A hard Account or security revocation blocks new issuance for the revoked account or authority. A successful consume is terminal for that exact token `jti`. A deny-marker write becomes a confirmed terminal denial only after its configured same-connection `WAITAOF` acknowledgement succeeds; Gateway then never admits that `jti` again during its remaining acceptance window. Consuming one token does not prevent a later independently authorized issuance with a new request identity and `jti`. Gateway evaluates the token against its deployment-approved synchronized UTC epoch-millisecond wall clock: target future-`iat` tolerance permits acceptance no earlier than `iat - firemud.gateway.connectTokenClockSkewMs`, and target expiry tolerance permits acceptance no later than `exp + firemud.gateway.connectTokenClockSkewMs`. Therefore, when `exp - iat` is at the 30-second hard maximum, the complete possible acceptance interval is at most 30 seconds plus two configured skew intervals (40 seconds at the default 5-second skew); measured from the signed `iat` to the latest consume, the bound is 30 seconds plus one skew interval. An unavailable, timed-out, malformed, below-threshold, or otherwise ambiguous deny write is unconfirmed: the marker may have been written and Gateway must deny if it observes it, but the caller retains the bounded token-window outcome until the write is durably acknowledged or the token expires and must not report terminal no-grace revocation earlier. - Account owns two logically isolated, prefix-separated connect-token issuance-result families for idempotent `/auth/connect-token` retries: the current unversioned legacy `session:connect-token:tenant::account::scope::request:` map and the target `session:connect-token:v1:tenant::account::scope::request:` projection. **Current runtime:** the legacy value contains the raw issued token or deterministic cached failure. **Target state:** the target value carries `schemaVersion: "connect-token-issuance-result-v1"` and a bounded Account-encrypted response envelope containing the exact result, opened for an exact retry only after current authority and issuance state are reconciled; it is not JWT reconstruction or admission authority. Target readers never fall back to the legacy family. Because the legacy writer lacks an issuance fence, target enablement requires full Account-cohort quiescence, in-flight drain, and the configured legacy TTL/retry horizon. The full persistence contract is owned by [Account connect-token issuance persistence](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Gateway alone owns the target replay-consumption, browser-revocation denial, and readiness/fence state in the Coordination Redis contract; an issuance-result projection, replay marker, deny marker, and readiness record never substitute for each other. - Replay and browser-revocation marker ownership is Gateway-only; downstream services do not participate in connect-token replay or browser-deny checks. - - Replay checks must be backed by the player-facing Coordination Redis deployment (not Cache/Rate-Limit Redis or per-pod memory) so `jti` replay decisions are consistent across horizontally scaled gateway pods and cannot be selectively evicted. The deployment requires Redis 7.2+ with AOF enabled, `noeviction`, replay-key ACL isolation, and admission-blocking capacity thresholds. The atomic marker script is followed by `WAITAOF requiredLocalAofCount requiredReplicaAofCount timeout`; `DURABLE_REPLAY_CONSUME_ACK` succeeds only when the reported AOF-fsync counts meet the configured thresholds, with at least one local AOF acknowledgement. The browser-deny write uses the same pinned Coordination connection and configured timeout/threshold after the write; its propagation remains in the default `redis.REPL_ALL` mode. An unavailable, timed-out, malformed, below-threshold, or otherwise ambiguous deny write is unconfirmed and cannot be reported as terminal revocation. `WAIT`, read-back, or a successful client write is not a substitute, and this contract does not claim protection from disk or hardware destruction. + - Replay checks must be backed by the player-facing Coordination Redis deployment (not Cache/Rate-Limit Redis or per-pod memory) so `jti` replay decisions are consistent across horizontally scaled gateway pods and cannot be selectively evicted. The deployment requires Redis 7.2+ with AOF enabled, `noeviction`, replay-key ACL isolation, and admission-blocking capacity thresholds. The atomic marker script is followed by `WAITAOF requiredLocalAofCount requiredReplicaAofCount timeout`; `DURABLE_REPLAY_CONSUME_ACK` succeeds only when the reported AOF-fsync counts meet the configured thresholds, with at least one local AOF acknowledgement. The browser-deny write uses the same pinned Coordination connection and configured timeout/threshold after the write; if a valid marker already exists, reassert it with its unchanged original absolute expiry before `WAITAOF`, or withhold the durable acknowledgement until the original write's durability is proven. Never extend its expiry; malformed or conflicting marker state stays non-mutating and fails closed. Its propagation remains in the default `redis.REPL_ALL` mode. An unavailable, timed-out, malformed, below-threshold, or otherwise ambiguous deny write is unconfirmed and cannot be reported as terminal revocation. `WAIT`, read-back, or a successful client write is not a substitute, and this contract does not claim protection from disk or hardware destruction. - Replay and browser-revocation state use the canonical target representation defined by the Redis ownership and recovery documents, with bounded cardinality and deterministic expiry at `exp + firemud.gateway.connectTokenClockSkewMs`. The readiness/fence record and marker state must remain one script-compatible Coordination Redis atomicity domain under that contract. The legacy representation emitted by the current writer is migration-only drift and cannot be treated as target state. - The replay and deny-marker prefixes are security-critical, non-evicting coordination state. Gateway's one consume script checks readiness state, signed fence/cutoff, and deny-marker absence before creating the replay marker; consumption is successful only after that script and the configured Redis 7.2+ `WAITAOF` acknowledgement both succeed. A deny marker that linearizes before or during the consume race returns a denial without creating the replay marker; a consume already linearized is spent and cannot be retroactively undone by a later browser logout. A browser revocation is confirmed only after its deny write and same-connection durability acknowledgement succeed; an uncertain deny write remains unconfirmed. Capacity or acknowledgement failure rejects the handshake rather than accepting an uncertain marker. A crash or connection loss between marker creation and acknowledgement is treated as uncertain consumption, not as an opportunity to unconsume or retry the token. - - Coordination Redis cold start, reset, unexpected eviction signal, failover, capacity-safety breach, or any other event that cannot prove replay-marker continuity starts a shared replay-protection quarantine for at least the 30-second token lifetime maximum plus two `firemud.gateway.connectTokenClockSkewMs` intervals. One interval covers a latest tolerated future `iat`; the second covers acceptance through `exp + skew`. Account stops issuing connect tokens and Gateway rejects admission until that barrier expires, configuration and capacity checks pass, and a disposable marker script followed by the configured `WAITAOF` thresholds proves `DURABLE_REPLAY_CONSUME_ACK`; tokens from the earlier fence and issuance races cannot survive reopening. The current replay deployment has one shared continuity domain, so an unscoped continuity failure intentionally blocks new connect-token issuance and admission platform-wide; a future partitioned deployment may narrow quarantine only when it can prove the exact affected marker and fence domain. + - Coordination Redis cold start, reset, unexpected eviction signal, failover, capacity-safety breach, or any other event that cannot prove replay-marker continuity starts a shared replay-protection quarantine for at least the 30-second token lifetime maximum plus two `firemud.gateway.connectTokenClockSkewMs` intervals. One interval covers a latest tolerated future `iat`; the second covers acceptance through `exp + skew`. When the latest expiry of an affected token is known, the quarantine deadline also covers that token's `exp + firemud.gateway.connectTokenClockSkewMs`; the deadline is the later of these bounds, and admission must never reopen before it. This deadline rule is defined by [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md). Account stops issuing connect tokens and Gateway rejects admission until that barrier expires, configuration and capacity checks pass, and a disposable marker script followed by the configured `WAITAOF` thresholds proves `DURABLE_REPLAY_CONSUME_ACK`; tokens from the earlier fence and issuance races cannot survive reopening. Before normal release, old Gateway replay writers must be drained or authoritatively blocked and the complete tagged replay state and readiness/fence state must be authoritative, in addition to the lifetime, skew, configuration/capacity, and disposable-marker `WAITAOF` gates above. If any old-version writer or admission remains allowed, release additionally requires a separately proven cross-version guard; none is currently implemented or proven, so that mixed-version release path remains forbidden. The current replay deployment has one shared continuity domain, so an unscoped continuity failure intentionally blocks new connect-token issuance and admission platform-wide; a future partitioned deployment may narrow quarantine only when it can prove the exact affected marker and fence domain. + - Recovery obtains post-reset replay readiness through a logical typed Gateway-owned probe, invoked automatically by the trusted recovery coordinator through the existing authenticated owning-service maintenance API boundary. This is target behavior, not a new public RPC or an implemented operation. The probe is bound under the existing Redis owner contracts to the exact durable maintenance operation and fence, the shared replay domain, expected `replayAdmissionFence`, and authoritative quarantine/readiness, configuration, and capacity evidence. While shared readiness remains `QUARANTINED`, Gateway uses one pinned Coordination Redis connection to conditionally write a Gateway-generated disposable marker at `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::` only if the exact operation/fence, replay domain, fence, and quarantine state still match, then immediately issues configured `WAITAOF` on that same connection with no intervening write. The nonce is Gateway-generated, not caller-supplied. The probe does not accept or consume a player JWT, real `jti` replay marker, or browser-deny marker, and does not write shared readiness. It succeeds only when the marker is created, configured local and replica durability thresholds are met, and subsequent readback still proves the same operation/fence, replay domain, replay fence, quarantine state, configuration, and capacity conditions. Connection loss, threshold timeout, malformed or uncertain result, or changed evidence fails closed; Gateway never retries an old marker to claim a new acknowledgement. Cleanup is a separate exact-operation/fence-guarded write and readback after acknowledgement and evidence readback; it cannot supply or replace the acknowledgement. Normal player consume remains `OPEN`-only and is never invoked during quarantine. A successful probe is evidence for the coordinator, not permission to enable player admission: only the coordinator may authorize reopening after the deadline, exact fenced probe evidence, and all other owner release gates succeed. The operation and its producer/consumer proof are currently unimplemented, so the post-reset checklist is not yet executable for this gate. Until implemented and proved under [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md), issuance and player admission remain closed. + - The probe uses only the Gateway-generated exact key family, nonce, and marker value; callers cannot supply key material or redirect a probe to player replay/deny prefixes. Its marker uses a finite bounded expiry, followed by separate exact-operation/fence-guarded cleanup and readback outside `WAITAOF`. The coordinator authorizes release only after all gates pass, then uses Gateway's existing authenticated owner-maintenance boundary; Gateway's owner-local helper performs the readiness compare-and-set. Recovery remains API-only and does not receive raw Redis authority. See [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md) for the canonical probe lifecycle. - Replay-quarantine lifecycle is a monitored security state. Gateway must emit low-cardinality `gateway.connect_token.replay_quarantine_entries_total{reason=...}`, `gateway.connect_token.replay_quarantine_exits_total{outcome=...}`, `gateway.connect_token.replay_quarantine_active`, and `gateway.connect_token.replay_quarantine_duration_seconds`, plus structured records containing the shared `replayAdmissionFence`, `state`, `quarantineStartedAt`, `quarantineUntil`, and `openedAt` values. Alertmanager must alert when a player-facing quarantine is entered, remains active past `quarantineUntil` or has no observed exit, or exits without fresh `DURABLE_REPLAY_CONSUME_ACK` proof. Dashboards must show entry/exit counts and duration. Labels must exclude `jti`, tenant identifiers, and other high-cardinality values. - Replay-cache outage behavior: - Player-facing environments (`/ws/game/**` in `enforce` mode): fail closed with HTTP `403` and `CONNECT_REPLAY_PROTECTION_UNAVAILABLE` when replay protection is unavailable. diff --git a/design/architecture/system-architecture-identifier-glossary.md b/design/architecture/system-architecture-identifier-glossary.md index 981cfe08b3..8a8fd9e781 100644 --- a/design/architecture/system-architecture-identifier-glossary.md +++ b/design/architecture/system-architecture-identifier-glossary.md @@ -84,9 +84,11 @@ World Management may use a numeric room row key as `roomInstanceId` only when it Tick-driven, cross-service mutations are at-least-once and must be idempotent. -- `EffectId` – the stable root identity for one logical effect. Game Session assigns it once from the admitted operation and its authoritative tick context; ordinary retry, recovery, and replay preserve it. It is not derived from mutable payload or regenerated for a replay. A fresh root is reserved for a **post-abandon re-drive**: the original effect must be conclusively terminal `ABANDONED` with its source claim terminalized, then recovery allocates a later coordinate, fresh root, new retry/source identity, and durable lineage. An implementation may store it opaquely only when the canonical identity projection remains retained or deterministically recoverable. -- **Participant guard identity** – a deterministic uniqueness identity derived from exactly the root `EffectId`, typed operation, and target aggregate. Its durable guard binds that identity to the immutable request digest; the durable outcome and other evidence/reconciliation fields are mutable guard-row state protected by CAS, not part of uniqueness identity. Same guard identity with the same request returns the prior result; a changed operation, target, or digest fails closed. Derived reactions receive deterministic child `EffectId` values. -- The root effect identity, required participant set, and participant outcomes are Game Session reconciliation data. The durable guard/effect behavior is owned by [Transaction Strategies](./system-architecture-transactions.md) and must not be replaced with an ad-hoc service-local key. +- `EffectId` – the persisted mutation identity for one logical effect. Retries, replay, and reconciliation must preserve the same mutation identity and validate the immutable request digest under the accepted effect contract. A generated child has its own persisted child `EffectId` while retaining enclosing-root and parent lineage where applicable. Current Entity replay looks up by `(tenantId, effectId)` but does not validate a request digest, so it does not prove this target contract. Command-root allocation details remain pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). +- `deterministic effect plan` – a proposed ordered set of command-root effects described in pending [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); it is not an accepted canonical term or requirement. +- `planOrdinal` – a proposed command-root allocation field described in pending [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); it is not an accepted identity or ordering contract. +- **Participant guard identity** – a deterministic uniqueness identity under the owning runtime-family contract. For owner-classified S1/S2 families, the durable guard partition is `(tenantId, playableStateNamespaceId)` plus the owning identity/effect (`EffectId`, typed operation, and target aggregate); `gameInstanceId` is not a uniqueness dimension and is carried and exact-validated separately as active-runtime authorization/fence evidence. Only an explicitly owner-classified S3 family uses `(tenantId, gameInstanceId)` as its durable partition; an unknown or unclassified family is rejected before any participant-guard allocation or admission and is never treated as S3 by default. A root effect uses its root `EffectId`; a generated child mutation uses its persisted child `EffectId`, while the enclosing root remains lineage and reconciliation context rather than collapsing sibling guards. The owner must allocate and durably persist each generated child's ordinal and owner-scope/root/parent/ordinal-to-child-`EffectId` mapping under the accepted owner contract; deterministic child-ID derivation is only proposed by pending [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) and is not current target. The ordinal is not a second guard-key field. For S1/S2, `playableStateNamespaceId` is the uniqueness partition; `playableStateScope` and `gameInstanceId` are separately persisted, exact-validated routing/authorization/fence evidence and are not additional uniqueness dimensions. Same family-partitioned guard identity with the same request and evidence returns the prior result; a changed tenant, namespace, owning effect, operation, target, scope, digest, or separately validated active-instance fence fails closed. Work explicitly outside playable-state scope must use an accepted owner-specific idempotency/partition contract; it cannot omit namespace/scope and proceed under this gameplay participant-guard contract. The durable outcome and other evidence/reconciliation fields are mutable guard-row state protected by CAS, not part of uniqueness identity. A conserved multi-participant operation normally shares one effect identity but still follows [ADR 0053](./decisions/adr-0053-command-atomicity-by-invariant-class.md)'s atomicity/co-location/reservation semantics. +- The root effect identity, required participant set, and participant outcomes are Game Session reconciliation data. The durable plan allocation and guard/effect behavior are owned by [Transaction Strategies](./system-architecture-transactions.md) and must not be replaced with an ad-hoc service-local key. ## Cross-Service Causal-Read Fence Identity diff --git a/design/architecture/system-architecture-overview.md b/design/architecture/system-architecture-overview.md index a29c60ef9b..24d7824cf3 100644 --- a/design/architecture/system-architecture-overview.md +++ b/design/architecture/system-architecture-overview.md @@ -54,7 +54,7 @@ The documents linked from this overview describe the target-state design, but th - **Redis topology policy:** In all non-ephemeral environments, Coordination Redis and Cache/Rate-Limit Redis are separate deployments. Local development is treated as non-ephemeral and should run two Redis deployments to exercise role separation. Only an explicitly labelled one-shot test/CI stack may collapse roles into a single Redis instance, and it must be guarded as an ephemeral topology; hosted `pr-preview` is not exempt. - **Coordination Redis ownership boundary:** Coordination Redis prefixes and fences are owner-governed (Game Session for gameplay coordination prefixes such as `session:game:*`, `tick:*`, `timer:*`, `retry:*`, and `tick-executor-lease:*`; Account Service for the registered auth-session and exact-input issuance-result families; Automation & Scripting for its documented scheduling families; Spring Cloud Gateway only for the narrow edge replay/denial contract), and no wildcard grant over future families is implied. The Account connect-token family is distinct from Gateway replay markers and follows its Account-owned fail-closed reset/recovery consequence. Gateway's exception does not grant it general Coordination Redis ownership. Non-owner participation is allowed only through documented shared-helper contracts. See [ADR 0009](./decisions/adr-0009-coordination-redis-ownership-boundary.md), [Redis Coordination Invariants](./system-architecture-redis.md#coordination-vs-cache-prefixes), the [reset policy matrix](./system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary), and the Gateway replay/denial contract in [Gateway Architecture](./system-architecture-gateway.md). - **TCP Proxy identity canonicalization:** Gateway selects exactly one environment-bound TCP Proxy trust profile. Steady-state player-facing deployments require the exact environment-specific URI SAN identity; named DNS migration and fingerprint break-glass profiles are explicit and expiring, while CIDR trust is development/test-only. See [ADR 0169](./decisions/adr-0169-exclusive-environment-bound-tcp-proxy-trust.md). -- **Canonical room-read composition:** [Transaction Strategies](./system-architecture-transactions.md) owns split spatial authority and operation-bound effect behavior. The [Identifier Glossary](./system-architecture-identifier-glossary.md#cross-service-effect-identity) owns root `EffectId`/participant identity, and its [causal-read fence contract](./system-architecture-identifier-glossary.md#cross-service-causal-read-fence-identity) owns the requested floor and composite identity. Game Logic composes World occupancy with Entity presentation under those owner contracts; see [Canonical Room Runtime Contract](#canonical-room-runtime-contract). +- **Canonical room-read composition:** [Transaction Strategies](./system-architecture-transactions.md) owns split spatial authority and operation-bound effect behavior. The [Identifier Glossary](./system-architecture-identifier-glossary.md#cross-service-effect-identity) owns root `EffectId`/participant identity and enclosing-root lineage, and its [causal-read fence contract](./system-architecture-identifier-glossary.md#cross-service-causal-read-fence-identity) owns the requested floor and composite identity. Game Logic composes World occupancy with Entity presentation under those owner contracts; see [Canonical Room Runtime Contract](#canonical-room-runtime-contract). Exact generated-child allocation remains non-authoritative in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). - **Canonical room-read interoperability:** The current live proto seam carries World `worldSnapshotId` / `world_snapshot_id` and Entity `entitySnapshotId` / `entity_snapshot_id` as deterministic scope markers only; both request paths are floor-free. Game Session allocates the complete target `CausalReadFence`, including `regionId`, from durable region commit authority before invoking `ResolveLook`, and Game Logic propagates that floor unchanged to World and Entity. Each participant returns the same region/scope/epoch proof, a scoped `servedThroughTickId`, and an opaque component version. Same-region/scope/epoch responses with `servedThroughTickId >=` the requested `committedTickId` are accepted; a participant behind the floor or mixed region/scope/epoch is rejected or retried, and opaque component versions are not directly compared. The composed identity exposes only the requested floor plus World and Entity component versions; `servedThroughTickId` is response validation proof, not an additional identity member. The target request/response and composite-proof protocol is not present in the current adapter/proto path. - **Durable cross-region effects and static live topology:** Cross-region gameplay uses durable asynchronous legs and current-epoch/executor-fence validation rather than shared region locks. Origin commit means the remote leg is durably scheduled, not that the whole command succeeded; old-epoch work is terminalized only when authority-fenced evidence proves it applied or was unapplied under [ADR 0067](./decisions/adr-0067-abandon-old-epoch-work-and-reschedule-with-new-lineage.md). Inconclusive old-epoch work remains fenced, non-terminal, and reconciliation-required, blocking new lineage and reopen. A normally open instance has static region topology; split/merge is an operator-controlled maintenance cutover with admission barriers, bounded drain, evidence-qualified terminalization, durable mapping installation, Redis rebuild, and controlled reopen. See [ADR 0055](./decisions/adr-0055-durable-cross-region-effects-with-static-live-topology.md). - **Logical-effect reconciliation authority:** Game Session owns one durable reconciliation record per logical effect, freezes its expected participant set at admission, derives the cross-owner player outcome, and runs retries in isolated resource-bounded workers. World, Entity, and other domain services retain write authority and report their durable participant outcomes; they do not create competing retry ledgers. See [ADR 0057](./decisions/adr-0057-game-session-owned-reconciliation-with-isolated-workers.md). @@ -665,9 +665,9 @@ To avoid drift between gameplay orchestration, entity state, and world occupancy 2. Game Logic computes deterministic movement/travel outcomes (valid destination, cost, and mechanics). 3. World Management performs the authoritative location/occupancy commit for the target room/region instance. 4. Entity Management applies entity-side state updates (stats/effects/inventory consequences) but does not maintain a competing authoritative occupancy index. -5. Each actual mutation owner derives its operation/aggregate-specific guard from the root `EffectId`, binds it to the immutable request digest, and returns a durable result; evidence-only services are not artificial mutation participants. Retries/replays use the same identity and converge through owner guards and Game Session reconciliation; no service may treat local admission or partial writes as authoritative command completion. +5. Each actual mutation owner uses its persisted effect identity, binds its operation/aggregate-specific guard to the immutable request digest, and returns a durable result; evidence-only services are not artificial mutation participants. Retries/replays use the same identity and converge through owner guards and Game Session reconciliation; no service may treat local admission or partial writes as authoritative command completion. -`DROP` and `PICKUP` are Entity-local containment commits against the admitted `RoomInstanceRef`; World location/version evidence is carried in an attestation bound to the root `EffectId`, `actorEntityId`, `RoomInstanceRef`, operational `regionId`, `regionEpoch`, `executorFence`, and `requestDigest`, and Entity verifies that binding with its participant guard at local commit. Game Session's durable barrier and actor-lock/fence gate prevents a conflicting `MOVE` across lock expiry or handoff until terminal evidence; stale re-resolution is requested by Game Session through Game Logic under the same root `EffectId`, preserving the `requestDigest`. A later valid `MOVE` is allowed after Entity commit and barrier terminalization. The current proto/request and focused proof do not yet carry or demonstrate this attestation/barrier path. +`DROP` and `PICKUP` are command-root Entity-local containment commits against the admitted `RoomInstanceRef`; World location/version evidence is carried in an attestation bound to the command-root `EffectId`, `actorEntityId`, `RoomInstanceRef`, operational `regionId`, `regionEpoch`, `executorFence`, and `requestDigest`, and Entity verifies that binding with its participant guard at local commit. Game Session's durable barrier and actor-lock/fence gate prevents a conflicting `MOVE` across lock expiry or handoff until terminal evidence; stale re-resolution is requested by Game Session through Game Logic under the same command-root `EffectId`, preserving the `requestDigest`. A later valid `MOVE` is allowed after Entity commit and barrier terminalization. The current proto/request and focused proof do not yet carry or demonstrate this attestation/barrier path. If a feature needs a different movement write order, it must be documented as a design change in tick + transactions docs before implementation. diff --git a/design/architecture/system-architecture-redis-cache-reference.md b/design/architecture/system-architecture-redis-cache-reference.md index 66068add5b..6200a42e33 100644 --- a/design/architecture/system-architecture-redis-cache-reference.md +++ b/design/architecture/system-architecture-redis-cache-reference.md @@ -4,7 +4,9 @@ This companion document holds the reference-heavy material for Redis cache and r ## Implementation Status -The `room:*` Class A cache contract below is target-state only. It is not a current correctness path until World Management has an opaque room component version and a proven invalidation path. Namespace-backed `inventory:*` and explicitly instance-scoped `inventory:room-ground:*` cache adoption is likewise target-state; current readers remain authoritative until Entity Management's owner-version/event validation is proven. Current readers must not substitute `worldSnapshotId` or `roomDynamicVersion` for that component version; they must use authoritative reads when the target validation contract is unavailable. A cache-embedded version, TTL, or invalidation event alone is not currentness proof. The current Game Session `ratelimit:` key is likewise a legacy implementation and must be drained by its maximum TTL or isolated behind a versioned prefix before target rate-limit helpers consume the shared family. The future reader, invalidation, and version-advance rules below remain normative. +The `room:*` Class A cache contract below is target-state only. It is not a current correctness path until World Management has an opaque room component version and a proven invalidation path. Namespace-backed `inventory:*` and explicitly instance-scoped `inventory:room-ground:*` cache adoption is likewise target-state; current readers remain authoritative until Entity Management's owner-version/event validation is proven. Current readers must not substitute `worldSnapshotId` or `roomDynamicVersion` for that component version; they must use authoritative reads when the target validation contract is unavailable. A cache-embedded version, TTL, or invalidation event alone is not currentness proof. The current Game Session `ratelimit:` key is likewise a legacy implementation: `SessionRateLimiterImpl` writes it through the generic Game Session Redis client with a one-second window/TTL, while its Cache/Rate-Limit endpoint and ACL binding remain unproved. It must be registered as current legacy state, its writer stopped, and its maximum one-second TTL allowed to elapse with an empty-key readback before unversioned target rate-limit helpers consume the shared family; an adopter that cannot prove that drain must use a distinct versioned prefix. The current Game Session `lookcache::` writer is also legacy implementation drift: it is disposable and non-authoritative, but its incomplete scope and ten-minute TTL cannot satisfy target causal room-read semantics. Current composition remains authoritative/uncached until the target `view:room-look:*` contract is proven. The future reader, invalidation, and version-advance rules below remain normative. + +The current Automation implementation also emits `automation:test:quota:*`, `automation:test:capacity:*`, and `automation:readiness:capacity:*` families. They are named in the catalog below as Cache/Rate-Limit, Class B, reset-tolerant projections. Current readiness and dry-run capacity counter/lease reservations pass two keys with one shared tenant or fixed-family hash tag to each Lua invocation, so each pair occupies one Redis Cluster slot and is not inherently `CROSSSLOT`. Central ownership registration, canonical key encoding, durable charge/admission, reset, retention, and idempotent lease-accounting proof remain incomplete; the same-slot shape alone does not establish a supported clustered workload. The current Game Session `IpConnectionLimiter` has a distinct live limitation: registration passes the untagged `ipconn:
` and `sessionip:` keys to one Lua invocation, which can return `CROSSSLOT` when those keys hash to different Redis Cluster slots; this is in addition to the raw-address/privacy drift. The target must follow ADR 0087's one-mutation/one-opaque-subject-bucket boundary, with session lifecycle correlation kept outside any exact cross-key atomicity requirement; no final reverse-index shape is assumed here. Destructive resets additionally require the external, generation-bound [Cache deployment maintenance gate](./system-architecture-redis-operations.md#external-cache-deployment-maintenance-gate), not a fence key stored in the cache being reset. ## Cache Adoption Checklist @@ -73,12 +75,17 @@ Cache/Rate-Limit Redis hosts prefixes that are not part of the coordination log | `world-dynamic::room-dynamic::` | Cache | Versioned (Class A) | Reset-tolerant | World Management room-scoped dynamic-state cache. | | `room:::` | Cache | Versioned (Class A) | Reset-tolerant | World Management correctness-critical room snapshot cache; payload stores and validates owner `regionId`/`regionEpoch` with the opaque component version, atomically with refresh/TTL, and invalidates on epoch change. | | `view:room-look:::::::` | Cache | TTL-only (Class B) | Reset-tolerant | Target-only Game Session-owned disposable presentation/redraw helper; see the [canonical Class-B contract](./system-architecture-redis-cache.md#canonical-viewroom-look-class-b-contract). Current `ResolveLook` behavior is uncached and no focused proof establishes this prefix. The cache remains non-authoritative and disposable: unavailable or untrusted cache/fence evidence falls back to authoritative uncached `ResolveLook`, and it is never semantic reconnect context, frame/output replay, a transcript archive, or a delivery ledger. | +| `lookcache::` | Cache (current legacy only; target role unapproved) | Legacy disposable projection (not target Class B) | Reset-tolerant for disposable loss | Current Game Session writer only. The ten-minute payload is non-authoritative, but the legacy session/game-instance scope lacks viewer, policy, and causal read-fence identity; a clustered cache reset may delete and verify this family only while the external, generation-bound Cache deployment maintenance gate is held through deletion and verification. Remove/drain this writer or migrate to the exact `view:room-look:*` contract before target helpers consume it; otherwise continue authoritative uncached composition. This prefix is not target Class B authority. | +| `ipconn:
` and `sessionip:` | Cache / Rate-Limit (current legacy implementation drift) | Legacy heuristic (not target Class B authority) | Reset-tolerant heuristic loss | Game Session owns the current paired raw-address counter and session reverse-map. Entries use the current connection TTL (`GAME_SESSION_CONN_TTL_SEC`, default 3600 seconds); a reset may temporarily relax or tighten abuse limits and can leave the pair incomplete, but must not be treated as durable authority. Current registration passes both untagged keys to one Lua invocation, which can return `CROSSSLOT` on Redis Cluster when the keys hash to different slots; this is in addition to the raw-address/privacy defect covered by ADR 0087. The target must use one mutation on one opaque subject bucket and keep session lifecycle correlation outside exact cross-key atomicity; no final reverse-index shape is assumed here. | | `screenbuffer:::` | Cache | TTL-only (Class B) | Reset-tolerant | Current Game Session disposable hot-cache prefix for durable semantic reconnect context; PostgreSQL `resume_transcript_entry` rows remain authoritative. This prefix is distinct from `view:room-look:*` and never serves as semantic authority. Current keying is `gameInstanceId`-based; target reconnect scope is `{tenantId, playableStateNamespaceId, characterId}` under ADR 0134, so namespace-key migration and complete reconnect-envelope/generation proof remain implementation gaps. The row records prefix semantics, not current endpoint/role wiring. | | `chat:say::`, `chat:whisper:::`, `chat:tell::`, `chat:guild::`, `chat:city::`, `chat:account::` | Cache | TTL-only (Class B) | Reset-tolerant | Social & Groups short-lived chat projections; current `SAY` is sender-account scoped. Any future gameplay-SAY projection must publish its exact recipient/view scope and original-view contract rather than infer it from a bare character ID. See the [canonical `chat:whisper` Class-B contract](#canonical-social--groups-chatwhisper-class-b-contract). | | `chat:whisper::` | Cache | TTL-only (Class B) | Reset-tolerant | Legacy `ChatService` account-keyed whisper implementation-drift prefix (`chat:whisper:%d:%d`); it does not provide the target playable-state/character scope and remains a reset-tolerant disposable projection during migration. | -| `automation:queue:{tenantInstanceTag}:*` | Cache / Rate-Limit | TTL-only (target Class B; current reset/rebuild unavailable) | **Current queue reset/recovery is unavailable and must fail closed**; the implementation's rebuild query includes `EVALUATING` rows without stale-owner/CAS reconciliation, so this projection must not be flushed, rebuilt, or resumed as a supported current operation. Once the owner-reconciled target path is implemented and proven, it may be reset and rebuilt from durable work. | Automation & Scripting derived work-item pointers; PostgreSQL remains authoritative. See the [Automation & Scripting runtime/data owner contract](./microservices/automation-scripting-service/runtime-and-data.md#redis-roles-and-prefixes) and [API implementation status](./microservices/automation-scripting-service/api-contracts.md#implementation-status). The current queue implementation has no per-list TTL/trim or declared key-count/payload-size envelope; those are adoption/proof gaps, not implied bounds. | +| `automation:queue:{tenantInstanceTag}:*` | Cache / Rate-Limit | TTL-only (target Class B; current reset/rebuild unavailable) | **Current queue reset/recovery is unavailable and must fail closed**; the implementation's rebuild query selects only `PENDING_EVALUATION`, but it lacks owner/CAS reconciliation and cannot establish a safe disposition for existing `EVALUATING` rows, so this projection must not be flushed, rebuilt, or resumed as a supported current operation. Once the owner-reconciled target path is implemented and proven, it may be reset and rebuilt from durable work. | Automation & Scripting derived work-item pointers; PostgreSQL remains authoritative. See the [Automation & Scripting runtime/data owner contract](./microservices/automation-scripting-service/runtime-and-data.md#redis-roles-and-prefixes) and [API implementation status](./microservices/automation-scripting-service/api-contracts.md#implementation-status). The current queue implementation has no per-list TTL/trim or declared key-count/payload-size envelope; those are adoption/proof gaps, not implied bounds. | | `automation:quota::*`, `automation:tenant-budget::tier:`, `automation:test:quota::script::tenant`, `automation:test:quota::script::principal:`, `automation:test:capacity:{}:*`, `automation:test:capacity:{automation-test-capacity}:cluster*`, `automation:readiness:capacity:{}:*`, `automation:readiness:capacity:{automation-readiness-capacity}:cluster*` | Cache / Rate-Limit | TTL-only (Class B) | Reset-tolerant | Automation & Scripting per-script quota and tenant-budget counters, one-minute dry-run/test tenant/principal quota counters, exact tenantless cluster capacity counters paired with tenant/work-scoped leases, and bounded tenant/cluster `PUBLISH_READINESS` capacity reservations. Capacity counter/lease pairs share the documented hash tag (`{}` for tenant-scoped pairs and fixed family tags for cluster pairs) so their Lua operations remain in one Redis Cluster slot. The owner settings and capacity bounds are defined in the [Automation service configuration](./microservices/automation-scripting-service/configuration.md#service-specific-variables); the implementation uses one-minute counter windows and ten-minute capacity-lease TTLs. The counters/leases are disposable Cache/Rate-Limit projections, not Coordination Redis state, and are not rebuilt from Redis after reset. The catalog currently has no per-prefix key-count or serialized-payload envelope for these families; do not infer one from the concurrency limits until the owner declares and proves it. Durable trigger/work-item/readiness state and execution correctness remain in PostgreSQL and the owning service. | | `ratelimit:::` | Cache / Rate-Limit | TTL-only (Class B) | Reset-tolerant | Spring Cloud Gateway and other edge/credential rate-limit buckets. Each individual subject has one opaque stable hash; no modulo collision pool or request-derived shard is used. Reset-induced heuristic shifts are acceptable, while hard authority remains outside evictable Redis. | +| `ratelimit:` | Cache / Rate-Limit (current legacy; generic-client role unproved) | Legacy heuristic (not target Class B authority) | Reset-tolerant heuristic loss | Game Session's live `SessionRateLimiterImpl` command limiter. The current generic client may land on the wrong Redis role; the one-second counter/TTL is disposable and loss may relax or tighten heuristic limits. Cache-only writer registration and ACL proof do not make the legacy arity compatible with target helpers. Before any unversioned target `ratelimit:*` helper is enabled, stop the legacy writer, allow the maximum one-second TTL to elapse, and prove empty-key readback; an adopter that cannot prove that drain must use a distinct versioned prefix. | + +The current `automation:queue:{tenantInstanceTag}:*` implementation is not yet TTL-only: its enqueue and rebuild paths append to Redis lists without `EXPIRE`, `LTRIM`, or another bound. Target adoption requires configuration-backed `SCRIPT_OUTBOX_QUEUE_POINTER_TTL_SECONDS` and `SCRIPT_OUTBOX_QUEUE_MAX_POINTERS_PER_KEY` (exact values remain environment/service settings), applied atomically with every enqueue and rebuild. Truncation or expiry is acceptable only as pointer loss: Automation must re-drive from eligible durable PostgreSQL work-item rows, and reset/rebuild release requires every eligible durable identity to be rematerialized or durably settled. That release also requires the external, generation-bound Cache deployment maintenance gate to remain held through deletion, post-reset verification, and the authorized rebuild/readback; because the current gate and safe rebuild path are unavailable, queue reset/rebuild must fail closed. Until that policy and focused retention, memory-pressure, and rebuild proof exist, this is implementation/proof drift rather than a proven TTL-only cache. Separately, the live `AutomationRedisKeys.tenantInstanceTag` concatenates raw IDs, and `requirePart` rejects only null or blank values; delimiter collisions and braces that alter Redis Cluster hash tags are not prevented. `AutomationQueueServiceImpl` passes persisted identity fields to the builder during enqueue and rebuild, and `AutomationQueuePublicationSupport` forwards rows without validating those fields. This remains implementation drift until the shared encoded tuple or canonical UUID-boundary contract is enforced at those paths. ### Canonical Social & Groups `chat:whisper` Class-B Contract @@ -125,7 +132,7 @@ CI and code review checks are expected to: - `world-dynamic:*` / `room:*` - hit/miss counters plus key-count gauges where available. - `view:room-look:*` - hit/miss, recompute, write-skip reason, oversize, active-key/variant-budget, and Redis-failure metrics as specified by the [canonical Class-B contract](./system-architecture-redis-cache.md#canonical-viewroom-look-class-b-contract). - `chat:*` - hit/miss counters plus chat-type gauges where helpful. -- `automation:queue:*` / `automation:quota:*` / `automation:tenant-budget:*` / `automation:test:quota:*` / `automation:test:capacity:*` / `automation:readiness:capacity:*` - queue, quota, and bounded-capacity counters or leases; service metrics should make best-effort loss, expiry, and any durable re-admission/reconciliation visible. +- `automation:queue:*` / `automation:quota:*` / `automation:tenant-budget:*` / `automation:test:quota:*` / `automation:test:capacity:*` / `automation:readiness:capacity:*` - queue, quota, and bounded-capacity counters or leases; service metrics should make best-effort loss, expiry, and any durable re-admission/reconciliation visible across tenant and cluster variants. - Prefix tags should stay consistent across services so dashboards can reason about cache behavior by aggregate family rather than by one-off metric names. ### Future Work / TODO diff --git a/design/architecture/system-architecture-redis-cache.md b/design/architecture/system-architecture-redis-cache.md index 371e0ffe77..6eae23eb36 100644 --- a/design/architecture/system-architecture-redis-cache.md +++ b/design/architecture/system-architecture-redis-cache.md @@ -2,7 +2,7 @@ Redis is already used for transient coordination (ticks, sessions, locks). This document describes how **Cache/Rate-Limit Redis** backs selected read-side caches and rate limiting as a performance optimization. It focuses on cache ownership, invalidation rules, consistency expectations, and canonical cache policy. The detailed prefix catalog, worked examples, reference tables, adoption checklist, and testing guidance live in [Redis Cache & Rate Limiting Reference](./system-architecture-redis-cache-reference.md). -The canonical cache policy in this file and the reference catalog in the companion document must stay aligned with the global reset policy matrix in `system-architecture-redis-reset-and-recovery.md`. +The canonical cache policy in this file and the reference catalog in the companion document must stay aligned with the global reset policy matrix in `system-architecture-redis-reset-and-recovery.md`. Any destructive Cache/Rate-Limit reset also requires the external, generation-bound [Cache deployment maintenance gate](./system-architecture-redis-operations.md#external-cache-deployment-maintenance-gate); it is outside Cache/Rate-Limit Redis and must cover every registered writer through deletion, verification, and rebuild. > ℹ️ **Implementation status** > @@ -35,7 +35,7 @@ All other controls (for example, per-tenant heuristics, noisy-tenant detection s - All non-ephemeral environments, including local development and small self-hosted setups, run **at least two Redis roles**: - A **Coordination Redis** deployment dedicated to ticks, locks, timers, sessions, and other gameplay-critical coordination state. - A **Cache/Rate-Limit Redis** deployment dedicated to read-side caches and gateway rate limits. - - Coordination Redis must not host large, eviction-driven caches under any profile. Even in development and hobby/self-hosted profiles, caches and rate limits are pointed at the separate Cache/Rate-Limit deployment so eviction and OOM behavior cannot silently affect coordination keys. The only supported exception is an explicitly marked ephemeral CI/test stack whose tests are reset-tolerant, do not exercise coordination tail-loss or replay guarantees, and surface the shared endpoint; such a stack is outside coordination SLO validation. See `system-architecture-redis-usage-and-profiles.md` for environment profiles and mappings. + - Coordination Redis must not host large, eviction-driven caches under any profile. Even in development and hobby/self-hosted profiles, caches and rate limits are pointed at the separate Cache/Rate-Limit deployment so eviction and OOM behavior cannot silently affect coordination keys. The only supported exception is one explicitly marked, one-shot ephemeral test/CI stack (never hosted `pr-preview` or another player-facing environment) whose tests are reset-tolerant, which surfaces the shared endpoint, and which passes the complete [canonical post-reset verification checklist](./system-architecture-redis-ops-access.md#canonical-post-reset-verification-checklist). That stack may run reset-tolerant tests but is outside and provides no role-isolation, replay, tail-loss, or coordination-SLO evidence. See `system-architecture-redis-usage-and-profiles.md` for environment profiles and mappings. - No soft coordination logs on Cache/Rate-Limit Redis: - Tick ordering, tick idempotency, and any correctness or fairness invariants for gameplay **must not** depend on cache or rate-limit keys. Cache/Rate-Limit Redis may only influence latency and load, never “what happened” or “in which order” from the tick engine’s perspective. - Automation and scripting structures on Cache/Rate-Limit Redis (for example `automation:queue:*`, `automation:quota:*`, `automation:tenant-budget:*`, `automation:test:quota:*`, `automation:test:capacity:*`, and `automation:readiness:capacity:*`) are explicitly documented as best-effort buffers, counters, and bounded owner-token leases; they cannot act as authoritative logs or effect ledgers. Durable automation schedules, work, and readiness state live in PostgreSQL; cache entries merely accelerate lookups, quota checks, and disposable capacity admission. @@ -204,10 +204,7 @@ Memory and eviction behavior for cache and rate-limit workloads must not comprom - Apply a safety factor of at least **2–3×** (`coord_bytes * SAFETY_FACTOR`) to account for spikes, fragmentation, and unforeseen growth. - Keep coordination prefixes (`tick:*`, `session:*`, `timer:*`, `retry:*`) under a target fraction of `maxmemory` (for example, <30–40%) and treat sustained growth beyond that as a sizing or design issue. - The canonical threshold source is `system-architecture-redis-operations.md` (Redis SLOs & Budgets); this doc intentionally mirrors that value. - - Does **not** store large cache payloads or unbounded aggregates; those belong in the Cache/Rate-Limit cluster or in PostgreSQL/object storage. Any exception must: - - Use a distinct, clearly documented prefix (for example, `coordCache:`). - - Respect strict per-key size limits and a small aggregate memory budget. - - Have an explicit incident plan if it contributes to memory pressure. + - Does **not** store large cache payloads or unbounded aggregates; those belong in the Cache/Rate-Limit cluster or in PostgreSQL/object storage. There is no general Coordination Redis cache exception: only the explicitly labelled, one-shot ephemeral test/CI topology (never hosted `pr-preview`) may collapse the physical roles. It must be reset-tolerant, surface the shared endpoint, preserve logical prefix, ACL, reset, and memory-policy classification, and pass the complete [canonical post-reset verification checklist](./system-architecture-redis-ops-access.md#canonical-post-reset-verification-checklist). It yields no role-isolation, replay, tail-loss, or coordination-SLO evidence. No unregistered cache family may be placed on Coordination Redis. - Treats any `OOM`/`OUT OF MEMORY` write error for coordination commands as a **critical failure condition**: the Game Session Service and other coordination clients: - Detect write failures from Redis clients (including Lua script results) instead of ignoring them. - Log structured errors and increment metrics (for example `redis.coordination_oom_errors`). @@ -220,7 +217,7 @@ For **all non-ephemeral deployments**, including local development: - Coordination and cache/rate-limit roles run on **separate Redis deployments** (for example, two containers/pods on the same host or separate processes), even when serving a single developer or tenant. - Deployment mechanisms vary by environment: local Docker Compose provides both `redis-coord` and `redis-cache`; the umbrella Helm chart's `k8s/helm/firemud/values.yaml` defaults `previewStack.enabled=false` and therefore does not render its in-chart Redis services by default; the hosted overlay enables both in-chart Redis services; and production Terraform provisions separate Redis releases. These are local deployment consequences of the two-role requirement, not a second role policy. -- Explicitly marked ephemeral CI/test stacks may collapse roles into a single Redis instance only when tests are reset-tolerant, do not exercise coordination tail-loss or replay guarantees, the environment is labelled `ephemeral / single-Redis`, and configuration/metrics surface the shared endpoint. These stacks are outside coordination tail-loss, replay, and SLO validation and must not be used for QA, staging, production, or any player-facing game instance. +- Only an explicitly marked, one-shot ephemeral CI/test stack other than hosted `pr-preview` may collapse roles into a single Redis instance. It must be labelled `ephemeral / single-Redis`, use reset-tolerant tests, not exercise coordination tail-loss or replay guarantees, surface the shared endpoint in configuration/metrics, and pass the complete [canonical post-reset verification checklist](./system-architecture-redis-ops-access.md#canonical-post-reset-verification-checklist). It provides no role-isolation, replay, tail-loss, or SLO evidence and must not be used for QA, staging, production, or any player-facing game instance. Operational dashboards track `used_memory`, `maxmemory`, and eviction counters for each deployment. In addition: diff --git a/design/architecture/system-architecture-redis-cheatsheet.md b/design/architecture/system-architecture-redis-cheatsheet.md index 75d472ef53..5adaf8e826 100644 --- a/design/architecture/system-architecture-redis-cheatsheet.md +++ b/design/architecture/system-architecture-redis-cheatsheet.md @@ -50,11 +50,14 @@ This table highlights representative prefixes and their intended Redis role. It | `session:auth:generation:issuer:`, `session:auth:generation:account:`, `session:auth:generation:tenant:`, `session:auth:generation:membership::` | **Approved global/account exception: Account durable authority with required Coordination Redis projection** | Account Service | Account advances one positive monotonic `generation` per scope transactionally in its durable store and is the sole writer of the Redis projection. Idempotent set-if-greater is permitted for a missing or lower projection only. A projection greater than durable authority is poison: Account must quarantine or replace that exact scope through an audited workflow, recreate it from durable authority, and emit immutable per-scope evidence/verification; consumers fail closed until the evidence is accepted. Region- and tenant-scoped resets preserve unaffected projections but verify affected scopes; a cluster reset may discard projections only after the Account repair/reset cutover and must rebuild and verify every affected scope before reopening. | | `session:connect-token:tenant::account::scope::request:` | **Coordination Redis — approved untagged Account legacy exception** | Account Service | Current Account-owned exact-input result-map projection. It is reset-sensitive, retained through the legacy TTL/retry horizon, and never read or promoted by target code. | | `session:connect-token:v1:tenant::account::scope::request:` | **Coordination Redis — approved untagged Account target exception** | Account Service | Target Account-owned exact-input issuance-result projection. It requires `schemaVersion: "connect-token-issuance-result-v1"`, durable SQL first-writer-wins before mint, and Redis set-if-absent/read-winner. Target readers and writers are isolated from the legacy family; exact repair comes only from the durable operation/envelope. | -| `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness` | **Coordination Redis** | Spring Cloud Gateway | Target security-critical, non-evicting single-use connect-token replay and browser-denial state. The consume script uses the three tagged keys and one same-connection `WAITAOF` acknowledgement before readiness can admit tokens. Region- and tenant-scoped resets preserve the shared replay domain. The current writer emits only the untagged replay marker, with no deny/readiness/fence writer; that is migration-only drift and not target proof. A replay-continuity loss trigger, including a cluster reset that invalidates this shared state, requires new gameplay handshakes to remain closed for the 30-second maximum connect-token lifetime plus two configured clock-skew intervals, followed by the required disposable-marker and durability-acknowledgement proof before readiness may admit tokens. This quarantine does not apply to unrelated tenant/region reset handling or Cache/Rate-Limit Redis. | +| `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness` | **Coordination Redis** | Spring Cloud Gateway | Target security-critical, non-evicting single-use connect-token replay and browser-denial state. The literal `{gateway-connect-token-replay-v1}` tag co-slots replay, browser-deny, and readiness/fence keys for the atomic consume script; the readiness value carries `replayAdmissionFence`. A winning consume (`1`) and a browser-deny write require the configured same-connection, threshold-satisfying `WAITAOF` durability acknowledgement; a definitive consume (`0`/`-1`) is non-mutating and has no marker acknowledgement. An unavailable, timed-out, malformed, below-threshold, lost, or otherwise ambiguous consume/deny result or durability acknowledgement is unconfirmed: fail the handshake or revocation operation closed, keep the affected admission quarantined, and enter the replay-continuity quarantine/reconciliation path for that `jti`/operation; never accept, mint, or report terminal revocation from uncertainty. This fence covers only the `/ws/game/**` gameplay-connect handshake; direct TCP/Telnet `LOGIN` does not consume this replay domain and follows its separate Account/Game Session authentication path. Region- and tenant-scoped resets preserve the shared replay domain. A replay-continuity loss trigger, including a cluster reset that invalidates this shared state, requires new gameplay handshakes to remain closed until the later of the detection-time deadline (the 30-second maximum token lifetime plus two configured clock-skew intervals) and any later known affected-token `exp` plus one clock-skew interval. Admission remains closed until that deadline passes and the required fresh disposable-marker, durability-acknowledgement, and shared readiness proof succeeds. The exact deadline and reopen contract is owned by [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md). The current generic Cache-bound writer emits only the untagged replay marker, with no deny/readiness/fence writer; that old replay key is migration-only drift and is quarantined/inventoried during cutover. This quarantine does not apply to unrelated tenant/region reset handling or Cache/Rate-Limit Redis. | + +| `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::` | **Coordination Redis** | Spring Cloud Gateway | Target-only Gateway-generated disposable recovery-probe marker in the same replay hash slot, separate from player `jti` and browser-deny markers. Gateway alone supplies its exact key/nonce/value; callers cannot redirect it to player keys. The marker has a finite bounded expiry and guarded cleanup/readback separate from the same-connection `WAITAOF`. The typed probe runs only while shared readiness is `QUARANTINED`, accepts no player JWT/`jti`/deny input, and never writes readiness. Only the recovery coordinator may authorize reopen after exact fenced probe evidence and every release gate; Gateway's owner-local helper performs the readiness CAS through its authenticated maintenance API. The probe is currently unimplemented. See [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md). | | `remote:{tenantInstanceTag}:` | **Coordination Redis** | Game Session Service / Automation & Scripting | Best-effort, TTL-bounded hint marker for remote participation scoped to the complete `` identity (typically “this entity has remote follow-ups due”). Default `remote_hint_ttl_ms = 60_000`. Region-scoped resets leave instance-scoped hints intact; tenant/cluster resets resolve every game instance from the durable scope inventory and enumerate `remote:{tenantInstanceTag}:*` per instance before removal. No tenant-only remote key family exists. | | `automation:timer:{tenantRegionTag}`, `script-scheduler:{tenantRegionTag}:lastTickId` | **Coordination Redis (target-only, once implemented)** | Automation & Scripting Service | Reserved target-only timer/checkpoint projections; they are not current runtime keys and have no current reset operation. Once implemented, they are reset-tolerant derived hints rebuilt from durable PostgreSQL schedules, trigger-instance rows, and heartbeat progress; they are never the source of truth for automation work. | | `tick-events:{tenantRegionTag}` and `tick-events-offset:{tenantRegionTag}:` | **Coordination Redis** | Game Session Service / Automation & Scripting | Best-effort tick event stream and per-consumer offsets used only as observer/wakeup hints. `tenantRegionTag` is the opaque encoding of the complete `` scope and must include `gameInstanceId`; no tenant-plus-region alias is valid. The key's `tenantRegionTag` and `` are authoritative for the event-offset scope; each offset payload stores `{tenantId, gameInstanceId, regionId, consumerId, region_epoch, latestTickId, streamOffset}` and is not a standalone scope identifier. It is discarded before reuse when `region_epoch` differs from the control-plane epoch. Stream retention is capped (default `tick_events_maxlen = 2048` per region). Correctness derives from committed heartbeats/RegionStatus plus durable schedules; missing/duplicated events must not change which schedules eventually fire. | -| `automation:queue:{tenantInstanceTag}:*` | **Cache/Rate-Limit Redis** (single-key ops) | Automation & Scripting Service | Non-authoritative, best-effort queue pointers. The target rebuild permits `PENDING_EVALUATION` and only an owner-reconciled/reclaimed safe non-stale `EVALUATING` row; stale or unresolved rows remain excluded. The current `rebuildPendingWorkItemIndex` unconditionally selects both statuses and has no stale, owner, or compare-and-set gate, so queue-prefix reset/rebuild and resume are unavailable and must fail closed; a non-atomic status preflight cannot authorize a safe PENDING-only path. Do not migrate or recover work from Redis payloads, or mix this single-key family with coordination prefixes in one Lua call. The adjacent timer/checkpoint projections remain target-only and unavailable. See [Redis Operations](./system-architecture-redis-operations.md#cacherate-limit-redis-reset), [Redis incident handling](./system-architecture-redis-incident-runbook.md#automation-queue-schema-mistakes), and [Scripting Runtime Execution](./system-architecture-scripting-runtime-execution.md#redis-queue-index-and-durable-work-boundary). | +| `conflict:entity::` and `conflict:session::` | **Coordination Redis** | `common-data-runtime` helper used by Entity Management and Game Session | Reset-tolerant, non-authoritative hotspot diagnostics. Current generic-client placement and separate `INCR`/`EXPIRE` warning-only path are implementation drift; target role, finite cardinality, 300-second inactivity TTL, ACL, and atomic-helper convergence are defined in [Redis Architecture](./system-architecture-redis.md#coordination-vs-cache-prefixes). | +| `automation:queue:{tenantInstanceTag}:*` | **Cache/Rate-Limit Redis** (single-key ops) | Automation & Scripting Service | Non-authoritative, best-effort queue pointers. Target rebuild eligibility includes `PENDING_EVALUATION`; an `EVALUATING` row is eligible only after its owner proves the lease stale or ownership is explicitly released through a fenced compare-and-set. Active non-stale leases are excluded, and these criteria are necessary but not sufficient for safe recovery or DSL replay. Staleness alone never authorizes DSL replay. The current `rebuildPendingWorkItemIndex` selects only `PENDING_EVALUATION` rows, but has no owner or compare-and-set gate, so queue-prefix reset/rebuild and resume are unavailable and must fail closed; a non-atomic status preflight cannot authorize even a PENDING-only path or establish a safe disposition for existing `EVALUATING` rows. Do not migrate or recover work from Redis payloads, or mix this single-key family with coordination prefixes in one Lua call. The adjacent timer/checkpoint projections remain target-only and unavailable. See [Redis Operations](./system-architecture-redis-operations.md#cache-rate-limit-redis-reset), [Redis incident handling](./system-architecture-redis-incident-runbook.md#automation-queue-schema-mistakes), and [Scripting Runtime Execution](./system-architecture-scripting-runtime-execution.md#redis-queue-index-and-durable-work-boundary) for the owner contract. | `automation:quota::` | **Cache/Rate-Limit Redis** | Automation & Scripting Service | Best-effort per-script quota counters. Safe to drop; budgets are re-established from configuration and durable state. | | `automation:tenant-budget::tier:` | **Cache/Rate-Limit Redis** | Automation & Scripting Service | Best-effort per-tenant live execution budget counters. Safe to drop; counters are re-established from configuration and durable work state. | | `automation:test:capacity:{}:tenant` and `automation:test:capacity:{}:lease:`; `automation:test:capacity:{automation-test-capacity}:cluster` and `automation:test:capacity:{automation-test-capacity}:cluster:lease::` | **Cache/Rate-Limit Redis** | Automation & Scripting Service | Best-effort dry-run/test capacity: the first pair is the tenant-scoped counter/lease and the second pair is the fixed-tag cluster counter plus tenant/work-scoped lease. Same-slot tenant keys use the canonical `{}` tag; cluster keys use the fixed `{automation-test-capacity}` tag. Safe to drop; lease/counter expiry or Redis state loss may temporarily over- or under-admit test work, so this is a best-effort fairness control rather than a hard correctness cap; separate live capacity remains protected. See the [canonical quota lifecycle](./system-architecture-scripting-quotas-and-operations.md#budget-accounting-rules). | @@ -69,7 +72,6 @@ This table highlights representative prefixes and their intended Redis role. It When introducing **new prefixes**, update the owning service design doc and ensure the prefix is consistent with the role and reset expectations above. -The “shared replay-readiness generation” wording in the table is an explanatory alias for the canonical `replayAdmissionFence`; it is not a second key or field. For tick prefixes, `tenantRegionTag` is a naming alias, not a reduced scope: it must encode `tenantId`, `gameInstanceId`, and `regionId` in a stable, collision-free form. The event stream and offset rows are especially sensitive because omitting `gameInstanceId` would merge wakeups and baselines for otherwise independent game instances. --- diff --git a/design/architecture/system-architecture-redis-design-checklist.md b/design/architecture/system-architecture-redis-design-checklist.md index 1dddce5a93..7be48b9ccf 100644 --- a/design/architecture/system-architecture-redis-design-checklist.md +++ b/design/architecture/system-architecture-redis-design-checklist.md @@ -125,9 +125,10 @@ Use this when adding or changing cache or rate‑limit prefixes (for example `in ### Eviction and TTL - [ ] Set explicit TTLs that match the data’s volatility and usage patterns. +- [ ] For `automation:queue:*` pointer lists, declare `SCRIPT_OUTBOX_QUEUE_POINTER_TTL_SECONDS` and `SCRIPT_OUTBOX_QUEUE_MAX_POINTERS_PER_KEY`, apply both atomically on enqueue/rebuild, and document that expiry/truncation triggers durable owner re-drive rather than work settlement. - [ ] Confirm eviction is acceptable: - [ ] Cold caches should degrade into acceptable behavior (extra DB reads, recomputation). - - [ ] Rate‑limit keys may be dropped without violating security or fairness guarantees. + - [ ] Rate-limit keys may be dropped without violating hard authorization, security, financial, or other declared invariants; declared heuristic enforcement may temporarily weaken or tighten, and the limiter's documented unavailable-store behavior must apply. - [ ] For versioned caches: - [ ] The authoritative store exposes a version or `lastModified` field. - [ ] Cache invalidation logic clearly ties updates to version changes. @@ -135,6 +136,7 @@ Use this when adding or changing cache or rate‑limit prefixes (for example `in ### Key Shape and Multi-Tenant Behavior - [ ] Keys include `tenantId` and any other isolation dimensions required (for example, per‑player or per‑guild). +- [ ] Any opaque hash-tag builder uses a canonical collision-safe tuple encoding (or a proven canonical UUID parser with separator/brace rejection); add delimiter/brace collision vectors and same-scope slot golden tests before claiming the builder is canonical. Use the shared [validation and runtime-proof workflow](../developer-workflows/validation-and-runtime-proof.md) to select the proof and record delimiter/brace collision-vector and same-scope slot golden-test execution results in PR/CI or implementation-tracking evidence; it supplements, rather than replaces, these owner-local requirements. - [ ] For rate‑limit prefixes: - [ ] Bucketing strategy is documented (per‑client vs hashed buckets). - [ ] Memory and key count growth per tenant/time window stays within budget. @@ -224,6 +226,11 @@ Use this when changing Redis profiles, topologies, or reset behavior. - [ ] Design changes explicitly state: - [ ] Which reset scopes are safe (region, tenant, cluster). - [ ] Whether reset or accept‑loss is the expected response to problems. +- [ ] For any destructive Cache/Rate-Limit reset, require the ADR-0085-derived external durable operation/fence outside Cache Redis: + - [ ] Bind an immutable `operationId`, exact deployment/generation, and frozen complete writer/prefix inventory to the external fence. + - [ ] Require restart-surviving writer admission/acknowledgement checks, stale-operation rejection, serialized takeover/expiry/release evidence, and fail-closed ambiguity handling. + - [ ] Keep ordinary writers denied through deletion and verification. The Automation rebuild/re-drive exception applies only to registered Automation prefixes (currently `automation:queue:*`) and only through the target-only named ACL principal `automation_queue_rebuild_maint` bound to the same `operationId`/fence/generation and exact registered prefix/scope. Non-Automation maintenance principals and their permitted prefix/scope contracts are target-only and undefined until each owner is separately named and its exact contract is accepted; do not infer or authorize a principal for Gateway, Game Session, Entity, World, or Social from ownership alone. No generic writer or operator principal is implied; use the owner and prefix contract in the [Cache/Rate-Limit reset runbook](./system-architecture-redis-operations.md#external-cache-deployment-maintenance-gate) and [cache reference](./system-architecture-redis-cache-reference.md). + - [ ] Attest Cache-only endpoint/role/ACL identity and complete prefix inventory before deletion; any coordination prefix, generic legacy writer, unknown prefix, or ambiguous evidence aborts/escalates without deletion. - [ ] Runbooks in `system-architecture-redis-operations.md` are updated or confirmed to cover new/reset behaviors. - [ ] For workloads that are **reset-sensitive** rather than reset-tolerant: - [ ] The impact of a reset is documented (player-facing effects, operational steps). diff --git a/design/architecture/system-architecture-redis-incident-runbook.md b/design/architecture/system-architecture-redis-incident-runbook.md index 126a3147af..85ba33cdc7 100644 --- a/design/architecture/system-architecture-redis-incident-runbook.md +++ b/design/architecture/system-architecture-redis-incident-runbook.md @@ -39,7 +39,8 @@ Region-scoped coordination key examples use `{tenantRegionTag}`, the canonical o - Pause non-critical background scripts that depend heavily on Coordination Redis. 3. **Recover** - Follow cluster or node failover procedures documented in `design/architecture/system-architecture-redis-operations.md`. - - If a reset is required, use the coordination reset model and key enumeration strategy from `design/architecture/system-architecture-redis-reset-and-recovery.md` to clear affected prefixes safely. + - **Target state only, once the canonical gated coordination-maintenance operation is implemented and proven:** If a reset is required, use the coordination reset model and key enumeration strategy from `design/architecture/system-architecture-redis-reset-and-recovery.md` to clear affected prefixes safely. + - **Current deployments:** Do not execute a scoped reset or mutate raw coordination prefixes. Preserve the AOF, operation records, and incident evidence; keep the affected scope fenced or stopped; use only the shipped `PauseTicksForScope` / `GetRuntimeOwnershipStatus` boundary and `coord_ops_ro` read-only inspection; then escalate through the [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback). 4. **Inspect durable command outcomes** - After replay/reset work, use the canonical `GetGameplayCommandStatus` surface described in `design/architecture/system-architecture-tick-failures-and-operations.md` to confirm commands converged to their final durable outcomes. - Do not treat raw Redis queue/key inspection as the primary operator answer for player-visible command status after remediation. @@ -61,9 +62,9 @@ When Coordination Redis recovers after an outage or severe degradation: - **Tick executors** - Do not attempt to resume in-flight locks or leases based on in-memory state. - Re-establish the authoritative recovery baseline from PostgreSQL tick-batch records, the tick effect ledger, follow-up tables, and `RegionStatus`; surviving Redis keys are inspected only as coordination residue and hints. - - If `pending` survives for a region, the next executor validates each immutable pending envelope against the durable `tick_batch_id` and complete expected root-`EffectId`/participant set (or equivalent exact ledger-row identities), then replays the tick as described in the tick system design; a count, digest, or descriptor-only correlation is insufficient. - - If `pending` is missing (for example due to AOF tail loss), treat this as “coordination state may have been partially lost” rather than silently skipping work: - - Advance to the next `tickId` only after running the tick effect ledger replay controller / reconcile tooling for the affected scope so any lingering `SCHEDULED` effects converge to `APPLIED` or `ABANDONED` with an explicit tail-loss reason where the evidence policy permits. For `reset_first`, once the old timeline is durably fenced, the epoch bump is a separate fencing step and does not wait for conclusive ledger outcomes. Inconclusive old-epoch effects remain quarantined, non-terminal, owner-fenced reconciliation work under their original root `EffectId`; current-epoch executors must never replay that `EffectId`, and the work blocks reset-scope convergence, next-tick progress, and reopening, not the epoch bump itself. + - **Target state only — complete pending-envelope validation is not live:** If `pending` survives for a region, the future recovery controller validates each immutable pending envelope against the durable `tick_batch_id` and complete expected persisted-mutation/participant projection: the mutation `EffectId` (root `EffectId` for a root mutation or the persisted child `EffectId` for a generated child), any enclosing `rootEffectId` retained separately as lineage and reconciliation context, typed operation, complete scope/timeline and target projection, immutable request payload/digest, and sealed participant/manifest context. Every expected participant identity and guard must match exactly; missing, extra, stale, conflicting, or otherwise mismatched envelope evidence fails closed without replay or durable mutation. A count, digest, or descriptor-only correlation is insufficient. The current live Redis payload is only the compact `N||` / `S||` form, with no complete immutable participant envelope. Current code therefore applies only its narrower fail-closed checks: it excludes entries when current runtime ownership is absent, unusable, paused, or stale, when the durable command is missing or not `STAGED`/`RETRY_QUEUED`, or when tenant, game-instance, region, or epoch scope does not match; replay additionally requires the pending command set/scope and sealed-manifest/effect-count checks. These checks do not establish the target complete-envelope contract or authorize target recovery; when the current recovery path cannot prove the required boundary, keep the scope fenced or stopped and use the [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback). + - If `pending` is missing (for example due to AOF tail loss), treat this as “coordination state may have been partially lost” rather than silently skipping work: + - **Target state only — unavailable today:** Advance to the next `tickId` only after the tick effect ledger replay controller / reconcile tooling has converged lingering `SCHEDULED` effects to `APPLIED` or evidence-qualified `ABANDONED` outcomes. For `reset_first`, once the old timeline is durably fenced, the epoch bump is a separate fencing step and does not wait for conclusive ledger outcomes. Inconclusive old-epoch effects remain quarantined, non-terminal, owner-fenced reconciliation work under their original persisted mutation `EffectId`, with any enclosing `rootEffectId` retained separately as lineage and reconciliation context; current-epoch executors must never replay that mutation identity, and the work blocks reset-scope convergence, next-tick progress, and reopening, not the epoch bump itself. **Current deployments:** Do not run unavailable replay/reconcile tooling or advance the affected tick; preserve the AOF and incident evidence, keep the scope fenced or stopped, use only shipped pause/status and read-only inspection, and escalate through the [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback). - Converge only command records with `ackLevel` = `ACCEPTED_VOLATILE` in `RECEIVED`/`ENQUEUED` and no surviving batch/binding to `executionOutcome = LOST_BEFORE_STAGING`; `ACCEPTED_DURABLE` records follow their feature-specific durable replay or post-abandon re-drive contract, while inconclusive batch-bound work remains non-terminal/reconciliation-required. See the [canonical command outcome convergence](./system-architecture-tick-execution-flows.md#command-outcome-convergence-required). - Use the resulting evidence-qualified ledger outcomes plus service-level idempotency guards to validate that no effect is silently terminalized or left without an owned reconciliation path; inconclusive old-epoch work remains visible as non-terminal. - **Leases** @@ -80,8 +81,9 @@ When Coordination Redis recovers after an outage or severe degradation: - Throttle non-essential cache usage or, only through an explicitly documented cache-owner/deployment control, temporarily reduce TTLs for non-lease, disposable Class B cache prefixes. That control must identify the authorized operator or workload, exact deployment/scope, bounded duration, audit record, and rollback/readback proof; owner-token leases, including test/readiness capacity owner leases, are excluded unless their owner contract explicitly defines a semantic minimum lifetime plus renewal or reacquisition behavior. Operators must not issue Redis TTL commands directly. - Confirm that coordination keys are not co-located with caches. 3. **Recover** - - Scale the cache deployment or provision additional nodes. - - Mutating Cache/Rate-Limit reset tooling is currently unavailable. Preserve the keyspace and incident evidence; do not use `redis-cli` or any other ad-hoc tool or Redis command to issue writes, delete prefixes, change TTLs, `FLUSHDB`, or `FLUSHALL`. An explicitly documented cache-owner/deployment TTL control remains permitted only under the authorization, bounded-duration, audit, rollback, and readback proof above. Only supported bounded read-only inspection through the applicable read-only ops user, using known keys or an approved bounded inspection surface, is otherwise allowed. Follow the [current fail-closed Cache/Rate-Limit reset fallback](./system-architecture-redis-operations.md#runbook-environment-scoped-cache-reset), and escalate to the cache owner or authorized infrastructure operator if an existing deployment control cannot contain impact. Do not reset coordination prefixes from the cache deployment. + + - **Target state only, once the external generation-bound Cache maintenance gate and its writer admission/acknowledgement, complete inventory/readback, and accepted owner-specific rebuild or repopulation paths are implemented and proven:** First require trusted deployment/endpoint/role/ACL attestation and bounded exact prefix inventory/readback proving the selected deployment is Cache-only and distinct from Coordination Redis; abort without deletion on any Coordination prefix, generic legacy writer, unknown prefix, or ambiguous role evidence. Then flush or reset only registered Cache/Rate-Limit prefixes while holding the same external gate through deletion and verification. Automation rebuild/readback applies specifically to the `automation:queue:{tenantInstanceTag}:*` pointer family, from durable work truth as described below; every other affected Cache/Rate-Limit prefix requires its own accepted owner-specific rebuild or repopulation/readback contract before release. Do not reset coordination prefixes from the cache deployment. + - **Current deployments:** Do not flush or reset cache prefixes, perform a Coordination Redis reset, or issue raw Coordination-prefix writes. Non-colocation confirmation is diagnostic only and does not replace role/endpoint/ACL isolation proof. Keep affected writers/clients quarantined or stopped and use the role-specific `cache_ops_ro` read-only inspection path where configured (never for writes). If bounded inspection or abort evidence identifies Coordination prefixes or a generic legacy writer, use only the shipped instance-scoped `PauseTicksForScope` / `GetRuntimeOwnershipStatus` boundary as needed to fence and inspect the affected scope; this does not authorize any Coordination reset or raw mutation. Preserve reset/incident evidence and escalate through the [Cache/Rate-Limit Redis Reset](./system-architecture-redis-operations.md#cache-rate-limit-redis-reset) authority and its current fail-closed fallback. ## Session Schema and TTL Cleanup @@ -113,7 +115,7 @@ When session-related metrics indicate schema or TTL problems, use this scoped cl - The scoped reset/full-wipe flow in `system-architecture-redis-operations.md` is target state only until its durable controller, Account projection-repair workflow, immutable evidence gates, and bounded maintenance tooling are implemented and proven. It must use the [canonical coordination reset sequence](./system-architecture-redis-operations.md#canonical-coordination-reset-sequence), including the [canonical post-reset verification checklist](./system-architecture-redis-ops-access.md#canonical-post-reset-verification-checklist); node-level scope still requires the documented cluster-blast-radius or physical-dedication proof before handoff. The incident-specific fallback remains fail-closed when those target-state controls are unavailable. - Current fail-closed fallback: if the AOF cannot be trusted, keep protected admission, gameplay mutation, and affected coordination writers stopped; preserve the AOF and incident evidence; use the shipped pause/status surface and read-only inspection where available; and escalate through the incident process. Abort any destructive wipe, recovery continuation, or reopen attempt when the required durable controller, Account projection repair, or immutable evidence path is unavailable. There is no supported current full-wipe substitute. - Do not perform manual AOF truncation or file editing. - - Use idempotent replay and tick system rules to rebuild necessary state. + - **Target state only — unavailable today:** Use idempotent application-level replay/reconciliation and tick system rules to rebuild necessary state after the target recovery controller and its evidence gates are implemented and proven. **Current deployments:** Do not initiate application-level tick/ledger replay, state rebuild, or advance ticks; preserve the AOF and incident evidence, keep the affected scope fenced or stopped, use only shipped pause/status and read-only inspection, and escalate through the [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback). This prohibition does not cover Redis's built-in startup replay: when an existing AOF is trusted, a normal Redis restart/failover may replay it as-is, as described above. That storage-level replay is not application recovery or a state rebuild and does not authorize admission, gameplay mutation, tick progress, or reopen without the same evidence and fencing gates. - During Account projection repair, Account's snapshot field `issuerAuthGeneration` maps exactly to canonical persisted `lastAppliedIssuerGeneration` and that mapping is used consistently during bootstrap, persistence, exact readback, contiguous replay, and recovery; it is not a second persisted alias or a local fallback. Set-if-greater is permitted only for a missing or lower Redis generation. A Redis generation greater than Account durable authority is poisoned and must be quarantined or replaced by an Account-owned audited workflow, recreated from durable authority, and verified with immutable evidence for each affected scope before protected traffic reopens. The current repository does not ship and prove this projection-repair workflow end to end. ## Redis Incident Scenarios @@ -135,7 +137,7 @@ Before entering this measured-SLO detect/decide path, verify that the affected d - Goal: preserve as much in-epoch work as possible by driving lingering `SCHEDULED` rows to `APPLIED` or `ABANDONED` without bumping `regionEpoch`, only where durable evidence permits; inconclusive old-epoch rows remain reconciliation-required. - `reset_first` - The controller derives this classification when the region is already `STALLED`, when mixed-epoch or orphaned coordination state is suspected, when duplicate/inconsistent durable batches are detected, or when `replay_first` fails to make bounded progress within the replay convergence budget. - - Goal: fence the old timeline with an epoch bump and use the canonical reset handshake to reconcile old-epoch work explicitly, terminalizing only where the evidence policy permits and retaining inconclusive work as non-terminal reconciliation under its original root `EffectId`. + - Goal: fence the old timeline with an epoch bump and use the canonical reset handshake to reconcile old-epoch work explicitly, terminalizing only where the evidence policy permits and retaining inconclusive work as non-terminal reconciliation under its original persisted mutation `EffectId`, with any enclosing `rootEffectId` retained separately as lineage and reconciliation context. 3. **Act** - The account-wide branch uses one canonical lifecycle for linked and standalone flows. Before inventory capture, each flow acquires and holds the live `accountAdmissionFence` through exact full-key readback and durable `coverageGeneration`, and carries `accountCoverageState=ACTIVE` with that concrete fence. The atomic coverage-proven transition releases the live fence and retains its exact value as `historicalAccountAdmissionFence`, changes the result to `accountCoverageState=HISTORICAL`, and makes the parent-independent child or standalone result reusable only after that proof. A flow that acquired the fence never uses `accountCoverageState=NO_ACTIVE_ACCOUNT_WIDE_FLOW` or `NOT_APPLICABLE` for either fence. A linked parent edge and its consumption CAS exact-compare the active state/live fence while coverage is active, then exact-compare the historical state/released fence after success; a standalone operation applies the same checks without a parent-consumption path. Missing, mismatched, or lifecycle-inappropriate live/historical values fail closed while preserving the existing parent-independent global child result and historical fence contract. 1. If the controller-validated classification is `replay_first`: @@ -152,7 +154,8 @@ Before entering this measured-SLO detect/decide path, verify that the affected d 3. The recovery workflow runs its internal ledger and command-convergence phases, converging lingering epoch-13 `SCHEDULED` rows to `APPLIED` or `ABANDONED` without bumping `region_epoch` only where durable evidence permits; inconclusive rows remain reconciliation-required, and command records follow the canonical terminal vocabulary. 4. If pending age and stalled signals recover within one emitted budget window, the region stays on epoch `13`; otherwise the controller upgrades the same operation and maintenance lock to `reset_first`. 2. If the controller-validated classification is `reset_first`: - - Execute the [Canonical Coordination Reset Sequence](./system-architecture-redis-operations.md#canonical-coordination-reset-sequence) for the same scope. + - **Target state only, once the canonical gated coordination-maintenance operation is implemented and proven:** Execute the [Canonical Coordination Reset Sequence](./system-architecture-redis-operations.md#canonical-coordination-reset-sequence) for the same scope. + - **Current deployments:** Do not execute the reset or mutate raw coordination keys. Preserve evidence, keep the affected scope fenced or stopped, use only the shipped `PauseTicksForScope` / `GetRuntimeOwnershipStatus` boundary and `coord_ops_ro` read-only inspection, then follow the [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback). - Keep only the incident-specific choices local to this runbook: scope selection, whether `replay_first` was exhausted first, whether gameplay sessions are preserved, and what evidence justified escalation. 3. Verify region health returns to `RUNNING` or bounded `DEGRADED` and eligible-profile measured exposure, including `redis_unreplicated_write_window_ms{scope}`, returns within `redis_unreplicated_write_window_slo_ms` for the same deployment/environment/ruleset scope after the controller-validated recovery classification completes. If replay cannot complete before `RESUME_AUTHORIZED`, the operation remains paused and quarantined until reset escalation or audited `release-lock`. A failure after `RESUME_AUTHORIZED` is reconciled only through the same operation's internal release worker; `release-lock` is prohibited. @@ -167,7 +170,8 @@ Before entering this measured-SLO detect/decide path, verify that the affected d - If mis-keyed data is purely coordination state (no unique business data), prefer a reset over in-place fixes. - If the mistake involves non-coordination prefixes that cannot be safely discarded, plan a one-off migration tool. 3. **Act** - 1. For coordination prefixes: follow the region/tenant/cluster reset flow from [Coordination Reset Model](./system-architecture-redis-reset-and-recovery.md#coordination-reset-model) and rely on PostgreSQL/idempotent ticks to rebuild state. + 1. **Target state only, once the canonical gated coordination-maintenance operation is implemented and proven:** For coordination prefixes, follow the region/tenant/cluster reset flow from [Coordination Reset Model](./system-architecture-redis-reset-and-recovery.md#coordination-reset-model) and rely on PostgreSQL/idempotent ticks to rebuild state. + - **Current deployments:** Do not execute this reset or mutate raw coordination keys. Preserve evidence, keep the affected scope fenced or stopped, use only the shipped `PauseTicksForScope` / `GetRuntimeOwnershipStatus` boundary and `coord_ops_ro` read-only inspection, and escalate through the [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback). 2. For non-coordination prefixes: write a small migration Job that: - Iterates the affected prefix (for example `automation:queue:{tenantInstanceTag}:*`). - Uses the prefix owner's documented writer fence while it writes corrected keys through shared builders. If no scope-wide writer fence exists, each corrected write must use an owner-specific atomic guarded transform whose single linearization boundary exact-compares the current source key's value digest, applicable version, and absolute expiry with the immutable per-key source evidence and conditionally writes the destination without overwriting a newer destination version. A changed or unavailable source aborts that key and leaves it for owner reconciliation rather than copying stale state. If the source and destination cannot be covered by that owner-specific primitive, including when they cannot share a Redis Cluster slot, the Job must abort and reconcile the key instead of migrating it. @@ -180,9 +184,11 @@ Before entering this measured-SLO detect/decide path, verify that the affected d - Automation consumers log deserialization errors or unknown `schemaVersion` values for `automation:queue:{tenantInstanceTag}:*` keys. - Metrics show sustained failures processing automation work items. 2. **Decide** - - Treat the queue as a non-authoritative Cache/Rate-Limit projection. The admissible row states and owner-fenced stale-lease/release CAS are owned by the [Redis Operations queue rebuild/index contract](./system-architecture-redis-operations.md#cacherate-limit-redis-reset); this incident runbook records the local consequence. A target `EVALUATING` row may be reindexed only after the owner proves its lease is stale or explicitly releases it through one fenced CAS covering status, lease owner, freshness, and fence transition; non-stale, unresolved, or ambiguous rows remain excluded. Current `rebuildPendingWorkItemIndex` unconditionally selects both statuses and has no stale, owner, or compare-and-set gate, so the current queue-prefix flush/rebuild and resume path is unavailable and must fail closed; no live scheduled rebuild invokes it, and an explicit invocation is not authorized by an admission pause. Durable PostgreSQL `script_work_items` remain authoritative, and Redis contents are not migrated. This implementation/proof gap is owned by Automation's scripting recovery contract. + - Treat the queue as a non-authoritative Cache/Rate-Limit projection. The admissible row states and owner-fenced stale-lease/release CAS are owned by the [Redis Operations queue rebuild/index contract](./system-architecture-redis-operations.md#cacherate-limit-redis-reset); this incident runbook records the local consequence. A target `EVALUATING` row may be reindexed only after the owner proves its lease is stale or explicitly releases it through one fenced CAS covering status, lease owner, freshness, and fence transition; non-stale, unresolved, or ambiguous rows remain excluded. Current `rebuildPendingWorkItemIndex` selects only `PENDING_EVALUATION` rows, but has no owner or compare-and-set gate, so the current queue-prefix flush/rebuild and resume path is unavailable and must fail closed; no live scheduled rebuild invokes it, and an explicit invocation is not authorized by an admission pause. Durable PostgreSQL `script_work_items` remain authoritative, and Redis contents are not migrated. This implementation/proof gap is owned by Automation's scripting recovery contract. - Do not treat the reserved `automation:timer:{tenantRegionTag}` or `script-scheduler:{tenantRegionTag}:lastTickId` timer/checkpoint projections as available reset targets; they remain target-only and unavailable. 3. **Act** - 1. For current recovery, before applying Game Session containment, obtain explicit impact approval for deployment-wide Automation containment, enumerate the affected `` scopes from the complete durable PostgreSQL/runtime inventory, stop or scale the Automation deployment so all executor processes cease, and obtain a durable deployment/owner acknowledgement plus authoritative readback that no executor claims or unsafe `rebuildPendingWorkItemIndex` invocations continue. Use Redis queue evidence only to supplement and locate symptoms, never to define inventory completeness, because lost queue pointers can omit affected instances. If any approval, complete inventory, containment, acknowledgement, or readback is unavailable, stale, or contradictory, keep the deployment and affected scopes fenced and escalate rather than applying a partial enumeration. Per-scope `SetAutomationAdmissionMode`/`GetAutomationDrainStatus` pause-and-drain is target state only, not current recovery authorization; see the [canonical scripting rollout and rollback convergence contract](./system-architecture-scripting-rollout-and-rollback.md) and [Automation drain contract](./system-architecture-scripting-control-plane-operations.md#getautomationdrainstatus). Only after the deployment-wide containment evidence is complete, apply the shipped Game Session `PauseTicksForScope` control to the containing `{tenantId, gameInstanceId}` instance (it is instance-wide, so omit `regionId`) and verify a successful response plus `GetRuntimeOwnershipStatus` showing `paused=true` for that instance before proceeding. - 2. Do not flush or rebuild the affected `automation:queue:{tenantInstanceTag}:*` prefix as a current recovery workflow. The live combined-status query has no atomic PENDING-only/owner-fenced stale-lease-or-release CAS gate and cannot establish a safe `EVALUATING` disposition; therefore the current queue flush/rebuild path is unavailable. The callable `rebuildPendingWorkItemIndex` remains unsafe and has no owner/CAS gate; no live scheduled rebuild invokes it, but an explicit invocation is not authorized by an admission pause. Redis queue payloads are not recovery authority. - 3. Do not resume current automation processing after this queue incident. A safe PENDING-only rebuild, owner-reconciled `EVALUATING` recovery, and the associated queue-specific stop/resume gate are target-state capabilities only; they may be used only after implementation and end-to-end proof. Monitor the contained deployment and affected scopes until the target recovery surface or an owner-approved replacement is available. + 1. Obtain explicit impact approval for deployment-wide Automation containment and enumerate the affected `` scopes from the complete durable PostgreSQL/runtime scope inventory. Use Redis queue evidence only to supplement and locate symptoms, never to define inventory completeness, because lost queue pointers can omit affected instances. If approval or the complete durable inventory is unavailable, keep the deployment and affected scopes fenced and escalate rather than applying a partial enumeration. In production recovery, pause Automation admission before applying Game Session containment; apply `SetAutomationAdmissionMode` with `mode=PAUSED_FOR_ROLLBACK` and a unique `controlPlaneRequestId` to each exact scope, then apply the shipped Game Session `PauseTicksForScope` control to the containing `{tenantId, gameInstanceId}` instance (it is instance-wide, so omit `regionId`) and verify a successful response plus `GetRuntimeOwnershipStatus` showing `paused=true` for that instance before proceeding. A tenant-wide or global pause is not a current Automation mutation; it must be represented by this complete per-instance enumeration. + 2. Do not flush or rebuild the affected `automation:queue:{tenantInstanceTag}:*` prefix as a current recovery workflow. The current rebuild query is PENDING-only, but has no atomic owner-fenced CAS gate and cannot establish a safe disposition for existing `EVALUATING` rows; therefore the current queue flush/rebuild path is unavailable. The callable `rebuildPendingWorkItemIndex` remains unsafe without an owner/CAS gate; no live scheduled rebuild invokes it, but an explicit invocation is not authorized by an admission pause. Redis queue payloads are not recovery authority. + 3. For the current fallback, stop or scale the Automation deployment so all executor processes cease. A process-level readiness state may be used only when an external deployment control can verify that it makes the whole process non-accepting; readiness is not a per-scope mutation. Verify that every executor claim and unsafe rebuild invocation has ceased, record the deployment-wide availability impact, and keep the exact scopes fenced. If no such deployment/process control exists, leave the service fenced and escalate through the Automation recovery owner; do not invent a queue-specific stop gate. + 4. After process cessation is verified, read back the admission state and drain status for each exact scope and `admissionEpoch`. Require the matching `PAUSED_FOR_ROLLBACK` mode, a fresh observation, `activeExecutionCount=0`, `pendingCancelableWorkItemCount=0`, and a durable owner/deployment acknowledgement bound to the scope, admission epoch, and control-plane request proving that executors have ceased and no unsafe rebuild invocation remains. Zero counts observed before process cessation are diagnostic only; a pause request or read-only drain count alone is not drain proof. The current-live drain surface does not expose exact `scriptPinEpoch`; target-state recovery additionally requires exact script-pin-epoch equality and a pin-epoch-bound acknowledgement, but that equality is not a current-live prerequisite. + 5. Do not resume current automation processing after this queue incident. A safe PENDING-only rebuild, owner-reconciled `EVALUATING` recovery, and the associated queue-specific stop/resume gate are target-state capabilities only; they may be used only after implementation and end-to-end proof. Monitor the paused scopes until the target recovery surface or an owner-approved replacement is available. diff --git a/design/architecture/system-architecture-redis-lua-patterns.md b/design/architecture/system-architecture-redis-lua-patterns.md index 080826b4a9..a8cc68a8b4 100644 --- a/design/architecture/system-architecture-redis-lua-patterns.md +++ b/design/architecture/system-architecture-redis-lua-patterns.md @@ -36,12 +36,21 @@ Every coordination script belongs to a **script category** that constrains which | Gameplay session CAS / bindings | `session:game:{tenantGameplayTag}::` plus tenant-tagged `session:game:index:*:{tenantGameplayTag}:*` | Gameplay session CAS/update scripts may be shard-local multi-key scripts where all gameplay-session keys share `{tenantGameplayTag}`. They own gameplay binding and reconnect state only; they do not operate on Account auth-token registry keys, tick keys, or the global account index in the same invocation. | | Cross-tenant gameplay-session account index | `session:game:index:account:` | This global account index cannot share every tenant gameplay slot and is never included in a shard-local gameplay CAS/Lua invocation. Game Session updates it through a separate idempotent write after the owning gameplay-session mutation and reconciles it from authoritative session bindings. Account-wide revocation uses the index as a discovery projection but verifies and mutates each tenant-local binding through its owning shard-local contract; missing or stale index entries are repaired rather than treated as authorization truth. | | Account auth-token registry | `session:auth:token:` | Account-owned issued-token registry operations are single-key operations for the exact token hash. The exact-token registry record is mandatory validity and per-token-revocation authority: a cryptographically valid JWT without a matching permitted record is denied, and Lua must not invent validity from absence or from a generation alone. Durable issuer/account/tenant/membership authority generations advance in Account Service; Redis entries project/read through those durable generations for validation, while Lua may enforce the stored record state but never becomes the authority for generation advancement. This is not part of gameplay session CAS. | +| Gateway replay admission | `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:` | The `gateway-connect-token-replay-consume/v1` descriptor is the only three-key descriptor in this category: it runs only on Coordination Redis and receives readiness/fence, replay, and deny keys in that order. The literal `{gateway-connect-token-replay-v1}` hash tag is required on all three keys so Redis Cluster executes the atomic operation in one slot; the readiness value carries `replayAdmissionFence`. The separate `gateway-connect-token-browser-revoke/v1` descriptor is a one-key deny-marker mutation using only `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:` with the same literal tag; it is not part of this three-key key order. The current generic Cache-bound writer's only untagged output is the replay marker; it has no deny-marker, readiness, or replay-fence writer. That old replay key is migration-only drift and is not a valid descriptor shape. | | Session-to-region bridge | `tick:{tenantRegionTag}:session-binding:` plus `tick-executor-lease:{tenantRegionTag}` | Region-lease scripts only. They update region-authoritative gameplay bindings using caller-supplied `sessionId` / `binding_generation` and never read `session:game:*` directly inside Lua. | | Maintenance / cleanup | Region-local maintenance keys under `tick:{tenantRegionTag}:*` or `timer:{tenantRegionTag}` | Shard-local scans and deletes constrained to one `{tenantRegionTag}` at a time; no cross-slot operations. | | Automation helpers (coordination role only, target-only once implemented) | `script-scheduler:{tenantRegionTag}:lastTickId` and similar | This is a reserved target pattern only: no current Automation-owned coordination helper or key is implemented. Any future helper must not touch Cache/Rate-Limit prefixes. | The Lua Script Registry encodes these category→prefix→shard rules so that callers do not hard-code prefixes or slots. New categories or key families must be added to this table and to the registry schema before scripts using them are accepted. +Automation queue-pointer enqueue and rebuild are a separate Cache/Rate-Limit descriptor boundary, not additions to the Coordination categories above. An atomic operation over `automation:queue:{tenantInstanceTag}:*` must declare `redis_role=cache`, use only queue keys for one exact `{tenantInstanceTag}` scope, and be authorized by `cache_app` for normal projection or by the target-only `automation_queue_rebuild_maint` ACL principal during an externally fenced reset/rebuild. The descriptor must carry the operation/fence, deployment generation, and exact prefix/scope admission fields described in the [Cache/Rate-Limit reset runbook](./system-architecture-redis-operations.md#external-cache-deployment-maintenance-gate); it must reject Coordination keys and `coord_app`, and its outcome must remain a best-effort pointer projection rather than durable-work authority. If the atomic enqueue/rebuild implementation uses single-key Redis commands instead of Lua, the same `redis_role`, key, slot, and ACL boundary still applies. These descriptors must be represented separately from the Coordination script categories in the ADR 0176 registry. + +The Gateway replay-consume descriptor is `gateway-connect-token-replay-consume/v1`: `redis_role=coordination`, `KEYS[1]=gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, `KEYS[2]=gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, and `KEYS[3]=gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`. The descriptor must require the literal `{gateway-connect-token-replay-v1}` tag on every key, reject the untagged current-drift replay marker, and declare the stable outcomes `1` (marker created), `0` (already replayed), and `-1` (browser denied), with no mutation for `0` or `-1`. Focused contract tests must prove the three keys resolve to one Redis Cluster slot, reject any missing or different tag, preserve readiness/fence and deny-marker race ordering, and keep the same `KEYS` order under RESP2 and RESP3. Migration tests separately inventory/read back the current untagged replay prefix under quarantine and prove that it cannot be accepted by the target descriptor. Select and report implementation and runtime proof using [Validation and Runtime Proof](../developer-workflows/validation-and-runtime-proof.md). + +While an untagged legacy `jti` marker may still represent a token accepted in its original window, replay admission remains blocked. Legacy-marker continuity requires proven exact transfer to canonical tagged authority or expiry/quarantine release gates proving the marker unusable; absence of a tagged target key alone never proves the legacy token unused. Resolving that continuity condition does not release quarantine: all ADR 0029 deadline, exact fenced probe, old-writer, and owner release gates still apply. + +Browser revocation has a separate descriptor, `gateway-connect-token-browser-revoke/v1`, because its deny-marker mutation and durability acknowledgement are not the three-key replay-consume script contract. It uses `redis_role=coordination`, `KEYS[1]=gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`, and the token's absolute expiry (including the configured clock-skew allowance) as the bounded marker TTL. A newly created marker may return `1`. An existing marker may return `0` only as an observation; it is not by itself proof on the current connection. Before `WAITAOF`, the existing-marker path must reassert the valid marker with its unchanged original absolute expiry on the same pinned connection, or withhold `DURABLE_BROWSER_REVOKE_ACK` until durability of the original write is proven. It must never extend the expiry. Malformed or conflicting marker state is non-mutating and fails closed. Gateway must immediately issue `WAITAOF requiredLocalAofCount requiredReplicaAofCount firemud.gateway.replayConsumeAckTimeoutMs` on the same pinned connection, with the same exact two-integer threshold validation as replay consumption; only that acknowledgement yields `DURABLE_BROWSER_REVOKE_ACK`. This descriptor must require the literal `{gateway-connect-token-replay-v1}` tag and must not be folded into, or represented as, the replay-consume descriptor's three-key invocation. The current implementation provides neither this deny-marker write nor its `WAITAOF` proof: it is replay-only, untagged, and Cache-bound migration drift. + Entity-lock hard rule: each Redis tick Lua invocation may acquire at most one `tick:{tenantRegionTag}:lock:`. Piecemeal acquisition across invocations, a multi-lock whitelist, and a configurable multi-lock count are prohibited. A script fails closed when its declared or supplied key set would require more than one entity lock. Multi-entity invariants belong to an owning transaction or durable effect/workflow path, not Redis lock lifetime. See [ADR 0074](./decisions/adr-0074-one-entity-lock-per-redis-script.md). ## Idempotent Script Patterns and Examples @@ -263,7 +272,7 @@ The Automation & Scripting Service does not construct or invoke `tick:*` keys. G - Automation scripts **never** perform multi-key operations that span both `automation:*` and `tick:*` prefixes in one `EVAL`/`EVALSHA` call. - Automation work is projected under `automation:queue:*` and handed off to Game Session via gRPC; only Game Session scripts mutate `tick:*` prefixes. - Current live timer rows may expose an optional `dueTickId` alongside the existing due-state fields and derived projections; live Redis scripts must not assume that the tagged `duePoint` migration shape is already present. In target state, schedule-derived work uses the complete due-candidate and firing-claim projection defined by the [Scripting Scheduler and Timer Lifecycle](./system-architecture-scripting-scheduler-and-timers.md#script-timers-vs-tick-timers): it includes mandatory `stableOwnerKind` and `stableOwnerId`, `entityId` only for an entity-scoped target, `resumeWindowId` only for `triggerMode=CATCH_UP`, the exact script pin, `isDryRun`, and applicable plugin provenance. For plugin-owned candidates, `pluginActivationEpoch` is a tagged candidate/firing-claim and derived-`scriptEventId` identity field, while `lifecycleRevision` is required non-identity fence evidence. The winning claim derives `scriptEventId` from that complete candidate identity; it is not a pre-claim input, and retries reuse the derived value. Scheduled rows require exactly one tagged `duePoint`, either `dueTickId:` or `dueAt:`; both forms, neither form, empty values, and zero placeholders are invalid. Immediate event rows use the distinct event-driven identity branch, omit scheduler-only fields and `duePoint`, and have both physical `dueTickId` and `dueAt` columns explicitly `NULL`. A versioned migration must translate live due fields before enforcing the target tagged form. The per-command `automationDispatchId` plus `commandOrdinal` is the suffix of the complete source/optional-target-scoped Command-Handoff Identity and must not be replaced by `scriptEventId` or `commandKind` alone. - - Before invoking the Redis enqueue script, Game Session must insert or confirm a durable admission row whose uniqueness key is the complete [Command-Handoff Identity](./system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state): source runtime scope, optional distinct target runtime scope, `automationDispatchId`, and `commandOrdinal`. When a distinct target applies, its `targetGameInstanceId`, `targetPlayableStateScope`, `targetRegionId`, and `targetRegionEpoch` are part of that optional target runtime identity. The parent Trigger Identity, due point, command payload, and any current-routing fields outside the immutable source/optional-target scopes are retained as immutable comparison and readback evidence; they do not extend command identity. Scheduled rows retain exactly one tagged due point (`dueTickId:` or `dueAt:`); immediate event rows use the separate immediate branch and keep scheduler-only fields and both physical due columns `NULL`. Redis enqueue scripts may project that complete Command-Handoff Identity into an idempotent member key for hot-path dedupe; the dispatch-plus-ordinal suffix alone is insufficient because `automationDispatchId` is not globally unique. The durable admission row and durable trigger-instance uniqueness projection remain the authorities used after resets, gRPC retries, and failover. + - Before invoking the Redis enqueue script, Game Session must insert or confirm a durable admission row whose uniqueness key is the complete [Command-Handoff Identity](./system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state): source runtime scope, optional distinct target runtime scope, `automationDispatchId`, and `commandOrdinal`. When a distinct target applies, its `targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetRegionId`, and `targetRegionEpoch` are part of that optional target runtime identity; `targetPlayableStateScope` remains separately persisted and exact-validated target policy/routing/authorization/fence evidence, not a uniqueness input. The parent Trigger Identity, due point, command payload, and any current-routing fields outside the immutable source/optional-target scopes are retained as immutable comparison and readback evidence; they do not extend command identity. Scheduled rows retain exactly one tagged due point (`dueTickId:` or `dueAt:`); immediate event rows use the separate immediate branch and keep scheduler-only fields and both physical due columns `NULL`. Redis enqueue scripts may project that complete Command-Handoff Identity into an idempotent member key for hot-path dedupe; the dispatch-plus-ordinal suffix alone is insufficient because `automationDispatchId` is not globally unique. The durable admission row and durable trigger-instance uniqueness projection remain the authorities used after resets, gRPC retries, and failover. Once ADR 0176's target descriptor validation is implemented, CI must reject automation Lua/descriptors that construct or reference any `tick:*` key; Game Session alone uses its owner-local tick builders. @@ -333,18 +342,18 @@ Bulk key-walking is reserved for **offline maintenance tooling**, not tick execu - After the owner-defined recovery release, the first fenced staging CAS must accept only `requestedTickId = 0` and atomically advance exactly `-1 → 0` and `APPLIED → STAGED`; no other requested tick may treat `-1` as an ordinary terminal prior tick. Subsequent ticks follow the ordinary immediate-next-tick terminal transition. - These hot-path scripts are intentionally **not** the mechanism for reconstructing a lost older tick after coordination loss or reset. - First implementation replays older work directly from durable tick-batch manifests and ledger rows without re-materializing that old tick into `pending`. - - Older-tick recovery records `APPLIED` or `ABANDONED` only in the durable ledger/reconciliation state under the older tick's original epoch and root effect identity; it must not overwrite or regress `tick:{tenantRegionTag}:meta`. Redis `pending` contents alone are never sufficient evidence that the current epoch scheduler timeline may move on, and tick metadata updates are limited to that current timeline. + - Older-tick recovery records `APPLIED` or `ABANDONED` only in the durable ledger/reconciliation state under the older tick's original epoch and persisted mutation `effect_id`; `root_effect_id` remains separately retained as lineage and reconciliation context. It must not overwrite or regress `tick:{tenantRegionTag}:meta`. Redis `pending` contents alone are never sufficient evidence that the current epoch scheduler timeline may move on, and tick metadata updates are limited to that current timeline. - If FireMUD later introduces a dedicated recovery-restage script, it must be registered as a separate maintenance script category with its own explicit invariants, compatibility mode, and runbook entry; it must not silently reuse the normal tick staging contract. - Such a recovery-restage path is not considered specified or implementable until the corresponding maintenance runbook in the Redis operations docs names the entrypoint, scope restrictions, and post-run verification steps. -- **Pattern 3 – Immutable pending-envelope identity and replay (no collision-prone staging)** -- Each staged member in `pending` carries an immutable envelope whose logical identity is the exact `tick_batch_id` plus the complete root `EffectId` participant projection: `root_effect_id`, the canonical typed operation, the exact `target_aggregate_type`/`target_aggregate_id`, and the exact scope, epoch, and tick needed to resolve one durable ledger row. Envelope construction must reject a missing, malformed, or ambiguous typed operation or exact target; `effect_key` remains descriptor metadata only and is never the pending member identity or replay authority. Physical encoding may use a hash, set/ZSET member, or another registered representation, but it must preserve this complete logical envelope unchanged. -- Before adding or replaying a staged member, the script compares the complete envelope and bound request payload, including the typed operation and immutable request digest, not `effect_key` alone. An exact full-envelope/request-payload match returns the prior stored staging/replay outcome without creating another member or changing its payload or TTL. A same `effect_key` with a different `tick_batch_id`, root `EffectId`, typed operation, participant/target projection, scope, epoch, tick, or request payload is a conflict/fail-closed result and must not overwrite or merge the existing member. +- **Pattern 3 – Immutable pending-envelope identity and replay (target state; no collision-prone staging)** +- Each target staged member in `pending` carries an immutable envelope whose logical identity is the exact `tick_batch_id` plus the collision-safe participant/target projection: `(tenant_id, game_instance_id, playableStateNamespaceId, regionId, regionEpoch, tickId, mutation EffectId (effect_id), typed_operation, target_aggregate_type, target_aggregate_id)`. `playableStateScope` remains immutable envelope and exact-comparison/readback evidence, but is not a pending-member uniqueness dimension. The envelope also carries the exact immutable request payload/digest needed to resolve one durable ledger row. The enclosing `root_effect_id` is retained as immutable lineage/conflict evidence but is excluded from member uniqueness, so it cannot collapse sibling mutations. Envelope construction must reject a missing, malformed, or ambiguous typed operation or exact target; `effect_key` remains descriptor metadata only and is never the pending member identity or replay authority. Physical encoding may use a hash, set/ZSET member, or another registered representation, but it must preserve this complete logical envelope unchanged. Current Game Session `gamesession:tick:pending:*` entries instead use the narrower command envelope documented by [Tick Execution Flows](./system-architecture-tick-execution-flows.md#implementation-notes); complete Pattern 3 producer, consumer, replay, and focused proof remain an implementation gap. +- Before adding or replaying a staged member, the script compares the complete envelope and bound request payload, including the mutation `effect_id`, typed operation, participant/target projection, and immutable request digest; `root_effect_id` remains lineage/conflict evidence and `effect_key` remains descriptor metadata. An exact full-envelope/request-payload match returns the prior stored staging/replay outcome without creating another member or changing its payload or TTL. Distinct envelopes may share an `effect_key` when their complete identities differ; an exact identity with conflicting immutable envelope or request-payload evidence, including a differing bound `root_effect_id`, is a conflict/fail-closed result and must not overwrite or merge the existing member. Replay uses the mutation `effect_id`/participant identity, never `effect_key` or the enclosing root alone. - Missing, malformed, ambiguous, partial, or conflicting envelopes are non-mutating failures. Exact-envelope duplicate handling is local staging idempotency only; domain services still use their participant guards and Game Session still performs durable batch/ledger exact-set validation. - **Pattern 4 – Queue insertion with uniqueness** - When scripts enqueue work (for example timers or retryable actions), they use data structures that naturally deduplicate: - - ZSET-based queues use `ZADD` with a unique member identifier (effect key or command ID); scripts check `ZSCORE` first and only call `ZADD` when the member is not already present. + - ZSET-based queues use `ZADD` with a unique member identifier (effect key or command ID) only when the owning queue contract declares that value to be the complete member identity; this excludes `tick:pending`, which follows Pattern 3's full immutable envelope. Scripts check `ZSCORE` first and only call `ZADD` when the member is not already present. - For simple sets of flags or participants, scripts use `SADD` and ignore the return value except for observability; repeated `SADD` calls with the same member are safe no-ops. - This ensures that retries or replays do not create duplicate queue entries even when callers re-invoke the script. @@ -402,7 +411,7 @@ Unit tests for this script would: Script changes must be rolled out in a way that respects both AOF replay semantics and the reset model described in `system-architecture-redis-reset-and-recovery.md`: - **Compatibility levels** - - `compatible` – purely additive changes (for example, new return fields, extra read-only validations) that do not change key shape or semantics. These may be rolled out without coordination resets as long as callers tolerate older results. + - `compatible` – purely additive changes (for example, new return fields or additional observability) that preserve the accepted-input set, outcomes, fencing, idempotency, and mutation semantics. Any validation that can reject a previously valid caller or payload requires the versioned/reset path. These may be rolled out without coordination resets as long as callers tolerate older results. - `requires_region_reset` / `requires_tenant_reset` / `requires_cluster_reset` – changes that alter key shapes or semantics in ways that cannot be safely mixed with old behavior. These must run alongside the corresponding coordination reset flows and are expected to be rare. - If a rollout requires an epoch boundary to avoid mixed old/new semantics, classify it as the corresponding `requires_*_reset` scope and execute the full reset handshake (pause ticks → bump `region_epoch` → reconcile ledger → resume). Do not treat `region_epoch` bumps as a routine rollout mechanism outside this compatibility contract. - **Registry as the source of truth** @@ -424,7 +433,7 @@ The registry, validators, ownership enforcement, generic test harness, and CI ch - `reset_sensitivity` describing which reset scopes (region, tenant, cluster) must be considered when changing script behavior or key shape. - `loss_outcome_class` naming the ADR 0058 work class and its required loss/recovery disposition. - `tail_loss_behavior` describing what is expected to happen if the script’s writes are lost or replayed within the measured unreplicated-write exposure (for example “pure lease; safe to lose”, “can enqueue duplicates; relies on domain idempotency”, “must not silently drop without a corresponding ledger row”). - - Shard-locality metadata for multi-key scripts, including whether all `KEYS` must share the same `{tenantRegionTag}`, `{tenantInstanceTag}`, or `{tenantGameplayTag}` hash tag and slot. + - Shard-locality metadata for multi-key scripts, including whether all `KEYS` must share the same `{tenantRegionTag}`, `{tenantInstanceTag}`, `{tenantGameplayTag}`, or fixed `{gateway-connect-token-replay-v1}` hash tag and slot. The registry descriptors are sufficient to **drive a generic test harness** over owner-local or genuinely shared sources: any coordination script must be invokable in isolation using the registry metadata (script identifier, expected `KEYS`/`ARGV`, and allowed prefixes). Callers must not hard-code key names or slots that diverge from their owner descriptor. @@ -438,7 +447,7 @@ CI enforces the following invariants for registered scripts: - They reference prefixes that belong to Cache/Rate-Limit Redis, or - They omit required `reset_sensitivity`, `loss_outcome_class`, or `tail_loss_behavior` metadata. - For scripts that declare shard-local multi-key behavior, CI verifies that: - - All declared `KEYS` share the same hash tag (for example `{tenantRegionTag}`), and + - All declared `KEYS` share the same hash tag (for example `{tenantRegionTag}` or the fixed `{gateway-connect-token-replay-v1}`), and - No script attempts cross-slot operations under the `coordination` role. ## Call-Side Time and Randomness Contract diff --git a/design/architecture/system-architecture-redis-operations.md b/design/architecture/system-architecture-redis-operations.md index 6a7b0f9a85..b55c93356a 100644 --- a/design/architecture/system-architecture-redis-operations.md +++ b/design/architecture/system-architecture-redis-operations.md @@ -34,6 +34,8 @@ This target-state blanket explicitly excludes the linked **Current Operator Fall ## Canonical Coordination Reset Sequence +> **Target state only — unavailable today.** The `coordination-maintenance` operation and phases below are not current operator instructions. Current operators must use the [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback): preserve evidence, keep the affected scope fenced, use only shipped pause/status and read-only inspection, and escalate. + This section is the normative source for the multi-step Coordination Redis reset/recovery workflow. Other runbooks should point here and then describe only scope choice, session policy, evidence, and scenario-specific abort or storage steps. Canonical public operation: @@ -135,7 +137,7 @@ This section centralizes the normative targets for Redis behavior that other doc - **Script runtime** - tick- and session-related Lua scripts are expected to complete within roughly 10–20 ms per invocation under normal load - **Coordination memory share** - - coordination prefixes should normally occupy no more than about 30–40% of `maxmemory` on Coordination Redis with `noeviction` + - coordination prefixes should normally occupy no more than about 30–40% of `maxmemory` on Coordination Redis with mandatory `maxmemory-policy=noeviction` for every non-ephemeral profile; the only permitted deviation is an explicitly labeled ephemeral one-shot test stack, and any non-ephemeral deviation or observed eviction is fail-closed incident evidence ### Cache/Rate-Limit Redis Core Targets @@ -174,15 +176,19 @@ Manual AOF surgery is not supported. Either the AOF is trusted and replayed as-i Goal: provide a simple, explicit runbook for resetting Cache/Rate-Limit Redis without entangling it with Coordination Redis resets. +> **Target state only — unavailable today.** The external Cache deployment maintenance gate, `FLUSHDB`/`FLUSHALL` or clustered deletion, client release, and authorized Automation rebuild/readback sequence below are not current operator instructions. The repository does not yet provide the required external gate, writer admission/acknowledgement proof, or authorized rebuild path. Current operators must preserve cache, reset, and incident evidence and avoid destructive reset or client-release actions. Affected writers may be quarantined or stopped only through an existing supported readiness control; if none applies, leave the deployment untouched, preserve evidence, and escalate through the safe fail-closed [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback) and escalation path. + +### External Cache Deployment Maintenance Gate + +The reset gate reuses the ADR-0085 external durable operation/fence pattern without making Cache/Rate-Limit Redis an authority. It is one durable operation outside the target deployment with an immutable `operationId`, exact environment/deployment identity and generation, a frozen complete registered writer and prefix inventory, and a durable external fencing token/generation. Before deletion, every ordinary writer must either pause and drain with an acknowledgement bound to that exact operation/fence or be denied Cache/Rate-Limit Redis connection/network admission. Writer admission and acknowledgements must revalidate the operation/fence and deployment generation after every restart or replacement; stale writers, stale operations, inventory changes, and missing, partial, or ambiguous evidence are rejected. Competing operations are serialized, and takeover, expiry, abort, and release each require durable evidence bound to the same operation/fence. A local Redis key is not the gate: the external gate must survive Redis and writer restarts and remain held through deletion, verification, and rebuild. Only the target-only named ACL principal `automation_queue_rebuild_maint`, bound to the same operation/fence, deployment generation, and exact registered `automation:queue:*` prefix/scope, may write while the gate is held; ordinary writers remain denied, and its completion/readback is required before release. This narrow Automation rebuild writer is not privileged reset-deletion authority: Cache reset deletion separately requires actor/workload authorization for the exact complete registered prefix inventory, bound to the same operation/fence and deployment generation, plus deletion apply/readback proof under [Redis Ops Access](./system-architecture-redis-ops-access.md#canonical-control-plane-and-cli-contract). No shipped principal currently authorizes that complete inventory, so reset deletion remains unavailable and fail-closed. This is not a generic cache or operator writer: any future non-Automation Cache/Rate-Limit rebuild, if needed, requires its own separately named owner principal and prefix contract. The current tooling does not yet provide this complete gate, writer acknowledgement/admission proof, or authorized rebuild path, so current operators must use the fallback above. + Cache/Rate-Limit Redis is fully reset-tolerant for the prefixes listed in [`system-architecture-redis-cache.md`](./system-architecture-redis-cache.md) and the reset policy matrix in [`system-architecture-redis-reset-and-recovery.md`](./system-architecture-redis-reset-and-recovery.md). A reset: - applies deletion only to the exact registered key patterns in the immutable Cache/Rate-Limit prefix inventory, under the bounded apply/readback contract; catalog family labels such as inventory, character-cache, world-dynamic, room, view:room-look, chat, and ratelimit are not executable deletion selectors, and broad `automation:*` matching remains prohibited - does not affect Coordination Redis keys such as `tick:*`, `timer:*`, `retry:*`, `session:*`, `tick-executor-lease:*`, `automation:timer:*`, or `script-scheduler:*` - increases load on backing services temporarily but must not lose authoritative game data -The current `automation:queue:{tenantInstanceTag}:*` family is a non-authoritative Cache/Rate-Limit projection. The target rebuild/index operation may index only safe durable `PENDING_EVALUATION` work, or an `EVALUATING` row only after the owner proves its lease is stale or explicitly releases it through one fenced CAS covering the status, lease owner, freshness, and fence transition. Non-stale, unresolved, or ambiguous rows remain excluded. Current `rebuildPendingWorkItemIndex` unconditionally selects both statuses and has no stale, owner, or compare-and-set gate, so queue-prefix reset/rebuild and resume are unavailable and must fail closed; a non-atomic status preflight cannot authorize a safe PENDING-only path. Redis queue payloads are never recovery authority. The reserved `automation:timer:{tenantRegionTag}` and `script-scheduler:{tenantRegionTag}:lastTickId` timer/checkpoint projections remain target-only and unavailable. - -Do not use the generic Cache/Rate-Limit reset procedure below for the current Automation queue family. A queue-prefix flush, safe PENDING-only rebuild, and resume sequence is target-only until the owner-reconciled status/CAS recovery contract is implemented and proven; current queue incidents remain paused and fail closed under the [Automation queue incident runbook](./system-architecture-redis-incident-runbook.md#automation-queue-schema-mistakes). +The current `automation:queue:{tenantInstanceTag}:*` family is a non-authoritative Cache/Rate-Limit projection. The target rebuild/index operation may index only safe durable `PENDING_EVALUATION` work, or an `EVALUATING` row only after the owner proves its lease is stale or explicitly releases it through one fenced CAS covering the status, lease owner, freshness, and fence transition. Non-stale, unresolved, or ambiguous rows remain excluded. Current `rebuildPendingWorkItemIndex` selects only `PENDING_EVALUATION` rows, but has no owner or compare-and-set gate, so queue-prefix reset/rebuild and resume are unavailable and must fail closed; a non-atomic status preflight cannot authorize a safe PENDING-only path or establish a safe disposition for existing `EVALUATING` rows. Redis queue payloads are never recovery authority. The reserved `automation:timer:{tenantRegionTag}` and `script-scheduler:{tenantRegionTag}:lastTickId` timer/checkpoint projections remain target-only and unavailable. ### Runbook: Environment-Scoped Cache Reset @@ -206,6 +212,8 @@ FireMUD classifies coordination-backed workloads by reset tolerance: - **reset-sensitive** - gameplay session prefixes such as `session:game:*`; current live Account auth uses the legacy `session:auth:account:*` and `session:auth:tenant:*` projections, while target-only Account auth families are `session:auth:token:*` and `session:auth:generation:*`; the Account-owned unversioned legacy `session:connect-token:*` result map and target `session:connect-token:v1:*` issuance-result projection are also reset-sensitive - future automation queues explicitly assigned to Coordination Redis by their owner contract (the current `automation:queue:{tenantInstanceTag}:*` family is a Cache/Rate-Limit projection and follows the unavailable queue-reset path above), or non-critical analytics that can be recomputed or re-enqueued + - The connect-token issuance-result family is distinct from Gateway replay/deny markers. Narrow region/tenant resets preserve it; cluster reset may discard it only after Account-owned durable/fenced recovery or request-identity expiry, otherwise missing state requires exact-result recovery or fail-closed refusal. + - future automation queues explicitly assigned to Coordination Redis by their owner contract, or non-critical analytics that can be recomputed or re-enqueued; new automation or analytics prefixes are not implicitly assigned this class and each exact family must be registered with its owner and reset contract before use. - **reset-forbidden** - future workloads that would treat Redis as a durable component of a long-lived contract @@ -221,12 +229,12 @@ Facts: - Coordination Redis uses asynchronous replication. - A promoted replica may be missing recent coordination writes. -- The new primary’s keyspace is authoritative after promotion. +- The new primary becomes the active source for surviving Redis coordination projections after promotion, but remains only a coordination projection and never durable authority. PostgreSQL and the owning domain stores remain authoritative for durable outcomes, timeline baselines, and recovery decisions. Behavior: - modest promotion lag contributes to the measured unreplicated-write exposure -- replay safety is preserved by lease/lock/epoch validation and PostgreSQL-backed effect ledgers +- tick/effect replay safety is preserved by lease/lock/epoch validation and PostgreSQL-backed effect ledgers; protected admission is separate and requires owner-specific replay-marker, auth-token, session, generation, and relevant fence continuity/readback proof Runbook: @@ -235,15 +243,15 @@ Runbook: - acceptable: `redis_replication_lag_ms <= 0.5 * redis_unreplicated_write_window_slo_ms` - warning: `0.5 * redis_unreplicated_write_window_slo_ms < redis_replication_lag_ms < redis_unreplicated_write_window_slo_ms` - red: `redis_replication_lag_ms >= redis_unreplicated_write_window_slo_ms` -3. If lag is in the acceptable band, promotion is acceptable from a replay perspective. +3. If lag is in the acceptable band, it bounds tick/effect replay exposure only; it does not by itself authorize protected admission or prove replay-marker/auth-token/session/generation continuity. Any uncertain continuity remains quarantined/fenced until the owning proof/readback succeeds. 4. If lag is in the warning band, investigate immediately and delay promotion unless the failover risk of waiting is worse than accepting a wider measured exposure. -5. If lag crosses the red line, either wait for recovery or treat promotion as a deliberate drop-recent-coordination-state event handled by one bounded `coordination-maintenance recover --mode reset --scope ` operation under the normal maintenance-lock and epoch-fencing workflow, with exactly one of `--preserve-sessions` or `--invalidate-sessions` selected. +5. If lag crosses the red line, the following is **target-state procedure only and unavailable in the current implementation**: either wait for recovery or treat promotion as a deliberate drop-recent-coordination-state event handled by one bounded `coordination-maintenance recover --mode reset --scope ` operation under the normal maintenance-lock and epoch-fencing workflow, with exactly one of `--preserve-sessions` or `--invalidate-sessions` selected. For a current red-lag incident, do not invoke that unavailable reset; use the fail-closed [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback), preserve AOF and incident evidence, keep the affected scope fenced, and escalate through the linked incident runbook. ## Key Shape Mistakes and Coordination Resets > This runbook inherits the [current execution boundary](#current-execution-boundary); its imperative steps are target-state only. -Coordination keys are treated as reset-tolerant, volatile, and backed by PostgreSQL plus replay. +Coordination keys are volatile, and each prefix follows the class in the canonical [reset policy matrix](./system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). Only reset-tolerant families may be dropped without reset-sensitive owner gates. A reset-sensitive family may be deleted only after its owner’s pause and applicable cutover or invalidation and fencing gates succeed; the applicable reconciliation/readback must then complete before release, with preserved-session rebind required only when `--preserve-sessions` is selected. Before performing any coordination reset, operators should walk a short pre-reset validation checklist: @@ -258,6 +266,8 @@ Every coordination reset that affects tick execution must include the Game Sessi ### Runbook: Mis-Sharded Coordination Keys +> **Target state only — unavailable today.** Do not execute this reset/resume sequence in current operations. Use the [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback) and escalate with the affected scope fenced. + 1. detect the issue through CI, logs, or metrics 2. choose the smallest safe scope 3. execute the [Canonical Coordination Reset Sequence](#canonical-coordination-reset-sequence) for that scope @@ -265,10 +275,12 @@ Every coordination reset that affects tick execution must include the Game Sessi ### Key Enumeration Strategy for Scoped Resets -Cluster-safe scoped resets rely on prefix-scoped `SCAN` per master under strict operational preconditions: +Cluster-safe scoped resets use prefix-scoped `SCAN` per master only as an internal, target-state phase of the canonical durable `coordination-maintenance` operation described above. This phase is unavailable in the current implementation and is not a standalone reset or cleanup recipe. Before enumeration starts, that same operation must carry the unchanged ADR-0085 external maintenance handoff: the exact `operationId`, external maintenance fence/lock binding, classifier, immutable evidence digest, and complete affected scope, with the canonical pre-wipe gates already proven where the phase is destructive. The operation remains fenced through the canonical post-reset verification; scan completion or key absence is never evidence to bypass those gates. A fine-grained scoped reset lock may coordinate batches inside the already-held operation, but it never replaces the deployment-wide maintenance operation or lock. + +Within that operation, cluster-safe enumeration follows these internal steps: -1. pause the target region or scope -2. acquire a scoped reset lock +1. use the operation-owned pause and external maintenance fence for the target scope +2. bind any scoped reset lock to that operation and its complete recorded scope 3. enumerate only known prefix families 4. scan each master with modest `COUNT` and strict time budgets 5. delete via `UNLINK` where possible @@ -280,6 +292,8 @@ A lightweight unknown-prefix scanner periodically scans with conservative budget ## Session Schema Cleanup and Large Keyspaces +> **Target state only — unavailable today.** The `coordination-maintenance recover --mode session-schema-cleanup` flow and its mutating continuation/release controls are not current operator instructions. Current operators must use the [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback): preserve evidence, keep the affected scope fenced, use shipped pause/status and read-only inspection, and escalate. + Session schema cleanup is a hygiene and recovery tool, not a normal steady-state path. When cleanup is required after a schema change or persistent unsupported-schema drift: - operate on tenant-scoped gameplay/bootstrap prefixes such as `session:game:{tenantGameplayTag}:*` and the current `sessionctx::*` family @@ -349,6 +363,7 @@ Canonical maintenance-active signal: ## Dual-Leader Detection and Coordination Reset > This runbook inherits the [current execution boundary](#current-execution-boundary); its imperative steps are target-state only. +> **Target state only — unavailable today.** The recovery commands in this runbook are not current operator instructions. Use the [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback), keep affected admission and mutation fenced, and escalate. Goal: detect Redis split-brain or conflicting primaries and recover through a coordinated reset before duplicate logical effects can escape the tick subsystem. @@ -375,6 +390,8 @@ Goal: change how `tenantId` / `gameInstanceId` / `regionId` normalization and ha ### Runbook: Normalization Migration via Reset +> **Target state only — unavailable today.** This reset-based normalization migration and its `coordination-maintenance` CLI/release controls are not current operator instructions. Current operators must use the [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback): preserve evidence, keep the affected scope fenced, use shipped pause/status and read-only inspection, and escalate. + The migration reset gate must pass the complete [canonical post-reset verification checklist](./system-architecture-redis-ops-access.md#canonical-post-reset-verification-checklist), including the two independent exact digests, mode-specific startup attestation, all positive and destructive negative probes, and isolated-target cleanup/readback evidence. A combined or caller-asserted digest value or copied probe subset cannot satisfy this gate. 1. define an immutable migration contract containing the old and new normalization/hash-tag versions, affected scope, maintenance CLI and control-plane build digests, every participating service image digest, and the Lua Script Registry version/digest diff --git a/design/architecture/system-architecture-redis-ops-access.md b/design/architecture/system-architecture-redis-ops-access.md index 102bb59518..b7c15d415a 100644 --- a/design/architecture/system-architecture-redis-ops-access.md +++ b/design/architecture/system-architecture-redis-ops-access.md @@ -10,10 +10,12 @@ The target control-plane and maintenance contract in this document is ahead of t - The live implementation supports the current `{tenantId, gameInstanceId}` queue boundary; `regionId` is present in the proto contract but is currently rejected by the service implementation. - The bounded `coordination-maintenance ...` public surface remains target state, not a description of fully implemented repo-local tooling today. No public recovery scope is currently implemented and proven; recovery phases may be implemented and tested behind the high-level operation without becoming separate public commands. - The owning-service typed maintenance API, role-bound Redis helper surface, aggregated registry, descriptor validators, and ownership-enforcement checks described below are target state and are not implemented; current direct access remains subject to the generic runtime seam and the incident-only fallback. -- Reset-smoke isolation is a separate mechanism decision: the existing [Game Session readiness-only identity contract](./microservices/game-session-service/operations.md#readiness-and-liveness) and [synthetic player-flow canary contract](./system-architecture-logging-monitoring.md#synthetic-player-flow-canaries-target-state-prod-like-contract) do not define an isolated reset-smoke namespace or durable synthetic identity that can safely map to tick staging and ledger rows. Automation's separate [`isDryRun=true` namespace](./system-architecture-scripting-contracts.md#6-dry-run--test-traffic-safety) is explicitly non-committing and cannot reach tick queues, so it is not a reset-smoke identity. Until a reset-smoke mechanism decision is accepted and implemented, `RunPostResetSmokeCheck` is non-mutating for real PostgreSQL tick state, real Redis tick metadata/staging/pending, and real tick-ledger rows. It may perform only bounded sampled lease acquire/renew/release probes and, when the workflow affects the shared replay domain, a disposable probe through the target tagged `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, `jti`, and `deny:jti` keys: one canonical consume script creates the marker and the same pinned connection obtains one configured `WAITAOF` local/replica durability acknowledgement before the probe returns `DURABLE_REPLAY_CONSUME_ACK`. The current writer's untagged replay marker remains migration-only drift and is not target proof. The probe must fail closed on timeout, malformed, below-threshold, or uncertain results and must not enter real staging or ledger paths. +- Reset-smoke isolation is a separate mechanism decision: the existing [Game Session readiness-only identity contract](./microservices/game-session-service/operations.md#readiness-and-liveness) and [synthetic player-flow canary contract](./system-architecture-logging-monitoring.md#synthetic-player-flow-canaries-target-state-prod-like-contract) do not define an isolated reset-smoke namespace or durable synthetic identity that can safely map to tick staging and ledger rows. Automation's separate [`isDryRun=true` namespace](./system-architecture-scripting-contracts.md#6-dry-run--test-traffic-safety) is explicitly non-committing and cannot reach tick queues, so it is not a reset-smoke identity. Until a reset-smoke mechanism decision is accepted and implemented, `RunPostResetSmokeCheck` is non-mutating for real PostgreSQL tick state, real Redis tick metadata/staging/pending, and real tick-ledger rows. It may perform bounded sampled lease acquire/renew/release probes and, when the workflow affects the shared replay domain, require Gateway's typed recovery probe over the existing authenticated owning-service transport boundary only; that boundary provides authenticated transport, but no recovery endpoint is implemented while shared readiness remains `QUARANTINED`. Existing ACL-denial probes may also run through the documented isolated disposable/protected harness: key-scoped denials use a protected probe namespace that cannot contain shared deployment data, while `FLUSHALL`, `FLUSHDB`, and `SCRIPT FLUSH` denials run only against an isolated disposable target with required cleanup/readback and never real tick state. Normal player consume remains `OPEN`-only and is not invoked for this recovery proof. The probe's durability acknowledgement and fenced evidence must satisfy [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md), [Gateway replay readiness](./system-architecture-gateway.md#tenant-aware-edge-connect-token-gameplay-handshake), and the [reset policy matrix](./system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary); timeout, malformed, below-threshold, or uncertain results fail closed, and successful probe evidence does not bypass any other recovery gate or authorize reopening by itself. This probe remains target-only and unimplemented, so the checklist is not yet executable for this gate. The current writer's untagged replay marker remains migration-only drift and is not target proof, and reset-smoke must not enter real staging or ledger paths. Use this doc as the canonical target-state contract for later reset/replay tooling, but do not assume every operation below is already available in the running codebase. Current operators, runbooks, Helm hooks, Jobs, and dashboards must not invoke the `coordination-maintenance` commands described below until that surface is implemented and end-to-end proven. +Current Gateway wiring is a frozen wrong-role exception: `GameplayHandshakeFilter` receives the generic reactive Redis template from the `spring.data.redis` binding, whose current profile uses `FIREMUD_REDIS_CACHE_HOST`, while writing only the untagged replay marker `gateway:connect-token:jti:*`. It has no current browser-deny, readiness, or replay-fence writer; those are target-only state. The replay prefix remains Coordination-owned in the target and must not be admitted as Cache state. A Cache reset inventory/readback that finds that prefix, or the generic Gateway writer, must abort without deletion. Target Gateway replay uses the named Coordination ACL and exact co-slotted keys `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`; migration requires quarantine, exact old replay-prefix inventory/readback, named Coordination client/ACL cutover, target-key readback, and same-connection `WAITAOF` proof before the current writer is drained and Cache reset admission can be considered safe. Quarantine release and Cache-reset admission remain fail-closed until the [Gateway replay-quarantine release gate](./system-architecture-gateway.md#tenant-aware-edge-connect-token-gameplay-handshake) is proven; the current untagged replay state and generic writer do not satisfy it. If old-version writers/admission cannot be excluded, release additionally requires a separately proven cross-version guard, which is not currently implemented or proven. + ## Default Operator Surface - Use the **read-only ops user** for inspection. Coordination writes are never an ordinary operator action: when supported maintenance exists, operators invoke the owning service's authenticated typed maintenance API, while the service runtime performs the Redis mutation. Operators and generic tools never receive application credentials for this purpose. @@ -25,7 +27,7 @@ Defining additional Redis users, ACL variations, or ad-hoc tools is considered * ## Coordination Redis Access Rules - Coordination Redis is treated as an **application-only write surface during normal operation**: - - Current normal-operation access uses the generic `common-data-runtime` `firemud.redis.*` properties and its auto-configured `RedisConnectionFactory`, `RedisTemplate`, and `StringRedisTemplate`; deployment configuration routes a service to the appropriate role-specific endpoint. The ADR 0176 owner-local descriptor/key-builder foundation, shared contract validation, and aggregated registry are target state and are not implemented. Target state requires all mutations to coordination prefixes (`tick:*`, `retry:*`, `timer:*`, `remote:*`, `session:*`, `tick-executor-lease:*`, and related keys) to use the owning service's registered typed key and mutation helpers, with the shared foundation validating descriptors and aggregation; it does not centralize owner-exclusive execution. Lua is mandatory for atomic multi-key behavior and may be used for an explicitly documented single-key atomic guard or compare-and-set contract. Ordinary single-key mutations use owner-local typed helpers without Lua, and executable helpers or Lua are shared only for mutations genuinely executed by multiple independently deployed callers. The audited incident-only break-glass path below is the explicit exception to this normal-operation rule and must follow its evidence, fencing, reset, and verification gates. + - Current normal-operation access uses the generic `common-data-runtime` `firemud.redis.*` properties and its auto-configured `RedisConnectionFactory`, `RedisTemplate`, and `StringRedisTemplate`; deployment configuration routes that generic client only to its configured endpoint. The shared hosted profile points that endpoint at `redis-cache`, and the role-specific environment variables are not consumed by this generic factory, so current Coordination callers cannot claim role-isolated routing. The ADR 0176 owner-local descriptor/key-builder foundation, shared contract validation, and aggregated registry are target state and are not implemented. Target state requires all mutations to coordination prefixes (`tick:*`, `retry:*`, `timer:*`, `remote:*`, `session:*`, `tick-executor-lease:*`, and related keys) to use the owning service's registered typed key and mutation helpers, with the shared foundation validating descriptors and aggregation; it does not centralize owner-exclusive execution. Lua is mandatory for atomic multi-key behavior and may be used for an explicitly documented single-key atomic guard or compare-and-set contract. Ordinary single-key mutations use owner-local typed helpers without Lua, and executable helpers or Lua are shared only for mutations genuinely executed by multiple independently deployed callers. The audited incident-only break-glass path below is the explicit exception to this normal-operation rule and must follow its evidence, fencing, reset, and verification gates. - In target state, application services (Game Session, Automation & Scripting, and any future tick participants) never bypass those helpers with raw Redis commands; current direct usages require reconciliation against the owner-local contract rather than being treated as proof that the target helpers exist. - Human operators and ad-hoc tools: - May use `redis-cli`, RedisInsight, or similar tools with **read-only ops users** to inspect coordination state. @@ -67,27 +69,31 @@ To keep ACL usage consistent across services and documentation, Redis deployment | ACL User (example) | Intended Role | Typical Consumers | | --- | --- | --- | -| `coord_app` (logical profile; distinct principals) | Coordination application clients – may write and run Lua scripts against **Coordination Redis** only through their owner-local helper and within disjoint owner/contract key patterns | `account_coord_app` (Account-owned `session:auth:account:*`, `session:auth:tenant:*`, `session:auth:token:*`, `session:auth:generation:*`, legacy unversioned `session:connect-token:tenant:*`, and target `session:connect-token:v1:tenant:*`), `gateway_coord_app` (Gateway `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness` only), `gamesession_coord_app` (Game Session `tick:*`, `timer:*`, `retry:*`, `session:game:*`, and the producer side of `tick-events:*`; stream publication uses `XADD` with bounded `MAXLEN`; any `tick-executor-lease:*` access is confined to the owner-local lease helper and its registered lease script, never to a workload-facing raw Redis path), and `automation_coord_app` (Automation-owned target coordination families such as `automation:timer:*` and `script-scheduler:*`; if a target scheduler consumes Redis Streams directly, its owner registration must bind the exact consumer-scoped `tick-events-offset:{tenantRegionTag}:` key, stream/consumer identity, caller principal, and registered script digest to one atomic compare-and-set helper. ACL/key patterns scope which keys and commands a principal may access but do not enforce compare-and-set semantics or restrict a script digest. Offset advancement must therefore go through one typed owner-local API/helper backed by that registered atomic CAS script, binding the exact consumer/key, expected current offset, monotonic next offset, script digest/version, and readback; no generic `SET` or direct Redis write call path is allowed. If direct Redis consumer access remains, its workload-facing principal is read-only (`GET`) for offset keys; the distinct owner-local executor path/principal is narrowly key-scoped and invoked only through the typed API. Its `tick-events:{tenantRegionTag}` stream pattern permits only `XREAD`/`XRANGE`, and its `tick-events-lease:{tenantRegionTag}` pattern permits only the owner-registered lease renewal/release script). Event-stream consumer identities, exact keys, and executable registrations must be complete before granting these latter permissions; absent that registration Automation uses the owner API/heartbeat contract and receives no direct stream or offset grant. Maintenance tooling is API-only and has no `coord_maintenance_app` principal. | +| `coord_app` (logical profile; distinct principals) | Coordination application clients – may write and run Lua scripts against **Coordination Redis** only through their owner-local helper and within disjoint owner/contract key patterns | `account_coord_app` (Account-owned `session:auth:account:*`, `session:auth:tenant:*`, `session:auth:token:*`, `session:auth:generation:*`, legacy unversioned `session:connect-token:tenant:*`, and target `session:connect-token:v1:tenant:*`), `gateway_coord_app` (Gateway `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:probe:*` only), `gamesession_coord_app` (Game Session `tick:*`, `timer:*`, `retry:*`, `session:game:*`, and the producer side of `tick-events:*`; stream publication uses `XADD` with bounded `MAXLEN` as a best-effort coordination hint, not durable stream or work authority (see [Tick Events & Heartbeat Stream](./system-architecture-ticks.md#tick-events--heartbeat-stream)); any `tick-executor-lease:*` access is confined to the owner-local lease helper and its registered lease script, never to a workload-facing raw Redis path), and `automation_coord_app` (Automation-owned target coordination families such as `automation:timer:*` and `script-scheduler:*`; if a target scheduler consumes Redis Streams directly, its owner registration must bind the exact consumer-scoped `tick-events-offset:{tenantRegionTag}:` key, stream/consumer identity, caller principal, and registered script digest to one atomic compare-and-set helper. ACL/key patterns scope which keys and commands a principal may access but do not enforce compare-and-set semantics or restrict a script digest. Offset advancement must therefore go through one typed owner-local API/helper backed by that registered atomic CAS script, binding the exact consumer/key, expected current offset, monotonic next offset, script digest/version, and readback; no generic `SET` or direct Redis write call path is allowed. If direct Redis consumer access remains, its workload-facing principal is read-only (`GET`) for offset keys; the distinct owner-local executor path/principal is narrowly key-scoped and invoked only through the typed API. Its `tick-events:{tenantRegionTag}` stream pattern permits only `XREAD`/`XRANGE`, and its `tick-events-lease:{tenantRegionTag}` pattern permits only the owner-registered lease renewal/release script). Event-stream consumer identities, exact keys, and executable registrations must be complete before granting these latter permissions; absent that registration Automation uses the owner API/heartbeat contract and receives no direct stream or offset grant. Maintenance tooling is API-only and has no `coord_maintenance_app` principal. | +| `entity_coord_app` | Entity Management's target Coordination Redis principal for its registered ConflictTracker entity producer; may write/run Lua only against `~conflict:entity:*` | Entity Management ConflictTracker producer scope; no `conflict:session:*` or other owner-family access | +| `gamesession_coord_app` | Game Session's target Coordination Redis principal for its registered tick/session families and ConflictTracker session producer; its ConflictTracker grant is exactly `~conflict:session:*` | Game Session tick/session owner paths plus Game Session ConflictTracker producer scope; no `conflict:entity:*` access | + | `coord_ops_ro` | Read-only coordination ops user – may inspect known coordination keys and container members but cannot enumerate the database, write, or run Lua | Human operators using `redis-cli`/RedisInsight, monitoring/exporter agents for Coordination Redis | -| `cache_app` (logical profile; distinct principals) | Cache/Rate-Limit application clients – may read/write **only** cache/rate-limit prefixes on **Cache/Rate-Limit Redis** within each service's disjoint key-pattern allowlist | `gateway_cache_app` (Gateway rate-limit/cache families), `gamesession_cache_app` (Game Session `view:room-look:*` only), `entity_cache_app`, `world_cache_app`, `social_cache_app`, and `automation_cache_app` (Automation `automation:queue:{tenantInstanceTag}:*` / `automation:quota:*` / `automation:tenant-budget:*` / `automation:test:capacity:*` / `automation:test:quota:*` / `automation:readiness:capacity:*`) | +| `cache_app` (logical profile; distinct principals) | Cache/Rate-Limit application clients – may read/write **only** cache/rate-limit prefixes on **Cache/Rate-Limit Redis** within each service's disjoint key-pattern allowlist | `gateway_cache_app` (Gateway rate-limit/cache families), `gamesession_cache_app` (Game Session `view:room-look:*` only; current `lookcache:*`, `screenbuffer:*`, `ipconn:
`, `sessionip:`, and `ratelimit:` writers require explicit inventory, binding, and drain/isolation evidence), `entity_cache_app`, `world_cache_app`, `social_cache_app`, and `automation_cache_app` (Automation `automation:queue:{tenantInstanceTag}:*` / `automation:quota:*` / `automation:tenant-budget:*` / `automation:test:capacity:*` / `automation:test:quota:*` / `automation:readiness:capacity:*`) | +| `automation_queue_rebuild_maint` | Target-only Cache/Rate-Limit maintenance principal – may write only registered `automation:queue:*` prefixes/scopes during an active external Cache maintenance operation, when bound to the same `operationId`, fence/generation, deployment generation, and exact scope; it cannot write other Cache/Rate-Limit or Coordination prefixes | External Cache reset/rebuild controller for the Automation owner; not a general cache or operator user | | `cache_ops_ro` | Read-only cache ops user – may inspect cache/rate-limit keys but never write to them | Human operators inspecting Cache/Rate-Limit Redis, cache-focused monitoring/exporters | +The ConflictTracker target grants above do not describe the current wiring: `RedisConflictTracker` is currently constructed with the generic `StringRedisTemplate`, and Entity Management and Game Session use separate `INCR`/`EXPIRE` calls with warning-only expiry failure. That generic client and mutation sequence are implementation drift; migration must introduce the named Coordination clients and the distinct principals before the target grants can be treated as deployed. + Per-service READMEs are expected to state which ACL user(s) each service uses and which Redis role(s) it connects to so configuration drift is easy to detect during reviews. CI and configuration checks should ensure that: - Services that only participate in coordination (for example Automation's tick-adjacent target path) never use cache ACL users. Game Session is the explicit target dual-role exception: its `gamesession_coord_app` principal and Coordination Redis client are separate from its `gamesession_cache_app` principal and Cache/Rate-Limit Redis client, and neither may be broadened to the other role's prefixes. -- Services that only use Cache/Rate-Limit Redis (for example Entity Management or World Management) never use coordination ACL users. Spring Cloud Gateway is another target dual-role exception: its `gateway_coord_app` replay/deny/readiness client uses a distinct principal, credential, and Coordination Redis deployment from its `gateway_cache_app` rate-limit/cache client; neither client may be broadened to the other role's prefixes. -- The logical `coord_app` profile is instantiated as distinct `account_coord_app`, `gateway_coord_app`, `gamesession_coord_app`, and `automation_coord_app` principals with disjoint key-pattern allowlists. No service may use a shared principal that can read/write another service's owner families; maintenance tooling has no Coordination Redis ACL principal and must use the owning service API. No ACL user may read/write both coordination and cache prefixes on the same deployment. +- Services that have no coordination participation never use coordination ACL users. Entity Management's dedicated `entity_coord_app` is the narrow exception for its registered ConflictTracker producer, with only `~conflict:entity:*`; its Cache/Rate-Limit client remains separate. Spring Cloud Gateway is another target dual-role exception: its `gateway_coord_app` replay/deny/readiness client uses a distinct principal, credential, and Coordination Redis deployment from its `gateway_cache_app` rate-limit/cache client; neither client may be broadened to the other role's prefixes. +- The logical `coord_app` profile is instantiated as distinct `account_coord_app`, `gateway_coord_app`, `entity_coord_app`, `gamesession_coord_app`, and `automation_coord_app` principals with disjoint key-pattern allowlists. The ConflictTracker grants are exact: `entity_coord_app` may access only `~conflict:entity:*`, while the Game Session grant is only `~conflict:session:*` for that diagnostic family (alongside Game Session's separately registered tick/session families); neither principal may access the other's conflict scope. No service or maintenance tool may use a shared principal that can read/write another service's owner families, and no ACL user may read/write both coordination and cache prefixes on the same deployment. +- `automation_queue_rebuild_maint` is admitted only for the externally fenced Automation queue reset/rebuild path; future non-Automation rebuilds require separate named owner principals and prefix contracts rather than reusing it. Game Session's target dual-role wiring is explicit: `gamesession_coord_app` uses `RedisCoordConfig` and a dedicated Coordination Redis connection for tick/session coordination families, while `gamesession_cache_app` uses `RedisCacheConfig` and a separate Cache/Rate-Limit Redis connection for `view:room-look:*` only. The clients, credentials, pools, and endpoint configuration are distinct. The current generic `firemud.redis.*` binding and shared Spring Redis template remain implementation drift and are not proof that role separation or the target ACLs are implemented. ## Configuration and Redis Role Selection -All tools and services refer to Redis deployments via **role-specific configuration**, not hard-coded URLs: +**Target role-specific configuration:** Coordination clients and ops tools read connection settings from `FIREMUD_REDIS_COORD_HOST` / `FIREMUD_REDIS_COORD_PORT` (or an equivalent `FIREMUD_REDIS_COORD_URL`), which identify the **Coordination Redis** deployment. Cache/rate-limit clients and tools read from `FIREMUD_REDIS_CACHE_HOST` / `FIREMUD_REDIS_CACHE_PORT` (or `FIREMUD_REDIS_CACHE_URL`), which identify the **Cache/Rate-Limit Redis** deployment. These describe the planned role-bound configuration, not current routing through typed role-specific clients. -- Coordination clients and ops tools read connection settings from `FIREMUD_REDIS_COORD_HOST` / `FIREMUD_REDIS_COORD_PORT` (or an equivalent `FIREMUD_REDIS_COORD_URL`), which identify the **Coordination Redis** deployment. -- Cache/rate-limit clients and tools read from `FIREMUD_REDIS_CACHE_HOST` / `FIREMUD_REDIS_CACHE_PORT` (or `FIREMUD_REDIS_CACHE_URL`), which identify the **Cache/Rate-Limit Redis** deployment. - -The current implemented Redis connection seam is the generic `firemud.redis.*` `RedisProperties` binding and `common-data-runtime` auto-configuration, which provides the injected Spring Redis connection factory/templates used by services. Deployment configuration supplies the role-specific endpoint routing through `FIREMUD_REDIS_COORD_*` and `FIREMUD_REDIS_CACHE_*`; this is not a current role-bound maintenance client or typed contract surface. The ADR 0176 shared foundation, owner-local descriptor contributions, and repository aggregation remain unimplemented. The following role-specific config types and factory methods are planned target-state examples only: they are not currently exposed by the repository and must not be presented as an available API. Target state may add a small shared configuration module in the existing split common modules or a dedicated tooling/contract module (for example, a future `common-redis-contracts` module, not an implemented module) exposing **role-specific typed configs and helpers** such as: +The current common Redis connection seam is `common-data-runtime`'s `DatabaseAutoConfiguration`: it reads the generic `firemud.redis.*` `RedisProperties` binding and creates its connection factory and templates from those properties only. It does not consume `FIREMUD_REDIS_COORD_*` or `FIREMUD_REDIS_CACHE_*` to select a Redis role or construct a role-bound client. The shared hosted profile routes the current generic endpoint to `redis-cache`; Gateway's `spring.data.redis` configuration is the separately documented Cache-bound exception. This is current generic endpoint wiring, not role-specific routing. The ADR 0176 shared foundation, owner-local descriptor contributions, and repository aggregation remain unimplemented. The following role-specific config types and factory methods are planned target-state examples only: they are not currently exposed by the repository and must not be presented as an available API. Target state may add a small shared configuration module in the existing split common modules or a dedicated tooling/contract module (for example, a future `common-redis-contracts` module, not an implemented module) exposing **role-specific typed configs and helpers** such as: - `RedisCoordConfig` + `createCoordinationRedisClient(...)` - `RedisCacheConfig` + `createCacheRedisClient(...)` @@ -124,7 +130,7 @@ The target operator model interacts with coordination state through **supported To keep reset/replay behavior implementation-safe, the target maintenance/tooling surface is not left to per-runbook invention. Its initial public contract is deliberately small, whether eventually delivered as a CLI, an admin API, or both; it is not currently available for operator invocation: -This recovery contract is role-bound to Coordination Redis and to the exact scope advertised and proved by that runtime. It never targets Cache/Rate-Limit Redis. Cache or rate-limit clearing uses separate owner-supported tooling bound to the Cache/Rate-Limit deployment and an exact registered prefix inventory; it cannot accept coordination region, tenant, or cluster scope or invoke gameplay epoch, session, Account-projection, or replay recovery. Any future mutating cache reset must independently prove its actor/workload authorization, deployment and prefix scope, immutable evidence, cache-maintenance exclusion lock, and apply/readback postconditions before it is advertised. +This recovery contract is role-bound to Coordination Redis and to the exact scope advertised and proved by that runtime. It never targets Cache/Rate-Limit Redis. Cache or rate-limit clearing uses separate owner-supported tooling bound to the Cache/Rate-Limit deployment and an exact registered prefix inventory; it cannot accept coordination region, tenant, or cluster scope or invoke gameplay epoch, session, Account-projection, or replay recovery. An external durable operation/fence may authorize and serialize maintenance, but it does not grant Cache key-deletion authority: a mutating reset must separately authorize its actor/workload for the exact registered prefix inventory and bind that authorization to the same durable operation/fence and deployment generation, then prove deletion apply/readback. No shipped principal currently authorizes the complete Cache inventory, so this operation remains unavailable and fail-closed until that authorization and apply/readback proof exist. Any future mutating cache reset must also prove immutable evidence and the cache-maintenance exclusion lock before it is advertised. - `status(scope, operationId)` reports the canonical state, affected inventory, and recovery progress. - `recover(scope, sessionPolicy, mode)` starts the one public recovery/reset operation. Its protected issuance response returns the durable `operationId` and plaintext `maintenanceLockToken` only to the authenticated actor or workload principal authorized for and durably bound to that operation. That principal must retain the one-time plaintext token in protected custody, such as a permissioned token file, protected workload secret, or secret manager, because the controller stores only its digest and cannot reconstruct it after restart. Its canonical CLI mapping is `coordination-maintenance recover --mode --scope ...`: `mode` is `replay-first`, `reset`, or `session-schema-cleanup`; exactly one of `--preserve-sessions` or `--invalidate-sessions` is required where the mode supports session policy, and the choice is never inferred from scope. `scope` maps to `--scope` plus its scope arguments. Maintenance compatibility is derived from the selected mode and any durable migration, topology-change, restore, or exceptional-backup contract already bound to the operation; it is not a caller-selectable public flag. `--mode replay-first` maps to internal classification `replay_first` and persists `compatibilityClass=replay-first`; `--mode reset` maps to internal classification `reset_first` and persists `compatibilityClass=reset-first`; `--mode session-schema-cleanup` maps to internal and serialized `cleanup` (`compatibilityClass=cleanup`). Its internal pause-and-lock phase fences new work and acquires the maintenance lock; after the post-reset smoke check it remains fenced in `ready_to_reopen` until public continuation. @@ -246,8 +252,8 @@ The public CLI surface listed above is target state only; it is not currently im - consumes the advertised supported scope selected by the recovery workflow and its maintenance lock token. - accepts either `--old-region-epoch ` for `--scope region` or `--old-region-epoch-map ` for tenant/cluster scopes. - owns `replay-first` convergence as well as old-epoch reset convergence: - - without an epoch bump, it drives in-epoch `SCHEDULED` ledger rows toward `APPLIED` or `ABANDONED` for the selected current-epoch scope only where the evidence policy permits; inconclusive rows remain non-terminal and reconciliation-required under their original root `EffectId`. - - after an epoch bump, it publishes `APPLIED`/`ABANDONED` reset outcomes for old-epoch rows only with the owner-fenced per-effect evidence/attestation required by the [Inconclusive Old-Epoch Reconciliation Policy](./system-architecture-tick-failures-and-operations.md#inconclusive-old-epoch-reconciliation-policy); inconclusive old-epoch work remains non-terminal and reconciliation-required under its original root `EffectId`. + - without an epoch bump, it drives in-epoch `SCHEDULED` ledger rows toward `APPLIED` or `ABANDONED` for the selected current-epoch scope only where the evidence policy permits; inconclusive rows remain non-terminal and reconciliation-required under their original persisted mutation `EffectId`, with enclosing `rootEffectId` retained as lineage and reconciliation context. + - after an epoch bump, it publishes `APPLIED`/`ABANDONED` reset outcomes for old-epoch rows only with the owner-fenced per-effect evidence/attestation required by the [Inconclusive Old-Epoch Reconciliation Policy](./system-architecture-tick-failures-and-operations.md#inconclusive-old-epoch-reconciliation-policy); inconclusive old-epoch work remains non-terminal and reconciliation-required under its original persisted mutation `EffectId`, with enclosing `rootEffectId` retained as lineage and reconciliation context. - may support `--discover-old-epochs` as an implementation convenience, but only if it resolves epochs from PostgreSQL and emits the discovered map in its audit output. - Internal command-convergence phase - consumes the same maintenance lock token as the prior internal phase. @@ -266,7 +272,7 @@ The public CLI surface listed above is target state only; it is not currently im - Internal session-rebind phase - accepts either `--region-epoch ` for `--scope region` or `--region-epoch-map ` for tenant/cluster scopes. - The Account-validated opaque `rebindHandle` must bind and match the binding's exact one-tenant `membershipVersion` map `{tenantId: version}`, independently from `authorityTuple.membershipAuthorityGeneration`, and the complete stream-key-ordered `outboxCheckpoints` set. Missing, extra, scalar, differently keyed, stale, regressed, contradictory, or aggregate-only membership or checkpoint evidence, or a mismatch in either independent predicate, fails closed; rebind never merges handle and binding values, reconstructs one carrier from the other, or drops checkpoint entries. - - is permitted when a region- or tenant-scoped reset's explicitly recorded session policy is `--preserve-sessions`; those scopes must record either `--preserve-sessions` or `--invalidate-sessions` rather than relying on scope inference. Cluster requests accept only explicit `--invalidate-sessions` and never enter this phase. For an eligible scope, the phase reads only the immutable `GameplayBindingInventory` snapshot identified by the operation's exact `inventorySnapshotRevision` and validates the complete recovery evidence carrier: parent operation fence, distinct `parentCoverageFence`, applicable linked child IDs/lifecycles/fences or explicit `NOT_APPLICABLE` markers, and later `coverageGeneration`. It recreates region-authoritative bindings through the durable inventory and session-to-region bridge, persists and validates that carrier on the rebind transition and readback, and must refresh the same maintenance lock rather than acquiring another lock. Affected tenant-owned `session:game:index:*` projections may be dropped under either policy and must reconcile and read back before release; the one global account index is exempt from tenant-local selector handling because its members are tenant-qualified, and it requires complete account-wide inventory and coverage before replacement. Untagged global issuer indexes are not narrow rebind or cleanup targets and require their complete owner-defined global inventory and coverage proof before replacement. Ordinary gameplay mutation intake remains blocked until this phase and that reconciliation succeed. Only an actually attempted valid-identity command with an established command record may be terminalized as `REGION_REBIND_REQUIRED` without gameplay mutation. + - is permitted when a region- or tenant-scoped reset's explicitly recorded session policy is `--preserve-sessions`; those scopes must record either `--preserve-sessions` or `--invalidate-sessions` rather than relying on scope inference. Cluster requests accept only explicit `--invalidate-sessions` and never enter this phase. For an eligible scope, the phase reads only the immutable `GameplayBindingInventory` snapshot identified by the operation's exact `inventorySnapshotRevision` and validates the complete recovery evidence carrier: parent operation fence, distinct `parentCoverageFence`, applicable linked child IDs/lifecycles/fences or explicit `NOT_APPLICABLE` markers, and later `coverageGeneration`. It recreates region-authoritative bindings through the durable inventory and session-to-region bridge, persists and validates that carrier on the rebind transition and readback, and must refresh the same maintenance lock rather than acquiring another lock. At tenant scope, affected tenant-owned `session:game:index:*` families may be dropped as whole families; at region scope, only exact affected keys or members are updated, removed, or recreated from durable inventory according to the owning index schema, preserving unrelated keys, members, regions, and tenants. All affected projections must reconcile and read back before release; the one global account index is exempt from tenant-local selector handling because its members are tenant-qualified, and it requires complete account-wide inventory and coverage before replacement. Untagged global issuer indexes are not narrow rebind or cleanup targets and require their complete owner-defined global inventory and coverage proof before replacement. Ordinary gameplay mutation intake remains blocked until this phase and that reconciliation succeed. Only an actually attempted valid-identity command with an established command record may be terminalized as `REGION_REBIND_REQUIRED` without gameplay mutation. - Before recreating a binding, it validates the complete [canonical preserved-session rebind predicate](./system-architecture-redis.md#session-and-region-binding-contract), including only a supported `schemaVersion=2` payload (missing, `schemaVersion=1`, unsupported, or incomplete versions fail closed), the payload's exact `issuanceFence`, `authorityTuple.membershipAuthorityGeneration`, exact one-tenant `membershipVersion` map, complete `outboxCheckpoints` set, exact equality of `authTokenIssuedAt`/`authTokenExpiresAt`/`tokenGeneration` to the registry `iat`/`exp`/`tokenGeneration`, and every token-registry, identity, authority, expiry, generation, epoch, and lease-fence predicate defined there. The rebind predicate is realm-specific: public production requires current membership and entitlement, and its bounded entitlement fallback is permitted only for the public-production entitlement read; private/playtest requires existing membership and the exact current Account-owned realm-grant identity and `grantVersion`, with no entitlement fallback or grant substitution. Missing, unavailable, stale, contradictory, or mismatched private/playtest grant evidence fails closed. The canonical gameplay-session record and pre-auth transport context are not authority substitutes; pre-auth context is outside the preservation policy. A reachable token-registry or Account-authority result of `AUTH_SESSION_REVOKED` or an invalid-token outcome, including missing, expired, malformed, revoked, or mismatched token authority, is a security failure: the phase marks the preserved session auth-revoked, closes its socket, and ends the current resume episode without emitting `REGION_REBIND_REQUIRED`. Unavailable or ambiguous Account evidence remains fenced under the outage policy and is not a region rebind gap. Only after every Account identity, token, authority, membership, lease, and delegation-JWT predicate has succeeded, with the applicable realm predicate satisfied by either a fresh public-production entitlement read or its qualifying bounded fallback, may a solely non-security region gap leave the session connected but not gameplay-admitted; a gameplay or admission command actually attempted after valid identity and command-record establishment may then receive terminal, non-applied `executionOutcome = REGION_REBIND_REQUIRED`. No command record or identity is synthesized for a missing, invalid, or unauthenticated request, and this command outcome does not close or terminalize the connected session. Any non-security predicate evidence that is missing, stale, ambiguous, mismatched, expired, partial, Redis-derived, or otherwise non-exact blocks rebind and reopen. - A failed non-security preserved-session predicate never implicitly changes the recorded session policy. The operation remains paused and fenced under the same `operationId` and `maintenanceLockToken`; an explicit audited preserve-to-invalidate transition may compare-and-set the policy under that same lock only after persisting and validating the complete recovery evidence carrier, including the parent operation fence, distinct `parentCoverageFence`, applicable linked child IDs/lifecycles/fences or explicit `NOT_APPLICABLE` markers, `inventorySnapshotRevision`, and later `coverageGeneration`. If that same-lock transition is unavailable, complete audited `release-lock` abandonment and start an explicit new `recover` operation with `--invalidate-sessions`. Rebind failure alone is never invalidation proof; the security failure above is the explicit auth-revocation transition. Any public-production entitlement-read-only outage fallback must also satisfy the canonical same-binding predicate; private/playtest never uses that fallback and requires the exact current Account realm-grant identity and `grantVersion`. A disconnected binding must carry its immutable `resumeDeadline`; a still-connected binding with no `resumeDeadline` must carry the trusted `connectedSessionFallbackProof` and immutable `connectedSessionDeadline` defined by the Redis session contract. The applicable bound is `min(continuityBindingExpiresAt, resumeDeadline)` or `min(continuityBindingExpiresAt, connectedSessionDeadline)`, respectively, followed by the `fallbackAt + 5 minutes` and `fallbackAt + session_expiration_ms` caps; ops tooling must not widen any bound. - Internal session-schema-cleanup phase @@ -455,7 +461,7 @@ The complete checklist and the applicable recovery release gates are mandatory f | Ledger convergence | No real tick-ledger row is created, advanced, or terminalized by smoke. The smoke check verifies that the real ledger is unchanged; `APPLIED`, `ABANDONED`, or other terminal outcomes from a synthetic durable row are not available until the separate isolation mechanism is decided. | | Cleanup | Any temporary probe lease or lock is released, no smoke-created `pending` state remains, and the sampled region is not considered in-flight. No durable batch or ledger cleanup is used as a substitute for isolation. | | Durable advancement | PostgreSQL `lastCommittedTickId`, the real tick ledger, and the real Redis tick metadata remain at their pre-smoke recovery values; real `tickId=0` is neither consumed nor authorized. | -| Replay-domain readiness | When the workflow affects the shared replay domain, `replayAdmissionFence` is advanced, the lifetime-plus-skew quarantine is observed, and a disposable probe uses the target tagged `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, `jti`, and `deny:jti` keys through the canonical consume script on one pinned Redis connection. The script creates the marker and that same connection obtains one configured `WAITAOF` local/replica durability acknowledgement; only then may the probe yield `DURABLE_REPLAY_CONSUME_ACK` before the operation may reach `AWAITING_RESUME`. This post-reset replay revalidation and durable consume proof are separate from `post_reset_replacement_verification/v1` and Account projection evidence. Select and report implementation checks and runtime proof for this evidence under the shared [Validation and Runtime Proof workflow](../developer-workflows/validation-and-runtime-proof.md); this contract does not replace that workflow or claim current proof. The current untagged replay marker is migration-only drift and is not target proof. Timeout, malformed, below-threshold, or uncertain results fail closed. | +| Replay-domain readiness | When the workflow affects the shared replay domain, trusted recovery invokes Gateway's typed readiness-probe operation through the existing authenticated owning-service maintenance API boundary. The probe runs while shared readiness remains `QUARANTINED`, conditionally writes a distinct Gateway-generated disposable probe marker on one pinned connection, and immediately issues configured `WAITAOF` on that connection with no intervening write; guarded cleanup/readback follows the acknowledgement. It returns `DURABLE_REPLAY_CONSUME_ACK` only after the acknowledgement and exact evidence readback; it neither consumes player credentials nor writes shared readiness. Only the recovery coordinator may authorize reopening after the deadline, exact fenced probe evidence, and every other release gate, with Gateway's owner-local helper performing the readiness CAS. Gateway's ownership and proof contract is defined in [Gateway replay readiness](./system-architecture-gateway.md#tenant-aware-edge-connect-token-gameplay-handshake). This is target-only and currently unimplemented, so the checklist is not yet executable for this gate. Its result is distinct from `post_reset_replacement_verification/v1` and Account projection evidence, and does not itself enable normal player admission. | | Scope sampling | For tenant- or cluster-scoped resets, the smoke check samples at least one representative region per affected executor/shard group rather than only one global region. | The high-level recovery workflow must compose these phases without inventing alternate write paths or omitting required steps such as command-record convergence. @@ -464,18 +470,21 @@ The table above is the canonical post-reset verification checklist. Other runboo After recovery release, the first real fenced staging/release step separately verifies that the staging CAS advances exactly `-1 → 0` and `APPLIED → STAGED`; later ticks use the immediate-next terminal transition. -Direct `redis-cli` writes to coordination prefixes are reserved for **break-glass scenarios** and must follow the incident guidelines in `system-architecture-redis.md` (auditing, post-incident reset, and verification). As an additional guardrail: +**Target state only, once the canonical gated coordination-maintenance operation is implemented and proven:** Direct `redis-cli` writes to coordination prefixes are not an operator write path. Target incident break-glass mutations must use the owner-authorized gated wrapper and follow the incident guidelines in `system-architecture-redis.md` (auditing, scoped reset, and verification); operators must not issue raw Redis writes. **Current deployments authorize no raw Coordination-prefix writes and do not yet provide this wrapper; any observed write is unsupported incident evidence and requires preserving the evidence, keeping the affected scope fenced, and escalating.** As an additional guardrail: - When target reset tooling exists, any break-glass write that mutates `tick:*`, `timer:*`, `retry:*`, `remote:*`, `session:*`, `tick-executor-lease:*`, `tick-events:*`, `tick-events-offset:*`, or `tick-events-lease:*` must be followed by a reset/cleanup scope that actually covers the mutated prefix before normal tick processing resumes. Without that tooling, preserve the incident evidence, keep the affected scope fenced, and escalate through [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback) rather than attempting an unsupported follow-up reset: - - For region-scoped families (`tick:*`, `timer:*`, `retry:*`, `tick-executor-lease:*`), run a region- or tenant-scoped coordination reset as appropriate. + - For registered tagged region-scoped families (target `tick:{tenantRegionTag}:*`, excluding the legacy untagged `tick:lock::` family, plus `timer:*`, `retry:*`, and `tick-executor-lease:*`), run a region- or tenant-scoped coordination reset as appropriate. + - For legacy/unscoped families (`tick:lock:*`, `gamesession:tick:*`, `gamesession:notifydisconnect:dedup:*`, `gameplaypresence:*`, `accountrecentpresence:*`), follow the exact family row in the [Redis reset-policy matrix](./system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary): do not treat them as covered by tagged `tick:*` reset handling, and do not perform a narrow reset until that row's writer-drain, complete-scope/reconciliation, and readback gate is proven. Presence remains private-by-failure and disconnect deduplication remains fail-closed; use only an evidenced cluster reset where the matrix permits it. - For instance-scoped `remote:{tenantInstanceTag}:*`, run a tenant-scoped reset so the tooling resolves every affected game instance and removes each instance pattern with an audit trail; do not use a region-only reset or invent a tenant-only pattern. + - For gameplay session prefixes, follow the canonical reset-policy matrix in [Redis Reset & Recovery](./system-architecture-redis-reset-and-recovery.md#session-policy-and-preserved-session-consequences): every region- and tenant-scoped reset must explicitly record either `--preserve-sessions` or `--invalidate-sessions`; `--preserve-sessions` applies only to `session:game:{tenantGameplayTag}::` and is the only policy that may enter preserved-session rebind after current identity, membership, and revocation validation. `--invalidate-sessions` is handled by the reset/cleanup phase for affected session invalidation and cleanup and never enters preserved-session rebind. Affected tenant-owned `session:game:index:*` projections are droppable under either policy and must reconcile and read back before release; narrow region/tenant recovery or break-glass cleanup may repair only affected members of those projections and must preserve unrelated members. Untagged global account and issuer indexes are not narrow cleanup targets and require complete account- or issuer-wide durable inventory, coverage proof, exact readback, and the maintenance-lock release gate before replacement. If break-glass mutates an untagged global account or issuer index, preserve the evidence, keep the affected index and dependent admission fenced, and escalate through the owner-defined [global index-family recovery consequence](./system-architecture-redis-reset-and-recovery.md#global-index-family-recovery-consequence); do not use a narrow reset as local repair. Pre-auth transport context is always invalidated or rebuilt. Every cluster reset must explicitly record `--invalidate-sessions` and rejects `--preserve-sessions`. Account-owned `session:auth:token:` records and the unversioned legacy plus target `session:connect-token:v1:*` issuance-result projections are separate authority/result domains: region- and tenant-scoped resets preserve them, while a cluster reset must close protected admission and complete the Account repair/reset cutover before deleting or recovering them under their owner contracts. A generic region/tenant reset is never a repair for Account token or connect-token issuance state. - For target-only tick-event families (`tick-events:{tenantRegionTag}`, `tick-events-offset:{tenantRegionTag}:{consumerId}`, and `tick-events-lease:{tenantRegionTag}`), direct mutation is prohibited under the current unavailable fallback: preserve evidence, keep the affected consumer/region fenced, and escalate. Once the owner tooling exists, owner reset/readback/fencing must cover the stream, exact consumer offset, and lease before resume; Automation must re-bootstrap from the canonical heartbeat/status and owner registration contract. Manual mutations of Account-owned `session:auth:account:*`, `session:auth:tenant:*`, `session:auth:generation:*`, or `session:auth:token:` are never repaired by a region- or tenant-scoped coordination reset. The operator must invoke Account-owned exact projection repair/readback (and token revocation/rotation tooling where applicable); target `session:auth:token:` repair is conditional on the target issued-token registry cutover being implemented. The target `session:connect-token:v1:*` projection requires Account repair from the exact SQL issuance operation/result and exact Redis readback; it cannot be reconstructed from a JWT or request fields. The unversioned legacy map is not a target repair source. Account may clean it only after quiescing and draining connect-token issuance/retries, preserving the legacy entries and reading them back through the configured TTL/retry horizon, then performing owner-authorized cleanup with exact absence/readback evidence. The cluster-reset/replay-quarantine/forced re-registration or reauthentication path is target-state-only until the Account repair, replay quarantine, and replacement tooling are implemented and proven. Under the current fallback, preserve the evidence, keep affected scopes fenced, and escalate whenever exact repair, token custody, replay continuity, or the affected token set cannot be proven; direct Redis edits are not a substitute for either path. -- Operators must treat such writes as equivalent to “coordination state may be inconsistent” and use the Coordination Reset Model to bring the region/tenant/cluster back to a known-good state, rather than leaving ad-hoc edits in place as a permanent fix. -- When target reset tooling exists, break-glass flows should go through a small wrapper (CLI or Logging & Admin action) that: +- **Current fallback:** after such writes, preserve incident evidence, keep the affected scope fenced, and escalate through [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback). The Coordination Reset Model is target-state only and applies after its canonical gated coordination-maintenance operation is implemented and proven. + +- When target reset tooling exists, break-glass flows must go through the owner-authorized gated wrapper (CLI or Logging & Admin action) that: - Executes the minimal required Redis mutation. - Immediately triggers the appropriate scoped coordination reset. - Emits a structured audit event (for example `coordination_break_glass`) recording: @@ -507,7 +516,7 @@ This ensures that operators use the same abstractions as application code and re - Target state: the coordination maintenance CLI is shipped as part of the normal build/release pipeline under the canonical command name `coordination-maintenance`; environment packaging may wrap that command in a Gradle task, container entrypoint, or `dev-tools/` script. Once implemented and proven, target-state runbooks and Helm hooks may reference the bounded public operation names above. Current runbooks and Helm hooks must not invoke this unavailable command. - Target-state version rule: once the CLI is implemented and proven, operators must use only a version that matches the deployed services and Lua registry: - If the target CLI build version does **not** match the image tag or Git commit used for the running deployment, the target-state operator must not attempt coordination recovery actions; the operator must use the same artifact version or perform a coordinated upgrade. - - In the target state, break-glass or manual `redis-cli` operations are not an acceptable substitute for a mismatched maintenance CLI; they still require a scoped coordination reset afterwards and should be treated as incident-only paths. This does not make the unavailable CLI a current operator path. + - In the target state, manual `redis-cli` operations are not an acceptable substitute for a mismatched or unavailable maintenance CLI. Incident-only break-glass mutation must use the owner-authorized gated wrapper, which performs the scoped coordination reset and required verification; this does not make the unavailable wrapper or CLI a current operator path. Target-state runbooks may call the maintenance CLI entrypoint explicitly, after the implementation and proof gates above are complete, and should avoid embedding raw Redis commands. Current runbooks must not call the unavailable entrypoint. diff --git a/design/architecture/system-architecture-redis-reset-and-recovery.md b/design/architecture/system-architecture-redis-reset-and-recovery.md index f49122c6a9..5d734fa9a3 100644 --- a/design/architecture/system-architecture-redis-reset-and-recovery.md +++ b/design/architecture/system-architecture-redis-reset-and-recovery.md @@ -34,6 +34,7 @@ Coordination Redis is treated as a **long‑lived, measured-exposure coordinatio - **Region‑scoped reset** – affects a single ``: - Clears tick queues, timers, retry structures, and region‑scoped locks/leases for one region. - Does not clear Account-owned issued-token registry records, live legacy account/tenant auth projections, authority-generation projections, or target exact-input `session:connect-token:v1:*` issuance-result projections because these are not region-scoped coordination state. The unversioned legacy `session:connect-token:*` map is preserved/read back only while present through its configured TTL/retry horizon and then owner-cleaned; a missing, changed, or untrusted legacy entry leaves the affected handshake fenced and requires escalation, never reconstruction. A missing or untrusted target `session:connect-token:v1:*` projection remains subject to Account-owned exact durable repair and readback. + - Does not drop a whole tenant-tagged gameplay-index family. Game Session updates, removes, or recreates only exact affected keys or members from the durable binding inventory according to the owning index schema and preserves unrelated keys, members, regions, and tenants. - Leaves other regions and tenants untouched. - Typically used when: - A mis‑keyed script or bug has polluted tick state for one region. @@ -41,8 +42,8 @@ Coordination Redis is treated as a **long‑lived, measured-exposure coordinatio - **Tenant‑scoped reset** – affects a single `tenantId`: - Clears the affected tenant-scoped gameplay coordination prefixes for all regions under one tenant. - - Preserves only `session:game:{tenantGameplayTag}::` records when operators explicitly choose `--preserve-sessions`; affected tenant-owned `session:game:index:*` projections are derived and may be dropped, but must reconcile before release. Untagged global account and issuer indexes are not narrow reset targets; replacement requires their complete owner-defined durable inventory, coverage proof, and exact readback before release. Pre-auth transport context is not covered by session preservation and is invalidated or rebuilt. - - Does not clear Account-owned `session:auth:token:` records, live legacy account/tenant auth projections, authority-generation projections, or target exact-input `session:connect-token:v1:*` issuance-result projections. Region- and tenant-scoped resets preserve these families because they are not region-scoped coordination state. The unversioned legacy `session:connect-token:*` map is only preserved and read back while present through its configured TTL/retry horizon, then owner-cleaned; if it is missing, changed, or untrusted, the affected handshake remains fenced and operators escalate. A missing or untrusted target `session:connect-token:v1:*` projection requires Account exact durable repair and readback before the affected operation can release. A tenant reset may terminate affected gameplay bindings, but it must not turn a tenant-region coordination reset into account-wide token revocation. + - Preserves only `session:game:{tenantGameplayTag}::` records when operators explicitly choose `--preserve-sessions`. At tenant scope, the complete affected tenant-tagged character, account-tenant, tenant, and realm-grant `session:game:index:*` families are derived and may be dropped, but must reconcile before release; a region-scoped reset instead updates or removes only exact affected keys or members from durable inventory. Untagged global account and issuer indexes are not narrow reset targets; any replacement requires their complete owner-defined durable inventory, coverage proof, and exact readback before release. Pre-auth transport context is not covered by session preservation and is invalidated or rebuilt. + - Region- and tenant-scoped resets preserve Account-owned `session:auth:token:` records, live legacy account/tenant auth projections, authority-generation projections, and target exact-input `session:connect-token:v1:*` issuance-result projections because these are not coordination-reset state. The unversioned legacy exact-input `session:connect-token:tenant::account::scope::request:` map is preserve/readback-only while present through its bounded TTL/retry horizon, then owner-cleaned; if it is missing, changed, or untrusted, the affected handshake remains fenced and requires escalation, never reconstruction, reminting, or repair as target authority. A missing or untrusted target `session:connect-token:v1:*` projection requires Account repair and exact readback only from the durable issuance operation/encrypted response envelope before the affected operation can release. A tenant reset may terminate affected gameplay bindings, but it must not turn a tenant-region coordination reset into account-wide token revocation or permit a live connect request to receive a different result on retry. - Often combined with an in‑game maintenance window or a revert/repin of tenant‑specific published content. - Used when: - A full in‑game reset is acceptable for a single tenant. @@ -117,12 +118,12 @@ Worked example (illustrative, non-normative, reset-local): region-scoped reset f > **Illustrative reset-local contract sketch; non-normative and unavailable today.** The `coordination-maintenance` commands below are not current operator instructions. Canonical reset ordering remains owned by [Redis Operations](./system-architecture-redis-operations.md#canonical-coordination-reset-sequence); recovery release/evidence remains owned by [Backup Recovery Evidence and Compliance](./system-architecture-backup-recovery-evidence-and-compliance.md#canonical-recovery-record) and the linked session/recovery evidence contracts. -1. The target-state command records `--preserve-sessions` and applies the reset-local effects for this region: it advances `region_epoch` from `12` to `13`, clears `tick:{tenantRegionTag}:*`, `timer:{tenantRegionTag}`, `retry:{tenantRegionTag}`, and `tick-executor-lease:{tenantRegionTag}`, and runs old-epoch ledger and accepted-but-unbound command reconciliation under the linked evidence policy. `APPLIED` or `ABANDONED` is permitted only when that policy proves the corresponding outcome; inconclusive effects remain reconciliation-required under their original `EffectId` rather than being bulk-terminalized. Preserved sessions remain fenced until the owner-defined session and recovery evidence contracts qualify them. +1. The target-state command records `--preserve-sessions` and applies the reset-local effects for this region: it advances `region_epoch` from `12` to `13`, clears `tick:{tenantRegionTag}:*`, `timer:{tenantRegionTag}`, `retry:{tenantRegionTag}`, and `tick-executor-lease:{tenantRegionTag}`, and runs old-epoch ledger and accepted-but-unbound command reconciliation under the linked evidence policy. `APPLIED` or `ABANDONED` is permitted only when that policy proves the corresponding outcome; inconclusive effects remain reconciliation-required under their original persisted mutation `EffectId`—the root `EffectId` for a root mutation or the generated child's persisted `EffectId` for a child—with the enclosing `rootEffectId` retained separately as lineage and reconciliation context, rather than being bulk-terminalized. Preserved sessions remain fenced until the owner-defined session and recovery evidence contracts qualify them. 2. The first real tick in the new epoch is `tickId=0` only after the owner-defined recovery and release boundary; this example does not prescribe that boundary. Worked example (illustrative, non-normative, reset-local): tenant-scoped reset for `` with `--preserve-sessions` (target-state only; unavailable today) -1. The target-state command records `--preserve-sessions` and applies reset-local effects across the complete affected-region scope: it advances each `region_epoch`, clears affected tenant-scoped gameplay coordination prefixes while retaining only canonical `session:game:{tenantGameplayTag}::` records, drops affected tenant-owned `session:game:index:*` projections for reconciliation, always invalidates or rebuilds pre-auth transport context, removes affected `remote:{tenantInstanceTag}:*` hints from the durable game-instance scope, and runs old-epoch ledger and accepted-but-unbound command reconciliation under the linked evidence policy. `APPLIED` or `ABANDONED` is permitted only when that policy proves the corresponding outcome; inconclusive effects remain reconciliation-required under their original `EffectId` rather than being bulk-terminalized. Preserved sessions remain fenced until the owner-defined session and recovery evidence contracts qualify them and derived indexes reconcile; Account-owned token records and authorities are not tenant-reset state. The tenant reset also excludes untagged Account auth/generation families (`session:auth:token:*`, `session:auth:account:*`, `session:auth:tenant:*`, `session:auth:generation:*`, and `session:connect-token:*` issuance-result projections), the Game Session issuer-generation consumer projection (`session:game:auth:issuer-generation:v1:*`), and the shared Gateway replay domain (`gateway:connect-token:{gateway-connect-token-replay-v1}:*` and its readiness/fence record carrying `replayAdmissionFence`); those remain under their owner-specific validation and reprojection contracts. +1. The target-state command records `--preserve-sessions` and applies reset-local effects across the complete affected-region scope: it advances each `region_epoch`, clears affected tenant-scoped gameplay coordination prefixes while retaining only canonical `session:game:{tenantGameplayTag}::` records, drops only the affected tenant-tagged `session:game:index:character:{tenantGameplayTag}::`, `session:game:index:account-tenant:{tenantGameplayTag}:`, `session:game:index:tenant:{tenantGameplayTag}`, and `session:game:index:realm-grant:{tenantGameplayTag}:` projections for reconciliation, and leaves the untagged global `session:game:index:account:` and `session:game:index:issuer:{issuerIndexLayoutTag}::` families to their owner-specific account-wide or issuer-wide reconciliation. It always invalidates or rebuilds pre-auth transport context, removes affected `remote:{tenantInstanceTag}:*` hints from the durable game-instance scope, and runs old-epoch ledger and accepted-but-unbound command reconciliation under the linked evidence policy. `APPLIED` or `ABANDONED` is permitted only when that policy proves the corresponding outcome; inconclusive effects remain reconciliation-required under their original persisted mutation `EffectId`—the root `EffectId` for a root mutation or the generated child's persisted `EffectId` for a child—with the enclosing `rootEffectId` retained separately as lineage and reconciliation context, rather than being bulk-terminalized. Preserved sessions remain fenced until the owner-defined session and recovery evidence contracts qualify them and derived indexes reconcile; Account-owned token records, exact-input connect-token issuance-result/idempotency records, and authorities are not tenant-reset state. The tenant reset also excludes untagged Account auth/generation families (`session:auth:token:*`, `session:auth:account:*`, `session:auth:tenant:*`, and `session:auth:generation:*`), the exact-input Account connect-token family (`session:connect-token:tenant::account::scope::request:`), the Game Session issuer-generation consumer projection (`session:game:auth:issuer-generation:v1:*`), and the shared Gateway replay domain (`gateway:connect-token:{gateway-connect-token-replay-v1}:*` and its readiness/fence record carrying `replayAdmissionFence`); those remain under their owner-specific validation and reprojection contracts. 2. This example is reset-local only: the canonical sequence, complete evidence, and release boundary are defined by the owner documents linked above. Worked example (illustrative, non-normative, reset-local): cluster-scoped reset (target-state only; unavailable today) @@ -179,14 +180,14 @@ Worked example (illustrative, non-normative, reset-local): cold start for ` **Illustrative reset-local contract sketch; non-normative and unavailable today.** The command below is not a current operator instruction. Current operators must keep the affected scope fenced and use the current fail-closed fallback above instead; the canonical recovery and release owners are not restated here. 1. Coordination Redis starts empty after loss of its data directory, while PostgreSQL still shows `RegionStatus(regionEpoch=13, lastCommittedTickId=41)` for `(7b3b074e-d597-4e9b-b96f-4f5946d26120, 9a2bb6d1-74c7-4f81-a9e8-418e65f6ad78, R7)`. -2. The target-state command records `--preserve-sessions`, advances `region_epoch` from `13` to `14`, establishes PostgreSQL `lastCommittedTickId = -1` separately from the fenced Redis `current_tick_id = -1`, `current_tick_state = APPLIED` baseline, and runs old-epoch durable-work and accepted-but-unbound-command reconciliation under the linked evidence policy. `APPLIED` or `ABANDONED` is permitted only when that policy proves the corresponding outcome; inconclusive effects remain reconciliation-required under their original `EffectId` rather than being bulk-terminalized. Preserved sessions remain fenced until the owner-defined evidence qualifies them. +2. The target-state command records `--preserve-sessions`, advances `region_epoch` from `13` to `14`, establishes PostgreSQL `lastCommittedTickId = -1` separately from the fenced Redis `current_tick_id = -1`, `current_tick_state = APPLIED` baseline, and runs old-epoch durable-work and accepted-but-unbound-command reconciliation under the linked evidence policy. `APPLIED` or `ABANDONED` is permitted only when that policy proves the corresponding outcome; inconclusive effects remain reconciliation-required under their original persisted mutation `EffectId`—the root `EffectId` for a root mutation or the generated child's persisted `EffectId` for a child—with the enclosing `rootEffectId` retained separately as lineage and reconciliation context, rather than being bulk-terminalized. Preserved sessions remain fenced until the owner-defined evidence qualifies them. 3. After the owner-defined recovery boundary, the first fenced staging CAS advances exactly `-1 → 0` and `APPLIED → STAGED`, making the first real committable tick in epoch `14` `tickId=0`; later ticks use the immediate-next terminal transition. This example does not define that boundary. - **Reset** (intentional operational action) - A deliberate, scoped choice to discard volatile coordination state (region/tenant/cluster) and resume from PostgreSQL state plus new activity. - Target state only: apply a scoped reset through supported, implemented, and proven tooling for that exact scope and an explicit session policy. - Until that tooling exists, current handling is the [Current Operator Fallback](#current-operator-fallback): preserve evidence, keep the affected scope fenced, and escalate. - - Must follow the reset model and runbooks; ad‑hoc `redis-cli` edits are treated as “unknown resets” and require a follow‑up scoped reset. + - Must follow the reset model and runbooks; any observed ad‑hoc `redis-cli` edit is unsupported incident evidence (an “unknown reset”), not a current repair path. Preserve the mutation evidence, keep the affected scope fenced, and escalate through the current fallback. Design implications: @@ -206,7 +207,9 @@ This table is the **canonical reset-policy catalog** for the main Redis prefixes Service design docs and per-service READMEs should link to this matrix (or any future expanded key catalog derived from it) instead of duplicating their own reset-policy tables; when a service introduces new prefixes, the catalog is extended here first. -The six gameplay index families below are Game Session-owned derived coordination state, independent of the explicit gameplay-session policy and not authorization state or preserved-session state. A reset may drop affected tenant-owned families under either policy only after the affected scope is paused and fenced. Untagged global account and issuer families are not narrow reset targets; replacement or rebuild requires complete account- or issuer-wide durable inventory, coverage proof, exact readback, and the maintenance-lock release gate. The one untagged global account index is an explicit exception because each member carries a complete tenant-qualified binding reference; it remains a single account-wide projection rather than a tenant-local selector. All affected families remain non-admissible until Game Session completes the owner-defined inventory reconciliation and exact readback; release is not authorized while any affected index family is missing, stale, partial, or ambiguous. The exact index shapes, child/parent carriers, reservation/capacity proof, and admission predicates are owned by [Session and Region-Binding Contract](./system-architecture-redis.md#session-and-region-binding-contract), [Global Account Active-Binding Index](./system-architecture-session-behavior.md#global-account-active-binding-index), and the [canonical active-binding recovery evidence contract](./system-architecture-redis-ops-access.md#canonical-active-binding-recovery-evidence-contract). This reset catalog records only scope, drop behavior, and fencing consequences. +Cache/Rate-Limit reset execution additionally requires the external, generation-bound [Cache deployment maintenance gate](./system-architecture-redis-operations.md#external-cache-deployment-maintenance-gate); this gate is outside the Cache/Rate-Limit Redis deployment and is held through deletion, verification, and rebuild. + +The six gameplay index families below are Game Session-owned derived coordination state, independent of the explicit gameplay-session policy and not authorization state or preserved-session state. At tenant scope, the four tenant-tagged families (`character`, `account-tenant`, `tenant`, and `realm-grant`) may be dropped as whole families after the affected scope is paused and fenced. At region scope, only exact affected keys or members are updated, removed, or recreated from the durable binding inventory according to the owning index schema; unrelated keys, members, regions, and tenants are preserved. The untagged global account and issuer families remain untouched by narrow reset and require owner-specific account-wide or issuer-wide replacement/reconciliation with complete durable inventory, coverage proof, exact readback, and the maintenance-lock release gate. The one untagged global account index is an explicit exception because each member carries a complete tenant-qualified binding reference; it remains a single account-wide projection rather than a tenant-local selector. All affected families remain non-admissible until Game Session completes the owner-defined inventory reconciliation and exact readback; release is not authorized while any affected index family is missing, stale, partial, or ambiguous. The exact index shapes, child/parent carriers, reservation/capacity proof, and admission predicates are owned by [Session and Region-Binding Contract](./system-architecture-redis.md#session-and-region-binding-contract), [Global Account Active-Binding Index](./system-architecture-session-behavior.md#global-account-active-binding-index), and the [canonical active-binding recovery evidence contract](./system-architecture-redis-ops-access.md#canonical-active-binding-recovery-evidence-contract). This reset catalog records only scope, drop behavior, and fencing consequences. Entity cache rows below intentionally distinguish namespace-backed aggregates from explicitly instance-scoped S3 holders. Reset tooling may enumerate the complete affected namespace or instance/room scope and drop both families, but Redis remains only a disposable cache: PostgreSQL or the owning Entity lifecycle contract remains authoritative, and `playableStateScope` is separately validated evidence rather than a cache-key or reset-authority dimension. @@ -216,19 +219,26 @@ A region- or tenant-scoped reset parent cannot claim global account- or issuer-i | Prefix / Family | Role | Reset Policy (Coordination Reset) | Behavior When Dropped | Notes | | --- | --- | --- | --- | --- | -| `tick:{tenantRegionTag}:pending` and `tick:{tenantRegionTag}:queue:*` | Coordination | **Reset-tolerant** | In-flight ticks and queued commands for affected regions are discarded; future ticks process only new commands. | `pending` effects are reconciled through the tick-effect ledger under the [Inconclusive Old-Epoch Reconciliation Policy](./system-architecture-tick-failures-and-operations.md#inconclusive-old-epoch-reconciliation-policy): evidence may permit `APPLIED`/`ABANDONED`, while inconclusive work remains a reconciliation-required non-terminal marker under its original `EffectId`; reset does not bulk-terminalize it. Idempotency prevents double-apply. Only command records with `ackLevel` = `ACCEPTED_VOLATILE` in `RECEIVED`/`ENQUEUED` and no surviving batch/binding are intentionally **lost** and not reconstructed from PostgreSQL; `ACCEPTED_DURABLE` records follow their feature-specific durable replay or post-abandon re-drive contract, while inconclusive batch-bound work remains non-terminal/reconciliation-required. See the [canonical command outcome convergence](./system-architecture-tick-execution-flows.md#command-outcome-convergence-required). | +| `tick:{tenantRegionTag}:pending` and `tick:{tenantRegionTag}:queue:*` | Coordination | **Reset-tolerant** | In-flight ticks and queued commands for affected regions are discarded; future ticks process only new commands. | `pending` effects are reconciled through the tick effect ledger under the [Inconclusive Old-Epoch Reconciliation Policy](./system-architecture-tick-failures-and-operations.md#inconclusive-old-epoch-reconciliation-policy): evidence may permit `APPLIED`/`ABANDONED`, while inconclusive work remains a reconciliation-required non-terminal marker under its original persisted mutation `EffectId`—the root `EffectId` for a root mutation or the generated child's persisted `EffectId` for a child—with the enclosing `rootEffectId` retained separately as lineage and reconciliation context; reset does not bulk-terminalize it. Idempotency prevents double-apply. Only command records with `ackLevel` = `ACCEPTED_VOLATILE` in `RECEIVED`/`ENQUEUED` and no surviving batch/binding are intentionally **lost** and not reconstructed from PostgreSQL; `ACCEPTED_DURABLE` records follow their feature-specific durable replay or post-abandon re-drive contract, while inconclusive batch-bound work remains non-terminal/reconciliation-required. See the [canonical command outcome convergence](./system-architecture-tick-execution-flows.md#command-outcome-convergence-required). | | `tick:{tenantRegionTag}:meta` | Coordination | **Reset-tolerant** | Epoch/tick guard metadata is dropped; reset tooling re-establishes the new epoch baseline from durable RegionStatus state before normal progress. | The Redis metadata is a coordination view only; the reset handshake establishes the same new epoch and first-real-tick baseline in PostgreSQL and Redis. | | `tick:{tenantRegionTag}:session-binding:*` | Coordination | **Reset-tolerant with preserved-session rebind** | Region-local gameplay admission bindings are dropped. Preserved sessions remain fenced until the owner-defined session/recovery evidence contract qualifies them; invalidated sessions require fresh `LOGIN` / `PLAY`. | These keys are region-authoritative for gameplay command admission. The exact rebind, inventory, carrier, reservation, and admission predicates are owned by the [session and region-binding contract](./system-architecture-redis.md#session-and-region-binding-contract) and [active-binding recovery evidence contract](./system-architecture-redis-ops-access.md#canonical-active-binding-recovery-evidence-contract). | | `timer:{tenantRegionTag}` and `retry:{tenantRegionTag}` | Coordination | **Reset-tolerant** | Timers and retries for affected regions are discarded; future ticks process only newly scheduled timers/retries. | Only timers/retries that are also represented durably elsewhere (for example, PostgreSQL-backed automation schedules or durable follow-ups) are re-discovered after a reset; region-scoped timer/retry coordination keys themselves are not treated as reconstructible logs. | | `tick-executor-lease:{tenantRegionTag}` and tick lock keys (`tick:{tenantRegionTag}:lock:*`) | Coordination | **Reset-tolerant** | Existing leases/locks vanish; new executors reacquire leadership and locks as ticks resume. | Leases and locks are transient; executors reacquire leases and lock state after reset. | -| `session:game:index:character:{tenantGameplayTag}::` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | The target `{tenantId, playableStateNamespaceId, characterId}` character-to-session controller uniqueness entry is dropped; takeover, resume, and new admission using that character remain fenced until Game Session rebuilds the exact entry from the durable binding inventory and validates the server-derived `playableStateScope` binding/routing evidence plus value/evidence `{sessionId, gameInstanceId, bindingGeneration}` against the session record. An unbound-character decision requires that durable inventory readback to prove there is no active binding; an empty Redis key alone never proves availability. See [ADR 0132](./decisions/adr-0132-namespace-scoped-single-character-controller.md) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). | Tenant-scoped and namespace-qualified, with the shard-local session CAS; `playableStateScope` remains binding/routing context. Rebuild removes stale entries, recreates missing entries, and rejects conflicting identities. The existing `:` index key is current implementation drift, not the target key. | +| `tick:lock::` | Coordination (current Entity legacy implementation drift; unscoped) | **Reset-sensitive; narrow reset forbidden until writer is removed or complete scope is proven** | The live Entity `TickLockServiceImpl` lock family is not the canonical region lock and has no game-instance/region/fence evidence. A reset must not delete or treat this family as covered by the tagged `tick:{tenantRegionTag}:lock:*` row; the affected scope remains fenced until the writer is drained/quarantined and no independent lock can authorize mutation. | Current Entity code uses a private TTL formula and an untagged tenant/entity key. It is not a second authority: target convergence routes locking through Game Session/shared full-runtime-scope helpers. | +| `conflict:entity::` and `conflict:session::` | Coordination (current shared diagnostic projection; generic-client placement and separate `INCR`/`EXPIRE` warning-only path are implementation drift) | **Reset-tolerant** | Conflict counters are disposable hotspot hints. Dropping them may temporarily hide or reset contention diagnostics but cannot authorize or deny gameplay, admission, or durable work. Reset inventory must include the complete registered family; unknown or misplaced copies on Cache/Rate-Limit Redis remain a role-collision finding. | `common-data-runtime` owns the shared helper; Entity Management and Game Session supply the producer scopes. The target role, finite per-scope cardinality, 300-second inactivity TTL, named Coordination client/`coord_app` ACL, and atomic increment/TTL convergence are defined in [Redis Architecture](./system-architecture-redis.md#coordination-vs-cache-prefixes). PostgreSQL and runtime locks remain authoritative. | +| `gamesession:tick:queue::`, `gamesession:tick:pending::`, `gamesession:tick:lock::`, and `gamesession:tick:mutation-lock::` | **Coordination (current legacy implementation drift; untagged)** | **Reset-sensitive (narrow reset forbidden until complete scope/reconciliation is proven)** | These live keys may contain queued work, pending state, or locks, but their key shape carries only `tenantId` and `gameInstanceId`; it does not prove the complete `` scope. A region- or tenant-scoped reset must not claim coverage or delete them from a wildcard pattern. If they may be in the affected deployment, the scope remains fenced until Game Session supplies complete durable inventory and exact readback; an explicitly cluster-scoped reset may drop them only as part of its evidenced cluster blast radius, with queued/pending work following the legacy-loss and reconciliation consequences above. | `TickQueueControlService` is the current builder owner. This family is not the target tagged `tick:{tenantRegionTag}:*` contract and must not be made narrow by guessing a region from `gameInstanceId`. Game Session must fence/drain the legacy writer, map any retained work through authoritative durable records, and migrate to registered canonical tagged builders before scoped reset tooling treats the target families as exhaustive. | +| `session::` | **Coordination (current legacy implementation drift; untagged)** | **Reset-sensitive** | This current Game Session runtime-state projection is derived from PostgreSQL/current ownership state, which remains authoritative. Missing, stale, partial, or ambiguous Redis state cannot authorize tick progress; Game Session must rebuild it and complete exact readback before resuming affected runtime operations. | `SessionStateService`/Game Session currently writes the projection for game-instance lifecycle state. It is distinct from target `session:game:*` gameplay bindings and from `sessionctx:*`; the current key has no canonical region scope and remains implementation drift. | +| `session:game:index:character:{tenantGameplayTag}::` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | At tenant scope, the target `{tenantId, playableStateNamespaceId, characterId}` character-to-session controller uniqueness entry may be dropped; at region scope, only the exact key for an affected binding is retained, removed, or recreated from durable binding inventory, preserving unrelated character keys, regions, and tenants. Takeover, resume, and new admission remain fenced until Game Session rebuilds or reconciles the exact entry and validates the server-derived `playableStateScope` binding/routing evidence plus value/evidence `{sessionId, gameInstanceId, bindingGeneration}` against the session record. An unbound-character decision requires that durable inventory readback to prove there is no active binding; an empty Redis key alone never proves availability. See [ADR 0132](./decisions/adr-0132-namespace-scoped-single-character-controller.md) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). | Tenant-scoped and namespace-qualified, with the shard-local session CAS; `playableStateScope` remains binding/routing context. Rebuild removes stale entries, recreates missing entries, and rejects conflicting identities. The existing `:` index key is current implementation drift, not the target key. | | `session:game:index:account:` | Coordination | **Reset-sensitive with mandatory account-wide reconciliation** | Account-wide lookup is unavailable while the global index is dropped; narrow parents do not rebuild the untagged key, and account-wide access remains fenced until the complete owner-defined recovery result is consumed. | This is the one retained untagged global account exception: every member is a complete tenant-qualified `accountIndexMember`, so the key is not a tenant-local selector. Its physical layout and member contract are owned by [Global Account Active-Binding Index](./system-architecture-session-behavior.md#global-account-active-binding-index); narrower resets preserve unrelated tenants and cluster reset rebuilds the complete key. | -| `session:game:index:account-tenant:{tenantGameplayTag}:` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | The tenant-qualified account lookup is dropped; tenant-scoped resume, takeover, and bounded revocation remain fenced until Game Session rebuilds it from the durable inventory and the matching session/index obligations are acknowledged. Each index member remains an active `sessionId` value under the owner-defined schema. Reconciliation is inventory-led: it derives the exact expected active `sessionId` set from authoritative durable `GameplayBindingInventory` rows; each row's complete `bindingRef` and tenant/game/session identity supply `gameInstanceId` and directly address its canonical session record. Before deriving or writing a member or accepting readback, it exact-compares the row's canonical binding-owner `accountId` with the key's ``; a missing, malformed, or mismatched owner is rejected or quarantined and keeps the affected account/index scope fenced. It independently validates the exact session record, including controller identity `{tenantId, playableStateNamespaceId, characterId}`, server-derived `playableStateScope`, `gameInstanceId`, `bindingGeneration`, and lifecycle, then reads back the expected `sessionId` set before acknowledging the matching index/session obligations. Reconciliation never infers `gameInstanceId` from a bare member and does not use wildcard scans or invent a separate resolver. This consumes the existing owner-defined schema and producers; it does not change them. | Tenant-scoped and part of the shard-local session CAS. Reconciliation is limited to the gameplay tag and validates the canonical session record rather than treating index membership as authoritative. | -| `session:game:index:tenant:{tenantGameplayTag}` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | Tenant-wide active-session lookup is dropped; tenant revocation, inspection, and repair remain fenced until Game Session rebuilds and reads back the tenant index from durable inventory. | Tenant-scoped and shard-local. Reconciliation must not use the global account index as a substitute or admit a binding from tenant-local key presence alone. | -| `session:game:index:realm-grant:{tenantGameplayTag}:` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | Lifecycle-bound private/playtest grant lookup is dropped; reset tooling enumerates the complete expected tuple set from the exact Account v1 inventory, obtains every key through the shared `grant/v1` lifecycle-qualified realm-grant index builder, and keeps realm admission and grant-driven revocation fenced until Game Session rebuilds and reads back those exact entries under current Account grant authority. | `grantScopeId` is the exact canonical scope ID for the complete Account-owned tuple. Reset and reconciliation never concatenate world/realm selectors or other tuple fields independently. The entries are tenant-scoped, shard-local bounded lookup evidence; Account state remains authoritative, and stale, wrong-lifecycle, or cross-tenant entries are removed. Public-production and unscoped bindings have no entry. | +| `session:game:index:account-tenant:{tenantGameplayTag}:` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | At tenant scope, the tenant-qualified account lookup may be dropped; at region scope, the key remains and only members affected by the selected region are updated or reconciled from durable binding inventory, preserving unrelated regions and tenants. Tenant-scoped resume, takeover, and bounded revocation remain fenced until Game Session rebuilds it and the matching session/index obligations are acknowledged. Each index member remains an active `sessionId` value under the owner-defined schema. Reconciliation is inventory-led: it derives the exact expected active `sessionId` set from authoritative durable `GameplayBindingInventory` rows; each row's complete `bindingRef` and tenant/game/session identity supply `gameInstanceId` and directly address its canonical session record. Before deriving or writing a member or accepting readback, it exact-compares the row's canonical binding-owner `accountId` with the key's ``; a missing, malformed, or mismatched owner is rejected or quarantined and keeps the affected account/index scope fenced. It independently validates the exact session record, including controller identity `{tenantId, playableStateNamespaceId, characterId}`, server-derived `playableStateScope`, `gameInstanceId`, `bindingGeneration`, and lifecycle, then reads back the expected `sessionId` set before acknowledging the matching index/session obligations. Reconciliation never infers `gameInstanceId` from a bare member and does not use wildcard scans or invent a separate resolver. This consumes the existing owner-defined schema and producers; it does not change them. | Tenant-scoped and part of the shard-local session CAS. Reconciliation is limited to the gameplay tag and validates the canonical session record rather than treating index membership as authoritative. | +| `session:game:index:tenant:{tenantGameplayTag}` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | At tenant scope, the tenant-wide active-session lookup may be dropped; at region scope, the key remains and only members affected by the selected region are updated or reconciled from durable binding inventory, preserving unrelated regions and tenants. Tenant revocation, inspection, and repair remain fenced until Game Session rebuilds or reconciles and reads back the tenant index. | Tenant-scoped and shard-local. Reconciliation must not use the global account index as a substitute or admit a binding from tenant-local key presence alone. | +| `session:game:index:realm-grant:{tenantGameplayTag}:` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | At tenant scope, the lifecycle-bound private/playtest grant lookup may be dropped; at region scope, the key remains and only members affected by the selected region are updated or reconciled from durable binding inventory, preserving unrelated regions and tenants. Reset tooling enumerates the complete expected tuple set from the exact Account v1 inventory, obtains every key through the shared `grant/v1` lifecycle-qualified realm-grant index builder, and keeps realm admission and grant-driven revocation fenced until Game Session rebuilds or reconciles and reads back those exact entries under current Account grant authority. | `grantScopeId` is the exact canonical scope ID for the complete Account-owned tuple. Reset and reconciliation never concatenate world/realm selectors or other tuple fields independently. The entries are tenant-scoped, shard-local bounded lookup evidence; Account state remains authoritative, and stale, wrong-lifecycle, or cross-tenant entries are removed. Public-production and unscoped bindings have no entry. | | `session:game:index:issuer:{issuerIndexLayoutTag}::` | Coordination | **Reset-sensitive with mandatory issuer-coverage rebuild** | Issuer cutoff and issuer-wide lookup remain fenced until the complete owner-defined issuer recovery result qualifies; region and tenant resets never flush a whole issuer partition. | Global per issuer across tenants and partitioned by the immutable issuer layout, not tenant-tagged. The inventory, capacity, acknowledgement, and coverage contract is owned by the linked Game Session evidence documents. | | `session:game:{tenantGameplayTag}::` | Coordination | **Reset-sensitive** | Region and tenant resets retain or invalidate this record only under their explicit session policy. Cluster scope requires `--invalidate-sessions`; preserved-session rebind is not a cluster option. | Authoritative for connection identity and reconnect/session CAS state, but not a substitute for the owner-defined rebind/admission contract. | | `sessionctx:*` | Coordination | **Reset-sensitive, not preservable** | Current Game Session bootstrap and lookup context is invalidated or rebuilt by any reset; it is never covered by `--preserve-sessions` and cannot authorize gameplay. | Game Session owns this live implementation-local family. Its reset consequence is local to the family; the canonical reset lifecycle and session policy remain defined above. | +| `gameplaypresence:session:`, `gameplaypresence:::sessions`, and `gameplaypresence::account::sessions` | **Current legacy projection (role unproved; not an accepted target prefix)** | **Reset-sensitive, private-by-failure until the target contract is proven** | These current live-presence value/index families are unavailable when missing, partial, stale, or ambiguous; `WHO` and account-presence reads must fail private-by-failure rather than expose stale or cross-scope presence. Game Session must fence the affected scope, rebuild an exact-scoped owner projection, and complete exact readback before presence is exposed again. | The current writer uses untagged keys and separate value/set mutations; it is implementation drift, not target authority. The target must choose and prove the Redis role, exact scope, atomic owner mutation, reset inventory, and readback contract. | +| `accountrecentpresence::` | **Current legacy projection (role unproved; not an accepted target prefix)** | **Reset-sensitive, private-by-failure until the target contract is proven** | Loss, partial state, stale state, or ambiguous routing evidence makes recent/offline presence unavailable/private; it must not be presented as a verified location or routing fact. Game Session must fence or suppress the affected projection and rebuild/read back the exact target owner projection before exposing it. | The current account recent-presence record is a direct untagged value with an implementation TTL; its storage role, exact retention, reset behavior, and owner readback are unproved. It remains a disposable current shape, not durable authority or target cache semantics. | +| `gamesession:notifydisconnect:dedup:` | **Coordination (current legacy drift; target sequencing contract unproved)** | **Reset-sensitive, fail-closed until the target contract is proven** | Dropping or losing the latest sequence must not permit an old duplicate `NotifyDisconnect` to remove presence, emit region exit, or suspend runtime state. Until exact connection/generation binding and durable sequencing are proven, the affected scope remains fenced and Redis loss/error cannot authorize fail-open stale effects. | Game Session owns the current sequence-dedup writer; the current one-hour key and Redis failure behavior are implementation drift. The target owner contract must define durable sequencing, binding validation before side effects, reset inventory, and exact readback. | | Pre-auth transport context | Coordination | **Reset-sensitive, not preservable** | Region and tenant resets invalidate or rebuild this context regardless of `--preserve-sessions`; cluster scope requires invalidation. | Pre-auth context is not gameplay authority and is outside the canonical gameplay-session preservation domain. | | `session:auth:token:` | Coordination | **Reset-sensitive by scope** | Region and tenant resets preserve these Account-owned records. For a destructive cluster reset, Account-owned authority/token cutover and immutable pre-wipe handoff evidence complete before the wipe; after reset, Account repairs and durably reads back the affected projections; replay quarantine and durable replay-consumption proof complete before replacement registration. Cleanup removes only old or stale projections, and replacement registry records remain after registration. Missing records deny protected use and require fresh authentication. | The exact-token registry is the runtime authority for that token, while Account durable generations remain the authority for issuer, compromise, and reset invalidation. Reset tooling must not infer scope from key names or recreate a record from a JWT. See `system-architecture-jwt-and-token-contracts.md` for full semantics. | | `session:auth:account::` | Coordination | **Reset-sensitive, Account-owned legacy projection** | Region- and tenant-scoped coordination resets preserve the live Account account-session record; a cluster reset or cold start may discard it only through the Account-owned cutover and repair path, with protected admission closed until replacement auth state is verified. | This legacy family is outside gameplay session policy. Account owns repair, revocation, and eventual convergence to `session:auth:token:`; a coordination reset or Game Session must not delete or recreate it. | @@ -237,7 +247,7 @@ A region- or tenant-scoped reset parent cannot claim global account- or issuer-i | `session:connect-token:v1:tenant::account::scope::request:` | Coordination | **Target exact-result projection; unavailable and not currently proven** | Region- and tenant-scoped coordination resets preserve this Account-owned projection once the target operation/envelope cutover is implemented. For a planned destructive cluster reset, Account’s durable issuance operation/response-envelope authority and immutable pre-wipe evidence must complete before the wipe; after reset, Account repairs and durably reads back the exact projection. For unexpected cold-start loss, handshakes remain fenced until Account performs exact repair and readback. Missing or untrusted results fail closed until the applicable identity expires; they must not be reconstructed from a JWT or silently reminted. | The target value requires `schemaVersion: "connect-token-issuance-result-v1"`; `scopeHash` and `requestHash` are fixed-length lowercase hexadecimal SHA-256 of canonical UTF-8 `connectScopeId` and `requestId`, respectively; the target reader/writer is isolated to this versioned prefix, uses durable SQL first-writer-wins before mint, and installs Redis with set-if-absent/read-winner. Exact repair only is permitted. See the [Account connect-token persistence contract](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). | | `session:auth:generation:issuer:`, `session:auth:generation:account:`, `session:auth:generation:tenant:`, and `session:auth:generation:membership::` | Coordination | **Reset-sensitive, fail-closed by scope** | Region- and tenant-scoped coordination resets do not reset these untagged Account-owned projections; they leave unaffected scopes intact and re-project/verify every affected exact scope. A missing or lower Redis projection may be repaired with Account-owned idempotent set-if-greater. If that projection mutation is unavailable, the same Account-owned durable generation-mutation/repair operation is the fallback; an unavailable or ambiguous durable result keeps the scope fenced. A projection greater than Account durable authority is poisoned and must be quarantined or replaced through an Account-owned audited workflow, recreated from durable authority, and accompanied by immutable per-scope repair evidence before protected traffic reopens. A cluster-scoped reset may discard projections only after protected admission is closed and Account advances the issuer authority generation; Account then rebuilds and verifies every affected projection and current issued-token record before reopen. | Account's durable transactional generation is the sole authority. Redis is only a bounded projection/cache and must never become an alternate writer or reset baseline. No scoped coordination reset advances, deletes, or recreates these projection families; they remain outside gameplay session policy. | | `session:game:auth:issuer-generation:v1:` | Coordination | **Reset-sensitive, fail-closed by scope** | Region- and tenant-scoped coordination resets do not reset the Game Session issuer-generation consumer projection; affected scopes are reinstalled or reconciled from the exact Account-owned issuer checkpoint and read back before issuer-gated admission, reconnect, or revocation consumption. A cluster-scoped reset may discard it only after the Account repair/reset cutover and issuer-generation projection gates close protected admission; Game Session then installs the exact derived projection and verifies its complete source checkpoint before reopen. | Game Session owns only this derived consumer projection; Account's durable issuer generation and `session:auth:generation:issuer:` remain authoritative. No scoped coordination reset advances or recreates this projection from local state. | -| `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness` | Coordination | **Reset-sensitive, fail-closed** | These shared Gateway replay-domain keys are an explicit exception to tenant/region key tagging and are untouched by region- or tenant-scoped resets. The readiness value carries `replayAdmissionFence` and all three keys share the literal hash tag `{gateway-connect-token-replay-v1}` for one Redis Cluster slot. If replay markers or browser-revocation deny markers are dropped or become untrusted, or fence/readiness continuity is uncertain, the reset advances the fence and rejects all new first-party gameplay handshakes for at least the maximum gameplay-connect lifetime (`30 seconds`) plus two configured clock-skew intervals. Reopen requires the same quarantine and disposable-marker proof: one fresh invocation of the canonical consume script must return `1` and create a disposable replay marker, followed by one same-connection `WAITAOF` local/replica durability acknowledgement meeting the configured thresholds. A `0` or `-1` result is non-mutating and cannot supply a second write acknowledgement; any cleanup is a separate guarded cleanup write/readback and is not part of `DURABLE_REPLAY_CONSUME_ACK`. This gate covers loss of either replay or deny markers and is in addition to, and cannot bypass, the Account cutover, issuer-generation projection rebuild/proof, and post-reset smoke ordering. The current generic Cache-bound writer emits only the untagged replay marker; it has no current deny-marker, readiness, or replay-fence writer. Migration requires quarantine, exact old replay-prefix inventory/readback, named Coordination client/ACL cutover, target-key readback, and retention or explicit cleanup of old markers through their original acceptance window. Resetting this replay state alone does not close already admitted WebSockets. A cluster reset closes affected gameplay sockets under its required explicit invalidation policy. | Consumed replay and deny markers are security-critical and non-evicting. The fence is advanced only after old marker state is dropped or rejected; quarantine and the single durability acknowledgement must complete before the readiness record reopens admission. Existing admitted WebSockets are unaffected by replay-state reset alone. | +| `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`, `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::` | Coordination | **Reset-sensitive, fail-closed** | These shared Gateway replay-domain keys are an explicit exception to tenant/region key tagging and are untouched by region- or tenant-scoped resets. The readiness value carries `replayAdmissionFence`; all four key families share the literal hash tag `{gateway-connect-token-replay-v1}` for one Redis Cluster slot. If replay markers or browser-revocation deny markers are dropped or become untrusted, or fence/readiness continuity is uncertain, the reset advances the fence and rejects all new first-party gameplay handshakes for at least the maximum gameplay-connect lifetime (`30 seconds`) plus two configured clock-skew intervals. While readiness remains `QUARANTINED`, the trusted recovery coordinator invokes Gateway's separate typed probe: Gateway conditionally writes its own disposable probe marker on one pinned connection, then obtains the configured same-connection `WAITAOF` acknowledgement. Gateway owns the probe key, nonce, and marker value; callers cannot redirect it to a player `jti` or deny prefix. The probe marker has a finite bounded expiry. The probe does not call the normal `OPEN`-only consume script or write shared readiness. Only the recovery coordinator may authorize reopening after the deadline, exact fenced probe evidence, and every other owner release gate; Gateway's owner-local helper performs the readiness CAS through the existing authenticated maintenance API. Exact-operation/fence-guarded cleanup and readback are separate from `DURABLE_REPLAY_CONSUME_ACK`. This gate covers loss of either replay or deny markers and is in addition to, and cannot bypass, the Account cutover, issuer-generation projection rebuild/proof, and post-reset smoke ordering. The current generic Cache-bound writer emits only the untagged replay marker; it has no current deny-marker, readiness, replay-fence, or recovery-probe writer. Migration requires quarantine, exact old replay-prefix inventory/readback, named Coordination client/ACL cutover, target-key readback, and retention or explicit cleanup of old markers through their original acceptance window. Resetting this replay state alone does not close already admitted WebSockets. A cluster reset closes affected gameplay sockets under its required explicit invalidation policy. | Consumed replay and deny markers are security-critical and non-evicting. The fence is advanced only after old marker state is dropped or rejected; quarantine and the recovery coordinator's separately gated release must complete before the readiness record reopens admission. Existing admitted WebSockets are unaffected by replay-state reset alone. See [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md) for the canonical probe and reopen contract. | | `remote:{tenantInstanceTag}:` | Coordination | **Reset-tolerant** | Cross-region follow-ups rely solely on durable tables; hints may be temporarily missing, increasing latency only. Region-scoped coordination resets leave instance-scoped hints intact; tenant- and cluster-scoped resets enumerate every affected game instance from the durable scope inventory and remove each instance's `remote:{tenantInstanceTag}:*` keys. | The complete key scope is `` because durable remote follow-up identity is instance-aware. These are best-effort cross-region wake-up hints only; dropping them affects latency, not correctness. Hint keys are TTL-bounded (default `remote_hint_ttl_ms = 60_000`) so stale hints age out automatically. | | `ratelimit:::*` and separately declared shared heuristics | Cache/Rate-Limit | **Reset-tolerant** | Rate-limit counters reset; future requests rebuild subject or shared-policy state from zero. | Each limiter declares whether reset temporarily weakens or tightens its heuristic and its unavailable-store behavior. Hard authorization, financial, durable-quota, or security invariants remain outside evictable Redis. | | `inventory:::*` | Cache/Rate-Limit | **Reset-tolerant** | Namespace-backed cached inventory/container aggregates are flushed; subsequent reads recompute views from PostgreSQL and repopulate Redis. | The cache scope is `(tenantId, playableStateNamespaceId, containerId)`; `playableStateScope` is separately validated evidence and is not inferred from the key. Inventories remain authoritative in PostgreSQL; cache loss affects latency only. | @@ -246,10 +256,11 @@ A region- or tenant-scoped reset parent cannot claim global account- or issuer-i | `world-dynamic::*` | Cache/Rate-Limit | **Reset-tolerant** | Cached dynamic world aggregates are flushed; subsequent reads recompute views from PostgreSQL. | World topology/dynamic state remains authoritative in PostgreSQL; resets may increase load temporarily. | | `room::*` | Cache/Rate-Limit | **Reset-tolerant** | Cached room topology snapshots are dropped; callers reload rooms from PostgreSQL and repopulate caches. | Used for LOOK/navigation snapshots; resets never affect canonical topology in PostgreSQL. | | `view:room-look::*` | Cache/Rate-Limit | **Reset-tolerant** | Cached rendered room views are dropped; Game Session recomputes views on demand for affected rooms. | Strictly Class B, TTL-only caches; correctness-critical flows (combat, visibility, movement) do not read from this prefix, and Game Session is the sole writer/reader of these keys. | +| `lookcache::` | Cache/Rate-Limit (current legacy only; target role unapproved) | **Reset-tolerant, disposable** | A clustered cache reset may delete this legacy projection and must verify the family is gone; loss affects no authoritative LOOK state. | The current ten-minute writer is non-authoritative and lacks target viewer/policy/read-fence scope. Drain/remove the writer or migrate it exactly before target `view:room-look:*` helpers consume the family; this prefix is not target Class B authority. | | `chat:say::*`, `chat:whisper:::*`, legacy `chat:whisper::`, `chat:tell::*`, `chat:guild::*`, `chat:city::*`, `chat:account::*` | Cache/Rate-Limit | **Reset-tolerant** | Target and live legacy chat projections are cleared; reads use or fall back to authoritative Social/PostgreSQL history where the communication type promises durable player history, while non-durable projections may rebuild or remain absent. Reset/TTL loss may create gaps or non-contiguous windows only in transient Redis projections and cannot create a durable-history entitlement gap. `chat:city` is a current legacy TTL projection, not durable history and not `SHOUT`. | `WHISPER` reset scope is the complete gameplay recipient namespace `(tenantId, playableStateNamespaceId, characterId)`, and reset cleanup includes the live legacy `chat:whisper::` prefix alongside the target prefix until migration completes. Resets drop recent in-memory history but do not lose persisted moderation logs where required; the legacy prefix must not be used for history/refill across same-account characters or namespaces. No `SHOUT` Redis/reset family exists until a selected profile publishes its type/storage/topology contract. | | `script-scheduler:{tenantRegionTag}:lastTickId` (target-only, once implemented) | Coordination | **Reset-tolerant (target-only, once implemented)** | Once implemented, Automation scheduler treats the next heartbeat as its baseline and may re-scan due interval boundaries, but durable trigger-instance uniqueness prevents duplicate logical trigger creation. Until then, no current reset operation is defined for this unimplemented target projection. | Target-state Automation scheduler checkpoint for “every N ticks” triggers; once implemented, losing it causes the scheduler to re-establish its baseline from the heartbeat stream while PostgreSQL-backed trigger-instance rows remain the de-duplication boundary. | | `automation:timer:{tenantRegionTag}` (target-only, once implemented) | Coordination | **Reset-tolerant (target-only, once implemented)** | Once implemented, Automation timer indexes for affected regions are discarded and rebuilt from durable schedules, trigger-instance rows, and heartbeat progress. Until then, no current reset operation is defined for this unimplemented target projection. | Target-state region-scoped coordination index for script timers/intervals. Once implemented, entries must remain instance-aware in payload and rebuild logic (`gameInstanceId`, and plugin identifiers when applicable) even though the Redis key is region-scoped for slotting/locality. | -| `automation:queue:{tenantInstanceTag}:*` | Cache/Rate-Limit | **Current reset/recovery unavailable; fail-closed (target reset-tolerant)** | Queue entries are disposable pointers: losing all Redis list contents does not lose PostgreSQL `script_work_items`, but missing pointers do not authorize resume. The current `rebuildPendingWorkItemIndex` selects both `PENDING_EVALUATION` and `EVALUATING` rows without a stale-owner or compare-and-set reconciliation gate, so queue reset, rebuild, and resume are unavailable. Do not flush, rebuild, or resume this projection as a supported current operation; keep the affected `{tenantId, gameInstanceId}` scope paused/fenced and escalate to the Automation owner. Once owner status reconciliation/reclamation, CAS fencing, and exact readback are implemented and proven, tooling may drop and rebuild only this pointer projection from the authoritative rows before releasing the scope. | The queue is a derived pointer projection, never execution authority; PostgreSQL work-item state remains authoritative. See the [Automation & Scripting API contract](./microservices/automation-scripting-service/api-contracts.md#implementation-status) and [runtime/data owner contract](./microservices/automation-scripting-service/runtime-and-data.md#redis-roles-and-prefixes). | +| `automation:queue:{tenantInstanceTag}:*` | Cache/Rate-Limit | **Current reset/recovery unavailable; fail-closed (target reset-tolerant)** | Queue entries are disposable pointers: losing all Redis list contents does not lose PostgreSQL `script_work_items`, but missing pointers do not authorize resume. The current `rebuildPendingWorkItemIndex` selects only `PENDING_EVALUATION` rows, but has no stale-owner or compare-and-set reconciliation gate and cannot establish a safe disposition for existing `EVALUATING` rows, so queue reset, rebuild, and resume are unavailable. Do not flush, rebuild, or resume this projection as a supported current operation; keep the affected `{tenantId, gameInstanceId}` scope paused/fenced and escalate to the Automation owner. Before any future rebuild can release that scope, owner reconciliation must establish a definitive stage-aware disposition for ambiguous post-DSL handoffs from a durable evaluated descriptor, retaining durable handoff intent without replaying the DSL, then complete owner CAS fencing and exact readback. Only after these conditions are implemented and proven may tooling drop and rebuild this pointer projection from authoritative rows. | The queue is a derived pointer projection, never execution authority; PostgreSQL work-item state remains authoritative. See the [Automation & Scripting API contract](./microservices/automation-scripting-service/api-contracts.md#implementation-status) and [runtime/data owner contract](./microservices/automation-scripting-service/runtime-and-data.md#redis-roles-and-prefixes) for the durable evaluated-descriptor and recovery boundary. | | `automation:quota::*`, `automation:tenant-budget::tier:`, `automation:test:quota::script::tenant`, `automation:test:quota::script::principal:`, `automation:test:capacity:{}:tenant`, `automation:test:capacity:{}:lease:`, `automation:test:capacity:{automation-test-capacity}:cluster`, `automation:test:capacity:{automation-test-capacity}:cluster:lease::`, `automation:readiness:capacity:{}:tenant`, `automation:readiness:capacity:{}:lease:`, `automation:readiness:capacity:{automation-readiness-capacity}:cluster`, `automation:readiness:capacity:{automation-readiness-capacity}:cluster:lease::` | Cache/Rate-Limit | **Reset-tolerant** | Quota windows and capacity reservations restart from an empty state; durable automation work/readiness state remains authoritative. The service does not rebuild the one-minute quota windows or ten-minute readiness leases; new requests acquire fresh disposable reservations. | Best-effort counters and owner-token leases; resets clear them but do not affect authoritative state. Repeated resets or lease expiry may temporarily relax test fairness or readiness concurrency, but must not change which durable work eventually runs. Only the Automation service's Cache/Rate-Limit ACL may access these families; they are not Coordination Redis scheduler/tick keys. Tenant counter/lease pairs use the tenant hash tag, while cluster counter/lease pairs use their fixed family hash tag. | | `tick-events-lease:{tenantRegionTag}` (target-only, once implemented) | Coordination | **Reset-tolerant (target-only, once implemented)** | The target lease is currently unavailable; once implemented, observer leases are dropped, consumers reacquire them, and may duplicate best-effort processing until offsets are re-established. | Used only to avoid duplicate tick-event consumption work. Losing it is safe because tick events are observers/hints; correctness derives from the committed heartbeat/RegionStatus timeline and durable domain state. | | `tick-events:{tenantRegionTag}` and all `tick-events-offset:{tenantRegionTag}:{consumerId}` keys (target-only, once implemented) | Coordination | **Reset-tolerant (target-only, once implemented)** | The target stream and offsets are currently unavailable; once implemented, tick event streams and every consumer's offset are dropped, and observers re-establish their baselines from the gRPC heartbeat and domain state. Any surviving per-consumer offset value is reusable only when its stored `region_epoch` matches the current control-plane epoch; otherwise it is discarded before resume. | Tick event streams are best-effort observer/wakeup hints (for example, reconnection hints and faster scheduler discovery). Each offset value stores `{tenantId, gameInstanceId, regionId, consumerId, region_epoch, latestTickId, streamOffset}`. Streams are retention-capped (default `tick_events_maxlen = 2048` per region). Correctness derives from the committed heartbeat/RegionStatus timeline plus durable PostgreSQL schedules/effects; missing or duplicated events must not change which schedules eventually fire. | @@ -295,7 +306,7 @@ Once the bounded recovery controller and its coordination-maintenance CLI are im - Always accompanied by post‑reset health checks (ticks can be scheduled, sessions can be created/resumed, automation works). - Region‑ and tenant‑scoped resets should prefer **smaller scopes first**; cluster‑scoped reset is reserved for catastrophic or planned migration scenarios where finer scopes are ineffective. -General in-place repair of coordination keys is intentionally **not** a first-implementation operator path. A future repair path may be added only by defining named maintenance CLI verbs with scope rules, fencing/quiescence requirements, audit output, and mandatory post-repair verification. In the current fallback, any direct coordination-prefix mutation is break-glass activity: preserve the mutation evidence, keep the affected scope fenced, and escalate when no supported scoped reset or cleanup path exists. In the target state, a direct mutation must be followed by the owner-defined scoped reset or documented cleanup flow that covers the mutated prefix before normal processing resumes. +General in-place repair of coordination keys is intentionally **not** a first-implementation operator path. A future repair path may be added only through named maintenance CLI verbs with scope rules, fencing/quiescence requirements, audit output, and mandatory post-repair verification, after that supported tooling is implemented and its focused proof is complete. In the current fallback, every observed direct coordination-prefix mutation is unsupported incident evidence, not an operator path: preserve the mutation evidence, keep the affected scope fenced, and escalate; no current fallback authorizes, repairs, or makes durable any direct mutation. Only target-state tooling, once implemented and proven, may perform a direct mutation, and it must then run the owner-defined scoped reset or documented cleanup flow covering the mutated prefix before normal processing resumes. Target-state design reviews should explicitly state which of these strategies is expected to be safe for each coordination structure. @@ -386,6 +397,7 @@ For a current Coordination Redis cold start, incomplete recovery, or reset incid - Preserve the AOF, operation records, and incident evidence. Keep Gateway protected admission, gameplay mutation, command intake, and affected coordination writers fenced or stopped; an empty keyspace is not safe-resume evidence. - No current scoped reset is supported. The target-state scope grammar and `coordination-maintenance` CLI are unavailable today, and raw coordination-prefix mutations are not a reset path. - Use only the shipped `PauseTicksForScope` pause and `GetRuntimeOwnershipStatus` status surface for the supported `{tenantId, gameInstanceId}` boundary. Read-only Redis inspection is permitted only through an independently provisioned credential bound to the exact Coordination Redis endpoint and deployment generation, with attested `coord_ops_ro/v2` ACL/key-pattern and `coord_redis_config/v1` evidence, the applicable authenticated-TLS peer/hostname transport attestation for remote/shared/hosted/staging/production targets, and successful canonical positive/negative readback probes. A same-host loopback `dev_local` inspection may use its explicitly authorized local transport profile and is not hosted evidence. `coord_ops_ro` is a target logical profile, not a repository-shipped credential; if any applicable endpoint, transport, ACL, credential, attestation, or readback evidence is unavailable or ambiguous, do not connect with a generic, default, application, or admin credential—leave the fence in place and escalate. Follow the current failover/AOF procedures and escalation path in the [Redis incident runbook](./system-architecture-redis-incident-runbook.md) and [Redis Operations](./system-architecture-redis-operations.md); do not invoke the target-state CLI or use raw coordination-prefix mutations. +- After every applicable endpoint, transport, credential, ACL, attestation, and canonical readback gate in the preceding bullet succeeds, use only the shipped `PauseTicksForScope` pause and `GetRuntimeOwnershipStatus` status surface for the supported `{tenantId, gameInstanceId}` boundary, plus read-only `coord_ops_ro` inspection. Preserve the original AOF without editing or rewriting it, and keep it only in the approved restricted custody path for raw storage evidence. If incident evidence must include command data, never copy raw AOF contents to a workstation, ticket, log, terminal, shared artifact, or ordinary disk. A working copy may be produced only by approved tooling that proves complete field-level redaction or irreversible tokenization of every credential- or identity-bearing value (including bearer/access tokens, token or session credential material, account/tenant/issuer/session/character identifiers, and operator/workload identity or secret material), followed by encryption in the approved evidence store, access logging, and an explicit owner/expiry. If complete redaction, custody, encryption, or access-control proof is unavailable, retain only the original under restricted custody and escalate; do not produce a working copy. At retention expiry, request disposal through the approved evidence-custody process and record the result; if disposal cannot be verified, keep the copy inaccessible in the approved restricted store and escalate rather than claim destruction. Never expose raw AOF contents in tickets, logs, terminals, or shared artifacts. Then follow only the current failover/incident-evidence procedures and escalation path in the [Redis incident runbook](./system-architecture-redis-incident-runbook.md) and [Redis Operations](./system-architecture-redis-operations.md); there is no supported current AOF rewrite or other destructive AOF mutation, and operators must not invoke the target-state CLI or use raw coordination-prefix mutations. - No fallback or future recovery release may rely on an empty keyspace, script loading, sample ticks, or local operator observations. The complete [canonical post-reset verification checklist](./system-architecture-redis-ops-access.md#canonical-post-reset-verification-checklist) and applicable recovery release gates are required; script-load and sample-tick checks are supplemental only. - If the durable recovery controller, Account projection repair/replacement, replay quarantine/fence, or immutable evidence path is unavailable, stale, or ambiguous, abort any destructive wipe, recovery continuation, `resume`, `release-lock`, or reopen attempt. Leave the fence in place and escalate; there is no supported current full-wipe or unlock substitute. @@ -403,7 +415,7 @@ Coordination resets interact with measured coordination exposure and replay in p - In-place **repair** is not part of the first-implementation operator model: - Local mutations of coordination keys bypass the normal script/key-builder path unless they are wrapped in future dedicated maintenance tooling. - - Until such tooling exists, direct mutation is break-glass activity and is followed by the reset/cleanup rules above rather than treated as a durable fix. + - Until such tooling exists, any observed direct mutation is unsupported incident evidence and must be preserved, fenced, and escalated; it is never an authorized current repair or durable fix. - **Replay** behavior must remain safe regardless of resets: - Lua scripts must be idempotent with respect to their `KEYS` and `ARGV`. @@ -424,9 +436,10 @@ Operators interacting with Coordination Redis should assume: - Region‑ and tenant‑scoped resets are standard responses to certain classes of incidents. - Cluster‑scoped resets are rare but documented for extreme scenarios. -- **Break‑glass writes require follow‑up resets**: +- **Break‑glass writes require target-state tooling and follow-up recovery**: - Any manual mutation of core coordination prefixes is considered equivalent to corruption for that scope. - - Runbooks must include clear guidance to reset and verify affected regions/tenants afterwards. + - Once supported maintenance tooling is implemented and proven, runbooks must include clear guidance to use the smallest valid reset/recovery workflow and verify affected regions/tenants afterwards. + - Until then, direct mutations and follow-up resets are prohibited current actions; preserve evidence, maintain fencing, and escalate through the current fallback. - **Metrics drive decisions**: - Measured unreplicated-write-window observability (described in `system-architecture-redis-operations.md`) surfaces when exposure exceeds the environment SLO. diff --git a/design/architecture/system-architecture-redis-script-rollout-and-compatibility.md b/design/architecture/system-architecture-redis-script-rollout-and-compatibility.md index 2dc272630a..f38094f0ba 100644 --- a/design/architecture/system-architecture-redis-script-rollout-and-compatibility.md +++ b/design/architecture/system-architecture-redis-script-rollout-and-compatibility.md @@ -74,8 +74,9 @@ Potentially compatible when proven by tests: - `requires_region_reset` - `requires_tenant_reset` - `requires_cluster_reset` -6. Confirm reset safety before resuming: - - no `SCHEDULED` ledger rows remain for the affected scope +6. Confirm reset safety before continuing the script rollout, and apply the separate traffic-reopen gate: + - no executable or unowned `SCHEDULED` ledger work remains for the affected scope; any remaining old-epoch `SCHEDULED` row is completely enumerated, explicitly fenced, and owned by reconciliation + - the affected scope remains blocked from reopening while any such reconciliation-owned row lacks the policy-defined authority-fenced terminal decision - in-flight commands are retried or marked terminal appropriately The registry, together with its golden compatibility tests, remains the single source of truth for whether coordination state can be safely replayed across script versions or must be reset. diff --git a/design/architecture/system-architecture-redis-usage-and-profiles.md b/design/architecture/system-architecture-redis-usage-and-profiles.md index be16efe876..2bc168cc26 100644 --- a/design/architecture/system-architecture-redis-usage-and-profiles.md +++ b/design/architecture/system-architecture-redis-usage-and-profiles.md @@ -11,6 +11,13 @@ The target automation handoff also requires the complete Trigger Identity, inclu Separate Coordination and Cache/Rate-Limit Redis processes exist in current manifests, but role-specific application clients, ACLs, key/script registration, and ownership proof under [ADR 0171](./decisions/adr-0171-separated-redis-role-processes-and-owned-keyspaces.md) remain incomplete. Account-owned auth, authority-generation, and connect-token projections remain reset-sensitive rather than fully reset-tolerant. The current live `session:auth:account:*` and `session:auth:tenant:*` projections, and target-only `session:auth:token:*` and `session:auth:generation:*` projections, are preserved by region/tenant resets; cluster or cold-start loss requires Account-owned repair and exact readback. The unversioned legacy connect-token map remains preserve/readback-only through its TTL/retry horizon, while target versioned exact-result projections require their owner repair contract. Their region/tenant-preserve versus cluster/cold-start repair consequences are canonical in the [Redis Reset & Recovery reset matrix](./system-architecture-redis-reset-and-recovery.md#global-index-family-recovery-consequence); this usage document records ownership and profile wiring only and does not redefine that matrix. Current reset/reopen remains blocked until Account-owned repair, exact projection readback, and the matrix's applicable evidence gates are implemented and proved. +The current hosted application wiring still exposes one generic `firemud.redis` client, with the shared hosted profile setting `FIREMUD_REDIS_HOST=redis-cache`; the role-specific Redis variables are present in the profile but are not consumed by the shared client configuration. Consequently, Game Session and Account coordination/auth paths cannot claim Coordination endpoint isolation in the hosted profile and may currently land on Cache/Rate-Limit Redis. This is implementation drift against ADR 0171, not a new role contract: hosted `pr-preview` and every other non-ephemeral/player-facing environment require named role clients and fail-closed endpoint-collision handling. The only exception is an explicitly labelled one-shot ephemeral CI/test stack, which may remain live after a collision only while surfacing the shared endpoint and forfeiting role-isolation, replay, and SLO evidence. + +The shared `ConflictTracker` is another concrete consumer of this generic wiring: current Entity and Game Session callers emit `conflict:entity::` and `conflict:session::` through `RedisConflictTracker`, which performs separate `INCR` and `EXPIRE` calls, warns when `EXPIRE` does not return true, and does not catch command exceptions. If increment succeeds but expiry fails, the counter may remain without a TTL. These counters are reset-tolerant diagnostics, never authority, but their current endpoint placement and mutation sequence remain implementation drift. The target role, owner, finite cardinality, TTL, ACL, and atomic-helper convergence are defined in [Redis Architecture](./system-architecture-redis.md#coordination-vs-cache-prefixes) and its [reset-policy entry](./system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary); no current runtime proof is implied. + +The hosted Helm Cache/Rate-Limit Redis process has a separate configuration drift: the enabled hosted overlay provisions a persistent cache volume, while the in-chart `redis-cache` Deployment starts Redis with AOF enabled and does not set `maxmemory` or an eviction policy. This does not provide the bounded, eviction-driven Cache/Rate-Limit profile and can retain disposable cache/rate-limit state across restart; the hosted cache process must load the cache profile or declare equivalent bounded settings before this environment can claim the target cache posture. + +The checked Coordination configurations (`config/redis/redis.conf`, the in-chart `redis-coord`, and production Coordination values) do not set an internal Redis `maxmemory` bound. Container and pod resource limits are external process constraints, not Redis `maxmemory`; while Redis defaults to `noeviction` when no policy is configured, the absent internal bound does not establish the required bounded Coordination profile. Concrete per-environment sizing and configuration remain with Platform Operations/6D. --- @@ -39,7 +46,7 @@ Scope-key convention: `{tenantRegionTag}` is the canonical opaque tag for the co - Automation coordination structures that participate in tick timelines under Automation & Scripting ownership and Game Session enqueue contracts. - Characteristics: - Treated as a long-running **coordination buffer with bounded tail-loss** in persistent environments; durable history for tick effects and gameplay outcomes lives in PostgreSQL tick effect ledgers and domain stores. - - Game Session owns only its tick/session coordination prefixes and registered scripts: gameplay coordination families such as `tick:*`, `timer:*`, `retry:*`, `tick-executor-lease:*`, and the target-only, once-implemented `tick-events:*` stream, plus the canonical `session:game:{tenantGameplayTag}::` records and their derived `session:game:index:*` projections. The separately approved `session:game:auth:issuer-generation:v1:*` consumer projection is a distinct family with its own ownership and recovery rules. Automation & Scripting is the target registered consumer owner for the corresponding `tick-events-offset:*` and `tick-events-lease:*` records; live integration uses `ObserveRuntimeTickProgress`. See the [tick event contract](./system-architecture-ticks.md#tick-events--heartbeat-stream). Account Service retains ownership of the current legacy `session:auth:account:*` and `session:auth:tenant:*` projections, the explicit `session:auth:token:*` and `session:auth:generation:*` families, legacy unversioned `session:connect-token:tenant:*`, and target `session:connect-token:v1:tenant:*` prefixes, and Automation & Scripting Service retains ownership of its other automation-specific prefixes and scripts as documented below; Game Session invokes those contracts but does not write them. + - Game Session owns its tick/session coordination prefixes and registered scripts, as well as the live and recent presence projection responsibility: gameplay coordination families such as `tick:*`, `timer:*`, `retry:*`, `tick-executor-lease:*`, and the target-only, once-implemented `tick-events:*` stream, plus the canonical `session:game:{tenantGameplayTag}::` records and their derived `session:game:index:*` projections. This projection responsibility does not assign the current physical `gameplaypresence:session:` or `accountrecentpresence::` prefixes to the Coordination Redis role; their storage-role classification and target key contract remain unproven. See the [Game Session runtime and data status](./microservices/game-session-service/runtime-and-data.md#implementation-status) and the [Redis owner and reset catalog](./system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). The separately approved `session:game:auth:issuer-generation:v1:*` consumer projection is a distinct family with its own ownership and recovery rules. Automation & Scripting is the target registered consumer owner for the corresponding `tick-events-offset:*` and `tick-events-lease:*` records; live integration uses `ObserveRuntimeTickProgress`. See the [tick event contract](./system-architecture-ticks.md#tick-events--heartbeat-stream). Account Service retains ownership of the current legacy `session:auth:account:*` and `session:auth:tenant:*` projections, the explicit `session:auth:token:*` and `session:auth:generation:*` families, legacy unversioned `session:connect-token:tenant:*`, and target `session:connect-token:v1:tenant:*` prefixes, and Automation & Scripting Service retains ownership of its other automation-specific prefixes and scripts as documented below; Game Session invokes those contracts but does not write them. - AOF enabled in `dev_local`, `hobby_self_hosted`, and `production_clustered`–like profiles. - Subject to tail‑loss SLOs and replay guarantees described in the Redis hub doc. - Example prefixes: @@ -67,10 +74,13 @@ Scope-key convention: `{tenantRegionTag}` is the canonical opaque tag for the co - `view:room-look:::::::` (target-only Game Session disposable presentation/redraw helper; exact room, viewer/session, policy context, and applicable read-fence context bound. Current `ResolveLook` behavior is uncached; cache misses, unavailable or untrusted cache/fence evidence, and write refusal fall back to the authoritative uncached `ResolveLook` result. See the [canonical Class-B contract](./system-architecture-redis-cache.md#canonical-viewroom-look-class-b-contract); never semantic reconnect context, frame/output replay, archive, or delivery ledger.) - `world-dynamic::room-dynamic::` - `ratelimit:::` (one opaque stable subject hash per individual subject) + - Current Game Session `ratelimit:` is a separately registered legacy heuristic written through the generic client; it is not target subject authority and remains inadmissible for target shared helpers until explicit Cache admission and maximum-TTL drain/versioned migration. - `automation:queue:{tenantInstanceTag}:` and automation quota counters. Coordination Redis and Cache/Rate‑Limit Redis must use **separate processes and endpoints** in every non-ephemeral or player-facing environment, including `local-dev` and hosted `pr-preview`, so cache eviction/pressure cannot silently impact coordination SLOs. They may be two containers or processes on the same hobby host or cluster node; separate hardware is not required. The only supported exception is an explicitly labelled one-shot ephemeral test/CI stack other than hosted `pr-preview`; it may collapse roles temporarily only when reset-tolerant, must visibly surface the shared endpoint, and provides no role-isolation, replay, tail-loss, or SLO evidence. Such a stack may still run reset-tolerant coordination tests, but it must not be used to establish role-isolation, replay, tail-loss, or SLO proof. See [ADR 0171](./decisions/adr-0171-separated-redis-role-processes-and-owned-keyspaces.md) and [Environment Profiles and Mappings](#environment-profiles-and-mappings). +The current `gameplaypresence:*` and `accountrecentpresence:*` physical shapes are unregistered legacy implementation drift, not Coordination or Cache/Rate-Limit role-assigned prefixes and not target authority. Their role, exact scope, atomicity, and owner readback remain unproved. The reset matrix classifies them as reset-sensitive and private-by-failure: Game Session must fence/suppress affected presence, rebuild the exact target owner projection, and complete exact readback before exposing presence again. + New prefixes must declare: - Which role they live on (Coordination vs Cache/Rate‑Limit), @@ -91,15 +101,17 @@ Keep the cheat sheet and the owning service Redis sections aligned with the cano A small set of automation/scheduler-specific prefixes is target-only and will be **reset-tolerant once implemented**; no current reset operation is defined for these unimplemented target projections: +The schedule-candidate and firing-claim identities below consume the [canonical scripting identity contract](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields): `playableStateNamespaceId` is the durable identity component, while `playableStateScope` is separately persisted and exact-validated fence evidence, not a uniqueness dimension. + - `script-scheduler:{tenantRegionTag}:lastTickId` (target-only, once implemented) - Role: Coordination Redis. - Owner: Automation & Scripting Service. - Purpose: per-region derived discovery hint for “every N ticks” schedulers tied to the canonical `(regionEpoch, tickId)` timeline. Its value is `{regionEpoch, latestTickId}`; consumers reject and rebuild it when the stored epoch differs from the authoritative epoch. It does not store `streamOffset`; `tick-events-offset:{tenantRegionTag}:` is the sole event-stream offset record for each consumer. - - Reset behavior: target-only reset-tolerant projection once implemented; region/tenant/cluster resets may drop this key. Until that target projection exists, no current reset operation is defined for it; current scheduling rebuilds due work from PostgreSQL schedules and the Game Session `ObserveRuntimeTickProgress` feed as described in the tick and scripting docs. Duplicate trigger prevention comes from a durable PostgreSQL trigger-instance or outbox row with a uniqueness projection over the applicable identity branch. For schedule-derived triggers, the pre-claim branch includes `(tenantId, gameInstanceId, playableStateScope, stableOwnerKind, stableOwnerId, regionId, regionEpoch, entityId only when targetScopeType is entity-scoped, scriptId, eventType, eventSchemaVersion, scriptPatchVersion, scriptPinEpoch, isDryRun, scheduleDefinitionId, targetScopeType, targetScopeId, duePoint, triggerMode)`, plus `resumeWindowId` only when `triggerMode=CATCH_UP` and plugin identity `(pluginId, pluginVersionId, bindingId)` when applicable; `resumeWindowId` is absent otherwise. The paired `scriptPinControlPlaneRequestId` remains immutable owner evidence on the candidate and claim and is exact-compared during admission/replay, but it is excluded from their uniqueness and derived `scriptEventId`. For plugin-owned schedules, the captured `pluginActivationEpoch` is an additional tagged dimension of due-candidate and firing-claim identity and therefore of the derived event-scope scheduler `scriptEventId`; the captured `lifecycleRevision` travels alongside as immutable non-identity lifecycle-fence evidence. Neither field is a per-command child-key dimension, and both are revalidated through admission, retry, replay, and recovery. The winning claim then derives one immutable event-scope scheduler `scriptEventId` from that complete candidate identity and propagates it into each resolved handler's normalized Trigger Identity; `pluginActivationEpoch` remains excluded from that handler identity. Contenders reuse the winning event-scope ID instead of including a generated value in the race key. `duePoint` is exactly `dueTickId:` or `dueAt:`; if physical storage uses nullable `dueTickId`/`dueAt` columns, the alternate field is explicitly `NULL`, never an empty/zero substitute, and both fields may not be null or populated together. For an immediate event-driven trigger, the scheduler-only fields `scheduleDefinitionId`, `duePoint`, and `triggerMode` are absent, both physical due columns are `NULL`, and the event-driven branch includes the generated stable `scriptEventId` as the occurrence discriminator. Storage must represent the event-driven versus scheduler-derived branch explicitly, for example with a discriminator or branch-specific unique constraints, rather than allowing nullable scheduler fields to alias distinct event triggers. The per-command `automationDispatchId` and `commandOrdinal` are separately unique under the same runtime timeline and link the trigger claim to each emitted command; they remain child handoff identity and do not replace the full Trigger Identity. The row retains the full schedule projection when applicable (`cadence`, `unit`, `priorityTag`, `targetScopeType`, `targetScopeId`, binding priority/exclusivity, `scheduleSemanticsHash`, the pin operation's `controlPlaneRequestId`, owner/version metadata, due-point state, and `runtimeRegionId`/`runtimeRegionEpoch`), including the captured plugin lifecycle pair when applicable; it is not reduced to this Redis checkpoint or a schedule ID alone. + - Reset behavior: target-only reset-tolerant projection once implemented; region/tenant/cluster resets may drop this key. Until that target projection exists, no current reset operation is defined for it; current scheduling rebuilds due work from PostgreSQL schedules and the Game Session `ObserveRuntimeTickProgress` feed as described in the tick and scripting docs. Duplicate trigger prevention comes from a durable PostgreSQL trigger-instance or outbox row with a uniqueness projection over the applicable identity branch. For schedule-derived triggers, the pre-claim branch includes `(tenantId, gameInstanceId, playableStateNamespaceId, stableOwnerKind, stableOwnerId, regionId, regionEpoch, entityId only when targetScopeType is entity-scoped, scriptId, eventType, eventSchemaVersion, scriptPatchVersion, scriptPinEpoch, isDryRun, scheduleDefinitionId, targetScopeType, targetScopeId, duePoint, triggerMode)`, plus `resumeWindowId` only when `triggerMode=CATCH_UP` and plugin identity `(pluginId, pluginVersionId, bindingId)` when applicable; `resumeWindowId` is absent otherwise. The paired `scriptPinControlPlaneRequestId` remains immutable owner evidence on the candidate and claim and is exact-compared during admission/replay, but it is excluded from their uniqueness and derived `scriptEventId`. For plugin-owned schedules, the captured `pluginActivationEpoch` is an additional tagged dimension of due-candidate and firing-claim identity and therefore of the derived event-scope scheduler `scriptEventId`; the captured `lifecycleRevision` travels alongside as immutable non-identity lifecycle-fence evidence. Neither field is a per-command child-key dimension, and both are revalidated through admission, retry, replay, and recovery. The winning claim then derives one immutable event-scope scheduler `scriptEventId` from that complete candidate identity and propagates it into each resolved handler's normalized Trigger Identity; `pluginActivationEpoch` remains excluded from that handler identity. Contenders reuse the winning event-scope ID instead of including a generated value in the race key. `duePoint` is exactly `dueTickId:` or `dueAt:`; if physical storage uses nullable `dueTickId`/`dueAt` columns, the alternate field is explicitly `NULL`, never an empty/zero substitute, and both fields may not be null or populated together. For an immediate event-driven trigger, the scheduler-only fields `scheduleDefinitionId`, `duePoint`, and `triggerMode` are absent, both physical due columns are `NULL`, and the event-driven branch includes the generated stable `scriptEventId` as the occurrence discriminator. Storage must represent the event-driven versus scheduler-derived branch explicitly, for example with a discriminator or branch-specific unique constraints, rather than allowing nullable scheduler fields to alias distinct event triggers. The per-command `automationDispatchId` and `commandOrdinal` are separately unique under the same runtime timeline and link the trigger claim to each emitted command; they remain child handoff identity and do not replace the full Trigger Identity. The row retains the full schedule projection when applicable (`cadence`, `unit`, `priorityTag`, `targetScopeType`, `targetScopeId`, binding priority/exclusivity, `scheduleSemanticsHash`, the pin operation's `controlPlaneRequestId`, owner/version metadata, due-point state, and `runtimeRegionId`/`runtimeRegionEpoch`), including the captured plugin lifecycle pair when applicable; it is not reduced to this Redis checkpoint or a schedule ID alone. - `automation:timer:{tenantRegionTag}` (target-only, once implemented) - Role: Coordination Redis. - Owner: Automation & Scripting Service. - - Purpose: per-region timer/index structure for script intervals and timer-driven triggers; stored entries remain instance-aware via payload identity such as `gameInstanceId`. + - Purpose: per-region timer/index structure for script intervals and timer-driven triggers; stored entries retain the complete schedule identity via payload fields including `gameInstanceId` and `playableStateNamespaceId` (plus plugin identity when applicable), despite the region-scoped key. - Reset behavior: target-only reset-tolerant projection once implemented; keys may be dropped by scoped coordination resets and are rebuilt from PostgreSQL-backed schedules, trigger-instance rows, and heartbeat progress. Until then, no current reset operation is defined for this unimplemented target projection. Durable automation schedules, quotas, script configuration, and trigger-instance de-duplication live in PostgreSQL; these coordination prefixes are latency and progress hints only and must not be treated as the primary record of “which scripts should run”. Designs that introduce new automation-related coordination prefixes must register them in the reset policy matrix and document how they recover from resets. @@ -125,11 +137,12 @@ Automation workloads split into two broad classes, with different expectations a - Current implementation boundary: `EnqueueAutomationCommandIfAbsent` does not yet carry or fully enforce the target lane, one-root actor-slot, or bounded-cost guarantees. Its current wire, durable-storage, and admission path remains narrower than the target contract (including the complete Trigger Identity, `commandOrdinal`, `lane`, and `cost_class`), so current enqueue success is not proof of those guarantees. - Canonical handoff contract (target state): - When work references a revocable component, the durable trigger/admission row and handoff payload retain the applicable component-revocation security-policy fence as independent parent evidence. It is included in the canonical handoff request digest and immutable readback/conflict comparison, revalidated through handoff, retry, replay, recovery, and final-effect boundaries, and excluded from Trigger Identity, Command-Handoff Identity, and their uniqueness keys; a changed or unavailable fence fails closed under the established disposition rather than minting a replacement identity. - - Automation & Scripting creates or reuses a durable PostgreSQL trigger-instance / outbox row keyed by the applicable Trigger Identity branch. A schedule-derived pre-claim row uses `(tenantId, gameInstanceId, playableStateScope, stableOwnerKind, stableOwnerId, regionId, regionEpoch, entityId only when targetScopeType is entity-scoped, scriptId, eventType, eventSchemaVersion, scriptPatchVersion, scriptPinEpoch, isDryRun, scheduleDefinitionId, targetScopeType, targetScopeId, duePoint, triggerMode)`, plus `resumeWindowId` only when `triggerMode=CATCH_UP` and plugin identity `(pluginId, pluginVersionId, bindingId)` when applicable; `resumeWindowId` is absent otherwise. The paired `scriptPinControlPlaneRequestId` remains immutable owner evidence on the row and is exact-compared during admission, handoff, retry, replay, and recovery, but is excluded from uniqueness and derived `scriptEventId`. For plugin-owned schedules, the captured `pluginActivationEpoch` is an additional tagged dimension of due-candidate and firing-claim identity and therefore of the derived `scriptEventId`; the captured `lifecycleRevision` travels alongside as immutable non-identity lifecycle-fence evidence. Neither field is a per-command child-key dimension, and both are carried and revalidated through admission, handoff, retry, replay, and recovery per [Scripting Contracts §8](./system-architecture-scripting-contracts.md#8-plugin-version-fencing-and-control-plane-scope). The winning claim derives one immutable `scriptEventId`, and retries reuse it. An immediate event-driven row omits the scheduler-only fields and uses its generated stable `scriptEventId` to distinguish one event occurrence from another; its storage uniqueness branch must remain distinct from scheduled rows and includes the server-derived `sourceService` in its event-scope claim when the event is custom or service-specific. The immutable source Trigger Identity, including source `regionId` and `regionEpoch`, is retained on the row; current enqueue routing fields are separate. The complete per-command child handoff identity comprises the source runtime scope, optional distinct target runtime scope, `automationDispatchId`, and `commandOrdinal`; it is stored separately from the parent Trigger Identity. The row also retains `cadence`, `unit`, `priorityTag`, `targetScopeType`, `targetScopeId`, binding priority/exclusivity, `scheduleSemanticsHash`, the pin operation's `controlPlaneRequestId`, owner/version metadata, due-point state, and `runtimeRegionId`/`runtimeRegionEpoch` when those fields apply, plus the captured plugin lifecycle pair when applicable. + - Automation & Scripting creates or reuses a durable PostgreSQL trigger-instance / outbox row keyed by the applicable Trigger Identity branch. A schedule-derived pre-claim row uses `(tenantId, gameInstanceId, playableStateNamespaceId, stableOwnerKind, stableOwnerId, regionId, regionEpoch, entityId only when targetScopeType is entity-scoped, scriptId, eventType, eventSchemaVersion, scriptPatchVersion, scriptPinEpoch, isDryRun, scheduleDefinitionId, targetScopeType, targetScopeId, duePoint, triggerMode)`, plus `resumeWindowId` only when `triggerMode=CATCH_UP` and plugin identity `(pluginId, pluginVersionId, bindingId)` when applicable; `resumeWindowId` is absent otherwise. The paired `scriptPinControlPlaneRequestId` remains immutable owner evidence on the row and is exact-compared during admission, handoff, retry, replay, and recovery, but is excluded from uniqueness and derived `scriptEventId`. For plugin-owned schedules, the captured `pluginActivationEpoch` is an additional tagged dimension of due-candidate and firing-claim identity and therefore of the derived `scriptEventId`; the captured `lifecycleRevision` travels alongside as immutable non-identity lifecycle-fence evidence. Neither field is a per-command child-key dimension, and both are carried and revalidated through admission, handoff, retry, replay, and recovery per [Scripting Contracts §8](./system-architecture-scripting-contracts.md#8-plugin-version-fencing-and-control-plane-scope). The winning claim derives one immutable `scriptEventId`, and retries reuse it. An immediate event-driven row omits the scheduler-only fields and uses its generated stable `scriptEventId` to distinguish one event occurrence from another; its storage uniqueness branch must remain distinct from scheduled rows and includes the server-derived `sourceService` in its event-scope claim when the event is custom or service-specific. The immutable source Trigger Identity, including source `regionId` and `regionEpoch`, is retained on the row; current enqueue routing fields are separate. The complete per-command child handoff identity comprises the source runtime scope, optional distinct target runtime scope, `automationDispatchId`, and `commandOrdinal`; it is stored separately from the parent Trigger Identity. The row also retains `cadence`, `unit`, `priorityTag`, `targetScopeType`, `targetScopeId`, binding priority/exclusivity, `scheduleSemanticsHash`, the pin operation's `controlPlaneRequestId`, owner/version metadata, due-point state, and `runtimeRegionId`/`runtimeRegionEpoch` when those fields apply, plus the captured plugin lifecycle pair when applicable. - Automation & Scripting then calls a Game Session gRPC/API contract such as `EnqueueAutomationCommandIfAbsent`, carrying the complete immutable Trigger Identity and child handoff identity: - - Parent Trigger/event-scope evidence: `tenantId`, `gameInstanceId`, `playableStateScope`, source `regionId`, source `regionEpoch`, `entityId` only for an entity-scoped trigger, `scriptId`, `eventType`, `eventSchemaVersion`, `scriptPatchVersion`, `scriptPinEpoch`, paired `scriptPinControlPlaneRequestId`, `scriptEventId`, and `isDryRun`, plus applicable plugin identity `(pluginId, pluginVersionId, bindingId)`, captured `(pluginActivationEpoch, lifecycleRevision)` lifecycle-fence evidence, and the server-derived `sourceService` for custom or service-specific events. + - Parent Trigger Identity and separately carried evidence: `tenantId`, `gameInstanceId`, `playableStateNamespaceId`, source `regionId`, source `regionEpoch`, `entityId` only for an entity-scoped trigger, `scriptId`, `eventType`, `eventSchemaVersion`, `scriptPatchVersion`, `scriptPinEpoch`, `scriptEventId`, and `isDryRun`, plus applicable plugin identity `(pluginId, pluginVersionId, bindingId)` and the server-derived `sourceService` for custom or service-specific events. `playableStateScope`, paired `scriptPinControlPlaneRequestId`, and captured `lifecycleRevision` are separately carried and validated evidence; the owner request ID and `lifecycleRevision` are non-identity evidence. For plugin-owned schedules, `pluginActivationEpoch` retains its owner-defined candidate/firing-claim identity role. - Scheduled rows also carry `scheduleDefinitionId`, `targetScopeType`, `targetScopeId`, `triggerMode`, exactly one tagged `duePoint`: `dueTickId:` or `dueAt:`, and `resumeWindowId` only when `triggerMode=CATCH_UP`; immediate event-driven rows use the separate event branch, omit scheduler-only fields and `duePoint`, and carry a stable `scriptEventId`; their physical `dueTickId` and `dueAt` fields are both `NULL`. - Child handoff identity: complete source runtime scope, optional distinct target runtime scope, `automationDispatchId`, and `commandOrdinal`. `commandOrdinal` identifies the emitted command within the dispatch and is not replaced by `commandKind` or by `scriptEventId`. + - Identity clarification: the source and target runtime scopes in the child handoff identity use `playableStateNamespaceId` and `targetPlayableStateNamespaceId` where applicable. `playableStateScope` and `targetPlayableStateScope` remain separately persisted, exact-validated policy/routing/authorization/migration-fence evidence and are excluded from child uniqueness. - Current enqueue routing fields, including `runtimeRegionId` and `runtimeRegionEpoch` when applicable, are carried separately from immutable source Trigger Identity. - The accepted immutable scheduling metadata is also carried explicitly: `lane` (`actor_action` or `passive_effect`) and bounded `cost_class`, as defined by the [Scripting Scheduler and Timer Lifecycle](./system-architecture-scripting-scheduler-and-timers.md) owner contract, with the current gap tracked in [Automation and Scheduler Runtime](../project-management/implementation-tracking/automation-and-scheduler-runtime.md). Game Session copies these values into the durable admission row and selected-work manifest before any tick-queue mutation. They are included in the canonical handoff request digest and durable readback/conflict comparison, but are immutable conflict fields rather than additional dimensions of the canonical command uniqueness key. The complete child handoff identity remains the source runtime scope, optional distinct target runtime scope, `automationDispatchId`, and `commandOrdinal`; the parent Trigger Identity and due-point branch remain immutable correlation and conflict/readback evidence. - the deterministic gameplay command payload @@ -145,21 +158,22 @@ Automation workloads split into two broad classes, with different expectations a - The Game Session enqueue acknowledgement is the source of truth that the accepted automation was materialized into current Redis coordination for that region. If Redis enqueue fails after durable admission, Game Session retries materialization from the admission record or converges it to a terminal non-applied outcome under the same command-status rules used for player commands. - Redis keys are hot-path coordination state only; they are never the sole record that a fairness-critical automation action existed. - Worked example: - - A schedule for NPC `entityId=E1` becomes due at `(tenantId=7b3b074e-d597-4e9b-b96f-4f5946d26120, gameInstanceId=9a2bb6d1-74c7-4f81-a9e8-418e65f6ad78, playableStateScope=shared, regionId=R1, regionEpoch=7, scriptPatchVersion=P3, scriptPinEpoch=4, scriptPinControlPlaneRequestId=pin-request-4, duePoint=dueTickId:420)`. - - Automation & Scripting creates the canonical trigger claim for that due point and evaluates under the claim; before a winning evaluated-descriptor/outbox commit it has no dispatch or command-child identity. If evaluation emits one command, that first atomic commit allocates and persists `automationDispatchId=AD1` and `commandOrdinal=0`; a valid zero-command evaluation creates neither. The source trigger-claim row is unique on `(tenantId=7b3b074e-d597-4e9b-b96f-4f5946d26120, gameInstanceId=9a2bb6d1-74c7-4f81-a9e8-418e65f6ad78, playableStateScope=shared, stableOwnerKind=SCRIPT, stableOwnerId=NPC_MOVE, regionId=R1, regionEpoch=7, entityId=E1, scriptId=NPC_MOVE, eventType=onInterval, eventSchemaVersion=v1, scriptPatchVersion=P3, scriptPinEpoch=4, isDryRun=false, scheduleDefinitionId=S1, targetScopeType=ENTITY, targetScopeId=E1, duePoint=dueTickId:420, triggerMode=CATCH_UP, resumeWindowId=RW1)`, plus any applicable plugin fields. Its `scriptPinControlPlaneRequestId=pin-request-4` remains persisted and exact-compared owner evidence on the candidate and claim, but is excluded from this uniqueness key and derived `scriptEventId`. This source trigger-claim projection is distinct from the Game Session durable admission projection, whose key is the complete child Command-Handoff Identity. The Game Session row retains the complete parent Trigger Identity and schedule projection, including the branch-specific target selector, due point, `resumeWindowId=RW1`, `cadence`, `unit`, `priorityTag`, `targetScopeType`, `targetScopeId`, binding priority/exclusivity, `scheduleSemanticsHash`, the pin operation's `controlPlaneRequestId`, owner/version metadata, due-point state, and `runtimeRegionId`/`runtimeRegionEpoch`, plus immutable `lane` and bounded `cost_class` metadata, as correlation and conflict/readback evidence. - - After that commit, it calls `EnqueueAutomationCommandIfAbsent` with the complete Trigger Identity, including `scriptPatchVersion=P3`, `scriptPinEpoch=4`, and `scriptPinControlPlaneRequestId=pin-request-4`, persisted `automationDispatchId=AD1`, `commandOrdinal=0`, scheduled candidate evidence `targetScopeType=ENTITY`, `targetScopeId=E1`, `triggerMode=CATCH_UP`, `resumeWindowId=RW1`, and `duePoint=dueTickId:420`, immutable `lane` and bounded `cost_class`, the target region timeline fields, and the deterministic command payload. A retry after the winning commit reuses `AD1` and its ordinal. - - Game Session inserts or reads the durable admission row identified by the complete child Command-Handoff Identity: source scope `(tenantId=7b3b074e-d597-4e9b-b96f-4f5946d26120, gameInstanceId=9a2bb6d1-74c7-4f81-a9e8-418e65f6ad78, playableStateScope=shared, regionId=R1, regionEpoch=7)`, no distinct target scope, and `(automationDispatchId=AD1, commandOrdinal=0)`. It verifies the stored parent Trigger Identity and scheduled candidate evidence `targetScopeType=ENTITY`, `targetScopeId=E1`, `triggerMode=CATCH_UP`, `resumeWindowId=RW1`, and `duePoint=dueTickId:420` as immutable comparison evidence, validates the active lease, epoch, and due point for `R1`, maps the request to `tick:{tenantRegionTag}:queue:E1`, and returns `"ENQUEUED"` on the first successful materialization. + - A schedule for NPC `entityId=E1` becomes due at `(tenantId=7b3b074e-d597-4e9b-b96f-4f5946d26120, gameInstanceId=9a2bb6d1-74c7-4f81-a9e8-418e65f6ad78, playableStateNamespaceId=namespace-1, playableStateScope=shared, regionId=R1, regionEpoch=7, scriptPatchVersion=P3, scriptPinEpoch=4, scriptPinControlPlaneRequestId=pin-request-4, duePoint=dueTickId:420)`. + - Automation & Scripting creates the canonical trigger claim for that due point and evaluates under the claim; before a winning evaluated-descriptor/outbox commit it has no dispatch or command-child identity. If evaluation emits one command, that first atomic commit allocates and persists `automationDispatchId=AD1` and `commandOrdinal=0`; a valid zero-command evaluation creates neither. The source trigger-claim row is unique on `(tenantId=7b3b074e-d597-4e9b-b96f-4f5946d26120, gameInstanceId=9a2bb6d1-74c7-4f81-a9e8-418e65f6ad78, playableStateNamespaceId=namespace-1, stableOwnerKind=SCRIPT, stableOwnerId=NPC_MOVE, regionId=R1, regionEpoch=7, entityId=E1, scriptId=NPC_MOVE, eventType=onInterval, eventSchemaVersion=v1, scriptPatchVersion=P3, scriptPinEpoch=4, isDryRun=false, scheduleDefinitionId=S1, targetScopeType=ENTITY, targetScopeId=E1, duePoint=dueTickId:420, triggerMode=CATCH_UP, resumeWindowId=RW1)`, plus any applicable plugin fields. `playableStateScope=shared` remains separately persisted and exact-validated policy/routing/authorization/migration-fence evidence, not a uniqueness dimension. Its `scriptPinControlPlaneRequestId=pin-request-4` remains persisted and exact-compared owner evidence on the candidate and claim, but is excluded from this uniqueness key and derived `scriptEventId`. This source trigger-claim projection is distinct from the Game Session durable admission projection, whose key is the complete child Command-Handoff Identity. The Game Session row retains the complete parent Trigger Identity and schedule projection, including the branch-specific target selector, due point, `resumeWindowId=RW1`, `cadence`, `unit`, `priorityTag`, `targetScopeType`, `targetScopeId`, binding priority/exclusivity, `scheduleSemanticsHash`, the pin operation's `controlPlaneRequestId`, owner/version metadata, due-point state, and `runtimeRegionId`/`runtimeRegionEpoch`, plus immutable `lane` and bounded `cost_class` metadata, as correlation and conflict/readback evidence. + - After that commit, it calls `EnqueueAutomationCommandIfAbsent` with the complete Trigger Identity, including `scriptPatchVersion=P3` and `scriptPinEpoch=4`, alongside the persisted, exact-compared owner evidence `scriptPinControlPlaneRequestId=pin-request-4`; it also sends persisted `automationDispatchId=AD1`, `commandOrdinal=0`, scheduled candidate evidence `targetScopeType=ENTITY`, `targetScopeId=E1`, `triggerMode=CATCH_UP`, `resumeWindowId=RW1`, and `duePoint=dueTickId:420`, immutable `lane` and bounded `cost_class`, the target region timeline fields, and the deterministic command payload. A retry after the winning commit reuses `AD1` and its ordinal. + - Game Session inserts or reads the durable admission row identified by the complete child Command-Handoff Identity: source runtime identity `(tenantId=7b3b074e-d597-4e9b-b96f-4f5946d26120, gameInstanceId=9a2bb6d1-74c7-4f81-a9e8-418e65f6ad78, playableStateNamespaceId=namespace-1, regionId=R1, regionEpoch=7)`, no distinct target scope, and `(automationDispatchId=AD1, commandOrdinal=0)`. The matching `playableStateScope=shared` is separately exact-validated evidence, excluded from uniqueness. It verifies the stored parent Trigger Identity and scheduled candidate evidence `targetScopeType=ENTITY`, `targetScopeId=E1`, `triggerMode=CATCH_UP`, `resumeWindowId=RW1`, and `duePoint=dueTickId:420` as immutable comparison evidence, validates the active lease, epoch, and due point for `R1`, maps the request to `tick:{tenantRegionTag}:queue:E1`, and returns `"ENQUEUED"` on the first successful materialization. - If the same trigger retries due to gRPC timeout with the same immutable Trigger and scheduled candidate evidence, including `targetScopeType=ENTITY`, `targetScopeId=E1`, `triggerMode=CATCH_UP`, `resumeWindowId=RW1`, and `duePoint=dueTickId:420`, Game Session sees the same durable admission row and returns a replay/no-op outcome instead of enqueuing a second command; a retry with a different due point or resume window is rejected as conflicting evidence under the same child identity. - If the region has already moved to `regionEpoch=8`, Game Session returns a stale-timeline outcome and Automation & Scripting re-derives what should happen next from the durable trigger-instance row instead of inferring state from Redis. - **Best-effort, non-critical automation** - Examples: analytics-style background work, non-critical notifications, opportunistic refreshes that can be dropped or reordered without visible gameplay impact. - Redis role: **Cache/Rate-Limit Redis**. - - Prefixes: `automation:queue:{tenantInstanceTag}:*`, `automation:quota::*`, `automation:tenant-budget::tier:`, `automation:test:quota::script::tenant`, `automation:test:quota::script::principal:`, `automation:test:capacity:{}:*` where `` excludes the reserved tag `automation-test-capacity`, the exact tenantless counter `automation:test:capacity:{automation-test-capacity}:cluster`, its scoped lease variant `automation:test:capacity:{automation-test-capacity}:cluster:lease::`, `automation:readiness:capacity:{}:*` where `` excludes the reserved tag `automation-readiness-capacity`, the exact tenantless counter `automation:readiness:capacity:{automation-readiness-capacity}:cluster`, its scoped lease variant `automation:readiness:capacity:{automation-readiness-capacity}:cluster:lease::`, and similar TTL-only queues, counters, and leases documented in the Redis Cache & Rate Limiting design. The two exact `:cluster` counters are deployment-wide bounded-capacity records; their `:lease::` variants are tenant/work-scoped leases. Quota and capacity counters/leases remain TTL-only and reset-tolerant, while the current `automation:queue` reset/rebuild/resume path is unavailable and must fail closed; the target owner-reconciled queue rebuild is reset-tolerant once implemented. None becomes durable Coordination Redis state or hard correctness authority. + - Prefixes: `automation:queue:{tenantInstanceTag}:*`, `automation:quota::*`, `automation:tenant-budget::tier:`, `automation:test:quota::script::tenant`, `automation:test:quota::script::principal:`, `automation:test:capacity:{}:*` where `` excludes the reserved tag `automation-test-capacity`, the exact tenantless counter `automation:test:capacity:{automation-test-capacity}:cluster`, its scoped lease variant `automation:test:capacity:{automation-test-capacity}:cluster:lease::`, `automation:readiness:capacity:{}:*` where `` excludes the reserved tag `automation-readiness-capacity`, the exact tenantless counter `automation:readiness:capacity:{automation-readiness-capacity}:cluster`, its scoped lease variant `automation:readiness:capacity:{automation-readiness-capacity}:cluster:lease::`, and similar TTL-only queues, counters, and leases documented in the Redis Cache & Rate Limiting design. The two exact `:cluster` counters are deployment-wide bounded-capacity records; their `:lease::` variants are tenant/work-scoped leases. Quota and capacity counters/leases remain TTL-only and reset-tolerant, while the current `automation:queue` reset/rebuild/resume path is unavailable and must fail closed; the target owner-reconciled queue rebuild is reset-tolerant once implemented. The `automation:queue:{tenantInstanceTag}:*` family is reserved for disposable pointers to durably admitted work and is not a silently droppable work queue; a genuinely droppable analytics or notification queue requires its own registered prefix and owner contract. None becomes durable Coordination Redis state or hard correctness authority. - Guarantees: - - Treated as **TTL-only, reset-tolerant** hints: items may be dropped, duplicated, or processed late. - - Correctness (for example, “was this workflow triggered at least once?”) must come from durable trigger tables and idempotent domain logic, not from the queue contents. - - Design rule: features that require strong ordering, fairness relative to player actions, or at-least-once guarantees **must not** rely solely on `automation:queue:*`; they either belong in the coordination category above or should use tick-adjacent outbox/saga patterns. + - Cache counters and genuinely best-effort queue hints are **TTL-only, reset-tolerant**: they may reset, be dropped, duplicated, or processed late, and quota/fairness heuristics may temporarily relax or tighten. + - Current loss of an `automation:queue:*` pointer is fenced for owner reconciliation; current queue reset/rebuild/resume remains unavailable and must fail closed. Queue rebuild/redrive from durable trigger/work-item authority is target-only and not a live recovery action. Pointer loss is not itself durable-work loss. + - Correctness (for example, “was this workflow triggered at least once?”) must come from durable trigger tables and idempotent domain logic, not from Redis contents. + - Design rule: features that require strong ordering, fairness relative to player actions, or at-least-once guarantees **must not** rely solely on Cache/Rate-Limit queues or pointers; they either belong in the coordination category above or should use tick-adjacent outbox/saga patterns. When designing new automation, authors must explicitly state which category it belongs to and which Redis role/prefixes it uses, and link to the relevant tick or cache sections. Reviews should push gameplay-equivalent automation toward coordination prefixes and reserve cache-based queues for truly best-effort workloads. @@ -177,7 +191,7 @@ The following table summarizes how core services interact with Coordination Redi | **Spring Cloud Gateway** | **Target dual-role wiring:** Cache/Rate‑Limit Redis serves token‑bucket rate limiting and best-effort caches through a separate `gateway_cache_app` principal (the Gateway instance of logical `cache_app`) and separate deployment, while a separate `gateway_coord_app` principal (the Gateway instance of logical `coord_app`) and Coordination Redis deployment serves the narrow one-use connect-token replay marker `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, browser-revocation deny marker `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`, and readiness/fence record `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness` (whose value carries `replayAdmissionFence`). Replay consumption and browser-deny writes use pinned Coordination connections and the configured threshold-satisfying `WAITAOF` acknowledgement; an ambiguous deny write is unconfirmed. The target wiring never touches tick, session, or other gameplay-coordination prefixes. The current generic Cache-bound writer emits only the untagged replay marker; it has no current deny/readiness/fence writer. Those untagged replay keys are migration-only drift and are not target ACL state. | | **Logging & Admin Service** | Does not connect to Redis in the current runtime or target service role. It consumes Redis-derived health and metrics through Game Session APIs and exporters, may invoke named owner control APIs, and never receives Coordination or Cache/Rate-Limit Redis credentials. | | **TCP Proxy Service** | No current Cache/Rate-Limit Redis runtime dependency or shared-helper use. Future proxy cache/throttling participation is target/optional, non-authoritative, and requires a dedicated `tcpproxy:*` prefix registration; it must never use Coordination Redis. | -| **Other microservices (Game Logic, Entity Management, World Management, Social & Groups, etc.)** | Do not define or own coordination prefixes; they participate in Coordination Redis **only** through shared helpers and Lua descriptors owned by Game Session (for example, `tick:{tenantRegionTag}:lock:` for tick locks). Where they cache read‑heavy aggregates, they use **Cache/Rate‑Limit Redis** and the key patterns from the Redis Cache & Rate Limiting design. | +| **Other microservices (Game Logic, Entity Management, World Management, Social & Groups, etc.)** | Do not define or own gameplay coordination prefixes; they participate in Coordination Redis **only** through shared helpers and Lua descriptors owned by Game Session (for example, `tick:{tenantRegionTag}:lock:` for tick locks). Entity Management is the narrow exception for the registered `conflict:entity::` ConflictTracker producer: target `entity_coord_app` may access only `~conflict:entity:*`, and the reset inventory must treat this reset-tolerant, non-authoritative diagnostic family as a complete family; it does not grant tick-lock or other owner-family access. The live Entity `TickLockServiceImpl` `tick:lock::` bean is an explicitly registered legacy exception/drift family, not a second lock authority, and remains fenced from target admission until removed or routed through the canonical helper. Where they cache read‑heavy aggregates, they use **Cache/Rate‑Limit Redis** and the key patterns from the Redis Cache & Rate Limiting design. | These boundaries are part of the **Redis Coordination Invariants** described in `system-architecture-redis.md`. In the target state, they will be enforced via shared key helpers, the Lua script registry, and CI tooling; current role-specific clients, ACLs, key/script registration, and ownership proof remain incomplete as noted above. @@ -267,10 +281,12 @@ Coordination and Cache/Rate‑Limit Redis are sized and configured differently. ### Coordination Redis - **Goal:** predictable restart behavior and bounded memory usage for coordination keys. -- **Recommendations:** - - Keep peak memory for coordination prefixes (`tick:*`, `timer:*`, `retry:*`, `session:game:*`, `session:auth:token:*`, `session:auth:generation:*`, `session:connect-token:*`, `tick-executor-lease:*`, etc.) within the canonical Coordination Redis budget from `system-architecture-redis-operations.md` (normally **≤ 30–40% of `maxmemory`**). +- **Requirements and recommendations:** + - Every non-ephemeral Coordination Redis profile must configure an explicit finite positive Redis `maxmemory` bound. Container and pod resource limits do not satisfy this Redis-level requirement. + - `maxmemory-policy=noeviction` is mandatory for every non-ephemeral Coordination Redis profile. The only permitted deviation is an explicitly labelled ephemeral one-shot test/CI stack; any non-ephemeral deviation or observed eviction is fail-closed incident evidence. + - Keep peak memory for coordination prefixes (`tick:*`, `timer:*`, `retry:*`, `session:game:*`, `session:auth:token:*`, `session:auth:generation:*`, `tick-executor-lease:*`, etc.) within the canonical Coordination Redis budget from `system-architecture-redis-operations.md` (normally **≤ 30–40% of `maxmemory`**). - Use AOF preamble and rewrite settings that keep AOF size within the budgets described in **Redis Operations & Migrations**. - - Avoid eviction for coordination keys whenever possible; if `maxmemory` is configured with eviction, treat eviction events as incidents rather than normal operation. + - Any observed eviction remains a fail-closed incident and requires operator reconciliation before the profile is treated as healthy. ### Cache/Rate‑Limit Redis diff --git a/design/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index 769b5400b4..7e8799f5db 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -89,7 +89,7 @@ FireMUD uses Redis as a **transient, high‑performance coordination layer**, no Redis coordination keys form a long-running, measured-exposure **coordination buffer**, not the durable log of record for gameplay effects: -- Durable history for tick-driven outcomes (for example, “which effects were applied or abandoned for a given `(tenantId, gameInstanceId, playableStateScope, regionId, region_epoch, tickId, effectKey, targetAggregateType, targetAggregateId)`”) lives in PostgreSQL via the tick effect ledger and domain idempotency tables described in `system-architecture-tick-failures-and-operations.md` and `system-architecture-transactions.md`; `APPLIED`/`ABANDONED` are recorded only when that existing evidence policy permits terminalization, while inconclusive old-epoch work remains reconciliation-required under its original root `EffectId`. +- Durable history for tick-driven outcomes lives in PostgreSQL via the tick effect ledger and domain idempotency tables described in `system-architecture-tick-failures-and-operations.md` and `system-architecture-transactions.md`. Each durable tick-outcome row retains the complete `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId)` projection; `playableStateNamespaceId` is the durable namespace identity and `playableStateScope` is separately exact-validated evidence. Durable participant/replay authority is each mutation's persisted root-or-child `EffectId` (the root identity for a root mutation or the child's own identity for a generated child) plus typed operation, exact target, and immutable request digest. Participant-guard uniqueness also includes the owner-declared runtime-family partition: S1/S2 use `(tenantId, playableStateNamespaceId)`, while only explicitly declared S3 uses `(tenantId, gameInstanceId)`; unknown or unclassified families fail closed. The immutable `requestDigest` binds that identity but is not a uniqueness field or partition substitute; other scope and tick values remain exact evidence. The enclosing root `EffectId` remains lineage and reconciliation context for child mutations and cannot collapse siblings beneath one participant identity. See [Transaction Strategies](./system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory) and the [Identifier Glossary](./system-architecture-identifier-glossary.md#cross-service-effect-identity). `effectKey` and the remaining scope/tick facts are descriptor, projection, or evidence, not ledger uniqueness. `APPLIED`/`ABANDONED` are recorded only when that existing evidence policy permits terminalization, while inconclusive old-epoch work remains reconciliation-required under its original mutation `EffectId` with the enclosing root retained as lineage. - Coordination Redis holds volatile structures such as tick queues, `pending` sets, timers, region leases, tick event streams, and scheduler offsets; these structures are subject to measured unreplicated-write exposure and scoped resets as defined in this document and the Redis reset/runbook docs. - Application and ops designs must not treat AOF contents or Redis key history as the primary log for audits, analytics, or long-term effect replay; those concerns belong in PostgreSQL-backed ledgers and domain stores. - Redis Streams, lists, queue pointers, and wake signals are not durable event authority. Durable event capture, per-consumer delivery state, replay/reconstruction, retention, and backpressure remain owned by each flow's PostgreSQL outbox and worker/API contract; this hub records only the volatile Redis consequence. @@ -99,7 +99,11 @@ Redis coordination keys form a long-running, measured-exposure **coordination bu - Every issuer-generation projection, including the canonical `session:auth:generation:issuer:` projection and the Game Session `session:game:auth:issuer-generation:v1:` consumer projection, atomically stores `lastAppliedSourceOutboxSequence` (the accepted source `outboxSequence`) and `lastAppliedIssuerGeneration` for its exact canonical `outboxStreamKey`, plus `lastAppliedSourceEventId` and `lastAppliedSourceEventDigest` as derived source-checkpoint evidence for every nonzero sequence. These `lastAppliedSource*` fields are projection evidence associated with the canonical `outboxStreamKey`/`outboxSequence` and the applicable `outboxCheckpoints`; they are not authority-tuple fields or JWT claims. For sequence `0`, the two source-event fields are omitted from the projection, not serialized as JSON `null`, an empty string, a zero digest, or another sentinel; the Account-owned zero-sequence checkpoint is the only evidence. For every positive sequence, both source-event fields are required non-null values in their canonical formats. Ordinary delivered events may apply only the next contiguous sequence. A higher delivered sequence is a gap and must quarantine the affected projection and reconcile from Account before advancing the watermark or generation. The sole exception is one Account-owned authoritative snapshot/reconciliation installation, which may atomically install the exact Account checkpoint and generation at its latest sequence without consuming skipped events; that installation must carry the exact snapshot/checkpoint evidence and operation identity, and the next delivered event must be exactly one greater than the installed sequence. For each stream, the projection also retains bounded duplicate evidence for the most recent accepted sequences, at minimum `{outboxStreamKey, outboxSequence, eventId, eventDigest}`; each evidence entry has a required non-null `eventDigest`, and no entry represents the zero-sequence baseline. An equal or lower sequence is a no-op only when that bounded evidence matches or an authoritative Account lookup for the exact `(outboxStreamKey, outboxSequence)` proves the same event identity and digest; a high-water mark alone is never duplicate proof. If the evidence has aged out, the lookup is unavailable, or same-sequence evidence conflicts, the projection is quarantined. A valid next event advances the complete persisted checkpoint even when set-if-greater generation semantics leave the generation unchanged. The gameplay binding's separate `{outboxStreamKey, outboxSequence}` freshness set does not replace this projection-local replay evidence. Projection recovery fails closed while the checkpoint is missing, stale, regressed, ambiguous, or quarantined, including any invalid omitted/null/sentinel representation. - An empty Game Session issuer projection is an uninstalled and quarantined state, not an implicit zero-authority state and not permission to consume live events. Game Session, not Account, must install `session:game:auth:issuer-generation:v1:` from one Account-owned authoritative snapshot/reconciliation transaction for the exact `issuer/` scope and read back that installed derived projection. That transaction returns the exact checkpoint: `outboxStreamKey = account:auth-authority:v1:issuer/`, `lastAppliedSourceOutboxSequence` equal to the Account checkpoint's exact latest `outboxSequence`, and source `issuerAuthGeneration` from the same snapshot. For a nonzero sequence it also returns the exact source `eventId` and `eventDigest`; for sequence `0`, permitted only when the stream has no committed event, `lastAppliedSourceEventId` and `lastAppliedSourceEventDigest` are absent, and the Account-owned zero-sequence checkpoint itself is the evidence. The result also carries the source transaction or immutable bundle version, the exact checkpoint evidence, and the reconciliation operation identity; Game Session must not invent bootstrap event IDs, digests, sequences, or authority values locally. Before consuming events, Game Session atomically persists that complete checkpoint with the exact `issuerAuthGeneration` mapped to canonical persisted `lastAppliedIssuerGeneration`, stores matching `{outboxStreamKey, outboxSequence, eventId, eventDigest}` duplicate evidence only for a nonzero checkpoint, and reads back the installed projection. For a zero-sequence baseline, duplicate evidence is empty and the first consumable event must be sequence `1`; for a nonzero baseline, the next consumable event must be exactly `lastAppliedSourceOutboxSequence + 1`. Until the atomic installation and exact readback succeed, or if any applicable snapshot, source-checkpoint, event-identity/digest, or authority value is missing, stale, regressed, contradictory, or ambiguous, the projection remains quarantined and issuer-gated admission, reconnect, and revocation consumption fail closed. - Canonical issuer snapshot mapping is exact across bootstrap, persistence, readback, replay, and recovery: Account's authoritative snapshot field `issuerAuthGeneration` maps one-to-one to the projection field `lastAppliedIssuerGeneration`. The latter is the only persisted projection field used for comparison and replay advancement; `issuerAuthGeneration` is the source snapshot/authority name and is not a second persisted alias or a local fallback. Every bootstrap install, event replay, exact readback, set-if-greater repair decision, and recovery acknowledgement must compare the mapped value together with the exact `outboxStreamKey`, `lastAppliedSourceOutboxSequence`, source event evidence, and operation/checkpoint evidence. -- Spring Cloud Gateway has one narrow Coordination Redis authority: one-use connect-token replay consumption under `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, browser-revocation deny markers under `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, and the shared replay-readiness record under `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`. The readiness value carries the shared `replayAdmissionFence`. The Gateway fails closed when that replay authority is unavailable, owns the marker TTLs and reset contract, and must not expand this exception into ownership of gameplay sessions, Account auth state, or general coordination policy. +- Spring Cloud Gateway has one narrow Coordination Redis authority: one-use connect-token replay consumption under `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, browser-revocation deny markers under `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, the shared replay-readiness record under `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, and a separate Gateway-generated disposable recovery-probe marker under `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::`. The readiness value carries the shared `replayAdmissionFence`. Any marker-loss or reset event that can break replay continuity keeps shared readiness quarantined under an advanced `replayAdmissionFence` until the canonical [ADR 0029 readiness proof](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md) permits reopening; during that quarantine, an absent `jti` marker alone never proves first use. The probe marker is not a player `jti` or deny marker: its typed probe runs only in `QUARANTINED`, does not accept player credentials or write shared readiness, and returns evidence to the recovery coordinator. Normal player consume remains `OPEN`-only; only the coordinator may reopen after every release gate passes. The Gateway fails closed when that replay authority is unavailable, owns marker TTLs and reset contract, and must not expand this exception into ownership of gameplay sessions, Account auth state, or general coordination policy. These probe and release contracts are target-only and currently unimplemented. + +Game Session owns the live and recent account-presence projections described in [Game Session Runtime and Data](./microservices/game-session-service/runtime-and-data.md), but their current Redis shapes are implementation drift rather than accepted target authority. The live `gameplaypresence:session:`, `gameplaypresence:::sessions`, and `gameplaypresence::account::sessions` families, and the recent `accountrecentpresence::` family, currently use direct untagged writes with separate value/index mutations. Their exact owner scope, storage role, partial-write behavior, reset policy, rebuild/readback evidence, and private-by-failure semantics are not proven. These shapes must remain outside the accepted target key contract: the target owner projection requires an exact scope, atomic owner-controlled mutation, and a missing, stale, partial, or ambiguous projection must make presence private/unavailable rather than expose stale or cross-scope presence. The current families are cataloged in the reset matrix only to prevent an operator from treating an unregistered legacy shape as safe to delete, preserve, or use as authority. + +Account owns the exact-input connect-token issuance-result/idempotency family `session:connect-token:tenant::account::scope::request:`, distinct from Gateway's replay markers, deny markers, and `replayAdmissionFence`. **Current runtime:** the bounded legacy Redis value contains the raw issued token or deterministic cached failure and is not durable authority; loss while the request identity is still live must not silently produce a new result. **Target state:** Account uses durable/fenced recovery plus a bounded Account-encrypted response envelope containing the exact result, opened only for an exact retry after current authority and issuance reconciliation; missing or unreconciled state fails closed until the request identity expires. See [Account connect-token issuance persistence](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the owning contract. Reset handling and cataloging must not transfer this family to Gateway or treat it as a `session:auth:*` substitute. ### Canonical Grant Authority-Stream Scope Codec @@ -156,7 +160,7 @@ Legacy inventory/readback is permitted only as a bounded, read-only evidence ope - `current_tick_state` – the Redis-side execution state for `current_tick_id`. Allowed values are: - `STAGED` – Redis `pending`/queue state exists for this tick and hot-path scripts may continue to add idempotent entries for the same tick. - `RESOLVING` – durable domain/application work for this tick is in progress or being reconciled; no newer tick may be staged yet. - - `APPLIED` – every required participant for this tick has explicit durable terminal evidence: its participant outcome is `APPLIED` or `ABANDONED` in the PostgreSQL-backed ledger or an equivalent durable terminal record, and the existing evidence policy permits the tick to be terminal. The fenced recovery baseline uses `current_tick_id = -1` with `APPLIED` as its terminal no-prior-tick marker before the first tick is staged. An inconclusive old-epoch participant keeps the tick non-terminal and reconciliation-required. The mere presence of a reconciliation-backlog item is not evidence of a terminal outcome. Handler-level replay/no-op results are recorded separately as `replay_ok` attempt outcomes and do not satisfy this requirement by themselves. + - `APPLIED` – every eligible ledger row in this tick's complete expected participant-projection set for the exact current `(region_epoch, tickId)` has explicit durable terminal evidence: its participant outcome is `APPLIED` or `ABANDONED` in the PostgreSQL-backed ledger or an equivalent durable terminal record, and the existing evidence policy permits the tick to be terminal. Required-versus-optional classification affects command-result aggregation, not tick commit. The fenced recovery baseline uses `current_tick_id = -1` with `APPLIED` as its terminal no-prior-tick marker before the first tick is staged. An inconclusive participant belonging to this current-epoch tick keeps this tick non-terminal and reconciliation-required. An unresolved old-epoch participant is outside this current-epoch participant set; it remains non-terminal under its original mutation identity and can still block reset-scope convergence or reopening. The mere presence of a reconciliation-backlog item is not evidence of a terminal outcome. Handler-level replay/no-op results are recorded separately as `replay_ok` attempt outcomes and do not satisfy this requirement by themselves. - `ABANDONED` – the tick was intentionally terminated for the current epoch only after the owner/fenced recovery decision and evidence policy permit that terminal state (for example due to reset/recovery); no more work for that `(region_epoch, tickId)` may be staged through hot-path scripts. Reset scope alone does not authorize bulk terminalization. - `current_tick_terminal_at_ms` – absent/NULL while `current_tick_state` is `STAGED` or `RESOLVING`; set exactly once when the current tick first terminalizes as `APPLIED` or `ABANDONED`, and cleared/absent again when a newer tick is staged. Exact retries of that same terminal transition preserve the stored value, while a conflicting caller value is a non-mutating idempotency conflict. It is used for observability and bounded cleanup only, never for correctness decisions inside Lua. - Illustrative Redis hash contents: @@ -183,7 +187,7 @@ Legacy inventory/readback is permitted only as a bounded, read-only evidence ope - The first script or caller that hands staged effects to durable domain/application processing flips the state to `RESOLVING`. - Replays for the same tick must treat `STAGED` and `RESOLVING` as the same logical in-flight tick and may only add idempotent effect entries for that same `current_tick_id`. - `RESOLVING -> APPLIED`: - - Only after the durable tick ledger or equivalent durable terminal records for `(tenantId, gameInstanceId, playableStateScope, regionId, region_epoch, tickId)` contain explicit `APPLIED` or `ABANDONED` evidence for every required participant and the existing evidence policy permits terminalization. An inconclusive old-epoch participant keeps the tick non-terminal. A reconciliation-backlog item may identify work still needing reconciliation, but its presence alone cannot establish `APPLIED`; replay/no-op is a handler attempt outcome, recorded as `replay_ok`, not a ledger status. + - Only after the durable tick ledger or equivalent durable terminal records for `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, region_epoch, tickId)` contain explicit `APPLIED` or `ABANDONED` evidence for every eligible ledger row in that exact current-tick participant set and the existing evidence policy permits terminalization. Required-versus-optional classification affects command-result aggregation, not tick commit. An inconclusive participant in that current-epoch set keeps this tick non-terminal. An inconclusive old-epoch participant is not silently included in the current-tick set: it remains non-terminal under its original mutation identity and follows the old-epoch reconciliation and reopen gates. A reconciliation-backlog item may identify work still needing reconciliation, but its presence alone cannot establish `APPLIED`; replay/no-op is a handler attempt outcome, recorded as `replay_ok`, not a ledger status. - `RESOLVING -> ABANDONED`: - Only after the control plane or recovery tooling has made an explicit, evidence-qualified terminal decision to abandon the tick for the current epoch; reset scope alone is insufficient. - `APPLIED` or `ABANDONED` for tick `T`: @@ -200,8 +204,8 @@ Legacy inventory/readback is permitted only as a bounded, read-only evidence ope - Obtain their authoritative baseline for `(region_epoch, tickId)` from PostgreSQL RegionStatus/tick effect ledger and heartbeats, not from `current_tick_id`. - On a normal cold start with empty Coordination Redis and no active recovery, the next winning tick executor initializes `tick:{tenantRegionTag}:meta` during hot-path staging from PostgreSQL `RegionStatus` only when `requestedTickId` is the durable first-eligible tick, the caller explicitly proves that the exact environment and deployment are a documented non-reset profile, and the caller presents durable proof that all prior batches, effects, and commands are evidence-qualified terminal or that no unresolved work exists; without any of those guards or that proof, the region remains fenced. Schedulers and operators do not treat missing `meta` as a manual pre‑seeding task. While reset recovery is active, missing metadata keeps the scope fenced and hot-path staging must not create or recreate it until the canonical recovery release in [Redis Reset & Recovery](./system-architecture-redis-reset-and-recovery.md). - During reset recovery, the reset owner first establishes the durable new epoch, then initializes and verifies `tick:{tenantRegionTag}:meta` from that same authoritative baseline while the scope remains fenced. Only after that readback and the owner-defined recovery gates complete may the scope be released. The reset lifecycle and release prerequisites remain canonical in [Redis Reset & Recovery](./system-architecture-redis-reset-and-recovery.md#canonical-reset-sequence-boundary); this hub records only the local metadata and stale-key consequences. - - Treat Redis `pending` contents as an implementation detail of the hot path, not as proof of durable convergence. The durable proof that a tick is safe to move past is explicit terminal `APPLIED` or `ABANDONED` evidence for every required participant in the PostgreSQL ledger or equivalent durable terminal records; reconciliation-backlog presence and `replay_ok` attempt outcomes are insufficient by themselves. An inconclusive old-epoch row remains non-terminal under its original root `EffectId`; it cannot mutate current `tick:{tenantRegionTag}:meta` or block an otherwise evidence-permitted current-epoch terminalization, though it may still block unsafe next-tick progression, reset-scope convergence, or reopening. A terminal outcome for older or historical work remains in the durable ledger/reconciliation records under its original epoch and root effect identity; it must never overwrite or regress the current `tick:{tenantRegionTag}:meta`. Tick metadata updates remain limited to the current epoch's scheduler timeline; only a terminal outcome for that timeline may set `APPLIED` or `ABANDONED`. - - Recovery after coordination loss or reset does **not** reconstruct old ticks by silently restaging them through normal hot-path scripts. Recovery completes or abandons older work from durable manifests, ledger rows, and reconciliation backlog state only where the evidence policy permits; those historical terminal outcomes remain durable reconciliation state and do not update the current Redis tick metadata. Inconclusive old-epoch work remains non-terminal reconciliation work under its original root `EffectId`; it may prevent newer ticks from staging when that progression is unsafe, but it is not a reason to mutate or regress the current metadata or to withhold an otherwise permitted current-epoch terminalization. + - Treat Redis `pending` contents as an implementation detail of the hot path, not as proof of durable convergence. The durable proof that a tick is safe to move past is explicit terminal `APPLIED` or `ABANDONED` evidence for every eligible ledger row in that tick's complete expected current-epoch participant set in the PostgreSQL ledger or equivalent durable terminal records; required-versus-optional classification affects command-result aggregation, not tick commit. Reconciliation-backlog presence and `replay_ok` attempt outcomes are insufficient by themselves. An inconclusive old-epoch row remains non-terminal under its original mutation `EffectId`, with any enclosing root retained as lineage; it cannot mutate current `tick:{tenantRegionTag}:meta` or block an otherwise evidence-permitted current-epoch terminalization, though it may still block unsafe next-tick progression, reset-scope convergence, or reopening. A terminal outcome for older or historical work remains in the durable ledger/reconciliation records under its original epoch and mutation effect identity; it must never overwrite or regress the current `tick:{tenantRegionTag}:meta`. Tick metadata updates remain limited to the current epoch's scheduler timeline; only a terminal outcome for that timeline may set `APPLIED` or `ABANDONED`. + - Recovery after coordination loss or reset does **not** reconstruct old ticks by silently restaging them through normal hot-path scripts. Recovery completes or abandons older work from durable manifests, ledger rows, and reconciliation backlog state only where the evidence policy permits; those historical terminal outcomes remain durable reconciliation state and do not update the current Redis tick metadata. Inconclusive old-epoch work remains non-terminal reconciliation work under its original mutation `EffectId`, with any enclosing root retained as lineage; it may prevent newer ticks from staging when that progression is unsafe, but it is not a reason to mutate or regress the current metadata or to withhold an otherwise permitted current-epoch terminalization. - Redis-local split-brain and reset consequences: - `tick-executor-lease:{tenantRegionTag}` stores only the opaque lease token; `region_epoch` is read from the separate `tick:{tenantRegionTag}:meta` view and/or the durable reset contract. Region lease and coordination Lua receives both values separately, compares them before mutation, and follows the canonical result mapping in [Redis Lua Patterns](./system-architecture-redis-lua-patterns.md#canonical-region-lease-and-tick-staging-result-mapping). - After a reset, keys carrying an older `region_epoch` are ignored or explicitly cleaned up by reset tooling; Redis does not choose the durable epoch or authorize a new owner. @@ -515,9 +519,9 @@ Gateway connect-token replay state is a narrow security-critical exception to th - **Canonical replay-domain pin:** Gateway owns the shared domain identity and carries it through the non-secret `FIREMUD_GATEWAY_REPLAY_DOMAIN` configuration value. The only accepted value is the versioned literal `gateway-connect-token-replay-v1`; it is not generated per pod, tenant, region, deployment attempt, or reset. This fixed literal is the complete shared replay namespace: tenant, game, and region identifiers are intentionally not additional key components. Target Gateway startup and deployment preflight must reject a missing, unknown, or mismatched value, and every target key helper, ACL/prefix declaration, migration, reset, and recovery tool must use the exact hash tag `{gateway-connect-token-replay-v1}`. -- The target key shapes are `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`. The readiness value carries `replayAdmissionFence`, state, cutoff, and quarantine fields. All three keys contain the same literal `{gateway-connect-token-replay-v1}` hash tag and therefore share one Redis Cluster slot; matching [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md), the consume script receives `KEYS[1]=readiness`, `KEYS[2]=replay jti`, and `KEYS[3]=deny jti` and **must atomically validate readiness state, the signed fence and cutoff, and deny-marker absence, then create the replay marker in that same operation**. Replay and deny marker expiries are absolute at `token.exp + firemud.gateway.connectTokenClockSkewMs`; neither marker is refreshed, extended from consumption time, or replaced with a fixed 30-second TTL. The deployed clock-skew setting is the single `FIREMUD_GATEWAY_CONNECT_TOKEN_CLOCK_SKEW_MS` value, default `5000` ms and bounded to `0..5000` ms. -- The target deployment has one shared replay-continuity domain, so replay markers, deny markers, and the shared `replayAdmissionFence` are not tenant- or region-partitioned even though their physical keys use the fixed slot tag. Region- and tenant-scoped coordination resets must leave the Gateway replay and deny-marker prefixes and readiness record untouched and must not invalidate connect tokens solely because gameplay coordination in that narrower scope was reset. If either reset cannot prove that the shared replay domain was untouched and continuous, it escalates to the same shared quarantine rather than attempting a narrower fence. Migration and recovery use the owner-defined quarantine, exact old-prefix inventory/readback of `gateway:connect-token:jti:*`, named Coordination client/ACL cutover, target-key readback, and retention or explicit cleanup of old markers through their original acceptance window before reopening admission; the broad `gateway:connect-token:*` selector is forbidden for migration, reset, and ACL boundaries because it also matches tagged target keys; see [Redis Reset & Recovery](./system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). -- A cluster-scoped Coordination Redis reset, loss of replay or deny-marker continuity, uncertain failover, eviction, capacity breach, or durability-acknowledgement failure invalidates the shared replay domain. The reset drops or makes untrusted all replay markers, deny markers, and readiness state, advances the shared fence, rejects new first-party handshakes for at least the maximum gameplay-connect lifetime (`30 seconds`) plus two configured clock-skew intervals after the recorded detection cutoff, and reopens only after the configured disposable-marker plus `WAITAOF` proof establishes `DURABLE_REPLAY_CONSUME_ACK`. Existing WebSockets are not closed by replay-state reset alone; the broader cluster reset separately requires explicit gameplay-session invalidation. +- The target key shapes are `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::`. The readiness value carries `replayAdmissionFence`, state, cutoff, and quarantine fields. All four key families contain the same literal `{gateway-connect-token-replay-v1}` hash tag and therefore share one Redis Cluster slot; matching [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md), the normal consume script receives `KEYS[1]=readiness`, `KEYS[2]=replay jti`, and `KEYS[3]=deny jti` and **must atomically validate `OPEN` readiness, the signed fence and cutoff, and deny-marker absence, then create the replay marker in that same operation**. Normal consume is never called during quarantine. The separate recovery probe uses only the Gateway-generated disposable probe marker while readiness remains `QUARANTINED`, does not consume player JWT/`jti`/deny state, and cannot mutate shared readiness; the recovery coordinator alone may reopen after exact fenced proof and all owner gates. Replay and deny marker expiries are absolute at `token.exp + firemud.gateway.connectTokenClockSkewMs`; neither marker is refreshed, extended from consumption time, or replaced with a fixed 30-second TTL. The deployed clock-skew setting is the single `FIREMUD_GATEWAY_CONNECT_TOKEN_CLOCK_SKEW_MS` value, default `5000` ms and bounded to `0..5000` ms. See [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md) for the canonical recovery-probe binding and reopen sequence. +- The target deployment has one shared replay-continuity domain, so replay markers, deny markers, and the shared `replayAdmissionFence` are not tenant- or region-partitioned even though their physical keys use the fixed slot tag. Region- and tenant-scoped coordination resets must leave the Gateway replay and deny-marker prefixes and readiness record untouched and must not invalidate connect tokens solely because gameplay coordination in that narrower scope was reset. If either reset cannot prove that the shared replay domain was untouched and continuous, it escalates to the same shared quarantine rather than attempting a narrower fence. The current writer emits only the untagged replay marker `gateway:connect-token:jti:` through the generic Cache-bound client; it has no current deny-marker, readiness, or replay-fence writer. These are migration-only implementation gaps, not target state. Migration and recovery use the owner-defined quarantine, exact old-prefix inventory/readback of `gateway:connect-token:jti:*`, named Coordination client/ACL cutover, target-key readback, and retention or explicit cleanup of old markers through their original acceptance window before reopening admission; the broad `gateway:connect-token:*` selector is forbidden for migration, reset, and ACL boundaries because it also matches tagged target keys; see [Redis Reset & Recovery](./system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). +- A cluster-scoped Coordination Redis reset, loss of replay or deny-marker continuity, uncertain failover, eviction, capacity breach, or durability-acknowledgement failure invalidates the shared replay domain. The reset drops or makes untrusted all replay markers, deny markers, probe markers, and readiness state, advances the shared fence, and rejects new first-party handshakes for at least the maximum gameplay-connect lifetime (`30 seconds`) plus two configured clock-skew intervals after the recorded detection cutoff. While readiness remains `QUARANTINED`, the separate Gateway-owned probe must establish configured `WAITAOF` durability; only the recovery coordinator may reopen after exact fenced probe evidence and every other release gate. The probe alone never reopens admission. Existing WebSockets are not closed by replay-state reset alone; the broader cluster reset separately requires explicit gameplay-session invalidation. - A future partitioned replay deployment may narrow quarantine to a proven marker/fence domain only after its topology and reset contract establish that isolation. It must not be inferred from a tenant or region label in the current shared deployment. --- @@ -551,7 +555,7 @@ Redis is used primarily for non‑authoritative, transient data. The target-stat - In‑flight command queues and tick staging structures. - Tick locks and executor leases. -- Reconstructible timer, cooldown-expiry, and retry scheduling metadata (stored in milliseconds). +- Reconstructible timer, cooldown-expiry, and retry scheduling metadata use one explicitly tagged due domain per source, never a mixture or alias. Tick/game timers use `dueTickId` (stored as `due_tick_id` where the storage schema uses snake case); wall-clock timers use one immutable absolute `dueAt` in epoch milliseconds. When a wall-clock timer is admitted to a gameplay tick, the scheduler assigns a separate `due_tick_id` admission-order coordinate without changing its `dueAt` due domain. Tick IDs and epoch-millisecond values must never be numerically compared or aliased. - Gameplay session state and live coordination (session bindings, queue participation). - Best‑effort caches for hot‑path aggregates and chat history in Cache/Rate‑Limit Redis. - Automation queues and coordination hints that can be reconstructed from durable domain state. @@ -602,6 +606,7 @@ Key principles: - **`{tenantInstanceTag}` hash tag** - Instance-scoped coordination or automation projection keys use a canonical opaque hash tag placeholder `{tenantInstanceTag}` derived from ``. - The concrete string format is an implementation detail of shared key helpers; callers must not replace it with a tenant-only tag or append a second raw instance identifier. + - The live Automation queue builder currently concatenates raw nonblank string parts and does not prove delimiter/brace rejection or collision-safe canonical encoding. Until it adopts the shared encoded/length-prefixed tuple helper or proves canonical lowercase UUID parsing at every boundary, that builder is implementation drift and must not be treated as the canonical opaque tag. - **`{tenantGameplayTag}` hash tag** - Session-only gameplay keys use a canonical hash tag placeholder `{tenantGameplayTag}` derived from ``. @@ -622,8 +627,11 @@ Key principles: - **Coordination vs cache prefixes** - Canonical coordination prefixes (for example `tick:*`, `timer:*`, `retry:*`, `session:game:*`, `session:auth:token:*`, `session:auth:generation:*`, the target exact-result `session:connect-token:v1:tenant::account::scope::request:` family, `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, and `tick-executor-lease:*`) live **only** on Coordination Redis. The current legacy Account result map remains at the separate unversioned `session:connect-token:tenant::account::scope::request:` family and is not parsed as target. The shared `replayAdmissionFence` is a field in `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, not a physical prefix. The current generic Cache-bound writer's untagged `gateway:connect-token:*` replay marker is migration-only implementation drift, not a current canonical Coordination Redis prefix or authority. + - Gateway's recovery-only disposable marker family `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::` is a separately registered Coordination Redis prefix owned by Gateway. Its ACL and reset inventories are distinct from player `jti`, deny, and readiness data; see the target-only probe contract in [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md). - Cache and rate‑limit prefixes (for example `inventory:*`, `view:room-look:*`, `ratelimit:*`) live **only** on Cache/Rate‑Limit Redis. -- Coordination prefix ownership is normative: Account owns the live legacy `session:auth:account:*` and `session:auth:tenant:*` projections, the current legacy `session:connect-token:tenant::account::scope::request:` result-map pattern, the target `session:auth:token:*` exact-token registry, the target `session:auth:generation:*` authority-generation projections, and the target exact-input `session:connect-token:v1:tenant::account::scope::request:` issuance-result projections. The legacy result map and target exact-result family are physically isolated; the former remains unversioned legacy-only and is not target proof. Gateway's tagged Coordination replay authority is target-only: it owns the shared replay-domain exception `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness` carrying `replayAdmissionFence`; the current writer remains migration-only behavior that emits the untagged `gateway:connect-token:jti:*` marker through the generic Cache-bound client, with no current deny/readiness/fence writer. This target ownership does not grant gameplay-session, Account-auth, or general coordination ownership. Game Session owns the separately approved gameplay families under `session:game:*`, including `session:game:auth:issuer-generation:v1:`; it never owns the Account auth prefixes, and no wildcard `session:auth:*` grant is implied. Game Session also owns `tick:*`, `timer:*`, `retry:*`, and `tick-executor-lease:*`; it does not own or mutate the target-only, unimplemented Automation & Scripting families `automation:timer:*` or `script-scheduler:*`. The retired `automation:tick:*` staging path is not part of the live design or active prefix inventory. Automation & Scripting owns its current automation prefixes and the reserved target families once implemented; non-owner participation is contract-bound through approved helpers. See `design/architecture/decisions/adr-0009-coordination-redis-ownership-boundary.md`, with later canonical owner contracts including ADR 0029 defining the Gateway replay carrier. + +- Coordination prefix ownership is normative: Account owns the live legacy `session:auth:account:*` and `session:auth:tenant:*` projections, the target `session:auth:token:*` exact-token registry, the target `session:auth:generation:*` authority-generation projections, and the target `session:connect-token:v1:*` exact-input issuance-result projections. The current legacy result map remains a separate unversioned `session:connect-token:*` family and is owner-cleaned only after its TTL/retry horizon; both families remain Account-owned. Gateway owns only the shared replay-domain exception: `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, and the separately registered recovery-only `gateway:connect-token:{gateway-connect-token-replay-v1}:probe:*`; this does not grant gameplay-session, Account-auth, or general coordination ownership. Game Session owns the separately approved gameplay families under `session:game:*`, including `session:game:auth:issuer-generation:v1:`; it never owns the Account auth or connect-token issuance prefixes, and no wildcard `session:auth:*` grant is implied. Game Session also owns `tick:*`, `timer:*`, `retry:*`, and `tick-executor-lease:*`; it does not own or mutate the target-only, unimplemented Automation & Scripting families `automation:timer:*` or `script-scheduler:*`. The retired `automation:tick:*` staging path is not part of the live design or active prefix inventory. Automation & Scripting owns its current automation prefixes and the reserved target families once implemented, while its Cache/Rate-Limit families `automation:queue:*`, `automation:quota:*`, `automation:tenant-budget:*`, `automation:test:quota:*`, `automation:test:capacity:*`, and `automation:readiness:capacity:*` remain separate; non-owner participation is contract-bound through approved helpers. The shared `conflict:*` diagnostic family is Coordination-only, reset-tolerant, and non-authoritative: `common-data-runtime` owns the mutation helper, while Game Session and Entity Management own the producer scopes that call it. Its target deployed principals are distinct: `entity_coord_app` has the exact `~conflict:entity:*` grant and no `conflict:session:*` or other owner-family grant, while `gamesession_coord_app` has the exact `~conflict:session:*` grant in addition to its separately registered Game Session families and no `conflict:entity:*` grant. No shared principal, generic maintenance principal, or helper-library identity may cross those producer-owner boundaries. Current `conflict:entity::` and `conflict:session::` writes use the generic Redis client and separate `INCR`/`EXPIRE` calls with warning-only expiry failure; both endpoint placement and mutation shape are implementation drift. The target accepts only those registered producer kinds and canonical scope identifiers, permits one key per admitted producer scope, enforces a finite deployment key-cardinality cap with overflow sampled or aggregated rather than creating arbitrary keys, and uses a 300-second inactivity TTL unless an owner-approved profile states a shorter bound. The target uses named Coordination clients and these distinct `coord_app` principals only, never cache ACLs, and converges the mutation through a registered single-key atomic helper/script that performs both `INCR` and `PEXPIRE` on every accepted increment so the inactivity TTL is refreshed atomically. The existing `RedisAtomicOperations.incrementWithTtl` helper sets expiry only when the count is first created and therefore does not satisfy this sliding-inactivity contract unless it is extended; this is target guidance, not a claim that the current tracker implements it. The live Entity `TickLockServiceImpl` `tick:lock::` family is an unscoped implementation-drift writer, not a second Game Session authority; it remains fenced/unregistered for target reset and admission until routed through the canonical full-runtime-scope helper. See `design/architecture/decisions/adr-0009-coordination-redis-ownership-boundary.md`, with later canonical owner contracts including ADR 0029 defining the Gateway replay carrier. + - New prefixes must be registered in the canonical catalogs: - Coordination prefixes and their reset policies belong in the reset policy matrix and any extended catalogs in `system-architecture-redis-reset-and-recovery.md`. - Cache/rate-limit prefix details belong in the [Cache/Rate-Limit Key Catalog](./system-architecture-redis-cache-reference.md#cacherate-limit-key-catalog), including their correctness class and reset tolerance; cache policy remains in [Redis Cache & Rate Limiting](./system-architecture-redis-cache.md). @@ -649,7 +657,7 @@ If a proposed coordination pattern cannot satisfy this checklist, it should be t ### Coordination Key Examples -This table lists representative coordination keys and their responsibilities. Full semantics live in service‑specific docs and Lua descriptors, but these examples provide a quick mental model: +This table lists representative coordination keys and their responsibilities. Full semantics live in service‑specific docs and Lua descriptors, but these examples provide a quick mental model. Logical, API, and domain prose uses `regionEpoch`; the `tick:*:meta` hash and explicit storage/schema fields use `region_epoch`; serialized scheduler payloads use `regionEpoch`, while the tick-event offset record uses `region_epoch` as defined in [Tick System](./system-architecture-ticks.md#tick-commit-definition-heartbeat-watermark). These spellings represent the same exact epoch, not alternate fields or timelines. Other serialized Redis payload examples use canonical camelCase; the owner-defined offset field and explicit Redis hash/storage or SQL/domain fields retain their stated snake_case spellings, not alternate payload schemas. | Redis Key | Description | | --- | --- | @@ -666,11 +674,11 @@ This table lists representative coordination keys and their responsibilities. Fu | `session:game:index:issuer:{issuerIndexLayoutTag}::` | Global-per-issuer bounded hash of active/provisional binding references and captured issuer generations across tenants, maintained by Game Session through the versioned-layout repair/CAS and durable coverage-ack protocol and swept across the finite configured partition range for issuer cutoffs. | | `retry:{tenantRegionTag}` | Retry queue for failed actions, keyed by `next_eligible_tick_id` on the target region timeline (not wall-clock due time). | | `tick-executor-lease:{tenantRegionTag}` | Redis-local liveness key for the active tick executor. Its value is an opaque token checked by lease Lua; durable ownership and handoff semantics are owned by [Tick System: Region Authority and Tick Executor](./system-architecture-ticks.md#region-authority-and-tick-executor). | -| `timer:{tenantRegionTag}` | Sorted set of timers for a region; score is expiration timestamp (ms), members encode entity/effect metadata. | +| `timer:{tenantRegionTag}` | Typed due-domain projection for region timers. Every source carries exactly one due-domain tag: tick/game timers use `dueTickId`, while wall-clock timers retain one immutable absolute `dueAt`; a wall-clock source may receive a separately assigned `due_tick_id` only as its gameplay-tick admission-order coordinate. Storage/indexing must preserve the tag and must never numerically compare or alias tick IDs and epoch-millisecond values. The due-point and ordering owner is [Tick Execution Flow: Work Ordering Inputs](./system-architecture-tick-execution-flows.md#work-ordering-inputs-adr-0065). | | `remote:{tenantInstanceTag}:` | Best‑effort, TTL-bounded hint marker scoped to the complete `` identity for cross‑region follow‑ups (durable follow‑ups live in PostgreSQL). Default `remote_hint_ttl_ms = 60_000`; expiry/missing keys affect latency only. Tenant/cluster reset tooling resolves game instances from the durable scope inventory and scans one `remote:{tenantInstanceTag}:*` pattern per instance; no tenant-only remote key family exists. | | `route:{tenantRegionTag}:gamesession` | Reserved for a potential future gameplay routing view for ` → shardTarget`. Per ADR 0007, lease-aware edge admission and a client-visible shard handoff signal are not part of the current edge contract; do not implement Gateway consumption of this mapping without a dedicated sharding/routing design update. | | `tick-events:{tenantRegionTag}` | **Target-only, currently unavailable.** Best‑effort per-region tick event stream; the Game Session producer is not currently implemented/proven. Streams are retention-capped (default `tick_events_maxlen = 2048` per region); once implemented, consumers treat trimmed history as normal truncation and bootstrap from committed heartbeats/RegionStatus. | -| `tick-events-offset:{tenantRegionTag}:{consumerId}` | **Target-only, currently unavailable.** Per-consumer offset (typically Redis Stream entry ID), owned by the registered Automation consumer path. Each value must include `{tenantId, gameInstanceId, regionId, consumerId, region_epoch, latestTickId, streamOffset}`; consumers compare `region_epoch` with the current control-plane epoch and discard that value before reuse on mismatch. | +| `tick-events-offset:{tenantRegionTag}:{consumerId}` | **Target-only, currently unavailable.** Per-consumer offset (typically Redis Stream entry ID), owned by the registered Automation consumer path. Each serialized value must include `{tenantId, gameInstanceId, regionId, consumerId, region_epoch, latestTickId, streamOffset}`; consumers compare its stored `region_epoch` with the current control-plane `regionEpoch` and discard that value before reuse on mismatch. The producer and reader remain unimplemented; this row defines no current wire implementation. | | `tick-events-lease:{tenantRegionTag}` | **Target-only, currently unavailable.** Best-effort lease to avoid duplicate tick-event consumption work by registered observers. Once implemented, it is safe to drop and consumers reacquire after restarts/resets. | | `automation:timer:{tenantRegionTag}` | **Target-only, once implemented.** Reserved for the region-scoped Automation & Scripting timer index for `onInterval` and timer coordination. Stored entries must remain instance-aware in payload and durable identity (`gameInstanceId`, and plugin identifiers when applicable) even though the Redis key is region-scoped for slotting and reset targeting. No current key or reset operation is defined for this unimplemented target projection. | | `script-scheduler:{tenantRegionTag}:lastTickId` | **Target-only, once implemented.** Reserved for the Automation & Scripting derived discovery hint for “every N ticks” triggers. Its value will contain `{regionEpoch, latestTickId}` and be rejected/rebuilt when the stored epoch differs from the authoritative epoch. It will not store or own `streamOffset`; `tick-events-offset:{tenantRegionTag}:{consumerId}` is the sole event-stream offset record for each consumer. Durable automation schedules, quotas, and trigger-instance de-duplication live in PostgreSQL; this unimplemented key is not the source of truth for which scripts should eventually run or whether a due trigger was already emitted. No current key or reset operation is defined. | @@ -687,7 +695,7 @@ Redis features and assumptions in FireMUD must work across both single‑instanc | --- | --- | --- | --- | | Single‑node with AOF (coordination) | **Supported.** All coordination prefixes (`tick:*`, `timer:*`, `retry:*`, `session:game:*`, `session:auth:token:*`, `session:auth:generation:*`, `tick-executor-lease:*`, etc.) and shard‑local Lua patterns apply. Measured unreplicated-write exposure and AOF replay guarantees assume this profile or better. | **Supported** on a separate Cache/Rate‑Limit deployment (distinct process or container). | Recommended baseline for `dev_local` and `hobby_self_hosted` profiles. | | Single‑node without AOF (ephemeral coordination) | **Supported only for explicitly labelled one-shot test/CI stacks** (hosted `pr-preview` is excluded) that opt out of measured unreplicated-write SLOs and replay guarantees. Coordination keys are disposable and must be reset‑tolerant. | **Supported** on a separate Cache/Rate‑Limit deployment by default. An explicitly labelled one-shot test/CI stack may temporarily collapse both roles under ADR 0171's narrow exception. | Not appropriate for environments where role-isolation, tick replay, measured loss-window SLOs, or long‑lived coordination logs are required. | -| Redis Cluster (coordination) | **Supported** provided all coordination Lua scripts obey shard‑local rules using `{tenantRegionTag}` for region/tick flows, `{tenantInstanceTag}` for instance-scoped Coordination projections (currently `remote:{tenantInstanceTag}:*` remote hints), `{tenantGameplayTag}` for tenant-scoped session flows, `{issuerIndexLayoutTag}` for one issuer-layout partition, and the fixed `{gateway-connect-token-replay-v1}` for Gateway replay-admission flows. Multi-key coordination scripts must only touch keys that share one hash tag and slot; the reserved Automation & Scripting families `automation:timer:*` and `script-scheduler:*` remain target-only and unimplemented, while the retired `automation:tick:*` path is not a current family. | **Supported** for cache/rate‑limit workloads; rate‑limit prefixes (`ratelimit:*`) are treated as single‑key operations without cross‑slot atomicity. | Cluster deployment requires strict adherence to the canonical family/tag rules in [Key Naming and Shard Discipline](#key-naming-and-shard-discipline), including the issuer-layout partition and instance-scoped Coordination projections. | +| Redis Cluster (coordination) | **Supported for registered workloads** provided every registered coordination Lua script uses its applicable hash tag: `{tenantRegionTag}` for region/tick, maintenance, and automation-coordination flows; `{tenantInstanceTag}` for instance-scoped automation and remote-hint flows; `{tenantGameplayTag}` for session-only gameplay flows; the fixed `{gateway-connect-token-replay-v1}` for Gateway replay-admission flows; and `{issuerIndexLayoutTag}` for issuer-index partition flows. Multi-key coordination scripts must only touch keys that share one exact registered hash tag and slot; approved global or untagged single-key/reconciliation exceptions remain subject to their owner contracts and do not establish clustered multi-key support. The reserved Automation & Scripting families `automation:timer:*` and `script-scheduler:*` remain target-only and unimplemented, while the retired `automation:tick:*` path is not a current family. | **Target/registered workloads only.** Canonical single-bucket rate-limit operations and cache families with a registered scope/tag are supported without cross-slot atomicity. The current Automation readiness and dry-run capacity reservations use canonical shared hash tags for each counter/lease pair, so those pairs are not inherently cross-slot; they remain unregistered/unsupported as a complete clustered workload until central ownership inventory, canonical key encoding, and durable charge/admission proof are established. Current legacy `ipconn:
` + `sessionip:` registration remains unsupported because it can fail `CROSSSLOT`. | Cluster deployment requires strict adherence to hash-tag and slotting rules described in [Key Naming and Shard Discipline](#key-naming-and-shard-discipline), including the issuer-layout and instance-scoped automation families; a general Cache/Rate-Limit support claim must not be used as proof for unregistered current families. | In all non-ephemeral topologies: diff --git a/design/architecture/system-architecture-scripting-contracts.md b/design/architecture/system-architecture-scripting-contracts.md index 01897b2efb..ca6a5544ff 100644 --- a/design/architecture/system-architecture-scripting-contracts.md +++ b/design/architecture/system-architecture-scripting-contracts.md @@ -22,7 +22,7 @@ The current evaluator supports a bounded emitted-command collection per work ite - A **script work item** is the post-DSL output staged by Automation & Scripting (domain commands + metadata such as `scriptId`, `scriptPatchVersion`, and `scriptEventId`). It preserves the immutable source Trigger Identity, including the source `regionId` and `regionEpoch` when applicable; any enqueue or current-routing identity is carried separately and must not overwrite the source trigger fields. - A **tick command** is a unit of work that has been accepted into an entity’s tick queue by Game Session and will be executed under tick locks and replay semantics. - **Target-state command handoff:** Every script work item that emits gameplay commands receives one stable `automationDispatchId`, and each emitted command carries a deterministic `commandOrdinal` under that dispatch. The pair is only the final discriminator within the complete Command-Handoff Identity; one handler may fan out into multiple commands, and a pair without its complete source/target runtime scope is not a command identity. -- **Target-state command handoff:** The complete Command-Handoff Identity is the canonical identity for evaluated child-dispatch handoff deduplication, execution-fence reporting, replay selection, and correlation. It is not the downstream effect guard: authoritative effect idempotency uses the root `EffectId`, typed operation, exact target aggregate, and stored/compared immutable request digest, with conflicts failing closed. The `(automationDispatchId, commandOrdinal)` pair is only a display suffix and is insufficient by itself; `automationDispatchId` identifies a dispatch group, and `scriptEventId` alone must never identify a fan-out command. See [Implementation Status](#implementation-status) for the current evaluator boundary. +- **Target-state command handoff:** The complete Command-Handoff Identity is the canonical identity for evaluated child-dispatch handoff deduplication, execution-fence reporting, replay selection, and correlation. It is not the downstream effect guard: authoritative effect idempotency uses the persisted mutation `EffectId` (the root `EffectId` for a root mutation or the generated child's persisted `EffectId` for a child mutation), typed operation, exact target aggregate, and stored/compared immutable request digest, with any enclosing `rootEffectId` retained only as lineage and reconciliation context and conflicts failing closed. Participant-guard identity follows the owner-classified rules in [Transaction Strategies](./system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory): S1/S2 use the `(tenantId, playableStateNamespaceId)` partition, and only explicitly classified S3 uses `(tenantId, gameInstanceId)`; `playableStateScope` and `requestDigest` are exact-validated evidence, not uniqueness dimensions, and unclassified families fail before admission. The `(automationDispatchId, commandOrdinal)` pair is only an identity suffix and is insufficient by itself; `automationDispatchId` identifies a dispatch group, and `scriptEventId` alone must never identify a fan-out command. See [Implementation Status](#implementation-status) for the current evaluator boundary. Target-state handoff linkage uses the complete Command-Handoff Identity: complete source/target runtime scope, `automationDispatchId`, and `commandOrdinal`. The current implementation is narrower than this target: because Trigger Identity and `commandOrdinal` are not carried end to end, current live linkage and retry diagnostics use `outboxWorkItemId`, `gameSessionCommandId`, available `automationDispatchId`, and `script_event_audit`. This fallback is not complete command-level deduplication or replay evidence. The remaining gap is tracked under `AS-1.5` and its Game Session handoff dependency in the [automation and scheduler runtime tracker](../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status). @@ -49,7 +49,7 @@ To make script patch rollback meaningful: - On execution, Game Session must enforce a **version fence**: - If a command’s `scriptPatchVersion` does not match the game instance’s currently pinned `scriptPatchVersion`, Game Session must not execute it. - If a command’s `scriptPinEpoch` does not match the game instance’s current epoch, Game Session must not execute it, even when the patch version is identical. - - **Target state:** rejection must retain the complete applicable Trigger Identity (`tenantId`, `gameInstanceId`, `playableStateScope`, `regionId`, `regionEpoch`, `entityId`, `scriptId`, `eventType`, `eventSchemaVersion`, `scriptPatchVersion`, `scriptPinEpoch`, `scriptEventId`, `isDryRun`, plus plugin/binding and scheduler fields when applicable), together with the paired `scriptPinControlPlaneRequestId` as required owner evidence/correlation and the complete Command-Handoff Identity, including `outboxWorkItemId` as parent correlation and optional distinct target fields (`targetGameInstanceId`, `targetPlayableStateScope`, `targetRegionId`, `targetRegionEpoch`), so operators can diagnose exactly which fan-out command was dropped. A child rejection must not be reduced to one handler-level disposition. The live fallback records the narrower work-item, command, and available dispatch fields in the current handoff/audit surfaces until `AS-1.5` is complete. + - **Target state:** rejection must retain the complete applicable parent event-scope/Trigger Identity (`tenantId`, `gameInstanceId`, `playableStateNamespaceId`, `regionId`, `regionEpoch`, `entityId`, `scriptId`, `eventType`, `eventSchemaVersion`, `scriptPatchVersion`, `scriptPinEpoch`, `scriptEventId`, `isDryRun`, plus producer-derived `sourceService` when the event is custom or service-specific, and plugin/binding and scheduler fields when applicable), together with the paired `scriptPinControlPlaneRequestId` as required owner evidence/correlation. It must separately retain the complete Command-Handoff Identity: required source runtime fields, dispatch/ordinal, and applicable distinct target runtime fields (`targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetRegionId`, `targetRegionEpoch`); parent `outboxWorkItemId` is retained only as correlation and is not part of that identity. The server-derived source and target `playableStateScope` values remain separately persisted, exact-validated policy/routing/authorization/fence evidence and are not identity fields. This evidence lets operators diagnose exactly which fan-out command was dropped; a child rejection must not be reduced to one handler-level disposition. The live fallback records the narrower work-item, command, and available dispatch fields in the current handoff/audit surfaces until `AS-1.5` is complete. The canonical [Table 2 identity owner](./system-architecture-scripting-normative-contract-tables.md#table-2-command-handoff-identity) defines the exact identity fields. - Parent `outboxWorkItemId` and Trigger Identity fields are correlation-only; they are excluded from child uniqueness, deduplication, and replay selection (see the [normative identity tables](./system-architecture-scripting-normative-contract-tables.md#table-2-command-handoff-identity)). - Rejected entries must be removed or moved to a bounded dead-letter store with explicit `maxAge`/`maxRows` and alert-backed cleanup cadence. - Before schedule admission resumes under a new `scriptPinEpoch`, durable or resumable-idempotent reconciliation must fence or terminalize pending old-epoch occurrences and claims, and every old-epoch enqueue attempt must fail. Rollback may still cancel or purge displaced rows asynchronously for bounded resource use, but that cleanup is not the admission or mutation correctness barrier. The epoch fence at each persistence, handoff, staging, replay, and final effect boundary remains authoritative; ordinary player commands and ticks continue unless an explicitly declared unfenced effect requires an exceptional pause. @@ -60,10 +60,10 @@ To make script patch rollback meaningful: `scriptEventId` identifies the handler trigger, but it is not the complete idempotency token for “run a handler for this trigger”. Scripting idempotency must use every applicable field in the full Trigger Identity defined in the normative contract tables; `scriptEventId` alone is insufficient. -- **Entity-scoped events** (`onSpawn`, `onEnterRegion`, `onCommand`, custom events) must use every applicable field in the full Trigger Identity, including `tenantId`, `gameInstanceId`, `playableStateScope`, `regionId`, `regionEpoch` when gameplay/runtime-scoped, `entityId`, `scriptId`, `eventType`, `eventSchemaVersion`, the exact `scriptPatchVersion`/`scriptPinEpoch` execution tuple for gameplay/runtime work, `scriptEventId`, and `isDryRun`. The paired nonblank `scriptPinControlPlaneRequestId` remains required owner evidence and is validated against the authoritative owner, but is not a Trigger Identity component. Plugin handlers additionally require `pluginId`, `pluginVersionId`, and the signed-bundle `bindingId`. These fields, not `scriptEventId` alone, define the unique trigger identity; tenant-readiness `onLoad` retains its explicit pre-instance-pin exception. +- **Entity-scoped events** (`onSpawn`, `onEnterRegion`, `onCommand`, custom events) must use every applicable field in the full Trigger Identity, including `tenantId`, `gameInstanceId`, `playableStateNamespaceId`, `regionId`, `regionEpoch` when gameplay/runtime-scoped, `entityId`, `scriptId`, `eventType`, `eventSchemaVersion`, the exact `scriptPatchVersion`/`scriptPinEpoch` pair for gameplay/runtime work, `scriptEventId`, and `isDryRun`. The paired nonblank `scriptPinControlPlaneRequestId` remains required owner evidence and is validated against the authoritative owner, but is not a Trigger Identity component. The server-derived `playableStateScope` is persisted and exact-validated as policy/routing/authorization/fence evidence, but is not a uniqueness discriminator. Plugin handlers additionally require `pluginId`, `pluginVersionId`, and the signed-bundle `bindingId`. These fields, not `scriptEventId` alone, define the unique trigger identity; tenant-readiness `onLoad` retains its explicit pre-instance-pin exception. - For custom or service-specific events, `sourceService` is derived from the authenticated producer/workload identity, participates in the event-scope dedupe identity, and is persisted unchanged in the ingress and handler audit records. It is not a caller-selected identity field; the canonical derivation and applicability rules are owned by the normative contract tables. - **Scheduler events** (`onInterval`, `onTimerExpire`) must use every applicable Trigger Identity field plus the due point and `triggerMode` so leader catch-up and retries do not double-fire. For tick-cadence scheduling (for example `onInterval` configured in ticks), the due point must be expressed as `dueTickId` in the canonical tick timeline. For wall-clock timers, the due point must be expressed as absolute `dueAt` and still include `regionEpoch` to fence across coordination resets. -- Scheduler identities and durable timer state must also include `gameInstanceId` and `playableStateScope` for gameplay/runtime schedules. For plugin timers, `pluginId`, `pluginVersionId`, and the binding-scoped `bindingId` are additionally required so multiple bindings, instances, and plugin-version rollbacks cannot alias timer state. +- Scheduler identities and durable timer state must also include `gameInstanceId` and `playableStateNamespaceId` for gameplay/runtime schedules; `playableStateScope` is separately persisted exact-validated policy/routing/authorization/fence evidence and is not an identity dimension. For plugin timers, `pluginId`, `pluginVersionId`, and the binding-scoped `bindingId` are additionally required so multiple bindings, instances, and plugin-version rollbacks cannot alias timer state. - After event fan-out, each resolved handler is a separate dedupe and audit unit. A plugin handler is uniquely identified by the full applicable Trigger Identity plus `(pluginId, pluginVersionId, bindingId)`; `pluginId` or `pluginVersionId` alone is never sufficient when one plugin version contributes multiple bindings. The same handler-scoped identity governs `script_event_audit`, quota attribution, timer ownership, and binding-scoped cleanup. - **Tenant-readiness `onLoad` events** apply only to embedded patch scripts; linked-plugin bindings are excluded from tenant-readiness `onLoad`. Plugin initialization, binding validation, and activation remain in the independently versioned, instance-scoped plugin lifecycle for `(tenantId, gameInstanceId, pluginId)`. These events intentionally omit `gameInstanceId`, `playableStateScope`, `regionId`, `regionEpoch`, and `entityId` because they run before any instance pins the patch. Automation & Scripting generates `scriptEventId` deterministically from the preimage ``. The persisted dedupe/audit Trigger Identity is then ``. - `onLoad` handler code may not create durable or semi-durable shared effects, including gameplay/tick commands or handler-owned records in shared stores. Platform-owned execution and readiness state, including required `script_event_audit` metadata, is permitted and required to claim, fence, record, and complete readiness; it is not a handler-created shared effect. diff --git a/design/architecture/system-architecture-scripting-control-plane-api.md b/design/architecture/system-architecture-scripting-control-plane-api.md index 0d88c81dc2..de5a5d5f36 100644 --- a/design/architecture/system-architecture-scripting-control-plane-api.md +++ b/design/architecture/system-architecture-scripting-control-plane-api.md @@ -555,10 +555,11 @@ Inputs: - `tenantId` - Optional `gameInstanceId` - Optional `scriptPatchVersion` -- Optional source runtime scope filters (`playableStateScope`, `regionId`, `regionEpoch`) +- Optional source runtime identity filters (`playableStateNamespaceId`, `regionId`, `regionEpoch`); `playableStateScope` is a separately validated evidence filter +- The complete source runtime identity for each row is `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch)`. `tenantId` and optional `gameInstanceId` are the inherited top-level filters above; the source-specific filters narrow that identity and do not make its persisted fields optional. - Optional `workItemId` - Optional `handoffOutcome` -- Optional target runtime scope filters (`targetGameInstanceId`, `targetPlayableStateScope`, `targetRegionId`, `targetRegionEpoch`) +- Optional target runtime identity filters (`targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetRegionId`, `targetRegionEpoch`); `targetPlayableStateScope` is separately validated target evidence - Optional durable remote-id filters (`remoteCoordinatorId`, `remoteFollowupId`) - Optional origin identity filters (`scriptId`, `pluginId`, `automationDispatchId`) - Optional `changedAfter` / `changedBefore` @@ -568,17 +569,17 @@ Inputs: Outputs: -- ordered event rows containing `eventId`, `tenantId`, source runtime scope (`gameInstanceId`, `playableStateScope`, `regionId`, `regionEpoch`), exact source owner tuple `scriptPatchVersion`/`scriptPinEpoch`/`scriptPinControlPlaneRequestId`, `scriptId`, optional plugin identity tuple `(pluginId, pluginVersionId, bindingId)` and target-state `pluginActivationEpoch`/captured `lifecycleRevision`; absent tuple fields are explicit and must not be inferred from epoch/revision, `workItemId`, `commandOrdinal`, `automationDispatchId`, target-state `handoffRequirement`, optional `gameSessionCommandId`, distinct target runtime scope when applicable (`targetGameInstanceId`, `targetPlayableStateScope`, `targetRegionId`, `targetRegionEpoch`), optional remote follow-up ids (`remoteCoordinatorId`, `remoteFollowupId`), current owned target runtime scope (`currentTargetRuntimeGameInstanceId`, `currentTargetRuntimeRegionId`, `currentTargetRuntimeRegionEpoch`) plus the current owned routing bundle (`currentTargetRuntimePlayableStateScope`, `currentTargetRuntimeWorldSlug`, `currentTargetRuntimeRealmSlug`, `currentTargetRuntimePointerVersion`) and stale-scope/routing signaling, later Game Session gameplay-command execution truth (`gameplayCommandExecutionOutcome`, `gameplayCommandGameplayResult`, failure details, and remote-state tail), `targetEntityId`, rendered `emittedCommandText`, `handoffOutcome`, `handoffReason`, and `observedAt` +- **Target-state output:** ordered event rows containing `eventId` and the complete source Command-Handoff runtime identity (`tenantId`, `gameInstanceId`, `playableStateNamespaceId`, `regionId`, `regionEpoch`), separately validated source `playableStateScope` evidence, exact source owner tuple `scriptPatchVersion`/`scriptPinEpoch`/`scriptPinControlPlaneRequestId`, `scriptId`, optional plugin identity tuple `(pluginId, pluginVersionId, bindingId)` and target-state `pluginActivationEpoch`/captured `lifecycleRevision`; absent tuple fields are explicit and must not be inferred from epoch/revision, `workItemId`, `commandOrdinal`, `automationDispatchId`, target-state `handoffRequirement`, optional `gameSessionCommandId`, distinct target Command-Handoff runtime identity when applicable (`targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetRegionId`, `targetRegionEpoch`), separately validated target `targetPlayableStateScope` evidence, optional remote follow-up ids (`remoteCoordinatorId`, `remoteFollowupId`), current owned target runtime identity (`currentTargetRuntimePlayableStateNamespaceId`, `currentTargetRuntimeGameInstanceId`, `currentTargetRuntimeRegionId`, `currentTargetRuntimeRegionEpoch`) plus the current owned routing bundle (`currentTargetRuntimePlayableStateScope`, `currentTargetRuntimeWorldSlug`, `currentTargetRuntimeRealmSlug`, `currentTargetRuntimePointerVersion`) and stale-scope/routing comparison against the persisted distinct target namespace/scope and admitted target routing bundle, later Game Session gameplay-command execution truth (`gameplayCommandExecutionOutcome`, `gameplayCommandGameplayResult`, failure details, and remote-state tail), `targetEntityId`, rendered `emittedCommandText`, `handoffOutcome`, `handoffReason`, and `observedAt` Contract rules: - This is the per-command observability companion to work-item-level audit and dead-letter reads. Multi-command work items must not collapse handoff chronology into one row. For plugin-backed rows, the captured `pluginActivationEpoch` and `lifecycleRevision` are retained as fence evidence rather than inferred from current plugin state. -- Automation must persist one durable handoff event per attempted emitted command, including pre-handoff rollback fencing and Game Session acceptance/rejection outcomes. -- `automationDispatchId` is the canonical low-cardinality correlation key between Automation handoff history and the Game Session gameplay-command ledger; metrics still must not label by it. Operator/debug reads can resolve the Game Session side either from the returned `gameSessionCommandId` or from the full automation identity tuple `(tenantId, gameInstanceId, regionId, regionEpoch, automationDispatchId)` when the command id is not yet known to the caller. +- **Target-state rule:** Automation must persist one durable handoff event per attempted emitted command, including pre-handoff rollback fencing and Game Session acceptance/rejection outcomes. +- `automationDispatchId` is a correlation key between Automation handoff history and the Game Session gameplay-command ledger; it is not a low-cardinality value and metrics must not use it as a label. Operator/debug reads can resolve the Game Session side either from the returned `gameSessionCommandId` or from the full automation identity tuple `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch, automationDispatchId, commandOrdinal)`, plus the applicable distinct target identity `(targetGameInstanceId, targetPlayableStateNamespaceId, targetRegionId, targetRegionEpoch)`, when the command id is not yet known to the caller; `playableStateScope` remains separately validated evidence. - Operators use this read to answer which emitted command ordinal reached Game Session, which rendered command text, target entity, and target runtime scope it addressed, whether it stayed local or became a durable remote follow-up, and whether the failure happened before handoff, at Game Session admission, or after later gameplay-side execution disposition. - Because remote follow-up legs are now durable first-class runtime rows, this read must support direct filtering by target runtime scope, remote coordinator/follow-up ids, and origin script/plugin/dispatch identity rather than assuming one bulk history scan plus client-side correlation. -- Source `playableStateScope`, `regionId`, `regionEpoch`, and exact `scriptPinEpoch` are the persisted source Trigger/Command-Handoff Identity fields. `targetPlayableStateScope` and the other `target*` scope fields are distinct optional target-state fields used only when the handoff targets a different runtime scope; they must not be inferred from source scope. These complete fields are target-state only: the current live handoff proto, storage, and read remain narrower and do not establish live support for this contract. -- The read must also expose the current owned target runtime scope and routing bundle from Game Session when the target instance still exists, so operators can see directly whether the persisted target runtime scope or admitted routing bundle has gone stale without a separate ownership-status lookup. +- The persisted source and optional target fields follow the [canonical Command-Handoff Identity](./system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state): the complete source identity is inherited `tenantId` and `gameInstanceId` plus source `playableStateNamespaceId`, `regionId`, and `regionEpoch`; the distinct target adds `targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetRegionId`, and `targetRegionEpoch` only when applicable, together with the dispatch and ordinal. Source and target `playableStateScope` values are separately persisted, exact-validated policy/routing/authorization/fence evidence and are excluded from identity. These complete fields are target-state only: the current live handoff proto, storage, and read remain narrower and do not establish live support for this contract. +- The read must also expose the current owned target runtime identity and routing bundle from Game Session when the target instance still exists, so operators can compare `currentTargetRuntimePlayableStateNamespaceId` and the current scope/routing bundle against the persisted distinct target identity and admitted target bundle, preserving same-target semantics without a separate ownership-status lookup. - When `gameSessionCommandId` is known, the read should also expose the later Game Session gameplay-command execution outcome instead of stopping at handoff-time admission, so operator diagnostics can stay on one handoff-history surface through local and remote gameplay execution tails. #### `CancelPendingWorkItemsForPluginVersion` @@ -658,15 +659,15 @@ Inputs: Outputs: - **Current live output:** instance-scoped schedule entries include the observed exact `scriptPatchVersion`/`scriptPinEpoch` pair and associated owner request identity; they remain a narrower projection because namespace, staleness, and full scheduler identity fields are target-only. -- **Target-state output:** instance-scoped schedule entries contain the exact `scriptPatchVersion` and `scriptPinEpoch`, `scriptId`, plugin owner metadata, persisted `playableStateNamespaceId` and resolved `playableStateScope`, `scheduleDefinitionId`, event type, cadence, scheduler priority tag, target-scope identity (`targetScopeType`, `targetScopeId`), binding priority/exclusivity flags, materialization status, due-point fields, observed runtime version id, the pin operation's `controlPlaneRequestId`, pin observation time, row timestamps, and the current owned runtime scope (`currentRuntimePlayableStateNamespaceId`, `currentRuntimeGameInstanceId`, `currentRuntimeRegionId`, `currentRuntimeRegionEpoch`) plus the current owned routing bundle (`currentRuntimePlayableStateScope`, `currentRuntimeWorldSlug`, `currentRuntimeRealmSlug`, `currentRuntimePointerVersion`) and stale-namespace/scope/routing signaling beside the persisted scheduler row evidence. +- **Target-state output:** instance-scoped schedule entries contain the exact `scriptPatchVersion` and `scriptPinEpoch`, `scriptId`, plugin owner metadata, persisted identity `playableStateNamespaceId` plus separately validated `playableStateScope` evidence, `scheduleDefinitionId`, event type, cadence, scheduler priority tag, target-scope identity (`targetScopeType`, `targetScopeId`), binding priority/exclusivity flags, materialization status, due-point fields, observed runtime version id, the pin operation's `controlPlaneRequestId`, pin observation time, row timestamps, and the current owned runtime scope (`currentRuntimePlayableStateNamespaceId`, `currentRuntimeGameInstanceId`, `currentRuntimeRegionId`, `currentRuntimeRegionEpoch`) plus the current owned routing bundle (`currentRuntimePlayableStateScope`, `currentRuntimeWorldSlug`, `currentRuntimeRealmSlug`, `currentRuntimePointerVersion`) and stale-namespace/scope/routing signaling beside the persisted scheduler row evidence. Contract rules: - This is a read-only operator/debugging surface for the first durable scheduler substrate below Redis timer indexes. - The live implementation must report tick-aligned schedules honestly as not-yet-advanced when no heartbeat-derived due point exists; it must not invent synthetic tick coordinates. -- Reconciliation across repins is keyed by stable `scheduleDefinitionId` plus plugin owner metadata and binding target identity, not by inferred semantic similarity. +- Reconciliation across repins uses the canonical stable continuity key `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, playableStateNamespaceId, targetScopeType, targetScopeId}`. Plugin ownership and binding metadata must resolve to and exact-match that complete immutable schedule identity; `scheduleDefinitionId` alone, a semantic similarity inference, or a binding without the namespace cannot select continuity. - The read must also expose the current owned runtime scope from Game Session when the instance still exists so operators can tell directly whether persisted scheduler scope has gone stale without a second runtime-state lookup. -- `playableStateNamespaceId` is immutable non-identity scope evidence, not a schedule, trigger, or command identity field. Missing or mismatched namespace evidence fails closed during materialization, due-candidate claim, retry, and reconciliation and remains visible on this read rather than being inferred or refreshed. +- **Target-state contract:** `playableStateNamespaceId` is the immutable playable-state identity/allocation dimension for applicable schedule, trigger, and command identities; `playableStateScope` remains separately persisted, exact-validated policy/routing/authorization/migration-fence evidence. Missing or mismatched namespace or scope evidence fails closed during materialization, due-candidate claim, retry, and reconciliation and remains visible on this read rather than being inferred or refreshed. See the [canonical Trigger Identity and Command-Handoff Identity tables](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). #### `ListScriptTimerAuditEvents` @@ -692,7 +693,7 @@ Contract rules: - The live implementation is sourced from durable `script_event_audit` rows, not reconstructed from metrics or volatile queue indexes. - The current implementation exposes both timer-fired work that reached durable work-item persistence and scheduler candidate decisions persisted as `SCHEDULE_DROPPED` through this read. In target state, the separate scheduler candidate-audit surface is authoritative for append-only candidate history; current `script_event_audit` rows must not be interpreted as that target surface. - The read must also expose the current owned runtime scope from Game Session when the instance still exists so operators can distinguish stale timer history from current-timeline timer activity without a second runtime-state lookup. -- Timer audit retains `playableStateNamespaceId` as the namespace evidence validated at claim/admission time. Missing or mismatched namespace evidence fails closed before firing and is never repaired by a current-owner read. +- **Target-state contract:** Timer audit retains `playableStateNamespaceId` as the identity field and `playableStateScope` as separately validated evidence from claim/admission time. Missing or mismatched namespace or scope evidence fails closed before firing and is never repaired by a current-owner read; the current output remains the narrower projection described above. #### `ListScriptDeadLetters` @@ -742,9 +743,9 @@ Contract rules: - For plugin-backed work, the recovery claim and attempt capture the exact `(pluginActivationEpoch, lifecycleRevision)` fence in addition to the script pin tuple. Work that references a revocable component also retains the applicable component-revocation security-policy fence as an independent recovery input; neither plugin lifecycle evidence nor ordinary component-policy evidence substitutes for it. Claim acquisition and each pre-evaluation/dispatch revalidation compare both lifecycle values with current owner evidence; a `lifecycleRevision` mismatch outside ADR 0119's same-epoch `DRAINING` predecessor eligibility is rejected with `plugin_binding_mismatch`, while `plugin_disabled` remains reserved for a lifecycle transition that invalidates admitted work. - Same-epoch `DRAINING` is the only predecessor exception: already-admitted work captured under the immediately preceding `ENABLED` lifecycle revision may finish only when its winning admission/fence compare-and-set committed before the durable `DRAINING` admission barrier was created (and therefore before the lifecycle transition) and every other exact fence passes. Arbitrary lower or non-predecessor revisions are rejected; see [ADR 0119](./decisions/adr-0119-epoch-fenced-per-instance-plugin-activation.md). -- Replay is fail-closed per work item. Eligibility requires exact current `(scriptPatchVersion, scriptPinEpoch)`, applicable plugin identity/version/binding and captured `(pluginActivationEpoch, lifecycleRevision)`, region/`regionEpoch`, and routing-bundle match to the immutable admitted evidence. For plugin work, the current scoped plugin activation/lifecycle, component-policy decision, capability-grant evidence, and signer/publication evidence must also be fresh and valid. +- Replay is fail-closed per work item. Eligibility requires exact current `(scriptPatchVersion, scriptPinEpoch)`, plus the separately captured nonblank `scriptPinControlPlaneRequestId` owner/fence evidence exact-compared with Game Session before evaluation and before each dispatch. The request ID is not part of the execution identity tuple. This owner evidence is distinct from the replay mutation's `controlPlaneRequestId`, which identifies the recovery request. Eligibility also requires applicable plugin identity/version/binding and captured `(pluginActivationEpoch, lifecycleRevision)`, region/`regionEpoch`, and routing-bundle match to the immutable admitted evidence. For plugin work, the current scoped plugin activation/lifecycle, component-policy decision, capability-grant evidence, and signer/publication evidence must also be fresh and valid. - After exact-request idempotency and current `failureGeneration` resolution, immutable successful-recovery evidence bound to that same current generation returns `outcome=already_recovered` before aggregate-status or active-claim checks; `recovery_in_progress` applies only when no same-generation successful-recovery evidence exists and an active claim remains. After that precedence check, retained evidence proving that the selected parent's recovery inputs were purged—including `descriptorEvidencePurgedAt` for an `EVALUATED_COMMITTED` parent or the retained purge outcome for a pre-DSL row—returns `outcome=rejected` with `rejectionReason=stage_evidence_unavailable` and creates no claim/attempt. Using that internal identity, recovery compares-and-sets the current parent recovery aggregate `status=DEAD_LETTERED` together with a persisted recovery claim/attempt record containing `(tenantId, outboxWorkItemId, failureGeneration)`, the expected exact `(scriptPatchVersion, scriptPinEpoch)`, runtime scope, applicable plugin binding tuple and captured `(pluginActivationEpoch, lifecycleRevision)`, and `controlPlaneRequestId`, before evaluation or dispatch. A post-evaluation parent may retain its `EVALUATED_COMMITTED` descriptor marker and complete output/child ledger while this separate recovery aggregate is `DEAD_LETTERED`; that is the eligible `resumed_dispatch` case. A selected row in any other aggregate status remains unchanged and returns `outcome=rejected` with `rejectionReason=work_item_not_dead_lettered`. If a different `controlPlaneRequestId` targets a row with an active `IN_PROGRESS` claim for that generation, its stored deterministic request result is `outcome=rejected` with `rejectionReason=recovery_in_progress` and it creates no new claim/attempt, evaluation, or dispatch. If a created claim/attempt reaches terminal `FAILED`, its stored request result is `outcome=recovery_failed` with a required, bounded failureReason and no `rejectionReason`; an exact retry returns that stored result and reason without a new attempt. An expired claim is reclaimed under the same attempt record and identity (with a new owner fence when needed), never by inserting a duplicate recovery attempt or audit record; lease expiry alone does not allow a different request to create an attempt. A later new request may create one new attempt only after the prior attempt is terminal `FAILED` and fresh eligibility/fence checks pass. A prior successful recovery generation remains immutable; it is not `already_recovered` evidence for a newer current failure generation. -- Evaluation-stage recovery uses the frozen original trigger/input manifest and exact graph, preserving the original work-item and `scriptEventId` identity; before its winning evaluated-descriptor/outbox commit it allocates no dispatch or command-child identity. If it emits commands, that first atomic descriptor commit allocates and persists the `automationDispatchId` and deterministic ordinals; retries after a winning commit reuse them. A valid zero-command evaluation creates no dispatch identity. It may invoke the DSL evaluator again for eligible gameplay/runtime work outside normal admission. Tenant-readiness `onLoad` remains at-most-once and is excluded from evaluation replay. Post-evaluation recovery uses only the immutable evaluated output and complete child-dispatch ledger keyed by the full Command-Handoff Identity, preserving original child identities and per-child recovery state without invoking the DSL. `HANDED_OFF` (accepted), `CANCELED`, and `DEAD_LETTERED` children are terminal and no-op. An already `HANDOFF_IN_FLIGHT` child is fenced and reconciled against the durable downstream outcome, never blindly redispatched; if that outcome is ambiguous, the child remains active/unresolved, the same recovery attempt remains `IN_PROGRESS`, no temporary or terminal per-row application result is stored, and `resumed_dispatch` is not reported. The initiating request or an exact retry attaches to that same attempt until a terminal result is available or its transport deadline expires; a transport deadline does not store a different result. Immediately before evaluation, and immediately before each post-evaluation dispatch, it revalidates the immutable admitted source runtime scope `(tenantId, gameInstanceId, playableStateScope, regionId, regionEpoch)`, optional distinct target runtime scope `(targetGameInstanceId, targetPlayableStateScope, targetRegionId, targetRegionEpoch)`, exact `(scriptPatchVersion, scriptPinEpoch)`, and admitted routing bundle `(playableStateScope, worldSlug, realmSlug, pointerVersion)`, together with the recorded binding, captured `(pluginActivationEpoch, lifecycleRevision)`, and current scoped plugin activation/lifecycle, component-policy, capability-grant, and signer/publication evidence. For any revocable component, the retained component-revocation security-policy fence is independently revalidated at evaluation, each post-evaluation dispatch, and immediately before gameplay effects; it is not substituted by lifecycle or ordinary component-policy evidence. `DRAINING` blocks new trigger admission but does not invalidate already-admitted recovery; only a lifecycle transition that invalidates admitted work, such as `DISABLED`, revocation, or policy-driven disablement, uses `plugin_disabled`. Only after that dispatch-time revalidation succeeds may a `PENDING` or `INDEXED` child transition by durable compare-and-set to `HANDOFF_IN_FLIGHT` under the existing recovery claim/attempt fence and dispatch. Missing, stale, or temporarily unavailable evidence fails closed with the applicable established bounded reason (`authority_unavailable`, `component_policy_unavailable`, or `signer_policy_unavailable`); proven publication, component/capability, signer, tuple, epoch, or scope mismatches use `plugin_version_not_published`, `plugin_component_policy_blocked`, `signer_revoked`, `plugin_binding_mismatch`, `plugin_activation_epoch_mismatch`, `script_pin_epoch_mismatch`, or `runtime_scope_mismatch` as applicable. A `lifecycleRevision` mismatch outside the bounded `DRAINING` predecessor exception uses `plugin_binding_mismatch`; `plugin_disabled` remains reserved for an invalidating lifecycle transition. It never resolves a latest/local graph, and never regenerates an output after a child was accepted. +- Evaluation-stage recovery uses the frozen original trigger/input manifest and exact graph, preserving the original work-item and `scriptEventId` identity; before its winning evaluated-descriptor/outbox commit it allocates no dispatch or command-child identity. If it emits commands, that first atomic descriptor commit allocates and persists the `automationDispatchId` and deterministic ordinals; retries after a winning commit reuse them. A valid zero-command evaluation creates no dispatch identity. It may invoke the DSL evaluator again for eligible gameplay/runtime work outside normal admission. Tenant-readiness `onLoad` remains at-most-once and is excluded from evaluation replay. Post-evaluation recovery uses only the immutable evaluated output and complete child-dispatch ledger keyed by the full Command-Handoff Identity, preserving original child identities and per-child recovery state without invoking the DSL. `HANDED_OFF` (accepted), `CANCELED`, and `DEAD_LETTERED` children are terminal and no-op. An already `HANDOFF_IN_FLIGHT` child is fenced and reconciled against the durable downstream outcome, never blindly redispatched; if that outcome is ambiguous, the child remains active/unresolved, the same recovery attempt remains `IN_PROGRESS`, no temporary or terminal per-row application result is stored, and `resumed_dispatch` is not reported. The initiating request or an exact retry attaches to that same attempt until a terminal result is available or its transport deadline expires; a transport deadline does not store a different result. Immediately before evaluation, and immediately before each post-evaluation dispatch, it revalidates the immutable admitted source runtime identity `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch)`, optional distinct target runtime identity `(targetGameInstanceId, targetPlayableStateNamespaceId, targetRegionId, targetRegionEpoch)`, separately validated source/target `playableStateScope` routing/fence evidence, exact `(scriptPatchVersion, scriptPinEpoch)`, and the immutable admitted source routing bundle `(playableStateScope, worldSlug, realmSlug, pointerVersion)`; when the target is distinct, recovery also persists and exact-compares the target bundle `(targetPlayableStateScope, targetWorldSlug, targetRealmSlug, targetPointerVersion)` against that same target. Together with the recorded binding, captured `(pluginActivationEpoch, lifecycleRevision)`, and current scoped plugin activation/lifecycle, component-policy, capability-grant, and signer/publication evidence, these checks preserve the source bundle and same-target semantics. For any revocable component, the retained component-revocation security-policy fence is independently revalidated at evaluation, each post-evaluation dispatch, and immediately before gameplay effects; it is not substituted by lifecycle or ordinary component-policy evidence. `DRAINING` blocks new trigger admission but does not invalidate already-admitted recovery; only a lifecycle transition that invalidates admitted work, such as `DISABLED`, revocation, or policy-driven disablement, uses `plugin_disabled`. Only after that dispatch-time revalidation succeeds may a `PENDING` or `INDEXED` child transition by durable compare-and-set to `HANDOFF_IN_FLIGHT` under the existing recovery claim/attempt fence and dispatch. Missing, stale, or temporarily unavailable evidence fails closed with the applicable established bounded reason (`authority_unavailable`, `component_policy_unavailable`, or `signer_policy_unavailable`); proven publication, component/capability, signer, tuple, epoch, or scope mismatches use `plugin_version_not_published`, `plugin_component_policy_blocked`, `signer_revoked`, `plugin_binding_mismatch`, `plugin_activation_epoch_mismatch`, `script_pin_epoch_mismatch`, or `runtime_scope_mismatch` as applicable. A `lifecycleRevision` mismatch outside the bounded `DRAINING` predecessor exception uses `plugin_binding_mismatch`; `plugin_disabled` remains reserved for an invalidating lifecycle transition. It never resolves a latest/local graph, and never regenerates an output after a child was accepted. - Before claim acquisition, a committed lifecycle invalidation wins as `plugin_disabled`; when no such invalidation is committed, a directly proven signer or component-policy failure uses `signer_revoked` or `plugin_component_policy_blocked`, respectively. Rows with missing/contradictory stage evidence or any fence mismatch discovered before claim acquisition remain `DEAD_LETTERED` and return a deterministic per-row `outcome=rejected` with the applicable bounded `rejectionReason`, with no claim/attempt. If the same evidence failure occurs after a claim/attempt exists, the first failing stage's bounded `failureReason` is persisted and that attempt terminalizes as `FAILED`; later lifecycle changes do not rewrite it. The attempt returns/stores `outcome=recovery_failed` with no `rejectionReason`; an exact retry returns the stored deterministic result. A rejected row is not partially changed or counted as successful. - The request is bounded and idempotent by `controlPlaneRequestId`, actor, reason, and explicit work-item IDs. An exact retry of the same `controlPlaneRequestId` and canonical request fingerprint returns the identical stored per-row outcomes and stored generation, including `recovery_failed` with its stored `failureReason` or `rejected`, without evaluation, dispatch, or relabeling. Reusing a `controlPlaneRequestId` with a changed canonical request fingerprint is a request-level conflict detected before claim acquisition, evaluation, or dispatch; it cannot alter stored per-row results and is not represented as a per-row rejection. A new request that finds the current generation already recovered returns `outcome=already_recovered`; older-generation success does not block recovery of the current generation. No new Trigger Identity is introduced; a Command-Handoff Identity can first be allocated only by the winning descriptor commit, and later recovery never creates a second one. Purge is a separate operation and never masquerades as recovery. diff --git a/design/architecture/system-architecture-scripting-control-plane-operations.md b/design/architecture/system-architecture-scripting-control-plane-operations.md index 6ef8394529..bf21079a0b 100644 --- a/design/architecture/system-architecture-scripting-control-plane-operations.md +++ b/design/architecture/system-architecture-scripting-control-plane-operations.md @@ -259,7 +259,7 @@ Semantics: - `reason` is required and must be non-blank; Game Session validates it before reading the owned instance or purging queue or durable command state. - Idempotent. -- Under the shared queue mutation/tick lease, terminal-marks matching durable Game Session command rows before post-commit Redis queue/pending cleanup. Pre-batch commands use `executionOutcome = LOST_BEFORE_STAGING`; an explicitly retryable command with a durable prior tick-effect binding uses `executionOutcome = ABANDONED`. Both use `gameplayResult = NOT_APPLIED`, `failureCode = ROLLBACK_PURGED`, and the validated nonblank ingress `reason` as `failureMessage`. +- Under the shared queue mutation/tick lease, terminal-marks matching durable Game Session command rows before post-commit Redis queue/pending cleanup. `executionOutcome = LOST_BEFORE_STAGING` applies only to commands acknowledged `ACCEPTED_VOLATILE` whose ingress status is still `RECEIVED` or `ENQUEUED`, with no surviving durable batch, effect ledger, or source/effect claim, and only when an atomic owner-defined no-batch/version-fenced check wins; `ACCEPTED_DURABLE` pre-batch work cannot use this outcome and remains under its durable retry/recovery contract. An explicitly retryable command with a durable prior tick-effect binding may use `executionOutcome = ABANDONED` only when authoritative evidence proves that effect was unapplied and any already-declared applicable feature rule permits abandonment. A matching binding and `RETRY_QUEUED` status alone do not prove `NOT_APPLIED`; inconclusive work remains nonterminal and reconciliation-required, and this purge does not terminalize it. Any justified terminal mapping uses `gameplayResult = NOT_APPLIED`, `failureCode = ROLLBACK_PURGED`, and the validated nonblank ingress `reason` as `failureMessage`. - Batch-bound work that is not in the explicit retry queue is not purged through this hook; it requires effect-ledger remediation or rollback recovery because it has crossed the tick-batch boundary. - Emits an operator-visible metric for purge activity and for version-fence drops; exact metric names, labels, and increment units follow [Table 4](./system-architecture-scripting-normative-contract-tables.md#table-4-metrics-label-matrix), while audit and handoff diagnostics follow the observability contract. @@ -284,7 +284,7 @@ Inputs: `reason` is required and must be non-blank; Game Session validates it before reading the owned instance or purging queue/durable command state. -Semantics and outputs: same as `PurgeQueuedTickCommandsForScriptPatch`, including the pre-batch `LOST_BEFORE_STAGING` versus durably batch-bound retry `ABANDONED` outcome split, `gameplayResult = NOT_APPLIED`, `failureCode = ROLLBACK_PURGED`, and the validated nonblank ingress `reason` as `failureMessage`, scoped to plugin-produced commands by the `pluginId` and `pluginVersionId` provenance carried from Automation into Game Session during handoff. +Plugin rows are selected by their stored `pluginId` and `pluginVersionId` provenance. `LOST_BEFORE_STAGING` eligibility, the validated nonblank ingress `reason`, and evidence-qualified batch-bound handling follow [PurgeQueuedTickCommandsForScriptPatch](#purgequeuedtickcommandsforscriptpatch); inconclusive work remains nonterminal under that owner contract. ### Automation & Scripting: Drain/Purge Hooks (Rollback Support) diff --git a/design/architecture/system-architecture-scripting-dsl-for-designers.md b/design/architecture/system-architecture-scripting-dsl-for-designers.md index 579675848b..e5b83c1830 100644 --- a/design/architecture/system-architecture-scripting-dsl-for-designers.md +++ b/design/architecture/system-architecture-scripting-dsl-for-designers.md @@ -175,7 +175,7 @@ The platform performs **extensive validation** at design time and at publish tim - For **editor-time issues**, fix the graph based on validation errors in the Game Design Service UI and re-run validation before publishing. - For **runtime issues**, start from the script’s recent entries in `script_event_audit` and the associated metrics in `design/architecture/system-architecture-scripting-quotas-and-operations.md`, then adjust quotas or disable/throttle the script using the operational flows described there. - For **safe test runs**, the ADR 0114 command-plan preview endpoint is the target-state path for the Game Design / Logging & Admin UIs. Its current implementation boundary is summarized in [Implementation Status](#implementation-status). Once implemented, it will be a separate non-committing path that exercises the same sandbox and validation logic without live work or tick-queue handoff. Test tools are **privileged** and subject to their own rate limits and budgets so they cannot overload the scripting cluster; avoid running unbounded batches of previews against production tenants. - - When working with support or operators, you can use `scriptEventId` as a “debug ticket” for a single trigger, but never use it alone. The ticket must carry the complete applicable [Trigger Identity](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). Base fields are `tenantId`, `scriptId`, `eventType`, `eventSchemaVersion`, `scriptPatchVersion`, `scriptEventId`, and `isDryRun`; gameplay/runtime triggers additionally carry `gameInstanceId`, `playableStateScope`, `regionId`, `regionEpoch`, and `entityId`; resolved plugin handlers additionally carry `pluginId`, `pluginVersionId`, and `bindingId`; scheduler triggers additionally carry `triggerMode`, `scheduleDefinitionId`, `targetScopeType`/`targetScopeId`, plus exactly one applicable due point (`dueTickId` or `dueAt`). Tenant-readiness `onLoad` tickets explicitly omit `gameInstanceId`, `playableStateScope`, `regionId`, `regionEpoch`, and `entityId` because they are not tied to a running gameplay instance. Include command-level `outboxWorkItemId`, `automationDispatchId`, and `commandOrdinal` when a handoff child is in scope; those command-level fields are target-state until the Game Session handoff carries them end to end. + - When working with support or operators, use `scriptEventId` as a correlation ticket at the correct lifecycle layer after the applicable ingress has validated a supplied ID or allocated one, never by itself. A pre-resolution event-scope ticket or ingress-audit record carries the applicable fields available at that layer: `tenantId`, `eventType`, `eventSchemaVersion`, `isDryRun`, the exact `scriptPatchVersion`/`scriptPinEpoch` pair and paired `scriptPinControlPlaneRequestId` as non-identity owner evidence only after authoritative pin evidence is available, `scriptEventId` after the event-scope claim validates a supplied ID or allocates one, and, for gameplay/runtime events, `gameInstanceId`, `playableStateNamespaceId`, `playableStateScope`, `regionId`, and `regionEpoch`; it also carries producer-derived `sourceService` where applicable. The owner request ID follows the paired evidence rule in [Scripting Contracts §3](./system-architecture-scripting-contracts.md#3-version-fencing-rollback-safety) and is not a third pin identity component. A fail-closed pre-admission audit retains any caller-supplied `scriptPatchVersion`/`scriptPinEpoch` only in explicitly marked unverified request-evidence fields on the existing ingress-audit surface, never as canonical ingress identity or exact pin evidence; it also retains a caller-supplied `scriptEventId` once the event-scope claim has validated it, including on a pre-handler denial. An unfired internally owned timer due candidate, including a `reload_failed` candidate, creates no `scriptEventId` and instead carries its event-scope `scheduleCandidateId`. The ticket does not invent ordinary handler-resolution fields. Owner-known exceptions are tenant-readiness `onLoad`, which includes its `scriptId`, and scheduler/timer candidates, which include schedule-owned `scriptId`, plugin provenance `(pluginId, pluginVersionId, bindingId)` when the durable schedule already owns that binding, and `pluginActivationEpoch` for plugin-owned candidate identity; `resumeWindowId` appears for `CATCH_UP` candidates, while captured `lifecycleRevision` travels as non-identity fence evidence. These are candidate/event identity fields, not resolved handler fields. After handler resolution, the ticket carries the complete applicable [Trigger Identity](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields), including `entityId` when entity-scoped and the resolved plugin/binding fields. Scheduler triggers additionally carry `triggerMode`, `scheduleDefinitionId`, `targetScopeType`/`targetScopeId`, plus exactly one applicable due point (`dueTickId` or `dueAt`). Tenant-readiness `onLoad` tickets explicitly omit `scriptPinEpoch`, `gameInstanceId`, `playableStateNamespaceId`, `playableStateScope`, `regionId`, `regionEpoch`, and `entityId` because they are pre-instance readiness work. Include command-level `outboxWorkItemId`, `automationDispatchId`, and `commandOrdinal` when a handoff child is in scope; those command-level fields are target-state until the Game Session handoff carries them end to end. The Game Design and Logging & Admin audit/log views (for example `script_event_audit` queries and trace/log search) should support filtering by these fields so a single trigger can be followed end-to-end without ambiguity. Use the `AS-1.1` and `AS-1.5` entries in the [automation and scheduler runtime tracker](../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status) to distinguish the live identity/read surfaces from target-state command-handoff coverage. For the detailed loop safety algorithm and runtime budget enforcement, see: @@ -208,7 +208,7 @@ Recurring and advisory timer handlers such as `onInterval` (or an advisory `onTi - Each authored timer declares its clock and recovery class. Tick/game time is the only default clock; no recovery class is inferred by default. Recurring timers explicitly select one recovery policy: `SKIP_MISSED` advances to the next valid future occurrence without firing missed occurrences, while `COALESCE_ONE` permits one bounded synthetic firing for missed time. A correctness-bearing one-shot explicitly selects the correctness-bearing one-shot class. See the [canonical timer semantics matrix](./system-architecture-scripting-normative-contract-tables.md#table-3-timer-semantics-matrix) for the recovery-class contract. - When a recurring or advisory timer becomes due, the scheduler tries to fire it subject to per-script quotas, per-tenant budgets, and cluster ceilings. Under heavy load or when limits are reached, individual firings may be **skipped** and are not automatically replayed later, even if the timer continues to run at its configured cadence. -- After downtime or leader failover, a recurring `COALESCE_ONE` timer may emit at most one coalesced firing for each complete stable schedule-instance identity in one Automation-owned durable `resumeWindowId` identified by ``; it never replays one firing per cadence boundary. Same-window retries and takeovers reuse that mode-specific ID, while a later recovery episode receives a new generation only after the prior window's selected and cap-excluded outcomes are durable. The tenant-local `SCRIPT_TIMER_CATCH_UP_MAX_FIRINGS_PER_RESUME` cap is evaluated separately inside each such full runtime-scope-and-mode `resumeWindowId` (that one-tenant, one-mode ID): tenant-local describes the window's tenant owner, not a tenant-wide pool, so a schedule in another game instance, playable-state scope, region, or epoch cannot consume this window's cap. Selected candidates still pass through tenant-first shared scheduler/cluster admission; a tenant or cluster capacity denial is a durable terminal skip for that catch-up candidate and is not retried, deferred, backfilled, or reminted, while its next ordinary future cadence remains eligible. Candidates excluded by the catch-up cap are likewise dropped and audited rather than deferred as an unbounded backlog. Recurring `SKIP_MISSED` timers emit no catch-up firing. +- After downtime or leader failover, a recurring `COALESCE_ONE` timer may emit at most one coalesced firing for each complete stable schedule-instance identity in one Automation-owned durable `resumeWindowId` identified by ``; the server-derived `playableStateScope` is retained as immutable policy/routing/authorization/fence evidence and is exact-validated alongside that identity. It never replays one firing per cadence boundary. Same-window retries and takeovers reuse that mode-specific ID, while a later recovery episode receives a new generation only after the prior window's selected and cap-excluded outcomes are durable. The tenant-local `SCRIPT_TIMER_CATCH_UP_MAX_FIRINGS_PER_RESUME` cap is evaluated separately inside each such full runtime-identity-and-mode `resumeWindowId` (that one-tenant, one-mode ID): tenant-local describes the window's tenant owner, not a tenant-wide pool, so a schedule in another game instance, playable-state namespace, region, or epoch cannot consume this window's cap. Selected candidates still pass through tenant-first shared scheduler/cluster admission; a tenant or cluster capacity denial is a durable terminal skip for that catch-up candidate and is not retried, deferred, backfilled, or reminted, while its next ordinary future cadence remains eligible. Candidates excluded by the catch-up cap are likewise dropped and audited rather than deferred as an unbounded backlog. Recurring `SKIP_MISSED` timers emit no catch-up firing. - Infrastructure hiccups (for example, Redis or gRPC outages) do not promise that a recurring or advisory cadence firing will eventually run. Before the `EVALUATED_COMMITTED` descriptor-commit boundary, an admitted evaluation may rerun only under the same full Trigger Identity and must converge on the same durable work-item and child identities. After `EVALUATED_COMMITTED`, recovery replays durable descriptors and never re-enters the DSL; the audit `finalStage` and outcome remain tied to the last confirmed durable stage. Correctness-bearing one-shot timers instead retry or terminalize under their durable intent identity and must not duplicate the effect. - As a result, recurring timer callbacks should be treated as **bounded scheduling signals**, not per-cadence ledgers. Design timer handlers so they can tolerate missed or delayed firings and recompute from current world state instead of assuming that every interval has executed exactly once. diff --git a/design/architecture/system-architecture-scripting-dsl-reference-and-lifecycle.md b/design/architecture/system-architecture-scripting-dsl-reference-and-lifecycle.md index 8d9f33b295..e09114a7c6 100644 --- a/design/architecture/system-architecture-scripting-dsl-reference-and-lifecycle.md +++ b/design/architecture/system-architecture-scripting-dsl-reference-and-lifecycle.md @@ -27,7 +27,7 @@ For a higher-level routing guide to all scripting and automation docs, see the * ## Implementation Status -This document is target-state canonical for DSL shape and lifecycle semantics. For each resolved handler admitted to durable execution after handler-scoped gates, one durable parent work item starts at `PENDING_EVALUATION`, transitions to `EXECUTING`, and atomically reaches `EVALUATED_COMMITTED` while gaining immutable evaluated command descriptors/child-dispatch rows; descriptor rows then have independent handoff statuses. A handler denied before work-item materialization keeps its handler audit outcome but creates no parent work item. Executor acceptance, the execution-start charge marker, and the fenced capacity lease commit before DSL evaluation, and recovery of a committed parent replays its descriptors without re-entering the DSL. This target flow is distinct from the current pre-DSL queue path: the live Automation claim boundary is `PENDING_EVALUATION` -> `EVALUATING`, and `automation:queue` contains only derived pre-DSL parent-work pointers; the target evaluated descriptor/child projection and lease/fencing-generation recovery remain implementation gaps. Current runtime boundaries are recorded in [Scripting Runtime Execution](./system-architecture-scripting-runtime-execution.md#current-implementation-status): bounded local multi-command staging is live, including local expansion of `targetEntityIds[]` into individually attempted single-command, single-target handoff calls. The live handoff request itself carries only one command and target and lacks complete durable child/target identity, scope validation, and end-to-end dedup/progress proof, so target-state multi-target fan-out remains incomplete. Durable parent-event identity, canonical request-digest conflict handling, and atomic freezing of the complete ordered handler manifest under [ADR 0172](./decisions/adr-0172-parent-event-and-frozen-handler-execution-identity.md) are also unimplemented. Canonical scripting audit and handoff diagnostics are defined by the [Scripting & Automation Observability Contract](./system-architecture-scripting-observability-contract.md); metric families, labels, and increment units are solely owned by [normative Table 4](./system-architecture-scripting-normative-contract-tables.md#table-4-metrics-label-matrix). +This document is target-state canonical for DSL shape and lifecycle semantics. For each resolved handler admitted to durable execution after handler-scoped gates, one durable parent work item starts at `PENDING_EVALUATION`, transitions to `EXECUTING`, and atomically reaches `EVALUATED_COMMITTED` while gaining immutable evaluated command descriptors/child-dispatch rows; descriptor rows then have independent handoff statuses. A handler denied before work-item materialization keeps its handler audit outcome but creates no parent work item. Executor acceptance, the execution-start charge marker, and the fenced capacity lease commit before DSL evaluation, and recovery of a committed parent replays its descriptors without re-entering the DSL. This target flow is distinct from the current pre-DSL queue path: the live Automation claim boundary is `PENDING_EVALUATION` -> `EVALUATING`; no evaluated descriptor/outbox persistence or post-DSL replay is currently implemented, and `automation:queue` contains only derived pre-DSL parent-work pointers. The target evaluated descriptor/child projection and lease/fencing-generation recovery remain implementation gaps. Current runtime boundaries are recorded in [Scripting Runtime Execution](./system-architecture-scripting-runtime-execution.md#current-implementation-status): bounded local multi-command staging is live, including local expansion of `targetEntityIds[]` into individually attempted single-command, single-target handoff calls. The live handoff request itself carries only one command and target and lacks complete durable child/target identity, scope validation, and end-to-end dedup/progress proof, so target-state multi-target fan-out remains incomplete. Durable parent-event identity, canonical request-digest conflict handling, and atomic freezing of the complete ordered handler manifest under [ADR 0172](./decisions/adr-0172-parent-event-and-frozen-handler-execution-identity.md) are also unimplemented. Canonical scripting audit and handoff diagnostics are defined by the [Scripting & Automation Observability Contract](./system-architecture-scripting-observability-contract.md); metric families, labels, and increment units are solely owned by [normative Table 4](./system-architecture-scripting-normative-contract-tables.md#table-4-metrics-label-matrix). ## Table of Contents @@ -62,11 +62,11 @@ For designer-oriented guidance on building and debugging scripts in the visual e ## Terminology Glossary -- **`{tenantRegionTag}` hash tag** – an opaque placeholder produced by shared Redis key builders from the complete `` scope documented in [Redis Architecture](./system-architecture-redis.md#key-naming-and-shard-discipline). It exists for shard locality across region-scoped keys; it is not a replacement for those identity fields and does not define a competing schedule or tenant key family. `playableStateScope` is intentionally not part of this existing tag topology; it remains in durable Trigger Identity and command/effect identity and must not be inferred from the tag. -- **`{tenantInstanceTag}` hash tag** – an opaque placeholder produced by shared Redis key builders from ``. It scopes instance-wide automation projections and cross-region coordination hints such as `automation:queue:{tenantInstanceTag}:` and `remote:{tenantInstanceTag}:`; it must not be substituted for the region-scoped `{tenantRegionTag}` where a region timeline or lease fence applies. +- **`{tenantRegionTag}` hash tag** – an opaque placeholder produced by shared Redis key builders from the complete `` scope documented in [Redis Architecture](./system-architecture-redis.md#key-naming-and-shard-discipline). It exists for shard locality across region-scoped keys; it is not a replacement for those identity fields and does not define a competing schedule or tenant key family. `playableStateScope` is intentionally not part of this existing tag topology; durable Trigger, scheduler, and command-handoff identities use `playableStateNamespaceId`, while scope remains immutable policy/routing/authorization/fence evidence and must not be inferred from the tag. Downstream mutation guards exact-validate applicable namespace/scope evidence separately from their own effect-guard uniqueness. +- **`{tenantInstanceTag}` hash tag** – an opaque placeholder produced by shared Redis key builders from ``. It scopes instance-wide automation projections: `automation:queue:{tenantInstanceTag}:` is a Cache/Rate-Limit disposable dispatch-pointer index rebuilt from eligible durable pre-DSL records, while `remote:{tenantInstanceTag}:` is a separate Coordination Redis wake-up hint. This current key, the `ScriptWorkItem` row/claim, its queue pointer, and an `outboxWorkItemId`-only claim do not establish namespace isolation; the tenant-instance tag does not carry `playableStateNamespaceId`. Target work items, pointers, queue-index projections, rebuild eligibility, and consumers must retain and exact-validate authoritative `playableStateNamespaceId`, with `playableStateScope` separately exact-validated as policy/routing/fence evidence rather than identity. This requirement does not prescribe a Redis key topology. The tag must not be substituted for the region-scoped `{tenantRegionTag}` where a region timeline or lease fence applies. - **Game tick** – a region-scoped tick in the Game Session Service. Each `` advances through a monotonic `tickId` stream; game ticks are authoritative for gameplay state changes and use `tick:{tenantRegionTag}:...` keys and locks as described in [Tick System and Runtime Design](./system-architecture-ticks.md). - **Automation execution loop** – the durable executor path inside the Automation & Scripting Service. **Target state:** it claims committed descriptor children under a durable parent work item, evaluates no DSL again, and hands resulting commands to the Game Session Service so Game Session can enqueue **tick commands** into per-entity tick queues for later execution by game ticks. **Current implementation:** the scheduled queue-rebuild hook/configuration has been removed/disabled; the executor drains derived pointers and its durable claim filters to `PENDING_EVALUATION`, so `EVALUATING` pointers are not picked up, reclaimed, or re-entered into the DSL. Because there is no stale-owner/CAS recovery, queue reset/rebuild/resume remains unavailable and must fail closed; see [Scripting Runtime Execution: Current Queue-Rebuild Concurrency Gap](./system-architecture-scripting-runtime-execution.md#current-queue-rebuild-concurrency-gap). Atomic owner-reconciled recovery of safe post-DSL `PENDING` work is target-only. -- **Automation queue** – an instance-aware, per-entity Redis queue (`automation:queue:{tenantInstanceTag}:`) that currently holds **derived pre-DSL parent-work indexes/pointers** for `PENDING_EVALUATION` and `EVALUATING` work, not an authoritative log of pending work. `PENDING_EVALUATION` pointers can be claimed for evaluation; `EVALUATING` pointers are inspection-only and cannot be picked up, reclaimed, or re-enter the DSL. The former rebuild hook/configuration is removed/disabled; queue reset/rebuild/resume remains unavailable and must fail closed. See [Scripting Runtime Execution: Current Queue-Rebuild Concurrency Gap](./system-architecture-scripting-runtime-execution.md#current-queue-rebuild-concurrency-gap). Target post-DSL descriptor recovery uses separate `PENDING`/`INDEXED` states and atomic owner-reconciled recovery of safe work; it is not implemented. +- **Automation queue** – an instance-aware, per-entity Redis queue (`automation:queue:{tenantInstanceTag}:`) that currently holds **derived pre-DSL parent-work indexes/pointers** for `PENDING_EVALUATION` and `EVALUATING` work, not an authoritative log of pending work or proof of namespace isolation. `PENDING_EVALUATION` pointers can be claimed for evaluation; `EVALUATING` pointers are inspection-only and cannot be picked up, reclaimed, or re-enter the DSL. The former rebuild hook/configuration is removed/disabled; queue reset/rebuild/resume remains unavailable and must fail closed. See [Scripting Runtime Execution: Current Queue-Rebuild Concurrency Gap](./system-architecture-scripting-runtime-execution.md#current-queue-rebuild-concurrency-gap). Target post-DSL descriptor recovery uses separate `PENDING`/`INDEXED` states, retains/exact-validates namespace identity separately from scope evidence, and requires atomic owner-reconciled recovery of safe work; it is not implemented. - **Tick heartbeat** – a **gRPC streaming feed** produced by the Game Session Service that reports `(regionEpoch, tickId)` progression per ``. The script scheduler consumes this heartbeat over a long-lived gRPC stream to count “every N ticks” intervals and align `onInterval` triggers with the canonical game tick timeline without owning tick execution itself. See [Tick Events & Heartbeat Stream](./system-architecture-ticks.md#tick-events--heartbeat-stream) for transport details and the `(regionEpoch, tickId)` coordination timeline. --- @@ -98,10 +98,10 @@ The required Trigger Identity fields and target-scope exceptions are defined in | --- | --- | --- | --- | | 1 | **Trigger** | A concrete event such as `onEnterRegion`, `onCommand`, or a custom event emitted by a service. | gRPC `TriggerScriptEvent` call, tick heartbeat, or internal scheduler event. | | 2 | **DSL run** | Execution of a script handler in the sandboxed DSL for a single trigger. It evaluates the frozen inputs within the durable parent work item and produces domain commands, not direct state changes. | In-memory execution in the Automation & Scripting Service; results are committed to that parent and, at `EVALUATED_COMMITTED`, to immutable command descriptors. | -| 3 | **Script work item** | For each admitted resolved handler, one durable parent work item owns the applicable Trigger Identity and pre-DSL lifecycle; when it reaches `EVALUATED_COMMITTED`, it gains immutable evaluated command descriptor/child-dispatch rows, one per emitted command, with version metadata. A handler denied before work-item materialization has no parent work item. The descriptor rows have independent handoff statuses while the parent marker remains the recovery boundary. | **Target state only:** committed descriptor children are indexed via `automation:queue:{tenantInstanceTag}:` when they target an entity and are later claimed by Automation's durable executor for Game Session handoff. **Current implementation:** that queue is only a derived pre-DSL parent-work pointer projection for `PENDING_EVALUATION`/`EVALUATING`, not an evaluated-command descriptor index. | +| 3 | **Script work item** | For each admitted resolved handler, one durable parent work item owns the applicable Trigger Identity and pre-DSL lifecycle; when it reaches `EVALUATED_COMMITTED`, it gains immutable evaluated command descriptor/child-dispatch rows, one per emitted command, with version metadata. A handler denied before work-item materialization has no parent work item. The descriptor rows have independent handoff statuses while the parent marker remains the recovery boundary. | **Target state only:** each work item/descriptor and queue-index pointer retains and exact-validates authoritative `playableStateNamespaceId`, with `playableStateScope` separately exact-validated; an `outboxWorkItemId` alone is not isolation evidence. The displayed `automation:queue:{tenantInstanceTag}:` is the current pointer-key shape, not a target identity contract. **Current implementation:** that queue is only a derived pre-DSL parent-work pointer projection for `PENDING_EVALUATION`/`EVALUATING`, not an evaluated-command descriptor index or proof of namespace isolation. | | 4 | **Tick command** | A concrete command that the Game Session Service executes during game ticks under its normal locking and idempotency rules. | Enqueued into `tick:{tenantRegionTag}:queue:` for consumption by the tick loop. | -Triggers lead to durable parent work items for admitted handlers; their DSL runs execute within those parents and, after `EVALUATED_COMMITTED`, gain immutable descriptor children plus queue-pointer projection entries. Automation's execution loop turns those committed descriptors into tick commands for the Game Session Service. +Only after all applicable handler-scoped gates pass does each admitted resolved handler create a durable parent work item, and its DSL run executes within that parent. A trigger with no admitted handlers creates no parent work items. The exact per-handler gates remain owned by [Normative Table 2](./system-architecture-scripting-normative-contract-tables.md#table-2-script_event_audit-stages-and-outcomes). **Target state only:** after `EVALUATED_COMMITTED`, a work item gains immutable descriptor children and dispatches them through queue-pointer projections; target queue staging retains and exact-validates authoritative `playableStateNamespaceId` and separately validates `playableStateScope`. Current descriptor persistence and post-DSL dispatch/replay are unimplemented (see [Implementation Status](#implementation-status)); the current queue is only a pre-DSL parent-work pointer, and its instance-tagged key, work item/pointer, and outbox-ID-only claim do not establish namespace isolation. Target Automation dispatch turns committed descriptors into tick commands for the Game Session Service. This is an overview rather than an exhaustive lifecycle. **Target state only:** an identifiable readiness notification whose immutable manifest proves zero `onLoad` handlers takes a direct terminal readiness-record path with `status=READY` and readiness-level evidence; one whose zero-handler claim lacks verifiable immutable proof attempts a direct terminal readiness-record path with `status=FAILED` and `statusReason=zero_handler_manifest_unverifiable`, subject to the readiness terminalization CAS. If that CAS loses because the same readiness identity is already terminal (`READY`, `FAILED`, or `SUPERSEDED`), the later proof result is a no-op and cannot relabel the prior terminal outcome, including after a newer publish supersedes the candidate. Neither path creates synthetic `onLoad` handler work or a handler audit row. **Current implementation:** the notification wire has no immutable manifest-proof or handler-count fields; an empty `affectedScripts` notification returns without creating readiness, while the current projection's integer count path records `READY` with `statusReason=no_scripts_in_patch` and does not expose proof or declared/terminal counts. @@ -184,7 +184,7 @@ Concrete supersession example: Implementers should treat explicit continuity declarations plus the stable logical key as the canonical answer to "should this schedule continue?" `scheduleDefinitionId` alone is not sufficient: -- If patch `P21` contains a patrol interval with stable key `{SCRIPT, patrol, patrol.main.v1, ENTITY, guard-9}` and patch `P22` declares compatible continuity for that same key, the scheduler may preserve the row only after validating the prior `(scriptPatchVersion, scriptPinEpoch)` tuple and the exact target tuple, `source.isDryRun == target.isDryRun`, and typed cadence, interval-kind, target-binding, and playable-scope checks. It rewrites ownership, persists the target patch provenance and exact epoch, and applies the normative resume calculation before admission resumes; continuity does not require source and target tuples to be equal, and `scheduleSemanticsHash` is diagnostic evidence only. +- If patch `P21` contains a patrol interval with stable key `{SCRIPT, patrol, patrol.main.v1, playableStateNamespaceId, ENTITY, guard-9}` and patch `P22` declares compatible continuity for that same key, the scheduler may preserve the row only after validating the prior `(scriptPatchVersion, scriptPinEpoch)` tuple and the exact target tuple, `source.isDryRun == target.isDryRun`, and typed cadence, interval-kind, target-binding, and playable-scope checks. It rewrites ownership, persists the target patch provenance and exact epoch, and applies the normative resume calculation before admission resumes; continuity does not require source and target tuples to be equal, and `scheduleSemanticsHash` is diagnostic evidence only. - If either side omits continuity, explicitly resets it, changes the key/cadence/target, or authoritative reconciliation proves the target schedule absent, the scheduler atomically retires/tombstones P21, terminalizes any proven-displaced candidate under its original identity, and creates no P22 row, due state, firing claim, or `scriptEventId`. If target-definition or other required authority is unavailable, contradictory, or ambiguous, it retains P21 and its candidates/claims fenced and nonterminal; it does not tombstone or create replacement state until reconciliation. When a validated target definition exists on the reset/incompatible path, it creates P22 with fresh due state. A distinct combat-alert timer uses a new key and fresh state. - Rollback applies exactly the same opt-in matrix. A matching `scheduleDefinitionId` or historical similarity never carries due state by itself, and a one-shot timer is not migrated by this interval rule. @@ -226,7 +226,7 @@ A coalesced core script receives one execution manifest assembled from the retai Governance requirements for ordering overrides and exclusivity: - Ordering policy overrides (`PLUGIN` ahead of `SCRIPT`) are operator-controlled policy, not designer-level script metadata. -- At most one binding in the complete resolved set for the full applicable event/Trigger scope may set `requiresExclusiveEvent=true`. For instance-bound events, that scope includes `tenantId`, `gameInstanceId`, `playableStateScope`, `regionId`, `regionEpoch`, the concrete target identity, `eventType`, and `eventSchemaVersion` as applicable, plus the derived `sourceService` for custom or service-specific events; tenant-readiness `onLoad` uses its pre-instance-pin scope and intentionally omits instance, playable-state, region, and entity fields. Game Design validates publish-time-known conflicts and Automation revalidates the complete base-script plus active-plugin set at activation. Multiple or unauthorized exclusive claims fail closed; runtime does not select one by sort order. +- At most one binding in the complete resolved set for the full applicable event/Trigger scope may set `requiresExclusiveEvent=true`. For instance-bound events, that uniqueness scope includes `tenantId`, `gameInstanceId`, `playableStateNamespaceId`, `regionId`, `regionEpoch`, the concrete target identity, `eventType`, and `eventSchemaVersion` as applicable, plus the derived `sourceService` for custom or service-specific events; the server-derived `playableStateScope` is retained and exact-validated as immutable policy/routing/authorization/fence evidence, not as a uniqueness discriminator. Tenant-readiness `onLoad` uses its pre-instance-pin scope and intentionally omits instance, playable-state namespace/scope, region, and entity fields. Game Design validates publish-time-known conflicts and Automation revalidates the complete base-script plus active-plugin set at activation. Multiple or unauthorized exclusive claims fail closed; runtime does not select one by sort order. - Plugin bindings are non-exclusive by default. Granting plugin exclusivity requires explicit operator authorization and audit evidence bound to the plugin version, binding, target policy scope, and granting actor. - `orderIndex` and `handlerSequence` define semantic effect order. Operational `priorityTag`, quota tiers, and capacity policy may affect execution timing but must not reorder final command application. - Admission records must include explicit, bounded reasons when exclusivity policy blocks a binding so operators can distinguish policy denial from quota/sandbox failures. @@ -238,7 +238,8 @@ Governance requirements for ordering overrides and exclusivity: Domain services can define **custom events** that feed into the scripting pipeline: - The visual DSL exposes event source nodes for any event types enabled for the current game. Under the hood, bindings are stored as ``. -- Service-specific events follow the same trigger → DSL run → automation queue → tick command flow as built-in events. +- **Target state only:** service-specific events follow the same pre-DSL trigger/outbox → DSL run → durable descriptor/outbox → tick command flow as built-in events; the Redis automation queue remains only a derived pointer to the pre-DSL trigger record. +- **Current implementation:** the legacy service-specific event path attempts emitted commands through per-command Game Session handoff calls. It does not persist evaluated command descriptors/outbox rows or implement post-DSL descriptor replay; see [Scripting Runtime Execution: Current Implementation Status](./system-architecture-scripting-runtime-execution.md#current-implementation-status). - Event schemas are versioned so scripts can be migrated when payloads change. Custom events must follow the same determinism and idempotency rules as built-in events; the applicable identity and ingress requirements are defined in the [normative contract tables](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). @@ -355,7 +356,7 @@ The tenant lifecycle governs patch readiness and eligibility. The instance lifec Runtime execution must still remain **instance-aware** even though patch readiness is tenant-scoped: - A tenant-scoped `READY` state means a patch is eligible to be pinned by instances in that tenant; it does not imply that every running instance must pause, reload, or switch together. -- Admission, timer scheduling, and runtime work/effect fencing must evaluate the effective runtime scope as ``, even if implementations batch internal work by tenant. Pin observation and pin convergence are instance-wide control-plane state carrying the exact `` tuple. Pin-transition admission pause for promotion and rollback is separate instance-wide control-plane state keyed by `` with the existing admission epoch as state/fence; the exact pin tuple is convergence and execution-fence evidence, not pause identity. Neither control-plane state splits by `playableStateScope`. Plugin activation/configuration remains materialized per ``; plugin trigger identity and plugin-owned derived schedule/work state still carry the effective `playableStateScope`. Region and epoch fields remain required for region/tick-aligned runtime timelines. +- Admission, timer scheduling, and runtime work/effect fencing must carry the complete runtime identity ``, even if implementations batch internal work by tenant. `playableStateScope` remains separately exact-validated immutable policy/routing/authorization/fence evidence rather than a durable identity field. A non-region tenant/control-plane event must use an existing non-gameplay branch; it must not fabricate sentinel region fields or use a gameplay/runtime Trigger Identity. Pin observation and pin convergence are instance-wide control-plane state carrying the exact `` tuple. Pin-transition admission pause for promotion and rollback is separate instance-wide control-plane state keyed by `` with the existing admission epoch as state/fence; the exact pin tuple is convergence and execution-fence evidence, not pause identity. Neither control-plane state splits by `playableStateScope`. Plugin activation/configuration remains materialized per ``; plugin trigger identity and plugin-owned derived schedule/work state carry `playableStateNamespaceId` as durable identity plus the effective `playableStateScope` as immutable fence evidence. Region and epoch fields remain required for gameplay/runtime timelines. - If a deployment wants stronger coupling, it must explicitly declare the invariant that all instances in a tenant share one exact pinned script tuple. Absent that declaration, instance isolation is the normative behavior. - Instance-scoped runtime state tracks **pin observation and pin-convergence control** for the exact tuple an instance is trying to run (for example `observedPinnedScriptPatchVersion`, `observedScriptPinEpoch`, `reloadState`, and convergence checkpoints). The separate admission, schedule, work, and effect fences apply the resolved `playableStateScope` and region/epoch to trigger-derived state. Instance pin state does **not** rerun tenant patch readiness or `onLoad`. - A single tenant-wide mutable `activePatchVersion` inside Automation & Scripting is therefore not sufficient. The service must keep tenant-scoped patch readiness separate from instance-scoped pin observation and scheduling state. @@ -366,8 +367,8 @@ Side-by-side lifecycle view: | --- | --- | --- | --- | --- | | Patch readiness | `` | Automation & Scripting | `PENDING_VALIDATION` -> `ONLOAD_RUNNING` -> `READY` / `FAILED`, terminal `SUPERSEDED` | Publish ingestion, static validation, tenant-scoped `onLoad`, newer accepted publish supersession | | Runtime pin observation | ``; current observed value/fence evidence is the exact `(scriptPatchVersion, scriptPinEpoch)` tuple | Game Session pin plus Automation observation | Observed exact tuple, `reloadState=RELOADING`, observed new tuple, `reloadState=FAILED`, scoped admission/convergence checkpoints | `SetPinnedScriptPatchVersion`, `RollbackScriptPatchVersion`, pin-change events, reload reconciliation, promotion and rollback pin-transition orchestration | -| Runtime admission, schedule, work, and effect fencing | `` | Automation and domain runtime owners | Admission, due-point, work-item, command, and effect fences | Resolved trigger scope, region ownership, epoch changes, reload/rollback barriers | -| Plugin activation | `` | Automation & Scripting runtime registry | Active, pending, draining, disabled plugin version state | Operator activation/disable/drain actions; plugin trigger-derived state retains `pluginVersionId`, `bindingId`, and `playableStateScope` | +| Runtime admission, schedule, work, and effect fencing | Complete `` runtime identity; `playableStateScope` is separate exact-validated fence evidence | Automation and domain runtime owners | Admission, due-point, work-item, command, and effect fences | Resolved trigger scope, region ownership, epoch changes, reload/rollback barriers | +| Plugin activation | `` | Automation & Scripting runtime registry | Active, pending, draining, disabled plugin version state | Operator activation/disable/drain actions; plugin trigger-derived state retains `pluginVersionId`, `bindingId`, `playableStateNamespaceId`, and immutable `playableStateScope` fence evidence | Interpretation rules: diff --git a/design/architecture/system-architecture-scripting-event-registry.md b/design/architecture/system-architecture-scripting-event-registry.md index 376a41d909..e0523f7f95 100644 --- a/design/architecture/system-architecture-scripting-event-registry.md +++ b/design/architecture/system-architecture-scripting-event-registry.md @@ -68,9 +68,9 @@ Required semantics for those fields: - The exact identity fields applicable to this event at each stage: the event-scope ingress subset before handler resolution and the full handler Trigger Identity after each handler resolves, as defined by the [normative identity tables](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). - Ordinary producer event-scope ingress must not require, fabricate, or use synthetic values for handler-only fields. In particular, `scriptId`, `pluginId`, `pluginVersionId`, and `bindingId` are unavailable before handler resolution; they become required only when the resolved handler's scope requires them. - Tenant-readiness `onLoad` is the deliberate exception for `scriptId`: its event-scope identity targets one script and includes that `scriptId` so Automation can derive the deterministic `scriptEventId` before handler resolution. This does not authorize fabricated runtime-ingress script IDs; `pluginId`, `pluginVersionId`, and `bindingId` remain post-resolution fields. - - Scheduler/timer due candidates are another deliberate pre-handler exception: because Automation already materialized a durable schedule with its owner identity, the scheduler firing identity and deterministic event-scope `scriptEventId` include the schedule-owned `scriptId`, any schedule-owned `pluginId`, `pluginVersionId`, and `bindingId`, and the exact Game Session `scriptPatchVersion` and positive `scriptPinEpoch`. For plugin-owned schedules, the target candidate/firing identity additionally carries the captured `pluginActivationEpoch`; the paired `lifecycleRevision` travels with it as execution-fence evidence, and both are revalidated without becoming handler Trigger Identity fields. The paired nonblank `scriptPinControlPlaneRequestId` remains mandatory owner and fence evidence, is exact-compared for candidate/firing claims, and is propagated to durable rows and audits, but is excluded from candidate, firing, work-item claim, and uniqueness keys as well as from the derived `scriptEventId` and logical Trigger Identity. The scheduler must not fabricate a field absent from that schedule. This scheduler-owned exception does not authorize ordinary producer ingress to supply handler-only identity. **Target-state only:** the current registry/runtime path does not yet persist and propagate the plugin lifecycle pair through every required boundary, so current plugin ingress must not be described as proving this fence. - - For gameplay-originated events, the producer must resolve shared-versus-isolated realm state before making the gameplay/runtime event-scope claim or attempting durable admission. This set must then include the resolved `playableStateScope` so durable ingress/work-item identity, timer follow-up work, and operator read models do not collapse distinct playable-state namespaces that happen to share the same tenant and instance identifiers; missing or unspecified scope fails closed. - - **Target-state exact-fence requirement:** For gameplay/runtime and scheduler events, durable admission evidence must include the exact Game Session `scriptPatchVersion`, `scriptPinEpoch`, and paired owner `scriptPinControlPlaneRequestId`; a version-only or partial tuple is incomplete and cannot be admitted after a repin. The owner request ID is evidence/correlation, not a third logical Trigger Identity component. + - Scheduler/timer due candidates are another deliberate pre-handler exception: because Automation already materialized a durable schedule with its owner identity, the scheduler firing identity and deterministic event-scope `scriptEventId` include the schedule-owned `scriptId` and any schedule-owned `pluginId`, `pluginVersionId`, and `bindingId`; plugin-owned candidates also include the captured `pluginActivationEpoch`, and `CATCH_UP` candidates include `resumeWindowId`. Gameplay/runtime and scheduler candidate identity also includes the exact Game Session `(scriptPatchVersion, scriptPinEpoch)` tuple required by the target-state exact-fence rule below and the [normative identity tables](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). The paired nonblank `scriptPinControlPlaneRequestId` and captured `lifecycleRevision` travel alongside as required, exact-compared non-identity owner/fence evidence; they are excluded from candidate, firing-claim, work-item, and derived event identity. The scheduler must not fabricate a field absent from that schedule. This scheduler-owned exception does not authorize ordinary producer ingress to supply handler-only identity. + - For every gameplay-originated event, this set must unconditionally include `playableStateNamespaceId` in the applicable gameplay/runtime identity, regardless of whether the realm is shared or isolated. The producer must resolve that namespace authoritatively before admission; a missing, unresolved, stale, or contradictory namespace fails closed. An explicitly declared non-gameplay contract may omit it only when the registry entry is classified outside gameplay/runtime and uses the non-gameplay Trigger Identity branch. `playableStateScope` remains separately persisted, exact-validated policy/routing/authorization/migration-fence evidence; it is excluded from Trigger Identity, event-scope, handoff, schedule, and other uniqueness/deduplication keys. See the [normative identity tables](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). + - **Target-state exact-fence requirement:** For gameplay/runtime and scheduler events, the identity set includes the exact Game Session `scriptPatchVersion` and `scriptPinEpoch`; the paired nonblank `scriptPinControlPlaneRequestId` is separately required owner/fence evidence, exact-compared with Game Session, and excluded from registry idempotency identity and keys. A version-only or partial identity tuple is incomplete and cannot be admitted after a repin. - `snapshotAuthority` - Declares the owner-specific input source used to seed the handler-scoped input manifest. Its values remain: - `PRODUCER_SUPPLIED_TOKEN` diff --git a/design/architecture/system-architecture-scripting-examples-and-patterns.md b/design/architecture/system-architecture-scripting-examples-and-patterns.md index 7b65868700..25190f2dc4 100644 --- a/design/architecture/system-architecture-scripting-examples-and-patterns.md +++ b/design/architecture/system-architecture-scripting-examples-and-patterns.md @@ -22,7 +22,7 @@ Companion docs: ## Implementation Status -These examples are target-state first. The target evaluated-work-item lifecycle uses one durable parent work item per admitted resolved handler: it starts `PENDING_EVALUATION`, transitions to `EXECUTING`, and atomically reaches `EVALUATED_COMMITTED` with immutable evaluated command descriptors/child-dispatch rows. A handler denied before work-item materialization keeps its handler audit outcome but creates no parent work item. Executor acceptance, the execution-start charge marker, and the fenced capacity lease commit before DSL evaluation; committed descriptors are later replayed without DSL re-entry. The current legacy evaluator collects a bounded list of emitted commands and attempts a separate Game Session handoff for each. For a same-scope target, `ENQUEUED` means Game Session accepted the command into its local tick queue, while idempotent `DUPLICATE_NOOP` confirms a prior local acceptance; for a distinct target scope, `REMOTE_SCHEDULED` means only that the remote follow-up was scheduled and does not claim local tick-queue admission. That legacy handoff does not carry `commandOrdinal` or the complete Trigger/Command-Handoff Identity end-to-end, so target per-command identity, deduplication, and independent progress remain unproved. The current `automation:queue` is a pre-DSL parent-work pointer projection; target committed-descriptor replay, a rebuildable evaluated-work queue projection, end-to-end `commandOrdinal`, and independent per-command recovery/progress are unavailable. Unresolved current-live `EVALUATING` work remains fail-closed and active, and the live runtime lacks `EVALUATED_COMMITTED` descriptor replay without DSL re-entry. See [Cross-Service Contracts](./system-architecture-scripting-contracts.md#implementation-status), the [normative Command-Handoff Identity](./system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state), [ADR 0063](./decisions/adr-0063-durable-per-dispatch-script-handoff.md), and the [automation and scheduler runtime tracker](../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status). +These examples are target-state first. The target evaluated-work-item lifecycle uses one durable parent work item per admitted resolved handler: it starts `PENDING_EVALUATION`, transitions to `EXECUTING`, and atomically reaches `EVALUATED_COMMITTED` with immutable evaluated command descriptors/child-dispatch rows. A handler denied before work-item materialization keeps its handler audit outcome but creates no parent work item. Executor acceptance, the execution-start charge marker, and the fenced capacity lease commit before DSL evaluation; committed descriptors are later replayed without DSL re-entry. The current legacy evaluator collects a bounded list of emitted commands and attempts a separate Game Session handoff for each. Both current authenticated Game Session receiving RPCs (`EnqueueAutomationCommandIfAbsent` and `ScheduleRemoteFollowup`) fail closed with `FAILED_PRECONDITION` (`automation_admission_receiver_fence_unavailable`) before mutation, so this path currently proves neither local tick-queue acceptance nor remote follow-up scheduling. `ENQUEUED` and `DUPLICATE_NOOP` describe local acceptance dispositions, while `REMOTE_SCHEDULED` describes only remote follow-up scheduling; none is a successful outcome established by those current receivers. That legacy handoff does not carry `commandOrdinal` or the complete Trigger/Command-Handoff Identity end-to-end, so target per-command identity, deduplication, and independent progress remain unproved. The current `automation:queue` is a pre-DSL parent-work pointer projection; target committed-descriptor replay, a rebuildable evaluated-work queue projection, end-to-end `commandOrdinal`, and independent per-command recovery/progress are unavailable. Unresolved current-live `EVALUATING` work remains fail-closed and active, and the live runtime lacks `EVALUATED_COMMITTED` descriptor replay without DSL re-entry. See [Cross-Service Contracts](./system-architecture-scripting-contracts.md#implementation-status), the [normative Command-Handoff Identity](./system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state), [ADR 0063](./decisions/adr-0063-durable-per-dispatch-script-handoff.md), and the [automation and scheduler runtime tracker](../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status). --- @@ -48,7 +48,7 @@ This example walks through how a typical `onEnterRegion` script executes end-to- 2. **`onEnterRegion` event is emitted** - After the move is committed and the player is now in the new region, the Game Session Service emits an `onEnterRegion` **script event** to the Automation & Scripting Service over gRPC. - Conceptually this is a unary `TriggerScriptEvent` call on the Automation & Scripting Service that carries: - - `tenantId`, `gameInstanceId`, `playableStateScope`, and `regionId`. + - `tenantId`, `gameInstanceId`, and `regionId`; the target Trigger Identity additionally requires `playableStateNamespaceId`, which current `TriggerScriptEventRequest` does not carry. The current request carries `playableStateScope` separately as exact-validated policy/routing/authorization/migration-fence evidence, not as an identity field. - Target `entityId` (for example, an NPC guarding the room). - `eventType=onEnterRegion`. - The exact currently pinned `(scriptPatchVersion, scriptPinEpoch)` tuple for that game. @@ -69,18 +69,18 @@ This example walks through how a typical `onEnterRegion` script executes end-to- - Scheduling follow-up timers (for example, delayed emotes or encounter escalation). 5. **Automation queue staging** - - Actions produced by the handler are evaluated within its one durable parent work item. Target evaluation atomically reaches `EVALUATED_COMMITTED` with one immutable command descriptor/child-dispatch row per emitted command, after which committed descriptor children are indexed into `automation:queue:{tenantInstanceTag}:`; current implementation persists pre-DSL parent work and indexes only the derived parent pointer. - - The firing admission links the durable firing claim, one applicable resolved-handler audit row for every resolved handler, parent work items and queue-pointer projections only for handlers admitted by all handler-scoped gates (including quota), and due-point advancement in one atomic durable transition or a resumable idempotent recovery operation. Zero-handler firings create no handler audit, parent work item, or queue-pointer projection; handlers denied by a handler-scoped gate, including quota-denied handlers, retain an audit row but create no parent work item or queue-pointer projection. Firing-claim and queue-link recovery completes missing links from the existing claim rather than re-evaluating the handler. - - Each durable parent work item carries the originating `scriptEventId`, `scriptId`, `gameInstanceId`, `playableStateScope`, exact `scriptPatchVersion`/`scriptPinEpoch`, and region context. In the target handoff contract, each immutable emitted-command child is keyed by the complete source runtime scope plus any distinct target runtime scope, the persisted `automationDispatchId`, and deterministic `commandOrdinal` from canonical output order; both child identities are reused for every handoff, retry, and downstream disposition. The full parent Trigger Identity (including `bindingId` where applicable), `outboxWorkItemId`, and `scriptEventId` remain correlation only, while bounded `workItemIds[]` are parent-row selectors rather than child identities. The target `ListScriptHandoffEvents` child records are keyed by the complete Command-Handoff Identity, with `(automationDispatchId, commandOrdinal)` retained only as its dispatch-group suffix, and retain the full parent Trigger Identity while the handler audit remains one row. See [Implementation Status](#implementation-status) for the current live handoff boundary. + - The committed pre-DSL trigger is currently projected into `automation:queue:{tenantInstanceTag}:` as a derived parent-work pointer, but this current pointer is not rebuildable today, so queue reset/rebuild/resume remain unavailable and fail closed; see the [DSL Reference and Lifecycle implementation status](./system-architecture-scripting-dsl-reference-and-lifecycle.md#implementation-status). Actions produced by the handler are evaluated within its one durable parent work item. Target evaluation atomically reaches `EVALUATED_COMMITTED` with one immutable command descriptor/child-dispatch row per emitted command, after which committed descriptor children are indexed into the queue; current implementation persists pre-DSL parent work and indexes only the derived parent pointer. + - Ordinary event ingress such as `onEnterRegion` proceeds through event-scope admission and handler resolution/handler-scoped gates; it does not require the scheduler firing claim or due-point advancement described under the target `onInterval` timer lifecycle below. + - **Target-state only:** Each durable parent work item carries the originating `scriptEventId`, `scriptId`, `gameInstanceId`, `playableStateNamespaceId`, exact `scriptPatchVersion`/`scriptPinEpoch`, and region context. It retains `playableStateScope` separately as exact-validated policy/routing/authorization/migration-fence evidence, excluded from Trigger Identity, Command-Handoff Identity, uniqueness, and deduplication keys. The current instance-tagged queue pointer and `outboxWorkItemId`-only path do not establish namespace-complete identity or isolation. In the target handoff contract, each immutable emitted-command child is keyed by the complete source runtime scope plus any distinct target runtime scope, the persisted `automationDispatchId`, and deterministic `commandOrdinal` from canonical output order; both child identities are reused for every handoff, retry, and downstream disposition. The full parent Trigger Identity (including `bindingId` where applicable), `outboxWorkItemId`, and `scriptEventId` remain correlation only, while bounded `workItemIds[]` are parent-row selectors rather than child identities. The target `ListScriptHandoffEvents` child records are keyed by the complete Command-Handoff Identity, with `(automationDispatchId, commandOrdinal)` retained only as its dispatch-group suffix, and retain the full parent Trigger Identity while the handler audit remains one row. See [Implementation Status](#implementation-status) for the current live handoff boundary. 6. **Automation ticks and tick command enqueue** - - **Current legacy path:** For each emitted command, Automation calls Game Session over internal gRPC. For a same-scope target, Game Session admits the command idempotently and invokes tick enqueue; `ENQUEUED` means local queue admission and `DUPLICATE_NOOP` confirms prior local acceptance. For a distinct target scope, the successful `REMOTE_SCHEDULED` result records only remote follow-up scheduling and does not claim local tick-queue admission. + - **Current legacy path:** For each emitted command, Automation attempts a separate Game Session internal gRPC handoff. The authenticated current receiving RPCs fail closed with `FAILED_PRECONDITION` (`automation_admission_receiver_fence_unavailable`) before mutation, so this path does not establish local tick-queue admission or remote follow-up scheduling. The `ENQUEUED`, `DUPLICATE_NOOP`, and `REMOTE_SCHEDULED` dispositions describe acceptance outcomes, not successful outcomes proved by these current receivers. - **Target path:** Automation will later use the durable evaluated-command descriptor and rebuildable queue projection to hand resulting commands to Game Session, which owns enqueueing them into `tick:{tenantRegionTag}:queue:` using the tick engine’s Lua registry and invariants. The target descriptor/recovery and complete command identity/progress guarantees remain unavailable. 7. **Execution, audit, and observability** - On subsequent ticks, the Game Session Service selects at most one root actor action per eligible entity in the `actor_action` lane; the separately bounded `passive_effect` lane includes passive, inbound, and actor-generated effect sources without consuming that actor-action slot. Both lanes follow their canonical fairness and conflict-resolution rules. - **Automation observability (Table 4 authority; current-vs-target status):** Canonical families such as `automation_script_triggers_total`, `automation_script_skips_total`, `automation_script_triggers_dropped_total`, and `automation_tick_events_enqueued_total` have names, finite labels, and increment units owned solely by [normative Table 4](./system-architecture-scripting-normative-contract-tables.md#table-4-metrics-label-matrix); the quota counters `script_quota_allowed_total` and `script_quota_denied_total` are separately instrumented current evidence. The implemented evaluator's live `automation_script_work_item_outcomes_total` follows the Table 4 `service`, `stage`, `outcome`, `priority`, and bounded `source_class` label contract. Table 4 defines target materialized dry-run/test attempts with `automation_script_test_runs_total` (including capacity-denied results) and applicable test runtime, sandbox-failure, and `automation_script_test_capacity_denied_total` families; the canonical runs, runtime, and sandbox families remain unimplemented, while the current evaluator does emit a reused `automation_script_test_capacity_denied_total` metric with nonconforming labels. Current dry-run evidence also includes implementation-specific admission/capacity families `automation_script_test_runs_allowed_total`, `automation_script_test_runs_denied_total`, and `automation_script_test_capacity_{reserved,released}_total`; these current metrics do not prove Table 4 conformance, and dry-run terminal outcomes remain suppressed from the live family. **Target state:** an admitted live event resolving zero handlers contributes only metric-only `outcome=admitted_no_handlers`; **current implementation:** ingress still returns `admissionReason=admitted_no_handlers` and persists the ingress-audit row, with no handler-audit row. Tenant-readiness `onLoad` is separate and uses its readiness-owner `READY`/`FAILED` status and audit path, including `zero_handler_manifest_unverifiable` when applicable. The current ingress response/audit drift is documented in the [scripting observability contract](./system-architecture-scripting-observability-contract.md#ingress-audit-vs-handler-audit). - - An audit record is written to `script_event_audit` for each resolved handler Trigger Identity, with identifiers such as `scriptEventId`, `scriptId`, `tenantId`, `gameInstanceId`, `playableStateScope`, `regionId`, `regionEpoch`, and `tickId`, plus stage-aware outcome fields (`finalStage`, `finalOutcome`, `finalReason`) so operators can distinguish “DSL evaluated” from “accepted into tick queues”, enabling replay and troubleshooting as described in the same quotas and operations document. + - **Target-state audit contract:** An audit record is written to `script_event_audit` for each resolved handler Trigger Identity, with identifiers such as `scriptEventId`, `scriptId`, `tenantId`, `gameInstanceId`, `playableStateNamespaceId`, `regionId`, `regionEpoch`, and `tickId`, plus separately persisted exact-validated `playableStateScope` evidence and stage-aware outcome fields (`finalStage`, `finalOutcome`, `finalReason`) so operators can distinguish “DSL evaluated” from “accepted into tick queues”, enabling replay and troubleshooting as described in the same quotas and operations document. Current `TriggerScriptEventRequest` has no `playableStateNamespaceId`; its `playableStateScope` remains separate evidence and cannot substitute for the target namespace identity. ### Mixed Fan-Out Example @@ -116,19 +116,20 @@ If the `scriptPatchVersion` pinned by the Game Session Service for a given game This example shows how a script that runs on a fixed cadence (for example, an NPC patrol) moves through the pipeline using `onInterval`. The target scheduler admits at most one durable event-scope firing claim and one derived `scriptEventId` for each due candidate; retries reuse that claim and never create a second firing. For the target-only, unimplemented timer and failover internals (including the reserved region-scoped coordination keys `automation:timer:{tenantRegionTag}` and `script-scheduler:{tenantRegionTag}:lastTickId`, whose future stored entries must remain instance-aware), see [End-to-End `onInterval` Timer Lifecycle](./system-architecture-scripting-scheduler-and-timers.md#end-to-end-oninterval-timer-lifecycle). -The complete target fixed-cadence pipeline below—durable timer firing, evaluated command descriptors, rebuildable queue projection, and complete per-command handoff identity—is target-state only and remains unimplemented. Current live behavior is narrower but does include the legacy path: Automation reaches the pre-DSL work-item and queue-pointer projection, evaluates a bounded command list, and hands each emitted command separately to Game Session. For same-scope targets, `ENQUEUED` admits the command into the local tick queue and `DUPLICATE_NOOP` confirms prior local acceptance; for distinct target scopes, `REMOTE_SCHEDULED` records only remote follow-up scheduling and does not claim local tick-queue admission. The current pointer projection is not the target rebuildable evaluated-work projection, and target descriptor replay/recovery, end-to-end `commandOrdinal`, and independent per-command progress guarantees remain unavailable or unproved. +The complete target fixed-cadence pipeline below—durable timer firing, evaluated command descriptors, rebuildable queue projection, and complete per-command handoff identity—is target-state only and remains unimplemented. Current live behavior is narrower: Automation reaches the pre-DSL work-item and queue-pointer projection, evaluates a bounded command list, and attempts a separate Game Session handoff per emitted command. The authenticated current receiving RPCs fail closed with `FAILED_PRECONDITION` (`automation_admission_receiver_fence_unavailable`) before mutation, so these attempts prove neither local tick-queue admission nor remote follow-up scheduling. The current pointer projection is not the target rebuildable evaluated-work projection, and target descriptor replay/recovery, end-to-end `commandOrdinal`, and independent per-command progress guarantees remain unavailable or unproved. 1. **Script configuration and publish** - A designer configures an NPC patrol script in the Game Design Service, binding an `onInterval` handler with a chosen cadence (for example, every N ticks) and a sequence of waypoints. - When the script is published, its compiled DSL graph, `intervalTicks` (or equivalent cadence configuration), and version metadata are stored in the Automation & Scripting Service database and exposed under the current `scriptPatchVersion` for that game. 2. **Scheduling the next interval** - - Target-state scheduler behavior: When the NPC spawns or when the script is first loaded, the Automation & Scripting Service's scheduler registers a durable interval row retaining patch/plugin provenance. A wall-clock row carries exactly one due point; a tick-aligned row may remain `PENDING_RUNTIME_PROGRESS` without a due point until Game Session supplies runtime region/epoch and tick progress. Its stable continuity key is `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, targetScopeType, targetScopeId}`; `scriptPatchVersion`, `scriptPinEpoch`, and `pluginVersionId` remain provenance and execution-fence metadata, while a plugin-owned row also captures the Automation-owned `(pluginActivationEpoch, lifecycleRevision)` pair as execution-fence evidence, not stable schedule or continuity identity. `pluginActivationEpoch` is Automation-owned, scheduler-carried candidate/firing evidence and an input to the derived `scriptEventId`, not a separate handler field; disable/re-enable therefore gets a fresh event ID, while a lifecycle-revision mismatch fences the candidate under its captured evidence without rewriting it. The [scheduler and timer owner](./system-architecture-scripting-scheduler-and-timers.md#explicit-continuity-across-script-transitions) defines the candidate/firing identity; continuity uses that owner's full typed compatibility/fencing matrix and exact target `(scriptPatchVersion, scriptPinEpoch)` tuple. `scheduleSemanticsHash` is diagnostic evidence only. The default transition is cancel-and-recreate. Runtime `regionId`/`regionEpoch` and due state remain mutable schedule state rather than continuity identity. - - Leaders track these interval entries alongside other automation timers using bounded scans. Event gates, the durable firing claim, handler resolution, and handler-scoped gates happen first; handlers admitted by all handler-scoped gates (including quota) become durable parent work items. The later execution scheduler applies `AUTOMATION_TICK_BUDGET_MS` to the canonical ordered prefix of queued parent work items. This reservation is not actual execution time, a per-run timeout, or a capacity lease. + - Target-state scheduler behavior: When the NPC spawns or when the script is first loaded, the Automation & Scripting Service's scheduler registers a durable interval row retaining patch/plugin provenance. A wall-clock row carries exactly one due point; a tick-aligned row may remain `PENDING_RUNTIME_PROGRESS` without a due point until Game Session supplies runtime region/epoch and tick progress. Its stable continuity key is `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, playableStateNamespaceId, targetScopeType, targetScopeId}`; `scriptPatchVersion`, `scriptPinEpoch`, and `pluginVersionId` remain provenance and execution-fence metadata, while a plugin-owned row also captures the Automation-owned `(pluginActivationEpoch, lifecycleRevision)` pair as execution-fence evidence, not stable schedule or continuity identity. `pluginActivationEpoch` is Automation-owned, scheduler-carried candidate/firing evidence and an input to the derived `scriptEventId`, not a separate handler field; disable/re-enable therefore gets a fresh event ID, while a lifecycle-revision mismatch fences the candidate under its captured evidence without rewriting it. The [scheduler and timer owner](./system-architecture-scripting-scheduler-and-timers.md#explicit-continuity-across-script-transitions) defines the candidate/firing identity; continuity uses that owner's full typed compatibility/fencing matrix and exact target `(scriptPatchVersion, scriptPinEpoch)` tuple. `scheduleSemanticsHash` is diagnostic evidence only. The default transition is cancel-and-recreate. Runtime `regionId`/`regionEpoch` and due state remain mutable schedule state rather than continuity identity. + - Leaders track these interval entries alongside other automation timers using bounded scans. Event gates, the durable firing claim, handler resolution, and handler-scoped gates happen first; handlers admitted by all handler-scoped gates (including quota) become durable queued work. The later execution scheduler applies `AUTOMATION_TICK_BUDGET_MS` to the canonical ordered prefix of queued handler work. This reservation is not actual execution time, a per-run timeout, or a capacity lease. 3. **Firing `onInterval` and enforcing budgets** - When an interval becomes due, the scheduler first applies event-scope candidate gates (cadence, reload/version visibility, and applicable event-policy checks); a permanent or declared skip is recorded by a deterministic `scheduleCandidateId` derived from the complete event-scope due-candidate identity defined by the [scheduler and timer owner](./system-architecture-scripting-scheduler-and-timers.md#interval-entry-identity-and-due-point-persistence), including required `stableOwnerKind`/`stableOwnerId` and, only for `triggerMode=CATCH_UP`, `resumeWindowId` (whose only generation component is `resumeGeneration`), plus captured `(pluginActivationEpoch, lifecycleRevision)` evidence for plugin-owned schedules. For plugin-owned schedules, `pluginActivationEpoch` is the tagged candidate/firing/derived `scriptEventId` identity field and input to that deterministic derivation; `lifecycleRevision` travels as fence evidence only. Core schedules use the exact `(scriptPatchVersion, scriptPinEpoch)` tuple and do not imply a separate core generation. A transient reload/reconciliation/authority-fence outcome instead retains the same due-candidate state under the complete applicable exact fence predicate: the original exact tuple, runtime scope/region epoch, schedule-owned provenance and binding, owner evidence, and captured lifecycle pair when plugin-owned, with no terminal candidate audit or `finalStage`/`finalOutcome`; only when every predicate element still matches may it resume after reconciliation. A lifecycle-revision mismatch fences the candidate under its captured evidence; reconciliation never refreshes or rebinds it. If authoritative evidence proves any other predicate no longer matches, the candidate does not resume or rebind and follows the scheduler owner's applicable terminal candidate outcome/reason; unavailable or ambiguous authority remains fenced and nonterminal. Retries reuse the candidate, firing claim, and derived `scriptEventId` only while the complete applicable candidate identity and captured fence evidence remain unchanged; all other runtime scope/region epoch, exact pin tuple, schedule-owned binding/provenance, due point, catch-up window, and plugin activation-epoch mismatches remain fenced. Core schedules require the same exact pin tuple and no separate core generation. An activation-epoch or core exact-tuple transition fences the old identity and derives a fresh one only before the new candidate is admitted. A lifecycle-revision-only change never mints a replacement candidate: a `DRAINING` transition cannot start a new firing, while already-admitted work may retain the existing identity only with ADR 0119's winning admission/fence CAS committed before the durable drain barrier. Neither path creates a firing claim, `scriptEventId`, or handler identity until its candidate gates pass. The lifecycle pair is not part of stable schedule/continuity identity, handler Trigger Identity, or Command-Handoff Identity. After handlers are bound, all handler-scoped gates run; a quota denial is handler-scoped `ADMISSION/quota_denied` with no work item, queue projection, lease, or execution marker, while only handlers admitted by all handler-scoped gates (including quota) create durable queued work. The later execution scheduler considers queued handler work in canonical order for the artifact-estimate prefix reservation; its remainder remains durably queued/deferred. When a handler is selected, a separately fenced capacity lease is acquired and its fence, executor acceptance, execution-start marker, and `EXECUTING` transition commit in one Automation-owned durable transaction before evaluation. The firing transition records one audit row for every resolved handler, including denied handlers, and creates work/queue projections only for handlers admitted by all handler-scoped gates; firing-claim and queue-link retries do not re-run the DSL, while eligible pre-`EVALUATED_COMMITTED` evaluation recovery may re-run the frozen DSL under the original identity and evidence. - If multiple handlers are bound to the timer event, the timer firing is admitted once at event scope and then fans out into handler-scoped Trigger Identities whose outcomes are tracked independently. + - **Target timer-firing transition only:** Firing admission links the durable firing claim, one applicable resolved-handler audit row for every resolved handler, parent work items and queue-pointer projections only for handlers admitted by all handler-scoped gates (including quota), and due-point advancement in one atomic durable transition or a resumable idempotent recovery operation. Zero-handler firings create no handler audit, parent work item, or queue-pointer projection; handlers denied by a handler-scoped gate retain an audit row but create no parent work item or queue-pointer projection. Firing-claim and queue-link recovery completes missing links from the existing claim rather than re-evaluating the handler. See the [scheduler and timer owner](./system-architecture-scripting-scheduler-and-timers.md#end-to-end-oninterval-timer-lifecycle). - If an event-scope candidate gate is a permanent or declared skip, the due candidate is terminally consumed and recorded in metrics and an event-scope audit keyed by the same complete event-scope `scheduleCandidateId` identity. A transient reload/reconciliation/authority-fence gate instead retains the same due-candidate state and canonical due point under the complete applicable exact fence predicate described above, including the captured `(pluginActivationEpoch, lifecycleRevision)` pair and runtime-scope, binding, and owner evidence; without a terminal candidate audit or `finalStage`/`finalOutcome`, only that unchanged predicate may resume after reconciliation. A lifecycle-revision mismatch fences the candidate under its captured evidence; reconciliation never refreshes or rebinds it. Any other non-match remains governed by the scheduler owner's existing fenced/terminal resolution and is not rebound. Neither path creates a firing claim, handler Trigger Identity, or `scriptEventId`; `scriptEventId` is minted only after firing claim/admission succeeds. Handler quota denial after a firing claim is instead recorded under that handler's full Trigger Identity and does not consume the candidate as an event-scope skip. - If the event-scope candidate is allowed, the scheduler enqueues the `onInterval` trigger for sandbox execution and advances the canonical due point (`dueTickId` for tick cadence or `dueAt` for wall-clock cadence) according to the cadence or resume rule within that atomic durable firing transition or its resumable idempotent recovery operation, and then derives `nextTick` or `nextRunAt` from that due point. This keeps the cadence stable even if some intervals are occasionally delayed by load. If the timer survives a reload or rollback because the logical schedule is preserved, the next due point is recalculated from the canonical resume rule rather than by replaying the paused window. @@ -136,10 +137,10 @@ The complete target fixed-cadence pipeline below—durable timer firing, evaluat - The `onInterval` handler runs inside the sandboxed DSL engine, evaluating conditions such as “is the NPC currently out of combat?” and “is the patrol still active?” before deciding on the next waypoint or behavior. - Actions produced by the handler (for example, “move to the next patrol room,” “play an emote,” “schedule an `onTimerExpire` follow-up”) are evaluated within one durable parent work item. Target evaluation atomically reaches `EVALUATED_COMMITTED` with one immutable command descriptor/child-dispatch row per emitted command, after which committed descriptor children are indexed into `automation:queue:{tenantInstanceTag}:`; current implementation persists pre-DSL parent work and indexes only the derived parent pointer. - **Request validation:** `payloadJson` is bounded before the event-scope claim; an oversized envelope returns non-OK gRPC `INVALID_ARGUMENT` with no claim, admission result/fields, queue work, `script_event_ingress_audit` row or ingress-drop metric, or handler `script_event_audit` row. It does not use `TRIGGER_ADMISSION_OUTCOME_OUTPUT_BUDGET_EXCEEDED`. **Handler-time behavior:** current command-count and per-entity ceilings are enforced while expanding legacy emitted commands. **Target-only behavior:** serialized generated-output byte/data-dependent metering is applied during DSL evaluation before descriptor commit and remains unavailable/unproven in the current runtime. A missing or conflicting artifact-cost digest is a distinct event-scope `OUTPUT_BUDGET_EXCEEDED` outcome, while a handler that exceeds an enforced runtime cap uses its handler-scoped `DSL_EVAL` outcome/reason. Handler-time output failures are bounded non-success outcomes rather than unbounded backlog. - - Target-state work-item behavior: Each durable parent work item carries the full applicable Trigger Identity, including `scriptEventId`, `scriptId`, `gameInstanceId`, `playableStateScope`, version metadata, and the immutable trigger-created `regionId` and `regionEpoch`. Plugin-backed work also retains its captured `(pluginActivationEpoch, lifecycleRevision)` pair unchanged through the durable queue, handoff, retry, replay, recovery, and final execution, revalidating it as fence evidence rather than handler or command identity. If current entity state is needed to route the work at enqueue time, persist separate fields such as `enqueueRegionId` and `enqueueRegionEpoch`; never overwrite the original trigger fields. Deduplication, fencing, and replay continue to use the original `regionId` and `regionEpoch`. In the target handoff contract, each immutable emitted-command child uses the complete source runtime scope plus any distinct target runtime scope, a persisted `automationDispatchId`, and deterministic `commandOrdinal` from canonical output order; retries reuse that complete child identity. Parent Trigger Identity, `outboxWorkItemId`, and `scriptEventId` remain correlation only. See [Implementation Status](#implementation-status) for the current live handoff boundary. + - Target-state work-item behavior: Each durable parent work item carries the full applicable Trigger Identity, including `scriptEventId`, `scriptId`, `gameInstanceId`, `playableStateNamespaceId`, version metadata, and the immutable trigger-created `regionId` and `regionEpoch`; it retains `playableStateScope` separately as exact-validated policy/routing/authorization/migration-fence evidence. Plugin-backed work also retains its captured `(pluginActivationEpoch, lifecycleRevision)` pair unchanged through the durable queue, handoff, retry, replay, recovery, and final execution, revalidating it as fence evidence rather than handler or command identity. If current entity state is needed to route the work at enqueue time, persist separate fields such as `enqueueRegionId` and `enqueueRegionEpoch`; never overwrite the original trigger fields. Deduplication, fencing, and replay continue to use the original `regionId` and `regionEpoch`. In the target handoff contract, each immutable emitted-command child uses the complete source runtime scope plus any distinct target runtime scope, a persisted `automationDispatchId`, and deterministic `commandOrdinal` from canonical output order; retries reuse that complete child identity. Parent Trigger Identity, `outboxWorkItemId`, and `scriptEventId` remain correlation only. See [Implementation Status](#implementation-status) for the current live handoff boundary. 5. **Execution, audit, and observability** - - **Target state only/unimplemented:** Automation later claims each durable parent work item in `PENDING_EVALUATION`, transitions the parent to `EXECUTING` under the fenced capacity lease, and atomically commits emitted command descriptors/child-dispatch rows at `EVALUATED_COMMITTED`; it uses `automation:queue` only as a rebuildable pointer index over committed descriptor children and hands resulting commands to the Game Session Service over internal gRPC so Game Session can enqueue them into the appropriate `tick:{tenantRegionTag}:queue:`. **Current legacy:** Automation drains the pre-DSL `automation:queue` parent-pointer projection (with a durable-scan fallback), evaluates each bounded parent work item, and attempts one Game Session handoff per emitted command. For same-scope targets, `ENQUEUED` means Game Session accepted the command into the local tick queue and `DUPLICATE_NOOP` confirms prior local acceptance; for distinct target scopes, `REMOTE_SCHEDULED` means only that the remote follow-up was scheduled and does not claim local tick-queue admission. Target descriptor replay/recovery, a rebuildable evaluated-work projection, complete command identity/`commandOrdinal` propagation, and independent per-command progress are unavailable or unproved. + - **Target state only/unimplemented:** Automation later claims each durable parent work item in `PENDING_EVALUATION`, transitions the parent to `EXECUTING` under the fenced capacity lease, and atomically commits emitted command descriptors/child-dispatch rows at `EVALUATED_COMMITTED`; it uses `automation:queue` only as a rebuildable pointer index over committed descriptor children and hands resulting commands to the Game Session Service over internal gRPC so Game Session can enqueue them into the appropriate `tick:{tenantRegionTag}:queue:`. **Current legacy:** Automation drains the pre-DSL `automation:queue` parent-pointer projection (with a durable-scan fallback), evaluates each bounded parent work item, and attempts one Game Session handoff per emitted command. The current authenticated receiving RPCs fail closed with `FAILED_PRECONDITION` (`automation_admission_receiver_fence_unavailable`) before mutation, so these attempts prove neither local tick-queue acceptance nor remote follow-up scheduling; see [Implementation Status](#implementation-status). Target descriptor replay/recovery, a rebuildable evaluated-work projection, complete command identity/`commandOrdinal` propagation, and independent per-command progress are unavailable or unproved. - On subsequent ticks, the Game Session Service selects at most one root actor action per eligible entity in the `actor_action` lane; the separately bounded `passive_effect` lane includes passive, inbound, and actor-generated effect sources without consuming that actor-action slot. Patrol movements and emotes follow the canonical lane fairness and conflict-resolution rules. - **Target-state observability only:** `automation_script_triggers_total` increments once per resolved live handler using its applicable outcome and the finite scheduler/timer `event_class` value owned by [normative Table 4](./system-architecture-scripting-normative-contract-tables.md#table-4-metrics-label-matrix), not once per interval. An admitted live event that resolves zero handlers increments once at event scope with metric-only `outcome=admitted_no_handlers`; this target example does not imply dry-run metrics or execution. If a resolved handler produces work that is accepted into tick queues, `automation_tick_events_enqueued_total` increases. The evaluator's live `automation_script_work_item_outcomes_total` uses the Table 4 label contract and excludes dry-run/test executions. Canonical dry-run/test terminal, runtime, and sandbox-failure families remain target-only; current dry-run evidence is limited to its implemented quota and capacity admission counters. Zero-handler ingress returns `admitted=true`, `admissionOutcome=TRIGGER_ADMISSION_OUTCOME_ADMITTED`, and `resolvedHandlerCount=0`; `admitted_no_handlers` is metric-only and is not returned or persisted in `script_event_ingress_audit` or `script_event_audit`. See the [scripting observability contract](./system-architecture-scripting-observability-contract.md#ingress-audit-vs-handler-audit) for the target/current boundary. An audit record is written to `script_event_audit` per resolved handler so missed or delayed intervals can be debugged using stage-aware fields (`finalStage`, `finalOutcome`, `finalReason`) alongside identifiers like `scriptEventId`, `scriptId`, `scheduleDefinitionId`, the persisted due point, and `tickId`. - The target `ListScriptHandoffEvents` view composes downstream execution dispositions keyed by the complete source/optional-target Command-Handoff Identity, with persisted `automationDispatchId` and deterministic `commandOrdinal`; `(automationDispatchId, commandOrdinal)` is only its suffix. Parent Trigger Identity, `outboxWorkItemId`, `workItemIds[]`, and `scriptEventId` are correlation/selectors only and cannot replace that child identity. See [Implementation Status](#implementation-status) for the current live read boundary and the metrics and audit sections in `design/architecture/system-architecture-scripting-quotas-and-operations.md` for interpretation. @@ -158,7 +159,7 @@ Recurring timer-driven handlers such as `onInterval` produce at most one event-s `scheduleDefinitionId` participates in the stable compiled continuity key but does not by itself decide whether a logical timer survives publish, reload, or rollback. Initial materialization and default/incompatible reset transitions create a new physical durable row and retire the displaced row. A valid explicitly declared, typed-compatible continuity transition instead preserves the existing stable row, rewrites its target patch/plugin provenance and exact pin/epoch fencing metadata in place, and recalculates its due point without creating a replacement row or tombstone; the logical key must not be confused with a row or firing-claim identity: -For carry-forward, match the stable schedule-instance identity and the stable logical continuity key `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, targetScopeType, targetScopeId}` within the applicable tenant/instance scope, then apply the explicit typed compatibility checks. `scheduleSemanticsHash` and displaced/replacement patch or plugin versions are transition-mapping provenance and exact execution-fence evidence, not immutable continuity identity; matching only `scheduleDefinitionId` or semantic similarity is insufficient. +For carry-forward, match the stable schedule-instance identity and the stable logical continuity key `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, playableStateNamespaceId, targetScopeType, targetScopeId}` within the applicable tenant/namespace scope, then apply the explicit typed compatibility checks. `scheduleSemanticsHash` and displaced/replacement patch or plugin versions are transition-mapping provenance and exact execution-fence evidence, not immutable continuity identity; matching only `scheduleDefinitionId` or semantic similarity is insufficient. - If patch `P11` and patch `P12` both define the NPC patrol timer as "run every 30 ticks while patrol is enabled", both explicitly declare the same stable continuity key, `source.isDryRun == target.isDryRun`, and cadence, target, and playable scope are compatible, Automation preserves the existing stable row, rewrites its target patch/plugin provenance and exact pin/epoch fencing metadata in place, and applies the resume calculation without creating a replacement row or tombstone. The in-place update is atomic or resumable/idempotent. After a due candidate passes admission, the scheduler creates a separate firing claim and `scriptEventId` keyed by the complete candidate identity; the stable schedule row remains distinct from the firing claim and event identity, while the old owner history is not reused as a new row. - If either side omits continuity, explicitly resets it, changes cadence/target/scope/key, or authoritative reconciliation proves the target definition absent, the scheduler atomically retires/tombstones P11 and terminalizes any proven-displaced candidate under its original identity. It creates no P12 replacement row, due state, firing claim, or `scriptEventId`; only a validated replacement definition, after target schedule reconciliation, may receive fresh due state and proceed to exact admission. If target-definition or other required authority is unavailable, contradictory, or ambiguous, P11 and its candidates/claims remain fenced and nonterminal and neither tombstoning nor replacement occurs until reconciliation. Existing P11 firing claims and candidate audits retain their original exact patch/epoch and resume-window metadata; only pending firing claims may be fenced or terminal-marked, while candidate-audit identities and outcomes remain immutable and are never rewritten or reused by P12. P12 claims are created only after target schedule reconciliation and exact admission. Rollback to P11 follows the same matrix; hash equality or historical similarity never grants continuity. diff --git a/design/architecture/system-architecture-scripting-normative-contract-tables.md b/design/architecture/system-architecture-scripting-normative-contract-tables.md index ef97810239..2641275542 100644 --- a/design/architecture/system-architecture-scripting-normative-contract-tables.md +++ b/design/architecture/system-architecture-scripting-normative-contract-tables.md @@ -35,7 +35,11 @@ This ordering does not supersede accepted ADR decisions. Accepted ADRs remain bi ## Table 1: Trigger Identity (Required Fields) -Trigger Identity is the composite idempotency identity for logical work/effect materialization of this resolved handler for this trigger at most once, and the natural primary key for handler-scoped `script_event_audit` records. This logical at-most-once boundary does not prohibit a frozen-input DSL re-evaluation attempt for eligible gameplay/runtime work before `EVALUATED_COMMITTED`; after that boundary, recovery never re-enters the DSL. `scriptEventId` is the stable, producer-namespaced parent-event token within the applicable event scope; it is not a globally unique standalone execution identity or a substitute for all other applicable identity fields. Incoming requests use the separate event-scope identity defined below until handler resolution completes. The handler-scoped input manifest defined by the [DSL lifecycle owner](./system-architecture-scripting-dsl-reference-and-lifecycle.md#read-consistency-contract) is durable evaluation input, not an additional Trigger Identity field; its owner versions and causal floor must be retained with the handler record. For gameplay/runtime work, `scriptPatchVersion` and the Game Session-owned `scriptPinEpoch` are the inseparable exact execution tuple; matching patch text under a different epoch is a fence mismatch. The captured `scriptPinControlPlaneRequestId` is mandatory paired owner evidence/correlation for that tuple, retained immutably but excluded from logical identity and the trigger/candidate claim uniqueness and conflict keys governed here; it must still match the authoritative owner evidence through ingress, persistence, replay, and finalization. For plugin work, the captured `(pluginActivationEpoch, lifecycleRevision)` pair is required execution-fence evidence and is deliberately excluded from handler Trigger Identity. +Trigger Identity is the composite idempotency identity for logical handler work and handler-scoped evaluated-descriptor materialization of this resolved handler for this trigger at most once, and the natural primary key for handler-scoped `script_event_audit` records. It does not govern downstream gameplay effect materialization: authoritative effect idempotency belongs to the persisted mutation `EffectId` (the root `EffectId` for a root mutation or the generated child's persisted `EffectId` for a child mutation), typed operation, exact target aggregate, and immutable request digest. Any enclosing `rootEffectId` is lineage and reconciliation context only. This logical at-most-once boundary does not prohibit a frozen-input DSL re-evaluation attempt for eligible gameplay/runtime work before `EVALUATED_COMMITTED`; after that boundary, recovery never re-enters the DSL. `scriptEventId` is the stable, producer-namespaced parent-event token within the applicable event scope; it is not a globally unique standalone execution identity or a substitute for all other applicable identity fields. Incoming requests use the separate event-scope identity defined below until handler resolution completes. The handler-scoped input manifest defined by the [DSL lifecycle owner](./system-architecture-scripting-dsl-reference-and-lifecycle.md#read-consistency-contract) is durable evaluation input, not an additional Trigger Identity field; its owner versions and causal floor must be retained with the handler record. For gameplay/runtime work, `scriptPatchVersion` and the Game Session-owned `scriptPinEpoch` are an inseparable exact execution tuple; matching patch text under a different epoch is a fence mismatch. For plugin work, the captured `(pluginActivationEpoch, lifecycleRevision)` pair is required execution-fence evidence and is deliberately excluded from handler Trigger Identity. + +For applicable gameplay/runtime identities, `playableStateNamespaceId` is the durable playable-state uniqueness/allocation dimension. The server-derived `playableStateScope` is immutable within one playable-state lifecycle and is policy/routing/authorization/migration-fence evidence that must be persisted and exact-validated; a missing, stale, or mismatched scope fails closed. `playableStateScope` is not a Trigger Identity, event-scope, handoff, schedule, resume-window, or other uniqueness/deduplication dimension. A presented scope mismatch therefore requires authoritative reconciliation before admission: only stale or incorrect evidence with unchanged authoritative scope may reuse the namespace-keyed identity; an authoritative scope-policy transition starts a new playable-state lifecycle and selects or allocates a new `playableStateNamespaceId` before fresh durable identity is admitted. + +Downstream gameplay effects emitted by a handler use the ordinary Game Session effect-admission boundary, not Trigger Identity. Full Trigger Identity governs resolved handler work, including handler-scoped audit and deduplication, only. The complete applicable Command-Handoff Identity governs emitted-command handoff admission and deduplication; `scriptEventId`, the rest of Trigger Identity, and handler lineage remain separate correlation identities. The accepted effect contract requires downstream mutations to preserve the persisted mutation `EffectId`, typed operation, exact target aggregate, and immutable request digest through retries and participant guards. Deterministic command-plan ordering, `planOrdinal`, and root-allocation behavior remain proposal-only in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). Ordinary producer event-ingress RPCs into Automation & Scripting (for example `TriggerScriptEvent`) use two-stage deduplication: @@ -48,8 +52,9 @@ Required Trigger Identity fields for all triggers: | --- | --- | --- | | `tenantId` | Yes | Tenant/project identity. | | `gameInstanceId` | Yes | Required to avoid collisions when a tenant has multiple instances. Must be carried through audit and downstream idempotency. | -| `playableStateScope` | Yes (gameplay/runtime) | Resolved admitted gameplay-state namespace. Shared and isolated realm state must not collide even when other runtime identity fields match. | -| `regionId` | Yes (gameplay/runtime) | Region context for the trigger. If a trigger is not region-scoped (rare), it must declare its own scope explicitly and still include `gameInstanceId`. | +| `playableStateNamespaceId` | Yes (gameplay/runtime) | Durable playable-state namespace used in Trigger Identity uniqueness/allocation. Shared, isolated, and playtest state namespaces must not collide even when other runtime identity fields match. | +| `playableStateScope` | Yes (gameplay/runtime) | Server-derived playable-state policy/routing/authorization/migration-fence evidence, immutable for the namespace during one playable-state lifecycle. Persist and exact-validate it with the handler record; a missing or mismatched value fails closed. It is required evidence but is excluded from Trigger Identity uniqueness/deduplication. An authority-proven scope transition requires a new playable-state lifecycle/namespace rather than reuse. | +| `regionId` | Yes (gameplay/runtime) | Region context for every gameplay/runtime trigger. Non-region tenant/control-plane events use an existing non-gameplay branch rather than a gameplay/runtime Trigger Identity. | | `regionEpoch` | Yes (gameplay/runtime) | Required for any trigger emitted from, aligned to, or fenced by the tick timeline. This includes standard gameplay lifecycle events emitted after tick commit (for example `onEnterRegion`, `onSpawn`, `onCommand`) and all scheduler/timer events. | | `entityId` | Yes (entity-scoped) | Required for entity-scoped triggers. | | `scriptId` | Yes | The script definition identity that will run. If bindings fan out, each `` is a distinct Trigger Identity. | @@ -78,7 +83,9 @@ Additional required fields for scheduler/timer triggers: Plugin-owned schedule rows, due candidates, firing claims, candidate audits, and timer-derived work retain the captured `lifecycleRevision` alongside `pluginActivationEpoch`. The revision is fence evidence only: before a new firing claim or handler admission, the scheduler must observe the exact current lifecycle tuple and require the current revision in `ENABLED`; it may not use the `DRAINING` predecessor exception for a new firing. A same-epoch lifecycle revision change fences the old candidate under its existing identity and does not mint a fresh candidate identity merely because the revision changed. Already-admitted work may use the narrowly retained immediately preceding `ENABLED` revision only with ADR 0119's durable pre-`DRAINING` admission/fence evidence and same-version/same-epoch rule. -Before handler resolution, a scheduler/timer firing claim is keyed by the complete durable schedule-instance identity, exact `scriptPatchVersion`, positive `scriptPinEpoch`, `isDryRun`, applicable runtime scope, target selector, trigger mode, and tagged due point; the paired nonblank `scriptPinControlPlaneRequestId` is retained immutably as owner evidence for validation/correlation but is excluded from this claim/conflict key and is not execution identity. When `triggerMode=CATCH_UP`, `resumeWindowId` is additionally required and participates in claim uniqueness and `scriptEventId` derivation, and it is absent otherwise. It therefore includes schedule-owned `scriptId` and any schedule-owned `pluginId`, `pluginVersionId`, and `bindingId`; for plugin-owned candidates, the captured `pluginActivationEpoch` is an additional tagged field in the local `scheduleCandidateId`/firing-claim uniqueness key, while core-script candidates omit it. Same-epoch retries reuse that candidate identity only while the complete captured fence evidence remains current; for plugin-owned schedules, a same-version disable/re-enable derives a fresh candidate identity from the newer `pluginActivationEpoch`. `pluginActivationEpoch` is not a separate handler Trigger Identity field: it is included in the candidate, firing-claim, and candidate-audit identities and is an input to the scheduler-derived `scriptEventId`, so a fresh activation epoch yields a fresh event ID transitively in every resolved handler identity. Core schedule transition identity changes only through the accepted exact `scriptPatchVersion`/`scriptPinEpoch` contract; no separate core epoch is implied. It must not fabricate fields absent from the durable schedule. Candidate audits use that same complete due-candidate identity, including the exact patch, positive epoch owner evidence, and `isDryRun`, captured plugin activation epoch when applicable, and `resumeWindowId` only for `CATCH_UP`; the owner request ID is retained/read back for validation and correlation but does not expand execution identity. This owner-known firing identity is distinct from the ordinary producer event-ingress key below and derives the one event-scope `scriptEventId` propagated to resolved handlers. After resolution, each plugin child uses the captured handler execution identity above; only scheduler candidate/firing-claim/audit identities include activation epoch directly, while the scheduler-derived `scriptEventId` makes it differ transitively in the handler Trigger Identity. `lifecycleRevision` is retained and revalidated alongside it as non-identity fence evidence and is not added to those identities. Neither lifecycle value is part of Command-Handoff Identity, stable schedule-row identity, or the stable continuity key. Durable schedule rows, due candidates, firing claims, candidate audits, and list/read projections persist and expose the exact plugin activation epoch and captured lifecycle revision as fence evidence; `scriptPinEpoch` remains execution/fence metadata and is excluded from the stable continuity key. +Before handler resolution, a scheduler/timer firing claim is keyed by the complete durable logical schedule/event identity: the stable logical schedule continuity fields together with exact `scriptPatchVersion` and `scriptPinEpoch`, `isDryRun`, applicable runtime scope, target selector, trigger mode, and tagged due point; when `triggerMode=CATCH_UP`, `resumeWindowId` is additionally required and participates in claim uniqueness and `scriptEventId` derivation, and it is absent otherwise. The physical `scheduleInstanceId` is retained only as immutable row-generation metadata for durable lookup and reconciliation; it is explicitly excluded from `scheduleCandidateId`, firing-claim uniqueness, and `scriptEventId` derivation. Core-owned schedules include their schedule-owned `scriptId`; plugin-owned schedules use their schedule-owned `pluginId`, `pluginVersionId`, and `bindingId` without adding a synthetic `scriptId`. For plugin-owned candidates, the captured `pluginActivationEpoch` is an additional tagged field in the local `scheduleCandidateId`/firing-claim uniqueness key, while core-script candidates omit it. Same-epoch retries reuse that candidate identity only while the complete captured fence evidence remains current; for plugin-owned schedules, a same-version disable/re-enable derives a fresh candidate identity from the newer `pluginActivationEpoch`. `pluginActivationEpoch` is not a separate handler Trigger Identity field: it is included in the candidate, firing-claim, and candidate-audit identities and is an input to the scheduler-derived `scriptEventId`, so a fresh activation epoch yields a fresh event ID transitively in every resolved handler identity. Core schedule transition identity changes only through the accepted exact `scriptPatchVersion`/`scriptPinEpoch` contract; no separate core epoch is implied. It must not fabricate fields absent from the durable schedule. Candidate audits use that same complete due-candidate identity, including the exact patch and epoch, `isDryRun`, captured plugin activation epoch when applicable, and `resumeWindowId` only for `CATCH_UP`. This owner-known firing identity is distinct from the ordinary producer event-ingress key below and derives the one event-scope `scriptEventId` propagated to resolved handlers. After resolution, each plugin child uses the captured handler execution identity above; only scheduler candidate/firing-claim/audit identities include activation epoch directly, while the scheduler-derived `scriptEventId` makes it differ transitively in the handler Trigger Identity. `lifecycleRevision` is retained and revalidated alongside it as non-identity fence evidence and is not added to those identities. Neither lifecycle value is part of Command-Handoff Identity, stable schedule-row identity, or the stable continuity key. Durable schedule rows, due candidates, firing claims, candidate audits, and list/read projections persist and expose the exact plugin activation epoch and captured lifecycle revision as fence evidence; `scriptPinEpoch` remains execution/fence metadata and is excluded from the stable continuity key. + +For scheduler/timer identities, the applicable `playableStateNamespaceId` is the durable playable-state identity component carried in the schedule instance, due candidate, firing claim, candidate audit, and derived `scriptEventId`. The server-derived `playableStateScope` is retained alongside those records as separately persisted exact-validated policy/routing/authorization/migration-fence evidence; it is not added to schedule, candidate, firing-claim, event-scope, or handler uniqueness. Missing or mismatched scope evidence fails closed and fences admission until authoritative reconciliation. Only a stale or incorrect presented scope with unchanged authoritative scope may resume the existing namespace-keyed identity; an authority-proven scope transition starts a new playable-state lifecycle and namespace before fresh schedule state is admitted. | Field | Required | Notes | | --- | --- | --- | @@ -86,6 +93,14 @@ Before handler resolution, a scheduler/timer firing claim is keyed by the comple | Exactly one of `dueTickId` or `dueAt` | Yes | A tagged due point is required so scheduler `scriptEventId` can be deterministic and catch-up behavior can be audited. The alternate field must be absent/`NULL`; both populated or both absent are invalid for scheduler triggers. | | `triggerMode` | Yes | `NORMAL` vs `CATCH_UP` to make bounded catch-up observable. | +### Scheduler Candidate Identity Preimage (Normative) + +The canonical scheduler preimage fields are serialized in this fixed order: ``. The target implementation in `ScriptScheduleInstanceServiceImpl.TimerFiringCandidate.identity()` must serialize these fields in this order; the current live implementation remains narrower and does not yet implement this target preimage. Fields marked `when ...` are omitted, not replaced by empty or sentinel values, when their branch does not apply; `targetScopeType` makes the target selector explicit and `stableOwnerKind` makes the core/plugin owner branch explicit. The server-derived `playableStateScope` remains immutable policy/routing/authorization/fence evidence and is not a preimage or uniqueness input. `scriptEventId` itself is excluded from the preimage, and `resumeWindowId` is absent for non-catch-up triggers. `duePoint` is exactly one tagged value: `dueTickId:` for tick-aligned schedules or `dueAt:` for wall-clock timers. Any additional scheduler schema version or trigger mode must become an explicit deterministic-ID input before it is admitted. This permits delimiters and arbitrary UTF-8 text without creating tuple collisions. + +Serialize the preimage as fixed-order, length-prefixed UTF-8 fields. Encode each field as its UTF-8 byte length rendered as unsigned base-10 ASCII decimal with no leading zeroes, followed by a colon and its unescaped UTF-8 value; concatenate fields without separators. Numeric identity values use canonical base-10 ASCII spelling (for example, `0`, `7`, and `-1`), and the prefix length counts UTF-8 bytes rather than Unicode code points. Semantic validation controls which numeric values are admissible; deterministic decimal serialization does not make an otherwise invalid value valid. Booleans serialize as lowercase `true` or `false`. Enum values use the contract-declared enum symbol/name, never an ordinal, localized spelling, or implementation-specific representation. Hash the serialized bytes with SHA-256, encode the digest as lowercase hexadecimal, retain the first 60 hexadecimal characters, and prefix the result with `timer-`. + +Before this identity is considered proven, cross-producer golden vectors must cover empty values, non-ASCII values, delimiters, negative and zero numeric values, both boolean values, representative enum branches, and both tagged due-point branches. Proof also covers optional-branch omission and exact retry reuse without collisions or duplicate logical triggers. Select validation through the shared [Validation and Runtime Proof](../developer-workflows/validation-and-runtime-proof.md) workflow. + Additional required fields and exceptions for tenant-readiness lifecycle triggers: | Field | Required | Notes | @@ -97,7 +112,7 @@ Additional required fields and exceptions for tenant-readiness lifecycle trigger | `scriptPatchVersion` | Yes | Pending patch being validated for tenant readiness. | | `scriptEventId` | Yes | Deterministically generated by Automation & Scripting from all non-generated applicable onLoad identity fields, including ``. | | `isDryRun` | Yes | Must be `false` for readiness `onLoad`; dry-run/test `onLoad` probes use the dry-run/test ingress contract instead. | -| `gameInstanceId`, `playableStateScope`, `regionId`, `regionEpoch`, `entityId` | No | `onLoad` is tenant-readiness work and is not tied to a running instance, gameplay-state namespace, region, tick epoch, or entity. These fields must be absent rather than populated with sentinel values. | +| `gameInstanceId`, `playableStateNamespaceId`, `playableStateScope`, `regionId`, `regionEpoch`, `entityId` | No | `onLoad` is tenant-readiness work and is not tied to a running instance, playable-state namespace, playable-state policy, region, tick epoch, or entity. These fields must be absent rather than populated with sentinel values. | Ordinary producer event-scope ingress identity before handler resolution: @@ -105,7 +120,8 @@ Ordinary producer event-scope ingress identity before handler resolution: | --- | --- | --- | | `tenantId` | Yes | Tenant/project identity. | | `gameInstanceId` | Yes (runtime ingress) | Required for runtime ingress fences such as reload, rollback pause, and pin visibility. | -| `playableStateScope` | Yes (gameplay/runtime ingress) | Resolved admitted gameplay-state namespace carried before handler fan-out. | +| `playableStateNamespaceId` | Yes (gameplay/runtime ingress) | Durable playable-state namespace identity carried before handler fan-out and included in the event-scope uniqueness key. | +| `playableStateScope` | Yes (gameplay/runtime ingress) | Server-derived policy/routing/authorization/migration-fence evidence carried before handler fan-out, immutable for the namespace during one playable-state lifecycle, persisted with the ingress claim/audit, and exact-validated. It is excluded from the event-scope uniqueness key; a mismatch fails closed. Only unchanged authoritative scope permits reuse; an authority-proven transition requires a new lifecycle/namespace. | | `regionId`, `regionEpoch`, `entityId` | Yes when the incoming event is gameplay/runtime-scoped | These fields describe the source event before handler fan-out. | | `eventType` | Yes | Logical event key being admitted for handler resolution. | | `eventSchemaVersion` | Yes | Version of the event and payload contract being admitted. | @@ -118,14 +134,16 @@ Ordinary producer event-scope ingress identity before handler resolution: ### Remote Follow-Up Tuple Binding (Normative) -A remote follow-up whose source and target game instances differ carries two exact pin roles, each with its paired owner request evidence. The originating `sourceScriptPatchVersion`/`sourceScriptPinEpoch`/`sourceScriptPinControlPlaneRequestId` fields are captured when the source event/follow-up is admitted and remain immutable source provenance, owner evidence, and the source rollback fence; the source request ID is evidence/correlation, not execution identity. Before target-side Automation admission, Game Session revalidates that complete source evidence against the authoritative source instance, reads and freezes the target instance's current `targetScriptPatchVersion`/`targetScriptPinEpoch`/`targetScriptPinControlPlaneRequestId`, and durably binds both source and target records to the target delivery/claim and its immutable request/dedupe evidence. The target record, not the source record, populates the target event-scope and resolved-handler Trigger Identity and all target-side script admission and execution fences; target `scriptPinControlPlaneRequestId` remains paired owner evidence and is not substituted into execution identity. Source evidence remains separately named provenance/fence and is never substituted into that target identity. Retries reuse both frozen source/target records. Source or target displacement, a conflicting retry, or a changed owner record fails closed; unavailable authority is retryable and creates no target admission, while semantic target `UNPINNED` creates no target script work. When source and target are the same game instance, one authoritative `scriptPatchVersion`/`scriptPinEpoch` record plus its paired owner request evidence serves both roles and no distinct second record is fabricated. +For remote playable-state handoff, the source `playableStateNamespaceId` is the source durable identity dimension, while the server-derived source `playableStateScope` is separately persisted exact-validated policy/routing/authorization/migration-fence evidence. The target `targetPlayableStateNamespaceId` is the target durable identity dimension; `targetPlayableStateScope` is separately persisted exact-validated target evidence and is excluded from target uniqueness/deduplication. A missing, stale, or mismatched source or target scope fails closed and requires authoritative reconciliation; only stale or incorrect presented evidence with unchanged authoritative scope may reuse the existing handoff identity. An authority-proven scope-policy transition starts a new playable-state lifecycle and selects or allocates the corresponding target namespace before fresh handoff identity is admitted. + +A remote follow-up whose source and target game instances differ carries two exact pin roles. The originating `sourceScriptPatchVersion`/`sourceScriptPinEpoch` pair is captured when the source event/follow-up is admitted and remains immutable source provenance and the source rollback fence. Before target-side Automation admission, Game Session revalidates that source pair against the authoritative source instance, reads and freezes the target instance's current exact `scriptPatchVersion`/`scriptPinEpoch` pair, and durably binds both pairs to the target delivery/claim and its immutable request/dedupe evidence. The target pair, not the source pair, populates the target event-scope and resolved-handler Trigger Identity and all target-side script admission and execution fences; the source pair remains separately named provenance/fence and is never substituted into that target identity. Retries reuse both frozen pairs. Source or target displacement, a conflicting retry, or a changed tuple fails closed; unavailable authority is retryable and creates no target admission, while semantic target `UNPINNED` creates no target script work. When source and target are the same game instance, one authoritative exact pair serves both roles and no distinct second tuple is fabricated. For semantic target `UNPINNED`, Game Session's existing `remote_followup_result` transaction is the sole result owner: it persists exactly one terminal row under `resultId=remote-result:` with `outcome=ABANDONED`, `resultErrorCode=REMOTE_TARGET_UNPINNED`, canonical empty `resultPayloadJson={}`, and no `resultCommandId`; the same transaction updates the existing follow-up and coordinator identities and creates no Automation event, work item, or command. An exact retry returns that row without work. A retry whose existing scope, source/target tuple or identity, outcome, or normalized result-authority fingerprint differs conflicts and cannot overwrite it; this reuses the existing persisted fields and adds no digest column or outcome family. `authority_unavailable` persists no terminal result and does not terminalize delivery: it remains non-admitted/retryable under the same follow-up identity after authority recovers. This is distinct from the finalized no-script result. ### Event-Scope Claim and Retry Semantics (Normative) The ordinary producer event-scope claim/conflict key is the ordered composite of every applicable field in the event-scope ingress identity table: -``. -The paired `scriptPinControlPlaneRequestId` is retained immutably as owner evidence/correlation but is excluded from this durable storage key and the logical execution identity; the exact execution pin tuple remains `(scriptPatchVersion, scriptPinEpoch)` and the request ID must match authoritative owner evidence. +``. +The paired `scriptPinControlPlaneRequestId` is retained immutably as owner evidence/correlation but is excluded from this durable storage key and the logical execution identity; the exact execution pin tuple remains `(scriptPatchVersion, scriptPinEpoch)` and the request ID must match authoritative owner evidence. `playableStateNamespaceId` is the applicable composite identity dimension; `playableStateScope` remains separately persisted, exact-validated scope evidence and is excluded from the key. An optional field is included exactly when its ingress scope requires it; absent optional fields remain absent and must not be replaced with sentinel values. `scriptId`, `pluginId`, `pluginVersionId`, and `bindingId` are not part of this ordinary producer key because they are unavailable before handler resolution. The scheduler/timer and tenant-readiness owner-known exceptions above use their separately defined pre-resolution identities; they do not authorize a producer to supply synthetic handler fields. For custom or service-specific events, Automation derives `sourceService` from the authenticated producer/workload identity and the event-registry authorization result. The derived value, rather than a caller-supplied value, participates in the event-scope dedupe key and is persisted identically in `script_event_ingress_audit` and every resolved-handler `script_event_audit` record. A changed or unauthorized producer identity is an admission identity conflict, not a retry. @@ -136,7 +154,7 @@ The durable event-scope claim has an `IN_PROGRESS` phase, a retry-eligible trans - A retry or duplicate delivery with the same terminal finalized event-scope key returns the exact stored admission result, without re-evaluating admission or materializing duplicate handler work. Permanent denials and successful results are terminal finalized results; a retry-eligible transient denial is the explicit exception and may be reclaimed only through the bounded lifecycle above. - `resolvedHandlerCount` is the count of enabled bindings that matched and were resolved for the admitted event scope, including dry-run/test claims. It is not a count of persisted work items, emitted commands, successful handlers, or handler audit rows, and it is immutable in the finalized claim result. A resolved handler may have no work item when its handler-scoped admission decision denies it. - An admitted live claim with zero resolved handlers returns the normal admitted result with `resolvedHandlerCount=0`; `admitted_no_handlers` is emitted only as the Table 4 metric-only outcome. A dry-run/test claim with zero resolved handlers emits no live trigger metric. The finalized value is returned in the ingress response and stored on the claim and `script_event_ingress_audit`; it is not stored in handler-scoped `script_event_audit` rows. -- A request that reuses `scriptEventId` but changes any other applicable key field is an identity conflict, not a retry. Reject it deterministically, preserve the original claim and outcome, and do not materialize handlers. +- A request that reuses `scriptEventId` must perform a producer-scoped collision lookup against the complete ordered event-scope key above, including every applicable runtime, namespace, region/epoch, event, pin, dry-run, and producer field. If it changes any other applicable key field, or presents required scope evidence that does not exactly match the authoritative bound evidence, it is an identity/evidence conflict, not a retry. Reject or fence it deterministically, preserve the original claim and outcome, and do not write a competing audit or materialize handlers until authoritative reconciliation completes. - A rejected claim has no handler materialization and remains represented only by its one event-scope ingress-audit row. Event-scope ingress outcomes are recorded in the existing `script_event_ingress_audit` surface using its event-scope identity, `scriptEventId` correlation, `createdAt` retention anchor, mutable `claimStartedAt` lease, and `admissionOutcome`/`admissionReason` fields, not in handler-scoped `script_event_audit`. Stale `IN_PROGRESS` recovery compares the claim's current row-version fence and lease timestamp before advancing the fence, so an abandoned owner's finalization is rejected as a stale write and operators can identify the reclaim through its bounded durable reason. Transport authentication/authorization and request/schema validation occur before the event-scope claim and use canonical non-OK gRPC status; they do not create a claim, finalized ingress-audit result, or ingress-drop metric. After the claim exists, genuine event-scope/domain decisions such as stale pin state, reload backpressure, rollback pause, or version unavailability may use typed admission fields and the matching ingress audit/drop metric. Once the event is accepted for handler resolution, each resolved handler produces its own full applicable Trigger Identity and `script_event_audit` row. Pre-resolution event-scope decisions must not invent a synthetic `scriptId`, `bindingId`, or command identity. Scheduler due-candidate skips use the candidate-audit rule in Table 3 instead of event-scope ingress audit. @@ -159,12 +177,14 @@ Notes: - If an implementation wants to treat some gameplay lifecycle events as “not tick-aligned”, it must define that exception explicitly in this table (not only in prose docs) and document why it is safe across scoped coordination resets. The default contract is that gameplay lifecycle triggers are fenced by `regionEpoch`. - Dry-run/test ingress must use a namespace separate from live ingress (`isDryRun=true`) regardless of whether `scriptEventId` is caller-generated or server-generated. -- Downstream service calls made from scripts must propagate a per-command idempotency token derived from the full applicable Trigger Identity plus tick context when applicable (for example `tickId`), the emitted command's `automationDispatchId` (or an equivalent command-level identity), and the target aggregate type and ID, following `design/architecture/system-architecture-transactions.md`; `scriptEventId` alone is insufficient for fan-out. +- Full Trigger Identity governs resolved-handler work only; it does not govern emitted-command child admission or deduplication. The complete applicable Command-Handoff Identity governs that child admission and deduplication. After it is admitted/deduplicated and exact-maps to one durable target `commandId`, downstream authoritative service calls must use the mutation's persisted root-or-child `EffectId`, typed operation, exact target aggregate, and immutable request digest under `design/architecture/system-architecture-transactions.md`; a generated child uses its own persisted child identity while retaining the enclosing root only as lineage/reconciliation context. `scriptEventId`, `automationDispatchId`, and tick context remain correlation or admission metadata and cannot substitute for that mutation guard. ## Table 1A: Event Ingress `scriptEventId` Ownership Matrix The ingress endpoint determines who owns `scriptEventId` generation and retry behavior. Implementations must reject requests that violate these ownership rules. +In the scheduler/timer ingress row, `runtime scope` means the durable runtime identity, including `playableStateNamespaceId` where applicable; the server-derived `playableStateScope` travels as separately persisted exact-validated policy/routing/authorization/migration-fence evidence and is excluded from the event-scope due-candidate identity. Missing or mismatched scope evidence fails closed before candidate or `scriptEventId` derivation. Only stale or incorrect presented evidence with unchanged authoritative scope may reuse an existing candidate; an authority-proven scope-policy transition starts a new playable-state lifecycle and namespace before fresh candidate identity is derived. + | Ingress surface | `scriptEventId` owner | Required behavior | | --- | --- | --- | | Live external ingress (`TriggerScriptEvent`) | Caller | Caller must supply `scriptEventId` and must reuse it across retries for the same trigger identity. Missing ID is a deterministic validation error. | @@ -216,15 +236,17 @@ Additional non-committing terminal outcome rules: ### Command-Handoff Identity (Target-State) The command collection uses one complete command-handoff identity for each evaluated child dispatch: -``. -The source scope fields are required for gameplay/runtime commands; the target scope fields are included exactly when the emitted command is routed to a distinct target runtime scope, and `targetPlayableStateScope` is included whenever that distinct target scope has its own shared/isolated playable-state namespace. Absent optional fields remain absent. For command-capable gameplay/runtime evaluations, before DSL evaluation the pre-DSL/evaluation claim allocates no `automationDispatchId` or command-child identity. If evaluation emits commands, the first atomic durable evaluated-descriptor/outbox commit allocates and persists one opaque `automationDispatchId`; a valid zero-command evaluation creates no dispatch identity. Pre-commit evaluation retries preserve the original Trigger Identity, work-item identity, and frozen inputs and allocate none; retries after a winning commit reuse its dispatch ID and canonical ordinals. Tenant-readiness `onLoad` is non-emitting and does not allocate or expose a command dispatch identity. Before an evaluated descriptor exists, the pre-DSL trigger has no child identity or `commandOrdinal` and must not expose an `automationDispatchId` as a synthetic child/handoff reference. Once descriptors are emitted, `commandOrdinal` is deterministic from canonical emitted-command order: the first emitted command under a dispatch is `0`, followed by `1`, and so on. The first durable descriptor/outbox commit enforces uniqueness on the complete Command-Handoff Identity above. The complete source/target runtime scope, dispatch ID, and ordinal together prevent unrelated evaluations from converging; `automationDispatchId` is not assumed to be globally unique. `outboxWorkItemId`, the parent Trigger Identity, and `scriptEventId` are correlation-only and excluded from command-child uniqueness. The complete identity above is the canonical identity for evaluated command-child handoff deduplication, execution-fence reporting, replay selection, and child correlation; it is not the downstream authoritative effect identity. Downstream effect idempotency instead uses the stable root `EffectId`, typed operation, and exact target aggregate, with the immutable request digest stored and compared; a conflicting operation, target, or digest fails closed. The `(automationDispatchId, commandOrdinal)` pair is only a suffix and is insufficient without the complete source/target scope; `script_event_audit` remains a separate one-row-per-handler surface. +``. +The source runtime identity fields are required for gameplay/runtime commands; the server-derived source `playableStateScope` is separately persisted exact-validated policy/routing/authorization/migration-fence evidence and is excluded from Command-Handoff Identity uniqueness/deduplication. The target runtime identity fields are included exactly when the emitted command is routed to a distinct target runtime scope, and `targetPlayableStateNamespaceId` is included whenever that distinct target has its own playable-state namespace. `targetPlayableStateScope` is separately persisted exact-validated target policy/routing/authorization/migration-fence evidence and is excluded from target uniqueness/deduplication. Missing, stale, or mismatched source or target scope evidence fails closed and requires authoritative reconciliation; only stale or incorrect presented scope evidence with unchanged authoritative scope may reuse the existing child identity. An authority-proven scope-policy transition starts a new playable-state lifecycle and selects or allocates the corresponding target namespace before fresh child identity is admitted. Absent optional identity fields remain absent. For command-capable gameplay/runtime evaluations, before DSL evaluation the pre-DSL/evaluation claim allocates no `automationDispatchId` or command-child identity. If evaluation emits commands, the first atomic durable evaluated-descriptor/outbox commit allocates and persists one opaque `automationDispatchId`; a valid zero-command evaluation creates no dispatch identity. Pre-commit evaluation retries preserve the original Trigger Identity, work-item identity, and frozen inputs and allocate none; retries after a winning commit reuse its dispatch ID and canonical ordinals. Tenant-readiness `onLoad` is non-emitting and does not allocate or expose a command dispatch identity. Before an evaluated descriptor exists, the pre-DSL trigger has no child identity or `commandOrdinal` and must not expose an `automationDispatchId` as a synthetic child/handoff reference. Once descriptors are emitted, `commandOrdinal` is deterministic from canonical emitted-command order: the first emitted command under a dispatch is `0`, followed by `1`, and so on. The first durable descriptor/outbox commit enforces uniqueness on the complete Command-Handoff Identity above. The complete source/target runtime identity, separately validated scope evidence, dispatch ID, and ordinal together prevent unrelated evaluations from converging; `automationDispatchId` is not assumed to be globally unique. `outboxWorkItemId`, the parent Trigger Identity, and `scriptEventId` are correlation-only and excluded from command-child uniqueness. The complete identity above is the canonical identity for evaluated command-child handoff deduplication, execution-fence reporting, replay selection, and child correlation; it is not the downstream authoritative effect identity. Downstream effect idempotency instead uses the persisted mutation `EffectId` (the root `EffectId` for a root mutation or the generated child's persisted `EffectId` for a child mutation), typed operation, and exact target aggregate, with the immutable request digest stored and compared; any enclosing `rootEffectId` is lineage and reconciliation context only, and a conflicting operation, target, or digest fails closed. The `(automationDispatchId, commandOrdinal)` pair is only a suffix and is insufficient without the complete source/target runtime identity; `script_event_audit` remains a separate one-row-per-handler surface. A command-handoff reference exists only for an emitted evaluated descriptor. Pre-DSL trigger records have no child Command-Handoff Identity or `commandOrdinal` and must not be represented by an `automationDispatchId`, parent `outboxWorkItemId`, parent Trigger Identity, or `scriptEventId` as a synthetic child/handoff reference. Read-only inspection may expose an emitted descriptor reference with the complete identity above, including `commandOrdinal`; mutation APIs currently accept bounded explicit `workItemIds[]` only. Descriptor references and filter selectors are listing/preview inputs, and descriptor-level replay or purge remains deferred until preview plus stable per-row proof. +The downstream command-plan root design, including semantic order, `planOrdinal`, and allocation binding, remains pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). Automation handoff identity and Trigger Identity retain their separate admission and handler/correlation roles under this document's existing contracts; those roles do not establish the pending root-allocation design. + Supplementary post-handoff correlation rule: -- **Target-state command-ordinal contract:** execution-time version/plugin fence drops that happen after tick handoff must not be left as metrics-only signals. They must be exposed on the affected per-command handoff disposition keyed by the complete Command-Handoff Identity, including `targetPlayableStateScope` when a distinct target runtime scope applies, with the parent Trigger Identity and its exact `scriptPatchVersion`/`scriptPinEpoch` pair retained for correlation, using bounded reasons such as `script_patch_mismatch` or `plugin_binding_mismatch`; use `plugin_activation_epoch_mismatch` specifically when the captured plugin activation epoch mismatches current authoritative epoch evidence. -- **Current live fallback:** the Game Session handoff currently carries `automationDispatchId`, command id/text, selected provenance fields, and parent work-item correlation, but not `commandOrdinal` or the complete Trigger Identity. Current diagnostics use those fields and must be labeled as the narrower fallback rather than as proof of the target-state contract. +- **Target-state command-ordinal contract:** execution-time version/plugin fence drops that happen after tick handoff must not be left as metrics-only signals. They must be exposed on the affected per-command handoff disposition keyed by the complete Command-Handoff Identity, including `targetPlayableStateNamespaceId` when a distinct target playable-state namespace applies; retain source and target `playableStateScope`/`targetPlayableStateScope` as separately persisted exact-validated policy/routing/authorization/fence evidence, excluded from uniqueness, with the parent Trigger Identity and its exact `scriptPatchVersion`/`scriptPinEpoch` pair retained for correlation. Missing or mismatched scope evidence fails closed. Use `plugin_binding_mismatch` only for a proven plugin/lifecycle binding mismatch; use `plugin_activation_epoch_mismatch` for a captured activation-epoch mismatch, `plugin_disabled` for a lifecycle disablement or revocation that invalidates admitted work, `plugin_version_not_published` for publication failure, `plugin_component_policy_blocked` for a proven component-policy block, `signer_revoked` for signer revocation, and `authority_unavailable`, `component_policy_unavailable`, or `signer_policy_unavailable` when the applicable evidence is unavailable or unverifiable. `script_patch_mismatch` remains the script-version reason. +- **Current live fallback:** the Game Session handoff currently carries `automationDispatchId`, command id/text, selected provenance fields, and parent work-item correlation, but not `commandOrdinal` or the complete Trigger Identity. Current diagnostics use those fields and must be labeled as the narrower fallback rather than as proof of the handoff target-state contract. The proposed plan-root allocation is not a live or accepted requirement. Per-command handoff correlation rule: @@ -270,7 +292,7 @@ Deprecated aliases: If Game Session rejects a queued command because its embedded `(scriptPatchVersion, scriptPinEpoch)` does not match the currently pinned exact tuple, because work referencing a revocable component lacks matching fresh component-revocation security-policy evidence, or because a plugin-produced command's execution evidence `(pluginId, pluginVersionId, bindingId)` plus captured `(pluginActivationEpoch, lifecycleRevision)` does not match fresh current activation-epoch, binding, and lifecycle evidence together with authoritative publication, signer-policy, component-policy, and capability-grant evidence for its scoped instance, or because any required component-revocation, activation-epoch, binding, lifecycle, publication, signer-policy, component-policy, or capability-grant evidence is unavailable, stale, contradictory, or unverifiable, it must fail closed and: -- Record the drop on the affected command-handoff record keyed by the complete Command-Handoff Identity: required source scope (`tenantId`, `gameInstanceId`, `playableStateScope`, `regionId`, `regionEpoch`), the dispatch-group suffix (`automationDispatchId`, `commandOrdinal`), and the optional distinct target scope (`targetGameInstanceId`, `targetPlayableStateScope`, `targetRegionId`, `targetRegionEpoch`) when applicable. `automationDispatchId` is retained as dispatch-group correlation and is not a standalone child key; parent `outboxWorkItemId`, the parent Trigger Identity, and `scriptEventId` remain correlation-only. Retain `scriptId` and the exact `(scriptPatchVersion, scriptPinEpoch)` tuple for diagnosis; retain `entityId` only for entity-scoped commands and keep it absent otherwise, plus the applicable component-revocation fence evidence and, for a plugin handler, `pluginId`, `pluginVersionId`, `bindingId`, and captured `(pluginActivationEpoch, lifecycleRevision)` as execution evidence, not Command-Handoff Identity. For a plugin tuple, binding, lifecycle, publication, or policy identity/evidence mismatch, this disposition uses bounded `reason=plugin_binding_mismatch`; when the captured `pluginActivationEpoch` itself mismatches current authoritative epoch evidence, it uses bounded `reason=plugin_activation_epoch_mismatch`. +- Record the drop on the affected command-handoff record keyed by the complete Command-Handoff Identity: required source runtime identity (`tenantId`, `gameInstanceId`, `playableStateNamespaceId`, `regionId`, `regionEpoch`), the dispatch-group suffix (`automationDispatchId`, `commandOrdinal`), and the optional distinct target runtime identity (`targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetRegionId`, `targetRegionEpoch`) when applicable. Retain the server-derived source `playableStateScope` and, when applicable, `targetPlayableStateScope` as separately persisted exact-validated policy/routing/authorization/fence evidence, excluded from uniqueness; missing or mismatched scope evidence fails closed and requires authoritative reconciliation. `automationDispatchId` is retained as dispatch-group correlation and is not a standalone child key; parent `outboxWorkItemId`, the parent Trigger Identity, and `scriptEventId` remain correlation-only. Retain `scriptId` and the exact `(scriptPatchVersion, scriptPinEpoch)` tuple for diagnosis; retain `entityId` only for entity-scoped commands and keep it absent otherwise, plus the applicable component-revocation fence evidence and, for a plugin handler, `pluginId`, `pluginVersionId`, `bindingId`, and captured `(pluginActivationEpoch, lifecycleRevision)` as execution evidence, not Command-Handoff Identity. Use bounded `reason=plugin_binding_mismatch` only for a proven plugin/lifecycle binding mismatch; use `plugin_activation_epoch_mismatch`, `plugin_disabled`, `plugin_version_not_published`, `plugin_component_policy_blocked`, or `signer_revoked` for the applicable proven epoch, disabled/revoked, publication, component-policy, or signer failure, and `authority_unavailable`, `component_policy_unavailable`, or `signer_policy_unavailable` when the applicable evidence is unavailable or unverifiable. - For a proven tuple, binding, lifecycle, publication, policy, or component-revocation mismatch, remove the rejected queue entry or move it to a bounded dead-letter store so terminal failures cannot accumulate unboundedly after a rollback. When required component-revocation or other authority evidence is temporarily unavailable or unverifiable without proving a permanent mismatch, retain the entry retryable under its original complete Command-Handoff Identity, record the applicable established bounded disposition such as `component_policy_unavailable`, `authority_unavailable`, or `signer_policy_unavailable`, and create no recovery claim/attempt or replacement identity. Retry timing and reconciliation use the owning queue/handoff policy and its existing lease/fence checks; the bounded dead-letter `maxAge`/`maxRows`, cleanup cadence, and alert thresholds are defined in [Scripting Quotas & Operations](./system-architecture-scripting-quotas-and-operations.md#auditability--metrics). Once evidence proves a component is blocked/revoked or another permanent mismatch, terminalize it under the applicable bounded disposition. These dispositions are distinct and do not create a new outcome or validator family. - Apply the corresponding Table 4 version-fence metric consequence for script-patch, plugin-version/binding, or plugin-activation-epoch mismatches; Table 4 owns the exact family, labels, and increment unit. - Dead-letter retention for rejected queue entries must be bounded and explicit: @@ -304,22 +326,23 @@ The matrix below defines what the scheduler does when a firing becomes due under | Recurring/advisory `reloadState=RELOADING` | Do not admit new timer firings or backfill while `RELOADING`; use the transient due-candidate lifecycle above and retry only after the exact pin tuple, runtime scope, and owner evidence reconcile. | Keep the due-candidate state/claim fenced and nonterminal: no `finalStage`, `finalOutcome`, terminal candidate audit, firing claim, handler Trigger Identity, or `scriptEventId` while fenced; settle once under the original exact tuple as above. | | Recurring/advisory `reloadState=FAILED` | Fail closed until durable recovery reconciles the current pin, schedule, scope/epoch, and due evidence and returns the scope to `IDLE`; do not backfill from the prior patch. | Record the non-admitted due candidate under deterministic `scheduleCandidateId` with `finalStage=ADMISSION`, `finalOutcome=version_unavailable`, and `finalReason=reload_failed`; do not create a firing claim, handler Trigger Identity, or `scriptEventId`. | | Recurring/advisory `PAUSED_FOR_ROLLBACK` | Do not admit new timer firings until the exact pin/artifact, schedule rows, due candidates, displaced/firing projections, and current list/read projections reconcile; only terminal old-execution evidence cleanup remains asynchronous/diagnostic and does not gate resumption. This Automation admission barrier does not pause ordinary gameplay ticks. While the original exact tuple remains current, retain the due candidate and its canonical due point as nonterminal state; if rollback displaces that tuple, keep the old candidate fenced under its original identity and derive any fresh candidate only from reconciled target schedule/due state. Follow the owner-defined [scheduler and timers transition rules](./system-architecture-scripting-scheduler-and-timers.md#explicit-continuity-across-script-transitions) for due-point advancement and replacement. | While the original tuple remains current, retain the deterministic `scheduleCandidateId` with no `finalStage`, `finalOutcome`, terminal candidate audit, firing claim, handler Trigger Identity, or `scriptEventId`; retry the same candidate only after exact evidence reconciles. When rollback displaces it, terminalize the old candidate under its original identity as `finalStage=ADMISSION`, `finalOutcome=canceled`, `finalReason=rollback_epoch_advanced` when required, and create any target candidate with a fresh deterministic identity only after reconciliation. | -| Recurring/durable-recurring leader failover or short downtime | Apply each complete stable schedule-instance identity's declared `SKIP_MISSED` or `COALESCE_ONE` policy. A coalescing schedule instance may admit at most one synthetic firing in the one Automation-owned durable timer-recovery resume window identified by ``; at creation, that durable window freezes the effective numeric `SCRIPT_TIMER_CATCH_UP_MAX_FIRINGS_PER_RESUME` cap and the selection-policy revision defining grouping, ordering, round-robin passes, and tie breaks. Those frozen values govern every scan, retry, takeover, selection, and cap-excluded outcome until the window reaches `COMPLETE`; a later configuration or policy change applies only to a later window. The deterministic fair tenant-local cap applies across independent schedule instances within that one-tenant, one-mode `resumeWindowId`, grouped by the stable schedule-instance identity defined in the scheduler lifecycle (including target scope and dry-run mode), not by `scheduleDefinitionId` alone. `pluginVersionId` and `bindingId` remain due-candidate provenance, fencing, and deduplication dimensions and do not split stable fairness groups. Durable compare-and-set creates or reuses one `OPEN` window per runtime scope, epoch, and `isDryRun` mode; same-window retries and takeovers revalidate and reuse that mode-specific identity and its frozen policy inputs. Excluded candidates are dropped and never deferred as backlog. A candidate selected within that cap still enters ADR 0166 tenant-first shared scheduler/cluster admission. Tenant or cluster capacity denial terminally skips that candidate under the same due-candidate and mode-specific `resumeWindowId` identity, consumes its deterministic selection slot, creates no firing claim, handler Trigger Identity, or `scriptEventId`, and is not retried, deferred, backfilled, or reminted as catch-up. Atomically persist that terminal candidate audit, advance the recurring schedule's canonical due state to its next ordinary future occurrence, and record the resume-window denial outcome; a resumable idempotent reconciliation keyed by `(scheduleCandidateId, resumeWindowId)` is required when one transaction is unavailable, and an incomplete settlement remains fenced. | Catch-up firings use `triggerMode=CATCH_UP` and deterministic identity from the coalesced due point and mode-specific `resumeWindowId`. The firing-claim uniqueness/comparison, candidate audit, and tenant-local-cap accounting all include `isDryRun` and `resumeWindowId`; same-window retries and takeovers reuse them. An epoch transition moves each prior epoch's `OPEN` window out of `OPEN` independently for each mode before creating the corresponding new-epoch window. The window completes only after selected candidates' firing or shared-admission-denial outcomes and all cap-excluded outcomes are durable, and only a later recovery episode allocates the next `resumeGeneration`. For `isDryRun=false`, a tenant-ceiling denial records candidate-audit `finalStage=ADMISSION`, `finalOutcome=tenant_budget_exceeded`, and `finalReason=tenant_budget_exceeded`, then increments `automation_script_skips_total` once with `scope="tenant"` and `reason="tenant_budget_exceeded"`; this candidate-level route does not invoke `ScriptTenantBudgetService` or increment `automation_script_tenant_budget_denied_total`. A cluster-ceiling denial records candidate-audit `finalStage=ADMISSION`, `finalOutcome=quota_denied`, and `finalReason=cluster_limit_reached`, then increments `automation_script_skips_total` once with `scope="cluster"` and `reason="cluster_limit_reached"`. Both live metrics use the remaining bounded Table 4 labels. For `isDryRun=true`, neither live-only family is emitted: no dedicated test-only candidate-ceiling metric is currently defined, so the settled candidate audit and mode-specific resume-window outcome are the complete observability surface; the handler-scoped test families are not used because the denial occurs before handler materialization. Neither denial increments `automation_script_timer_catchup_truncated_total`; cap-excluded candidates use that truncation family instead. | -| Recurring/advisory runtime scope / epoch change before due-point admission | Do not remint stale due points under the newer `(tenantId, gameInstanceId, playableStateScope, regionId, regionEpoch)` timeline. A `playableStateScope` change is a schedule/runtime migration fence even when the other runtime fields are unchanged: create or confirm the new scope-owned schedule entry before retiring the old entry, as one atomic durable result or a resumable idempotent operation, then advance to the new scope's next valid due point without reusing the stale one. | Record the dropped candidate at event scope under deterministic `scheduleCandidateId` with `finalStage=ADMISSION`, `finalOutcome=canceled`, and `finalReason=runtime_scope_changed` (or `playable_state_scope_changed` for that specific fence), and emit the runtime-fence metric. Because admission did not occur, do not create a firing claim, handler Trigger Identity, or `scriptEventId`. | -| Correctness-bearing one-shot runtime scope / epoch change | Keep the durable intent and any effect under the original identity and fence it from ordinary execution on the new timeline. Reconcile it under authority-fenced owner evidence; never rebind or remint it into the new scope/epoch. Only after the original intent/effect and source claim conclusively permit `ABANDONED` may an authorized recovery create a fresh current-scope identity with revalidation and durable lineage under [ADR 0067](./decisions/adr-0067-abandon-old-epoch-work-and-reschedule-with-new-lineage.md). | Retain the original identity, old scope/epoch, reconciliation evidence, terminal outcome when proven, and any fresh lineage link. Inconclusive old work remains nonterminal and blocks affected-scope reopen rather than being reported as skipped or silently replaced. | -| Recurring/advisory timer preserved across reload/rollback | Apply the owner-defined resume rule only when its runtime-region, scope, and epoch preconditions match; otherwise fence the old due point and derive a new due point after the replacement schedule entry is durable. Do not reuse a stale due point or Trigger Identity. | Preserve the dropped old due-point evidence and the exact identity; see [Timer Resume Rule](./system-architecture-scripting-scheduler-and-timers.md#timer-resume-rule-normative). | +| Recurring/durable-recurring leader failover or short downtime | Apply each complete stable schedule-instance identity's declared `SKIP_MISSED` or `COALESCE_ONE` policy. A coalescing schedule instance may admit at most one synthetic firing in the one Automation-owned durable timer-recovery resume window identified by ``; the server-derived `playableStateScope` is retained as immutable exact-validated policy/routing/authorization/migration-fence evidence for that window and is excluded from its identity, with missing or mismatched evidence fencing admission. At creation, that durable window freezes the effective numeric `SCRIPT_TIMER_CATCH_UP_MAX_FIRINGS_PER_RESUME` cap and the selection-policy revision defining grouping, ordering, round-robin passes, and tie breaks. Those frozen values govern every scan, retry, takeover, selection, and cap-excluded outcome until the window reaches `COMPLETE`; a later configuration or policy change applies only to a later window. The deterministic fair tenant-local cap applies across independent schedule instances within that one-tenant, one-mode `resumeWindowId`, grouped by the stable schedule-instance identity defined in the scheduler lifecycle (including target `playableStateNamespaceId` identity and dry-run mode; target scope remains evidence), not by `scheduleDefinitionId` alone. `pluginVersionId` and `bindingId` remain due-candidate provenance, fencing, and deduplication dimensions and do not split stable fairness groups. Durable compare-and-set creates or reuses one `OPEN` window per namespace/runtime identity, epoch, and `isDryRun` mode; same-window retries and takeovers revalidate and reuse that namespace identity, exact scope evidence, and frozen policy inputs. Excluded candidates are dropped and never deferred as backlog. A candidate selected within that cap still enters ADR 0166 tenant-first shared scheduler/cluster admission. Tenant or cluster capacity denial terminally skips that candidate under the same due-candidate and mode-specific `resumeWindowId` identity, consumes its deterministic selection slot, creates no firing claim, handler Trigger Identity, or `scriptEventId`, and is not retried, deferred, backfilled, or reminted as catch-up. Atomically persist that terminal candidate audit, advance the recurring schedule's canonical due state to its next ordinary future occurrence, and record the resume-window denial outcome; a resumable idempotent reconciliation keyed by `(scheduleCandidateId, resumeWindowId)` is required when one transaction is unavailable, and an incomplete settlement remains fenced. | Catch-up firings use `triggerMode=CATCH_UP` and deterministic identity from the coalesced due point and mode-specific `resumeWindowId`. The firing-claim uniqueness/comparison, candidate audit, and tenant-local-cap accounting all include `playableStateNamespaceId`, `isDryRun`, and `resumeWindowId`; same-window retries and takeovers reuse them while revalidating the separately persisted exact scope evidence. An epoch transition moves each prior epoch's `OPEN` window out of `OPEN` independently for each mode before creating the corresponding new-epoch window. The window completes only after selected candidates' firing or shared-admission-denial outcomes and all cap-excluded outcomes are durable, and only a later recovery episode allocates the next `resumeGeneration`. For `isDryRun=false`, a tenant-ceiling denial records candidate-audit `finalStage=ADMISSION`, `finalOutcome=tenant_budget_exceeded`, and `finalReason=tenant_budget_exceeded`, then increments `automation_script_skips_total` once with `scope="tenant"` and `reason="tenant_budget_exceeded"`; this candidate-level route does not invoke `ScriptTenantBudgetService` or increment `automation_script_tenant_budget_denied_total`. A cluster-ceiling denial records candidate-audit `finalStage=ADMISSION`, `finalOutcome=quota_denied`, and `finalReason=cluster_limit_reached`, then increments `automation_script_skips_total` once with `scope="cluster"` and `reason="cluster_limit_reached"`. Both live metrics use the remaining bounded Table 4 labels. For `isDryRun=true`, neither live-only family is emitted: no dedicated test-only candidate-ceiling metric is currently defined, so the settled candidate audit and mode-specific resume-window outcome are the complete observability surface; the handler-scoped test families are not used because the denial occurs before handler materialization. Neither denial increments `automation_script_timer_catchup_truncated_total`; cap-excluded candidates use that truncation family instead. | +| Recurring/advisory runtime scope / epoch change before due-point admission | Do not remint stale due points under the newer `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch)` identity timeline. The server-derived `playableStateScope` is separately persisted exact-validated policy/routing/authorization/migration-fence evidence and is immutable for a namespace during one playable-state lifecycle. A presented `playableStateScope` mismatch remains a schedule/runtime migration fence even when the identity fields are unchanged: fence admission and require authoritative reconciliation of the scope evidence. Only when authority proves the scope itself is unchanged and the presented evidence was stale or incorrect may the existing namespace-keyed schedule advance to its next valid due point; if authority proves a scope-policy transition, it must start a new playable-state lifecycle and select or allocate a new namespace under the existing retire/create ordering, never reuse the old identity. | For stale or incorrect presented scope evidence, or unavailable or ambiguous authority, keep the candidate fenced and nonterminal with no final audit (`finalStage`, `finalOutcome`, or `finalReason`) and no runtime-fence metric; retry only after authoritative reconciliation. When authority confirms the scope is unchanged, reuse the namespace-keyed identity and advance the due point without recording a scope-change cancellation or metric. Only an authority-proven runtime epoch change, scope-policy transition, or other displacement records the dropped candidate at event scope under deterministic `scheduleCandidateId` with `finalStage=ADMISSION`, `finalOutcome=canceled`, and `finalReason=runtime_scope_changed` (or `playable_state_scope_changed` for that specific fence), and emits the runtime-fence metric. Because actual displacement did not admit the candidate, do not create a firing claim, handler Trigger Identity, or `scriptEventId`. | +| Correctness-bearing one-shot runtime scope / epoch change | Keep the durable intent and any effect under the original identity and fence it from ordinary execution on the new timeline. Reconcile it under authority-fenced owner evidence; a presented `playableStateScope` mismatch remains separately validated fence evidence and does not by itself mint a new identity, while an authority-proven scope-policy transition starts a new playable-state lifecycle/namespace and is never silently rebound into the old intent. Only after the original intent/effect and source claim conclusively permit `ABANDONED` may an authorized recovery create a fresh current-namespace identity with revalidation and durable lineage under [ADR 0067](./decisions/adr-0067-abandon-old-epoch-work-and-reschedule-with-new-lineage.md). | Retain the original identity, old namespace/scope/epoch, reconciliation evidence, terminal outcome when proven, and any fresh lineage link. Inconclusive old work remains nonterminal and blocks affected-scope reopen rather than being reported as skipped or silently replaced. | +| Recurring/advisory timer preserved across reload/rollback | Apply the owner-defined resume rule only when its runtime-region, playable-state namespace, exact scope evidence, and epoch preconditions match; otherwise fence the old due point and derive a new due point after the replacement schedule entry is durable. A presented scope mismatch requires reconciliation and fences stale work; only unchanged authoritative scope permits reuse of the namespace-keyed Trigger Identity. An authority-proven scope-policy transition starts a new playable-state lifecycle/namespace and follows the existing replacement ordering. Do not reuse a stale due point or Trigger Identity. | Preserve the dropped old due-point evidence and the exact identity; see [Timer Resume Rule](./system-architecture-scripting-scheduler-and-timers.md#timer-resume-rule-normative). | | Recurring/advisory long downtime or sustained overload | No guarantee of eventual execution for every firing; the system converges by running future firings once capacity returns. | Missed firings must be visible as skips/drops in metrics and audit. | -| Infrastructure error after admission | Before `EVALUATED_COMMITTED`, an admitted evaluation may retry only under the same full Trigger Identity and must converge on the same parent work-item and child identities. After `EVALUATED_COMMITTED`, recovery replays the durable descriptors and never re-enters the DSL. Correctness-bearing one-shot recovery must converge under its durable intent identity to one execution or an explicit terminal outcome. Downstream retries remain idempotent. | Preserve the `finalStage` reached by the failed or committed operation; do not record `handoff_accepted` without full durable acceptance of every required child. | +| Infrastructure error after admission | Before `EVALUATED_COMMITTED`, an admitted evaluation may retry only under the same full Trigger Identity and must converge on the same parent work item, full Trigger Identity, and frozen inputs; no dispatch or child identity exists before the winning evaluated-descriptor/outbox commit. After `EVALUATED_COMMITTED`, recovery replays the durable descriptors and never re-enters the DSL. Correctness-bearing one-shot recovery must converge under its durable intent identity to one execution or an explicit terminal outcome. Downstream retries remain idempotent. | Preserve the `finalStage` reached by the failed or committed operation; do not record `handoff_accepted` without full durable acceptance of every required child. | ### Preserved-Timer Resume Rule -The exact resume formula, modulo-zero boundary behavior, and runtime scope/epoch preconditions are owned by [Scripting Scheduler and Timer Lifecycle](./system-architecture-scripting-scheduler-and-timers.md#timer-resume-rule-normative). This table records the resulting candidate-audit and identity requirements only: a preserved timer uses the original scope/epoch identity when those preconditions hold; a changed scope or epoch fences the old due point and does not reuse its Trigger Identity. +The exact resume formula, modulo-zero boundary behavior, and runtime scope/epoch preconditions are owned by [Scripting Scheduler and Timer Lifecycle](./system-architecture-scripting-scheduler-and-timers.md#timer-resume-rule-normative). This table records the resulting candidate-audit and identity requirements only: a preserved timer uses the original `playableStateNamespaceId`/runtime identity when those preconditions and unchanged authoritative scope evidence hold; a presented stale or incorrect scope fences admission until reconciliation, while an authority-proven scope-policy transition starts a new playable-state lifecycle/namespace, fences the old due point, and never reuses its Trigger Identity. ### Version-Owned Durable Schedule Migration (Normative) -- `scheduleDefinitionId` participates in the stable logical continuity key but is not the durable row or trigger-claim identity. The continuity key is `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, targetScopeType, targetScopeId}`; `pluginId` is the stable plugin owner while `pluginVersionId`, `scriptPatchVersion`, and `scriptPinEpoch` remain provenance and exact execution-fence metadata. -- By default, a version transition tombstones the displaced interval and creates a target interval with fresh due state when a validated target definition exists. When authoritative reconciliation proves the target definition is absent, reconciliation follows the [scheduler owner rule](./system-architecture-scripting-scheduler-and-timers.md#explicit-continuity-across-script-transitions): it fences admission and atomically tombstones the displaced interval, terminalizes any proven-displaced candidates under their original identities as applicable, creates no replacement row, due state, firing claim, or `scriptEventId`, and never rebinds existing candidates or claims. If target-definition or other required authority is unavailable, contradictory, or ambiguous, reconciliation must not tombstone or create replacement state; it retains the displaced row, candidates, and claims fenced and nonterminal until authority reconciles. Only a later validated target reconciliation may create fresh state and identities. Carrying due state requires explicit compatible continuity declarations on both sides, `source.isDryRun == target.isDryRun`, typed interval/cadence/target/playable-scope checks, and the exact pin/epoch transition identity. A same-version repin is still a new epoch transition: the transition must atomically or resumably reconcile the stable row and retire or rewrite all displaced mutable schedule state, due candidates, and current list/read projections before admission resumes. Old-epoch firing claims retain their original exact `(scriptPatchVersion, scriptPinEpoch)` and `resumeWindowId`, and only pending claims may be fenced or terminal-marked; claims already in handoff reconcile the downstream outcome under their original exact fence. Neither pending-claim fencing/terminalization nor in-handoff reconciliation creates a new firing claim, handler identity, or `scriptEventId`. Immutable candidate-audit identity, outcome, exact tuple, and `resumeWindowId` are never rewritten. A transient due-candidate state/claim keyed by `scheduleCandidateId` may remain fenced while reconciliation is pending. It may settle into the one firing path only while its original exact `(scriptPatchVersion, scriptPinEpoch)` tuple and every applicable authoritative binding, runtime-scope, owner, and plugin lifecycle fence (including the captured `(pluginActivationEpoch, lifecycleRevision)` pair when applicable) remain current, or into one immutable terminal candidate audit. If authoritative evidence proves any applicable fence displaced, terminalize the candidate under its original identity with the applicable bounded terminal outcome/reason and create no firing claim or `scriptEventId`; if authority is unavailable, contradictory, or ambiguous, retain the fenced candidate as nonterminal until reconciled. It is never rebound to a new scope or epoch. `scheduleSemanticsHash` is diagnostic evidence only; equality cannot grant continuity. Replacement creation and retirement are one atomic durable result or a resumable, idempotent operation keyed by `controlPlaneRequestId`. -- The new version/scope-owned entry must derive a new scheduler trigger claim and `scriptEventId`; a matching `scheduleDefinitionId`, due point, handler, or old `playableStateScope` must never be used to reuse a Trigger Identity across the migration. +- `scheduleDefinitionId` participates in the stable logical continuity key and the complete durable row/trigger-claim identity, but is never sufficient as a standalone row or claim identity. For a playable-state-scoped schedule, the continuity key is `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, playableStateNamespaceId, targetScopeType, targetScopeId}`; `playableStateScope` is separately persisted exact-validated policy/routing/authorization/migration-fence evidence and is not a continuity-key component. `pluginId` is the stable plugin owner while `pluginVersionId`, `scriptPatchVersion`, and `scriptPinEpoch` remain provenance and exact execution-fence metadata. +- By default, a version transition tombstones the displaced interval and creates a target interval with fresh due state when a validated target definition exists. When authoritative reconciliation proves the target definition is absent, reconciliation follows the [scheduler owner rule](./system-architecture-scripting-scheduler-and-timers.md#explicit-continuity-across-script-transitions): it fences admission and atomically tombstones the displaced interval, terminalizes any proven-displaced candidates under their original identities as applicable, creates no replacement row, due state, firing claim, or `scriptEventId`, and never rebinds existing candidates or claims. If target-definition or other required authority is unavailable, contradictory, or ambiguous, reconciliation must not tombstone or create replacement state; it retains the displaced row, candidates, and claims fenced and nonterminal until authority reconciles. Only a later validated target reconciliation may create fresh state and identities. Carrying due state requires explicit compatible continuity declarations on both sides, `source.isDryRun == target.isDryRun`, typed interval/cadence/target/playable-scope checks, and an exact pin/epoch transition: validate the prior/source `(scriptPatchVersion, scriptPinEpoch)` tuple and target tuple independently; they may differ across the transition, and both remain provenance and execution-fence metadata rather than members of the stable continuity key. A same-version repin is still a new epoch transition: the transition must atomically or resumably reconcile the stable row and retire or rewrite all displaced mutable schedule state, due candidates, and current list/read projections before admission resumes. Old-epoch firing claims retain their original exact `(scriptPatchVersion, scriptPinEpoch)` and `resumeWindowId`, and only pending claims may be fenced or terminal-marked; claims already in handoff reconcile the downstream outcome under their original exact fence. Neither pending-claim fencing/terminalization nor in-handoff reconciliation creates a new firing claim, handler identity, or `scriptEventId`. Immutable candidate-audit identity, outcome, exact tuple, and `resumeWindowId` are never rewritten. A transient due-candidate state/claim keyed by `scheduleCandidateId` may remain fenced while reconciliation is pending. It may settle into the one firing path only while its original exact `(scriptPatchVersion, scriptPinEpoch)` tuple and every applicable authoritative binding, runtime-scope, owner, and plugin lifecycle fence (including the captured `(pluginActivationEpoch, lifecycleRevision)` pair when applicable) remain current, or into one immutable terminal candidate audit. If authoritative evidence proves any applicable fence displaced, terminalize the candidate under its original identity with the applicable bounded terminal outcome/reason and create no firing claim or `scriptEventId`; if authority is unavailable, contradictory, or ambiguous, retain the fenced candidate as nonterminal until reconciled. It is never rebound to a new scope or epoch. `scheduleSemanticsHash` is diagnostic evidence only; equality cannot grant continuity. Replacement creation and retirement are one atomic durable result or a resumable, idempotent operation keyed by `controlPlaneRequestId`. +- The preceding playable-scope checks validate separately persisted server-derived policy/routing/authorization/fence evidence; they do not add `playableStateScope` to continuity, candidate, or Trigger Identity. A presented scope mismatch remains fenced until authoritative reconciliation; only unchanged authoritative scope permits the existing namespace-keyed identity, while an authority-proven scope-policy transition starts a new playable-state lifecycle and namespace. +- A new version/namespace-owned entry, or a target entry created after a namespace transition, must derive a new scheduler trigger claim and `scriptEventId`; a matching `scheduleDefinitionId`, due point, handler, or old `playableStateNamespaceId` must never be used to reuse a Trigger Identity across the migration. A presented `playableStateScope` mismatch remains an admission/migration fence requiring authoritative reconciliation and exact evidence validation; an authority-proven transition must allocate the new namespace before fresh identity, and no path may silently reuse the old identity while fenced. For plugin-owned migration evidence, displaced rows, due candidates, firing claims, and candidate audits retain and revalidate the captured `(pluginActivationEpoch, lifecycleRevision)` pair alongside the exact script pin. `pluginActivationEpoch` participates in due-candidate, firing-claim, and derived `scriptEventId` identity as specified above; `lifecycleRevision` is execution-fence evidence only and is not added to the stable schedule, continuity, Trigger, or Command-Handoff identity. diff --git a/design/architecture/system-architecture-scripting-observability-contract.md b/design/architecture/system-architecture-scripting-observability-contract.md index 76e9355b5c..8de4d55624 100644 --- a/design/architecture/system-architecture-scripting-observability-contract.md +++ b/design/architecture/system-architecture-scripting-observability-contract.md @@ -62,23 +62,29 @@ Write behavior requirements: - Conflicting concurrent writes for the same Trigger Identity must converge on a single row with deterministic precedence (higher stage wins). - Handler-scoped admission rejections and backpressure outcomes (for example `quota_denied`, `script_disabled`, timer-scope `skipped_reloading`, post-resolution `rollback_paused`, or plugin `disabled_due_to_errors`) must still produce the row for that Trigger Identity with `finalStage=ADMISSION`; plugin breaker denials use canonical bounded `finalReason=failure_rate_breaker` and retain `breakerState=DISABLED_DUE_TO_ERRORS` with the exact plugin version/runtime scope. When present on that row or a runtime read, `breakerReason` carries the same bounded `failure_rate_breaker` value as runtime-state evidence; it is not a competing audit reason. Handler retries reuse that full identity and propagated `scriptEventId`. Pre-resolution event-scope denials belong in the ingress audit/logging surface described above and follow the [event-scope claim retry lifecycle](./system-architecture-scripting-normative-contract-tables.md#event-scope-claim-and-retry-semantics-normative). Timer/cadence candidate skips remain on the `scheduleCandidateId` candidate-audit surface rather than becoming event-scope claims. -Audit records must include at least: +The following is the canonical target `script_event_audit` field list (with the stated conditional absences): - Identity and versioning - `tenantId` - `gameInstanceId` (absent for tenant-readiness `onLoad`) - - `regionId` - - `regionEpoch` (required for gameplay/runtime and scheduler triggers; exceptions must be explicitly documented in the normative Trigger Identity table) + - `playableStateNamespaceId` (required for gameplay/runtime; absent for tenant-readiness `onLoad`) + - `playableStateScope` (separately persisted server-derived policy/routing/authorization/migration-fence evidence required for gameplay/runtime; explicitly excluded from identity) + - `regionId` (required for gameplay/runtime; absent for tenant-readiness `onLoad`) + - `regionEpoch` (required for gameplay/runtime and scheduler triggers; absent for tenant-readiness `onLoad`) - `entityId` (for entity-scoped events) - `scriptId` - `pluginId`, `pluginVersionId`, and `bindingId` (required for resolved plugin handlers) - `eventType` + - `eventSchemaVersion` (admitted event and payload contract version, including tenant-readiness `onLoad`; see [normative Table 1](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields)) - `scriptPatchVersion` - `scriptPinEpoch` (required for gameplay/runtime and scheduler triggers; absent for tenant-readiness `onLoad`) - - `scriptPinControlPlaneRequestId` (retained immutable owner/audit evidence, required with a positive `scriptPinEpoch` for every instance-scoped gameplay/runtime and scheduler trigger; absent with the entire pin tuple for pre-instance requests such as tenant-readiness `onLoad`; epoch-zero records represent explicitly unpinned state only on contracts that support that state and are not valid instance-scoped trigger admission) + - `scriptPinControlPlaneRequestId` (retained immutable owner/audit evidence, required with a positive `scriptPinEpoch` for every instance-scoped gameplay/runtime and scheduler trigger; absent with `scriptPinEpoch` for pre-instance requests such as tenant-readiness `onLoad`, while `scriptPatchVersion` remains required; epoch-zero records represent explicitly unpinned state only on contracts that support that state and are not valid instance-scoped trigger admission) - `scriptEventId` - `isDryRun` (boolean) - `sourceService` (derived from authenticated producer/workload identity for custom/service-specific events; the same value used in ingress dedupe and persisted unchanged in ingress and handler audit; omitted for built-in events that originate entirely within Automation & Scripting) + +Tenant-readiness `onLoad` uses the non-gameplay Trigger Identity branch defined by the [normative Trigger Identity table](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields): `gameInstanceId`, `playableStateNamespaceId`, `playableStateScope`, `regionId`, `regionEpoch`, and `scriptPinEpoch` are absent, rather than represented by sentinels or inferred current-runtime values. Gameplay/runtime audit records use the namespace as identity and retain scope only as separately validated evidence. + - Scheduling context (when applicable) - `triggerMode` (for example `NORMAL` vs `CATCH_UP`) - Exactly one of `dueTickId` or `dueAt` (for timers/intervals); the alternate field is absent/`NULL` @@ -176,7 +182,7 @@ Rules: During rollback, operator views must show the handler's `finalStage`/`finalOutcome` beside the `commandHandoffDispositions[]` returned from `ListScriptHandoffEvents`. A `TICK_HANDOFF` with `finalOutcome=handoff_accepted` therefore remains visible even when one or more individual commands later receive `version_fence_dropped`; a child result must never overwrite the handler result or collapse sibling command records. -Concrete example. Both child records below carry the complete `T123` Trigger Identity (`tenantId=11111111-1111-4111-8111-111111111111`, `gameInstanceId=44444444-4444-4444-8444-444444444444`, `playableStateScope=isolated`, `regionId=R2`, `regionEpoch=14`, `entityId=npc-guard-9`, `scriptId=guard-on-enter`, `eventType=onEnterRegion`, `eventSchemaVersion=1`, `scriptPatchVersion=P22`, `scriptPinEpoch=23`, `scriptEventId=evt-7f4c`, `isDryRun=false`) for correlation and diagnosis. The paired owner/audit evidence is `scriptPinControlPlaneRequestId=pin-req-22`; it is retained on each audit/child record and is not a Trigger Identity field. Each child is keyed by the complete Command-Handoff Identity: complete source/target runtime scope plus `automationDispatchId` and `commandOrdinal`. Parent Trigger Identity fields, `outboxWorkItemId`, and `scriptEventId` are not child uniqueness, deduplication, or replay keys. `automationDispatchId=dispatch-9` identifies the dispatch group, while `outboxWorkItemId=work-9` is parent correlation only. The `(automationDispatchId, commandOrdinal)` notation in the bullets is a display suffix, not a standalone key. This is a same-instance, same-runtime-scope example; the optional target fields (`targetGameInstanceId`, `targetPlayableStateScope`, `targetRegionId`, `targetRegionEpoch`) are intentionally absent because no distinct target scope applies. +Concrete example. Both child records below carry the complete `T123` Trigger Identity (`tenantId=11111111-1111-4111-8111-111111111111`, `gameInstanceId=44444444-4444-4444-8444-444444444444`, `playableStateNamespaceId=55555555-5555-4555-8555-555555555555`, `regionId=R2`, `regionEpoch=14`, `entityId=npc-guard-9`, `scriptId=guard-on-enter`, `eventType=onEnterRegion`, `eventSchemaVersion=1`, `scriptPatchVersion=P22`, `scriptPinEpoch=23`, `scriptEventId=evt-7f4c`, `isDryRun=false`) for correlation and diagnosis. The same records retain `playableStateScope=isolated` as separately validated policy/routing/authorization/migration-fence evidence; the paired `scriptPinControlPlaneRequestId=pin-req-22` is also retained as owner evidence and is not part of Trigger Identity. Each child is keyed by the complete Command-Handoff Identity: complete source/target runtime identity plus `automationDispatchId` and `commandOrdinal`. Parent Trigger Identity fields, `outboxWorkItemId`, and `scriptEventId` are not child uniqueness, deduplication, or replay keys. `automationDispatchId=dispatch-9` identifies the dispatch group, while `outboxWorkItemId=work-9` is parent correlation only. The `(automationDispatchId, commandOrdinal)` notation in the bullets is a display suffix, not a standalone key. This is a same-instance, same-runtime-scope example; the optional target fields (`targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetPlayableStateScope`, `targetRegionId`, `targetRegionEpoch`) are intentionally absent because no distinct target scope applies. - `script_event_audit` row for Trigger Identity `T123` ends with `finalStage=TICK_HANDOFF`, `finalOutcome=handoff_accepted`. - The handler emitted two commands. Later, Game Session rejects only the child ending in `(automationDispatchId=dispatch-9, commandOrdinal=1)` under the same complete command-handoff scope during rollback convergence and appends a child disposition with `outcome=version_fence_dropped`, `reason=script_patch_mismatch`, `sourceService=game-session`, and `recordedAt=...`; the child ending in `(automationDispatchId=dispatch-9, commandOrdinal=0)` remains a separate sibling record. @@ -188,6 +194,7 @@ Illustrative record shape: { "tenantId": "11111111-1111-4111-8111-111111111111", "gameInstanceId": "44444444-4444-4444-8444-444444444444", + "playableStateNamespaceId": "55555555-5555-4555-8555-555555555555", "playableStateScope": "isolated", "regionId": "R2", "regionEpoch": 14, @@ -233,6 +240,7 @@ Illustrative record shape: { "tenantId": "11111111-1111-4111-8111-111111111111", "gameInstanceId": "44444444-4444-4444-8444-444444444444", + "playableStateNamespaceId": "55555555-5555-4555-8555-555555555555", "regionId": "R2", "regionEpoch": 14, "entityId": "npc-guard-9", @@ -262,6 +270,7 @@ Illustrative record shape: { "tenantId": "11111111-1111-4111-8111-111111111111", "gameInstanceId": "44444444-4444-4444-8444-444444444444", + "playableStateNamespaceId": "55555555-5555-4555-8555-555555555555", "regionId": "R2", "regionEpoch": 14, "entityId": "npc-guard-9", diff --git a/design/architecture/system-architecture-scripting-operations-cookbook.md b/design/architecture/system-architecture-scripting-operations-cookbook.md index 06e6721fa8..60950759fa 100644 --- a/design/architecture/system-architecture-scripting-operations-cookbook.md +++ b/design/architecture/system-architecture-scripting-operations-cookbook.md @@ -141,7 +141,7 @@ This section summarizes common failure and rollback scenarios and how operators In all of these cases, `script_event_audit` remains the primary source of truth for Automation-owned handler lifecycle. For the current live diagnostic boundary and target per-command identity contract, use [Command Identity and Live Handoff Boundary](./system-architecture-scripting-rollout-and-rollback.md#command-identity-and-live-handoff-boundary). Metrics defined by [normative Table 4](./system-architecture-scripting-normative-contract-tables.md#table-4-metrics-label-matrix), together with audit and handoff diagnostics from the [Scripting & Automation Observability Contract](./system-architecture-scripting-observability-contract.md), indicate whether the problem is localized to a script/plugin, a tenant budget, or cluster capacity. -Target-state note: exact `scriptPinEpoch` propagation and final same-version old-epoch rejection are required at runtime-derived boundaries. The live `EnqueueAutomationCommandIfAbsentRequest` carries `scriptPatchVersion` but not `scriptPinEpoch`, so the current boundary cannot reject same-version work from an older epoch; this is an implementation gap, not a relaxation of the target fence. +Target-state note: exact `(scriptPatchVersion, scriptPinEpoch)` propagation and final same-version old-epoch rejection are required at runtime-derived boundaries. The request schema carries `scriptPinEpoch` and its paired owner request ID, but the authenticated Game Session receiver currently fails closed with `FAILED_PRECONDITION` / `automation_admission_receiver_fence_unavailable` before command or queue mutation. Lower-level staging, replay, and final-execution code retains exact tuple checks where reached; this does not establish live receiver availability. Distinct-instance remote source/target tuple binding and remote final-effect fencing remain implementation gaps, not relaxations of the target fence. ## Rollback & Recovery Cookbook @@ -155,7 +155,7 @@ Game Session's committed exact pin and append-only rollout history are the sole For local diagnosis during a rollback: -The current runtime does not prove target-state drain recovery from lease age: unresolved `EVALUATING` work remains active and `PENDING_EVALUATION` remains pending; target cancellation treats `PENDING_EVALUATION` as cancelable pre-DSL work. These are pre-DSL states, not evaluated descriptor `PENDING` or `INDEXED` work. Keep the Automation admission barrier in place until exact pin convergence and schedule reconciliation succeed; do not wait for asynchronous cancel/purge cleanup. Cleanup remains bounded and non-blocking, while **target-state exact `(scriptPatchVersion, scriptPinEpoch)` fencing** remains authoritative. **Current live gap:** `EnqueueAutomationCommandIfAbsentRequest` carries `scriptPatchVersion` but not `scriptPinEpoch`, so the current handoff cannot reject same-version old-epoch work; do not infer target rejection as shipped. Ordinary gameplay ticks and player commands continue, except within a separately declared unfenced-effect workflow. Do not infer reclaim, terminalization, or safe resumption locally. +The current runtime does not prove target-state drain recovery from lease age: unresolved `EVALUATING` work remains active and `PENDING_EVALUATION` remains pending; target cancellation treats `PENDING_EVALUATION` as cancelable pre-DSL work. These are pre-DSL states, not evaluated descriptor `PENDING` or `INDEXED` work. Keep the Automation admission barrier in place until exact pin convergence and schedule reconciliation succeed; do not wait for asynchronous cancel/purge cleanup. Cleanup remains bounded and non-blocking, while **target-state exact `(scriptPatchVersion, scriptPinEpoch)` fencing** remains authoritative. **Current live boundary:** the request carries `scriptPinEpoch` and its paired owner request ID, but the authenticated Game Session receiver fails closed with `FAILED_PRECONDITION` / `automation_admission_receiver_fence_unavailable` before command or queue mutation. Lower-level tuple checks remain narrower implementation behavior and do not establish receiver availability. Distinct-instance remote source/target tuple binding and remote final-effect fencing are separate implementation gaps. Ordinary gameplay ticks and player commands continue, except within a separately declared unfenced-effect workflow. Do not infer reclaim, terminalization, or safe resumption locally. For target-state admission containment during rollback, use the complete authoritative affected-scope enumeration from the durable PostgreSQL/runtime inventory described by the [Redis incident runbook](./system-architecture-redis-incident-runbook.md) to identify every regional scope and any actual unscoped/empty-region work. An omitted `regionId` is one exact unscoped row, never a wildcard; pause and read back each exact scope separately. Use the workflow-scoped `controlPlaneRequestId` with the explicit `PAUSED_FOR_ROLLBACK` step/target mode, reusing the same `(workflow ID, exact scope, step)` tuple only for an exact retry; the same workflow ID may span deliberate distinct scopes and the later `NORMAL` step. Missing enumeration or any exact-scope durable `APPLIED`/`ALREADY_APPLIED` acknowledgement/readback leaves the barrier in place, and no single omitted-region row authorizes an instance-wide success claim. The request-result and readback fields are owned by the [Scripting & Automation: Control Plane API](./system-architecture-scripting-control-plane-api.md#setautomationadmissionmode). The live `SetAutomationAdmissionMode`/`GetAutomationDrainStatus` surfaces do not yet provide that durable request-result acknowledgement or matching readback identity, so this per-scope sequence is not current recovery authorization; for a current incident, follow the [tick incident runbook's current-live containment branch](./system-architecture-tick-incident-runbook.md#stalled-tick-region) and its deployment-wide Automation fallback. @@ -167,7 +167,7 @@ For pending and dead-lettered work, use control-plane APIs rather than direct da - Replay phase semantics are stage-aware. A pre-claim authority or policy-unavailability result is `outcome=rejected`, records the bounded `rejectionReason`, creates no recovery claim or attempt, and leaves the row `DEAD_LETTERED`. Once a recovery claim/attempt is durably created, any failed evaluation or dispatch attempt must terminalize that attempt as `FAILED` and return `outcome=recovery_failed` with its persisted bounded `failureReason`; it must not be relabeled as a pre-claim rejection. A new request may create another attempt only after the prior attempt is terminal `FAILED` and fresh eligibility/fence checks pass; an `IN_PROGRESS` or unreconciled claim remains ineligible. Each requested ID returns exactly one bounded result (`retried_evaluation`, `resumed_dispatch`, `already_recovered`, `recovery_failed`, or `rejected`) with the canonical `failureGeneration` when a generation is resolved, bound to `(tenantId, outboxWorkItemId, failureGeneration)`, plus its applicable reason. The recovery claim/attempt has its own persisted attempt identity; this API does not expose a separate recovery-attempt generation, so no second generation field should be inferred. One row's result never changes another row's outcome or aggregate count. - **Target-state only and capability-gated:** `PurgeOutboxWorkItems(tenantId=11111111-1111-4111-8111-111111111111, scriptPatchVersion=P22, scriptPinEpoch=41, workItemIds=[work-9], controlPlaneRequestId=PURGE-42, actor=operator:alice, reason="rollback RB-42")` is auditable cleanup only when each selected work item matches the displaced exact tuple, is terminal (`HANDED_OFF`, `CANCELED`, or `DEAD_LETTERED`), and its configured retention horizon has elapsed. For evaluated descriptor/output evidence, the parent must be `EVALUATED_COMMITTED`, the parent and every child/evidence record must be retention-eligible, and every child must be terminal before that evidence is purged; a same-version repin with a newer epoch does not by itself make terminal rows from the displaced tuple ineligible, but the selector must remain the displaced exact tuple so current-epoch rows cannot be selected. For a pre-DSL `DEAD_LETTERED` row with no committed descriptor, purge may remove only terminal, retention-eligible trigger/failure payloads after the recovery eligibility window has expired, after resolving the current `failureGeneration` and atomically CASing recovery claim/attempt state. Any current-generation `IN_PROGRESS` claim, including an expired claim not yet canonically reclaimed, rejects with `recovery_in_progress` and deletes no evidence; only when no current-generation claim exists or its claim/attempt is terminal may purge proceed. For that pre-DSL path, no new schema marker is introduced: the retained purge audit/idempotency outcome is the durable evidence and makes the row permanently non-recoverable, so later replay rejects deterministically with `rejectionReason=stage_evidence_unavailable`; its immutable identity/digest, failure-stage, corresponding `script_event_audit`, and recovery-causation evidence remain retained under their owning retention contracts. When terminal descriptor/evaluated-output evidence is purged under the retained parent, the same transaction persists durable `descriptorEvidencePurgedAt`; that marked parent is non-recoverable and non-replayable, and consumers reject it deterministically rather than treating missing children as recoverable. The purge does not mutate active or nonterminal work. -For command-level diagnosis, use the [Scripting & Automation Observability Contract](./system-architecture-scripting-observability-contract.md) and [Command Identity and Live Handoff Boundary](./system-architecture-scripting-rollout-and-rollback.md#command-identity-and-live-handoff-boundary). The target query is `ListScriptHandoffEvents`; child replay and deduplication use the complete source runtime scope plus any distinct target runtime scope, the persisted `automationDispatchId`, and deterministic `commandOrdinal` from canonical output order. The full parent Trigger Identity (including `bindingId` where applicable), `outboxWorkItemId`, and `scriptEventId` are correlation only; bounded `workItemIds[]` are parent-row selectors only and cannot replace the child identity. When a distinct target runtime exists, its complete query/reference identity includes `targetGameInstanceId`, optional `targetPlayableStateScope`, `targetRegionId`, and `targetRegionEpoch`. The current live fallback is the correlation of `script_event_audit`, narrower Automation handoff/work-item rows, `outboxWorkItemId`, `automationDispatchId`, `gameSessionCommandId`, and the Game Session command/result/fence fields currently exposed. Do not infer complete Trigger Identity or downstream per-command disposition from that fallback. +For command-level diagnosis, use the [Scripting & Automation Observability Contract](./system-architecture-scripting-observability-contract.md) and [Command Identity and Live Handoff Boundary](./system-architecture-scripting-rollout-and-rollback.md#command-identity-and-live-handoff-boundary). The target query is `ListScriptHandoffEvents`; child/descriptor replay and deduplication remain deferred target behavior and, when implemented, follow the [canonical Command-Handoff Identity](./system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state). The current `workItemIds[]` input remains an executable parent-row selector only; it does not select independent command descriptors or provide command-level replay. The full parent Trigger Identity (including `bindingId` where applicable), `outboxWorkItemId`, and `scriptEventId` are correlation only; bounded `workItemIds[]` cannot replace the child identity. The current live fallback is the correlation of `script_event_audit`, narrower Automation handoff/work-item rows, `outboxWorkItemId`, `automationDispatchId`, `gameSessionCommandId`, and the Game Session command/result/fence fields currently exposed. Do not infer complete Trigger Identity or downstream per-command disposition from that fallback. For the canonical rollback and version-fence requirements, follow [Scripting & Automation: Rollout and Rollback](./system-architecture-scripting-rollout-and-rollback.md#patch-rollback-operator-driven-required) and [Scripting & Automation: Cross-Service Contracts](./system-architecture-scripting-contracts.md#3-version-fencing-rollback-safety). @@ -200,7 +200,7 @@ Operator actions: - Automation admission should remain paused for the affected scope through repin and schedule reconciliation; **target-state cleanup** is asynchronous, bounded, and non-blocking and must not delay resumption. This is not a routine gameplay-tick pause. - **Target-state cleanup:** queued automation work items and staging entries that carry the displaced exact `(scriptPatchVersion, scriptPinEpoch)` tuple are drained/purged as bounded resource and diagnostic cleanup; cleanup completion is not the correctness barrier and must not be described as preventing execution after repin. - **Target-state cleanup:** if plugin versions are also being rolled back, disabled, or revoked, call `CancelPendingWorkItemsForPluginVersion(tenantId=11111111-1111-4111-8111-111111111111, gameInstanceId=44444444-4444-4444-8444-444444444444, pluginId=town-crier, pluginVersionId=town-crier-v22, pluginActivationEpoch=7, scriptPatchVersion=P22, scriptPinEpoch=41, workItemIds=[work-9,work-10], controlPlaneRequestId=RB-42-PLUGIN-01, actor=operator:alice, reason="rollback RB-42")` with a nonempty, unique batch of at most 100 parent IDs (and optional `regionId`) before queue purge. Callers group IDs by the exact tuple and repeat batches with new request IDs; an exact retry reuses the stored batch result. The operation covers all applicable bindings in that tuple; each bounded result retains its `workItemId` and `bindingId` evidence. `lifecycleRevision` is intentionally absent from this request example: it is not a selector or request-digest field, and is retained per row and in final-fence evidence for later revalidation beside `pluginActivationEpoch`. Cleanup remains asynchronous and non-blocking and is not the correctness barrier. - - **Target-state only:** before handoff, Automation validates and carries the exact `(pluginId, pluginVersionId, bindingId)`, captured `(pluginActivationEpoch, lifecycleRevision)` pair, and current lifecycle/publication/policy evidence for plugin work. That independent fence survives evaluation, persistence, handoff, replay, final execution, and dead-letter recovery. Same-epoch `DRAINING` permits only the immediately preceding `ENABLED` revision whose winning admission/fence compare-and-set durably committed before the transition; it does not admit new work. Game Session revalidates the exact script tuple and captured plugin lifecycle pair and rejects stale applicable plugin tuple or fence evidence at execution time, including same-version work from an older script epoch or plugin activation epoch. **Current live gap:** `EnqueueAutomationCommandIfAbsentRequest` carries `scriptPatchVersion` but lacks `scriptPinEpoch` and the complete plugin fence, so the current handoff cannot make those rejections; do not present them as shipped. + - **Target-state only:** before handoff, Automation validates and carries the exact `(pluginId, pluginVersionId, bindingId)`, captured `(pluginActivationEpoch, lifecycleRevision)` pair, and current lifecycle/publication/policy evidence for plugin work. That independent fence survives evaluation, persistence, handoff, replay, final execution, and dead-letter recovery. Same-epoch `DRAINING` permits only the immediately preceding `ENABLED` revision whose winning admission/fence compare-and-set durably committed before the transition; it does not admit new work. Game Session revalidates the exact script tuple and captured plugin lifecycle pair and rejects stale applicable plugin tuple or fence evidence at execution time, including same-version work from an older script epoch or plugin activation epoch. **Current live gap:** the request schema carries `scriptPinEpoch` and its paired owner request ID but not the complete plugin fence, and the authenticated receiver fails closed before queue or command mutation because its admission fence is unavailable. Do not present target execution rejection as shipped receiver behavior. - Use the [Command Identity and Live Handoff Boundary](./system-architecture-scripting-rollout-and-rollback.md#command-identity-and-live-handoff-boundary) contract. For current live incidents, correlate `script_event_audit`, the narrower Automation handoff rows, and the Game Session command/result/fence fields currently exposed; do not infer a complete Trigger Identity or downstream per-command disposition. 4. Repair and republish. - Fix the underlying script configuration in the Game Design Service and publish a new script-only patch version. diff --git a/design/architecture/system-architecture-scripting-quotas-and-operations.md b/design/architecture/system-architecture-scripting-quotas-and-operations.md index 847966b64c..15b7b9088f 100644 --- a/design/architecture/system-architecture-scripting-quotas-and-operations.md +++ b/design/architecture/system-architecture-scripting-quotas-and-operations.md @@ -157,7 +157,7 @@ Per-script scheduling knobs control how often scripts are allowed to run and how - Queued triggers retain their durable admission charge but hold no execution capacity. An event-scope limiter may reject an incoming trigger before handler resolution, but that is not a per-script quota charge and uses event-scope ingress audit and drop metrics. After handler resolution, `ScriptQuotaService` records one charge for each resolved handler and may deny it with `script_event_audit.finalStage=ADMISSION`, `finalOutcome=quota_denied`, and the handler outcome metric rather than the dropped-ingress metric. - **`priorityTag`** – assigns a priority tier (`high`, `normal`, `background`) that interacts with per-tenant budgets and cluster ceilings. When capacity is tight, the scheduler applies tenant fairness first, then admits `high`-priority work preferentially within each tenant's allocated share, deferring or dropping lower-priority triggers according to budget and quota rules. -Timer and interval limits are evaluated against the canonical runtime scope tuple ``. A per-tenant or per-game-instance timer limit must not substitute for that tuple and accidentally couple unrelated instances or regions; any broader aggregate ceiling is an additional explicitly named safety limit. `playableStateScope` remains part of trigger identity and handler/work fencing, but it does not replace the scheduler's runtime scope tuple for these timer-capacity limits. +Timer and interval limits are evaluated against the canonical mode-specific per-namespace runtime scope tuple ``. A per-tenant or per-game-instance timer limit must not substitute for that tuple and accidentally couple unrelated playable-state namespaces, regions, or live/test modes; any separately named broader aggregate ceiling (for example, a cluster-wide safety limit) is an additional safety limit. `playableStateScope` is server-derived and must be exact-validated against the authoritative namespace/routing proof, then retained unchanged as separately persisted policy/routing/authorization/migration-fence evidence on event-scope ingress, durable schedules, due-candidate records, firing claims, candidate-audit records, mode-specific resume-window records, handler/work items, and per-command handoff records. This persistence list is non-exhaustive; the complete timer identity and recovery projections are owned by [Scripting Scheduler and Timer Lifecycle](./system-architecture-scripting-scheduler-and-timers.md#target-state-design) and the [normative timer semantics matrix](./system-architecture-scripting-normative-contract-tables.md#table-3-timer-semantics-matrix). Logs, audit rows, and traces may carry bounded correlation copies for diagnosis, but those copies do not become authority and must not be used to reconstruct or override the retained evidence. Scope evidence does not replace the scheduler's runtime scope tuple or become a Trigger Identity, uniqueness, or deduplication input; see the [normative identity tables](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). ### `onLoad` Initialization Capacity @@ -265,9 +265,9 @@ The **target-state** canonical `script_event_audit` schema includes: - `sourceService` – producing service identity for custom/service-specific events so operators can diagnose routing and authorization problems. - `tickId` – canonical tick identifier associated with the trigger when the trigger is tick-aligned or once commands are accepted into the tick system. -For tenant-readiness `onLoad` triggers, `gameInstanceId`, `playableStateScope`, `regionId`, `regionEpoch`, `entityId`, and `scriptPinEpoch` are omitted; they must not be populated with sentinel values. Their existing identity remains ``. Gameplay/runtime triggers require `scriptPinEpoch` with `scriptPatchVersion` and include the other fields when applicable according to the normative Trigger Identity table. +For tenant-readiness `onLoad` triggers, `gameInstanceId`, `playableStateNamespaceId`, `playableStateScope`, `regionId`, `regionEpoch`, `entityId`, and `scriptPinEpoch` are omitted; they must not be populated with sentinel values. Their existing identity remains ``. Gameplay/runtime triggers require `scriptPinEpoch` with `scriptPatchVersion` and include the other fields when applicable according to the normative Trigger Identity table. -Current instance-scoped ingress validates the exact owner tuple before handler work is admitted, Automation persists that tuple on work-item and handoff-audit evidence, and the local Game Session handoff, durable staging/replay, and final execution boundaries revalidate it. The remaining downstream gap is distinct-instance remote source/target binding and remote final-effect fencing; see the [Automation & Scripting Service implementation status](./microservices/automation-scripting-service/runtime-and-data.md#implementation-status). +Current instance-scoped Automation ingress validates the exact owner tuple before handler work is admitted and persists it on work-item and handoff-audit evidence. Although `EnqueueAutomationCommandIfAbsentRequest` carries `scriptPinEpoch` and the paired owner request ID, the authenticated Game Session receiver currently fails closed with `FAILED_PRECONDITION` / `automation_admission_receiver_fence_unavailable` before command or queue mutation; the live handoff is unavailable, not a missing-epoch-field path. Lower-level Game Session staging, replay, and final-execution checks retain exact tuple validation where reached. Distinct-instance remote source/target tuple binding and remote final-effect fencing remain implementation gaps; see the [Automation & Scripting Service implementation status](./microservices/automation-scripting-service/runtime-and-data.md#implementation-status) and [Game Session API implementation status](./microservices/game-session-service/api-contracts.md#implementation-status). - **Stage-aware outcome** - `finalStage` – the last stage reached for the trigger (for example `ADMISSION`, `DSL_EVAL`, `WORK_ITEM_PERSIST`, `TICK_HANDOFF`). @@ -325,7 +325,7 @@ Plugin executions use the Table 4 bounded plugin classifications rather than raw Script execution spans several services (Game Design, Game Session, Automation & Scripting, Game Logic, Logging & Admin). To support end-to-end debugging and replay, the system relies on a shared set of identifiers: - `tenantId`, `gameInstanceId`, and `regionId` – identify the running game instance and region. -- `playableStateScope` (gameplay/runtime only) – identifies the resolved admitted gameplay-state namespace; shared and isolated realm state must not collide. Retain it in applicable audit/log/trace correlation, not as a metric label. See the [normative Trigger Identity table](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields); tenant-readiness `onLoad` intentionally omits it. +- `playableStateNamespaceId` (gameplay/runtime only) – identifies the durable playable-state namespace in applicable Trigger Identity and deduplication. `playableStateScope` is separately persisted and exact-validated policy/routing/authorization/migration-fence evidence; retain it in applicable audit/log/trace correlation, not as an identity or metric label. See the [normative Trigger Identity table](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields); tenant-readiness `onLoad` intentionally omits both fields. - `regionEpoch` – fences triggers and tick effects across scoped coordination resets. - `entityId` – identifies the target entity for script-driven work. - `scriptId` and `scriptPatchVersion` identify the script definition; gameplay/runtime rows also require `scriptPinEpoch` to identify the Game Session selection epoch. Tenant-readiness `onLoad` rows omit `scriptPinEpoch`. @@ -341,8 +341,8 @@ These identifiers are intended to appear in the following observability surfaces A typical troubleshooting flow for a problematic script or plugin is: -1. Start from a player-visible issue or a game tick log that includes `tenantId`, `gameInstanceId`, `playableStateScope` when gameplay/runtime-scoped, `regionId`, `regionEpoch`, `entityId`, and `tickId`. -2. Join the tick log, `script_event_audit`, and logs/traces by the complete applicable Trigger Identity: `tenantId`, `gameInstanceId`, `playableStateScope` when gameplay/runtime-scoped, `regionId`, `regionEpoch`, `entityId` when applicable, `scriptId`, `eventType`, `eventSchemaVersion`, `scriptPatchVersion`, `scriptPinEpoch` when applicable, `scriptEventId`, `isDryRun`, and plugin/scheduler fields when applicable. `scriptEventId` and `correlationId` are scoped filters that narrow a search; neither is a standalone execution identity and neither may be used as the join key without the remaining applicable fields. Do not rely on `scriptEventId` as a metric label; use metrics to understand aggregate rates by bounded `scope` / `script_kind` / `event_class` dimensions and use audit/log/trace queries for per-trigger correlation. +1. Start from a player-visible issue or a game tick log that includes `tenantId`, `gameInstanceId`, `playableStateNamespaceId` when gameplay/runtime-scoped, `regionId`, `regionEpoch`, `entityId`, and `tickId`; retain `playableStateScope` separately as exact-validated policy/routing/authorization/migration-fence evidence. +2. Join the tick log, `script_event_audit`, and logs/traces by the complete applicable Trigger Identity: `tenantId`, `gameInstanceId`, `playableStateNamespaceId` when gameplay/runtime-scoped, `regionId`, `regionEpoch`, `entityId` when applicable, `scriptId`, `eventType`, `eventSchemaVersion`, `scriptPatchVersion`, `scriptPinEpoch` when applicable, `scriptEventId`, `isDryRun`, and plugin/scheduler fields when applicable. Retain `playableStateScope` as separately persisted, exact-validated policy/routing/authorization/migration-fence evidence for filtering/readback, not as identity or a join-key dimension. `scriptEventId` and `correlationId` are scoped filters that narrow a search; neither is a standalone execution identity and neither may be used as the join key without the remaining applicable fields. Do not rely on `scriptEventId` as a metric label; use metrics to understand aggregate rates by bounded `scope` / `script_kind` / `event_class` dimensions and use audit/log/trace queries for per-trigger correlation. 3. From the identity-matched records, identify the responsible `scriptId`, `scriptPatchVersion`, and, where applicable, `pluginId`/`pluginVersionId`/`bindingId`. 4. Cross-reference the associated publish or plugin enable/disable actions in Game Design and Logging & Admin using the same identifiers. @@ -421,7 +421,7 @@ The **authoritative, up-to-date list of environment variables and defaults** liv - **Quota knobs** – control per-script and per-tenant quota windows and budgets used by `ScriptQuotaService` and the multi-level budgeting model (for example, limits on how many triggers a script or tenant may execute per window). - **Execution batch knobs** – bound how much automation work the durable executor performs per scheduling window, including batch sizes, per-window budgets, and cluster-wide ceilings on automation events. -- **Timer and scheduling knobs** – influence `onInterval` / `onTimerExpire` behavior, including cadence and maximum timers evaluated per canonical runtime scope tuple ``, plus any backoff or delay settings applied when regions are degraded. +- **Timer and scheduling knobs** – influence `onInterval` / `onTimerExpire` behavior, including cadence and maximum timers evaluated per canonical mode-specific per-namespace runtime scope tuple ``, plus any separately named broader aggregate ceilings and backoff or delay settings applied when regions are degraded. - **Audit and retention knobs** – govern how long `script_event_audit` and related records remain available for troubleshooting, and how large those tables are allowed to grow before automated cleanup; retention is typically controlled via `SCRIPT_EVENT_AUDIT_RETENTION_DAYS` and `SCRIPT_EVENT_AUDIT_MAX_ROWS`, with exact defaults and semantics documented in [Automation & Scripting Service Configuration](./microservices/automation-scripting-service/configuration.md#service-specific-variables). For the exact variable names, defaults, and any future additions, always refer to [Automation & Scripting Service Configuration](./microservices/automation-scripting-service/configuration.md#service-specific-variables) rather than the README or this document. diff --git a/design/architecture/system-architecture-scripting-runtime-execution.md b/design/architecture/system-architecture-scripting-runtime-execution.md index da06d60c46..d4e2733a71 100644 --- a/design/architecture/system-architecture-scripting-runtime-execution.md +++ b/design/architecture/system-architecture-scripting-runtime-execution.md @@ -70,35 +70,35 @@ This section records current implementation boundaries, not target-state authori The current executor commits each per-item `PENDING_EVALUATION` to `EVALUATING` claim before running the DSL in a separate local transaction. After evaluation, each child’s `HANDOFF_IN_FLIGHT` intent commits before the Game Session RPC, which runs without an Automation transaction active; a definitive response is recorded in a separate guarded transaction. Failed pre-RPC intent persistence prevents dispatch, while ambiguous post-dispatch failure remains unresolved and is not reset for DSL replay. The durable evaluated-descriptor and reconciliation-owner layers needed for safe stage-aware recovery remain target-only. -The current runtime now includes a first durable work-item executor instead of stopping at ingress-only outbox materialization. During ingress, after handler resolution, Automation acquires per-script quota for live `STANDARD_RUNTIME` handlers before persisting `PENDING_EVALUATION` work. The executor claims `PENDING_EVALUATION` rows without re-charging that per-script quota; it separately applies tenant-budget, publish-readiness, or isolated dry-run capacity controls as applicable before loading the persisted script definition, evaluating a current-boundary command-emission format, and handing emitted commands to Game Session through `EnqueueAutomationCommandIfAbsent`. The target durable full-Trigger-Identity charge record and separate exactly-once admission/execution-start markers remain unimplemented. The replay and evaluated-descriptor layers described by the target lifecycle are target-only. The current implementation still uses one `script_work_items` row spanning the pre-DSL trigger and later handoff processing; it does not yet implement the target separation between durable trigger state and evaluated command descriptors or descriptor-only replay. +The current runtime now includes a first durable pre-DSL trigger-record executor instead of stopping at ingress-only outbox materialization. During ingress, after handler resolution, Automation acquires per-script quota for live `STANDARD_RUNTIME` handlers before persisting `PENDING_EVALUATION` trigger records. The executor claims `PENDING_EVALUATION` rows without re-charging that per-script quota; it separately applies tenant-budget, publish-readiness, or isolated dry-run capacity controls as applicable before loading the persisted script definition, evaluating a current-boundary command-emission format, and handing emitted commands to Game Session through `EnqueueAutomationCommandIfAbsent`. The target full-Trigger-Identity handler charge record is separate from the pre-DSL trigger-record/work-item row, is the sole authority for exactly-once admission and execution-start markers, and is linked from that row; this record and linkage remain unimplemented. The replay and evaluated-descriptor layers described by the target lifecycle are target-only. The current implementation still uses one `script_work_items` row spanning the pre-DSL trigger record and later handoff processing; it does not yet implement the target separation between durable trigger records and evaluated script work items or descriptor-only replay. ### Current evaluator boundary The current evaluator supports a bounded emitted-command collection per work item, assigns deterministic local ordinals in emitted-command order, and attempts handoff for each emitted command. An actual configured output-count or per-entity limit is rejected before output/descriptor persistence or handoff; the pre-DSL parent work item was claimed from `PENDING_EVALUATION` and is `EVALUATING` at evaluation time, then its durable terminal transition and audit row record `finalStage=DSL_EVAL`, `finalOutcome=sandbox_error`, and the exact bounded limit reason (`command_count_exceeded` or `per_entity_command_limit_exceeded`). The target contract remains canonical in [Scripting & Automation: Cross-Service Contracts](./system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary), including deterministic identity under the complete [Command-Handoff Identity](./system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state). -That current-boundary execution format is intentionally narrow but no longer raw-text-only: script definitions may expose `emitCommands` at the top level or under `eventHandlers..emitCommands`, and each emitted command may currently carry either direct `commandText` or a structured `commandAlias` plus templated `arguments`, along with an optional target entity or bounded `targetEntityIds[]` list, optional explicit target runtime scope (`targetGameInstanceId`, `targetRegionId`, `targetRegionEpoch`), `requiresSoloTick`, and optional `dueTickId`. The evaluator may expand `targetEntityIds[]` locally and attempt one command per listed target. If no target is present, the command targets the triggering work item's entity; if explicit target runtime scope is absent, the command defaults to the triggering work item's owned gameplay scope. Each resulting command receives a local ordinal and is attempted through the handoff service, but this local expansion is not the target-state multi-target fan-out contract: the live wire does not carry the complete per-target identity or target `playableStateScope`, so complete handoff identity, scope validation, deduplication, and end-to-end progress remain unproved. Command nodes may also carry bounded `when` / `unless` predicate maps over durable work-item metadata and flat primitive payload fields; target-state command ordinals and optional `targetPlayableStateScope` distinguish emitted commands after handoff identity is widened. Template substitution is still limited to durable work-item metadata and flat primitive payload fields such as `{{payload.commandName}}`. Richer graph execution and broader DSL semantics remain target-state work above this first production evaluator path. +That current-boundary execution format is intentionally narrow but no longer raw-text-only: script definitions may expose `emitCommands` at the top level or under `eventHandlers..emitCommands`, and each emitted command may currently carry either direct `commandText` or a structured `commandAlias` plus templated `arguments`, along with an optional target entity or bounded `targetEntityIds[]` list, optional explicit target runtime scope (`targetGameInstanceId`, `targetRegionId`, `targetRegionEpoch`), `requiresSoloTick`, and optional `dueTickId`. The evaluator may expand `targetEntityIds[]` locally and attempt one command per listed target. If no target is present, the command targets the triggering pre-DSL trigger record's entity; if explicit target runtime scope is absent, the command defaults to the triggering pre-DSL trigger record's owned gameplay scope. Each resulting command receives a local ordinal and is attempted through the handoff service, but this local expansion is not the target-state multi-target fan-out contract: the live wire does not carry the complete per-target identity or target `playableStateScope`, so complete handoff identity, scope validation, deduplication, and end-to-end progress remain unproved. Command nodes may also carry bounded `when` / `unless` predicate maps over durable pre-DSL trigger-record metadata and flat primitive payload fields; target-state command ordinals and optional `targetPlayableStateNamespaceId` distinguish emitted commands after handoff identity is widened, while target `playableStateScope` remains separately exact-validated evidence. Template substitution is still limited to durable pre-DSL trigger-record metadata and flat primitive payload fields such as `{{payload.commandName}}`. Richer graph execution and broader DSL semantics remain target-state work above this first production evaluator path. The current claim boundary is the atomic PostgreSQL transition from `PENDING_EVALUATION` to `EVALUATING`; the existing Game Session lease rules govern region-owned tick execution, not Automation work-item claims. The current implementation has no evaluation lease expiry, fencing generation, descriptor-commit marker, or recovery owner. Its `GetAutomationDrainStatus` projection selects the counted epoch set by mode: `NORMAL` includes only rows whose `workItem.admissionEpoch` equals the current `admissionEpoch`, while `PAUSED_FOR_ROLLBACK` includes rows whose `workItem.admissionEpoch <= 0` or `workItem.admissionEpoch < current admissionEpoch`, excluding positive current-epoch rows. Within that set `activeExecutionCount` counts `EVALUATING` and `HANDOFF_IN_FLIGHT`, including unresolved stale `EVALUATING`, and `pendingCancelableWorkItemCount` counts `PENDING_EVALUATION`. These are current implementation gaps: the current runtime retains unresolved work and keeps the Automation admission barrier closed; ordinary gameplay ticks continue except within a separately declared unfenced-effect workflow. It cannot safely resume or promise terminal audit from lease age alone. The target mapping and recovery behavior are defined below, and current tooling must not infer reclaim, terminalization, or re-entry to the DSL. The current `onLoad` implementation slice is tenant-readiness work limited to configuration/runtime metadata validation and warming recomputable in-process caches. It does not perform per-entity setup or create handler-owned durable shared state. Platform-owned execution, readiness, and `script_event_audit` metadata remains required bookkeeping and is not a handler-created effect. The current implementation also lacks stale-`ONLOAD_RUNNING` generation recovery; that gap must not be handled by re-entering the same DSL execution. -At the live Game Session handoff boundary, the current `EnqueueAutomationCommandIfAbsentRequest` wire fields are exactly `tenant_id`, `game_instance_id`, `region_id`, `region_epoch`, `due_tick_id` (logically optional for immediate event-driven work), `automation_dispatch_id`, `automation_work_item_id`, `script_id`, `script_patch_version`, `target_entity_id`, `command`, `requires_solo_tick`, `plugin_id`, `plugin_version_id`, `playable_state_scope`, `world_slug`, `realm_slug`, `pointer_version`, `origin_source_kind`, `origin_source_state`, `origin_source_ordinal`, `origin_source_due_tick_id`, `origin_source_due_at_ms`, `binding_id`, `script_pin_epoch`, and `script_pin_control_plane_request_id`. Its response fields are exactly `accepted`, `admission_outcome`, `command_id`, and `error`. The current `playable_state_scope` is the source/current admitted routing scope, not a distinct target scope; `automation_work_item_id` is the wire alias for parent `outboxWorkItemId`. The request does not carry `command_ordinal`, `script_event_id`, `event_type`, `event_schema_version`, `is_dry_run`, `target_game_instance_id`, `target_playable_state_scope`, `target_region_id`, or `target_region_epoch`; those fields, the complete Trigger Identity, and the complete Command-Handoff Identity are target-only for this direct enqueue boundary. A command with a distinct target runtime scope must not be sent through this local enqueue mutation; if no existing remote follow-up path handles it, the local request rejects before its persistence/handoff attempt. The existing remote follow-up path remains separate and continues to carry its target scope. The supported source/current scope remains admitted. The current executor may attempt multiple emitted commands with local ordinals, but this narrower wire does not prove target per-command identity, deduplication, fencing, or independent progress. +At the live Game Session handoff boundary, the current `EnqueueAutomationCommandIfAbsentRequest` wire fields are exactly `tenant_id`, `game_instance_id`, `region_id`, `region_epoch`, `due_tick_id` (logically optional for immediate event-driven work), `automation_dispatch_id`, `automation_work_item_id`, `script_id`, `script_patch_version`, `target_entity_id`, `command`, `requires_solo_tick`, `plugin_id`, `plugin_version_id`, `playable_state_scope`, `world_slug`, `realm_slug`, `pointer_version`, `origin_source_kind`, `origin_source_state`, `origin_source_ordinal`, `origin_source_due_tick_id`, `origin_source_due_at_ms`, `binding_id`, `script_pin_epoch`, and `script_pin_control_plane_request_id`. Its response fields are exactly `accepted`, `admission_outcome`, `command_id`, and `error`. The current `playable_state_scope` is presented request evidence for the source/current routing scope, not proof of admitted scope; `automation_work_item_id` is the wire alias for parent `outboxWorkItemId`. The request does not carry `command_ordinal`, `script_event_id`, `event_type`, `event_schema_version`, `is_dry_run`, `target_game_instance_id`, `target_playable_state_scope`, `target_region_id`, or `target_region_epoch`; those fields, the complete Trigger Identity, and the complete Command-Handoff Identity are target-only for this direct enqueue boundary. A command with a distinct target runtime scope must not be sent through this local enqueue mutation; if no existing remote follow-up path handles it, the local request rejects before its persistence/handoff attempt. The authenticated enqueue RPC currently fails closed with `FAILED_PRECONDITION` (`automation_admission_receiver_fence_unavailable`) before command or queue mutation, so none of the request's scope fields establish successful admission through this receiver. The existing remote follow-up path remains separate and continues to carry its target scope. The current executor may attempt multiple emitted commands with local ordinals, but this narrower wire does not prove target per-command identity, deduplication, fencing, or independent progress. -The front exact ingress/timer tuple is live, with an important evidence distinction: an ingress claim records the caller's attempted `scriptPatchVersion`/`scriptPinEpoch`/`scriptPinControlPlaneRequestId` tuple, while an admitted instance-scoped trigger has that tuple validated against the authoritative Game Session read before handler work is created. A rejected pre-admission request, including an unavailable or mismatched authority result, may retain its attempted tuple as request evidence but must not be presented as an authoritative observation; the request ID is required whenever `scriptPinEpoch` is positive and is absent for both the unpinned `scriptPinEpoch=0` branch and the pre-instance tenant-readiness `onLoad` identity. For local instance-scoped Automation commands, Game Session compares that complete tuple with the current `GameInstance` before accepting or replaying a duplicate, locks and rechecks it while sealing fresh or replayed tick work, and rechecks the persisted tuple at final execution. The remote command handoff wire carries source `scriptPatchVersion`/`scriptPinEpoch`/`scriptPinControlPlaneRequestId` evidence, but its receiver does not yet persist or enforce the complete source/target tuple at admission and final effect; that remote boundary must not be presented as complete target enforcement. +The front exact ingress/timer tuple is live, with an important evidence distinction: an ingress claim records the caller's attempted `scriptPatchVersion`/`scriptPinEpoch`/`scriptPinControlPlaneRequestId` tuple, while an admitted instance-scoped trigger has that tuple validated against the authoritative Game Session read before handler work is created. A rejected pre-admission request, including an unavailable or mismatched authority result, may retain its attempted tuple as request evidence but must not be presented as an authoritative observation; the request ID is required whenever `scriptPinEpoch` is positive and is absent for both the unpinned `scriptPinEpoch=0` branch and the pre-instance tenant-readiness `onLoad` identity. Existing lower-level local instance-scoped command checks compare that complete tuple with the current `GameInstance` before acceptance or duplicate replay, recheck it while sealing fresh or replayed tick work, and recheck the persisted tuple at final execution where those paths are reached; they do not establish successful admission through the currently fail-closed authenticated enqueue RPC. The remote command handoff wire carries source `scriptPatchVersion`/`scriptPinEpoch`/`scriptPinControlPlaneRequestId` evidence, but its receiver does not yet persist or enforce the complete source/target tuple at admission and final effect; that remote boundary must not be presented as complete target enforcement. Target local instance admission and replay use Automation's bounded-fresh exact `(scriptPatchVersion, scriptPinEpoch, scriptPinControlPlaneRequestId)` projection; when it is absent or stale, Automation performs a bounded refresh from an owner-evidence-carrying authoritative Game Session read and fails closed if that refresh cannot prove the tuple. Direct Game Session reads remain the owner/final-fence source and are used to freeze a remote target tuple; neither path permits a patch-only local pointer or version-only fallback. See [ADR 0108](./decisions/adr-0108-no-degraded-script-admission-without-authoritative-pin.md) and the [cross-service version-fencing contract](./system-architecture-scripting-contracts.md#3-version-fencing-rollback-safety). **Target-state remote-follow-up consequence:** When a follow-up crosses to a distinct target game instance, the source work retains the originating exact `(scriptPatchVersion, scriptPinEpoch)` as immutable provenance and source rollback-fence evidence, with its paired `scriptPinControlPlaneRequestId` retained separately as immutable source pin-owner evidence rather than as an operation-scoped request ID. Before target-side Automation admission, Game Session revalidates that source tuple and owner evidence, reads and freezes the target instance's current exact tuple and paired owner request evidence, and binds both roles to the target delivery/claim and immutable request/dedupe evidence. Target event/handler Trigger Identity and target-side script admission/execution fences use the target tuple, not the source tuple; the paired request IDs remain non-identity evidence. Retries reuse both frozen tuples and their paired owner evidence; source or target displacement/conflict fails closed, authority unavailability remains retryable with no target admission, and target `UNPINNED` creates no target script work. A same-instance cross-region follow-up uses one exact tuple and paired owner evidence for both roles. For semantic target `UNPINNED`, Game Session applies the owner-defined durable/replayable result encoding and exact-retry/conflict rules; the target creates no Automation event, work item, or command. See the [Game Session remote-follow-up result contract](./microservices/game-session-service/api-contracts.md#service-interactions). Authority unavailability remains retryable and non-admitted rather than becoming that finalized result. -Current dedupe, rejection, and status diagnostics use the available `outboxWorkItemId`/parent work-item correlation, persisted `automationDispatchId`, Game Session `commandId`/persisted `gameSessionCommandId`, command text, selected provenance, and `script_event_audit`. `outboxWorkItemId` is not a per-command discriminator. This is a live diagnostic and retry fallback only; it does not claim end-to-end complete Trigger Identity, `commandOrdinal`, independent per-command progress, or target command-level deduplication/fence proof. +Current dedupe, rejection, and status diagnostics use the available `outboxWorkItemId`/parent pre-DSL trigger-record correlation, persisted `automationDispatchId`, Game Session `commandId`/persisted `gameSessionCommandId`, command text, selected provenance, and `script_event_audit`. `outboxWorkItemId` is not a per-command discriminator. This is a live diagnostic and retry fallback only; it does not claim end-to-end complete Trigger Identity, `commandOrdinal`, independent per-command progress, or target command-level deduplication/fence proof. ## Pre-DSL Trigger and Evaluated Descriptor Boundary The durable pre-DSL trigger state and the post-DSL evaluated command descriptor/outbox are separate durable roles: - The target lifecycle for the **pre-DSL trigger record** is `PENDING_EVALUATION` -> `EXECUTING` -> `EVALUATED_COMMITTED`, with explicit terminal cancellation/dead-letter transitions only where the cancellation and stale-recovery rules below permit them. The record owns the complete applicable Trigger Identity, event payload, pinned script/configuration and artifact references, the immutable handler-scoped input manifest, admission epoch, evaluation lease, fencing generation, and the durable descriptor-commit marker/status. Before that descriptor commit, a command-capable gameplay/runtime evaluation has no `automationDispatchId` or command-child identity. It contains no evaluated gameplay command descriptors. The manifest is the deterministic read input; an owner-specific `read_snapshot_token`, when applicable, is one recorded manifest entry rather than universal authority. -- The **evaluated command descriptor/outbox** is created only after DSL evaluation. It contains the immutable evaluated descriptor for each emitted command, including `automationDispatchId` and `commandOrdinal`, plus parent `outboxWorkItemId` correlation, the applicable trigger/configuration inputs, and optional `targetGameInstanceId`, `targetPlayableStateScope`, `targetRegionId`, and `targetRegionEpoch` when the command has a distinct target runtime scope needed for handoff and replay. +- The **evaluated command descriptor/outbox** is created only after DSL evaluation. It contains the immutable evaluated descriptor for each emitted command, including `automationDispatchId` and `commandOrdinal`, plus parent `outboxWorkItemId` correlation, the applicable trigger/configuration inputs, and an optional distinct target runtime scope expressed by `targetGameInstanceId`, `targetRegionId`, and `targetRegionEpoch` together. `targetPlayableStateNamespaceId` is included conditionally when the target scope is namespace-owned. The target `playableStateScope` remains separately persisted and exact-validated as policy/routing/authorization/migration-fence evidence. **Target state only:** Before DSL evaluation, the worker acquires the separately fenced, reclaimable capacity lease and uses one Automation-owned durable executor-acceptance transaction to revalidate the current fence, durably accept/claim the run for the executor, persist the exactly-once execution-start marker, and compare-and-set the pre-DSL trigger to `EXECUTING` with a monotonically increasing fencing generation. Evaluation begins only after that transaction commits. Tenant-readiness `onLoad` is non-emitting and neither allocates nor exposes a command dispatch identity. The worker may commit evaluated descriptors only while that lease and generation are current. If commands are emitted, the descriptor rows, their parent outbox record, the persisted `automationDispatchId` and canonical ordinals, the terminal evaluation outcome, and the audit update are committed atomically with a compare-and-set transition from `EXECUTING` to `EVALUATED_COMMITTED` in one transaction; a valid zero-command evaluation creates no dispatch identity. A non-cancellation retry after that commit boundary loads the committed descriptors and replays handoff; it never re-enters the DSL. If executor acceptance cannot commit, the transition does not occur, the lease is released or reclaimed, and no execution charge is recorded. @@ -109,11 +109,11 @@ Target-state cancellation of pre-DSL trigger states is durable and fencing-aware - `PENDING_EVALUATION` transitions by compare-and-set to terminal `CANCELED` without entering the DSL. The same durable transition records `cancelReason` and updates `script_event_audit` to `finalStage=ADMISSION`, `finalOutcome=canceled`, and the applicable bounded reason, such as `operator_canceled` or `rollback_epoch_advanced`. - `EXECUTING` cancellation first fences the claimed attempt and reads the descriptor-commit marker/status. If the state is or becomes `EVALUATED_COMMITTED`, cancellation never resumes or re-dispatches a committed child: evaluated `PENDING` and `INDEXED` children compare-and-set to `CANCELED` with durable `cancelReason`, `finalStage=WORK_ITEM_PERSIST`, and `finalOutcome=canceled`; `HANDOFF_IN_FLIGHT` fences further retry and reconciles the durable downstream outcome, remaining active/unresolved when that outcome is ambiguous; and `HANDED_OFF`, `CANCELED`, or `DEAD_LETTERED` children retain their outcome and no-op. Recovery of that committed state is a separate path owned by the control-plane recovery contract and may replay only the stored child ledger; cancellation itself does not dispatch. If no descriptor was committed, explicit cancellation compare-and-sets the trigger to terminal `CANCELED` and records `cancelReason`, `finalStage=DSL_EVAL`, `finalOutcome=canceled`, and the applicable bounded cancellation reason; this terminal cancellation is never replay-eligible. If the lease is instead expired and stale, only the distinct recovery-owner transition may make the row terminal `DEAD_LETTERED` with `finalStage=DSL_EVAL`, `finalOutcome=canceled`, and `finalReason=stale_execution_fenced`. -Cancellation and automatic stale-executor recovery never invoke or re-enter the DSL. Separately, control-plane evaluation-stage recovery may re-enter the DSL only when the persisted failure class is retryable under [Failure Modes and Error Handling](#failure-modes-and-error-handling), no descriptor has committed, and frozen manifest/graph evidence and the original work-item/Trigger Identity are present; non-retryable classes remain terminal/ineligible. Once a descriptor is committed, control-plane recovery replays the stored child ledger without DSL re-entry. These cancellation and automatic stale-recovery paths operate only on durable trigger state, descriptor-commit evidence, and already committed descriptors. +Cancellation and automatic stale-executor recovery never invoke or re-enter the DSL. Separately, control-plane evaluation-stage recovery may re-enter the DSL only when the persisted failure class is retryable under [Failure Modes and Error Handling](#failure-modes-and-error-handling), no descriptor has committed, and frozen manifest/graph evidence and the original pre-DSL trigger record/Trigger Identity are present; non-retryable classes remain terminal/ineligible. Once a descriptor is committed, control-plane recovery replays the stored child ledger without DSL re-entry. These cancellation and automatic stale-recovery paths operate only on durable trigger state, descriptor-commit evidence, and already committed descriptors. ## Work Item Outbox Contract (Normative) -The Automation & Scripting Service must treat Redis automation queues (`automation:queue:*`) as derived indexes/pointers only. The authoritative record of admitted post-DSL work is the durable work item outbox. Queue ownership, command handoff, and cross-service retry invariants are defined in the [scripting cross-service contracts](./system-architecture-scripting-contracts.md); this section retains the local outbox schema and projection behavior. +The Automation & Scripting Service must treat Redis automation queues (`automation:queue:*`) as derived indexes/pointers only. The authoritative record of admitted post-DSL work is the durable evaluated script work item outbox. Queue ownership, command handoff, and cross-service retry invariants are defined in the [scripting cross-service contracts](./system-architecture-scripting-contracts.md); this section retains the local outbox schema and projection behavior. This section defines the minimum contract that makes "persist -> index -> drain -> handoff" interoperable and rollback-safe across services and operational tooling. @@ -126,14 +126,14 @@ Each evaluated descriptor/outbox record must include: - Trigger Identity fields from [Table 1](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) (including `gameInstanceId` and, for gameplay/runtime triggers, `regionEpoch`). - The exact local `(scriptPatchVersion, scriptPinEpoch, scriptPinControlPlaneRequestId)` captured from the authoritative Game Session pin. A local active/latest pointer, version-only match, or unpaired owner request ID is insufficient. - `outboxWorkItemId` (stable parent correlation identifier; not descriptor identity). -- The unique child identity for each evaluated command descriptor: the complete Command-Handoff Identity, including optional `targetPlayableStateScope` and the other target runtime fields when a distinct target scope applies. `outboxWorkItemId` is parent correlation only and is excluded from command identity, uniqueness, and deduplication keys. +- The unique child identity for each evaluated command descriptor: the complete Command-Handoff Identity, including `targetGameInstanceId`, `targetRegionId`, and `targetRegionEpoch` together whenever a distinct target runtime scope applies, including same-namespace cross-region handoff. Include `targetPlayableStateNamespaceId` when the target scope is namespace-owned. Target `playableStateScope` remains separately persisted and exact-validated evidence and is excluded from command identity, uniqueness, and deduplication keys. `outboxWorkItemId` is parent correlation only and is excluded from command identity, uniqueness, and deduplication keys. - `createdAt` and `updatedAt`. - `workItemStatus` (per evaluated descriptor/command; see below, not a pre-DSL trigger or parent aggregate status). - The immutable evaluated command descriptor (one descriptor per emitted command, stored durably), including immutable `lane`, bounded `cost_class`, and `handoffRequirement` (`REQUIRED` or `OPTIONAL`) metadata. - `commandCount` (the immutable total number of committed descriptors for the parent `outboxWorkItemId`, for budgeting/inspection; it is not per-descriptor progress). - `cancelReason` (nullable; required when canceled). -`outboxWorkItemId` is the Automation-owned parent correlation identifier. At the current Game Session boundary, Automation produces `EnqueueAutomationCommandIfAbsentRequest.automationWorkItemId` with this same value, and Game Session consumes/reports it under the wire field name `automationWorkItemId`; these are boundary-specific names for one parent identifier, not separate work-item records. It is not the per-command discriminator and must not be used as command-level dedupe. +`outboxWorkItemId` is the Automation-owned parent correlation identifier. At the current Game Session boundary, Automation produces `EnqueueAutomationCommandIfAbsentRequest.automationWorkItemId` with this same value, and Game Session consumes/reports it under the wire field name `automationWorkItemId`; these are boundary-specific names for one parent identifier, not separate parent records or identities. In the current single-row model this identifier locates the pre-DSL trigger record; in the target model it locates the evaluated script work-item descriptor set. It is not the per-command discriminator and must not be used as command-level dedupe. Target-state per-command progress follows the [cross-service command boundary](./system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary): descriptor identity is the complete Command-Handoff Identity and is linked to the parent `outboxWorkItemId`. Each emitted command has independent durable progress, so a retry resumes only unresolved commands and cannot drop an unattempted command or replay a command already accepted or terminally rejected. A queue pointer may be deduplicated by parent `outboxWorkItemId` for index hygiene, but that does not deduplicate commands. The current live executor attempts each bounded emitted command, but the narrower handoff boundary above does not establish this target per-command identity or progress behavior end to end. @@ -143,7 +143,7 @@ Each emitted command is also represented by one durable child dispatch row under **Target-state handoff-requirement contract:** Evaluation commits the `handoffRequirement=REQUIRED|OPTIONAL` classification required by the accepted [durable per-dispatch handoff decision](./decisions/adr-0063-durable-per-dispatch-script-handoff.md) and persists it on both the evaluated descriptor and child dispatch before handoff. The value is bound by the immutable command digest but is not part of Command-Handoff Identity. Every emitted command must carry exactly one recognized value; missing, unknown, or contradictory descriptor/child evidence fails closed, and retry, readback, and recovery preserve the committed value rather than defaulting or reclassifying it. A valid zero-command evaluation creates no synthetic child. Parent convergence and optional-child retry follow that decision. -When a work item is handed to Game Session, the local wire boundary is: +When an evaluated script work item is handed to Game Session, the local wire boundary is: - `EnqueueAutomationCommandIfAbsent` carries the local handoff fields described in [Current Implementation Status](#current-implementation-status), and its response returns the live Game Session `commandId`/admission outcome. The target handoff identity and fenced acceptance rule are owned by the [cross-service scripting contracts](./system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary). @@ -193,9 +193,9 @@ For plugin-owned schedule-derived work, rebuilding a due candidate or firing cla Target-state rule: stable schedule rows carry the mutable current reconciled `(pluginActivationEpoch, lifecycleRevision)` pair for their current owner; due candidates, firing claims, candidate audits, and timer-derived work retain the immutable captured pair as execution-fence evidence across every mapping below. New evaluator or firing admission requires the exact current `(pluginActivationEpoch, lifecycleRevision)` under `ENABLED`; work may use only the immediately preceding `ENABLED` revision during same-version/same-epoch `DRAINING` when its winning admission CAS durably committed that revision before the durable Automation-owned `DRAINING` admission barrier was created. A non-executable or epoch-advancing transition supplies no predecessor exception. The current implementation does not yet persist and propagate this complete plugin fence across these surfaces; see [Current Implementation Status](#current-implementation-status) and the [Automation and Scheduler Runtime tracker](../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status). -The current `script_work_items` statuses span two target layers. `workItemStatus` on an evaluated descriptor is per descriptor/command; pre-DSL trigger status and any parent aggregate are separate scopes. Tooling must not collapse them into one command-outbox state machine: +The current `script_work_items` table is a pre-DSL trigger-record table, while its status vocabulary spans two target layers. `workItemStatus` on an evaluated script work item/descriptor is per descriptor/command; pre-DSL trigger status and any parent aggregate are separate scopes. Tooling must not collapse them into one command-outbox state machine: -Current legacy single-row marker: when the current executor completes a live non-`onLoad` zero-command evaluation on the `completed_no_commands` path, it stores that work item with `status=HANDED_OFF` as a terminal storage marker even though no command dispatch or Game Session handoff occurred. The authoritative outcome remains `finalStage=DSL_EVAL` / `finalOutcome=completed_no_commands`, with no dispatch identity; `HANDED_OFF` in this legacy single-row context is not evidence of a command handoff or `handoff_accepted`. This is implementation drift from the target two-layer status model and must not be treated as the target descriptor meaning below. +Current legacy single-row marker: when the current executor completes a live non-`onLoad` zero-command evaluation on the `completed_no_commands` path, it stores that pre-DSL trigger record with `status=HANDED_OFF` as a terminal storage marker even though no command dispatch or Game Session handoff occurred. The authoritative outcome remains `finalStage=DSL_EVAL` / `finalOutcome=completed_no_commands`, with no dispatch identity; `HANDED_OFF` in this legacy single-row context is not evidence of a command handoff or `handoff_accepted`. This is implementation drift from the target two-layer status model and must not be treated as the target descriptor meaning below. | Current or target status | Canonical target meaning | Drain and rebuild treatment | | --- | --- | --- | @@ -221,15 +221,15 @@ Recovery revalidates the exact admitted `(scriptPatchVersion, scriptPinEpoch)` e Replay preserves and revalidates the captured plugin lifecycle tuple at the stage boundary: `ENABLED` requires the exact current `lifecycleRevision`, while same-version/same-epoch `DRAINING` may resume only work whose winning admission CAS durably committed the immediately preceding `ENABLED` revision before the durable Automation-owned `DRAINING` admission barrier was created. It never refreshes a dead letter to an arbitrary lower revision, and a displaced item remains dead-lettered after a non-executable or epoch-advancing transition. -Recovery selection, eligibility, stage mapping, idempotency, and the atomic recovery claim/attempt owner are defined by [Control Plane Operations](./system-architecture-scripting-control-plane-operations.md#replaydeadletteredworkitems); that owner persists and revalidates the expected exact fence/binding and `controlPlaneRequestId`, including same-attempt claim reclaim. This runtime section records only local consequences: command-capable gameplay/runtime evaluation-stage recovery may invoke the DSL evaluator again only when the persisted failure class is retryable under [Failure Modes and Error Handling](#failure-modes-and-error-handling), using the original work-item and `scriptEventId`, original persisted payload, frozen manifest/graph evidence, exact admitted immutable graph and artifact references, and recorded digests, while remaining outside the normal admission path. Before its winning descriptor commit it allocates no dispatch or command-child identity; if commands are emitted, that first atomic evaluated-descriptor/outbox commit allocates and persists the `automationDispatchId` and ordinals, while retries after a winning commit reuse them. A valid zero-command evaluation creates no dispatch identity. Non-retryable classes remain terminal/ineligible, and recovery must never refresh to the latest/default payload, manifest, graph, or artifact. Post-evaluation recovery reads the immutable evaluated output and complete child-dispatch ledger keyed by the full Command-Handoff Identity, preserving original child identities, ordinals, downstream acknowledgements/outcomes, and per-child recovery state, and never invokes the DSL. A parent recovery aggregate marked `DEAD_LETTERED` because of a permanent required-child failure resumes this retained ledger as `resumed_dispatch`; a required-child cancellation does not mark that aggregate `DEAD_LETTERED`, so the canceled parent/children are not replay-eligible. Recovery never replaces or clears the `EVALUATED_COMMITTED` descriptor marker. Successful recovery clears only the separate parent recovery aggregate; purge may remove eligible descriptor evidence and writes `descriptorEvidencePurgedAt`, but retains the marker. `DRAINING` remains valid for recovery only when the work has ADR 0119's durable pre-`DRAINING` admission/fence evidence and exact plugin fences and policy evidence pass; a lifecycle state that invalidates admitted work fails closed. Evaluated-output and command digests are integrity evidence only, not substitutes for retained output or identity; `outboxWorkItemId`, the parent Trigger Identity, and `scriptEventId` remain correlation-only. Neither stage reopens the original audit row. +Recovery selection, eligibility, stage mapping, idempotency, and the atomic recovery claim/attempt owner are defined by [Control Plane Operations](./system-architecture-scripting-control-plane-operations.md#replaydeadletteredworkitems); that owner persists and revalidates the expected exact fence/binding and `controlPlaneRequestId`, including same-attempt claim reclaim. This runtime section records only local consequences: command-capable gameplay/runtime evaluation-stage recovery may invoke the DSL evaluator again only when the persisted failure class is retryable under [Failure Modes and Error Handling](#failure-modes-and-error-handling), using the original pre-DSL trigger record and `scriptEventId`, original persisted payload, frozen manifest/graph evidence, exact admitted immutable graph and artifact references, and recorded digests, while remaining outside the normal admission path. Before its winning descriptor commit it allocates no dispatch or command-child identity; if commands are emitted, that first atomic evaluated-descriptor/outbox commit allocates and persists the `automationDispatchId` and ordinals, while retries after a winning commit reuse them. A valid zero-command evaluation creates no dispatch identity. Non-retryable classes remain terminal/ineligible, and recovery must never refresh to the latest/default payload, manifest, graph, or artifact. Post-evaluation recovery reads the immutable evaluated output and complete child-dispatch ledger keyed by the full Command-Handoff Identity, preserving original child identities, ordinals, downstream acknowledgements/outcomes, and per-child recovery state, and never invokes the DSL. A parent recovery aggregate marked `DEAD_LETTERED` because of a permanent required-child failure resumes this retained ledger as `resumed_dispatch`; a required-child cancellation does not mark that aggregate `DEAD_LETTERED`, so the canceled parent/children are not replay-eligible. Recovery never replaces or clears the `EVALUATED_COMMITTED` descriptor marker. Successful recovery clears only the separate parent recovery aggregate; purge may remove eligible descriptor evidence and writes `descriptorEvidencePurgedAt`, but retains the marker. `DRAINING` remains valid for recovery only when the work has ADR 0119's durable pre-`DRAINING` admission/fence evidence and exact plugin fences and policy evidence pass; a lifecycle state that invalidates admitted work fails closed. Evaluated-output and command digests are integrity evidence only, not substitutes for retained output or identity; `outboxWorkItemId`, the parent Trigger Identity, and `scriptEventId` remain correlation-only. Neither stage reopens the original audit row. **Target-state only:** The control-plane recovery mutation accepts bounded explicit `workItemIds[]` only; descriptor references and filter selectors remain deferred until preview plus stable per-row proof. A `DEAD_LETTERED` evaluation-stage trigger with no committed descriptor may retry only when its persisted failure class is retryable under [Failure Modes and Error Handling](#failure-modes-and-error-handling), and its original work-item, `scriptEventId`, frozen manifest/graph evidence, and exact admitted immutable graph are present; a missing or contradictory stage record remains ineligible, and non-retryable classes remain terminal/ineligible. A parent recovery aggregate marked `DEAD_LETTERED` after a permanent required-child failure retains its `EVALUATED_COMMITTED` marker and may resume only the stored output/child ledger. The current mutation selects parent `workItemIds` and requeues eligible `script_work_items` rows, so it does not yet prove independent descriptor recovery. Command-capable gameplay/runtime evaluation-stage recovery may invoke the DSL evaluator again only for that retryable failure class, under the original identity and evidence, remains outside the normal admission path, allocates no dispatch or command-child identity before a winning descriptor commit, and must converge on the original work item. If commands are emitted, that first atomic descriptor commit allocates and persists the `automationDispatchId` and canonical ordinals; retries after a winning commit reuse them. A valid zero-command evaluation creates no dispatch identity. Post-evaluation recovery must resume only the stored output/child ledger and never invoke the DSL. Recovery must never move a dead-lettered item into a fresh admission path, regenerate output after the evaluation boundary, or append new history to the original audit row. Before recovery, the service must revalidate the current exact `(scriptPatchVersion, scriptPinEpoch)` execution identity, the paired `scriptPinControlPlaneRequestId` owner evidence, runtime `regionId`/`regionEpoch`, and admitted routing bundle (`playableStateScope`, world/realm identity, and pointer version); for plugin work, it must also revalidate the immutable `(pluginId, pluginVersionId, bindingId)` tuple, the captured `(pluginActivationEpoch, lifecycleRevision)` pair against the current Automation-owned lifecycle evidence, and fresh applicable activation/lifecycle, publication, component-policy, capability-grant, and signer evidence against the same scoped ``. `DRAINING` blocks new trigger admission; recovery requires ADR 0119's canonical durable pre-`DRAINING` admission-CAS/fence evidence and otherwise only remains eligible for a lifecycle state that does not invalidate admitted work. A captured-epoch mismatch returns `plugin_activation_epoch_mismatch`. A `DISABLED`, revoked, or policy-driven invalidation of admitted work returns `plugin_disabled`. If any authoritative fence or plugin-policy read is temporarily unavailable, return the applicable established bounded reason (`authority_unavailable`, `component_policy_unavailable`, or `signer_policy_unavailable`), leave the already-`DEAD_LETTERED` item unchanged with no recovery claim/attempt record, and persist the request-level rejected result so an exact retry of the same request replays it; only a later request with a new `controlPlaneRequestId` may retry after the evidence recovers. A proven fence, binding, publication, policy, or revocation mismatch remains terminal/ineligible, leaves the item `DEAD_LETTERED`, and produces no recovery claim/attempt record. -Target-state recovery is idempotent by stable `controlPlaneRequestId` for each original work item and Automation-owned `failureGeneration`. The first atomic parent recovery-aggregate transition into `DEAD_LETTERED` initializes generation `1`; a later re-entry advances it exactly once in that same transition, including a permanent required-child failure after the retained `EVALUATED_COMMITTED` marker, while an exact retry/no-op or failed recovery attempt that leaves the parent in the same generation does not advance it. Retrying the same operator request returns its stored per-work-item result and generation unchanged and creates no second recovery attempt or audit history. A new request resolves the current generation atomically: only same-generation successful-recovery evidence returns `outcome=already_recovered`; an older generation's success remains immutable and neither satisfies nor blocks recovery of a newer current generation. Claims are unique per current `(tenantId, outboxWorkItemId, failureGeneration)`, stale owners/generations fail CAS, and failure generation is not reused as a Trigger Identity or Command-Handoff Identity. Missing or contradictory stage evidence remains dead-lettered. +Target-state recovery is idempotent by stable `controlPlaneRequestId` for each original parent record and Automation-owned `failureGeneration`. The first atomic parent recovery-aggregate transition into `DEAD_LETTERED` initializes generation `1`; a later re-entry advances it exactly once in that same transition, including a permanent required-child failure after the retained `EVALUATED_COMMITTED` marker, while an exact retry/no-op or failed recovery attempt that leaves the parent in the same generation does not advance it. Retrying the same operator request returns its stored per-parent result and generation unchanged and creates no second recovery attempt or audit history. A new request resolves the current generation atomically: only same-generation successful-recovery evidence returns `outcome=already_recovered`; an older generation's success remains immutable and neither satisfies nor blocks recovery of a newer current generation. Claims are unique per current `(tenantId, outboxWorkItemId, failureGeneration)`, stale owners/generations fail CAS, and failure generation is not reused as a Trigger Identity or Command-Handoff Identity. Missing or contradictory stage evidence remains dead-lettered. ## `scriptEventId` Lifecycle and Deduplication -Trigger Identity, endpoint-specific `scriptEventId` ownership, audit uniqueness, and command-level retry identity are defined in the [normative contract tables](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) and [cross-service scripting contracts](./system-architecture-scripting-contracts.md#4-scripteventid-identity-and-at-most-once-dedupe). Runtime persistence carries the applicable identity on the durable work item and preserves it across queue projection, claims, and handoff attempts. +Trigger Identity, endpoint-specific `scriptEventId` ownership, audit uniqueness, and command-level retry identity are defined in the [normative contract tables](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) and [cross-service scripting contracts](./system-architecture-scripting-contracts.md#4-scripteventid-identity-and-at-most-once-dedupe). In the current implementation, one `script_work_items` row carries the applicable identity from the pre-DSL trigger through evaluation and handoff processing; separate evaluated-work-item records and descriptor replay remain target-state only. ## Runtime Deployment & Versioning @@ -255,19 +255,19 @@ Scripts do not execute inside the tick system. The Automation & Scripting Servic - Script-generated commands may fail due to lock contention or target remote regions, and Game Session handles those cases via its normal tick rescheduling and cross-region routing logic. - The Automation & Scripting Service only determines which commands to inject. It never mutates entity or world data directly. -For a non-exclusive multi-handler event, Automation assigns the resolved handlers a durable `handlerSequence` under [ADR 0118](./decisions/adr-0118-preselected-exclusive-handlers-and-durable-fanout-ordering.md). The event resolution record or equivalent durable manifest identifies the complete ordered set. That sequence and each handler's local command ordinal are preserved on work items, generated-command persistence, handoff records, Game Session command admission, retries, and final application. Consumers must not infer semantic order from enqueue time, database identity, Redis list position, worker claim order, scheduling priority, or arrival time. +For a non-exclusive multi-handler event, Automation assigns the resolved handlers a durable `handlerSequence` under [ADR 0118](./decisions/adr-0118-preselected-exclusive-handlers-and-durable-fanout-ordering.md). The event resolution record or equivalent durable manifest identifies the complete ordered set. That sequence and each handler's local command ordinal are preserved on evaluated script work items, generated-command persistence, handoff records, Game Session command admission, retries, and final application. Consumers must not infer semantic order from enqueue time, database identity, Redis list position, worker claim order, scheduling priority, or arrival time. This is target-state behavior. The current live Game Session handoff does not yet carry or prove the durable handler sequence and complete resolution evidence through handoff, Game Session admission, retry, and final application; it also lacks `commandOrdinal` and the complete Trigger/Command-Handoff Identity. Existing local ordinals and parent correlation are only current handoff bookkeeping and diagnostics, not semantic ordering authority or a fallback when target metadata is missing. A handler's terminal failure or empty output closes its sequence position and allows later non-exclusive handler commands to proceed without canceling them. A delayed lower sequence is not equivalent to a terminal failure; downstream application must retain or reconstruct enough resolution state to avoid applying a higher sequence prematurely. Missing or contradictory sequence/completeness metadata fails explicitly rather than degrading to arrival order. -Automation first resolves and seals the complete applicable core/plugin binding set, rejecting missing or contradictory completeness evidence, multiple exclusive claims, or unauthorized exclusive claims. It then selects an authorized exclusive binding before work-item fan-out; that binding is the only handler materialized for the event scope. If it fails or is denied, no sibling fallback is created. +Automation first resolves and seals the complete applicable core/plugin binding set, rejecting missing or contradictory completeness evidence, multiple exclusive claims, or unauthorized exclusive claims. It then selects an authorized exclusive binding before pre-DSL trigger-record fan-out; that binding is the only handler materialized for the event scope. If it fails or is denied, no sibling fallback is created. ## Output Budgeting and Command Fan-Out Admission and sandboxing must bound not only how often a handler runs, but also how much work a single admitted run can emit: -- Each DSL run must enforce explicit output budgets before a work item is persisted, including `maxCommandsPerRun`, `maxCommandsPerEntityPerTrigger`, and `maxSerializedWorkItemBytes`, plus any bounded payload ceilings needed for known large command families. +- Each DSL run must enforce explicit output budgets before an evaluated script work item is persisted, including `maxCommandsPerRun`, `maxCommandsPerEntityPerTrigger`, and `maxSerializedWorkItemBytes`, plus any bounded payload ceilings needed for known large command families. - Exceeding an output budget must fail deterministically with a non-success stage-aware outcome. A generated-output meter or cap violation discovered while evaluating a resolved handler is a handler-scoped `DSL_EVAL` outcome; an independent serialization or durable persistence transaction failure is a `WORK_ITEM_PERSIST` outcome. In either case, `finalReason` must use bounded canonical codes such as `command_count_exceeded`, `per_entity_command_limit_exceeded`, or `work_item_size_exceeded`. - A non-exclusive handler failure closes only that handler's durable sequence position. It does not cancel sibling work or change their Trigger Identities and outcomes. - Output budgets apply equally to core scripts and plugins. @@ -291,25 +291,25 @@ Every compiled script artifact must carry enough normalized output-cost metadata Runtime metering is incremental and happens before constructing each generated command or data-dependent collection. The evaluator charges the artifact-pinned conservative prospective serialized-byte bound together with cumulative command count, per-entity count, payload/collection bounds, and every data-dependent cap declared by the pinned metadata before construction or allocation. After bounded descriptors are staged, their exact serialized size is checked against the pinned ceiling immediately before atomic persistence. A run that would exceed any cap stops with the stage-correct `DSL_EVAL` non-success outcome and bounded reason; an independent serializer or persistence transaction failure remains `WORK_ITEM_PERSIST`. It must not construct an unbounded intermediate result and discover a cap violation only at handoff. -Generated output is atomic per resolved handler: either every bounded descriptor for that handler is durably persisted with its parent evidence, or none of that handler's generated output is persisted or handed off. A failed output-meter check, serialization check, or persistence transaction discards all staged output for that handler; it must not leave a partial command set that a retry could interpret as successful work. Event-scope ingress may reject a missing or conflicting artifact-cost digest with its ingress `OUTPUT_BUDGET_EXCEEDED` outcome, while a handler that exceeds a runtime cap records the canonical handler-scoped `DSL_EVAL` outcome and reason from [Table 2](./system-architecture-scripting-normative-contract-tables.md#table-2-script_event_audit-stages-and-outcomes). +Generated output is atomic per resolved handler: either every bounded descriptor for that handler is durably persisted with its parent evidence, or none of that handler's generated output is persisted or handed off. A failed output-meter check, serialized-size ceiling check, or persistence transaction discards all staged output for that handler; an output-limit failure therefore prevents evaluated descriptor/work-item/child-handoff persistence, while the owning pre-DSL trigger-record/work-item row still commits the terminal `DSL_EVAL` audit outcome. Target state also preserves any admission/execution-start charge markers already reached in the separate durable handler charge record, as defined by [Scripting Quotas & Operations](./system-architecture-scripting-quotas-and-operations.md#budget-accounting-rules); that record and its linkage are not claimed as current implementation. It must not leave a partial command set that a retry could interpret as successful work. Event-scope ingress may reject a missing or conflicting artifact-cost digest with its ingress `OUTPUT_BUDGET_EXCEEDED` outcome, while a handler that exceeds a runtime cap records the canonical handler-scoped `DSL_EVAL` outcome and reason from [Table 2](./system-architecture-scripting-normative-contract-tables.md#table-2-script_event_audit-stages-and-outcomes). ## Budget Charge Points The canonical charge lifecycle is owned by [Scripting Quotas & Operations](./system-architecture-scripting-quotas-and-operations.md#budget-accounting-rules). Runtime execution consumes its result and must not introduce another charge point: -- The durable handler charge record is keyed by the full applicable Trigger Identity, including each resolved `onLoad` handler. Its exactly-once admission and execution-start markers are reused by duplicate and recovery attempts. -- A queued handler holds no sandbox capacity. Runtime acquires a separately fenced, reclaimable capacity lease only when execution is about to start, then in one Automation-owned durable executor-acceptance transaction revalidates the current fence, durably accepts/claims the run for the executor, persists the exactly-once execution-start marker, and transitions the work item to `EXECUTING`; DSL evaluation begins only after that commit. If the executor cannot accept the run, the transition does not commit, the lease is released or reclaimed, and no execution charge is recorded. A crash after commit recovers from the durable executor claim and may reacquire a lease but never creates a second marker. -- A failed run does not refund an already committed admission charge or execution-start charge. Lease reclamation is capacity recovery, not a quota refund, and cannot create a second charge record or execution-start marker. +- **Target-state only:** For each resolved handler, including each `onLoad` handler, Automation creates or reuses one separate durable handler charge record keyed by the full applicable Trigger Identity. That record is the sole charge authority and persists the exactly-once admission and execution-start markers; the pre-DSL trigger-record/work-item row is durably linked to it and is not a second charge point. Duplicate and recovery attempts reuse the same charge record and markers. +- **Target-state only:** A queued handler holds no sandbox capacity. Runtime acquires a separately fenced, reclaimable capacity lease only when execution is about to start, then in one Automation-owned durable executor-acceptance transaction revalidates the current fence, durably accepts/claims the run for the executor, persists the exactly-once execution-start marker on the handler charge record, and transitions the pre-DSL trigger record to `EXECUTING`; DSL evaluation begins only after that commit. If the executor cannot accept the run, the transition does not commit, the lease is released or reclaimed, and no execution charge is recorded. A crash after commit recovers from the durable executor claim and may reacquire a lease but never creates a second marker. +- A failed run does not refund an already committed admission charge or execution-start charge. Lease reclamation is capacity recovery, not a quota refund, and cannot create a second charge row or execution-start marker. - Runtime persists the resolved `quotaClass` on durable work so execution follows the admission decision. `PUBLISH_READINESS` remains isolated from ordinary live quota and capacity; its readiness lease and outcome are local runtime consequences, not a new live charge path. - Target-state scheduler reservations are separate from the durable admission/execution charges and fenced occupancy lease described here; the current runtime does not implement that reservation. ## Ordering Between Player and Script Commands -Game Session owns the combined per-entity tick queue and its enqueue/order invariants as defined in the [cross-service scripting contracts](./system-architecture-scripting-contracts.md#1-tick-queue-ownership-tick). At this runtime boundary, the current handoff preserves `scriptId` and optional `dueTickId` when present. `commandOrdinal`, `triggerMode`, `scheduleDefinitionId`, and scheduler/ordinal propagation are target-only and are not current ordering guarantees. `scriptEventId` remains on the Automation-owned durable work item and `script_event_audit`; it is omitted from the current Game Session handoff. Target command identity and complete Trigger Identity propagation remain subject to the widened handoff contract. +Game Session owns the combined per-entity tick queue and its enqueue/order invariants as defined in the [cross-service scripting contracts](./system-architecture-scripting-contracts.md#1-tick-queue-ownership-tick). At this runtime boundary, the current handoff preserves `scriptId` and optional `dueTickId` when present. `commandOrdinal`, `triggerMode`, `scheduleDefinitionId`, and scheduler/ordinal propagation are target-only and are not current ordering guarantees. `scriptEventId` remains on the Automation-owned durable pre-DSL trigger record and resulting evaluated script work item/audit; it is omitted from the current Game Session handoff. Target command identity and complete Trigger Identity propagation remain subject to the widened handoff contract. ## Redis Key Summary for Scripting -The current Redis keys used by the Automation & Scripting Service, together with reserved target-only keys, are: +The current implementation has no scheduler/timer Coordination Redis projections; its current Redis projection in this section is the queue below. Durable schedule/timer state and runtime progress are PostgreSQL-backed. Separate live quota/budget/test-capacity/readiness-capacity families (`automation:quota:*`, `automation:tenant-budget:*`, `automation:test:quota:*`, `automation:test:capacity:*`, and `automation:readiness:capacity:*`) are also used through Cache/Rate-Limit Redis; see [Scripting Quotas & Operations](./system-architecture-scripting-quotas-and-operations.md#implementation-status). The `automation:timer:{tenantRegionTag}` and `script-scheduler:{tenantRegionTag}:lastTickId` entries are target-state projections only: those Redis families are unimplemented in the current runtime, no supported current manual-write or reset operation exists for them, and raw coordination-prefix mutation is prohibited. | Key pattern | Owner / service | Purpose | Hash tag / shard scope | TTL / retention expectations | | --- | --- | --- | --- | --- | @@ -317,7 +317,9 @@ The current Redis keys used by the Automation & Scripting Service, together with | `automation:timer:{tenantRegionTag}` | Automation & Scripting scheduler (target-only, once implemented) | Reserved target-only region-scoped index of script timers and intervals for the full `` scope represented by the opaque tag. No current key or reset operation is defined. | Hash-tagged on the shared `{tenantRegionTag}` derived by key helpers; the tag is not a competing identity family. | Reset-tolerant derived index once implemented; durable schedules remain authoritative. | | Scheduler leadership state | Automation & Scripting scheduler (live heartbeat-driven scheduling; target-only Redis projection) | Current live scheduling is driven by Game Session's `ObserveRuntimeTickProgress` call after each committed tick and durable PostgreSQL schedule rows; no independent Redis leadership key or checkpoint is implemented. The target scheduler checkpoint is explicitly reserved as `script-scheduler:{tenantRegionTag}:lastTickId`; it carries the current `regionEpoch` and `latestTickId` discovery hint, while the per-consumer `tick-events-offset:{tenantRegionTag}:` record remains the sole stream-offset owner. A future target projection may align scheduler ownership to the canonical runtime and region-scoped coordination model; do not assume a separate first-class `script-leader:*` prefix unless a later Redis design update explicitly introduces it. | The reserved checkpoint is target-only and has no current Redis slot/key or reset operation. Any future projection must follow the same slotting and reset rules as the documented scheduler coordination families. | No current Redis retention. A future projection is short-lived and reset-tolerant; durable schedules and firing state remain authoritative. | -`{tenantRegionTag}` is owned by the shared Redis key builders under [Redis Architecture](./system-architecture-redis.md#key-naming-and-shard-discipline) and is intentionally limited to full `` locality. `playableStateScope` remains a first-class field in durable Trigger Identity, command/effect identity, and handoff diagnostics; it must not be inferred from, or added to, this tag without an owning Redis design and key-builder change. +`{tenantRegionTag}` is owned by the shared Redis key builders under [Redis Architecture](./system-architecture-redis.md#key-naming-and-shard-discipline) and is intentionally limited to full `` locality. `playableStateNamespaceId` is the playable-state uniqueness component in durable Trigger Identity and Command-Handoff Identity. `playableStateScope` remains separately persisted and exact-validated as policy/routing/authorization/migration-fence evidence for durable trigger, descriptor, and handoff diagnostics; it is excluded from those uniqueness keys and must not be inferred from, or added to, this tag without an owning Redis design and key-builder change. Where current repository or schema uniqueness includes `playableStateScope`, that is current implementation drift and not target identity authority. + +Scheduler leadership remains an explicit, bounded runtime concern rather than state stored in `lastTickId`; the target design does not introduce a first-class `script-leader:*` Redis prefix. Any future leadership lease or projection must be separately specified and registered under the owning coordination/reset contracts. ## Failure Modes and Error Handling @@ -331,8 +333,8 @@ Routine core-script component safety classification is fixed at validation and r Target-state retry behavior (see [Current Implementation Status](#current-implementation-status)): -- Logical failures are treated as final for a trigger. Before `EVALUATED_COMMITTED`, infrastructure retry, including admitted timer evaluation, may re-run evaluation only under the same full Trigger Identity and must converge on the same work-item and frozen inputs; it allocates no dispatch or command-child identity before the first durable descriptor commit. If commands are emitted, that winning commit allocates/persists the dispatch ID and canonical ordinals; retries after the commit reuse them. It must never create a duplicate logical command. After `EVALUATED_COMMITTED`, recovery replays the durable descriptors and never re-enters the DSL. The audit `finalStage` remains the last stage actually reached rather than being advanced by an attempted retry. -- **Pre-commit replay evidence:** For event and timer evaluation retries before `EVALUATED_COMMITTED`, the executor reloads the original durable trigger payload, frozen dependency/manifest snapshot, immutable graph and artifact references with recorded digests. For plugin-backed work it also compares the exact plugin provenance and captured `(pluginActivationEpoch, lifecycleRevision)` pair; for the same-version/same-epoch `DRAINING` predecessor exception, the durable winning pre-`DRAINING` admission/fence CAS evidence is part of the immutable comparison and must be present. Missing, changed, capture-only, or unreadable evidence fails closed before DSL evaluation; the retry preserves the full Trigger Identity and original work-item identity, allocates no command-child identity, and can only reuse dispatch/ordinal identities after a winning descriptor commit with the same lifecycle evidence. +- Logical failures are treated as final for a trigger. Before `EVALUATED_COMMITTED`, infrastructure retry, including admitted timer evaluation, may re-run evaluation only under the same full Trigger Identity and must converge on the same pre-DSL trigger record and frozen inputs; it allocates no dispatch or command-child identity before the first durable descriptor commit. If commands are emitted, that winning commit allocates/persists the dispatch ID and canonical ordinals; retries after the commit reuse them. It must never create a duplicate logical command. After `EVALUATED_COMMITTED`, recovery replays the durable descriptors and never re-enters the DSL. The audit `finalStage` remains the last stage actually reached rather than being advanced by an attempted retry. +- **Pre-commit replay evidence:** For event and timer evaluation retries before `EVALUATED_COMMITTED`, the executor reloads the original durable trigger payload, frozen dependency/manifest snapshot, immutable graph and artifact references with recorded digests. For plugin-backed work it also compares the exact plugin provenance and captured `(pluginActivationEpoch, lifecycleRevision)` pair; for the same-version/same-epoch `DRAINING` predecessor exception, the durable winning pre-`DRAINING` admission/fence CAS evidence is part of the immutable comparison and must be present. Missing, changed, capture-only, or unreadable evidence fails closed before DSL evaluation; the retry preserves the full Trigger Identity and original pre-DSL trigger-record identity, allocates no command-child identity, and can only reuse dispatch/ordinal identities after a winning descriptor commit with the same lifecycle evidence. - Any work referencing a revocable component, including embedded/core-script and plugin-backed work, carries the component-revocation security-policy fence through evaluation, persistence, dispatch, staged/final effects, retry, replay, and recovery and is checked immediately before gameplay effects. Missing, stale, unavailable, or mismatched evidence fails closed with the established bounded component/authority disposition. Plugin-backed work additionally carries and revalidates the independent `(pluginActivationEpoch, lifecycleRevision)` fence pair; neither lifecycle fence substitutes for the other or for component-revocation evidence. The captured plugin lifecycle pair and exact recovery fences are revalidated immediately before evaluation, before descriptor/outbox persistence, before each post-evaluation dispatch, and at every applicable boundary. Applicable current signer, component, capability, publication, and lifecycle policy evidence is revalidated at evaluation, each dispatch, final effect, and activation/resume/recovery as owned by ADR 0119, using the canonical durable pre-`DRAINING` admission-CAS evidence for the narrowly retained predecessor exception. Proven lifecycle, publication, component/capability, signer, tuple, or scope mismatches remain terminal/ineligible with their applicable bounded reason. - For event ingress, pre-handler rollback pause is an ingress-audit backpressure outcome only. Timer candidates use the Table 3 candidate-audit rule instead. Post-resolution handler backpressure such as `skipped_reloading` and `rollback_paused` is not treated as final for low-rate external events. - Infrastructure errors may be retried by lower layers following platform-wide retry policies and idempotency contracts. @@ -345,7 +347,7 @@ Rollback of a script patch must not allow previously queued work from the displa ## Timer Failure Semantics -Timer admission, due-point identity, catch-up, reload, and failure outcomes follow the [normative timer semantics](./system-architecture-scripting-normative-contract-tables.md#table-3-timer-semantics-matrix). In the target state, before `EVALUATED_COMMITTED`, an admitted timer evaluation may retry only under the same full Trigger Identity, allocates no dispatch or command-child identity before the first durable descriptor commit, and must converge on the same work-item and frozen inputs. If commands are emitted, that atomic commit allocates/persists the `automationDispatchId` and canonical ordinals; retries after the commit reuse them. After that commit boundary, recovery replays durable descriptors and never re-enters the DSL; independently idempotent downstream operations may still retry. Recurring/advisory firings remain bounded scheduling signals rather than guaranteed cadence ledgers, while correctness-bearing one-shot timers converge to one execution or an explicit terminal outcome. +Timer admission, due-point identity, catch-up, reload, and failure outcomes follow the [normative timer semantics](./system-architecture-scripting-normative-contract-tables.md#table-3-timer-semantics-matrix). In the target state, before `EVALUATED_COMMITTED`, an admitted timer evaluation may retry only under the same full Trigger Identity, allocates no dispatch or command-child identity before the first durable descriptor commit, and must converge on the same pre-DSL trigger record and frozen inputs. If commands are emitted, that atomic commit allocates/persists the `automationDispatchId` and canonical ordinals; retries after the commit reuse them. After that commit boundary, recovery replays durable descriptors and never re-enters the DSL; independently idempotent downstream operations may still retry. Recurring/advisory firings remain bounded scheduling signals rather than guaranteed cadence ledgers, while correctness-bearing one-shot timers converge to one execution or an explicit terminal outcome. ## `onLoad` Semantics and Failure Handling diff --git a/design/architecture/system-architecture-scripting-scheduler-and-timers.md b/design/architecture/system-architecture-scripting-scheduler-and-timers.md index c37a66cd77..ac2205ce3a 100644 --- a/design/architecture/system-architecture-scripting-scheduler-and-timers.md +++ b/design/architecture/system-architecture-scripting-scheduler-and-timers.md @@ -1,6 +1,6 @@ # FireMUD System Architecture: Scripting Scheduler and Timer Lifecycle -This document defines the runtime scheduler, timer, and reload lifecycle for scripting and automation. It complements [Scripting DSL Reference & Event Lifecycle](./system-architecture-scripting-dsl-reference-and-lifecycle.md), which remains the canonical owner for DSL semantics, trigger identity, event fan-out, and determinism rules. +This document defines the runtime scheduler, timer, and reload lifecycle for scripting and automation. It complements [Scripting DSL Reference & Event Lifecycle](./system-architecture-scripting-dsl-reference-and-lifecycle.md), which remains the canonical owner for DSL semantics, trigger identity, event fan-out, and determinism rules. Documentation validation and proof selection follow the shared [Validation and Runtime Proof](../developer-workflows/validation-and-runtime-proof.md) workflow. Schedule transition semantics are owned here under [ADR 0110](./decisions/adr-0110-explicit-opt-in-schedule-continuity-across-script-transitions.md). The exact Game Session pin/epoch fence and no-routine-gameplay-pause rollback boundary remain owned by [Scripting & Automation: Rollout and Rollback](./system-architecture-scripting-rollout-and-rollback.md) and [ADR 0106](./decisions/adr-0106-epoch-fenced-script-rollback-without-routine-gameplay-pause.md). Clocks and recovery remain linked to existing [ADR 0091](./decisions/adr-0091-class-specific-script-timer-clocks-and-recovery.md), not duplicated here. @@ -16,8 +16,13 @@ The current implementation provides the following substrate: - Wall-clock timers persist `nextDueAt`; in the live schema/entity, `next_due_at`/`nextDueAt` is the current equivalent of target canonical `dueAt`, while `nextRunAt` is only a derived projection, not the canonical persisted due point. Tick-aligned schedules remain `PENDING_RUNTIME_PROGRESS` until Game Session reports `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)` through `ObserveRuntimeTickProgress`; Automation then stores `runtimeRegionId`, `runtimeRegionEpoch`, `lastObservedTickId`, `lastRuntimeProgressObservedAt`, and the next future `nextDueTickId`. - Game Session advances durable `lastCommittedTickId` on the runtime-ownership row that also carries `regionId`, `regionEpoch`, and `executorFence`, exposes that state through runtime ownership status, and publishes it after successful tick cycles. True region partitioning remains target-state; the live ownership row currently carries a transitional non-empty `regionId` scope marker, but consumers must not derive or reconstruct that value from `gameInstanceId`. - Runtime observations stamp the fenced region scope onto wall-clock timers as well as tick schedules. Due tick and wall-clock candidates emit deterministic timer-derived `ScriptWorkItem` rows through the normal durable work-item, audit, and `automation:queue:*` projection path, then advance or clear the consumed due point. -- A newer observation that proves the runtime scope changed fences the stale due point instead of reminting it under the new epoch. The service records `runtime_scope_changed` against the old Trigger Identity and increments `automation_script_timer_runtime_fence_dropped_total`. -- Due candidates are selected in round-robin passes across complete stable schedule-instance identities and capped by `script.scheduler.max-catch-up-firings-per-observation`; this current per-observation behavior does not yet prove the accepted one-per-schedule-instance durable resume-window cap across repeated observations. `ObserveRuntimeTickProgress` reports updated rows, fired work items, and truncated candidates; timer-fired, catch-up-truncated, and runtime-fence metrics expose aggregate outcomes. +- Current wall-clock timer work serializes the absolute `dueAt` into `payloadJson`, and the evaluator exposes primitive payload fields to template variables and command conditions/arguments. Consequently `{{payload.dueAt}}` can affect emitted gameplay commands. This is implementation drift from the wall-clock scheduler-only contract above: `dueAt` must remain internal durable identity/seed/fence/audit metadata, while DSL inputs expose only canonical tick/game-time context. The existing wall-clock test assertion for `dueAt` in the work-item payload is not proof of the target boundary; convergence requires metadata/input separation and focused proof that wall-clock values cannot affect DSL output. +- Current re-observation also resets millisecond `nextDueAt` unconditionally during schedule reconciliation, even for an existing row. `validatePinnedPatch` invokes runtime observation on every gameplay ingress, so a fired one-shot timer whose due point was cleared can be reseeded to its original `pinObservedAt + cadence`; the duplicate-work branch then returns without clearing or advancing that overdue point. This can rediscover the same timer indefinitely or re-fire it after terminal cleanup. It is drift from the preserve/derive-only-when-absent rule below; convergence requires preserving consumed due state across ordinary observation and focused re-observation, duplicate-work, and one-shot proof. +- A newer observation that proves the runtime region/epoch, active-instance binding, or current legacy `playableStateScope` changed fences the stale due point instead of reminting it under the new epoch. The live service currently writes a handler-shaped `ScriptEventAudit` with `finalStage=ADMISSION`, `finalOutcome=canceled`, and `finalReason=runtime_scope_changed`, then increments `automation_script_timer_runtime_fence_dropped_total`, even though no handler was admitted. That is implementation drift from the target candidate-audit boundary: the old `scheduleCandidateId` and captured due/fence evidence must receive that terminal candidate outcome without creating a handler Trigger Identity, firing claim, or `scriptEventId`. Current implementation also does not yet carry authoritative `playableStateNamespaceId` or distinguish stale presented scope evidence from an authority-proven scope transition; the target contract below permits same-namespace reuse only when authoritative scope is unchanged and otherwise starts a new playable-state lifecycle and namespace. +- Current timer candidate identity and the durable work-item uniqueness projection omit `targetScopeType`/`targetScopeId`; non-entity bindings therefore collapse to the same empty `entityId`. Distinct GLOBAL, REGION, or other bindings sharing a schedule and due point can produce one work item while the other candidate is treated as a duplicate. Target identity requires the complete target selector in the scheduler claim and candidate identity; convergence requires carrying it through work/audit uniqueness and focused cross-binding negative proof. +- Due candidates are selected in round-robin passes across complete stable schedule-instance identities and capped by `script.scheduler.max-catch-up-firings-per-observation`; however, the live `ScriptScheduleInstanceServiceImpl` comparator orders the wall-clock lane, then the due point within that lane (`dueTickId` for tick candidates or epoch-millisecond `dueAt` for wall-clock candidates), then `priorityTag`, and finally the schedule key. Round-robin grouping occurs after that ordering, so lane/due precedence can outrank bounded priority; this is drift from the target bounded priority-first, stable-identity round-robin fairness algorithm. This current per-observation behavior also does not yet prove the accepted one-per-schedule-instance durable resume-window cap across repeated observations. `ObserveRuntimeTickProgress` reports updated rows, fired work items, and truncated candidates; current timer instrumentation exposes aggregate outcomes, but its producer labels are noncanonical and the fired family is not defined in the metrics catalog. +- The comparator's clock-lane key is `wallClock ? 1 : 0`, so tick candidates sort before wall-clock candidates; the drift is that this lane key and the due point both precede `priorityTag`, not that wall-clock candidates universally sort first. +- The current timer metric producer emits raw `eventType` plus optional `reason`, and also emits an undocumented `automation_script_timer_fired_total` family. This does not satisfy the canonical bounded timer labels or the defined metric-family catalog in [Normative Table 4](./system-architecture-scripting-normative-contract-tables.md#table-4-metrics-label-matrix); the status claim above is current instrumentation only, not canonical observability proof. Convergence requires bounded-label producer changes, a decision on the fired family, and focused metric-schema proof. - Control-plane timer audit reads expose scheduler-owned `script_event_audit` rows, including plugin ownership, admitted routing, due-point coordinates, and skipped-versus-persisted outcomes. Plugin-owned definitions retain `pluginId`/`pluginVersionId`/`bindingId`, and materialization admits only the enabled runtime plugin version and resolved signed-bundle binding. - The live `TimerFiringCandidate` retains a mutable `ScriptScheduleInstance` reference and also captures an immutable `PluginFenceSnapshot` of the plugin ID, version, activation epoch, lifecycle revision, and applicable binding ID. Before work-item materialization, emission rechecks that snapshot against the row and the current enabled plugin owner, including its active version, activation epoch, lifecycle revision, and runtime scope, before quota/DSL evaluation. This in-memory snapshot and recheck do not provide durable candidate or retry evidence across a row mutation; broader replay/recovery, remote handoff, policy coordination, and final gameplay-effect fencing also remain gaps. - Current timer work-item materialization retains authored target-scope fields, but only the `ENTITY` target path has an end-to-end entity selector in the firing path. `REGION` and `GLOBAL` timer targets remain unproven target-state behavior and must not be reported as supported until their selector semantics, durable identity, handler resolution, and execution proof are implemented. @@ -27,8 +32,22 @@ The current implementation provides the following substrate: The sections below define the target-state scheduler contract. Current behavior remains limited to the implementation facts listed in the dedicated status section above unless a bullet explicitly identifies a target-state requirement. +### Runtime Replacement Classification + +The following classification applies to Automation-owned scheduler data; it does not assign all runtime or player state one blanket class: + +- Authored schedule definitions are versioned control-plane/catalog data outside the runtime S1/S2/S3 scheme. Their tenant/version retention is governed by publish and version lifecycle rules, not runtime replacement. +- Durable schedule instances and due state are S2 mapping-dependent runtime state. Their durable identity uses the tenant, `playableStateNamespaceId`, and owning schedule identity; the persisted `gameInstanceId` is separately exact-validated active-instance authorization evidence. Replacement requires explicit continuity or replacement mapping, exact target validation, and that active-instance fence. A namespace transition retires the old generation before target admission and never reuses its due point implicitly. +- Correctness-bearing one-shot intent is retained under its owner-defined durable identity (S1 when namespace-owned); an in-flight claim remains fenced and reconciled under its original instance, namespace, epoch, and pin evidence rather than being remapped into a new runtime. +- Durable recurring candidate/claim evidence remains under its original identity until its declared firing, skip, or reconciliation outcome. Advisory/cosmetic candidate state is S3-disposable only where the authored recovery policy permits dropping it; a retained candidate audit is immutable history, not replay authority. +- **Target state only:** Redis timer indexes, scheduler progress hints, queue pointers, and other rebuildable projections are S3 coordination state. Reset, epoch, namespace, or leader changes may discard them, but only durable owner state may rebuild or authorize scheduling. The current PostgreSQL schedule-definition and schedule-instance substrate, and its recovery/fence gaps, remain as recorded in [Implementation Status](../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status). + +Old-instance schedule state and correctness-bearing claims therefore block cleanup while nonterminal or reconciliation-required. A new target row or identity may admit only after the applicable old generation is fenced and the target's exact namespace, runtime, pin, and owner evidence has been validated. + ### Script Timers vs Tick Timers +The end-to-end lifecycle and reload behavior in this target-state section, including rebuilding timer indexes from durable owner state, is not a description of current implementation. Current PostgreSQL schedule storage and the remaining convergence gaps are listed above and tracked by [Automation and Scheduler Runtime](../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status). + Plugin timer admission carries the owner lifecycle fence as evidence separate from schedule identity: the stable schedule row carries the mutable current reconciled `(pluginActivationEpoch, lifecycleRevision)` pair, while each due candidate and firing claim captures the pair as immutable evidence; a new firing requires the exact current tuple. `DRAINING` cannot authorize a new firing; only same-version/same-epoch work whose winning admission CAS durably committed the immediately preceding `ENABLED` revision before the durable Automation-owned `DRAINING` admission barrier was created may retain it under ADR 0119. A revision change alone does not create a new candidate identity. Every authored timer declares both its clock unit and recovery class. Tick/game time is the default for gameplay timers; wall clock must be explicit and is a scheduler-eligibility clock only. Timers remain layered on the authoritative runtime timeline, but not every deadline is a tick deadline: @@ -42,16 +61,16 @@ Every authored timer declares both its clock unit and recovery class. Tick/game - **Advisory or cosmetic**: missed occurrences may drop and the timer resumes with a future occurrence under its declared cadence. - Redis timer indexes, due indexes, leader checkpoints, and wake-up hints are rebuildable coordination projections. Durable timer identity, due state, recovery policy, resume-window identity, and required terminal or skipped outcomes live outside Redis. - A correctness-bearing one-shot must durably terminalize under its original identity with one of the accepted outcomes: `applied`, `canceled`, `superseded`, `expired`, or a feature-defined terminal outcome. A scheduler or worker crash may reclaim a fenced lease, but an inconclusive one-shot remains nonterminal; it must not be silently marked skipped or reminted under a newer scope. -- For timer catch-up, Automation owns one durable timer-recovery resume-window record per ``. Including `isDryRun` in this key keeps live and dry-run/test catch-up candidates in separate windows and caps. A durable compare-and-set creates or returns the one `OPEN` record; its `resumeWindowId` is ``. At creation, the record freezes recovery start and through observations, the effective numeric tenant-local cap, and the selection-policy revision that defines grouping, ordering, round-robin passes, and tie breaks; it also retains the authoritative `playableStateNamespaceId` as immutable non-identity scope evidence. Creation, reuse, retry, observation, and takeover revalidate the same `isDryRun` mode and namespace/binding evidence, then reuse the frozen cap and selection-policy revision unchanged. A policy or configured-cap change applies only to a later window allocated after this one reaches `COMPLETE`; it cannot alter selection or cap-excluded outcomes within the existing `resumeWindowId`. Missing or mismatched mode or namespace evidence fails closed and cannot be refreshed, inferred, or added to `resumeWindowId`. Leader, worker, takeover, and attempt IDs are not identity inputs; retries and takeovers reuse the same mode-specific `resumeWindowId`, and only a later recovery episode after completion allocates the next generation. +- For timer catch-up, Automation owns one durable timer-recovery resume-window record per ``. Including `isDryRun` in this key keeps live and dry-run/test catch-up candidates in separate windows and caps. The server-derived `playableStateScope` is persisted separately as immutable policy/routing/authorization/migration-fence evidence and is exact-validated; it is not part of the window identity. A durable compare-and-set creates or returns the one `OPEN` record; its `resumeWindowId` is ``. At creation, the record freezes recovery start and through observations, the effective numeric tenant-local cap, and the selection-policy revision that defines grouping, ordering, round-robin passes, and tie breaks. Creation, reuse, retry, observation, and takeover revalidate the same `isDryRun` mode, namespace identity, exact scope evidence, and binding evidence, then reuse the frozen cap and selection-policy revision unchanged. A policy or configured-cap change applies only to a later window allocated after this one reaches `COMPLETE`; it cannot alter selection or cap-excluded outcomes within the existing `resumeWindowId`. Missing or mismatched mode, namespace, or scope evidence fails closed and cannot be refreshed, inferred, or added to `resumeWindowId`. Leader, worker, takeover, and attempt IDs are not identity inputs; retries and takeovers reuse the same mode-specific `resumeWindowId`, and only a later recovery episode after completion allocates the next generation. - An epoch transition atomically moves each prior epoch's `OPEN` resume window for each `isDryRun` mode out of `OPEN` before creating the corresponding new-epoch `OPEN` window; prior claims remain fenced and reconciled under their original epoch and resume-window identity and cannot enter the new window, as owned by [ADR 0072](./decisions/adr-0072-class-specific-timer-durability-and-recovery.md). -- `playableStateNamespaceId` is intentionally separate non-identity scope evidence, but a namespace transition is a new playable-state lifecycle under [ADR 0122](./decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md). If target materialization were allowed to update or reuse the prior schedule row, due point, or `OPEN` resume window before fencing the old namespace, the canonical candidate identity could collide—especially when the replacement has the same due point—and uniqueness could suppress the target firing. Namespace transitions therefore use a retire-before-materialize fence, which takes precedence over ordinary playable-scope replacement ordering: one atomic durable operation, or a resumable idempotent operation under the same `controlPlaneRequestId`, first fences and retires/tombstones every prior-namespace schedule row, moves its mode-specific `OPEN` resume windows out of `OPEN`, and preserves prior due candidates, firing claims, and candidate audits with their immutable old namespace evidence and original identities for settlement. No target-namespace schedule row or `OPEN` window may be materialized until that retirement barrier is durable. Target rows then receive fresh due state (the next future tick boundary or a transition-seeded wall-clock due point), never the old due point; namespace remains excluded from candidate, firing-claim, and `scriptEventId` identity, and the fresh due point ensures a same-due-point replacement cannot be suppressed by prior uniqueness. A crash or ambiguous retry leaves target admission fenced until this same operation converges; prior evidence is never rewritten or refreshed. +- `playableStateNamespaceId` is the durable schedule, candidate, firing, and event identity dimension, while `playableStateScope` is separately persisted exact-validated policy/routing/authorization/migration-fence evidence. A namespace transition is a new playable-state lifecycle under [ADR 0122](./decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), and an authoritative scope-policy transition therefore selects or allocates a new namespace before fresh state is admitted. If target materialization were allowed to update or reuse the prior schedule row, due point, or `OPEN` resume window before fencing the old namespace, the canonical candidate identity could collide—especially when the replacement has the same due point—and uniqueness could suppress the target firing. Namespace transitions therefore use a retire-before-materialize fence, which takes precedence over ordinary playable-scope replacement ordering: one atomic durable operation, or a resumable idempotent operation under the same `controlPlaneRequestId`, first fences and retires/tombstones every prior-namespace schedule row, moves its mode-specific `OPEN` resume windows out of `OPEN`, and preserves prior due candidates, firing claims, and candidate audits with their immutable old namespace identity, scope evidence, and original identities for settlement. No target-namespace schedule row or `OPEN` window may be materialized until that retirement barrier is durable. Target rows then receive fresh due state (the next future tick boundary or a transition-seeded wall-clock due point), never the old due point; the target namespace participates in candidate, firing-claim, and `scriptEventId` identity, while `playableStateScope` remains separately persisted evidence. The fresh due point and new namespace ensure a same-due-point replacement cannot be suppressed by prior uniqueness. A crash or ambiguous retry leaves target admission fenced until this same operation converges; prior evidence is never rewritten or refreshed. - Missed firings are handled in a bounded, deterministic way: - - `COALESCE_ONE` schedule instances may enqueue at most one synthetic firing for that complete stable schedule-instance identity within one `resumeWindowId` (and therefore one `isDryRun` mode); `SKIP_MISSED` schedule instances enqueue none. The window's frozen tenant-local cap and selection-policy revision govern every scan, retry, takeover, deterministic selection, and cap-excluded outcome across independent schedule instances within that same full runtime-scope-and-mode ID. Tenant-local identifies the window's tenant owner and does not create a tenant-wide pool, so another runtime scope cannot consume this window's cap. Excluded candidates are dropped rather than deferred as backlog. + - `COALESCE_ONE` schedule instances may enqueue at most one synthetic firing for that complete stable schedule-instance identity within one `resumeWindowId` (and therefore one `isDryRun` mode); `SKIP_MISSED` schedule instances enqueue none. The window's frozen tenant-local cap and selection-policy revision govern every scan, retry, takeover, deterministic selection, and cap-excluded outcome across independent schedule instances within that same full runtime-scope-and-mode ID, whose durable identity includes `playableStateNamespaceId`; `playableStateScope` remains separately persisted exact-validated evidence. Tenant-local identifies the window's tenant owner and does not create a tenant-wide pool, so another runtime scope or namespace cannot consume this window's cap. Excluded candidates are dropped rather than deferred as backlog. - Tenant-local catch-up selection is not shared scheduler admission. A selected candidate still passes through ADR 0166 tenant-first scheduling and the applicable tenant and cluster ceilings. Capacity denial there terminally skips that due candidate within the same `resumeWindowId`: a tenant-ceiling denial records candidate-audit `finalStage=ADMISSION`, `finalOutcome=tenant_budget_exceeded`, and `finalReason=tenant_budget_exceeded`; a cluster-ceiling denial records candidate-audit `finalStage=ADMISSION`, `finalOutcome=quota_denied`, and `finalReason=cluster_limit_reached`. Either denial consumes its deterministic catch-up selection slot, creates no firing claim, handler Trigger Identity, or `scriptEventId`, and is not deferred, retried, backfilled, or reminted as catch-up. The terminal candidate audit, advance of the recurring schedule's canonical due state to its next ordinary future occurrence, and resume-window denial outcome are one atomic owner transaction; when one storage transaction is unavailable, a resumable idempotent reconciliation keyed by `(scheduleCandidateId, resumeWindowId)` must complete all three before the denial is settled or the window can complete. A partial or crashed denial therefore remains fenced and cannot be rediscovered from the unchanged overdue due point. That durable denial counts toward resume-window completion and does not suppress the schedule's next ordinary future occurrence. For live candidates (`isDryRun=false`), emit `automation_script_skips_total` with `scope="tenant"` and `reason="tenant_budget_exceeded"` for a tenant-ceiling denial, or `automation_script_skips_total` with `scope="cluster"` and `reason="cluster_limit_reached"` for a cluster-ceiling denial, using every other required bounded label from [normative Table 4](./system-architecture-scripting-normative-contract-tables.md#table-4-metrics-label-matrix). For dry-run/test candidates (`isDryRun=true`), neither live-only family is emitted: no dedicated test-only candidate-ceiling metric is currently defined, so the settled candidate audit and mode-specific resume-window outcome are the complete observability surface. The handler-scoped test families are not used because the denial occurs before handler materialization. These candidate-level outcomes do not invoke `ScriptTenantBudgetService` or increment `automation_script_tenant_budget_denied_total`; do not increment the catch-up-truncation family for either shared-admission denial. Retryable authority, reload, or reconciliation fences remain governed by the separate nonterminal candidate lifecycle below and are not capacity denials. - After a due candidate passes admission, and before enqueueing that firing, the scheduler must claim or insert a durable trigger-instance row keyed by an instance-aware uniqueness projection. For `triggerMode=CATCH_UP`, the firing claim uniqueness and comparison include `resumeWindowId`, and the candidate-audit record carries the same ID, so failover or duplicate consumers cannot create duplicate logical triggers or consume a later window's cap. - - The projection must define the event-scope due-candidate identity, including `tenantId`, `gameInstanceId`, `playableStateScope`, mandatory `stableOwnerKind` and `stableOwnerId`, `regionId`, `regionEpoch`, `eventType`, `eventSchemaVersion`, the exact `scriptPatchVersion`, positive `scriptPinEpoch`, `isDryRun`, `scheduleDefinitionId`, the persisted due point (`dueTickId` or `dueAt`), and `triggerMode`; include `entityId` only when the schedule target scope is entity-scoped, and `resumeWindowId` for catch-up claims. The paired nonblank `scriptPinControlPlaneRequestId` remains immutable owner evidence retained on each durable candidate, claim, and candidate audit and is exact-compared against authoritative pin evidence, but is excluded from `scheduleCandidateId`, firing-claim, and `scriptEventId` derivation. Each durable row, candidate, claim, and candidate audit also retains and revalidates the authoritative `playableStateNamespaceId` as immutable non-identity scope evidence; it does not participate in `scheduleCandidateId`, firing-claim, `scriptEventId`, Trigger Identity, or Command-Handoff Identity derivation. A core-script schedule must carry its durable `scriptId`; a plugin-owned schedule must carry `pluginId`, `pluginVersionId`, its schedule-owned `bindingId`, and the captured `(pluginActivationEpoch, lifecycleRevision)` pair. `pluginActivationEpoch` is the tagged candidate/firing-claim field; `lifecycleRevision` is required non-identity fence evidence. Core-script candidates omit both plugin lifecycle fields. Missing applicable namespace, durable owner, provenance, or either plugin lifecycle field, or namespace evidence that mismatches the authoritative namespace/scope and active-instance/region binding, rejects the candidate before deriving `scheduleCandidateId`, the firing claim, or `scriptEventId`; a legacy or corrupt row missing any applicable required field is not a candidate: record one deterministic non-candidate schedule-reconciliation outcome keyed by the existing durable `scheduleInstanceId` (the natural key or surrogate row ID defined below) plus the originating `controlPlaneRequestId` from its pin operation or Automation runtime transition, with bounded missing-field reason codes; quarantine or tombstone it, create no `scheduleCandidateId`, `scriptEventId`, ingress audit, firing claim, or handler audit, and never replay it. A handler-only binding field not present on the schedule remains absent until handler resolution. The firing claim derives one event-scope `scriptEventId` from the event identity with owner request evidence excluded, and propagates that ID unchanged into every resolved handler's full Trigger Identity; the request ID remains in the durable candidate/firing-claim evidence for exact owner comparison. Globally unique schedule IDs do not replace runtime scope, exact pin tuple, explicit `isDryRun`, or timeline fencing. - - Candidates denied by a permanent or declared-skip cadence, reload, version, or event-policy outcome before handler binding are terminally consumed; they are recorded as event-scope `scheduleCandidateId` audits with no firing claim or `scriptEventId` and are not replayed later. A transient retryable reload, reconciliation, or authority fence instead retains a durable due-candidate state/claim keyed by `scheduleCandidateId` and the canonical due point under its original exact tuple and captured `(pluginActivationEpoch, lifecycleRevision)` pair, when applicable, as fenced/nonterminal evidence; this transient state is not a terminal candidate audit and carries no `finalStage`, `finalOutcome`, firing claim, handler Trigger Identity, or `scriptEventId` while fenced. Same-epoch retries reuse the candidate identity only while its complete captured fence evidence remains current. A lifecycle-revision mismatch fences the candidate under its original captured pair; reconciliation never refreshes or rebinds that candidate evidence. Unavailable, contradictory, or ambiguous owner evidence keeps it nonterminal. Once authoritative evidence proves that the captured revision is displaced and the ADR 0119 pre-`DRAINING` admission exception cannot apply, reconciliation terminalizes the candidate once under its original identity; it advances or retires a recurring/advisory row's canonical due state in the same durable reconciliation before any later candidate is admitted, while a correctness-bearing one-shot retains its original durable intent until an explicit terminal outcome and is never reminted. `DRAINING` cannot create a new firing; only already-admitted same-version/same-epoch work with the pre-barrier winning admission/fence CAS remains eligible under ADR 0119. A displaced old scope, region epoch, exact pin tuple, or plugin activation epoch remains fenced under its original candidate identity and is never reused on the new timeline; target reconciliation derives a fresh candidate identity for the changed identity tuple before admission. The durable candidate ID is derived from the complete event-scope due-candidate identity: tenant/instance/playable scope, stable schedule-owned script/plugin/binding identity when present, region and region epoch, exact script patch, positive pin epoch, event type and schema version, explicit `isDryRun`, schedule definition, trigger mode, target selector when applicable, and, for plugin-owned schedules, the tagged captured `pluginActivationEpoch`, and, when `triggerMode=CATCH_UP`, `resumeWindowId`, and the tagged due point. The candidate retains the paired nonblank `scriptPinControlPlaneRequestId` as immutable owner evidence and exact-compares it before admission, but it is excluded from candidate, firing-claim, and `scriptEventId` identity. A candidate that passes those gates creates at most one event-scope firing claim and deterministic event-scope `scriptEventId` for that due candidate using the same identity fields, with the tagged plugin activation epoch included in that derivation, resolves handlers, and fans out zero or more handler work items, each with its own full Trigger Identity containing that same propagated ID; a pre-materialization handler quota denial is recorded per resolved handler with no handler work item, while an ordinary post-executor-claim `ScriptTenantBudgetService` denial records the existing handler identity and terminally cancels its already materialized work item before DSL evaluation. + - The projection must define the event-scope due-candidate identity, including `tenantId`, `gameInstanceId`, `playableStateNamespaceId`, mandatory `stableOwnerKind` and `stableOwnerId`, `regionId`, `regionEpoch`, `eventType`, `eventSchemaVersion`, the exact `scriptPatchVersion` and `scriptPinEpoch`, `isDryRun`, `scheduleDefinitionId`, the target selector (`targetScopeType` and `targetScopeId` for `ENTITY`, `REGION`, or `GLOBAL` targets), the persisted due point (`dueTickId` or `dueAt`), and `triggerMode`; include `entityId` only when `targetScopeType=ENTITY`, and `resumeWindowId` for catch-up claims. Each durable row, candidate, claim, and candidate audit also retains and revalidates the server-derived `playableStateScope` as immutable separately persisted policy/routing/authorization/migration-fence evidence; it does not participate in `scheduleCandidateId`, firing-claim, `scriptEventId`, Trigger Identity, or Command-Handoff Identity derivation. A core-script schedule must carry its durable `scriptId`; a plugin-owned schedule must carry `pluginId`, `pluginVersionId`, its schedule-owned `bindingId`, and the captured `(pluginActivationEpoch, lifecycleRevision)` pair. `pluginActivationEpoch` is the tagged candidate/firing-claim field; `lifecycleRevision` is required non-identity fence evidence. Core-script candidates omit both plugin lifecycle fields. Missing applicable namespace, durable owner, provenance, or either plugin lifecycle field, or namespace/scope evidence that mismatches the authoritative namespace, scope, and active-instance/region binding, rejects the candidate before deriving `scheduleCandidateId`, the firing claim, or `scriptEventId`; a legacy or corrupt row missing any applicable required field is not a candidate: record one deterministic non-candidate schedule-reconciliation outcome keyed by the existing durable `scheduleInstanceId` (the immutable physical row-generation reference, not the logical schedule/event identity) plus the originating `controlPlaneRequestId` from its pin operation or Automation runtime transition, with bounded missing-field reason codes; quarantine or tombstone it, create no `scheduleCandidateId`, `scriptEventId`, ingress audit, firing claim, or handler audit, and never replay it. A handler-only binding field not present on the schedule remains absent until handler resolution. The firing claim derives one event-scope `scriptEventId` from this complete due-candidate identity and propagates that ID unchanged into every resolved handler's full Trigger Identity. Globally unique schedule IDs do not replace runtime scope, exact pin tuple, explicit `isDryRun`, or timeline fencing. + - Candidates denied by a permanent or declared-skip cadence, reload, version, or event-policy outcome before handler binding are terminally consumed; they are recorded as event-scope `scheduleCandidateId` audits with no firing claim or `scriptEventId` and are not replayed later. A transient retryable reload, reconciliation, or authority fence instead retains a durable due-candidate state/claim keyed by `scheduleCandidateId` and the canonical due point under its original exact tuple and captured `(pluginActivationEpoch, lifecycleRevision)` pair, when applicable, as fenced/nonterminal evidence; this transient state is not a terminal candidate audit and carries no `finalStage`, `finalOutcome`, firing claim, handler Trigger Identity, or `scriptEventId` while fenced. Same-epoch retries reuse the candidate identity only while its complete captured fence evidence remains current. A lifecycle-revision mismatch fences the candidate under its original captured pair; reconciliation never refreshes or rebinds that candidate evidence. Unavailable, contradictory, or ambiguous owner evidence keeps it nonterminal. Once authoritative evidence proves that the captured revision is displaced and the ADR 0119 pre-`DRAINING` admission exception cannot apply, reconciliation terminalizes the candidate once under its original identity; it advances or retires a recurring/advisory row's canonical due state in the same durable reconciliation before any later candidate is admitted, while a correctness-bearing one-shot retains its original durable intent until an explicit terminal outcome and is never reminted. `DRAINING` cannot create a new firing; only already-admitted same-version/same-epoch work with the pre-barrier winning admission/fence CAS remains eligible under ADR 0119. A displaced old namespace, scope evidence, region epoch, exact pin tuple, or plugin activation epoch remains fenced under its original candidate identity and is never reused on the new timeline; target reconciliation derives a fresh candidate identity for the changed identity tuple before admission. The candidate ID is derived from the complete event-scope due-candidate identity: tenant/instance/playable-state namespace, stable schedule-owned script/plugin/binding identity when present, region and region epoch, exact script patch and pin epoch, event type and schema version, explicit `isDryRun`, schedule definition, trigger mode, target selector when applicable, and, for plugin-owned schedules, the tagged captured `pluginActivationEpoch`, and, when `triggerMode=CATCH_UP`, `resumeWindowId`, and the tagged due point. The server-derived `playableStateScope` is retained and exact-validated as separate policy/routing/authorization/migration-fence evidence and is not an identity input; an authority-proven scope transition starts a new lifecycle/namespace. A candidate that passes those gates creates at most one event-scope firing claim and deterministic event-scope `scriptEventId` for that due candidate, with the tagged plugin activation epoch included in that derivation, resolves handlers, and fans out zero or more handler work items, each with its own full Trigger Identity containing that same propagated ID; a pre-materialization handler quota denial is recorded per resolved handler with no handler work item, while an ordinary post-executor-claim `ScriptTenantBudgetService` denial records the existing handler identity and terminally cancels its already materialized work item before DSL evaluation. For plugin-owned candidates, the transient candidate state, reconciliation evidence, and retry/reload state retain the captured `(pluginActivationEpoch, lifecycleRevision)` pair. Reconciliation and retry revalidate both values against the current owner pair; `pluginActivationEpoch` is part of `scheduleCandidateId`, firing-claim, and derived `scriptEventId` identity, while `lifecycleRevision` is fence evidence only and is not added to those identities. @@ -61,7 +80,7 @@ Within that model: - The Game Session Service owns authoritative tick progression and tick timers, as described in [Tick System and Runtime Design](./system-architecture-ticks.md). - The Automation & Scripting Service owns script timers and intervals, which are scheduled against tick heartbeat information but do not own ticks themselves. -- Scheduler data structures such as `automation:timer:{tenantRegionTag}` are used to track when script timers should fire relative to tick progression. `{tenantRegionTag}` is the opaque shared-key-builder tag derived from the full `` scope; it is not a competing schedule identity. Durable script schedules and quotas live in the Automation & Scripting Service’s PostgreSQL schema, while Redis indexes are coordination structures that can be rebuilt or reset without changing which scripts should eventually run. +- **Target-state only:** Scheduler data structures such as `automation:timer:{tenantRegionTag}` and `script-scheduler:{tenantRegionTag}:lastTickId` are unimplemented Redis coordination projections; no current scheduler/timer authority or supported manual/reset operation exists for them. `{tenantRegionTag}` is the opaque shared-key-builder tag derived from the full `` scope; it is not a competing schedule identity. Current durable script schedules live in the Automation & Scripting Service’s PostgreSQL schema, and current tick progress/heartbeat authority remains in Game Session. Target-state firing-claim de-duplication and durable quota/charge and admission-marker ownership also belong in PostgreSQL. The current quota, tenant-budget, readiness/capacity, and queue-pointer decisions are Redis best-effort, reset-sensitive projections with no durable charge/admission markers. Redis indexes can be rebuilt or reset without changing durable schedule identity or correctness-bearing one-shot outcomes; best-effort recurring or advisory missed firings may be skipped, while future eligible cadence remains available. From the tick system’s perspective, script timers are a source of work that ultimately enters the tick scheduler. Every scheduler and timer source must declare immutable `lane` (`actor_action` or `passive_effect`) and bounded `cost_class` before admission, and must carry those fields unchanged through durable schedule state, firing claims, work items, retries, and recovery. Missing or changed values reject timer firing, admission, retry, or recovery rather than being inferred or reclassified. Under ADR 0051, `passive_effect` is bounded non-actor work governed by the passive lane’s budgets: status pulses, environmental changes, passive inbound or remote envelopes, actor-generated consequences, and retries of already-admitted passive effects. Root intentional player, AI, automation, movement, or other gameplay commands remain `actor_action`; a timer is `actor_action` when it makes an actor act. If a passive inbound envelope emits a gameplay command, that resulting command is `actor_action` and cannot grant another same-tick root action. The determinism rules in the DSL reference apply equally to timer-driven triggers, while lane selection and budgets remain owned by the tick contract. @@ -80,8 +99,8 @@ When an explicitly preserved tick-aligned interval keeps a logical timer alive a - `previousDueTickId` = the durable due point stored before pause or reconciliation. - `intervalTicks` = the preserved schedule cadence in ticks. - Preconditions: - - Apply the preserved-due-point formula only when the preserved row's `runtimeRegionId`, runtime scope (`gameInstanceId` and `playableStateScope`), and `runtimeRegionEpoch` match the resumed runtime's corresponding region, scope, and `regionEpoch`. - - If the runtime region, runtime scope, or region epoch differs, fence the old due point and derive a new due point on the new timeline after the replacement/new-scope schedule entry is durable; do not feed the stale `previousDueTickId` into this formula. + - Apply the preserved-due-point formula only when the preserved row's `runtimeRegionId`, runtime scope (`gameInstanceId` and `playableStateNamespaceId`), separately persisted `playableStateScope` evidence, and `runtimeRegionEpoch` match the resumed runtime's corresponding region, namespace, exact scope evidence, and `regionEpoch`. + - If the runtime region, namespace, authoritative scope, or region epoch differs, fence the old due point and derive a new due point on the new timeline after the replacement/new-namespace schedule entry is durable; do not feed the stale `previousDueTickId` into this formula. A merely presented stale scope may reuse the namespace only after authority proves the scope is unchanged; an authority-proven scope transition starts a new lifecycle and namespace. - Rule: - `intervalTicks` must be a positive integer. A schedule with `intervalTicks <= 0` is invalid and must be rejected before any modulo or due-point calculation. - if `previousDueTickId >= resumeTickId`, keep `nextTick = previousDueTickId`; @@ -89,17 +108,17 @@ When an explicitly preserved tick-aligned interval keeps a logical timer alive a - Consequences: - the scheduler resumes on the next valid cadence boundary at or after resume, never by replaying every missed firing from the paused window; - a preserved schedule may fire immediately after resume only when its next valid cadence boundary is exactly `resumeTickId`; - - reload and rollback preservation and downtime recovery remain distinct behaviors. The resume rule governs preserved timers after a version transition on the same runtime region, scope, and epoch; a scope or epoch migration fences the old due point and starts from the new timeline. The declared recovery class and durable resume-window policy govern missed firings after scheduler downtime within the same logical schedule instance and version. + - reload and rollback preservation and downtime recovery remain distinct behaviors. The resume rule governs preserved timers after a version transition on the same runtime region, `gameInstanceId`, `playableStateNamespaceId`, exact `playableStateScope` evidence, and epoch; a region, namespace, authoritative scope, or epoch migration fences the old due point and starts from the new timeline. The declared recovery class and durable resume-window policy govern missed firings after scheduler downtime within the same logical schedule instance and version. - Reset, incompatible, or newly materialized replacement rows do not use this rule and start with fresh due state; a preserved wall-clock timer does not use the tick formula, and compatible continuity retains its persisted absolute `dueAt` and regenerates `nextRunAt`. ### End-to-End `onInterval` Timer Lifecycle -This section summarizes how a single `onInterval` timer behaves across normal operation, leader changes, and script reloads, and which Redis keys are authoritative at each step. +This section summarizes how a single `onInterval` timer behaves across normal operation, leader changes, and script reloads. Durable `script_schedule_instances` rows in PostgreSQL are authoritative schedule state; Redis keys are rebuildable coordination projections, as defined by [ADR 0072](./decisions/adr-0072-class-specific-timer-durability-and-recovery.md). -All durable timer identity and scheduler checkpoints must be instance-aware even when Redis keys are region-scoped for slotting and locality: +Timer, schedule, firing, and catch-up identities must be instance-aware even when Redis keys are region-scoped for slotting and locality. The per-region scheduler runtime-progress hint is intentionally namespace-independent: its opaque key tag carries the full tenant/game/region scope, while its payload carries only `{regionEpoch, latestTickId}`; it is derived progress, never timer, due, or admission identity. -- `gameInstanceId` is a required part of timer identity, deterministic scheduler `scriptEventId` derivation, catch-up deduplication, and checkpoint projection state. -- If a Redis key name omits `gameInstanceId`, the stored timer or checkpoint payload must still include it, and rebuild logic must treat instance mismatches as corruption rather than as reusable timer state. +- `gameInstanceId` and `playableStateNamespaceId` are required parts of timer identity, deterministic scheduler `scriptEventId` derivation, and catch-up deduplication. The server-derived `playableStateScope` is persisted separately as exact-validated policy/routing/authorization/migration-fence evidence, never as identity. +- For timer projections whose Redis key name omits `gameInstanceId`, the opaque `{tenantRegionTag}` must still encode the complete `` scope, and stored timer payloads must retain their full identity; rebuild logic must treat instance mismatches as corruption rather than as reusable timer state. - Plugin timers must additionally carry `pluginId`, `pluginVersionId`, and `bindingId` in their durable identity so sibling bindings and plugin rollback, disablement, or revocation cannot cross-contaminate interval state. #### Interval-Entry Identity and Due-Point Persistence @@ -108,22 +127,22 @@ A durable interval has two identities that must not be conflated. Stable schedule-instance row identity: -The stable durable row identity retains tenant, instance, playable-scope, stable-owner, definition, target-scope, and dry-run separation. Replaceable pin/provenance metadata remains on the row as mutable execution-fence evidence: +The stable durable row identity retains tenant, playable-state namespace, stable-owner, definition, target-scope, and dry-run separation. The persisted `gameInstanceId` is the active-instance authorization fence and is not part of this S2 durable identity. The server-derived playable-state scope remains separately persisted exact-validated policy/routing/authorization/migration-fence evidence. Replaceable pin/provenance metadata remains on the row as mutable execution-fence evidence: -`` +`` This row identity is distinct from the stable logical continuity key: -`{stableOwnerKind, stableOwnerId, scheduleDefinitionId, targetScopeType, targetScopeId}` +`{stableOwnerKind, stableOwnerId, scheduleDefinitionId, playableStateNamespaceId, targetScopeType, targetScopeId}` For a core script, `stableOwnerId` is the durable script identity. For a plugin, it is `pluginId`; `pluginVersionId` remains provenance and an execution fence, not continuity identity. `scriptPatchVersion` and `scriptPinEpoch` are exact pin metadata and execution-fence fields, not continuity identity. -- `scheduleInstanceId` is an immutable surrogate row-generation identity allocated idempotently under the materializing `controlPlaneRequestId`; it is not the stable logical continuity key. Within one `(tenantId, gameInstanceId, isDryRun)` runtime scope, the natural continuity key above identifies at most one admitting, non-tombstoned row. A compatible continuity transition retains the same `scheduleInstanceId`; a reset or incompatible transition that still has a replacement target allocates a fresh one. Immutable non-identity namespace evidence (`playableStateNamespaceId`), mutable pin/provenance metadata, mutable runtime-region metadata (`runtimeRegionId`, `runtimeRegionEpoch`), and due point remain outside both the continuity key and the surrogate identity. `playableStateNamespaceId` remains persisted and exact-matched with `playableStateScope` and the active-instance/region owner binding on materialization, readback, due-candidate creation, claim, retry, and reconciliation; it is never inferred or refreshed onto an existing row. `pluginVersionId`, `bindingId`, `scriptPatchVersion`, and `scriptPinEpoch` remain persisted on the row as exact provenance and execution-fence fields; `runtimeRegionId`, `runtimeRegionEpoch`, `nextDueTickId`/`nextDueAt`, and last-observed progress are schedule state. Ordinary matching heartbeat evidence may advance those mutable fields on the active generation, but a namespace or active-instance/region binding transition creates a replacement generation rather than rewriting that evidence in place. +- `scheduleInstanceId` is an immutable surrogate row-generation identity allocated idempotently under the materializing `controlPlaneRequestId`; it is not the stable logical continuity key. Within one `(tenantId, playableStateNamespaceId, isDryRun)` namespace binding, the natural continuity key above identifies at most one admitting, non-tombstoned row for the exact current active-instance/region fence. `gameInstanceId` remains persisted and exact-validated active-instance authorization evidence rather than an S2 identity dimension; a replacement instance therefore maps or creates a distinct physical generation under the same namespace and retires the source before target admission. A compatible continuity transition retains the same `scheduleInstanceId`; a reset or incompatible transition that still has a replacement target allocates a fresh one. `playableStateNamespaceId` is part of the durable row identity and continuity key. The separately persisted `playableStateScope` evidence, mutable pin/provenance metadata, mutable runtime-region metadata (`runtimeRegionId`, `runtimeRegionEpoch`), and due point remain outside the identity and are exact-validated at materialization, readback, due-candidate creation, claim, retry, and reconciliation. Namespace and scope evidence are never inferred or refreshed onto an existing row. `pluginVersionId`, `bindingId`, `scriptPatchVersion`, and `scriptPinEpoch` remain persisted on the row as exact provenance and execution-fence fields; `runtimeRegionId`, `runtimeRegionEpoch`, `nextDueTickId`/`nextDueAt`, and last-observed progress are schedule state. Ordinary matching heartbeat evidence may advance those mutable fields on the active generation, but a namespace or active-instance/region binding transition creates a replacement generation rather than rewriting that evidence in place. - `scheduleDefinitionId` participates in the stable logical continuity key and is one component of the complete due-candidate/firing claim identity; it is never sufficient alone and does not replace that complete identity. `scriptPatchVersion` and `scriptPinEpoch` identify the exact Game Session pin under which the row may execute; plugin-owned entries additionally carry `pluginId`, `pluginVersionId`, and `bindingId`, and `isDryRun` separates test execution from live scheduling. Live durable interval entries persist `isDryRun=false`. - `duePoint` is exactly one mutable persisted value: `dueTickId` for tick-aligned schedules or `dueAt` for wall-clock timers. `nextTick` and `nextRunAt` are projections of that stored due point, not substitutes for it. -- Each due candidate has at most one event-scope durable firing claim and one deterministic event-scope `scriptEventId`, keyed by the complete event-scope due-candidate identity defined above, including `scheduleDefinitionId`, `eventType`/`eventSchemaVersion`, the tagged captured `pluginActivationEpoch` for plugin-owned schedules, and, for catch-up claims and candidate audits, `resumeWindowId`. Same-epoch retries reuse that candidate identity; for plugin-owned schedules, a same-version disable/re-enable derives a fresh candidate identity from the newer `pluginActivationEpoch`. Core schedule transition identity changes only through the accepted exact patch/pin epoch contract; no separate core generation is implied. The claim and candidate audit persist/expose that same exact identity; handler-only identity fields are added only after resolution. Advancing the schedule due point must never rewrite a prior claim or mint a second ID. +- Each due candidate has at most one event-scope durable firing claim and one deterministic event-scope `scriptEventId`, keyed by the complete event-scope due-candidate identity defined above, including `playableStateNamespaceId`, `scheduleDefinitionId`, `eventType`/`eventSchemaVersion`, the tagged captured `pluginActivationEpoch` for plugin-owned schedules, and, for catch-up claims and candidate audits, `resumeWindowId`. The server-derived `playableStateScope` is separately persisted and exact-validated as policy/routing/authorization/migration-fence evidence, not identity. Same-epoch retries reuse that candidate identity; for plugin-owned schedules, a same-version disable/re-enable derives a fresh candidate identity from the newer `pluginActivationEpoch`. Core schedule transition identity changes only through the accepted exact patch/pin epoch contract; no separate core generation is implied. The claim and candidate audit persist/expose that same exact identity; handler-only identity fields are added only after resolution. Advancing the schedule due point must never rewrite a prior claim or mint a second ID. -Every durable schedule-instance row, resume window, due candidate, firing claim, candidate audit, and scheduler list/read output must persist and expose `isDryRun` as an identity dimension, `playableStateNamespaceId` as separate non-identity scope evidence, and `scriptPinEpoch` alongside `scriptPatchVersion`. Namespace evidence must exact-match the authoritative namespace/scope and active-instance/region owner binding at each materialization, claim, retry, and reconciliation boundary; missing or mismatched evidence fails closed without changing any canonical identity tuple. The pin epoch is exact execution/fence metadata and is deliberately excluded from the stable logical continuity key above. A same-version repin creates a new exact tuple: before Automation admission resumes, reconciliation may rewrite or retire only mutable schedule state. It must never rewrite an old-epoch firing claim or candidate/audit identity or outcome; pending claims may be fenced or terminal-marked when required while preserving their original exact tuples. Same-version repin retries must remain idempotent and replay-safe by reusing existing claim/candidate identities rather than duplicating them. +Every durable schedule-instance row, resume window, due candidate, firing claim, candidate audit, and scheduler list/read output must persist and expose `isDryRun` and `playableStateNamespaceId` as identity dimensions, the exact `playableStateScope` as separately persisted policy/routing/authorization/migration-fence evidence, and `scriptPinEpoch` alongside `scriptPatchVersion`. Namespace and scope evidence must exact-match the authoritative namespace/scope and active-instance/region owner binding at each materialization, claim, retry, and reconciliation boundary; missing or mismatched evidence fails closed without changing any canonical identity tuple. The pin epoch is exact execution/fence metadata and is deliberately excluded from the stable logical continuity key above. A same-version repin creates a new exact tuple: before Automation admission resumes, reconciliation may rewrite or retire only mutable schedule state. It must never rewrite an old-epoch firing claim or candidate/audit identity or outcome; pending claims may be fenced or terminal-marked when required while preserving their original exact tuples. Same-version repin retries must remain idempotent and replay-safe by reusing existing claim/candidate identities rather than duplicating them. On every exact script pin selection change, including a same-patch/new-epoch repin, reconciliation moves each prior `OPEN` resume window (independently for each `isDryRun` mode) out of `OPEN` before target timer admission resumes. Existing firing claims and candidate/audit records retain their original mode-specific `resumeWindowId` and exact pin, remain fenced for settlement under those original identities, and cannot consume the next window's cap. Only after the new exact `(scriptPatchVersion, scriptPinEpoch)` and schedules reconcile may a still-required catch-up episode allocate the next `resumeGeneration` window for the candidate's mode; retries are idempotent under the reconciliation `controlPlaneRequestId`. @@ -133,7 +152,7 @@ The schedule-row requirement to persist and expose `scriptPinEpoch` alongside `s The interval admission, durable-claim, artifact-estimate reservation, and retry/deferral behavior described below is target-state unless explicitly identified as current. It must not be read as evidence that the current runtime already implements those guarantees; the current-state gaps above and in the quotas document remain authoritative. -- When an instance first observes an exact pinned tuple, Automation materializes the patch-owned schedules for that `(tenantId, gameInstanceId)` scope into durable `script_schedule_instances` rows keyed by the stable schedule-instance identity above, with plugin owner metadata and binding target identity. Each row stores the authoritative `playableStateNamespaceId` as immutable non-identity scope evidence, the exact `scriptPatchVersion`, positive `scriptPinEpoch`, and paired nonblank `lastObservedControlPlaneRequestId`, `isDryRun`, `scheduleDefinitionId`, cadence, unit, scheduler priority tag, normalized schedule metadata hash, the initiating pin or runtime-transition `controlPlaneRequestId`, and exactly one mutable due-point field (`dueTickId` or `dueAt`). Missing or mismatched namespace evidence rejects materialization without creating or updating a row. For an initially materialized or reset wall-clock row with an absent durable `dueAt`, Automation derives it once from the transition's immutable seed plus the schedule's authored wall-clock cadence (`cadence`/`unit`) after any explicit time scaling. A Game Session pin or rollback uses Game Session `pinnedAt` bound to that pin request ID; a schedule-creating or resetting plugin activation/enable or other non-pin replacement instead uses an immutable Automation transition commit timestamp durably bound to that same `controlPlaneRequestId` (the runtime transition's committed `lastChangedAt` may supply the seed) and must never look up Game Session `pinnedAt` using a non-pin request ID. Automation persists and reuses that seed and derived `dueAt` across retries and reconciliation; projection refresh or observation time is diagnostic only. Disablement or revocation without a replacement tombstones the displaced row and creates no replacement row or fresh due point. Compatible continuity retains an existing `dueAt`; ordinary reload or repin does not overwrite it except through the transition branch below, while reset, incompatible, or newly materialized replacement rows receive fresh due state. Tick-aligned schedules remain persisted but `PENDING_RUNTIME_PROGRESS` until Game Session's `ObserveRuntimeTickProgress` input supplies the current runtime region epoch and tick id from Game Session's durable runtime ownership row. At that point Automation exact-matches the stored namespace/scope evidence with current owner scope, records the runtime region fields, and derives the first future `dueTickId` as `observedTickId + cadenceValue`; later observations that reach or pass it revalidate the complete namespace/scope and active-instance/region binding before admitting the due candidate, creating at most one event-scope firing claim, and deriving one deterministic event-scope `scriptEventId` for that due candidate, then use the same durable work-item, audit, and queue projection path as other admitted script events. Plugin-owned schedules are materialized only for the plugin version currently enabled in Automation's runtime registry for that instance; other published or displaced plugin versions must not keep durable schedule ownership. Region-scoped Redis indexes such as `automation:timer:{tenantRegionTag}` remain a derived coordination layer above those durable rows rather than the first source of schedule identity. +- When an instance first observes an exact pinned tuple, Automation materializes the patch-owned schedules for that `(tenantId, gameInstanceId, playableStateNamespaceId)` runtime scope into durable `script_schedule_instances` rows keyed by the stable schedule-instance identity above, with the server-derived `playableStateScope` persisted as separate exact-validated policy/routing/authorization/migration-fence evidence, plugin owner metadata, and binding target identity. Each row stores the namespace identity, exact `scriptPatchVersion` and `scriptPinEpoch`, `isDryRun`, `scheduleDefinitionId`, cadence, unit, scheduler priority tag, normalized schedule metadata hash, the initiating pin or runtime-transition `controlPlaneRequestId`, and exactly one mutable due-point field (`dueTickId` or `dueAt`). Missing or mismatched namespace or scope evidence rejects materialization without creating or updating a row. For an initially materialized or reset wall-clock row with an absent durable `dueAt`, Automation derives it once from the transition's immutable seed plus the schedule's authored wall-clock cadence (`cadence`/`unit`) after any explicit time scaling. A Game Session pin or rollback uses Game Session `pinnedAt` bound to that pin request ID; a schedule-creating or resetting plugin activation/enable or other non-pin replacement instead uses an immutable Automation transition commit timestamp durably bound to that same `controlPlaneRequestId` (the runtime transition's committed `lastChangedAt` may supply the seed) and must never look up Game Session `pinnedAt` using a non-pin request ID. Automation persists and reuses that seed and derived `dueAt` across retries and reconciliation; projection refresh or observation time is diagnostic only. Disablement or revocation without a replacement tombstones the displaced row and creates no replacement row or fresh due point. Compatible continuity retains an existing `dueAt`; ordinary reload or repin does not overwrite it except through the transition branch below, while reset, incompatible, or newly materialized replacement rows receive fresh due state. Tick-aligned schedules remain persisted but `PENDING_RUNTIME_PROGRESS` until Game Session's `ObserveRuntimeTickProgress` input supplies the current runtime region epoch and tick id from Game Session's durable runtime ownership row. At that point Automation exact-matches the stored namespace/scope evidence with current owner scope, records the runtime region fields, and derives the first future `dueTickId` as `observedTickId + cadenceValue`; later observations that reach or pass it revalidate the complete namespace/scope and active-instance/region binding before admitting the due candidate, creating at most one event-scope firing claim, and deriving one deterministic event-scope `scriptEventId` for that due candidate, then use the same durable work-item, audit, and queue projection path as other admitted script events. Plugin-owned schedules are materialized only for the plugin version currently enabled in Automation's runtime registry for that instance; other published or displaced plugin versions must not keep durable schedule ownership. Region-scoped Redis indexes such as `automation:timer:{tenantRegionTag}` remain a derived coordination layer above those durable rows rather than the first source of schedule identity. - Leaders track these interval entries alongside other automation timers using bounded scans. Event scope applies cadence, reload, version, and event-policy gates, then creates at most one event-scope firing claim and one event-scope `scriptEventId` per due candidate before resolving handlers. Handlers admitted by all pre-materialization handler-scoped gates, including quota, become durable queued work, each with its own full Trigger Identity containing that same propagated ID; every resolved handler still receives an audit row, while a handler denied by a pre-materialization handler-scoped gate receives no work item, queue projection, lease, or execution marker. The later execution scheduler considers queued handler work in canonical order and reserves the artifact-estimate ordered prefix up to `AUTOMATION_TICK_BUDGET_MS`, leaving the remainder durably queued/deferred under unchanged handler identity. An ordinary post-executor-claim `ScriptTenantBudgetService` denial instead acts on an existing durable work item, terminally cancels it before DSL evaluation, and follows the handler-level budget outcome route. The reservation is not actual execution time, a per-run timeout, or a lease debit; actual runtime never changes the selected prefix or creates a same-tick refund, and the quota owner separately governs fenced capacity lease acquisition and recovery. - When an interval becomes due, the scheduler derives a deterministic `scheduleCandidateId` from the complete event-scope due-candidate identity defined above, including the captured `pluginActivationEpoch` for plugin-owned schedules. It applies cadence, reload, version, and event-policy gates at event scope before handler binding. A permanent or declared-skip gate failure is durably consumed with its `scheduleCandidateId`-keyed audit outcome: advance the canonical due point according to the cadence, or quarantine/tombstone the schedule when safe advancement is impossible; it creates no firing claim or `scriptEventId`. A transient retryable reload, reconciliation, or authority fence instead retains a durable due-candidate state/claim keyed by `scheduleCandidateId` and the canonical due point under its original exact tuple and captured `(pluginActivationEpoch, lifecycleRevision)` pair, when applicable, as fenced/nonterminal evidence without creating a firing claim or `scriptEventId`; this transient state is not a terminal candidate audit and carries no `finalStage` or `finalOutcome` while fenced. It may retry the same candidate only while the captured lifecycle pair remains current and after the exact pin tuple, runtime scope, and owner evidence reconcile, then compare-and-set once into the one firing path or one immutable terminal candidate audit. A displaced old scope, epoch, or plugin activation epoch remains fenced under its original candidate identity and is never reused; a plugin-owned same-version disable/re-enable derives a fresh candidate identity from the newer `pluginActivationEpoch` before admission. Core schedule transition identity changes only through the accepted exact patch/pin epoch contract. Once the candidate passes those event gates, the scheduler creates at most one event-scope durable firing claim and one event-scope `scriptEventId`, resolves handlers, and applies all pre-materialization handler-scoped gates. Handlers admitted by those gates, including quota, create durable queued work, each with its own full Trigger Identity containing that same propagated ID; every resolved handler receives an audit row, while a handler denied by a pre-materialization handler-scoped gate, including quota denial as `ADMISSION/quota_denied`, creates no work item, queue projection, lease, or execution marker. An ordinary post-executor-claim `ScriptTenantBudgetService` denial instead terminally cancels the already materialized and claimed handler work item before DSL evaluation with `ADMISSION/tenant_budget_exceeded`; it is not a pre-materialization denial. Before `EVALUATED_COMMITTED`, a failed handler evaluation may retry under that same full Trigger Identity and same propagated `scriptEventId` only for a retryable infrastructure or fencing failure; deterministic logical, validation, and sandbox outcomes are final. After the boundary, recovery replays its durable descriptors without re-entering the DSL. The later execution scheduler applies the artifact-estimate ordered-prefix reservation to queued handler work and defers the remainder without changing identity. @@ -141,16 +160,16 @@ The interval admission, durable-claim, artifact-estimate reservation, and retry/ #### Leader Changes -- Leaders advance a per-region notion of time by consuming the tick heartbeat stream and tracking how far they have progressed. In addition to the current heartbeat `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)`, schedulers maintain a derived discovery hint such as `script-scheduler:{tenantRegionTag}:lastTickId`. The opaque `{tenantRegionTag}` physically carries the full `` scope, while the payload stores `regionEpoch` and `latestTickId`. Consumers must compare the stored epoch with the authoritative current epoch before reusing the progress value. The separate per-consumer `tick-events-offset:{tenantRegionTag}:` record is the sole owner of that consumer's `streamOffset`. +- Leaders advance a per-region notion of time by consuming the tick heartbeat stream and tracking how far they have progressed. In addition to the current heartbeat `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)`, a target scheduler may maintain a derived discovery hint such as `script-scheduler:{tenantRegionTag}:lastTickId`; this Redis key is target-only and unimplemented, while Game Session's durable runtime-ownership status and heartbeat remain current authority. This runtime-progress hint is deliberately namespace-independent: the opaque `{tenantRegionTag}` physically carries the full `` scope, while the payload stores `regionEpoch` and `latestTickId`. It is derived progress only, never timer, due-point, or admission identity; a namespace transition therefore re-enumerates durable schedule state and cannot be authorized by this hint. Consumers must compare the stored epoch with the authoritative current epoch before reusing the progress value. The separate per-consumer `tick-events-offset:{tenantRegionTag}:` record is the sole owner of that consumer's `streamOffset`. - When leadership changes, the new leader: - reads the scheduler hint and canonical event-offset record for the current `regionEpoch`; - rejects either value when its stored `regionEpoch` does not match the current heartbeat/status epoch. It must not walk old-epoch ticks, reuse an old stream offset, or reuse old-epoch due points. The mismatch is recorded in scheduler audit with `reason=checkpoint_region_epoch_mismatch`; this stale coordination projection does not drop or terminalize a due point and does not increment `automation_script_timer_runtime_fence_dropped_total`; - discards each stale value, rebuilds the current-epoch scheduler hint and event-offset record from the authoritative durable status/heartbeat, and then reconciles durable due points under the bounded catch-up policy; and - - enumerates the authoritative PostgreSQL `script_schedule_instances` rows for the current runtime scope to determine which current-epoch "every N ticks" boundaries were crossed during the gap. The Redis region index `automation:timer:{tenantRegionTag}` may accelerate this scan, but it is rebuildable and must not be the source of truth; if it is missing or stale, rebuild it from the durable rows before admitting candidates. It obtains or creates the one `OPEN` durable resume-window record for the candidate's `isDryRun` mode by CAS, freezes that record's recovery start and through observations, and admits each due candidate before claiming or inserting a durable firing claim. Every firing-claim insert, lookup, and conflict comparison uses the complete event-scope due-candidate identity defined above, including the exact pin tuple, event/schema, explicit `isDryRun`, trigger mode, applicable target selector, schedule definition, tagged due point, and `resumeWindowId` for catch-up; only then may it enqueue an `onInterval` trigger. - - Each `COALESCE_ONE` schedule instance may enqueue at most one missed `onInterval` trigger before normal scheduling resumes; `SKIP_MISSED` schedule instances enqueue none. `SCRIPT_TIMER_CATCH_UP_MAX_FIRINGS_PER_RESUME` is evaluated as a tenant-local cap across complete stable schedule-instance identities within one durable, mode-specific `resumeWindowId`; the cap's boundary is that ID's full runtime scope and `isDryRun` mode, while tenant-local identifies the window's tenant owner rather than a tenant-wide pool. Live and dry-run/test windows apply the cap independently, and a schedule in another game instance, playable-state scope, region, or epoch cannot consume this window's cap. Candidates beyond this cap are dropped, not deferred, and surfaced through candidate audit plus exactly one `automation_script_timer_catchup_truncated_total{reason="resume_window_cap"}` increment when each candidate's durable settlement completes; they create no firing claim or firing. The window is marked `COMPLETE` only after selected candidates' firing or durable shared-admission-denial outcomes and all cap-excluded candidate outcomes are durable; only a later recovery episode then allocates the next generation. These are target-state recovery guarantees; the current runtime's bounded per-observation catch-up does not yet prove the durable resume-window enforcement described here. + - enumerates the authoritative PostgreSQL `script_schedule_instances` rows for the current runtime scope and `playableStateNamespaceId` to determine which current-epoch "every N ticks" boundaries were crossed during the gap. The Redis region index `automation:timer:{tenantRegionTag}` may accelerate this scan, but it is rebuildable and must not be the source of truth; if it is missing or stale, rebuild it from the durable rows before admitting candidates. It obtains or creates the one `OPEN` durable resume-window record for the candidate's `isDryRun` mode by CAS, freezes that record's recovery start and through observations, and admits each due candidate before claiming or inserting a durable firing claim. Every firing-claim insert, lookup, and conflict comparison uses the complete event-scope due-candidate identity defined above, including the namespace identity, exact pin tuple, event/schema, explicit `isDryRun`, trigger mode, applicable target selector, schedule definition, tagged due point, and `resumeWindowId` for catch-up. The separately persisted exact `playableStateScope` remains policy/routing/authorization/migration-fence evidence that is revalidated before admission, not an identity input; only then may it enqueue an `onInterval` trigger. + - Each `COALESCE_ONE` schedule instance may enqueue at most one missed `onInterval` trigger before normal scheduling resumes; `SKIP_MISSED` schedule instances enqueue none. Cadence, reload, version, and event-policy gates settle any rejected candidate durably before it joins the resume window's enumerated set. `SCRIPT_TIMER_CATCH_UP_MAX_FIRINGS_PER_RESUME` is evaluated as a tenant-local cap across complete stable schedule-instance identities within one durable, mode-specific `resumeWindowId`; the cap's boundary is that ID's full runtime scope, `playableStateNamespaceId`, and `isDryRun` mode, while the server-derived `playableStateScope` remains separately persisted exact-validated policy/routing/authorization/migration-fence evidence. Live and dry-run/test windows apply the cap independently, and a schedule in another game instance, namespace, region, or epoch cannot consume this window's cap. Candidates beyond this cap are dropped, not deferred, and surfaced through candidate audit plus exactly one `automation_script_timer_catchup_truncated_total{reason="resume_window_cap"}` increment when each candidate's durable settlement completes; they create no firing claim or firing. Every candidate included in the window's enumerated set must reach a durable outcome before completion: the window is marked `COMPLETE` only after selected candidates' firing or durable shared-admission-denial outcomes and all cap-excluded candidate outcomes are durable. Only a later recovery episode then allocates the next generation. These are target-state recovery guarantees; the current runtime's bounded per-observation catch-up does not yet prove the durable resume-window enforcement described here. - Leader changes and takeover reconciliation preserve each firing's declared lane and cost class and validate the current runtime epoch/fence before admitting it; stale or ambiguous claims are fenced and reconciled rather than reclassified or replayed as new work. - Catch-up truncation must use one stable fairness algorithm when due candidates exceed `SCRIPT_TIMER_CATCH_UP_MAX_FIRINGS_PER_RESUME`: - - Collapse each overdue schedule instance to its earliest missed tagged due point in its declared clock domain (`dueTickId` for tick/game time or `dueAt` for wall clock). Do not numerically compare tick IDs with wall-clock timestamps. Because each `resumeWindowId` is already scoped to one `` record, this cap is evaluated only within that full runtime-scope-and-mode window: tenant-local identifies its tenant owner and does not make it a tenant-wide pool, so candidates from another game instance, playable-state scope, region, or epoch never join this set. It is mode-isolated and does not arbitrate across tenants. Within that window's candidate set, order by bounded `priorityTag` (`high`, `normal`, `background`), then complete stable schedule-instance identity ASC. + - Collapse each overdue schedule instance to its earliest missed tagged due point in its declared clock domain (`dueTickId` for tick/game time or `dueAt` for wall clock). Do not numerically compare tick IDs with wall-clock timestamps. Because each `resumeWindowId` is already scoped to one `` record, this cap is evaluated only within that full runtime-scope-and-mode window; the server-derived `playableStateScope` is separately persisted exact-validated evidence and is not a uniqueness boundary. Tenant-local identifies its tenant owner and does not make it a tenant-wide pool, so candidates from another game instance, namespace, region, or epoch never join this set. It is mode-isolated and does not arbitrate across tenants. Within that window's candidate set, order by bounded `priorityTag` (`high`, `normal`, `background`), then complete stable schedule-instance identity ASC. - Admit catch-up firings in round-robin passes across distinct complete stable schedule-instance identities within that resume-window candidate set (the stable row identity defined above, including target scope and `isDryRun`), not merely `scheduleDefinitionId`, so independently materialized instances sharing one definition each receive an opportunity and one noisy instance cannot consume the entire resume window. `pluginVersionId` and `bindingId` remain due-candidate provenance, fence, and deduplication dimensions; they do not split stable fairness groups. Priority and every tie break retain stable schedule-instance identity ordering. Candidates admitted by tenant-local catch-up still enter the shared scheduler/cluster admission layer, where [ADR 0166](./decisions/adr-0166-attributable-script-breakers-and-tenant-first-fairness.md) tenant-first fairness precedes priority; catch-up cannot bypass per-tenant or cluster ceilings. - Admit at most one missed firing for any logical schedule instance in the complete `resumeWindowId`, using its earliest missed tagged due point as the coalesced identity. - Once the resume cap is reached, remaining overdue firings are truncated rather than deferred into an unbounded backlog; emit audit/metrics that distinguish how many were coalesced or dropped. @@ -159,19 +178,21 @@ The interval admission, durable-claim, artifact-estimate reservation, and retry/ #### Script Reload +This reload sequence is target-state behavior; the current implementation status above does not establish Redis-index rebuild or end-to-end reload/recovery proof. + - During reload, leaders set `reloadState=RELOADING` for the affected runtime scope after observing that Game Session has pinned a tenant-`READY` patch for that instance. `onLoad` is not part of this instance reload path; it has already completed as part of tenant patch readiness. Existing timer entries in the region index `automation:timer:{tenantRegionTag}` and any derived per-script projections remain in Redis but are treated as pending until reconciliation completes. - Once the exact Game Session `(scriptPatchVersion, scriptPinEpoch)` is committed and reconciliation succeeds, the leader: - re-reads its heartbeat checkpoint and the current `tickId`; - reconciles durable schedule definitions for the newly pinned exact `(scriptPatchVersion, scriptPinEpoch)` tuple before any timer is allowed to fire again, updating the instance-scoped `script_schedule_instances` rows first; - updates each explicitly preserved interval entry's authoritative due point (`dueTickId` or `dueAt`) after typed continuity compatibility checks: it applies the normative tick resume formula only to preserved tick timers, while compatible wall-clock continuity retains persisted `dueAt` and regenerates `nextRunAt`; reset, incompatible, or newly materialized replacement rows retain fresh due state; and - resumes normal scheduling for `onInterval` using the exact committed patch and pin epoch. No interval runs against a partially loaded script definition or a local active/latest pointer. -- If reload fails or durable reconciliation evidence is unavailable, the pending exact `(scriptPatchVersion, scriptPinEpoch)` tuple is retained with failed/fenced diagnostic state and any partially loaded schedule state is discarded. The affected runtime scope admits no new timer firing until reconciliation confirms the current exact pin tuple, schedule owner, scope, epoch, due state, and, for plugin-owned schedules, the captured `(pluginActivationEpoch, lifecycleRevision)` pair. Transient retryable reload, reconciliation, or authority-fence conditions retain each due candidate as durable nonterminal state/claim under the same `scheduleCandidateId` and canonical due point from the original exact tuple; while fenced, that state has no `finalStage`, `finalOutcome`, firing claim, or `scriptEventId`. If the captured exact tuple remains current when evidence reconciles, the same state may compare-and-set once into the firing path or one immutable terminal candidate audit; a lifecycle-revision mismatch fences that candidate under its captured pair, and reconciliation never refreshes or rebinds its historical evidence. `DRAINING` permits this only for already-admitted work whose winning admission/fence CAS committed before the durable drain barrier; a merely fenced candidate without that proof cannot create a firing. Only a changed identity tuple—such as patch, pin epoch, runtime region epoch, or `pluginActivationEpoch` (including a same-version plugin disable/re-enable)—displaces the old candidate, which remains fenced under its original identity and captured lifecycle pair (and may be terminal-marked as required), while target reconciliation derives a fresh, non-reused candidate identity only after durable reconciliation and before admission. Explicit continuity may carry stable schedule-row/due state but never rewrites candidate identity, and no `scriptEventId` is minted before the target candidate passes admission. A prior observed tuple may remain observable for diagnosis, but the scheduler must not use a "last known good" fallback to mint or execute new timer work. +- If reload fails or durable reconciliation evidence is unavailable, the pending exact `(scriptPatchVersion, scriptPinEpoch)` tuple is retained with failed/fenced diagnostic state and any partially loaded schedule state is discarded. The affected runtime scope admits no new timer firing until reconciliation confirms the current exact pin tuple, schedule owner, `playableStateNamespaceId`, separately persisted exact `playableStateScope` evidence, region epoch, due state, and, for plugin-owned schedules, the captured `(pluginActivationEpoch, lifecycleRevision)` pair. Transient retryable reload, reconciliation, or authority-fence conditions retain each due candidate as durable nonterminal state/claim under the same `scheduleCandidateId` and canonical due point from the original exact tuple; while fenced, that state has no `finalStage`, `finalOutcome`, firing claim, or `scriptEventId`. If the captured exact tuple remains current when evidence reconciles, the same state may compare-and-set once into the firing path or one immutable terminal candidate audit; a lifecycle-revision mismatch fences that candidate under its captured pair, and reconciliation never refreshes or rebinds its historical evidence. `DRAINING` permits this only for already-admitted work whose winning admission/fence CAS committed before the durable drain barrier; a merely fenced candidate without that proof cannot create a firing. Only a changed identity tuple—such as namespace, patch, pin epoch, runtime region epoch, or `pluginActivationEpoch` (including a same-version plugin disable/re-enable)—displaces the old candidate, which remains fenced under its original identity and captured lifecycle pair (and may be terminal-marked as required), while target reconciliation derives a fresh, non-reused candidate identity only after durable reconciliation and before admission. A presented scope mismatch is also fenced until authority proves the scope unchanged; an authority-proven scope transition starts a new lifecycle/namespace and cannot reuse the old candidate. Explicit continuity may carry stable schedule-row/due state but never rewrites candidate identity, and no `scriptEventId` is minted before the target candidate passes admission. A prior observed tuple may remain observable for diagnosis, but the scheduler must not use a "last known good" fallback to mint or execute new timer work. During reload, plugin-owned due candidates retain and revalidate the captured `(pluginActivationEpoch, lifecycleRevision)` pair alongside the exact script pin and runtime scope. A same-version/same-epoch `DRAINING` predecessor is usable only with ADR 0119's durable pre-`DRAINING` admission-CAS evidence; lifecycle revision remains non-identity evidence and does not authorize a new candidate. ### Explicit Continuity Across Script Transitions -The default for an authored interval at a script-patch, plugin-version, activation, disablement, rollback, or repin transition is cancel-and-recreate. Continuity is an explicit opt-in on both sides of the transition, keyed by `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, targetScopeType, targetScopeId}` and accepted only after typed interval/cadence/target compatibility checks. `pluginId` is the stable plugin owner; `pluginVersionId` and `scriptPatchVersion` remain exact provenance and execution-fence metadata. One-shot timers are outside this rule and must not be silently migrated or recreated because a `scheduleDefinitionId` matches. The full recovery clock and downtime contract remains in [ADR 0091](./decisions/adr-0091-class-specific-script-timer-clocks-and-recovery.md). +The default for an authored interval at a script-patch, plugin-version, activation, disablement, rollback, or repin transition is cancel-and-recreate. Continuity is an explicit opt-in on both sides of the transition, keyed by `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, playableStateNamespaceId, targetScopeType, targetScopeId}` and accepted only after typed interval/cadence/target compatibility checks plus exact validation of the separately persisted `playableStateScope` policy/routing/authorization/migration-fence evidence. `pluginId` is the stable plugin owner; `pluginVersionId` and `scriptPatchVersion` remain exact provenance and execution-fence metadata. One-shot timers are outside this rule and must not be silently migrated or recreated because a `scheduleDefinitionId` matches. An authority-proven playable-state scope transition starts a new playable-state lifecycle and selects or allocates a new namespace before fresh schedule identity is admitted; stale presented scope evidence may reuse the namespace-keyed identity only when authoritative scope is unchanged. The full recovery clock and downtime contract remains in [ADR 0091](./decisions/adr-0091-class-specific-script-timer-clocks-and-recovery.md). Timer reconciliation on patch or plugin change is a required part of reload and rollback safety: @@ -184,9 +205,9 @@ For plugin-owned schedules, the stable schedule row carries the mutable current - Implementations must persist a `scheduleSemanticsHash` or equivalent canonical normalized fingerprint with each compiled definition as diagnostic evidence. Hash equality cannot grant continuity and hash inequality alone cannot deny an otherwise valid explicit declaration. - When an instance observes a newly pinned exact `(scriptPatchVersion, scriptPinEpoch)` tuple, the scheduler must compare the durable schedules for the previously observed tuple with those for the newly pinned tuple before resuming timer admission. Plugin activation, disablement, rollback, and revocation perform the same comparison for `(pluginId, pluginVersionId, bindingId)`. - Schedules that do not exist in the newly pinned patch must be tombstoned so they can no longer generate triggers. When there is no replacement owner, disablement or revocation must fence admission and tombstone the displaced row atomically under the same control-plane operation; it must not fabricate a replacement schedule. -- For the default or incompatible path, a patch, plugin-version, activation, disablement, rollback, or repin transition uses cancel-and-recreate: when a replacement owner exists, reconciliation creates or confirms the target schedule generation with fresh due state before retiring or tombstoning the displaced row; when no replacement owner exists, it fences and tombstones the displaced row without fabricating a replacement. Continuity is preserved only when both source and target explicitly declare compatible continuity for the same stable logical key `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, targetScopeType, targetScopeId}`, `source.isDryRun` equals `target.isDryRun`, and interval kind, cadence unit/value, target binding, playable-state scope, and runtime fencing are compatible, with exact equality of the authoritative `playableStateNamespaceId` and active-instance/region binding (including `gameInstanceId`, `regionId`, and `regionEpoch`); an ordinary executor-fence handoff that preserves that instance/region binding is not itself a transition. A namespace or active-instance/region binding transition is therefore incompatible with in-place continuity and routes to a fresh `scheduleInstanceId` under the applicable reset ordering. Namespace transitions follow the retire-before-materialize barrier above; other replacement-owner resets may prepare a fresh non-admitting generation before the atomic retirement/activation step below. Only when all continuity conditions hold is the existing generation updated in place with the target ownership/pin metadata and recalculated due point. A missing declaration, dry-run mode mismatch, changed key/cadence/target, explicit reset, absent target, disabled/revoked owner, namespace or active-instance/region binding mismatch, or ambiguity forces the reset path. A same-version repin is still a new epoch transition: for a continuity-preserved row, reconciliation adopts the target exact `(scriptPatchVersion, scriptPinEpoch)` and associated mutable current pin/owner/provenance metadata on the active row before admission resumes; for the reset path, it creates or confirms the target row with that exact metadata before retiring the displaced row. Only the active row and pending mutable schedule state may be retired or rewritten; old-epoch firing claims and candidate/audit identities and outcomes retain their original tuple and may only be fenced or terminal-marked, never rewritten. Rollback follows the same rule and never infers continuity from history or hash similarity. +- For the default or incompatible path, a patch, plugin-version, activation, disablement, rollback, or repin transition uses cancel-and-recreate: when a replacement owner exists, reconciliation creates or confirms the target schedule generation with fresh due state before retiring or tombstoning the displaced row; when no replacement owner exists, it fences and tombstones the displaced row without fabricating a replacement. Continuity is preserved only when both source and target explicitly declare compatible continuity for the same stable logical key `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, playableStateNamespaceId, targetScopeType, targetScopeId}`, `source.isDryRun` equals `target.isDryRun`, and interval kind, cadence unit/value, target binding, separately persisted `playableStateScope` evidence, and runtime fencing are compatible, with exact equality of the authoritative namespace and active-instance/region binding (including `gameInstanceId`, `regionId`, and `regionEpoch`); an ordinary executor-fence handoff that preserves that instance/region binding is not itself a transition. A namespace or active-instance/region binding transition is therefore incompatible with in-place continuity and routes to a fresh `scheduleInstanceId` under the applicable reset ordering. An authority-proven playable-state scope transition likewise starts a new lifecycle and selects or allocates a new namespace; only stale presented scope evidence with unchanged authoritative scope may reuse the namespace-keyed identity. Namespace transitions follow the retire-before-materialize barrier above; other replacement-owner resets may prepare a fresh non-admitting generation before the atomic retirement/activation step below. Only when all continuity conditions hold is the existing generation updated in place with the target ownership/pin metadata and recalculated due point. A missing declaration, dry-run mode mismatch, changed key/cadence/target, explicit reset, absent target, disabled/revoked owner, namespace or active-instance/region binding mismatch, scope-evidence mismatch, or ambiguity forces the reset path. A same-version repin is still a new epoch transition: for a continuity-preserved row, reconciliation adopts the target exact `(scriptPatchVersion, scriptPinEpoch)` and associated mutable current pin/owner/provenance metadata on the active row before admission resumes; for the reset path, it creates or confirms the target row with that exact metadata before retiring the displaced row. Only the active row and pending mutable schedule state may be retired or rewritten; old-epoch firing claims and candidate/audit identities and outcomes retain their original tuple and may only be fenced or terminal-marked, never rewritten. Rollback follows the same rule and never infers continuity from history or hash similarity. - `controlPlaneRequestId` is the reconciliation idempotency key. The same nonblank value from the initiating patch pin, plugin activation, disable, rollback, or signer-revocation request must be persisted on and carried through every schedule-reconciliation step, including preserved-schedule updates, reset replacement, retirement, and retry; a sub-step must not mint a new reconciliation key. -- When explicit continuity is valid, reconciliation updates the existing stable row in place, adopting the exact target `(scriptPatchVersion, scriptPinEpoch)` and associated mutable current pin/owner/provenance metadata before admission resumes, while retaining immutable namespace evidence, and branches due-point recalculation by clock unit: preserved tick timers use the normative tick resume formula, while compatible wall-clock timers retain persisted `dueAt` and regenerate `nextRunAt` strictly as its projection. Target resume time does not alter the persisted deadline, and any wall-clock overdue state remains governed by its declared recovery/catch-up policy. Both branches retain the exact target metadata and reconciliation idempotency under `controlPlaneRequestId`; the tick branch must not retain an overdue point, neither branch restarts from deployment time nor replays every missed interval. The in-place update must be atomic or a resumable idempotent operation keyed by `controlPlaneRequestId`; it creates no replacement row, tombstone, firing claim, or `scriptEventId`. Previously captured candidate, firing-claim, audit, and work evidence remains immutable under its original tuple and identity; the scheduler mints firing claims and `scriptEventId` only after a due candidate passes admission. +- When explicit continuity is valid, reconciliation updates the existing stable row in place, retaining the exact `playableStateNamespaceId` identity and separately persisted `playableStateScope` evidence while adopting the exact target `(scriptPatchVersion, scriptPinEpoch)` and associated mutable current pin/owner/provenance metadata before admission resumes, and branches due-point recalculation by clock unit: preserved tick timers use the normative tick resume formula, while compatible wall-clock timers retain persisted `dueAt` and regenerate `nextRunAt` strictly as its projection. Target resume time does not alter the persisted deadline, and any wall-clock overdue state remains governed by its declared recovery/catch-up policy. Both branches retain the exact target metadata and reconciliation idempotency under `controlPlaneRequestId`; the tick branch must not retain an overdue point, neither branch restarts from deployment time nor replays every missed interval. The in-place update must be atomic or a resumable idempotent operation keyed by `controlPlaneRequestId`; it creates no replacement row, tombstone, firing claim, or `scriptEventId`. Previously captured candidate, firing-claim, audit, and work evidence remains immutable under its original tuple and identity; the scheduler mints firing claims and `scriptEventId` only after a due candidate passes admission. - For the reset or incompatible path when a replacement owner exists, replacement-before-retirement applies to plugin activation, repin, rollback, region/epoch changes, and other transitions except the namespace barrier above: reconciliation creates or confirms a fresh target `scheduleInstanceId` in a non-admitting prepared state with the target owner/binding and fresh due state, then one atomic durable transition, or resumable idempotent operation under the same `controlPlaneRequestId`, retires the displaced generation and makes the target the sole admitting row for its natural continuity key. The active-row uniqueness rule therefore never permits two generations to admit, and a prepared target cannot mint a candidate, firing claim, or `scriptEventId`. Namespace changes instead retire the source before any target row is materialized as required above. Disablement or signer revocation without a replacement fences admission and atomically tombstones the displaced row under the same `controlPlaneRequestId`. - Canceling outbox work items alone is insufficient for rollback safety; old-version timer schedules must also be reconciled so they cannot mint new `scriptEventId` values after the version has been displaced. @@ -195,7 +216,7 @@ Plugin example: - If plugin version `combat-helper@v4` and `combat-helper@v5` both compile a "reapply guard aura every 20 ticks" timer with `scheduleDefinitionId=combat-helper.guard-aura.v1`, explicit compatible continuity updates the existing stable schedule row from `v4` to `v5` ownership/pin metadata in place and recalculates its next due point before scheduling resumes; it does not create a replacement row. If continuity is absent or incompatible, the default reset path instead creates or confirms `v5` before retiring `v4`. The `v5` entry receives a firing claim and `scriptEventId` only after a due candidate passes admission. - If `combat-helper@v5` replaces that timer with a different logical schedule such as "pulse only while threat > 0" compiled to a different `scheduleDefinitionId`, reconciliation must create the new timer for `v5` before retiring the old `v4` timer under the same atomic-or-resumable rule. -Under this model, durable script schedules, quotas, and firing-claim de-duplication live in PostgreSQL, while `automation:timer:{tenantRegionTag}`, `script-scheduler:{tenantRegionTag}:lastTickId`, and related coordination keys form a reset-tolerant coordination layer for interval state. Stored entries and reconciliation logic remain instance-aware even though the Redis keys are region-scoped for slotting. The combination of tick heartbeat, durable firing claims, epoch-validated checkpoints, and script patch versioning preserves both correctness and determinism across failures and leader changes: losing or resetting these Redis keys may delay or slightly reshuffle timer firings within the tail-loss envelope but must not change which scripts are eventually scheduled according to their stored configurations or cause duplicate logical trigger creation. +Under this target-state model, durable script schedules, quotas, and firing-claim de-duplication live in PostgreSQL, while `automation:timer:{tenantRegionTag}`, `script-scheduler:{tenantRegionTag}:lastTickId`, and related coordination keys form a reset-tolerant coordination layer for interval state. Stored entries and reconciliation logic remain instance-aware even though the Redis keys are region-scoped for slotting. The combination of tick heartbeat, durable firing claims, epoch-validated checkpoints, and script patch versioning preserves durable identity and correctness-bearing one-shot outcomes across failures and leader changes: for best-effort recurring or advisory missed firings only, losing or resetting these Redis keys may delay, slightly reshuffle, or skip missed firings within the tail-loss envelope; future eligible cadence remains available. Correctness-bearing one-shots retain PostgreSQL-backed durable intent and settlement under their original identity, so Redis loss or reset cannot silently skip or remint them, and duplicate logical trigger creation is prevented. The current runtime does not yet prove this guarantee: re-observation can reseed a consumed one-shot, and current candidate/work-item identity omits `targetScopeType`/`targetScopeId`; those implementation gaps remain recorded above. ### Scheduler Leadership & Coordination @@ -221,7 +242,7 @@ See [Tick System and Runtime Design](./system-architecture-ticks.md) and [`autom - During reloads, triggers are paused or skipped while in-flight runs drain under existing concurrency settings: - New triggers for the affected runtime scope are not admitted; attempts to schedule additional runs receive explicit backpressure outcomes (`skipped_reloading` during `RELOADING`, `rollback_paused` during rollback pause). For a low-rate runtime event denied before handler resolution by rollback pause, ingress records `admissionOutcome=TRIGGER_ADMISSION_OUTCOME_BACKPRESSURE_ROLLBACK` and `admissionReason=rollback_pause` in `script_event_ingress_audit`; this is an event-scope outcome, not a handler `finalOutcome`. While that event-scope claim remains `IN_PROGRESS`, a concurrent retry may wait for the same claim to finalize or receive a retryable transport/application signal without an admission result; recovery resumes the same claim under fencing. Once finalized, a retry with the same event-scope identity replays permanent denials and successful final results exactly; an explicitly retryable transient backpressure denial stores retry eligibility and hint, and after that window the same identity may atomically reclaim and reopen the fenced claim for a new admission attempt, retaining the same `scriptEventId` and event identity. Once a handler has resolved, retries of that handler use its same full Trigger Identity and the same propagated `scriptEventId`; no separate handler ID is minted. A pre-handler `FAILED` reload is different: ingress records `admissionOutcome=TRIGGER_ADMISSION_OUTCOME_VERSION_UNAVAILABLE` and `admissionReason=reload_failed` with no retry hint, while timer candidates use the terminal `reloadState=FAILED` candidate-audit behavior in [Table 3](./system-architecture-scripting-normative-contract-tables.md#table-3-timer-semantics-matrix), with no firing claim or `scriptEventId` until durable recovery returns the scope to `IDLE`. Resolved-handler failures continue to use `finalOutcome` in `script_event_audit`. - In-flight runs remain bounded by each script’s configured `maxConcurrent` and `concurrencyPolicy` (for example, `queue_until_free`); any short per-script waiting queues are allowed to drain, but no new entries are added while `reloadState=RELOADING`. - - Pending timer-based triggers that became due during a transient retryable reload, reconciliation, or authority fence retain a durable due-candidate state/claim keyed by `scheduleCandidateId` and the canonical due point under the original exact tuple; scheduler timer indexes remain only rebuildable projections until exact version, epoch, and runtime-scope reconciliation completes. While fenced, this transient state has no `finalStage`, `finalOutcome`, firing claim, handler identity, or `scriptEventId`. If the captured exact tuple remains current when evidence reconciles, that state may compare-and-set once into the one firing path or one immutable terminal candidate audit; if a patch, plugin, or pin-epoch transition displaces the tuple, the old candidate remains fenced under its original identity (and may be terminal-marked as required), while the target schedule derives a new candidate identity only after durable reconciliation. Explicit continuity may carry stable schedule-row/due state but never rewrites candidate identity; the target candidate creates its firing claim and `scriptEventId` only after admission. Permanent or declared skips consume/drop their candidate under the declared policy, and an old scope or epoch remains fenced and is never reused. + - Pending timer-based triggers that became due during a transient retryable reload, reconciliation, or authority fence retain a durable due-candidate state/claim keyed by `scheduleCandidateId` and the canonical due point under the original exact tuple; scheduler timer indexes remain only rebuildable projections until exact version, epoch, namespace, separately persisted scope evidence, and runtime binding reconciliation completes. While fenced, this transient state has no `finalStage`, `finalOutcome`, firing claim, handler identity, or `scriptEventId`. If the captured exact tuple remains current when evidence reconciles, that state may compare-and-set once into the one firing path or one immutable terminal candidate audit; if a patch, plugin, or pin-epoch transition displaces the tuple, the old candidate remains fenced under its original identity (and may be terminal-marked as required), while the target schedule derives a new candidate identity only after durable reconciliation. A presented scope mismatch remains fenced until authority proves the scope unchanged; an authority-proven scope transition starts a new lifecycle/namespace. Explicit continuity may carry stable schedule-row/due state but never rewrites candidate identity; the target candidate creates its firing claim and `scriptEventId` only after admission. Permanent or declared skips consume/drop their candidate under the declared policy, and an old namespace, scope, or epoch remains fenced and is never reused. - On success, the scheduler observes the newly committed Game Session `(scriptPatchVersion, scriptPinEpoch)` for future triggers; on failure: - `activePatchVersion` remains an observed diagnostic value, but it does not authorize new timer work while reconciliation is unresolved; - the pending exact `(scriptPatchVersion, scriptPinEpoch)` tuple is marked failed/fenced along with an error reason, and leaders discard any partially loaded state for that tuple; diff --git a/design/architecture/system-architecture-spatial-and-ambient-effects-catalog.md b/design/architecture/system-architecture-spatial-and-ambient-effects-catalog.md index 53e06334a6..88da55057d 100644 --- a/design/architecture/system-architecture-spatial-and-ambient-effects-catalog.md +++ b/design/architecture/system-architecture-spatial-and-ambient-effects-catalog.md @@ -10,13 +10,13 @@ The target `DROP`/`PICKUP` contracts below are not yet fully implemented or prov ## Common Requirements (All Effects) -- [Transaction Strategies](./system-architecture-transactions.md) owns split spatial authority and operation-bound effect behavior. [Identifier Glossary](./system-architecture-identifier-glossary.md#cross-service-effect-identity) owns root `EffectId` and participant guard identity, while its [causal-read fence contract](./system-architecture-identifier-glossary.md#cross-service-causal-read-fence-identity) owns the causal floor and composite component-version identity. This catalog retains only effect-local writes, guards, and reconciliation consequences. +- [Transaction Strategies](./system-architecture-transactions.md) owns split spatial authority and operation-bound effect behavior. [Identifier Glossary](./system-architecture-identifier-glossary.md#cross-service-effect-identity) owns root `EffectId` and participant guard identity, while its [causal-read fence contract](./system-architecture-identifier-glossary.md#cross-service-causal-read-fence-identity) owns the causal floor and composite component-version identity. This catalog retains only effect-local writes, guards, and reconciliation consequences. The pending [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is non-authoritative. - Every effect must be scoped by instance identifiers. For room-scoped effects, this is `RoomInstanceRef = (tenantId, gameInstanceId, roomInstanceId)`. See `design/architecture/system-architecture-identifier-glossary.md`. -- Game Session assigns one stable root `EffectId` to each logical effect. Each participating owner derives a deterministic participant-guard identity from that root, the typed operation, and the target aggregate, and binds it to the immutable request digest and stored outcome. Matching retries return the prior result; a changed operation, target, or digest fails closed under the owner contract in [Transaction Strategies](./system-architecture-transactions.md). -- The default reconciliation policy is **retry until convergence using the same root `EffectId`**. Do not generate compensating deletes inside the tick loop. +- Game Session assigns one stable root `EffectId` to each command-root logical effect. Each participating owner derives its participant-guard identity from the persisted mutation `EffectId`—the root for a root mutation or the persisted generated-child `EffectId` for a child, with the enclosing root retained only as lineage—plus the typed operation and target aggregate, within the owner-declared runtime-family partition: S1/S2 use `(tenantId, playableStateNamespaceId)`, explicit S3 uses `(tenantId, gameInstanceId)`, and an unknown or unclassified family fails closed. The guard binds to the immutable request digest and stored outcome. Matching retries return the prior result, while a changed operation, target, partition, or digest fails closed under the owner contract in [Transaction Strategies](./system-architecture-transactions.md). +- The default reconciliation policy is **retry until convergence using the same persisted mutation `EffectId`**, retaining the enclosing root lineage where applicable. Do not generate compensating deletes inside the tick loop. - Presentation reads follow the causal-floor and component-proof contract in [Identifier Glossary](./system-architecture-identifier-glossary.md). Current `worldSnapshotId`/`entitySnapshotId` values are scope markers only. Effect entries below record only local invalidation consequences; floor allocation, propagation, response acceptance, and composite-identity rules remain in the canonical contract. - For World-owned door, weather, and hazard effects, the participant guard, typed ambient-state mutation, and World component-version advance commit in one World-local transaction. A matching replay returns the stored outcome without applying the mutation or incrementing the component version twice. The canonical transaction rule belongs in [Transaction Strategies](./system-architecture-transactions.md); this catalog records only the effect-local consequence and proof obligation. -- Set-state reconciliation must resolve the participant guard by the current root `EffectId`, typed operation, exact target aggregate, and immutable `requestDigest`. A matching guard returns its stored outcome; mutable state already matching the requested value is not replay evidence by itself. When a new request has no matching guard but the state is already satisfied, the owner records a new guarded no-op under that request's current `EffectId` and immutable digest. A missing, conflicting, or ambiguous guard remains reconciliation-required rather than being inferred as replay. +- Set-state reconciliation must resolve the participant guard within the same owner-declared runtime-family partition by the current persisted mutation `EffectId`, typed operation, exact target aggregate, and immutable `requestDigest`. A matching guard returns its stored outcome; mutable state already matching the requested value is not replay evidence by itself. When a new request has no matching guard but the state is already satisfied, the owner records a new guarded no-op under that request's current `EffectId` and immutable digest. A missing, conflicting, or ambiguous guard remains reconciliation-required rather than being inferred as replay; an unknown or unclassified runtime family fails closed. ## Cross-Region Effects and Reconciliation @@ -49,10 +49,10 @@ Required writes: Reconciliation: -- Retry World Management using the same root `EffectId` and participant guard until the World location/occupancy mutation converges under the current epoch/fence. +- Retry World Management using the same persisted mutation `EffectId` and participant guard until the World location/occupancy mutation converges under the current epoch/fence. For generated work, this is the recorded child `EffectId`; the enclosing root remains lineage only. - There is no Entity success/failure or retry branch for pure `MOVE`. An Entity leg exists only for a future MOVE variant that explicitly writes containment; that variant must declare Entity as a participant with its own write, guard, and reconciliation contract. -`MOVE` commits World location/occupancy before destination presentation. `DROP` and `PICKUP` commit entirely in Entity against the admitted room scope, using the shared actor-lock/executor-fence and durable-barrier contract defined in [Transaction Strategies](./system-architecture-transactions.md#drop-pickup-targeting-and-actor-fence-critical-section). Lock expiry or handoff cannot admit a conflicting `MOVE` while the barrier lacks terminal evidence; Game Session owns retry orchestration and invokes Game Logic to re-resolve stale evidence under the same root `EffectId`, preserving the `requestDigest`. This catalog records only the effect-local writes and reconciliation consequences. An item never has two holders and an actor never has two authoritative locations. +`MOVE` commits World location/occupancy before destination presentation. `DROP` and `PICKUP` commit entirely in Entity against the admitted room scope, using the shared actor-lock/executor-fence and durable-barrier contract defined in [Transaction Strategies](./system-architecture-transactions.md#drop-pickup-targeting-and-actor-fence-critical-section). Lock expiry or handoff cannot admit a conflicting `MOVE` while the barrier lacks terminal evidence; Game Session owns retry orchestration and invokes Game Logic to re-resolve stale evidence under the same command-root `EffectId`, preserving the `requestDigest`. This catalog records only the effect-local writes and reconciliation consequences. An item never has two holders and an actor never has two authoritative locations. ### Drop (Inventory → Ground) @@ -68,13 +68,13 @@ Required inputs: Required writes: - **World Management** - - No required write unless the game also models a world-side “sound/door/hazard reaction”; such reactions must be expressed as separate ambient effects with their own `EffectId` (derived deterministically from the parent). + - No required write unless the game also models a world-side “sound/door/hazard reaction”; such reactions must be expressed as separate ambient effects with their own persisted mutation `EffectId`. A generated child's recorded `EffectId` is its mutation identity; the enclosing root remains lineage only. - **Entity Management** - Move `itemInstanceId` into the synthetic room-ground container for `roomInstanceRef`. Reconciliation: -- Retry the Entity mutation using the same participant guard until it converges or is terminalized. Derived ambient reactions use deterministic child effect identities and explicit required/optional classification; do not undo a committed item move to compensate for an optional reaction. +- Retry the Entity mutation using the same persisted mutation `EffectId` and participant guard until it converges or is terminalized. Derived ambient reactions use their recorded child `EffectId` and explicit required/optional classification; do not undo a committed item move to compensate for an optional reaction. ### Pickup (Ground → Inventory) @@ -96,7 +96,7 @@ Required writes: Reconciliation: -- Retry the EMS move using the same root `EffectId` until applied. Treat an already-moved item as replay only when the stored participant guard matches the same root `EffectId`, immutable request digest, and exact actor-inventory destination. If the item is held by another actor/container or the destination differs, return a conflict/stale/reconciliation outcome rather than replay/no-op. +- Retry the EMS move using the same persisted mutation `EffectId` until applied; for generated work, use its recorded child `EffectId` and retain the enclosing root only as lineage. Treat an already-moved item as replay only when the stored [participant guard identity](./system-architecture-identifier-glossary.md#cross-service-effect-identity) matches the `PICKUP` typed operation, the same persisted mutation `EffectId`, the owner-declared runtime-family partition (`(tenantId, playableStateNamespaceId)` for S1/S2 or an explicitly classified `(tenantId, gameInstanceId)` for S3), and the immutable `requestDigest`, with exact target semantics of `{item: itemInstanceId (or the canonical stack/item target), source: the synthetic room-ground container for this RoomInstanceRef, destination: the actor-inventory container for this actorEntityId}`. If the item is held by another actor/container or the destination differs, return a conflict/stale/reconciliation outcome rather than replay/no-op. The World targeting attestation remains bound to the root `EffectId`, actor, exact room, epoch, fence, and request digest as specified above. ## Ambient Effects (World Management Authoritative) @@ -116,12 +116,12 @@ Required inputs: Required writes: - **World Management** - - Apply the door state mutation under the owner participant guard derived from the root `EffectId`, typed `DOOR_TOGGLE` operation, and target room/door aggregate, bound to the request digest and stored outcome. + - Apply the door state mutation under the owner participant guard for the persisted mutation `EffectId`, typed `DOOR_TOGGLE` operation, and target room/door aggregate, bound to the request digest and stored outcome. - **Target-state only:** advance the World-owned ambient component version used in the composite `LOOK` identity in that same local transaction so the Game Session presentation cache can invalidate. A matching guard replay returns the prior result without a second version increment. The current `worldSnapshotId` scope marker provides no freshness proof and is not a cache-invalidation authority. Reconciliation: -- Retry WMS with the same root `EffectId` until the participant guard and door mutation converge. The replay/no-op path is valid only when the stored guard matches `DOOR_TOGGLE`, the exact room/door target aggregate, and the immutable request digest. If no matching guard exists but the door is already in `targetState`, issue the current request under a new guard and record a guarded no-op; mutable door state alone never proves replay. A conflicting or ambiguous guard remains reconciliation-required. +- Retry WMS with the same persisted mutation `EffectId` until the participant guard and door mutation converge. The replay/no-op path is valid only when the stored guard matches `DOOR_TOGGLE`, the exact room/door target aggregate, and the immutable request digest. If no matching guard exists but the door is already in `targetState`, issue the current request under a new guard and record a guarded no-op; mutable door state alone never proves replay. A conflicting or ambiguous guard remains reconciliation-required. ### Weather Update @@ -139,7 +139,7 @@ Required writes: Reconciliation: -- After the selector is accepted, retry WMS with the same root `EffectId` until the participant guard and weather mutation converge. The replay/no-op path is valid only when the stored guard matches the typed weather operation, the exact World-selected target aggregate, and the immutable request digest. If no matching guard exists but weather is already at the requested value, issue the current request under a new guard and record a guarded no-op; mutable weather state alone never proves replay. Until the World weather contract defines the exact aggregate selector, every Weather request remains fenced/reconciliation-required and a same-state observation is not replay evidence. +- After the selector is accepted, retry WMS with the same persisted mutation `EffectId` until the participant guard and weather mutation converge. The replay/no-op path is valid only when the stored guard matches the typed weather operation, the exact World-selected target aggregate, and the immutable request digest. If no matching guard exists but weather is already at the requested value, issue the current request under a new guard and record a guarded no-op; mutable weather state alone never proves replay. Until the World weather contract defines the exact aggregate selector, every Weather request remains fenced/reconciliation-required and a same-state observation is not replay evidence. ### Hazard State Update (Gameplay-Authoritative) @@ -153,7 +153,7 @@ Required inputs: Required writes: - **World Management** - - Persist hazard state as typed ambient room state under the owner participant guard derived from the root `EffectId`, typed `HAZARD_STATE_UPDATE` operation, and target room/hazard aggregate, bound to the request digest and stored outcome. + - Persist hazard state as typed ambient room state under the owner participant guard for the persisted mutation `EffectId`, typed `HAZARD_STATE_UPDATE` operation, and target room/hazard aggregate, bound to the request digest and stored outcome. - **Target-state only:** advance the World-owned ambient component version used in the composite `LOOK` identity in that same local transaction so downstream LOOK/gameplay caches invalidate deterministically. A matching guard replay returns the prior result without a second version increment. The current `worldSnapshotId` scope marker provides no freshness proof and is not a cache-invalidation authority. Read/API contract: @@ -164,4 +164,4 @@ Read/API contract: Reconciliation: -- Retry WMS with the same root `EffectId` until the participant guard and hazard mutation converge. The replay/no-op path is valid only when the stored guard matches `HAZARD_STATE_UPDATE`, the exact room/hazard target aggregate, and the immutable request digest. If no matching guard exists but hazard state is already `targetState`, issue the current request under a new guard and record a guarded no-op; mutable hazard state alone never proves replay. A conflicting or ambiguous guard remains reconciliation-required. +- Retry WMS with the same persisted mutation `EffectId` until the participant guard and hazard mutation converge. The replay/no-op path is valid only when the stored guard matches `HAZARD_STATE_UPDATE`, the exact room/hazard target aggregate, and the immutable request digest. If no matching guard exists but hazard state is already `targetState`, issue the current request under a new guard and record a guarded no-op; mutable hazard state alone never proves replay. A conflicting or ambiguous guard remains reconciliation-required. diff --git a/design/architecture/system-architecture-temporal-workflows.md b/design/architecture/system-architecture-temporal-workflows.md index ed8ac794c8..2590cff8cf 100644 --- a/design/architecture/system-architecture-temporal-workflows.md +++ b/design/architecture/system-architecture-temporal-workflows.md @@ -15,7 +15,7 @@ Current status (non-authoritative summary; [Shared Runtime, Service Contracts, a - Automation Scripting hosts the `script-patch-readiness` workflow family for eligible non-empty `NotifyScriptVersionUpdate` notifications and durable `onLoad`/readiness progression. Target behavior reloads the complete notified patch through validation and `onLoad` to tenant `READY` before Game Session may pin or progress to it; Temporal coordinates that workflow but never becomes pin authority. Under [ADR 0115](./decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md), an immutable manifest that proves zero handlers may complete readiness as terminal `READY` with no synthetic handler work or workflow; an identifiable notification without that proof records terminal `FAILED` with bounded reason `zero_handler_manifest_unverifiable`. The current normal Game Design integration sends an empty `affectedScripts` list, so Automation returns before creating a readiness row and the conditional workflow start is skipped; that publication has no readiness candidate or workflow and cannot establish reload, `READY`, or pin evidence. - `common-saga` remains the canonical substrate for short synchronous orchestration that does not need durable workflow execution. -The World Management `world-lifecycle` family is the concrete lifecycle adopter governed by [ADR 0123](./decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md). Temporal coordinates prepare, activation, failure, termination, retries, waits, and operator progress; World Management's durable lifecycle row and epoch remain the authority for `PREPARING`, `ACTIVE`, `FAILED_PRE_ACTIVATION`, `TERMINATING`, and `TERMINATED`. Owner cleanup acknowledgements are read from durable owner state, and routine gameplay/tick paths never query Temporal or wait on cleanup. +The World Management `world-lifecycle` family is the concrete lifecycle adopter governed by [ADR 0123](./decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md). Temporal coordinates prepare, activation, failure, termination, retries, waits, and operator progress; World Management's durable lifecycle row and epoch remain the authority for `PREPARING`, `ACTIVE`, `FAILED_PRE_ACTIVATION`, `TERMINATING`, and `TERMINATED`. **Target-only:** owner cleanup acknowledgements are to be read from durable owner state before final termination. The current implementation has only a synchronous termination seam that calls Entity cleanup and hard-deletes a partial World runtime-row subset; it does not yet persist or read the frozen all-owner cleanup snapshot and per-owner acknowledgements required by ADR 0123. Routine gameplay/tick paths never query Temporal or wait on cleanup. ## Canonical Usage Boundary @@ -80,12 +80,12 @@ The current `businessStepKey` is an incomplete implementation encoding, not the Guidance: - `workflowFamily` is a stable design-level family such as `world-lifecycle` or `script-patch-readiness`. -- `scopeKey` is the narrow workflow scope that matters operationally, such as `world-instance`, `version`, or `game-instance`. -- `businessKey` is the stable caller-visible request identity or domain identity that makes retries idempotent. +- `scopeKey` is the narrow workflow scope that matters operationally, such as `world-instance`, `version`, or `game-instance`; for World lifecycle it is `game-instance`. +- `businessKey` is the stable caller-visible request identity or domain identity that makes retries idempotent. For World lifecycle it is `gameInstanceId`, a domain identity scoped by `tenantId` and `scopeKey`, not necessarily a globally unique token. Current adopter examples: -- `world-lifecycle` uses stable world-instance identity for its workflow business key. +- `world-lifecycle` uses `gameInstanceId` as its business key within the `tenantId` and `game-instance` scope. - full Game Design publish uses the caller-supplied `publish_request_id` from `PublishVersionRequest`, so retries converge on the same caller-visible durable workflow instead of minting a fresh internal UUID. - script-patch readiness uses the stable patch/readiness domain tuple documented in Automation Scripting. diff --git a/design/architecture/system-architecture-tick-concepts-and-invariants.md b/design/architecture/system-architecture-tick-concepts-and-invariants.md index dd81000216..233b0423cf 100644 --- a/design/architecture/system-architecture-tick-concepts-and-invariants.md +++ b/design/architecture/system-architecture-tick-concepts-and-invariants.md @@ -8,7 +8,7 @@ This document summarizes the **core concepts and invariants** of the FireMUD tic This document describes the target-state invariants. The target ownership model is a region-scoped Redis liveness lease paired with a durable executor fence and authority-fenced takeover/replay recovery for each ``. The live deployment has not yet converged on that region-scoped boundary: durable ownership is currently instance-scoped at `{tenantId, gameInstanceId}`, exposed through `RuntimeOwnershipStatus` with selected region fields and an opaque compare-and-match fence. True region-scoped lease/fence installation, `RegionStatus` authority, and takeover reconciliation remain target-state implementation and proof work. The invariants below therefore remain the canonical target contract and must not be read as a claim that the target recovery protocol is already live. -The exact `scriptPinEpoch` propagation and final same-version old-epoch rejection described above are target-state only. The live `EnqueueAutomationCommandIfAbsentRequest` carries `scriptPatchVersion` but not `scriptPinEpoch`, so the current Game Session boundary cannot reject same-version work from an older script pin epoch; the target invariant remains required and unimplemented at that boundary. +Where reached, lower-level instance-bound Automation and Game Session checks enforce exact `scriptPinEpoch` propagation and final same-version old-epoch rejection. The authenticated live `EnqueueAutomationCommandIfAbsent` receiver still fails closed with `FAILED_PRECONDITION` (`automation_admission_receiver_fence_unavailable`) before command or queue mutation, so those checks do not prove successful live receiver admission. Complete source/target remote tuple binding and broader target command identity remain target-state gaps, along with other identity gaps; the target invariant remains required at those boundaries. ## What This Covers @@ -44,7 +44,7 @@ When designing new tick-driven features, keep these invariants in mind: - **No cross-region locks** – cross-region interactions are modeled as messages, not shared locks or multi-region transactions. - **Idempotent side effects** – the region-scoped tick timeline `(region_epoch, tickId)` supplies ordering and fence context, while namespace-complete effect projections and owner-local effect guards ensure that replays after failure do not double-apply mutations. -The identifier glossary owns the stable root `EffectId` for a tick-driven mutation. A concrete ledger/guard/storage projection may include the namespace-complete tuple `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)` for scope, ordering, and target lookup, but that tuple is a storage projection rather than the root identity. `playableStateScope` is separately persisted and exact-validated evidence, not a replacement for `playableStateNamespaceId`; `regionEpoch` and `tickId` are ordering/timeline metadata, not effect-guard uniqueness dimensions. The ADR-level `targetAggregateIdentity` is represented by the target aggregate type and ID (or an equivalent explicitly proven collision-safe encoding). Participant guard logical uniqueness is exactly the root `EffectId`, typed operation, and target aggregate. If an owner-local physical partition is used, it is storage placement only and cannot alter logical uniqueness or deduplication; the immutable request digest is bound to the logical identity, while durable outcome/evidence state is mutable guard-row state protected by CAS. A bare tick tuple or bare `effectKey` is not sufficient for that guard contract. Ordinary retries and replay preserve the root `EffectId`, original participant ledger projection, and collision-safe guard identity; retry eligibility/attempt metadata is separate and must not mutate the original `regionEpoch`, `tickId`, `effectKey`, or root/typed-operation/target projection. A future linked-attempt or supersession model requires an explicit contract. A fresh root is allowed only for a **post-abandon re-drive** after conclusive terminal `ABANDONED` plus source-claim terminalization, later coordinate allocation, and durable lineage. +The identifier glossary owns the stable root `EffectId` for a tick-driven mutation. A root mutation uses the root `EffectId`; a generated child retains its persisted deterministic child `EffectId` as `effectId` and the enclosing root as `rootEffectId` lineage and reconciliation context. A concrete ledger/guard/storage projection may include the namespace-complete tuple `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)` plus `effectId` and `rootEffectId` for scope, ordering, target lookup, and lineage, but that tuple is a storage projection rather than the mutation identity. `playableStateScope` is separately persisted and exact-validated evidence, not a replacement for `playableStateNamespaceId`; `regionEpoch` and `tickId` are ordering/timeline metadata, not effect-guard uniqueness dimensions. The ADR-level `targetAggregateIdentity` is represented by the target aggregate type and ID (or an equivalent explicitly proven collision-safe encoding). Participant guard logical uniqueness uses the owner-declared runtime-family partition plus the persisted mutation `EffectId`—the root `EffectId` for root operations and the child `EffectId` for generated children—typed operation, and target aggregate: S1/S2 uses `(tenantId, playableStateNamespaceId)`, while only an explicitly owner-classified S3 family uses `(tenantId, gameInstanceId)`; unknown or unclassified families fail closed. Additional physical partitioning used only for storage placement cannot alter this logical identity or deduplication. The immutable request digest is bound to the logical identity, while durable outcome/evidence state is mutable guard-row state protected by CAS. A bare tick tuple or bare `effectKey` is not sufficient for that guard contract. Ordinary retries and replay preserve the persisted mutation identity, original participant ledger projection, enclosing root lineage, and collision-safe participant-guard identity; retry eligibility/attempt metadata is separate and must not mutate the original `regionEpoch`, `tickId`, `effectKey`, or effect/typed-operation/target projection. A future linked-attempt or supersession model requires an explicit contract. A fresh root is allowed only for a **post-abandon re-drive** after conclusive terminal `ABANDONED` plus source-claim terminalization, later coordinate allocation, and durable lineage. The deterministic allocator and versioned fan-out binding in the pending [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) remain conditional and non-authoritative; they do not change this guard contract. The tick system adopts the same **coordination timeline** concept as the Redis architecture: for each `` there is a canonical timeline defined by `(region_epoch, tickId)`. Within a given `region_epoch`: @@ -67,13 +67,13 @@ The main tick document contains the detailed rules and Redis key shapes behind e Lane fairness and the “one root actor action per eligible entity per tick” rule apply to steady-state execution within a stable `region_epoch`. Around measured coordination exposure and explicit resets: - Redis coordination loss and scoped resets may cause some actions near the end of the coordination timeline to be delayed, dropped, replayed, or slightly re-ordered; `ticks_exposed` is diagnostic only. -- In these cases, the system prioritizes convergence of each concrete namespace-complete ledger/guard/storage projection `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, region_epoch, tickId, effectKey, targetAggregateType, targetAggregateId)` to durably `APPLIED` or `ABANDONED` when the evidence policy permits terminalization, while retaining its root `EffectId` and participant guard contract. `playableStateScope` remains separately exact-validated evidence, and `region_epoch`/`tickId` remain ordering metadata rather than uniqueness dimensions. Inconclusive old-epoch work remains reconciliation-required under the [Inconclusive Old-Epoch Reconciliation Policy](./system-architecture-tick-failures-and-operations.md#inconclusive-old-epoch-reconciliation-policy). +- In these cases, the system prioritizes convergence of each concrete namespace-complete ledger/guard/storage projection `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, region_epoch, tickId, effectKey, targetAggregateType, targetAggregateId)` to durably `APPLIED` or `ABANDONED` when the evidence policy permits terminalization, while retaining its mutation `EffectId`, enclosing root lineage where applicable, and participant guard contract. `playableStateScope` remains separately exact-validated evidence, and `region_epoch`/`tickId` remain ordering metadata rather than uniqueness dimensions. Inconclusive old-epoch work remains reconciliation-required under the [Inconclusive Old-Epoch Reconciliation Policy](./system-architecture-tick-failures-and-operations.md#inconclusive-old-epoch-reconciliation-policy). - Designers should treat fairness guarantees as strong within a healthy epoch and best-effort across failures and resets; if a feature requires stronger guarantees around resets, that requirement must be called out explicitly and validated against the measured unreplicated-write-window SLO and ADR 0058 outcome class. -Conceptually, domain services treat Redis locks and leases as **opaque tick-engine concerns**: handlers receive the root `EffectId`, typed operation, target aggregate, immutable request digest, and their own idempotency state. Ledger/guard/storage adapters may additionally expose the namespace-complete tick projection `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, region_epoch, tickId, effectKey, targetAggregateType, targetAggregateId)` for scope and ordering; `playableStateScope` is exact-validated evidence and the timeline coordinates are ordering metadata, not guard uniqueness. Handlers never read `tick:{tenantRegionTag}:lock:` or `tick-executor-lease:{tenantRegionTag}` to make application-level decisions, nor do they depend on Cache/Rate-Limit Redis keys (for example `inventory:*`, `view:*`, `ratelimit:*`) for correctness or ordering. Cache usage, when present, is encapsulated inside domain services and affects only latency, not the tick engine’s notion of “what happened” or “in which order”. +Conceptually, domain services treat Redis locks and leases as **opaque tick-engine concerns**: handlers receive the mutation `EffectId` (root or persisted child), enclosing root lineage where applicable, typed operation, target aggregate, immutable request digest, and their own idempotency state. Ledger/guard/storage adapters may additionally expose the namespace-complete tick projection `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, region_epoch, tickId, effectKey, targetAggregateType, targetAggregateId)` for scope and ordering; `playableStateScope` is exact-validated evidence and the timeline coordinates are ordering metadata, not guard uniqueness. Handlers never read `tick:{tenantRegionTag}:lock:` or `tick-executor-lease:{tenantRegionTag}` to make application-level decisions, nor do they depend on Cache/Rate-Limit Redis keys (for example `inventory:*`, `view:*`, `ratelimit:*`) for correctness or ordering. Cache usage, when present, is encapsulated inside domain services and affects only latency, not the tick engine’s notion of “what happened” or “in which order”. - **Target-state automation identity:** Script-generated child dispatch persists the complete Command-Handoff Identity separately from the effect ledger/storage projection. The child identity is the complete source/target runtime scope plus `(automationDispatchId, commandOrdinal)`, as defined by the [normative Command-Handoff Identity table](./system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state). The complete applicable parent Trigger Identity, including `bindingId` when applicable, and `outboxWorkItemId` are retained for correlation only and are excluded from child uniqueness, deduplication, and replay selection. `scriptEventId` alone cannot distinguish fan-out commands. `effectKey` may encode the child pair only as deterministic descriptor/correlation metadata and scheduler tie-break metadata. It never replaces the root `EffectId`, typed operation, exact target aggregate, immutable request digest, sealed participant/manifest context, or digest-conflict enforcement. -- **Current-live automation identity:** The Game Session handoff does not yet carry `commandOrdinal` or the full Trigger Identity. Live gameplay staging requires a present, nonblank durable `commandId`, and `TickStagingService` derives `effectKey` as `command:`. The target-state exact pin tuple and `automationDispatchId` plus `commandOrdinal` effect identity are implementation gaps, not current behavior. +- **Current live boundary:** The Game Session handoff does not yet carry `commandOrdinal` or the full Trigger Identity. `TickStagingService` derives `effectKey` from `commandId`; it retains a command-text-plus-slot helper branch, but `createBatchForTick` calls `requireDurableCommandIdentifiers` before selection and `commandSelections` repeats that guard before `effectKey` is called. That helper branch is unreachable for durable gameplay-command staging, not a live fallback. `effectKey` is not the target-state automation identity, and current behavior must not be documented as though `(automationDispatchId, commandOrdinal)` were enforced live. ### Coordination Exposure and Tick Replay Window @@ -91,12 +91,12 @@ Redis coordination state has an environment-measured unreplicated-write exposure The tick system and the Redis-measured exposure SLO combine into a simple contract: -- For the complete expected concrete participant-projection set for each root effect, including each namespace-complete `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, region_epoch, tickId, effectKey, targetAggregateType, targetAggregateId)` projection linked to its root `EffectId` and guard contract, every expected projection must eventually have exactly one **terminal** outcome in PostgreSQL (`APPLIED` or `ABANDONED`) when the existing evidence policy permits terminalization. `playableStateScope` is exact-validated evidence, and `region_epoch`/`tickId` are ordering metadata; neither is a participant guard uniqueness dimension. Reconciliation must reject missing, extra, partial, or conflicting projections rather than treating one root row as sufficient, even if: +- For the complete expected concrete participant-projection set for each logical mutation, including each namespace-complete `(effect_id, root_effect_id, typed_operation, tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, region_epoch, tickId, effectKey, targetAggregateType, targetAggregateId)` projection keyed by its persisted mutation `EffectId`—the root `EffectId` for a root mutation or the child `EffectId` for a generated child—with any enclosing root retained separately as lineage and reconciliation context, every expected projection must eventually have exactly one **terminal** outcome in PostgreSQL (`APPLIED` or `ABANDONED`) when the existing evidence policy permits terminalization. `playableStateScope` is exact-validated evidence, and `region_epoch`/`tickId` are ordering metadata; neither is a participant guard uniqueness dimension. Reconciliation must reject missing, extra, partial, or conflicting projections rather than treating one mutation row or root row as sufficient, even if: - Coordination writes near the measured exposure window are dropped, delayed, or replayed, or - Executors crash and re-acquire leases under the same `region_epoch`. - Any work that cannot be safely replayed after Redis loss or tick re-execution must be: - Guarded with idempotency checks that detect and short-circuit replays, or - - Intentionally marked `ABANDONED` in the tick effect ledger with a precise reason only when durable evidence proves it was not applied and the existing policy permits terminalization (for example, reset scopes as described in the failures and operations doc). Inconclusive old-epoch work remains non-terminal reconciliation-required under its original root `EffectId`; reset scope alone does not authorize bulk terminalization. + - Intentionally marked `ABANDONED` in the tick effect ledger with a precise reason only when durable evidence proves it was not applied and the existing policy permits terminalization (for example, reset scopes as described in the failures and operations doc). Inconclusive old-epoch work remains non-terminal reconciliation-required under its original persisted mutation `EffectId`, with any enclosing `rootEffectId` retained separately as lineage and reconciliation context; reset scope alone does not authorize bulk terminalization. Players may observe brief rollbacks or duplicated feedback around failover boundaries, but they must never experience permanent double-application of critical effects or silent corruption of authoritative state. @@ -125,13 +125,14 @@ The registry and focused proof must reject scripts declaring or receiving more t ## Timers and Time Scaling (Conceptual) -Tick timers (cooldowns, regeneration, delayed effects) are: +Timer sources (including cooldowns, regeneration, and delayed effects) carry exactly one explicit due-domain tag and one corresponding due value: -- Stored in per-region sorted sets such as `timer:{tenantRegionTag}`, where the score is an absolute millisecond timestamp and each member encodes the target entity/effect. -- Evaluated using a single, consistent application time source (NTP-synchronized wall clock); Redis server time is not used for timer comparisons. -- Treated as absolute wall-clock due times: changing `tick_interval_ms` does not rescale existing timer scores, and any time-scaling logic must be applied when scheduling (producing a new `due_ms`), not by rewriting past timers. +- Tick/game timers use committed tick identifiers (`dueTickId`, or `due_tick_id` in storage fields) for eligibility and cadence. Wall-clock timers use one immutable absolute `dueAt` in epoch milliseconds; changing `tick_interval_ms` does not rescale it. +- When a wall-clock timer is admitted to a gameplay tick, the scheduler assigns a separate `due_tick_id` admission-order coordinate. That coordinate does not replace, mutate, or become an alias for the timer's `dueAt` due domain. +- Per-region projections such as `timer:{tenantRegionTag}` must preserve the tag and value for each member; a sorted-set score or other index representation must not imply a shared numeric domain. Tick IDs and epoch-millisecond values are never compared or aliased. +- Wall-clock eligibility uses one consistent application time source (NTP-synchronized wall clock); tick eligibility uses the committed region heartbeat/timeline. Redis server time is not used for either comparison. - Drained with bounded work per tick (for example, up to `game.tick-max-timers` timers per region per tick) so delayed or bursty timers do not turn a single tick into unbounded work. -- Implemented using deterministic, idempotent Lua scripts that accept `now_ms` as a caller-supplied `ARGV` value; scripts must not call Redis `TIME`, and AOF replay reuses the same `ARGV` values. +- Implemented using deterministic, idempotent Lua scripts that accept explicit caller-supplied `currentTickId` and, when evaluating a wall-clock source, `now_ms` values as `ARGV`; scripts must not call Redis `TIME`. Under Redis 7.2+ effect-based script replication, the AOF records the script's write effects and restart replays those recorded commands; it does not rerun the Lua script with the original `ARGV` values. `ARGV` fixes the time/tick inputs for the original execution. See the official [Redis scripting and effects-replication documentation](https://redis.io/docs/latest/develop/interact/programmability/eval-intro/). All writes to timer keys (`timer:{tenantRegionTag}`) are performed under the same region lease and Lua scripts as tick processing; domain services must not modify timer keys via ad-hoc Redis commands. This keeps timers and command queues in the same concurrency domain. @@ -145,7 +146,7 @@ Durations may be scaled dynamically: ## Bounded Effect Chaining -Generated effects are bounded by a shared bootstrap depth ceiling (`8`), deterministic root-chain count and cost budgets, and a deterministic per-target cap. Platform hard ceilings bound every setting; operators and authored features may lower them but may not raise them. Each child records immutable parent/root identity, `depth = parent.depth + 1`, and a digest-covered deterministic child ordinal. +Generated effects are bounded by a shared bootstrap depth ceiling (`8`), deterministic root-chain count and cost budgets, and a deterministic per-target cap. Platform hard ceilings bound every setting; operators and authored features may lower them but may not raise them. Each child records immutable parent/root identity, `depth = parent.depth + 1`, and an owner-defined child ordinal that is deterministically allocated, durably persisted, and reused on replay. The ordinal is ordering and audit metadata, not part of an effect digest. The pending [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is non-authoritative for the allocation mechanism. Admission evaluates all limits deterministically. Only the child that would exceed a limit is suppressed; committed parents and earlier children are not rolled back. Every authored child is classified as required or optional so suppression derives truthful `SUCCESS`, `PARTIAL`, or `FAILED` outcomes. Durable suppression evidence records root/parent identity, feature/script/version, child ordinal, limit reason and actual/configured values, classification, and resulting player outcome. Metrics use bounded reason/depth/cost/classification dimensions; raw identities remain audit data. See [ADR 0075](./decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md). @@ -172,14 +173,14 @@ These mode-aware metric families and formulas are target-only and currently unav Changing tick cadence is also constrained by replay determinism: - `tick_interval_ms` is fixed within a live `region_epoch`. -- Any cadence change that would alter timer ordering or due normalization requires an explicit `regionEpoch` bump and timer re-derivation/reconciliation for the affected region. +- Any cadence change that would alter tick-domain timer ordering or due normalization requires an explicit `regionEpoch` bump and timer re-derivation/reconciliation for the affected region; it does not rewrite an existing wall-clock `dueAt`. Worked cadence-change example: 1. Region `R7` is running at `tick_interval_ms = 100` in `regionEpoch = 13`. 2. Operators decide to move `R7` to `tick_interval_ms = 200`. 3. Game Session pauses the region and bumps `regionEpoch` to `14` rather than changing cadence in place. -4. Timer ordering state is re-derived for the new epoch, including canonical `due_tick_id` values for any timers that must survive the change. +4. Tick-domain timer ordering state is re-derived for the new epoch, including canonical `due_tick_id` values for tick timers that must survive the change. A wall-clock timer retains its immutable `dueAt` and receives a separate admission `due_tick_id` only when it is admitted to a tick. 5. The new epoch resumes at `lastCommittedTickId = -1`, so the first committable tick under the new cadence is `tickId = 0`. At runtime, once the target-only mode-aware metric capability is advertised and proven with fresh required series, observed tick durations are compared against lock TTLs using Prometheus-facing metric-family signatures (non-executable notation) such as `tick_execution_time_ms_p95{scope_class,tick_mode}` and `tick_execution_time_ms_p99{scope_class,tick_mode}` (derived from `tick_execution_time_ms_bucket{scope_class,tick_mode,le}` recording rules). Normal ticks use `tick_execution_time_ms_p99{scope_class,tick_mode="normal"} / on (scope_class,tick_mode) label_replace(tick_lock_ttl_ms{scope_class},"tick_mode","normal","scope_class",".*")` for detection and escalation; an admitted solo-budget tick uses `tick_execution_time_ms_p99{scope_class,tick_mode="solo"} / on (scope_class,tick_mode) label_replace(solo_lock_ttl_ms{scope_class},"tick_mode","solo","scope_class",".*")` instead. If the capability or any required series is absent or stale, these metrics and ratios are unknown/unavailable and cannot drive a decision. The `scope_class` value is the controlled aggregation class (`region`, `game_instance`, `tenant`, or `cluster`), never an individual region or other raw runtime identity; `tick_mode` is exactly `normal` or `solo`; the exact `` tuple and its health remain authoritative control-plane/runtime-health evidence. A class-level rollup cannot identify or set the health of any individual region. diff --git a/design/architecture/system-architecture-tick-execution-flows.md b/design/architecture/system-architecture-tick-execution-flows.md index 4dc1a55a1a..2dd505f784 100644 --- a/design/architecture/system-architecture-tick-execution-flows.md +++ b/design/architecture/system-architecture-tick-execution-flows.md @@ -12,8 +12,8 @@ This document describes the target execution model. The current live runtime is - the durable owner/status surface is currently `{tenantId, gameInstanceId}`-scoped rather than true region-scoped; - `GetGameplayCommandStatus` is the canonical command-status API, but its live fields and state vocabulary are narrower than the accepted lifecycle described below; -- the live batch/effect substrate exists with the current gameplay-command selected-work manifest on `tick_batch`, but timer/retry/remote-follow-up source-claim manifests, the target-state empty-cadence watermark path, cross-region result-return plumbing, and some richer command-status fields are still target-state follow-through. The current-live runtime has no dedicated target-state empty-cadence status transition or `StreamTickHeartbeats` path. -- the live gameplay-command staging path requires a nonblank durable `commandId` before Redis enqueue and durable batch staging; malformed pre-existing queue entries fail closed before staging and require owner reconciliation. The target path is fail-closed: Game Session assigns the stable root `EffectId` before acknowledgement and rejects before acknowledgement when assignment fails. Target tick execution also rejects any missing or blank root `EffectId` before staging, ledger, or domain writes; a no-ID bypass is permitted only for an explicitly non-tick/control-plane path. The following `ACCEPTED_VOLATILE` clause is exceptional recovery for an acknowledgement that was already issued; it never authorizes late `EffectId` assignment. If assignment failure is discovered after that acknowledgement, `LOST_BEFORE_STAGING` is limited to an eligible unbound `RECEIVED`/`ENQUEUED` command with no surviving batch; batch-bound or inconclusive work remains non-terminal/reconciliation-required and cannot become evidence-free `ABANDONED`. +- the live batch/effect substrate exists with the current gameplay-command selected-work manifest on `tick_batch`, but timer/retry/remote-follow-up source-claim manifests, the target-state empty-cadence watermark path, cross-region result-return plumbing, and some richer command-status fields are still target-state follow-through. The current-live `ScheduleRequest`, `RemoteCommandCoordinator`, `RemoteFollowup`, and `RemoteFollowupResult` models/migrations omit `targetPlayableStateNamespaceId`, so the complete target-scope and request-digest equality contract below is not live or proven. The current-live runtime has no dedicated target-state empty-cadence status transition or `StreamTickHeartbeats` path. +- `createBatchForTick` calls `requireDurableCommandIdentifiers` before selection, and `commandSelections` repeats that guard before `effectKey` is called. The retained command-text-plus-slot `effectKey` branch is therefore an unreachable helper/legacy path, not a live gameplay-staging fallback. For work-bearing commands from non-empty plans, the target path is fail-closed: Game Session assigns the stable root `EffectId` before acknowledgement and rejects before acknowledgement when assignment fails. The work-bearing tick path also rejects any missing or blank root `EffectId` before staging, ledger, or domain writes; a no-ID bypass is permitted only for an explicitly non-tick/control-plane path. Status-only no-effect `SUCCESS` follows the Enqueue rule below and is outside root allocation and tick recovery. Separately, [ADR 0016](./decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) and the [transactions command/effect boundary](./system-architecture-transactions.md) permit command-scope `LOST_BEFORE_STAGING`/`NOT_APPLIED` only when an unbound `ACCEPTED_VOLATILE` command (ingress status `RECEIVED` or `ENQUEUED`, with no surviving `tickBatchId`) is proven lost before durable staging. This loss is not an EffectId-assignment failure: assignment failure is rejected before acknowledgement, and any root `EffectId` assigned before acknowledgement remains the same stable identity. Batch-bound or inconclusive work remains non-terminal/reconciliation-required and cannot become evidence-free `ABANDONED`. The current helper branch does not imply that the target root-identity contract is live. Naming convention: API, workflow, and EffectId prose uses `regionEpoch`. Snake-case forms such as `region_epoch`, `target_region_epoch`, and `due_tick_id` are reserved for explicitly identified SQL/storage fields, Redis payloads/keys, or schema examples. @@ -43,16 +43,18 @@ Within a region’s tick, root actor commands and their effects proceed through 1. **Enqueue** - Game Session accepts commands from Telnet and WebSocket clients, AI, or automation. - - Commands are enqueued into per-entity (or occasionally per-region) queues such as `tick:{tenantRegionTag}:queue:`. + - Work-bearing commands are enqueued into per-entity (or occasionally per-region) queues such as `tick:{tenantRegionTag}:queue:`. + - If admission resolves to no gameplay effects, the same durable command-status transaction records the canonical terminal outcome (`ingressStatus=TERMINAL`, `executionOutcome=APPLIED`, and `gameplayResult=SUCCESS` under [ADR 0053](./decisions/adr-0053-command-atomicity-by-invariant-class.md) and [ADR 0016](./decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md)). This status-only write allocates no root `EffectId`, creates no effect ledger row or `tick_batch`, advances no tick-domain state, and does not enqueue the command; an accepted no-effect command therefore cannot remain `ENQUEUED`, and retries return its stored terminal outcome. Command-plan ordinal and ID-generation/allocation mechanics remain pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). 2. **Target Resolution (read-only)** - During the tick, the executor resolves targets from the pinned snapshot for that ``: - Single-target actions select a specific entity or room. - Multi-target actions derive a bounded set of entity IDs from local region state (room occupants, threat lists, groups). - This phase is read-only with respect to durable state; it decides *what* to touch without mutating Redis or PostgreSQL. 3. **Region-Local Mutations** - - Before target tick staging or any tick-domain ledger or domain write, Game Session requires a present, nonblank root `EffectId`; a missing or blank identity is a non-mutating rejection. No-ID bypasses are limited to explicitly non-tick/control-plane paths. The current live command/text fallback remains an implementation gap and is not target behavior. + - Before target tick staging or any tick-domain ledger or domain write, Game Session materializes and persists the command plan and root allocation under the canonical [Transaction Strategies](./system-architecture-transactions.md#command-atomicity-and-outcome-aggregation) contract. The execution flow consumes that frozen plan in its supplied semantic order and reuses the stored binding across retry, replay, and reconciliation; it does not infer or reallocate roots from tick selection. + - A conserved multi-participant operation normally shares one root with participant guards beneath it, but the command still uses ADR 0053's required/optional classification and co-location or reservation/escrow semantics. A root is not a global transaction or participant-set identity. For each root in a non-empty materialized plan, Game Session requires a present, nonblank root `EffectId` before target tick staging or any tick-domain ledger or domain write; a missing or blank identity is a non-mutating rejection. A zero-effect plan allocates no root, is not rejected for lacking one, and stages or writes no tick-domain state. No-ID bypasses are limited to explicitly non-tick/control-plane paths. The current live command/text fallback remains an implementation gap and is not target behavior. - For purely local effects, each Lua invocation acquires at most one entity lock under `tick:{tenantRegionTag}:lock:`; piecemeal multi-lock acquisition is prohibited. Multi-entity invariants use the owning transaction, durable effect workflow, or reservation/saga boundary described by [ADR 0074](./decisions/adr-0074-one-entity-lock-per-redis-script.md). - - Domain services apply changes under local transactions and the root-`EffectId` participant-guard contract owned by Transaction Strategies. + - Domain services apply changes under local transactions and the persisted-mutation-`EffectId` participant-guard contract owned by Transaction Strategies: a root mutation uses its root `EffectId`, while a generated child uses its persisted child `EffectId`; any enclosing `rootEffectId` is retained separately as lineage and reconciliation context. 4. **Cross-Region Effects (if any)** - For cross-region commands, the origin region: - Applies local-only effects first (for example, text feedback, animations). @@ -61,17 +63,18 @@ Within a region’s tick, root actor commands and their effects proceed through - Writers must persist `target_region_epoch` and `due_tick_id` from the same status read so retries and failover cannot shift eligibility non-deterministically. - Optionally writes a best-effort Redis hint marker such as `remote:{tenantInstanceTag}:` (for the target entity, with the tag derived from the target ``) to reduce latency when the target region drains follow-ups. - If the command needs to wait for remote completion, the origin region creates or updates a separate durable cross-region coordinator record. This waiting state is **not** kept as a non-terminal row inside the origin tick batch. - - Minimum coordinator fields include durable `coordinatorId`, `tenantId`, `originCommandId`, `originGameInstanceId`, `originRegionId`, `originRegionEpoch`, `originTickId`, target scope (`targetGameInstanceId`, `targetPlayableStateScope`, `targetRegionId`, `targetRegionEpoch`, `dueTickId`), exact target aggregate (`targetAggregateType`, `targetAggregateId`), the originating `originEffectId` and distinct target-leg `targetEffectId`, target-leg `typedOperation`, immutable `requestDigest`, and the sealed required-participant manifest (or immutable manifest reference plus digest). These identity/binding fields are compared on replay and a missing or conflicting value fails closed. The lifecycle is (`PENDING_REMOTE`, `REMOTE_APPLIED`, `REMOTE_ABANDONED`, `REMOTE_TIMEOUT_ABANDONED`, `LATE_RESULT_IGNORED`, `LATE_RESULT_RECONCILED`), with origin-timeline deadline (`originDeadlineRegionEpoch`, `originDeadlineTickId`; storage may use names such as `remote_deadline_region_epoch` / `remote_deadline_tick_id`), final player-facing/result-facing projection fields when applicable (`executionOutcome`, `gameplayResult`), and `updatedAt`. - - Target completion is returned through one durable origin-owned result path, not an unspecified transient message: - - the target leg writes an origin-addressed result or inbox row keyed to `coordinatorId` and repeats `originCommandId`, `originGameInstanceId`, origin region/epoch/tick, target game instance, `targetPlayableStateScope`, target region/epoch and `dueTickId`, the distinct target `targetEffectId`, typed operation, exact target aggregate, and one immutable follow-up binding/digest reference that binds the request digest and sealed-manifest context, + - The target `ScheduleRequest`, coordinator, follow-up, and origin-addressed result projections share the complete target scope `(targetGameInstanceId, targetPlayableStateNamespaceId, targetPlayableStateScope, targetRegionId, targetRegionEpoch, dueTickId)` and the immutable request digest covering that scope, exact target identity, operation, and sealed manifest binding. The coordinator and origin-addressed result also retain the complete original source scope `(tenantId, originGameInstanceId, originPlayableStateNamespaceId, originPlayableStateScope, originRegionId, originRegionEpoch, originTickId)`. `playableStateNamespaceId` is stable playable-state identity; `playableStateScope` is separately exact-validated evidence, as defined by [Multi-Tenancy](./system-architecture-multi-tenancy.md). Each projection preserves the applicable source and target fields for exact replay/result equality checks; missing, conflicting, or mismatched namespace, scope, target, or digest evidence fails closed. + - Minimum coordinator fields include durable `coordinatorId`, `tenantId`, `originCommandId`, `originGameInstanceId`, `originPlayableStateNamespaceId`, `originPlayableStateScope`, `originRegionId`, `originRegionEpoch`, `originTickId`, target scope (`targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetPlayableStateScope`, `targetRegionId`, `targetRegionEpoch`, `dueTickId`), exact target aggregate (`targetAggregateType`, `targetAggregateId`), the originating `originEffectId` and distinct target-leg `targetEffectId`, target-leg `typedOperation`, immutable `requestDigest`, and the sealed required-participant manifest (or immutable manifest reference plus digest). These identity/binding fields are compared on replay and a missing or conflicting value fails closed. The lifecycle is (`PENDING_REMOTE`, `REMOTE_APPLIED`, `REMOTE_ABANDONED`, `REMOTE_TIMEOUT_ABANDONED`, `LATE_RESULT_IGNORED`, `LATE_RESULT_RECONCILED`), with origin-timeline deadline (`originDeadlineRegionEpoch`, `originDeadlineTickId`; storage may use names such as `remote_deadline_region_epoch` / `remote_deadline_tick_id`), final player-facing/result-facing projection fields when applicable (`executionOutcome`, `gameplayResult`), and `updatedAt`. + - Target completion is returned through one durable origin-owned result path, not an unspecified transient message. The current live coordinator and result projection schemas do not yet carry the complete source and target tuples described here; this remains target-state contract, not a claim of schema implementation: + - the target leg writes an origin-addressed result or inbox row keyed to `coordinatorId` and repeats `originCommandId`, `tenantId`, `originGameInstanceId`, `originPlayableStateNamespaceId`, `originPlayableStateScope`, origin region/epoch/tick, target game instance, `targetPlayableStateNamespaceId`, `targetPlayableStateScope`, target region/epoch and `dueTickId`, the distinct target `targetEffectId`, typed operation, exact target aggregate, and one immutable follow-up binding/digest reference that binds the request digest and sealed-manifest context, - the row records the target terminal outcome and any command-specific result payload needed by origin reconciliation; it is not correlated only by the target `gameInstanceId` or a transient message ID, - - origin-side processing claims and applies that result idempotently when advancing the coordinator lifecycle. Acceptance of a result that has a dependent child effect is crash-safe: the durable acceptance transition cannot commit without a deterministic child-effect intent. The result acceptance and child intent commit in one durable transaction where they share an owner, or a resumable durable acceptance intent records both before either is treated as accepted. Replays reuse the child identity and the exact accepted-result digest; missing, extra, partial, or conflicting intent/projection evidence fails closed. This is an acceptance/intent durability invariant, not another coordinator outcome. + - origin-side processing claims and applies that result idempotently when advancing the coordinator lifecycle. Acceptance of a result that has a dependent child effect is crash-safe: the durable acceptance transition cannot commit without a deterministic child-effect intent. The result acceptance and child intent commit in one durable transaction where they share an owner, or a resumable durable acceptance intent records both before either is treated as accepted. Replays reuse the child identity and the exact accepted-result digest; missing, extra, partial, or conflicting intent/projection evidence fails closed. This is an acceptance/intent durability invariant, not another coordinator outcome. Exact opaque allocation remains non-authoritative in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). - The target region later drains these follow-ups into its own tick pipeline and applies them under its lease and locks. 5. **Completion / Finalization (optional)** - Many commands do not need global awareness of “all regions finished”; origin and target regions can operate independently with eventual consistency. - For flows that truly require end-to-end completion (for example, complex cross-region trades), the origin region tracks participating-region outcomes in that separate coordinator record and later applies a final status in a subsequent origin-region tick only under the command family’s ADR 0053 declaration. `PARTIAL` is a permitted terminal subset only when declared before execution; unresolved required work, inconclusive evidence, or a timeout that does not prove a permitted terminal combination remains `PENDING`/reconciliation-required. -Every phase must use its phase-specific durable identity so replays after failure do not double-apply logical work. Command ingress uses `(tenantId, gameInstanceId, commandId)`; source claims and selection use the durable source identity (such as a timer member ID, retry member ID, or follow-up row ID) together with its bound target/timeline; tick effects retain their root `EffectId` and participant guards; and cross-region completion uses the coordinator identity plus the target ledger/result identity. Ordinary retry/replay preserves each identity, including the root `EffectId` and original participant ledger/guard projection. Retry eligibility/attempt metadata is separate and must not rewrite the original `regionEpoch`, `tickId`, `effectKey`, or root/typed-operation/target projection; a future linked-attempt or supersession model requires an explicit contract. A fresh root is reserved for a **post-abandon re-drive**, which requires a conclusively terminal `ABANDONED` effect and terminalized source claim, a later coordinate, a fresh root and participant projections, and durable lineage to the original identities. A command or source item may cross tick boundaries without changing its ingress or source identity. +Every phase must use its phase-specific durable identity so replays after failure do not double-apply logical work. Command ingress uses `(tenantId, gameInstanceId, commandId)`; source claims use their durable owner identity and bound target/timeline; staged effects use their persisted mutation identity and participant guards; inbound/remote, timer, retry, and generated work retain their owner/source identities; and cross-region completion uses the coordinator plus target ledger/result identity. Command-root allocation detail remains pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). Ordinary retry/replay preserves persisted effect identity. Retry metadata never rewrites the original timeline or root/operation/target projection. A post-abandon re-drive follows its source owner's admission and identity contract while retaining lineage. A command or source item may cross tick boundaries without changing its ingress or source identity. ### Command Ingress Acknowledgement Contract (Required) @@ -107,7 +110,7 @@ Ingress deduplication is not sufficient on its own: every accepted command must - `RETRY_QUEUED` means the command has already reached `BOUND_TO_BATCH` and its current retry source is enqueued. The prior batch binding remains part of the command lifecycle; retry source state does not make it a new ingress command. - These legacy values are non-terminal. They must not be exposed as new canonical terminal outcomes, and purge/recovery must classify the current attempt by the durable batch binding rather than by the legacy label alone. - Required recovery behavior: - - Region/tenant/cluster resets and coordination-loss reconciliation may assign `LOST_BEFORE_STAGING` only to an `ACCEPTED_VOLATILE` record whose `ingressStatus` is `RECEIVED` or `ENQUEUED` and which has no surviving `tickBatchId`. `BOUND_TO_BATCH` and `TERMINAL` records are never eligible for this ingress-only loss outcome. The decision must use one owner-defined CAS/version-fenced transition so a concurrent bind wins; this rule does not authorize terminalizing batch-bound effects whose old-epoch evidence is inconclusive, which remain non-terminal reconciliation work under the original root `EffectId`. + - Region/tenant/cluster resets and coordination-loss reconciliation may assign `LOST_BEFORE_STAGING` only to an `ACCEPTED_VOLATILE` record whose `ingressStatus` is `RECEIVED` or `ENQUEUED` and which has no surviving `tickBatchId`. `BOUND_TO_BATCH` and `TERMINAL` records are never eligible for this ingress-only loss outcome. The decision must use one owner-defined CAS/version-fenced transition so a concurrent bind wins; this rule does not authorize terminalizing batch-bound effects whose old-epoch evidence is inconclusive, which remain non-terminal reconciliation work under their original persisted mutation `EffectId`, with any enclosing `rootEffectId` retained separately as lineage and reconciliation context. - For eligible `ACCEPTED_VOLATILE` records, `LOST_BEFORE_STAGING` is an expected terminal outcome and must be returned by command-status APIs/events rather than leaving the command indefinitely deduplicated with no execution result. `ACCEPTED_DURABLE` records, including those still before batch binding, follow their feature-specific durable intake replay/re-drive contract and are never classified as `LOST_BEFORE_STAGING` by this reset rule. - Re-sends with the same `(tenantId, gameInstanceId, commandId)` after a terminal outcome return that prior terminal outcome and must not enqueue a new logical command. - Re-sends with a new `commandId` remain new commands. @@ -225,7 +228,7 @@ At each tick for a ``, the executor: - Phase 2 selects at most one root intentional actor action per eligible entity under the actor-action lane’s ordering and budget; a completed start-of-tick passive effect may make an entity ineligible, but selected-yet-uncompleted or deferred passive work does not, and passive work never consumes its actor-action slot. - Phase 3 admits only effects generated by the phase-2 selected actor actions under the passive/effect budget. Generated effects cannot recursively grant another root actor action in the same tick. - Passive or inbound work becoming due after start selection, or deferred because of lane, per-entity, cost, or region budget overflow, affects a later tick without changing its persisted ordering inputs or stable identity. - - Within one entity's eligible queue, orders work by the persisted tuple `(priority, due_tick_id, entity_enqueue_seq, source_kind, commandId_or_effectKey)`. `entity_enqueue_seq` is monotonic within the entity's current region epoch and assigned by the owning Game Session admission/scheduling path. Same-tick derived children use the persisted parent order plus deterministic child ordinals rather than completion timing. + - Within one entity's eligible queue, orders work by the persisted tuple `(priority, due_tick_id, entity_enqueue_seq, source_kind, commandId_or_effectKey)`. `entity_enqueue_seq` is monotonic within the entity's current `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch)` scope and assigned by the owning Game Session admission/scheduling path. Same-tick derived children use the persisted parent order plus deterministic child ordinals rather than completion timing. - Across eligible entities, persisted rotating/deficit scheduling accounts for declared work cost and advances only with the durable selected batch. Permanently eligible non-best-effort work receives capacity within a healthy epoch; bounded aging or `maxDeferralTicks` applies where declared. Source quotas may bound intake inside a lane but cannot bypass lane fairness or create a competing scheduler. - Each work item type (queued command, timer, retry, remote follow-up) must expose its declared phase, lane, cost class, and stable persisted ordering inputs so selection can be reproduced across retries and failover. New work sources must not introduce undocumented scheduler precedence. - After ordering, the executor locks or reserves the selected source entries with their source-specific ownership checks while they remain discoverable. These locks prevent competing executors from selecting the same candidates but are not a substitute for durable source claims. @@ -234,7 +237,7 @@ At each tick for a ``, the executor: - A fenced owner transaction compare-and-sets the expected `regionEpoch`, `executorFence`, and current `lastCommittedTickId`, then advances exactly one canonical `lastCommittedTickId` without creating a `tick_batch`, selected-work manifest, effect ledger row, Redis `pending` entry, entity lock, or domain RPC. A newly due source racing this check is serialized by the same owner transaction: either it is included in a normal batch or the empty CAS loses and the source remains due for the next attempt. - After the durable status transition commits, Game Session emits the target-state `StreamTickHeartbeats` heartbeat for that `(regionEpoch, tickId)`; heartbeat emission is post-commit and never the authority. Canonical `PAUSED` and `STALLED` states freeze the empty path and do not advance the timeline. This target-state branch is not implemented in the current-live instance-scoped owner/progress adapter. 3. Atomically binds selected work: - - While the candidate locks are held, Game Session atomically creates the durable PostgreSQL `tick_batch`, its selected-work manifest, `SCHEDULED` ledger rows, and source claims in one transaction for the complete `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)` scope. Any selected command also moves to `BOUND_TO_BATCH` in that transaction. + - While the candidate locks are held, Game Session atomically creates the durable PostgreSQL `tick_batch`, its selected-work manifest, `SCHEDULED` ledger rows, and source claims in one transaction for the complete `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)` runtime coordinate. The selected-work manifest exact-binds the active `playableStateNamespaceId` and separately persisted `playableStateScope` as immutable execution evidence; missing, stale, mixed, or mismatched namespace/scope evidence fails before batch admission rather than creating a second scheduler partition. Neither namespace nor scope changes tick-batch uniqueness or scheduler partitioning. Any selected command also moves to `BOUND_TO_BATCH` in that transaction. - For remote follow-ups, only that transaction may set the batch claim or remove the row from the due set. A rollback releases the candidate lock and leaves the follow-up discoverable for a later selection. 4. Stages effects: - This step is allowed only after the durable PostgreSQL `tick_batch`, ledger rows, and source claims have committed. Redis `pending` is staging/acceleration coordination only; it is never the authoritative record or a prerequisite that can precede durable batch creation. @@ -259,7 +262,7 @@ The lane is explicit metadata, not an inferred property of the source kind: acto - A wall-clock timer remains eligible from its immutable `dueAt` (`now >= dueAt`). Once eligible, one durable firing-claim/admission transaction reads the authoritative target timeline and assigns/persists exactly one target `regionEpoch` and `due_tick_id` ordering coordinate (normally the next committable tick), together with the source claim. Retries and replays reuse those persisted values and never recompute them from cadence or wall time. An epoch change follows old-epoch reconciliation and new admission; it never rebinds the old firing. - The within-entity tuple uses the persisted admission `due_tick_id` for wall-clock timers and the persisted `dueTickId` for tick timers. Wall-clock timestamps and tick IDs are different domains and must not be compared numerically. - `entity_enqueue_seq`: - - Strictly increasing across all candidate work sources for one entity within its current `` scope. The owning Game Session admission/scheduling path assigns and persists it; it is not a region-global, tenant-only, game-instance-only, or cross-region counter. + - Strictly increasing across all candidate work sources for one entity within its current `` scope. The owning Game Session admission/scheduling path assigns and persists it; it is not a region-global, tenant-only, game-instance-only, or cross-region counter. - A reset bumps `regionEpoch` and restarts `tickId` at `0`, creating a new entity-local sequence domain for new-epoch work. Old-epoch ordering identities remain immutable and are not rebound even if a sequence value is reused in the new epoch. - `source_kind`: - Fixed, low-cardinality source classification (`command`, `retry`, `timer`, `remote_followup`, `generated_effect`) and the fourth tuple component. @@ -293,10 +296,10 @@ Conceptually, tick commit proceeds through these phases: - Target-state winner rule: - The target-state winner is the transaction that successfully creates the tuple-unique `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)` row while holding a revalidated Redis lease and the authoritative current `regionEpoch`/`executorFence` pair. - If a competing executor finds that the existing row carries the authoritative current epoch and an `executorFence` exactly equal to the current status, it must reuse that row as authoritative state for replay/continuation. If the batch carries a different fence, it is prior-fence work; the current owner must pause and reconcile or abandon it before staging a new tick. Unequal opaque fence bytes establish no ordering and are not evidence that either fence is newer. - - If the current owner encounters prior-fence work, it must not continue that batch on the hot path or transfer it based on inferred fence recency. It pauses the affected region and uses the fence-guarded recovery path while preserving the unique tick coordinate, manifest, effect identities, and command bindings where proof permits; inconclusive old-epoch work remains non-terminal reconciliation work under its original root `EffectId`. + - If the current owner encounters prior-fence work, it must not continue that batch on the hot path or transfer it based on inferred fence recency. It pauses the affected region and uses the fence-guarded recovery path while preserving the unique tick coordinate, manifest, effect identities, and command bindings where proof permits; inconclusive old-epoch work remains non-terminal reconciliation work under its original persisted mutation `EffectId`, with any enclosing `rootEffectId` retained separately as lineage and reconciliation context. - If recovery or transfer preconditions fail or any effect might have started, reconciliation must not bulk-abandon the batch. It determines each effect from durable domain state and authoritative effect guards: an effect becomes `APPLIED` only when that evidence proves it is reflected, becomes `ABANDONED` only when that evidence proves it was not applied, and otherwise remains `SCHEDULED`. `reconciliation_required`, its reason, the observed epochs/fences, and the last proof attempt are recovery metadata outside the closed effect status enum; they are not another effect state. - After obtaining the domain evidence, one fence-guarded Game Session PostgreSQL transaction must atomically persist all conclusive effect outcomes together with the corresponding command statuses and source-claim disposition. If any effect is inconclusive, the transaction records reconciliation-required metadata, leaves its effect and dependent command/source claim non-terminal, and keeps the region paused. Unresolved work is ineligible for ordinary effect retry, Redis retry insertion, source requeue, source-claim release, batch transfer, or commit-watermark advancement. - - Independently retryable work becomes eligible for a **post-abandon re-drive** only after the original effect is conclusively `ABANDONED` and its command/source claim is terminalized in that same transaction. The recovery controller must then eventually assign that work a later `(regionEpoch, tickId)` coordinate and new `tick_batch_id`, a fresh root `EffectId` with its ledger/participant-guard projections, and a new retry/source-claim identity before the region resumes; it records lineage to the original identities and never reuses or requeues into the old coordinate. Ordinary retry/replay keeps the original root `EffectId`. Until that fresh-root allocation succeeds, the work remains durable recovery work and cannot return to an ordinary queue. + - Independently retryable work becomes eligible for a **post-abandon re-drive** only after the original effect is conclusively `ABANDONED` and its command/source claim is terminalized in that same transaction. The recovery controller must then eventually assign that work a later `(regionEpoch, tickId)` coordinate and new `tick_batch_id`, a fresh identity under the applicable owner contract with its ledger/participant-guard projections, and a new retry/source-claim identity before the region resumes. If it is re-admitted as a command, the accepted source/command owner contract governs its fresh root allocation and lineage; this post-abandon allocation is not governed by pending [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). It records lineage to the original identities and never reuses or requeues into the old coordinate. Ordinary retry/replay keeps the original mutation `EffectId`. Until fresh identity admission succeeds, the work remains durable recovery work and cannot return to an ordinary queue. - If the caller's expected epoch or fence is not current in authoritative status, the caller is stale. It must stop without modifying the batch, replaying effects, or requeueing source work. It must never infer recency from `executorFence`, create a second batch for the same unique coordinate, or requeue work into that same coordinate. - The target-state tick-batch record stores at minimum: - `tick_batch_id` @@ -307,9 +310,9 @@ Conceptually, tick commit proceeds through these phases: - `status` (`CREATED`, `REDIS_STAGED`, `COMMITTED`, `ABANDONED`) - `tick_batch.status` is batch lifecycle state, not tick-effect-ledger state; effect-ledger `status` remains closed to `SCHEDULED`, `APPLIED`, and `ABANDONED`. Reconciliation-required flags, reasons, ownership observations, and proof attempts are recovery metadata and never extend that enum. - the selected-work manifest for this batch - - an immutable collision-safe pending envelope for each staged member carrying the exact `tick_batch_id` plus the complete root `EffectId`/participant projection, or an equivalent exact ledger-row identity; `effect_key` remains descriptor metadata only and is not sufficient correlation by itself + - an immutable collision-safe pending envelope for each staged member carrying the exact `tick_batch_id` plus the complete mutation `effect_id`/participant projection (with `root_effect_id` retained for lineage), or an equivalent exact ledger-row identity; `effect_key` remains descriptor metadata only and is not sufficient correlation or replay identity by itself - The selected-work manifest is the authoritative record of which source items were chosen for the tick before Redis staging. At minimum, each selected item records: - - the batch scope `(tenantId, gameInstanceId, regionId, regionEpoch)`; `entity_enqueue_seq` values are allocated monotonically per entity within that complete scope. A `regionEpoch` reset starts a new entity-local sequence domain; old-epoch ordering identities remain immutable and are never rebound. + - the batch runtime scope `(tenantId, gameInstanceId, regionId, regionEpoch)` plus exact bound `playableStateNamespaceId` and separately persisted `playableStateScope` execution evidence; both values are immutable and exact-compared on replay/readback. Missing, stale, mixed, or mismatched namespace/scope evidence fails closed. `entity_enqueue_seq` values are allocated monotonically per entity within that complete runtime-and-namespace context. Namespace and scope evidence do not extend tick-batch uniqueness or the scheduler timeline. A `regionEpoch` reset starts a new entity-local sequence domain; old-epoch ordering identities remain immutable and are never rebound. - `lane` (`actor_action` or `passive_effect`) declared by the work source - explicit semantic `phase`; ordering and comparisons are phase-local or phase-aware - bounded `cost_class` declared by the work source and consumed by the applicable lane budget @@ -363,22 +366,22 @@ Conceptually, tick commit proceeds through these phases: 4. Under the current `regionEpoch` and exact `executorFence`, the executor creates the `tick_batch` and `SCHEDULED` ledger rows, then stages the sealed manifest. Every durable write compares the current epoch and fence. 5. Immediately before authoritative effect dispatch, executor revalidates the same Redis lease token and expected epoch; commit watermark advancement succeeds only under the current exact `executorFence`. Prior-fence work is reconciled or abandoned and does not advance commit state. 2. **Redis staging complete** - - After the durable batch exists, the executor stages the selected effects into `tick:{tenantRegionTag}:pending`, carrying an immutable collision-safe envelope for each staged member: the exact `tick_batch_id` plus the complete root `EffectId`/participant projection or an equivalent exact ledger-row identity. `effect_key` remains descriptor metadata, not the correlation identity. Stage, commit, rollback, and cleanup preserve the envelope unchanged; recovery accepts or clears pending state only after exact set equality with the durable batch/ledger expected set, so a count or digest alone is insufficient. + - After the durable batch exists, the executor stages the selected effects into `tick:{tenantRegionTag}:pending`, carrying an immutable collision-safe envelope for each staged member: the exact `tick_batch_id` plus the complete persisted mutation `EffectId`/participant projection (root ID for a root mutation, child ID for a generated child, with `rootEffectId` retained separately as lineage) or an equivalent exact ledger-row identity. `effect_key` remains descriptor metadata, not the correlation identity. Stage, commit, rollback, and cleanup preserve the envelope unchanged; recovery accepts or clears pending state only after exact set equality with the durable batch/ledger expected set, so a count or digest alone is insufficient. - `tick:{tenantRegionTag}:pending` is an acceleration/coordination structure. The durable tick-batch plus ledger rows are the authoritative record of what the tick intended to stage. 3. **Domain application** - - Domain services process staged effects under idempotent root-`EffectId` participant guards and update authoritative PostgreSQL state in their own databases. - - Game Session records the outcome of each effect in its tick effect ledger (`SCHEDULED` → `APPLIED` or `ABANDONED`) only when the durable domain evidence and existing recovery policy permit that transition; inconclusive old-epoch work remains non-terminal reconciliation work under its original root `EffectId`. Domain services do not write to the Game Session ledger directly. + - Domain services process staged effects under participant guards keyed by the persisted mutation `EffectId` (root ID for a root mutation, child ID for a generated child), with `rootEffectId` retained separately as lineage, and update authoritative PostgreSQL state in their own databases. + - Game Session records the outcome of each effect in its tick effect ledger (`SCHEDULED` → `APPLIED` or `ABANDONED`) only when the durable domain evidence and existing recovery policy permit that transition; inconclusive old-epoch work remains non-terminal reconciliation work under its original mutation `EffectId`, with enclosing `rootEffectId` retained as lineage and reconciliation context. Domain services do not write to the Game Session ledger directly. 4. **Commit visibility** - - For a non-empty batch, once all ledger rows that belong to that tick batch are terminal (`APPLIED` or `ABANDONED`) under the existing evidence policy, the target-state deployment advances the commit authority `RegionStatus.lastCommittedTickId` for the current `regionEpoch` under the same `executorFence`, and only then emits the target-state tick heartbeat for that `(regionEpoch, tickId)`. An inconclusive old-epoch row remains non-terminal and blocks this advancement. A truly empty boundary uses the separate fenced one-tick status transition and post-commit heartbeat branch above, with no batch ledger. The current-live deployment instead advances the committed tick fields on `RuntimeOwnershipStatus` under the current-live opaque fence; `ObserveRuntimeTickProgress` reports that progress, and neither `RegionStatus` nor `StreamTickHeartbeats` is implied to be live. + - For a non-empty batch, the current-epoch commit predicate: terminal (`APPLIED` or `ABANDONED`) evidence under the existing evidence policy is required for every eligible ledger row in that tick's complete expected current-epoch participant set. Once that predicate holds, one fenced durable commit boundary transitions `tick_batch.status` to `COMMITTED` and advances the commit authority `RegionStatus.lastCommittedTickId` for the complete current scope under the same `executorFence`; only then may the target-state tick heartbeat be emitted. Inconclusive old-epoch rows remain non-terminal reconciliation work outside this current-epoch commit predicate; they may still block unsafe next-tick progression, reset-scope convergence, or reopening. A truly empty boundary uses the separate fenced one-tick status transition and post-commit heartbeat branch above, with no batch ledger. The current-live deployment instead advances the committed tick fields on `RuntimeOwnershipStatus` under the current-live opaque fence; `ObserveRuntimeTickProgress` reports that progress, and neither `RegionStatus` nor `StreamTickHeartbeats` is implied to be live. - Cross-region coordinator rows such as `PENDING_REMOTE` are not part of this terminal set; they are durable workflow state outside the committing tick batch. 5. **Coordination cleanup** - - A final commit/cleanup script clears the `pending` entry for the tick and releases any entity locks for that region. + - A final commit/cleanup script clears the `pending` entry for the tick and releases any entity locks for that region only after exact equality between the pending envelope set and the durable batch/ledger expected set has been established. `expected_effect_count` and any digest are diagnostic hints and cannot authorize cleanup on their own. - Cleanup is a required part of “tick is no longer in flight”; if an executor crashes after commit visibility but before cleanup, crash recovery must clear/abandon the `pending` entry before any subsequent tick stages new work. From the perspective of the `(regionEpoch, tickId)` timeline: - A tick is `durable_committed` once: - - For a non-empty tick, all ledger rows owned by that tick batch for `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)` have reached a terminal state (`APPLIED` or `ABANDONED`) where the evidence policy permits terminalization; inconclusive old-epoch work remains non-terminal and prevents this boundary. A truly empty tick instead proves the authoritative no-due-work/source-claim condition and commits the fenced one-tick status transition, and + - For a non-empty tick, the current-epoch commit predicate: terminal (`APPLIED` or `ABANDONED`) evidence is required, where the evidence policy permits terminalization, for every eligible ledger row in that tick's complete expected current-epoch participant set. Inconclusive old-epoch rows remain non-terminal reconciliation work outside this current-epoch commit predicate; they may still block unsafe next-tick progression, reset-scope convergence, or reopening. A truly empty tick instead proves the authoritative no-due-work/source-claim condition and commits the fenced one-tick status transition, and - The target-state commit authority `RegionStatus.lastCommittedTickId`, or the current-live committed tick fields on `RuntimeOwnershipStatus`, has advanced to that `(regionEpoch, tickId)` under the applicable fence. `ObserveRuntimeTickProgress` may confirm current-live progress but does not replace the durable authority. - A tick is `coordination_cleared` once: - There is no remaining `pending` entry for that tick in Redis and lock cleanup for that tick has completed. @@ -387,7 +390,7 @@ From the perspective of the `(regionEpoch, tickId)` timeline: - AOF replay or measured coordination loss may cause staging scripts to be re-run; domain idempotency guards and the ledger ensure that replays converge to the same terminal outcome. - Recovery treats PostgreSQL as the source of truth for staging intent: - `tick_batch` exists, Redis `pending` missing: - - Recovery replays directly from the durable batch manifest and `SCHEDULED` ledger rows to drive effects to terminal `APPLIED` or `ABANDONED` outcomes only when durable evidence permits; inconclusive old-epoch work remains non-terminal reconciliation work under its original root `EffectId`. Missing Redis state is not treated as “no work existed”. + - Recovery replays directly from the durable batch manifest and `SCHEDULED` ledger rows to drive effects to terminal `APPLIED` or `ABANDONED` outcomes only when durable evidence permits; inconclusive old-epoch work remains non-terminal reconciliation work under its original mutation `EffectId`, with enclosing `rootEffectId` retained as lineage and reconciliation context. Missing Redis state is not treated as “no work existed”. - Before changing any `SCHEDULED` row, one Game Session durable transaction uses the applicable recovery CAS: target-state reads and locks `RegionStatus` for the complete region scope, requires exact current `regionEpoch`/`executorFence` equality and a matching `contextDigest` against the batch’s sealed execution-context digest or referenced sealed context; current-live instead reads and locks the current instance-scoped `RuntimeOwnershipStatus`, requires exact `regionEpoch`/opaque `executorFence` equality, and verifies the complete selected-work manifest plus `manifest_digest` against durable source, ledger, and participant evidence without requiring sealed execution context. The batch’s captured fence alone is not authority; a mismatch or incomplete set affects zero rows and fails closed. Domain-service evidence and guards remain in their own service-local transactions, so this CAS does not imply a cross-service database transaction. - First implementation does **not** re-stage old ticks through the normal hot-path `pending` scripts once Redis state is missing. The durable batch manifest is authoritative for what was selected, and replay proceeds without requiring the old tick to be materialized back into Redis. - If source entries were intentionally left in place until `REDIS_STAGED`, recovery may reconcile those source structures against the durable batch manifest to clean up or reclassify them, but it must not re-select different work for the same `tick_batch_id`. @@ -397,10 +400,10 @@ From the perspective of the `(regionEpoch, tickId)` timeline: - Recovery pauses the region, marks the batch inconsistent, and requires reconcile tooling before ticks resume. Silent “best effort” continuation is not allowed. - If a crash occurs after `durable_committed` but before `coordination_cleared`, recovery must finish cleanup before the next tick stages new work; this window does not regress the durable commit watermark. -The **TickScheduler** in Game Session enforces a **single in-flight tick per region** invariant and derives tick positions from durable state: +The **TickScheduler** in Game Session enforces a **single in-flight tick per runtime region** invariant and derives tick positions from durable state: - A region is considered busy while prior durable or coordination state has not reached `coordination_cleared`: this includes an existing non-terminal `tick_batch`, any `SCHEDULED` ledger rows, or `tick:{tenantRegionTag}:pending` for an in-flight `tickId`. Missing Redis `pending` does not make unfinished durable work idle. -- The scheduler does not start a new tick for that `` until the previous tick is `coordination_cleared` as part of normal cleanup or explicitly handled during crash recovery. +- The scheduler does not start a new tick for that `` until the previous tick is `coordination_cleared` as part of normal cleanup or explicitly handled during crash recovery. Every admitted work item must exact-match that active instance's bound `playableStateNamespaceId`; namespace is sealed execution evidence, not a second tick timeline or scheduler partition. - The target-state scheduler obtains the current `(regionEpoch, tickId)` baseline and commit authority from `RegionStatus` through `GetRegionTickStatus`. The current-live scheduler obtains owner, fence, and committed tick fields from `RuntimeOwnershipStatus` through `GetRuntimeOwnershipStatus`, and uses `ObserveRuntimeTickProgress` as the live region progress feed; neither deployment treats `tick:{tenantRegionTag}:meta.current_tick_id` as the authority. - Target-state scheduler and recovery tooling determine recency only from authoritative status/CAS of the current `regionEpoch`/`executorFence` pair. A caller whose expected pair is not current is stale; a batch carrying a different fence is prior-fence work that must be reconciled or abandoned before a new tick is staged. Opaque fence bytes are never ordered. - Current-live tooling compares the current `regionEpoch` and opaque `executorFence` for exact equality only; a mismatch fails closed and never supports an older/newer ordering claim. The complete target install/revalidate and takeover proof remains unshipped. @@ -449,9 +452,9 @@ Best-effort hint markers (`remote:{tenantInstanceTag}:`) are only allo Cross-region flows participate in the same coordination timeline and reset rules as purely local ticks: -- Each leg of a cross-region command has a stable root `EffectId`; its origin/target ledger and follow-up storage projections retain the specific scope/timeline on that region plus the distinct target-leg `targetEffectId`, typed operation, immutable request digest, sealed manifest binding, and exact target aggregate. `effectKey` remains descriptor/correlation metadata only, never uniqueness or guard authority. The payload also carries exact target identity plus required ownership, location, and aggregate-version preconditions; a matching target epoch alone is insufficient, and any identity, operation, digest, manifest, or target conflict fails closed. +- Each cross-region mutation leg has its own persisted mutation `EffectId`: `originEffectId` for the origin leg and `targetEffectId` for the target leg; an enclosing command/root `EffectId`, when present, remains lineage and reconciliation context rather than collapsing the legs into one participant identity. The origin/target ledger and follow-up storage projections retain the specific scope/timeline on that region plus the applicable leg identity, typed operation, immutable request digest, sealed manifest binding, exact target `playableStateNamespaceId`, separately persisted and exact-validated target `playableStateScope` fence evidence, and exact target aggregate. The target leg is inbound/remote follow-up work: its deterministic `targetEffectId` is bound to the durable coordinator/follow-up identity under the remote-flow owner contract and is not a command-plan `planOrdinal` allocation unless the target explicitly materializes a new admitted command. `effectKey` remains descriptor/correlation metadata only, never uniqueness or guard authority. The payload also carries exact target identity plus required ownership, location, and aggregate-version preconditions; a matching target epoch alone is insufficient, and any identity, scope, operation, digest, manifest, or target conflict fails closed. The pending [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is not current target state; its proposed child-manifest schema/serializer/digest binding is not an accepted requirement. - Any origin-side waiting or aggregation state for those legs lives in a separate durable coordinator record. It must not keep the origin tick batch open or prevent `lastCommittedTickId` from advancing. -- When a region/tenant/cluster reset bumps `regionEpoch` for a region, any surviving `SCHEDULED` ledger rows or follow-ups from the old epoch are reconciled under the existing evidence policy: only conclusively unapplied work may converge to `ABANDONED`, while inconclusive work remains non-terminal under its original root `EffectId`; none is silently retried on the new epoch. +- When a region/tenant/cluster reset bumps `regionEpoch` for a region, any surviving `SCHEDULED` ledger rows or follow-ups from the old epoch are reconciled under the existing evidence policy: only conclusively unapplied work may converge to `ABANDONED`, while inconclusive work remains non-terminal under its original mutation `EffectId`, with any enclosing root retained as lineage; none is silently retried on the new epoch. - Origin regions must treat: - Explicit, evidence-backed `ABANDONED` outcomes from target-region effects as a failed remote leg and, where relevant, surface that status to players (for example, “the remote portion of your action failed”). - Timeouts waiting for remote results as a failed remote leg only when the existing policy proves no required mutation succeeded and the command family permits that terminal combination; a timeout or multi-leg failure alone does not authorize `PARTIAL`, and unresolved or inconclusive required work remains `PENDING`/reconciliation-required. @@ -499,7 +502,7 @@ Worked reset example: ## Tick Chaining and Reentrant Effect Control -Some effects (for example, explosions, chained spells, scripted traps) spawn follow-up actions. Each root chain is bounded by the shared bootstrap depth ceiling (`8`), deterministic total count and cost budgets, and a deterministic per-target cap. A generated child records immutable parent/root identity, `depth = parent.depth + 1`, and a digest-covered deterministic child ordinal. Admission suppresses only the child that would exceed a limit; committed parents and earlier children remain authoritative. Required/optional authored classification derives truthful `SUCCESS`, `PARTIAL`, or `FAILED` outcomes, and every suppression records durable evidence with bounded metric labels. Generated effects remain passive/effect work and cannot grant another root actor action in the same tick. See [ADR 0075](./decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md). +Some effects (for example, explosions, chained spells, scripted traps) spawn follow-up actions. Each root chain is bounded by the shared bootstrap depth ceiling (`8`), deterministic total count and cost budgets, and a deterministic per-target cap. A generated child records immutable parent/root identity, `depth = parent.depth + 1`, and an owner-defined deterministic child ordinal allocated and persisted by the owning contract for replay-stable reuse. Script-generated command children additionally retain the applicable `automationDispatchId` and `commandOrdinal`; the generic generated-child ordinal replaces neither script-handoff field, and exact retries reuse the same complete binding. When the chain is under an admitted command, it remains beneath that command's root; otherwise it retains its owner/source-specific root identity and does not synthesize a command plan. Admission suppresses only the child that would exceed a limit; committed parents and earlier children remain authoritative. Required/optional authored classification derives truthful `SUCCESS`, `PARTIAL`, or `FAILED` outcomes, and every suppression records durable evidence with bounded metric labels. Generated effects remain passive/effect work and cannot grant another root actor action in the same tick. See [ADR 0075](./decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md). The pending [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is non-authoritative. ## Worked Example: Cross-Region Lifesteal Command @@ -518,10 +521,10 @@ To illustrate how cross-region flows compose from the phases above, consider a * - It may also write a best-effort hint marker such as `remote:{tenantInstanceTag}:` (for the target entity under the target ``) to reduce latency, but correctness does not depend on that marker. - In the next tick for ``, the target region’s executor: - Computes the damage amount as a percentage of the target’s authoritative current HP. - - Acquires the target’s lock (`tick:{tenantRegionTag}:lock:`) and applies damage via Entity Management under the stable target-leg root `EffectId` and its derived guard. - - Writes a durable origin-addressed result row for region A containing `coordinatorId`, `originGameInstanceId`, `originRegionId`, `originRegionEpoch`, the target leg identity, `casterEntityId`, the actual `damageApplied`, the exact accepted-result digest, and the target terminal outcome. Origin reconciliation verifies those fields against its durable coordinator row before accepting the result. Acceptance cannot become durable without the deterministic child-heal intent: the accepted result and child intent commit together when co-located, or a resumable durable acceptance intent records both before acceptance is acknowledged. + - Acquires the target’s lock (`tick:{tenantRegionTag}:lock:`) and applies damage via Entity Management under the target leg’s persisted mutation `EffectId` and its operation/target guard; any enclosing root remains lineage and reconciliation context. + - Writes a durable origin-addressed result row for region A containing `coordinatorId`, `originGameInstanceId`, `originRegionId`, `originRegionEpoch`, the target leg identity, `casterEntityId`, the actual `damageApplied`, the exact accepted-result digest, and the target terminal outcome. Origin reconciliation verifies those fields against its durable coordinator row before accepting the result. Acceptance cannot become durable without a persisted child-heal intent: the accepted result and child intent commit together when co-located, or a resumable durable acceptance intent records both before acceptance is acknowledged. 4. **Heal Leg (origin region)** - - Only after existing coordinator reconciliation accepts the target result does region A record the actor-generated “apply lifesteal heal” effect for the caster. A rejected or abandoned result creates no heal effect; an accepted heal has a deterministic, stable idempotent child `EffectId` derived from the accepted result and is not a new root actor command. Acceptance replay reuses that child identity and the exact accepted-result digest; it cannot create a second heal intent or silently accept a conflicting result. + - Only after existing coordinator reconciliation accepts the target result does region A record the actor-generated “apply lifesteal heal” effect for the caster. A rejected or abandoned result creates no heal effect; an accepted heal uses its persisted child `EffectId` under the applicable accepted effect-identity contract and is not a new root actor command. This example does not require deriving child identity from the accepted result. Acceptance replay reuses that persisted child identity and the exact accepted-result digest; it cannot create a second heal intent or silently accept a conflicting result. The allocation proposal in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) remains pending and non-authoritative. - In a subsequent tick for ``, the executor: - Acquires the caster’s lock. - Applies a heal up to `damageApplied` (subject to HP rules) using Entity Management and tick idempotency. @@ -533,6 +536,6 @@ To illustrate how cross-region flows compose from the phases above, consider a * Throughout this sequence: -- Each leg is idempotent through its stable root `EffectId` and derived operation/target guard in the domain service. The heal child is idempotent through the accepted-result digest and child identity; its acceptance/replay rule is a local durability consequence, not a new outcome state. +- Each leg is idempotent through its persisted mutation `EffectId` and operation/target guard in the domain service; the enclosing root remains lineage and reconciliation context. The heal child is idempotent through the accepted-result digest and child identity; its acceptance/replay rule is a local durability consequence, not a new outcome state. - Region executors never hold cross-region locks; they coordinate via queued commands, durable follow-up records, and durable origin-addressed result rows. - Retries due to lock contention or transient failures are handled by the standard retry queues and idempotent handlers in each region without breaking the overall experience. diff --git a/design/architecture/system-architecture-tick-failures-and-operations.md b/design/architecture/system-architecture-tick-failures-and-operations.md index 29adb9890f..ad00ecf5a1 100644 --- a/design/architecture/system-architecture-tick-failures-and-operations.md +++ b/design/architecture/system-architecture-tick-failures-and-operations.md @@ -14,7 +14,9 @@ This document describes the full target-state recovery and operator model. Curre - the live owner/status API is `GetRuntimeOwnershipStatus`, not yet a full region-scoped status surface; - the live fence token is opaque and compare-and-match based; - the live `tick_batch` / `tick_effect` ledger is real and now carries the current gameplay-command selected-work manifest on `tick_batch`, including current-boundary `enqueueSeq`, source metadata, and digest-checked replay reuse for surviving staged batches; live selected-work manifests do not yet preserve the required declared `phase`, `lane`, and `cost_class` metadata. The live `enqueueSeq` is allocated by one database-wide sequence; the region-scoped, cross-source allocator defined below is target-state. Timer/retry/remote-follow-up source-claim manifests, region-scoped replay controller breadth, and cross-region result-return semantics also remain target-state follow-through. -- the live gameplay-command staging path does not yet provide the complete target automation handoff identity: it derives `effectKey` from `commandId` and uses a deterministic text/slot fallback when no command ID is available. The target fail-closed contract below assigns the stable root `EffectId` before acknowledgement when possible and rejects before acknowledgement when assignment fails. If an already acknowledged `ACCEPTED_VOLATILE` command cannot receive that identity, `LOST_BEFORE_STAGING` remains limited to eligible `RECEIVED`/`ENQUEUED` work with no surviving batch; batch-bound or inconclusive work remains non-terminal/reconciliation-required and is never evidence-free `ABANDONED`. This document does not claim that target behavior is already live. +- The live gameplay-command staging path requires a present, nonblank durable `commandId` before Redis enqueue or durable batch staging, and malformed pre-existing entries fail closed before staging. `effectKey` is derived as `command:`; the retained text/slot helper fallback is unreachable through `createBatchForTick` and `commandSelections`, which require durable command identifiers before selection. This still does not provide the complete target Automation handoff identity. For work-bearing commands from non-empty plans, the accepted target path requires stable root `EffectId` assignment before acknowledgement, rejects before acknowledgement if assignment fails, and requires the persisted nonblank root before staging, ledger, or domain writes. Status-only no-effect `SUCCESS` follows the canonical [Enqueue rule](./system-architecture-tick-execution-flows.md) and is outside this staging/recovery path. An already acknowledged `ACCEPTED_VOLATILE` command may become `LOST_BEFORE_STAGING` only when the owner proves it remains unbound in `RECEIVED`/`ENQUEUED` with no surviving batch. Batch-bound or inconclusive work remains non-terminal/reconciliation-required and is never evidence-free `ABANDONED`. The live staging checks do not prove that target root allocation or complete Automation identity. +- The live rollback purge path is weaker than that target boundary: `TickQueueControlService.purgeCandidate` checks only `GameplayCommandRepository.hasDurableTickEffect(commandId)` before selecting `ABANDONED` versus `LOST_BEFORE_STAGING`. That non-atomic existence check does not prove the absence of a surviving batch, effect, or source claim, and it can race concurrent staging, drain, or effect ownership. The target atomic owner-defined CAS/no-batch proof remains unimplemented and unproved; this is a current implementation/proof gap, not a relaxation of the target `ACCEPTED_VOLATILE`/`RECEIVED`/`ENQUEUED` eligibility contract. +- The specific deterministic allocation mechanics and `planOrdinal` proposed in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) remain proposal-only, not current tick target requirements. They do not displace the accepted stable-root-before-acknowledgement and persisted nonblank-root-before-staging requirements above. The current `tickBatchId`/`effectKey` path does not prove any proposal-specific allocation behavior. - The accepted lane and fencing consequences are target-state requirements in this recovery model: selected-work manifests and replay records must preserve each item's declared `phase`, `lane`, and `cost_class`, while takeover reconciliation remains subject to the Redis lease plus durable executor-fence handshake owned by [Tick System and Runtime Design](./system-architecture-ticks.md). This document does not duplicate that owner protocol. Naming convention: API, workflow, and EffectId prose uses `regionEpoch`. Snake-case forms such as `region_epoch`, `last_region_epoch`, and `target_region_epoch` are reserved for explicitly identified SQL/storage fields, Redis payloads/keys, or schema examples. @@ -22,7 +24,7 @@ Naming convention: API, workflow, and EffectId prose uses `regionEpoch`. Snake-c ## What This Covers - Crash recovery and replay behavior. -- Idempotency rules tied to the region-scoped tick timeline `(regionEpoch, tickId)`. +- Root/participant idempotency guards, with a narrow last-tick watermark exception only for explicitly proven at-most-once aggregates; the region-scoped tick timeline `(regionEpoch, tickId)` remains ordering and fencing context. - Handling stuck or partial tick entries. - Design checklist for new tick-driven commands. @@ -31,29 +33,32 @@ Naming convention: API, workflow, and EffectId prose uses `regionEpoch`. Snake-c The following sections in `system-architecture-ticks.md` contain the main failure-handling and operational rules: - **Crash Recovery and Replay** – how executors recover from failure and resume processing safely. -- **Domain Idempotency Rules (Timeline Context + Owner Guards)** – how `(regionEpoch, tickId)` provide ordering/fence context while owner guards enforce logical effect idempotency. +- **Domain Idempotency Rules (Timeline Context + Owner Guards)** – how mutation-identity/participant guards enforce logical effect idempotency while `(regionEpoch, tickId)` provides ordering and fencing context. - **Design Checklist for New Tick-Driven Commands** – review checklist for new commands to ensure they follow tick invariants. - **Tick Execution and Redis Integration** – failure scenarios and invariants around the canonical commit pattern. - **Cross-Region Command Execution and Result Relay** – constraints for cross-region retries and replay. When implementing new failure-handling flows or adding operational procedures, ensure the detailed behavior is captured in `system-architecture-ticks.md` and reflected in the appropriate runbooks (for example, Redis incident runbooks). +Under ADR 0085, each coordination-maintenance recovery, takeover, replay, reset, cleanup, or topology-changing operation is admitted and serialized by one external durable maintenance operation/fence and the evidence-derived `replay_first`/`reset_first` classifier owned by [Redis Reset & Recovery](./system-architecture-redis-reset-and-recovery.md). Before any mutation or reconciliation, the durable handoff must validate, persist, and pass the exact external maintenance `operationId`, fence/lock binding, classifier decision, durable-evidence digest, and complete affected scope (keys, durable work, producers, and consumers). A missing, mismatched, or incomplete handoff or scope fails closed and escalates; Redis-local leases and executor fences remain separate execution aids, not substitutes for that maintenance fence. An ordinary idempotent crash replay may run outside this maintenance operation only when the owner contract explicitly classifies it as non-conflicting routine replay and records that classification and evidence; no path may infer that exemption from Redis residue alone. + ## Crash Recovery and Replay Tick recovery is driven by durable PostgreSQL tick state plus domain-level idempotency rules, with Redis acting only as a volatile coordination layer. Game Session creates the durable PostgreSQL `tick_batch` and `SCHEDULED` ledger rows first; only then may it stage the batch in Redis `pending`. Redis `pending` is staging/acceleration coordination only and is never authoritative for tick intent or recovery. - On executor crash or failover, a new worker acquires the region lease, re-establishes the authoritative recovery baseline from the durable tick-batch, tick effect ledger, follow-up tables, and the active status/progress surface: current live uses `GetRuntimeOwnershipStatus` plus `ObserveRuntimeTickProgress` for the owner, opaque `executorFence`, and committed `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)` progress; target-state uses `RegionStatus`/`GetRegionTickStatus`. It then inspects any surviving `tick:{tenantRegionTag}:pending`, `retry:{tenantRegionTag}`, and timer keys only as optional coordination hints while replay converges from durable state. -- Before replay, cleanup, or takeover adoption, the successor revalidates the same in-memory Redis lease token it acquired and the expected `regionEpoch`, then separately verifies the current durable executor fence under the owner contract before any recovery mutation; a missing or mismatched token, epoch, or fence pauses and enters fenced reconciliation, affects no state, and never persists the raw token. Lane identity is immutable during recovery: actor-action retries remain actor actions, passive/effect retries remain passive effects, and replay cannot mint a new root actor action for the same tick. +- Before replay, cleanup, or takeover adoption, the successor revalidates the same in-memory Redis lease token it acquired and the expected `regionEpoch`, then separately verifies the current durable executor fence under the owner contract. When the owner classifies the path as coordination maintenance under ADR 0085, it also validates the exact external maintenance handoff (`operationId`, fence/lock binding, classifier decision, evidence digest, and complete affected scope) and persists/passes that handoff unchanged with recovery evidence before any mutation; an ordinary crash replay may omit that maintenance operation only under the explicit owner classification described above. A missing or mismatched token, epoch, fence, handoff field, or scope pauses and enters fenced reconciliation, affects no state, and never persists the raw token. Lane identity is immutable during recovery: actor-action retries remain actor actions, passive/effect retries remain passive effects, and replay cannot mint a new root actor action for the same tick. +- A recovery skip after the ADR 0085 handoff is permitted only for an explicitly disposable ADR 0058 hint, or after ADR 0058 reconciliation durably proves an empty cadence with no unresolved authoritative work. A missing Redis entry, empty hint scan, timeout, or maintenance handoff alone never proves that a tick or authoritative work item may be skipped; otherwise recovery must replay or reconcile the durable work and retain any inconclusive item as non-terminal/reconciliation-required. - Redis is treated as a volatile coordination layer with **at-least-once** semantics; network retries, executor failover, and AOF replay can all cause the same logical effect to be attempted more than once. -- Domain services rely on `(regionEpoch, tickId)` and effect guards to ensure that replays do not double-apply logical effects even when Redis state is partially lost. +- Domain services use the mutation-identity/participant-guard boundary to ensure that replays do not double-apply logical effects; `(regionEpoch, tickId)` remains ordering and fencing context even when Redis state is partially lost. ### Durable Commit vs Coordination-Cleared Boundaries Failure handling assumes the same two-boundary model defined in the main tick design: - `durable_committed`: - - Ledger rows for `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId)` are terminal (`APPLIED` or `ABANDONED`) where the existing evidence policy permits terminalization; any inconclusive row remains non-terminal reconciliation work under its original root `EffectId`, and - - The current-live `GetRuntimeOwnershipStatus` reports the same opaque `executorFence` recorded by the batch, the live `regionEpoch` matches, and the live commit boundary has advanced under that same fenced write. `RegionStatus` is a target-state durable projection in examples where the live ownership/status surface is not available. + - **Target-state only:** For a work-bearing (non-empty) tick, the complete [canonical tick commit definition](./system-architecture-ticks.md#tick-commit-definition-heartbeat-watermark) requires every eligible ledger row for `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId)` to be terminal (`APPLIED` or `ABANDONED`) under the evidence policy, `tick_batch.status = COMMITTED`, and the target durable watermark to advance in that same fenced visibility boundary. Any inconclusive row remains non-terminal reconciliation work under its original mutation `EffectId`, with its enclosing root retained as lineage, and blocks this boundary. + - In the current-live deployment, `GetRuntimeOwnershipStatus` reports the same opaque `executorFence` recorded by the batch, the live `regionEpoch` matches, and the committed tick fields advance under that same fenced write. Target-state `RegionStatus.lastCommittedTickId` is the corresponding durable projection; `ObserveRuntimeTickProgress` is only the current-live progress feed and does not replace either durable authority. - `coordination_cleared`: - Redis `pending`/lock coordination for that tick is no longer in flight. @@ -72,21 +77,24 @@ To make replays observable and bounded, Game Session maintains a **tick effect l - Every tick effect that has been durably claimed or staged for execution (for example, rows associated with a tick batch, replay-eligible retry work, or durable follow-up records) is mirrored into a Game Session–owned ledger table (for example `tick_effects`) with columns such as: - `tenant_id`, `game_instance_id`, `playable_state_namespace_id`, `playable_state_scope`, `region_id`, `region_epoch`, `tick_id` - `tick_batch_id` - - `root_effect_id` (stable logical root identity retained on every ledger projection) - - `typed_operation` (canonical operation identity retained alongside the root on every participant projection) + - `effect_id` (persisted mutation identity used by the participant guard: the root `EffectId` for a root mutation or the deterministic child `EffectId` for a generated child) + - `root_effect_id` (enclosing stable logical root identity retained on every ledger projection for lineage and reconciliation; equal to `effect_id` for a root mutation) + - `typed_operation` (canonical operation identity retained alongside the mutation `effect_id` and enclosing root on every participant projection) - `effect_key` (stable, human-readable descriptor passed through from staging) - declared `phase`, `lane` ∈ {`actor_action`, `passive_effect`}, and bounded `cost_class`; recovery and replay preserve all three values - `target_aggregate_type`, `target_aggregate_id` (required target aggregate identity) + - `request_digest` (immutable request digest bound to the mutation guard and compared on replay; not part of uniqueness) - `automation_dispatch_id`, `command_ordinal` (both required for script-generated effects; nullable for non-scripting commands) - `command_id` - `status` ∈ {`SCHEDULED`, `APPLIED`, `ABANDONED`} - `reason` / `outcome` - replay-verification audit metadata when a replay proves that the effect was already applied (for example verifier, timestamp, and evidence digest/reference) - `created_at`, `updated_at` +- The ledger retains the persisted mutation `EffectId` and, where applicable, enclosing root lineage for participant guards and reconciliation. A generated child uses its persisted child `EffectId` as the mutation identity and retains the enclosing root for lineage and reconciliation. A shared effect identity for a conserved multi-participant operation does not replace ADR 0053 atomicity, co-location, or reservation semantics. Command-root ordering and allocation details are pending proposal-only work in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); this ledger contract does not define `planOrdinal`, a command-root key, or an allocation owner. - Target-state requires one durable tick-batch record per `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)`, owned by Game Session, and stores at minimum: - `tick_batch_id` - `executor_fence` (or equivalent opaque durable fence captured at batch allocation time); this is the canonical durable fence used for compare-and-match protection. - - exactly one immutable sealed execution-context binding: `sealed_execution_context_digest`, or a durable `sealed_execution_context_ref` whose referenced record contains that digest. The binding covers the batch coordinates, executor fence, selected-work manifest/digest, effect identities, and pinned execution inputs/version/script patch; replay must use the sealed context rather than reconstructing mutable context. + - exactly one immutable sealed execution-context binding: `sealed_execution_context_digest`, or a durable `sealed_execution_context_ref` whose referenced record contains that digest. The binding covers the batch coordinates, executor fence, applicable `playableStateNamespaceId`, selected-work manifest/digest, effect identities, and pinned execution inputs/version/script patch; replay must use the sealed context rather than reconstructing mutable context. - `lease_token_correlation` may be retained as optional non-secret lease-acquisition trace/audit metadata; raw Redis lease tokens are never persisted, and this correlation is not an authoritative durable fence and must not authorize batch allocation, commit, cleanup, or recovery writes. - `expected_effect_count` - `status` @@ -94,7 +102,7 @@ To make replays observable and bounded, Game Session maintains a **tick effect l - optional `pending_digest` or equivalent Redis-pending integrity field; it is not a substitute for the required immutable exact pending envelope or the sealed execution-context binding above - `created_at`, `updated_at` - The selected-work manifest is required for deterministic replay and source cleanup. At minimum it records, per selected source item: - - the batch scope `(tenantId, gameInstanceId, regionId, regionEpoch)`; its `enqueue_seq` is allocated from the complete `` scope and is not reset or reused when a reset bumps `regionEpoch` and restarts `tickId` at `0` + - the tick-batch identity `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)`; separately, its entity-local `entity_enqueue_seq` is allocated monotonically within the complete allocation scope `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch, entityId)`. `playableStateScope` is not part of either identity. A reset that bumps `regionEpoch` and restarts `tickId` at `0` starts a new entity-local sequence domain, while old-epoch ordering identities remain immutable and are never rebound even if a numeric sequence value is reused. - `source_kind` - declared `phase`, `lane`, and `cost_class` - source item identity @@ -117,7 +125,7 @@ To make replays observable and bounded, Game Session maintains a **tick effect l - Recovery that observes multiple durable rows for the same coordinates treats the region as inconsistent, pauses it, and requires reconcile tooling before normal ticks resume. - Current live boundary note: gameplay commands do not yet use the fuller target-state `BOUND_TO_BATCH` vocabulary. Instead, the command ledger exposes `enqueueSeq`, `STAGED`, `DRAINED`, and later terminal/requeue outcomes, while the sealed batch manifest digest is used to ensure replay reuses only matching staged batches instead of silently mutating an older batch contract. - **Target-state authority:** The durable `tick_batch` record, `tick_effects` ledger, and immutable sealed execution context are authoritative for selected work, execution identity, and replay. The sealed context includes the complete batch coordinates, executor fence, selected-work manifest/digest (including each item's declared phase/lane/cost-class and persisted ordering inputs), effect identities, and pinned execution inputs/version/script patch. Redis `pending`/event streams plus external metrics, logs, traces, and audit streams are projections or diagnostics; they cannot prove a commit or justify replay on their own. -- For the complete expected concrete participant-projection set linked to a root `EffectId` and participant guard contract, every expected `(root_effect_id, typed_operation, tenant_id, game_instance_id, playable_state_namespace_id, playable_state_scope, region_id, region_epoch, tick_id, target_aggregate_type, target_aggregate_id)` projection must eventually have **exactly one evidence-qualified terminal state**, and only when authoritative evidence permits terminalization. `typed_operation` is part of the participant projection alongside the root and exact target aggregate; `effect_key` remains descriptor metadata for correlation and lookup, not a substitute for that identity. Replay/recovery must reconcile the whole expected set and fail closed for missing, extra, partial, or conflicting projections; inconclusive or ambiguous projections remain non-terminal/reconciliation-required and cannot be recorded as `APPLIED` or `ABANDONED`; one root-effect or one ledger-row result is insufficient: +- For the complete expected concrete participant-projection set linked to an enclosing root `EffectId` and participant guard contract, every expected `(effect_id, root_effect_id, typed_operation, tenant_id, game_instance_id, playable_state_namespace_id, playable_state_scope, region_id, region_epoch, tick_id, target_aggregate_type, target_aggregate_id)` projection must eventually have **exactly one evidence-qualified terminal state**, and only when the applicable recovery/evidence policy permits terminalization. Explicitly inconclusive or ambiguous projections remain non-terminal/reconciliation-required (for example, `SCHEDULED`) and continue to block convergence; they cannot be recorded as `APPLIED` or `ABANDONED`. `effect_id` is the mutation's persisted root-or-child `EffectId`; `root_effect_id` remains enclosing lineage and reconciliation context. `typed_operation` is part of the participant projection alongside the mutation ID and exact target aggregate; guard uniqueness uses the owner-declared runtime-family partition: `playable_state_namespace_id` participates for S1/S2, while only explicit S3 uses `game_instance_id`; for S1/S2, `game_instance_id` is separately exact-validated active-runtime authorization/fence evidence. `playable_state_scope` and the remaining timeline/evidence fields are immutable bound evidence, and `effect_key` remains descriptor metadata for correlation and lookup, not a substitute for that identity. Replay/recovery must reconcile the whole expected set and fail closed for missing, extra, partial, or conflicting projections; one root-effect or one ledger-row result is insufficient: - `status = APPLIED` – effect successfully committed to domain state, or durable replay evidence proves that it was already committed under the existing fenced verification policy. - `status = ABANDONED` – effect intentionally skipped or judged unrecoverable only when durable evidence proves it was unapplied and the existing recovery policy permits terminalization; inconclusive work remains non-terminal reconciliation work. - A duplicate handler attempt may return a replay/no-op outcome such as `replay_ok`, but that outcome is recorded in service metrics/audit and never as a third ledger status; when the effect is already reflected in durable state, its ledger row is `APPLIED`. @@ -158,12 +166,12 @@ Tick-related durable structures are intentionally split between a central ledger - **Game Session Service** - Owns the global tick effect ledger tables (for example `tick_effects`) and any cross-region follow-up tables that encode scheduled work between regions. - - Defines the concrete ledger projection of the root `EffectId` and its typed participant-guard contract, and is responsible for converging `(rootEffectId, typedOperation, tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, targetAggregateType, targetAggregateId)`—with `effectKey` retained as descriptor metadata and linked to that root, operation, and guard evidence—to `APPLIED` or `ABANDONED` when the recovery policy permits terminalization. + - Defines the concrete ledger projection of the mutation's persisted root-or-child `EffectId` and its typed participant-guard contract, while retaining the enclosing root `EffectId` as lineage and reconciliation context. It is responsible for converging `(effectId, rootEffectId, typedOperation, tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, targetAggregateType, targetAggregateId)`—with `effectKey` retained as descriptor metadata and linked to that mutation, root, operation, and guard evidence—to `APPLIED` or `ABANDONED` when the recovery policy permits terminalization. - **Domain services (Entity Management, World Management, etc.)** - Own their own idempotency guard tables (for example `entity_tick_state`, `tick_effect_guard`) in their respective schemas. - - Use those guards to implement per-aggregate `last_tick_id` and operation-level idempotency patterns, but do not introduce additional “mini-ledgers” for tick effects. + - Use operation-level guards by default; a per-aggregate `last_tick_id` watermark is allowed only with an explicit proof of at-most-one logical mutation per tick timeline. Do not introduce additional “mini-ledgers” for tick effects. -New designs must not create ad-hoc ledger tables for tick effects in other services; they should either extend the Game Session–owned ledger/follow-up schema or add domain-local guard tables that project the existing `EffectId`. +New designs must not create ad-hoc ledger tables for tick effects in other services; they should either extend the Game Session–owned ledger/follow-up schema or add domain-local guard tables that project the existing mutation `EffectId` and retain its enclosing root lineage. Cross-region follow-ups extend the same concrete identity rather than treating a region or scope label as sufficient. Each durable coordinator, target follow-up, and origin-addressed result must carry both the origin and target runtime tuples `(tenant_id, game_instance_id, playable_state_namespace_id, playable_state_scope, region_id, region_epoch)` (with the origin/target role made explicit). `playable_state_namespace_id` participates in target-leg uniqueness/claim identity, exact replay comparison, old-epoch recovery, and coordinator-to-result correlation; `playable_state_scope` is separately persisted and exact-validated evidence, not a replacement key. A target result is admissible only when its origin and target namespace/timeline tuples, stable follow-up/coordinator identity, target effect/aggregate identity, and immutable request/result digest agree with the durable rows. Recovery retains the original namespace-complete projection and must not rebind an old follow-up to a new namespace or epoch. The current cross-region storage/wire substrate remains narrower than this target contract. @@ -171,7 +179,7 @@ Replay of a tick is driven from ledger state: - When reprocessing a tick, the executor loads ledger rows for that `` with `status = SCHEDULED` and: - A `SCHEDULED` effect may be re-queued/re-run only after durable authoritative domain evidence proves that it was unapplied and that replay is safe under the existing evidence policy. Absence of `APPLIED` evidence, a missing response, or an unreadable/ambiguous guard is inconclusive: retain `SCHEDULED`/reconciliation-required, escalate, and do not re-queue. After a permitted replay, mark the row `APPLIED` only when durable domain evidence and the fenced replay policy prove application. - - Marks effects `ABANDONED` with a precise reason only when replay proves no required mutation succeeded and the effect is no longer valid (expired session, entity gone, descheduled tick, and so on). Inconclusive work remains non-terminal reconciliation work under its original root `EffectId` and is escalated for reconciliation. + - Marks effects `ABANDONED` with a precise reason only when replay proves no required mutation succeeded and the effect is no longer valid (expired session, entity gone, descheduled tick, and so on). Inconclusive work remains non-terminal reconciliation work under its original mutation `EffectId`, with the enclosing root retained as lineage, and is escalated for reconciliation. - When idempotency evidence may prove that an effect was already applied, replay verification reconciles the complete expected concrete participant-projection set and binds the evidence to the `SCHEDULED -> APPLIED` transitions in fenced/CAS transactions (conceptual shape): ```sql @@ -208,7 +216,8 @@ Replay of a tick is driven from ledger state: -- field or this resolved digest as sealed_context_digest; never rebuild -- context from mutable state. -- expected is the sealed set of concrete participant projections for this - -- effect: root EffectId + typed operation + exact target aggregate, + -- effect: mutation EffectId (root or persisted child) + typed operation + -- + exact target aggregate; enclosing root is lineage/reconciliation context, -- including every required participant and its immutable request-digest -- binding. Read all expected guard rows and durable domain evidence under -- the current fence/context. Require set equality: every expected @@ -263,13 +272,13 @@ Replay of a tick is driven from ledger state: ``` The complete-set evidence check, target authority epoch/fence check, sealed context-digest check, all required Game Session ledger CAS operations, and replay-verification metadata commit together within this one Game Session durable transaction. A stale authority or batch fence/context, missing/extra/partial/conflicting projection, or concurrent winner affects an incomplete set and must roll back and fail closed/reject or retry; an audit/log write without this CAS is not proof and must not be used to skip the domain call. Domain-service guards and evidence remain in their own service-local transactions; this flow does not imply a cross-service database transaction. Current-live uses a separate CAS over the current `RuntimeOwnershipStatus` authority, exact `regionEpoch`/opaque `executorFence`, and the complete selected-work manifest plus `manifest_digest` against durable source, ledger, and participant evidence; sealed execution context is not required at that current-live boundary. Both branches fail closed on mismatches and leave durable state unchanged. -- Every staging script must carry an immutable collision-safe pending envelope for each staged member. `effect_key` remains descriptor metadata only. The envelope must carry the exact `tick_batch_id` plus either the complete root `EffectId`/participant projection (`root_effect_id`, canonical `typed_operation`, exact `target_aggregate_type`/`target_aggregate_id`, and the exact scope, epoch, and tick) or an equivalent immutable exact ledger-row identity that resolves to that complete projection. Stage, commit, rollback, and cleanup preserve the envelope unchanged; recovery exact-set-compares pending envelopes with the durable batch/ledger expected set and fails closed for missing, extra, duplicate, or conflicting envelopes. An `effect_key`-only, count-only, or digest-only correlation is insufficient, and malformed or orphan pending state cannot be committed. +- Every staging script must carry an immutable collision-safe pending envelope for each staged member. `effect_key` remains descriptor metadata only. The envelope must carry the exact `tick_batch_id` plus either the complete mutation `EffectId`/enclosing-root lineage/participant projection (`effect_id`, `root_effect_id`, canonical `typed_operation`, exact `target_aggregate_type`/`target_aggregate_id`, and the exact scope, epoch, and tick) or an equivalent immutable exact ledger-row identity that resolves to that complete projection. Stage, commit, rollback, and cleanup preserve the envelope unchanged; recovery exact-set-compares pending envelopes with the durable batch/ledger expected set and fails closed for missing, extra, duplicate, or conflicting envelopes. An `effect_key`-only, count-only, or digest-only correlation is insufficient, and malformed or orphan pending state cannot be committed. - Recovery rules for Redis/SQL mismatch are explicit: - durable tick-batch + `SCHEDULED` ledger rows exist, Redis `pending` missing: - replay proceeds from PostgreSQL using the durable batch manifest and `SCHEDULED` ledger rows; it does not rely on re-materializing the old tick through the normal hot-path staging scripts. - - First implementation treats normal tick Lua scripts as hot-path guards only. Recovery drives effects directly to `APPLIED`/`ABANDONED` only where the evidence policy permits, leaves any inconclusive work non-terminal under its original root `EffectId`, escalates it for reconciliation, reconciles any surviving source claims/entries against the manifest, and then clears stale coordination residue. + - First implementation treats normal tick Lua scripts as hot-path guards only. Recovery drives effects directly to `APPLIED`/`ABANDONED` only where the evidence policy permits, leaves any inconclusive work non-terminal under its original mutation `EffectId` and enclosing-root lineage, escalates it for reconciliation, reconciles any surviving source claims/entries against the manifest, and then clears stale coordination residue. - Redis `pending` exists without a durable tick-batch: - - treat the Redis entry as orphaned coordination state, clear it, alert, and do not commit work from it. + - treat the Redis entry as orphaned coordination state; clear it only after the exact ADR 0085 handoff has been validated and durably persisted, then passed unchanged to the cleanup operation (`operationId`, fence/lock binding, classifier decision, evidence digest, and complete affected scope), or after the owner has durably recorded this specific non-conflicting routine replay/cleanup classification and evidence. The cleanup must validate a nonblank operation identity, the current fence/lock, classifier, evidence digest, and complete scope immediately before deletion; it must not manufacture or reuse an operation record from Redis residue. Missing, stale, mismatched, or incomplete handoff/classification fails closed and escalates; alert and do not commit work from the orphaned entry. - durable tick-batch and Redis `pending` do not produce exact set equality for the immutable pending envelopes and durable batch/ledger expected set (including missing, extra, duplicate, malformed, or conflicting members; count/digest disagreement is only a diagnostic signal): - mark the batch inconsistent, pause the region, and require reconcile tooling before resuming normal ticks. @@ -288,7 +297,7 @@ Recovery-specific behavior is: ### EffectId, Ledger Rows, and Guard Keys -The canonical root `EffectId` described in the identifier glossary and `system-architecture-transactions.md` ties together the logical effect, Game Session participant status, and replay lineage. Participant guard uniqueness is deterministically derived from exactly that root effect, typed operation, and target aggregate; the immutable request digest is bound to the guard identity, while durable outcome/evidence state is mutable guard-row state protected by CAS. The root identity, original participant ledger projection, and collision-safe guard identity are preserved for every ordinary retry or uncertain replay. Retry eligibility/attempt metadata (such as retry count, next eligible tick, and source-claim state) is separate and must not rewrite the original `regionEpoch`, `tickId`, `effectKey`, or root/typed-operation/target projection. A future linked-attempt or supersession model requires an explicit contract; only a **post-abandon re-drive**—after the original effect is conclusively terminal `ABANDONED` and its source claim is terminalized—may receive a fresh logical `EffectId`, a later tick coordinate, a new retry/source identity, and durable lineage to the original identities. +The ledger retains the persisted mutation `EffectId`, enclosing root lineage where applicable, timeline, typed operation, exact target, digest, participant projection, and replay lineage; ordinary retry and uncertain replay preserve them. A generated child uses its persisted child `EffectId` while retaining the enclosing root as lineage and reconciliation context. Retry eligibility is mutable operational metadata and never rewrites that binding. A post-abandon re-drive requires conclusive terminal evidence and follows its source owner's admission and identity contract, retaining explicit lineage to the abandoned command/effect. Command-plan and root-allocation details remain pending proposal-only work in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). - Tick coordination in Redis. - Tick effect ledger rows in PostgreSQL. @@ -296,12 +305,14 @@ The canonical root `EffectId` described in the identifier glossary and `system-a In schema terms: -- The tick effect ledger persists a concrete, namespace-complete projection of the root `EffectId` and its tick coordinates for scope, ordering, evidence, and target lookup: - - The storage projection includes at minimum `(root_effect_id, typed_operation, tenant_id, game_instance_id, playable_state_namespace_id, playable_state_scope, region_id, region_epoch, tick_id, target_aggregate_type, target_aggregate_id)`. `playable_state_scope` and the tick/region coordinates are persisted and exact-validated evidence or ordering metadata, not uniqueness dimensions. The ledger's logical uniqueness key is exactly `(root_effect_id, typed_operation, target_aggregate_type, target_aggregate_id)`; an owner-local physical partition, if used, is storage placement only and cannot alter logical uniqueness or deduplication. The physical schema must enforce or project that exact logical identity without promoting `playable_state_scope` or tick coordinates into guard uniqueness. `effect_key` may be stored in the projection for stable descriptor/correlation metadata, but it is not the root identity or sole collision protection. Mutable `status`, `reason`, `outcome`, evidence/reconciliation fields, and timestamps remain outside the uniqueness key. The physical schema may encode target identity separately, but it must retain an explicit collision-safe projection containing `root_effect_id`, `typed_operation`, and the exact target aggregate. - - Additional columns such as `command_id`, `automation_dispatch_id`, or `command_ordinal` may exist for queryability and scripting correlation, but they do not replace the root `EffectId` or participant guard identity. +- The tick effect ledger persists a concrete, namespace-complete projection of the persisted mutation `EffectId`, enclosing root lineage, and tick coordinates for scope, ordering, evidence, and target lookup: + - The storage projection includes at minimum `(effect_id, root_effect_id, typed_operation, tenant_id, game_instance_id, playable_state_namespace_id, playable_state_scope, region_id, region_epoch, tick_id, target_aggregate_type, target_aggregate_id)`. `playable_state_scope` and the tick/region coordinates are persisted and exact-validated evidence or ordering metadata, not uniqueness dimensions. The ledger's logical uniqueness key is exactly `(effect_id, typed_operation, target_aggregate_type, target_aggregate_id)`, where `effect_id` is the root `EffectId` for a root mutation and the persisted child `EffectId` for a generated child; `root_effect_id` is retained as enclosing-root lineage and reconciliation context, not as a substitute for `effect_id`. An owner-local physical partition, if used, is storage placement only and cannot alter logical uniqueness or deduplication. The physical schema must enforce or project that exact logical identity without promoting `playable_state_scope` or tick coordinates into guard uniqueness. `effect_key` may be stored in the projection for stable descriptor/correlation metadata, but it is not the mutation identity or sole collision protection. Mutable `status`, `reason`, `outcome`, evidence/reconciliation fields, and timestamps remain outside the uniqueness key. The physical schema may encode target identity separately, but it must retain an explicit collision-safe projection containing `effect_id`, `root_effect_id`, `typed_operation`, and the exact target aggregate. + - Additional columns such as `command_id`, `automation_dispatch_id`, or `command_ordinal` may exist for queryability and scripting correlation, but they do not replace the persisted mutation `EffectId` or participant guard identity. + - On reuse of the persisted mutation identity, the writer exact-compares all immutable scope, lineage, timeline, descriptor, namespace, and request-digest bindings, including the stored projection fields, and fails closed on any conflict; it must not insert another row for a conflicting reuse. For a root mutation, `effect_id` is the root `EffectId`; for a generated child, the persisted child `EffectId` remains the distinct mutation identity while `root_effect_id` retains the enclosing-root lineage used for reconciliation. +- The command-root allocation identity and any collision-safe allocation partition remain pending in ADR 0183. Every ledger row retains the namespace-complete tick/recovery projection above, while `effect_key` remains descriptor metadata and mutable status, reason, outcome, evidence, and timestamps remain outside identity protection. - Guard tables such as `tick_effect_guard` implement the deterministic participant projection for multi-effect operations: - - Their uniqueness identity binds root `EffectId`, typed operation, and target aggregate. The immutable request digest is bound and compared on every replay; durable outcome/evidence/reconciliation fields are mutable row state protected by CAS and are not uniqueness inputs. - - The concrete tick/ledger projection columns remain storage scope/order/lookup metadata, not an alternative guard identity. Handlers must not invent alternative idempotency keys for tick-driven effects. + - Their uniqueness identity follows the owner-declared runtime family: S1/S2 uses the `(tenantId, playableStateNamespaceId)` partition plus the mutation's persisted root-or-child `EffectId`, typed operation, and exact target aggregate; only an explicitly owner-classified S3 family uses `(tenantId, gameInstanceId)` plus those identity fields. For S1/S2, `gameInstanceId` is separately exact-validated active-runtime authorization/fence evidence. The immutable request digest and applicable namespace binding are exact-compared on every replay; `playableStateScope`, active-instance evidence, timeline, and lineage remain immutable evidence, while durable outcome/reconciliation fields are mutable row state protected by CAS and are not uniqueness inputs. Unknown or unclassified families fail closed before guard admission and are never inferred to be S3. + - The concrete tick/ledger projection columns remain storage scope/order/lookup metadata, not an alternative guard identity. Handlers must not invent alternative idempotency keys for tick-driven effects or use enclosing-root lineage, child ordinal, `effect_key`, outcome, or evidence state as guard identity. Work explicitly outside playable-state scope must use an accepted owner-specific idempotency/partition contract; it cannot omit namespace/scope and proceed under this gameplay participant-guard contract. The ledger makes replay visible operationally via metrics such as: @@ -345,13 +356,13 @@ Responsibility for driving ledger rows to a terminal outcome lies with the Game - A background “ledger replay controller” in Game Session: - Periodically scans for `SCHEDULED` rows that have exceeded the emitted replay-convergence budget for a given `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId)`. - Replays eligible effects using the same idempotent handlers the tick pipeline uses, marking rows `APPLIED` only when durable domain evidence confirms success. - - Marks rows `ABANDONED` with a precise reason only when replay evidence proves the effect was not applied and is no longer safe or meaningful (for example, entities removed, sessions expired, or region/tenant/cluster resets that bumped `regionEpoch`); inconclusive work remains non-terminal under the original root `EffectId`, is escalated for reconciliation, and follows the applicable evidence policy. + - Marks rows `ABANDONED` with a precise reason only when authoritative owner/domain evidence proves the effect was not applied and an applicable feature rule makes it no longer safe or meaningful (for example, an entity was removed or a session expired, or a reset/epoch change invalidated the effect after that evidence); a reset or epoch change alone never proves non-application. Inconclusive work remains non-terminal under the original mutation `EffectId`, with the enclosing root retained as lineage, is escalated for reconciliation, and follows the applicable evidence policy. - Enforces bounded fairness across active complete recovery scopes so replay does not starve a smaller scope behind one hot backlog: - Scans and replays in bounded batches per complete recovery scope `` (with `tickId` and work identity retained within that scope). - Uses round-robin (or weighted-fair) scheduling across complete recovery scopes rather than draining one scope completely before touching others; fairness cursors and deficit/cost accounting are keyed by the complete recovery scope, while `scope_class` remains metrics-only selection metadata. - Emits `tick_effects_replay_scan_lag_ms{scope_class}` and `tick_effects_replay_batches_total{scope_class}` so starvation is visible without reintroducing raw tenant/game-instance/region labels to Prometheus. -- The controller also runs on service startup for each complete recovery scope to converge any lingering `SCHEDULED` rows before normal tick processing resumes; any inconclusive row instead remains reconciliation-required, is escalated, and cannot be hidden by normal startup replay. -- For incident handling, the same replay logic is exposed via coordination tooling (for example, an admin CLI or maintenance API) so operators can explicitly drive convergence for a selected complete `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch)` after authoritative enumeration and exact validation. Incomplete or caller-supplied namespace/scope evidence must fail closed before any replay or maintenance mutation when guided by runbooks in the Redis operations docs. +- The controller also runs on service startup for each complete recovery scope to converge any lingering `SCHEDULED` rows before normal tick processing resumes; any inconclusive row instead remains reconciliation-required, is escalated, and cannot be hidden by normal startup replay. Before startup replay mutates or reconciles a row, the owner must explicitly classify the path as non-conflicting routine idempotent replay and record that classification/evidence, or pass the exact ADR 0085 maintenance handoff; an absent or incomplete classification/handoff fails closed. +- For incident handling, the same replay logic is exposed via coordination tooling (for example, an admin CLI or maintenance API) so operators can explicitly drive convergence for a selected complete `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch)` after authoritative enumeration and exact validation. Incomplete or caller-supplied namespace/scope evidence must fail closed before any replay or maintenance mutation when guided by runbooks in the Redis operations docs. The incident path is a coordination-maintenance operation and must pass the exact ADR 0085 handoff before replay, reconciliation, or cleanup mutation; Redis leases and executor fences do not substitute for it. - Convergence SLO contract (required): - `SCHEDULED` rows should converge to terminal `APPLIED`/`ABANDONED` within the emitted `tick_effects_replay_convergence_budget_seconds` window when evidence permits; explicitly marked inconclusive/reconciliation-required work—including current-epoch timeout or retry-exhaustion cases—remains non-terminal and is escalated under the applicable reconciliation policy. - If oldest `SCHEDULED` age exceeds the emitted budget for a bounded scope-class rollup, incident runbooks require exact-scope enumeration and authoritative runtime-health lookup. The rollup does not itself classify or authorize a region as `DEGRADED`/`STALLED`. @@ -362,16 +373,16 @@ Before an affected region, tenant, or cluster scope reopens, recovery completely Across every epoch, an effect whose application status is inconclusive—including a current-epoch timeout or retry-exhaustion case—remains `SCHEDULED`/reconciliation-required and is escalated. Absence of a response, a deadline, control-plane health, or exhausted retry budget never proves `ABANDONED`; only durable evidence proving that no required mutation succeeded may authorize that terminal outcome. The policy below adds the authority-fenced attestation required for old-epoch reset work. -The same policy applies whenever a region-, tenant-, or cluster-scoped reset or epoch fence leaves an old-epoch effect in `SCHEDULED` and normal domain inspection cannot yet prove whether the effect was applied. Recovery must use a bounded, out-of-band attestation under the original `EffectId`; reset scope alone is never evidence for terminalization. The attestation: +The same policy applies whenever a region-, tenant-, or cluster-scoped reset or epoch fence leaves an old-epoch effect in `SCHEDULED` and normal domain inspection cannot yet prove whether the effect was applied. Recovery must use a bounded, out-of-band attestation under the original mutation `EffectId`, retaining its enclosing root as lineage and reconciliation context; reset scope alone is never evidence for terminalization. The attestation: -- retains the original concrete ledger/guard projection `(rootEffectId, typedOperation, tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)`, with `typedOperation` part of the collision-safe participant identity, and exact-compares that projection against both the durable ledger row and the authoritative domain guard/state; any missing, extra, partial, or conflicting field fails closed. It also retains the maintenance/recovery fence that authorized the reset; +- retains the original concrete ledger/guard projection `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectId, rootEffectId, typedOperation, requestDigest, effectKey, targetAggregateType, targetAggregateId)`, with the persisted mutation `effectId` as the root-or-child collision identity and `rootEffectId` retained only as enclosing lineage/reconciliation context; the owner-declared runtime-family partition plus `effectId`, `typedOperation`, and exact target aggregate form the collision-safe participant identity (S1/S2 uses `tenantId + playableStateNamespaceId`; only explicit S3 uses `tenantId + gameInstanceId`). The attestation independently exact-compares the partition, typed operation, exact target aggregate, immutable request digest, and every other projection field against both the durable ledger row and authoritative domain guard/state; any missing, extra, partial, or conflicting field fails closed. It also retains the exact external maintenance `operationId`, fence/lock binding, classifier decision, evidence digest, and complete affected scope that authorized the reset; `playableStateScope` and active-instance evidence remain immutable bound evidence; - reads the authoritative domain guard/state and any existing `APPLIED` reflection without invoking current-epoch staging or replay; - records an auditable attestation outcome and retries only within the emitted replay-convergence budget; and -- permits exactly these outcomes: `APPLIED` when durable domain state or the authoritative guard proves the effect occurred; `ABANDONED` with an explicit reset/reconciliation reason only when durable state proves it was unapplied and cannot be safely re-driven; or an explicit reconciliation-required non-terminal state while the evidence remains inconclusive. +- permits exactly these outcomes: ledger `status=APPLIED` when durable domain state or the authoritative guard proves the effect occurred; ledger `status=ABANDONED` with an explicit reset/reconciliation reason only when durable state proves it was unapplied and cannot be safely re-driven; or retained ledger `status=SCHEDULED` with explicit `reconciliation_required` metadata/reason while the evidence remains inconclusive. If the bounded attestation remains inconclusive, the original effect remains non-terminal under an explicit reconciliation-required marker. It is not an `ABANDONED` outcome, is never sent through normal current-epoch replay, and blocks the affected reset scope from declaring convergence until an authority-fenced worker records a terminal decision supported by authoritative evidence. A later epoch must not reuse the old row as though it were a new current-epoch effect. -Current-epoch executors must never re-drive the old `EffectId`. Any feature that needs to carry work across the epoch boundary requires separately designed maintenance or saga/outbox tooling. A new current-epoch identity is a **post-abandon re-drive** only: the old effect and source claim must first be terminal `ABANDONED`, then the tooling allocates a later coordinate, fresh root and retry/source identity, and durable lineage. Ordinary retry/replay preserves the old root, and inconclusive work cannot be re-driven. +Current-epoch executors must never re-drive the old mutation `EffectId`. Any feature that needs to carry work across the epoch boundary requires separately designed maintenance or saga/outbox tooling. A new current-epoch identity is a **post-abandon re-drive** only: the old effect and source claim must first be terminal `ABANDONED`, then the tooling allocates a later coordinate, fresh root and retry/source identity, and durable lineage. Ordinary retry/replay preserves the old mutation identity and its enclosing root lineage, and inconclusive work cannot be re-driven. Common scenarios and invariants: @@ -379,7 +390,7 @@ Common scenarios and invariants: - Redis: `pending`, locks, timers, and retry metadata preserved for recent ticks. - PostgreSQL: all committed effects durably stored. - Invariants: no double-apply; at-most-one executor per region after lease re-acquisition. - - Action: new executor replays any surviving `pending` entries; ticks complete or are retried automatically. + - Action: new executor replays any surviving `pending` entries; ticks complete or are retried automatically. This ordinary replay may omit a maintenance operation only when the owner explicitly classifies it as non-conflicting routine idempotent replay and records the classification/evidence; a recovery skip remains limited to an explicitly disposable ADR 0058 hint or an ADR 0058 reconciliation that durably proves an empty cadence with no unresolved authoritative work. Otherwise the exact ADR 0085 handoff must be validated and persisted before replay or reconciliation, and inconclusive work remains non-terminal. - **Crash during the measured Redis unreplicated-write window** - Redis: some recent `pending`/lock/queue keys for the last ticks may be missing. - PostgreSQL: effects applied before the crash remain; very recent, in-flight effects may or may not have been applied. @@ -387,11 +398,11 @@ Common scenarios and invariants: - Action: - Metrics and dashboards surface gaps or stuck regions. - Operators treat a breached unreplicated-write SLO as a trigger to run the **ledger replay controller** (and, where appropriate, the scoped reset/reconcile flows) for affected `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch)` combinations. - - The controller applies ADR 0058 class-specific outcomes: it drives eligible durable effects and correctness-bearing timers through evidence-backed replay or terminalization, while session/lease/cache/wake-up loss remains a latency or reconnect consequence. Any inconclusive effect remains reconciliation-required and escalated; old-epoch effects additionally follow the [Inconclusive Old-Epoch Reconciliation Policy](#inconclusive-old-epoch-reconciliation-policy). The controller does **not** re-stage older ticks through normal tick-staging Lua scripts; cross-epoch reconstruction uses the explicit fresh-identity lineage path. + - The controller applies ADR 0058 class-specific outcomes: it drives eligible durable effects and correctness-bearing timers through evidence-backed replay or terminalization, while session/lease/cache/wake-up loss remains a latency or reconnect consequence. Any inconclusive effect remains reconciliation-required and escalated; old-epoch effects additionally follow the [Inconclusive Old-Epoch Reconciliation Policy](#inconclusive-old-epoch-reconciliation-policy). The controller does **not** re-stage older ticks through normal tick-staging Lua scripts; cross-epoch reconstruction uses the explicit fresh-identity lineage path. The outage-triggered replay path must carry the exact ADR 0085 handoff, unless its owner explicitly records the non-conflicting routine-replay classification/evidence; any scoped reset/reconcile flow always requires the maintenance handoff before mutation. - The same reconcile scope also converges accepted-but-unbound `ACCEPTED_VOLATILE` command records according to the [canonical command outcome contract](./system-architecture-tick-execution-flows.md#command-outcome-status-surface-required), so ingress dedupe state does not strand commands indefinitely after coordination loss. `ACCEPTED_DURABLE` records delegate to their feature-specific durable intake and safe-replay recovery contract. - **GC pause > `lock_ttl_ms` but < `lease_ttl_ms`** - Redis: locks may expire and be reacquired; `pending` remains; lease still held by original executor. - - PostgreSQL: any effects applied before the pause remain consistent; replays of the same concrete ledger/guard projection `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)` retain the original root `EffectId` and are treated as no-ops by idempotent handlers. + - PostgreSQL: any effects applied before the pause remain consistent; replays of the same concrete ledger/guard projection `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectId, rootEffectId, typedOperation, requestDigest, effectKey, targetAggregateType, targetAggregateId)` retain the original mutation `EffectId` and enclosing root lineage and are treated as no-ops by idempotent handlers. Guard uniqueness follows the owner-declared runtime family (`tenantId + playableStateNamespaceId` for S1/S2, `tenantId + gameInstanceId` only for explicit S3, plus the mutation identity/operation/exact target); `playableStateScope`, active-instance evidence, and `requestDigest` are immutable bound evidence. - Invariants: no double-apply; lease ownership unchanged; at-most-one executor per region. - Action: late work that fails token checks is retried; regions with persistent over-TTL behavior may be marked degraded until configuration or workload is adjusted. - **GC pause > `lease_ttl_ms` (lease lost)** @@ -403,7 +414,7 @@ Common scenarios and invariants: - Redis: coordination keys temporarily unavailable; a tail window of recent `pending`/lock/queue state may be lost depending on failure and AOF configuration. - PostgreSQL: remains authoritative; effects committed before the outage are not rolled back. - Invariants: apply the ADR 0058 class-specific outcome. Durable commands/effects/correctness-bearing timers are replayed, reconstructed, reconciled, or evidence-terminalized from their durable records; only class-declared lossy hints may be dropped, while already-applied effects are not undone. - - Action: Game Session halts ticks/commands for affected regions, following the Redis outage policy; after Redis recovers, the recovery subsystem and operators decide whether to skip, retry, or repair missing ticks. + - Action: Game Session halts ticks/commands for affected regions, following the Redis outage policy; after Redis recovers, the owner recovery subsystem or operators may choose retry or repair for missing ticks after validating, persisting, and passing the exact ADR 0085 handoff (`operationId`, fence/lock binding, classifier decision, evidence digest, and complete affected scope) unchanged. A skip is permitted only for an explicitly disposable ADR 0058 hint or after ADR 0058 reconciliation durably proves an empty cadence with no unresolved authoritative work; otherwise recovery replays or reconciles durable work, retaining inconclusive items as non-terminal. A non-conflicting routine replay may omit that maintenance operation only when the owner explicitly records the specific classification and evidence; missing or incomplete handoff/classification fails closed and escalates. These scenarios assume the Redis persistence/profile contract described in `system-architecture-redis.md`. If AOF or replication settings differ, the same ADR 0058 class-specific outcomes and ledger replay rules still apply, but the measured coordination-exposure evidence and affected recovery scope may change. @@ -427,9 +438,9 @@ In rare cases, a `tick:{tenantRegionTag}:pending` entry may remain present even - Regions where `tick:{tenantRegionTag}:pending` has not advanced despite repeated recovery attempts. - Candidate stuck ticks are enqueued into a `tick_recovery` queue or table with metadata such as ``. The namespace identifier must be carried by the candidate or resolved from an authoritative, namespace-bound runtime record before any shadow-state lookup, cleanup, replay, or mutation; an unbound or ambiguous resolution fails closed. Metrics and Redis contents identify candidates only; they do not establish the authoritative region, namespace, epoch, or owner. - An automated recovery worker: - - Re-reads the current control-plane/runtime-health authority for the complete candidate scope and, before any recovery or cleanup mutation, revalidates the same in-memory Redis lease token it acquired and the expected candidate `regionEpoch`, then separately verifies the current durable `executorFence`. A missing, stale, or mismatched token, epoch, or authority record fails closed; the worker must not persist the raw token, clear pending state, or stage/commit work under a different owner or epoch. - - Uses the same idempotent handlers and ledger/guard patterns as normal ticks to drive any effects associated with the stuck tick to terminal `APPLIED` or `ABANDONED` outcomes only when the existing evidence policy permits; inconclusive effects remain non-terminal reconciliation work and are escalated. It reconciles any higher-level tick or command status (for example `FAILED`/`SKIPPED`) from that effect evidence into the durable authoritative status record, using its monotonic status version/CAS and preserving `failureCode`/`failureMessage`; the status record is not merely a derived view, and events/metrics remain projections of it. - - Clears `tick:{tenantRegionTag}:pending` and associated retry metadata via a dedicated, idempotent helper path. + - Re-reads the current control-plane/runtime-health authority for the complete candidate scope and, before any recovery or cleanup mutation, revalidates the same in-memory Redis lease token it acquired and the expected candidate `regionEpoch`, then separately verifies the current durable `executorFence`. It must also pass the exact ADR 0085 maintenance handoff, or have the owner explicitly classify and record this specific path as non-conflicting routine idempotent replay; that classification cannot be inferred from Redis residue. A missing, stale, or mismatched token, epoch, authority record, handoff, or classification fails closed; the worker must not persist the raw token, clear pending state, or stage/commit work under a different owner or epoch. + - Uses the same idempotent handlers and ledger/guard patterns as normal ticks to drive any effects associated with the stuck tick to terminal `APPLIED` or `ABANDONED` outcomes only when the existing evidence policy permits; inconclusive effects remain non-terminal reconciliation work and are escalated. It reconciles a higher-level command status only through the canonical command-outcome contract and supported durable `executionOutcome` values, using its monotonic status version/CAS and preserving `failureCode`/`failureMessage`. Tick-local labels such as `FAILED` or `SKIPPED` are not additional canonical `GetGameplayCommandStatus` values: they must be mapped to a supported command outcome only when the complete effect evidence and command-family policy justify that mapping; otherwise the command remains pending/reconciliation-required. The status record is authoritative, while events/metrics remain projections. + - Immediately before clearing, revalidates the selected branch: the exact ADR 0085 handoff (`operationId`, external maintenance fence/lock binding, evidence-derived classifier decision, durable-evidence digest, and complete affected scope), or the owner-recorded non-conflicting routine-replay classification/evidence with its applicable fence, epoch, and scope proof. For a maintenance handoff, every operation/fence/classifier/digest/scope field must exact-match; for routine replay, missing or mismatched classification, non-conflict evidence, fence, epoch, or scope fails closed. Any stale or regressed evidence leaves `pending` and retry metadata untouched and escalates for fenced reconciliation; only then does a dedicated idempotent helper clear `tick:{tenantRegionTag}:pending` and associated retry metadata. - Emits detailed logs and metrics for audit and dashboards. - Operator tooling allows manual override for complex cases (for example, suspected data corruption), with two typical modes: - **Recommendation mode** – the system proposes recoveries; operators approve or override. @@ -445,9 +456,9 @@ Entity Management provides the reference example for per-aggregate tick idempote ## Domain Idempotency Rules (Timeline Context + Owner Guards) -Domain services use the **region-scoped tick timeline** `(regionEpoch, tickId)` as ordering and fence context, not as the canonical idempotency token for tick-driven effects. The canonical participant guard logical uniqueness is exactly `(rootEffectId, typedOperation, exact target aggregate)`; the immutable request digest is bound to that identity. If an owner-local physical partition is used, it is storage placement only and cannot alter logical uniqueness or deduplication. A guard must not substitute the timeline tuple for that root/operation/aggregate identity. +Domain services use the **region-scoped tick timeline** `(regionEpoch, tickId)` as ordering and fence context, not as the canonical idempotency token for tick-driven effects. The canonical participant guard logical uniqueness is the owner-declared runtime-family partition plus `(effectId, typedOperation, exact target aggregate)`, where `effectId` is the persisted root `EffectId` for a root operation and the persisted child `EffectId` for a generated child; S1/S2 uses `(tenantId, playableStateNamespaceId)`, while only an explicitly owner-classified S3 family uses `(tenantId, gameInstanceId)`, and unknown or unclassified families fail closed. `rootEffectId` is retained only as enclosing-root lineage and reconciliation context. The immutable request digest is bound to that identity. Additional physical partitioning used only for storage placement cannot alter this logical identity or deduplication. A narrow last-tick watermark is permitted only for an explicitly documented aggregate proven to receive at most one logical mutation per tick timeline; it must not replace the effect/participant guard for general command effects. Any applicable namespace binding is validated separately from timeline ordering and fence evidence, and a guard must not substitute the timeline tuple for the root/operation/aggregate identity. Exact allocator details remain pending and non-authoritative under the conditional [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); they do not change this accepted guard contract. -`tickId` is monotonic only **within a given `regionEpoch`** and may restart at `0` after a region-scoped or tenant-scoped reset that bumps `regionEpoch`. Any idempotency scheme that keys only on `tickId` (without `regionEpoch`) is therefore unsafe across resets. +`tickId` is monotonic only **within a given `regionEpoch`** and may restart at `0` after a region-scoped or tenant-scoped reset that bumps `regionEpoch`. Any ordering or watermark scheme that keys only on `tickId` (without `regionEpoch`) is therefore unsafe across resets; the timeline pair still does not replace the effect/participant guard. Two patterns are used: @@ -456,20 +467,21 @@ Two patterns are used: - It is a narrow exception, not the default for gameplay-visible mutations. - Typical safe uses are once-per-tick watermark-style updates or aggregates whose design guarantees a single logical writer/effect per tick. - Aggregates that may receive multiple legitimate effects in one tick must not use this pattern. - - A shadow tick-state record such as `entity_tick_state` is keyed by `(tenant_id, game_instance_id, playable_state_namespace_id, region_id, target_aggregate_type, aggregate_id)`, not by the aggregate identifier alone; `playable_state_scope` is separately persisted and exact-validated evidence, not a key dimension. + - A shadow tick-state record such as `entity_tick_state` follows its owner-declared runtime-family partition: S1/S2 uses `(tenant_id, playable_state_namespace_id)`; only explicit S3 uses the complete `(tenant_id, game_instance_id, playable_state_namespace_id, region_id, target_aggregate_type, aggregate_id)` watermark identity. For S1/S2, `game_instance_id` is separately exact-validated active-runtime authorization/fence evidence, not part of the namespace partition. `playable_state_scope` is separately persisted and exact-validated evidence, not a key dimension. - The shadow state stores at minimum: - `last_region_epoch` - `last_tick_id` - - (plus tenant/game-instance/region identifiers or a foreign key implying them) + - (plus the owner-declared partition and region/target-aggregate identifiers or a foreign key implying them; S1/S2 retains active `game_instance_id` separately as authorization/fence evidence) - When applying a tick effect: - - The handler resolves and reads the shadow tick-state row using `(tenant_id, game_instance_id, playable_state_namespace_id, region_id, target_aggregate_type, aggregate_id)`, exact-validating separately persisted `playable_state_scope` evidence; an aggregate-only, aggregate-type-free, or namespace-free lookup is invalid. + - The handler resolves the shadow tick-state row using `(tenant_id, playable_state_namespace_id, region_id, target_aggregate_type, aggregate_id)` for S1/S2, or the complete `(tenant_id, game_instance_id, playable_state_namespace_id, region_id, target_aggregate_type, aggregate_id)` identity only for explicit S3. For S1/S2 it separately exact-validates the active `game_instance_id` as authorization/fence evidence; it also exact-validates separately persisted `playable_state_scope`. An aggregate-only, aggregate-type-free, or namespace-free lookup is invalid. - If `(last_region_epoch, last_tick_id) >= (currentRegionEpoch, currentTickId)` for that exact row, the update is treated as a replay or out-of-order attempt and becomes a no-op (or, in strict modes, a validation-only check). - If `(last_region_epoch, last_tick_id) < (currentRegionEpoch, currentTickId)`, the handler applies the change and updates `(last_region_epoch, last_tick_id) = (currentRegionEpoch, currentTickId)` on that same composite-key row in the same transaction as the domain mutation. - **Operation-level effect guard** - This is the default pattern for gameplay-visible mutations. - Operations that may touch multiple aggregates or legitimately apply multiple distinct effects to the same aggregate in a single tick (for example trades, combat damage, healing, AoE damage, room occupancy changes, drops/pickups, or multi-target buffs) use a small guard table such as `tick_effect_guard` with a concrete participant projection storing: - - The uniqueness identity is the root `EffectId`, typed operation, and exact target aggregate. The immutable request digest is bound to that identity and checked on replay; the durable outcome is mutable guard-row state advanced by CAS. The concrete fields below are retained as the participant projection for scope, ordering, and target lookup and must not be mistaken for an alternative uniqueness identity. - - `root_effect_id` + - The uniqueness identity follows the owner-declared runtime family: S1/S2 uses the `(tenantId, playableStateNamespaceId)` partition, while only an explicitly owner-classified S3 family uses `(tenantId, gameInstanceId)`; each partition also includes the mutation's persisted root-or-child `EffectId`, typed operation, and exact target aggregate. A root mutation uses the root `EffectId`; a generated child uses its persisted child `EffectId` while retaining the enclosing root as lineage and reconciliation context. For S1/S2, `gameInstanceId` is separately exact-validated active-runtime authorization/fence evidence. The immutable request digest and applicable namespace binding are bound evidence exact-compared on replay; `playableStateScope`, active-instance evidence, timeline, and lineage remain immutable projection evidence, and durable outcome/evidence is mutable guard-row state advanced by CAS. The concrete fields below are retained as the participant projection for scope, ordering, and target lookup and must not be mistaken for an alternative uniqueness identity. Unknown or unclassified families fail closed before guard admission and are never inferred to be S3. + - `effect_id` (the persisted mutation `EffectId` used by guard uniqueness) + - `root_effect_id` (enclosing root lineage and reconciliation context) - `typed_operation` - `tenant_id` - `game_instance_id` @@ -479,46 +491,47 @@ Two patterns are used: - `region_epoch` - `tick_id` - `effect_key` – a deterministic identifier describing the logical effect (for example `entity::award:achievement:` or `room::drop:item:`). + - `request_digest` – immutable request digest bound to the participant guard and compared on replay, not a uniqueness input. - `target_aggregate_type` - `target_aggregate_id` - - Inside the same transaction as the domain update, the handler attempts to insert a participant guard whose uniqueness identity is exactly `(root EffectId, typed operation, target aggregate type, target aggregate ID)`, binding the immutable request digest and storing the namespace-complete concrete projection `(root_effect_id, typed_operation, tenant_id, game_instance_id, playable_state_namespace_id, playable_state_scope, region_id, region_epoch, tick_id, effect_key, target_aggregate_type, target_aggregate_id)` as scope/order/ledger metadata. Replay and exact-set comparisons must compare the namespace as well as the scope; an implementation may omit a separate projection column only when the root/target guard is an authoritative, exact namespace-bound proof that is enforced by the owner transaction: + - Inside the same transaction as the domain update, the handler attempts to insert a participant guard whose collision-safe uniqueness identity follows the owner-declared runtime family: `(tenantId, playableStateNamespaceId, mutation EffectId, typed operation, target aggregate type, target aggregate ID)` for S1/S2, or `(tenantId, gameInstanceId, mutation EffectId, typed operation, target aggregate type, target aggregate ID)` only for explicit S3. `tenantId` and `playableStateNamespaceId` partition namespace-backed S1/S2 guards, while `tenantId` and `gameInstanceId` partition explicitly disposable S3 guards; for S1/S2, `gameInstanceId` is separately exact-validated active-runtime authorization/fence evidence. `playableStateScope`, timeline, digest, and lineage fields are immutable bound evidence, not additional uniqueness inputs. The guard binds the immutable request digest and stores the namespace-complete concrete projection `(effect_id, root_effect_id, typed_operation, tenant_id, game_instance_id, playable_state_namespace_id, playable_state_scope, region_id, region_epoch, tick_id, effect_key, target_aggregate_type, target_aggregate_id)` as scope/order/ledger metadata. For a generated child, `root_effect_id` is retained as enclosing lineage/reconciliation context and is not substituted for `effect_id`. Unknown or unclassified families, or work explicitly outside playable-state scope without an accepted owner-specific partition, are rejected before this insert. - If the insert succeeds, the effect is new for this participant identity and the handler applies all associated state changes, advancing mutable outcome state by CAS as required. - - If the uniqueness identity conflicts, the handler compares the stored namespace, typed operation, exact target aggregate, and immutable request digest. An exact existing guard replay returns its stored outcome without reapplying domain state; any changed namespace, operation, target, or digest fails closed. It must also verify the complete expected participant-guard set and corresponding authoritative state. Only a complete, consistent set is a replay/no-op; a partial conflict is incomplete and must reconcile the original root `EffectId` or fail closed. - - A replay at a later coordinate that retains the same root `EffectId`, typed operation, namespace, and target aggregate therefore reuses/conflicts with the same guard; `region_epoch`, `tick_id`, and `effect_key` metadata cannot create a second participant guard. + - If the uniqueness identity conflicts, the handler compares the stored owner-declared runtime-family partition, typed operation, exact target aggregate, immutable request digest, applicable `playableStateNamespaceId` binding, separately bound `playableStateScope` evidence, and separately validated active-instance authorization/fence evidence. An exact existing guard replay returns its stored outcome without reapplying domain state; any changed family/partition, operation, target, digest, namespace, scope, or active-instance evidence fails closed. It must also verify the complete expected participant-guard set and corresponding authoritative state. Only a complete, consistent set is a replay/no-op; a partial conflict is incomplete and must reconcile the original mutation `EffectId` and enclosing root lineage or fail closed. + - A replay attempted later in physical time with the same mutation `EffectId`, typed operation, and target aggregate reuses the same guard only when it carries and exactly matches the original sealed runtime-family partition and namespace-complete timeline projection, including the bound namespace where applicable, separately bound `playableStateScope`, active-instance authorization/fence evidence, `region_epoch`, and `tick_id`. A request with changed coordinates or a changed active-instance fence is conflicting reuse and fails closed; neither changed coordinates nor `effect_key`, enclosing-root lineage, or mutable outcome/evidence state can create a second participant guard or overwrite the original projection. Examples: - **Once-per-tick aggregate watermark (per-aggregate last-tick state)** - `AdvanceRegionAuraWatermark` receives `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, targetAggregateType, targetAggregateId)`. - The design guarantees this aggregate is advanced at most once per tick. - - It reads the shadow tick state for the complete `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, targetAggregateType, targetAggregateId)` key, exact-validating separately persisted `playableStateScope` evidence, and applies the update only when `(last_region_epoch, last_tick_id) < (regionEpoch, tickId)`. + - For S1/S2, it reads the shadow tick state in the owner-defined `(tenantId, playableStateNamespaceId, regionId, targetAggregateType, targetAggregateId)` partition and separately exact-validates active `gameInstanceId` as authorization/fence evidence; only explicit S3 uses the complete `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, targetAggregateType, targetAggregateId)` instance-keyed identity. It also exact-validates separately persisted `playableStateScope` evidence and applies the update only when `(last_region_epoch, last_tick_id) < (regionEpoch, tickId)`. - If `(last_region_epoch, last_tick_id) >= (regionEpoch, tickId)`, the handler treats the request as a replay/out-of-order and returns without changing state. - **Trade between two entities (operation-level effect guard)** - - The `TradeItem` endpoint explicitly receives `rootEffectId` and immutable `requestDigest` in addition to `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, fromEntityId, toEntityId, itemId)`. It creates one participant guard/ledger projection linked to that root effect per affected inventory aggregate. + - The `TradeItem` endpoint explicitly receives `rootEffectId` (the mutation `EffectId` for this root operation) and immutable `requestDigest` in addition to `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, fromEntityId, toEntityId, itemId)`. It creates one participant guard/ledger projection linked to that mutation/root effect per affected inventory aggregate. - The typed operation is `TradeItem`; it computes `effectKey = "trade:" + fromEntityId + ":" + toEntityId + ":" + itemId` only as stored projection/ledger metadata, not as guard uniqueness identity. - In one transaction it: - - Attempts to insert one guard per affected inventory aggregate with uniqueness identity `(rootEffectId, typed operation=TradeItem, targetAggregateType=INVENTORY, targetAggregateId)`, binding and comparing `requestDigest` and retaining `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey)` as namespace-complete projection/ledger metadata. - - If any uniqueness identity conflicts, it re-reads the complete expected guard set and the authoritative state of both source and target inventories. Only a complete guard set whose root effect, typed operation, target aggregates, immutable `requestDigest`, and inventory state all match the committed transfer is a replay/no-op; a partial conflict, missing guard, or mismatch must reconcile the original root effect or fail closed. `effectKey` is never used to admit a replay. + - Attempts to insert one guard per affected inventory aggregate with the namespace-backed S1/S2 inventory uniqueness identity `(tenantId, playableStateNamespaceId, mutation EffectId=rootEffectId, typed operation=TradeItem, targetAggregateType=INVENTORY, targetAggregateId)`. Inventory is durable player value and therefore remains namespace-stable, with any S2 version mapping validated and applied by its owner; it is not an S3 disposable family. The guard binds and exact-compares `requestDigest`, separately validates active `gameInstanceId` authorization/fence evidence, and retains `playableStateScope`, `regionId`, `regionEpoch`, `tickId`, and `effectKey` as exact-bound projection/ledger evidence, not additional uniqueness dimensions. + - If any uniqueness identity conflicts, it re-reads the complete expected guard set and the authoritative state of both source and target inventories. Only a complete guard set whose mutation/root effect, typed operation, target aggregates, immutable `requestDigest`, and inventory state all match the committed transfer is a replay/no-op; a partial conflict, missing guard, or mismatch must reconcile the original mutation/root effect or fail closed. `effectKey` is never used to admit a replay. - If the insert succeeds, it debits the item from `fromEntityId`, credits it to `toEntityId`, and commits both inventory changes and the guard-row insert together. Operationally: -- Every tick-driven write path must use either the per-aggregate `last_tick_id` pattern or the operation-level guard pattern. -- The default review assumption is that a gameplay-visible mutation requires an effect guard unless the design explicitly proves “at most one logical effect per aggregate per tick”. +- Every tick-driven write path must use the operation-level guard pattern by default; the per-aggregate `last_tick_id` pattern is allowed only with an explicit proof of at-most-one logical mutation per tick timeline. +- The default review assumption is that a gameplay-visible mutation requires an effect guard unless the design explicitly proves “at most one logical effect per aggregate per tick”; that proof must not be inferred from `(regionEpoch, tickId)` alone. - Domain handlers treat Redis locks and leases as opaque; they never read `tick:{tenantRegionTag}:lock:` or `tick-executor-lease:{tenantRegionTag}` directly. - Operations that cannot be made idempotent or compensatable at the domain layer—for example payments, emails, or webhooks into third-party systems—must not be executed directly inside tick-driven handlers. Those flows must use the saga/outbox patterns in `system-architecture-transactions.md` so they can tolerate retries and partial failures independently of tick replay. ### Effect Identity, Endpoint Semantics, and Outcome Metrics -Tick-driven domain calls use the stable root `EffectId` plus a shared participant guard contract for retries: +Tick-driven domain calls use the mutation's persisted root-or-child `EffectId` plus a shared participant guard contract for retries: -- Game Session assigns the stable root `EffectId` for the logical effect. A concrete ledger/guard/storage projection must carry the namespace-complete identity and tick context `(rootEffectId, typedOperation, tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)` for scope, ordering, and exact target lookup, unless the owner transaction enforces an equivalent namespace-bound root/target proof. It remains linked to the root identity. Each participant derives its guard uniqueness identity from the root `EffectId`, typed operation, and exact target aggregate, binding the immutable request digest; durable outcome/evidence state is mutable guard-row state protected by CAS. Additional operation-specific distinctions belong in that typed operation/target/request-digest contract; they must not create a competing root identity. -- Game Session passes the same opaque root `EffectId` plus the structured operation, target, request digest, and any concrete ledger projection fields to each tick-invoked handler. Handlers validate and project that contract into their own guards; they must not generate fresh random IDs, re-derive from mutable payload, or silently drop required scope or target fields. +- A concrete ledger/guard/storage projection must carry the namespace-complete applicable mutation identity and tick context `(effectId, rootEffectId, typedOperation, tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)` for scope, ordering, and exact target lookup; generated children retain `rootEffectId` as lineage and reconciliation context. Participant-guard uniqueness remains distinct from any effect-allocation binding: each participant derives its guard identity from the owner-declared runtime-family partition—`(tenantId, playableStateNamespaceId)` for S1/S2 or `(tenantId, gameInstanceId)` only for explicit S3—plus the mutation's persisted `EffectId`, typed operation, and exact target aggregate, binding the immutable request digest and applicable namespace evidence. For S1/S2, `gameInstanceId` is separately exact-validated active-runtime authorization/fence evidence; durable outcome/evidence state is mutable guard-row state protected by CAS. Unknown or unclassified families, and work explicitly outside playable-state scope without an accepted owner-specific partition, fail closed before guard admission. Additional operation-specific distinctions belong in that typed operation/target/request-digest contract; they must not create a competing mutation identity. Command-root allocation details remain pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). +- Game Session passes the mutation's persisted root-or-child `EffectId` plus the structured operation, target, immutable request digest, and any concrete ledger projection fields to each tick-invoked handler. Generated children also carry their enclosing root/parent lineage binding. Handlers validate and project that contract into their own guards; they must not generate fresh random IDs, re-derive from mutable payload, or silently drop required scope or target fields. Every gRPC endpoint that can be invoked from tick execution must document and implement: - **Duplicate handling** – repeated calls with the same effect identity must return OK / “already applied” semantics (for example, no new HP or inventory changes) instead of logical errors that drive infinite retries. -- **Already-in-desired-state handling** – if the target state already reflects the intended outcome, the endpoint first resolves the participant guard in the owner transaction. An exact existing guard with the same root `EffectId`, typed operation, exact target aggregate, and immutable `requestDigest` returns its stored outcome; when no matching guard exists, the owner records a new durable guarded no-op under the current root `EffectId`, typed operation, exact target, and `requestDigest` before returning OK. Mutable state already matching the requested value is not replay evidence by itself, and a conflicting or ambiguous guard fails closed. + - **Already-in-desired-state handling** – if the target state already reflects the intended outcome, the endpoint first resolves the participant guard in the owner transaction. An exact existing guard with the same owner-declared runtime-family partition (S1/S2 `(tenantId, playableStateNamespaceId)` or explicit S3 `(tenantId, gameInstanceId)`), mutation `EffectId` (root or persisted child), typed operation, exact target aggregate, immutable `requestDigest`, separately persisted `playableStateScope`, and separately exact-validated active-instance fence evidence returns its stored outcome; unknown or unclassified families, or work explicitly outside playable-state scope without an accepted owner-specific partition, are rejected before guard admission. When no matching guard exists, the owner records a new durable guarded no-op under the same conditional partition and exact evidence before returning OK. A generated child also retains its enclosing root as lineage and reconciliation context. Mutable state already matching the requested value is not replay evidence by itself, and a conflicting or ambiguous guard fails closed. - **Retry classification** – errors must be classified as retryable (transient infrastructure issues) vs terminal (invalid inputs, missing aggregates). Terminal errors may move the corresponding ledger/guard entry into a terminal state (for example `ABANDONED`) only when the error and durable evidence prove that no required mutation succeeded; inconclusive work remains reconciliation-required rather than entering a retry loop or being bulk-terminalized. Endpoints participating in tick-driven effects should also emit a small, standardized metric: @@ -571,7 +584,7 @@ Coordination resets are expressed in terms of Redis scopes (region, tenant, clus - Timeline impact: - A tenant reset is an orchestration over every running or recoverable `gameInstanceId` belonging to the tenant, not a single tenant-only key scan or epoch. The reset first snapshots the authoritative game-instance inventory and mapping generation under the reset lease, then enumerates every `` pair and reads each region's current `regionEpoch` and executor fence. - For every enumerated game instance and every one of its regions, the region-scoped coordination keys are cleared and that instance-region's `regionEpoch` is bumped independently. A changed mapping generation, missing instance/region, lost lease, or fence mismatch fails closed before the next mutation; it must not reset only the regions visible in Redis. - - Cross-region flows (for example follow-ups) resume only under the new epochs; stale follow-ups from previous epochs are ignored or reconciled. + - Cross-region flows (for example follow-ups) resume only under the new epochs; stale follow-ups from previous epochs are reconciled under the [Inconclusive Old-Epoch Reconciliation Policy](#inconclusive-old-epoch-reconciliation-policy), never ignored, and remain `APPLIED`, evidence-qualified `ABANDONED`, or fenced non-terminal `SCHEDULED` according to that policy. - Gameplay session records follow the canonical reset-policy matrix in [Redis Reset & Recovery](./system-architecture-redis-reset-and-recovery.md), while `sessionctx:*` pre-auth context is always invalidated or rebuilt and is never preserved. A tenant reset does not perform account-wide token invalidation. Preserved gameplay sessions must rebind after auth validation. - Ledger behavior: - Tick effect ledger rows for each enumerated instance-region scope with `status = SCHEDULED` follow the [Inconclusive Old-Epoch Reconciliation Policy](#inconclusive-old-epoch-reconciliation-policy): inspect durable domain state and any existing `APPLIED` reflection first, mark confirmed reflections `APPLIED`, and mark `ABANDONED` with a tenant-scoped reset reason such as `RESET_TENANT_SCOPED` only when domain state confirms the effect was unapplied and cannot be safely re-driven across the reset. @@ -596,8 +609,8 @@ Coordination resets are expressed in terms of Redis scopes (region, tenant, clus In all three cases, the **goal is convergence**: -- For each complete expected concrete participant-projection set linked to a root `EffectId`, every expected `(rootEffectId, typedOperation, tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, targetAggregateType, targetAggregateId)` projection must eventually have exactly one terminal ledger state (`APPLIED` or `ABANDONED`) when the evidence policy permits terminalization. `typedOperation` is part of the expected set alongside the root and exact target aggregate; `effectKey` remains descriptor metadata for correlation and lookup. Reconciliation rejects missing, extra, partial, or conflicting projections; any inconclusive row remains reconciliation-required and non-terminal, with old-epoch rows additionally following the [Inconclusive Old-Epoch Reconciliation Policy](#inconclusive-old-epoch-reconciliation-policy), including across resets. -- Reset tooling and Game Session control flows must ensure that no tick remains forever “half-applied” in the ledger (for example, perpetually `SCHEDULED` with no chance of replay), by running a per-effect tick-effect-ledger reconcile for the relevant `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch)` combinations as part of the reset flow. The reconcile must inspect durable domain state before terminalizing each row and may abandon only effects confirmed unapplied. +- For each complete expected concrete participant-projection set linked to an enclosing root `EffectId`, every expected `(effectId, rootEffectId, typedOperation, tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, targetAggregateType, targetAggregateId)` projection must eventually have exactly one terminal ledger state (`APPLIED` or `ABANDONED`) when the evidence policy permits terminalization. `effectId` is the mutation's persisted root-or-child `EffectId`; `rootEffectId` remains enclosing lineage and reconciliation context. `typedOperation` is part of the expected set alongside the mutation ID and exact target aggregate; guard uniqueness follows the owner-declared runtime-family partition (`tenantId + playableStateNamespaceId` for S1/S2, `tenantId + gameInstanceId` only for explicit S3), while `playableStateScope`, active-instance evidence, and `effectKey` remain immutable projection/descriptor evidence rather than additional uniqueness dimensions. Reconciliation rejects missing, extra, partial, or conflicting projections; any inconclusive row remains reconciliation-required and non-terminal, with old-epoch rows additionally following the [Inconclusive Old-Epoch Reconciliation Policy](#inconclusive-old-epoch-reconciliation-policy), including across resets. +- Reset tooling and Game Session control flows must ensure that no tick remains forever “half-applied” in the ledger (for example, perpetually `SCHEDULED` with no chance of replay), by running a per-effect tick-effect-ledger reconcile for the relevant `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch)` combinations as part of the reset flow. The reconcile must inspect durable domain state before terminalizing each row and may abandon only effects confirmed unapplied; inconclusive effects remain `SCHEDULED`/reconciliation-required, and reset reconciliation must neither force nor require their terminalization without that evidence. These expectations should be reflected in the coordination reset tooling described in `system-architecture-redis-operations.md` and the reset policy matrix in `system-architecture-redis-reset-and-recovery.md`. @@ -605,11 +618,11 @@ These expectations should be reflected in the coordination reset tooling describ Cross-region tick-driven flows (such as combat actions that affect entities in multiple regions) are designed to be **best-effort and eventually consistent** by default rather than globally atomic across regions: -- Each leg of a cross-region flow (origin-region effects, target-region effects, and any results relayed back) uses its own `EffectId` and converges independently to `APPLIED` or `ABANDONED` in the tick effect ledger only when the existing evidence policy permits terminalization; inconclusive work remains non-terminal reconciliation work under its original root `EffectId` and is escalated, with old-epoch work additionally following the applicable reset policy. +- Each leg of a cross-region flow (origin-region effects, target-region effects, and any results relayed back) uses its own persisted mutation `EffectId` and converges independently to `APPLIED` or `ABANDONED` in the tick effect ledger only when the existing evidence policy permits terminalization; inconclusive work remains non-terminal reconciliation work under its original mutation `EffectId`, with its enclosing root retained as lineage, and is escalated, with old-epoch work additionally following the applicable reset policy. - Origin regions derive a high-level **command outcome** (for example `SUCCESS`, `PARTIAL`, `FAILED`) from the combination of leg outcomes and timeouts only under the command family’s ADR 0053 declaration. `PARTIAL` is valid only for a permitted terminal subset declared before execution; unresolved required work remains `PENDING`, and a timeout or multi-leg failure does not silently become an undeclared `PARTIAL`. - Features that truly require “all-or-nothing across regions” semantics must build that coordination explicitly on top of the tick primitives (for example using saga/outbox patterns outside the tick loop as described in `system-architecture-transactions.md`); it is not provided implicitly by the tick engine. -When origin reconciliation accepts a target result that drives a dependent child effect (for example, remote lifesteal damage driving a local heal), the acceptance transition is crash-safe: it cannot become durable without a deterministic child-effect intent. The accepted result and child intent commit in one owner-local transaction when possible, or a resumable durable acceptance intent records both before acceptance is acknowledged. Acceptance replay reuses the child identity and exact accepted-result digest; missing, extra, partial, or conflicting result/intent projections fail closed. This is a durability consequence of the existing coordinator lifecycle, not a new outcome. +When origin reconciliation accepts a target result that drives a dependent child effect (for example, remote lifesteal damage driving a local heal), the acceptance transition is crash-safe: it cannot become durable without a deterministic child-effect intent. The accepted result and child intent commit in one owner-local transaction when possible, or a resumable durable acceptance intent records both before acceptance is acknowledged. Acceptance replay reuses the child identity and exact accepted-result digest; missing, extra, partial, or conflicting result/intent projections fail closed. This is a durability consequence of the existing coordinator lifecycle, not a new outcome. Any future opaque allocation shape remains conditional on the non-authoritative [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). Operationally: @@ -628,7 +641,7 @@ Region resets and epoch bumps intentionally sever the old coordination timeline - When a target region’s `regionEpoch` is bumped (via region/tenant/cluster reset): - Recovery first completely enumerates every undrained follow-up and `SCHEDULED` ledger row for the old epoch from durable storage. Conclusive rows terminalize as `APPLIED` or `ABANDONED` with a reset/topology reason under the authority-fenced policy; an inconclusive row keeps the scope fenced and cannot be hidden by Redis loss or omitted from the enumeration. - The ledger replay controller applies the [Inconclusive Old-Epoch Reconciliation Policy](#inconclusive-old-epoch-reconciliation-policy): it marks confirmed reflections `APPLIED`, converges only effects confirmed unapplied to `ABANDONED` with a reset-specific reason (for example `RESET_REGION_SCOPED` or `RESET_TENANT_SCOPED`), and keeps inconclusive effects non-terminal under their original EffectId for authority-fenced reconciliation rather than attempting to “replay them into the new epoch”. Normal current-epoch replay is forbidden. - - Target-region tick executors ignore old-epoch work based on epoch/tick guards in their coordination scripts; they only stage and apply effects for the current epoch. + - Target-region tick executors reject old-epoch work as non-executable based on epoch/tick guards in their coordination scripts; they only stage and apply effects for the current epoch. That rejection is not a terminal outcome or a disposable “ignored” observation: the durable follow-up/ledger identity remains enumerated and must reconcile to ledger `status=APPLIED`, evidence-qualified ledger `status=ABANDONED`, or retained ledger `status=SCHEDULED` with explicit `reconciliation_required` metadata/reason and its scope fenced. An ambiguous or missing execution response therefore cannot strand the follow-up behind an `ignored` label or make it eligible in the new epoch. - Origin regions: - Observe evidence-backed `ABANDONED` outcomes for remote legs and compute the appropriate high-level command outcome only when the command family declared that terminal combination before execution; unresolved required work, including timeouts without authoritative non-application evidence, remains `PENDING`/reconciliation-required rather than becoming `PARTIAL`. - Surface player-facing feedback consistent with that outcome (for example “your cross-region trade failed due to region reset; your currency has been refunded”). @@ -645,7 +658,7 @@ Cross-region follow-ups are durable PostgreSQL records owned by Game Session (or - `tenant_id`, `target_game_instance_id`, `target_playable_state_namespace_id`, resolved `target_playable_state_scope`, `target_region_id`, `target_region_epoch` - `due_tick_id` in the target region timeline (preferred; do not use wall-clock due-time fields for cross-region follow-up eligibility) - `origin_effect_id` for the originating leg and a distinct `target_effect_id` for the target leg, plus the target-leg `typed_operation`, `effect_key` (stable descriptor/correlation metadata only), `target_aggregate_type`, and `target_aggregate_id`. - - An immutable `request_digest` and sealed required-participant manifest (or immutable manifest reference plus digest) are persisted as binding/comparison evidence. Target admission and replay compare the exact operation, target, digest, and manifest binding; any missing, conflicting, or mismatched value fails closed. + - An immutable `request_digest` and sealed required-participant manifest (or immutable manifest reference plus digest) are persisted as binding/comparison evidence. Target admission and replay compare the exact operation, target, namespace, separately persisted `playable_state_scope`, digest, and manifest binding; any missing, conflicting, or mismatched value fails closed. - exact target identity plus required feature preconditions for ownership, location, and aggregate version. Target execution requires those preconditions to remain valid under current authoritative state and executor fence; matching `target_region_epoch` and `due_tick_id` alone are insufficient. - `due_tick_id` is computed from the authoritative region status read, not from Redis hint keys. Current live uses `GetRuntimeOwnershipStatus` and its committed region/epoch/tick fields; target state uses `GetRegionTickStatus` / `RegionStatus.lastCommittedTickId`. The target owner compare-and-set persists and exact-compares this coordinate with the target epoch when admitting/claiming the follow-up; retries and replays reuse it, but it is not part of stable follow-up uniqueness: - Canonical baseline: `due_tick_id = target_last_committed_tick_id + delta_ticks` (for immediate eligibility, `delta_ticks = 1`). @@ -662,11 +675,11 @@ Cross-region follow-ups are durable PostgreSQL records owned by Game Session (or - Origin-side reconciliation claims that row idempotently and advances the coordinator only after the correlation matches the durable coordinator record. A transient message, target-only `gameInstanceId`, or mutable command payload is not sufficient correlation. - **Topology changes** - Mapping-changing split/merge operations must bump `regionEpoch` for affected source/target regions before follow-up draining resumes (see required topology protocol in `system-architecture-ticks.md`). - - **Target-state rollover invariant:** If a topology change needs a new target leg, the old follow-up identity and the new identity must be handled atomically: one durable transaction creates and links the new target record, then marks the old identity `ABANDONED` only after that new record is durable and the existing per-effect evidence policy permits terminalization. If the records cannot share a transaction, persist a fenced durable rollover intent containing both identities, the desired mapping, and the sealed follow-up context; recovery retries that intent until the new record and link are durable before terminalizing the old identity, while inconclusive old-epoch work remains non-terminal under its original root `EffectId`. + - **Target-state rollover invariant:** If a topology change needs a new target leg, the old follow-up identity and the new identity must be handled atomically: one durable transaction creates and links the new target record, then marks the old identity `ABANDONED` only after that new record is durable and the existing per-effect evidence policy permits terminalization. If the records cannot share a transaction, persist a fenced durable rollover intent containing both identities, the desired mapping, and the sealed follow-up context; recovery retries that intent until the new record and link are durable before terminalizing the old identity, while inconclusive old-epoch work remains non-terminal under its original mutation `EffectId`, with its enclosing root retained as lineage and reconciliation context. - **Current drift:** The current cross-region follow-up path has durable rows and epoch/mapping checks but does not yet claim this atomic or recoverable rollover boundary. Until it is implemented and proven, topology tooling must remain paused/fenced and must not mark an old identity `ABANDONED` merely because its mapping changed. - If region split/merge changes which region owns the target entity, topology-change tooling must either: - Complete the atomic or durable-intent rollover above, creating a new target-leg/follow-up identity for the new `(target_game_instance_id, target_region_id, target_region_epoch)` before marking the old identity `ABANDONED` with a topology-change reason only where the existing per-effect evidence policy permits. The new record must carry a fresh `target_effect_id`, the typed operation, its sealed manifest and immutable request digest, and a new `due_tick_id`, linked to the old identity by durable correlation; updating only the target instance, region, or epoch on the old record is forbidden. - - Mark it `ABANDONED` with a topology-change reason only when the existing evidence policy proves replaying it under the new mapping is not valid and no required mutation succeeded; otherwise retain the old identity as non-terminal reconciliation work under its original root `EffectId`. + - Mark it `ABANDONED` with a topology-change reason only when the existing evidence policy proves replaying it under the new mapping is not valid and no required mutation succeeded; otherwise retain the old identity as non-terminal reconciliation work under its original mutation `EffectId`, with its enclosing root retained as lineage and reconciliation context. ## Remote Hint Markers and Resets @@ -690,10 +703,13 @@ When debugging cross-region issues, operators should rely on PostgreSQL follow-u Because crash recovery relies on idempotent handlers, each service with tick-driven logic should include integration tests that simulate Redis-style replays: -- Invoke the same handler multiple times with the same root `EffectId`, typed operation, target, immutable request digest, concrete ledger/guard projection `(rootEffectId, typedOperation, tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)`, and payload, and assert that: +Select validation commands and assign evidence ownership according to [Validation and Runtime Proof](../developer-workflows/validation-and-runtime-proof.md); this checklist does not add validation results or a validation ledger. + +- Invoke the same handler multiple times with the same mutation `EffectId` (root or persisted child), typed operation, target, immutable request digest, enclosing root lineage where applicable, concrete ledger/guard projection `(effectId, rootEffectId, typedOperation, tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)`, and payload, and assert that: - The first call mutates state as expected. - Subsequent calls are treated as replays and do not apply additional logical effects (HP changes, inventory moves, etc.). -- Repeat the same `effectKey` against a different `targetAggregateType` or `targetAggregateId` and assert that the distinct target is not incorrectly deduplicated. For script-generated fan-out effects, vary `automationDispatchId` and, as applicable, the root `EffectId`, typed operation, and target aggregate to create distinct logical identities; `effectKey` is projection/storage metadata, never guard uniqueness. A request-digest mismatch for the same guard identity must fail closed. +- Repeat the same `effectKey` against a different `targetAggregateType` or `targetAggregateId` and assert that the distinct target is not incorrectly deduplicated. For script-generated fan-out effects, vary `commandOrdinal` under one `automationDispatchId` and assert distinct logical identities, then replay the same dispatch/ordinal pair and assert stable deduplication; also vary, as applicable, the persisted root-or-child `EffectId`, enclosing root lineage, typed operation, and target aggregate. `effectKey` is projection/storage metadata, never guard uniqueness, and a request-digest mismatch for the same guard or dispatch/ordinal identity must fail closed. +- If ADR 0183 is accepted, add focused proof for its command-plan ordering, `planOrdinal`, and root-allocation requirements in that ADR's proof checklist. Those proposed requirements are not accepted proof obligations here. - Exercise both idempotency strategies: - Per-aggregate `last_tick_id` tables (for single-entity updates). - Operation-level `tick_effect_guard` tables (for multi-entity effects). @@ -715,8 +731,9 @@ When introducing a new command type that will run under tick control, design doc - Does it run because an entry is dequeued from `tick:{tenantRegionTag}:queue:` or because a tick timer/retry fired? - If not, it may follow different idempotency rules and does not belong in this section. - **What is the idempotency key?** - - For single-aggregate updates: which complete `(tenant_id, game_instance_id, playable_state_namespace_id, region_id, target_aggregate_type, aggregate_id)` key, separately validated `playable_state_scope` evidence, and `(last_region_epoch, last_tick_id)` (or equivalent) fields and table enforce “at most one update per tick timeline” for that aggregate? - - For multi-aggregate or multi-effect operations: what participant guard identity combines the root `EffectId`, typed operation, and target aggregate, and how is the immutable request digest bound and checked? `effect_key` is a concrete storage projection/descriptor, not a replacement for that guard identity. + - Command-plan ordering, ordinal assignment, and root-allocation behavior are pending in ADR 0183. Do not treat those proposal details as accepted invariants or proof obligations unless that ADR is accepted. + - For single-aggregate updates: has the owner proved that the aggregate receives at most one logical mutation per tick and declared its runtime family? An explicit S3 watermark uses the complete `(tenant_id, game_instance_id, playable_state_namespace_id, region_id, target_aggregate_type, aggregate_id)` key plus separately exact-validated `playable_state_scope` evidence and `(last_region_epoch, last_tick_id)` (or equivalent) fields. An S1/S2 watermark instead uses its owner-defined namespace partition and exact-validates the active `game_instance_id` only as separate authorization/fence evidence; it must not copy the S3 instance-keyed identity. Any aggregate capable of multiple effects in one tick uses the participant/effect guard contract below instead. + - For multi-aggregate or multi-effect operations: what participant guard identity combines the mutation's persisted root-or-child `EffectId`, typed operation, and exact target aggregate, and how is the immutable request digest bound and checked? A generated child retains its enclosing root as lineage and reconciliation context; `effect_key` is a concrete storage projection/descriptor, not a replacement for that guard identity. - **Where is the guard persisted?** - Which schema/table holds the per-aggregate “last applied tick” state or `tick_effect_guard` entries? - Is there a primary key or unique index that enforces the idempotency key at the database level? diff --git a/design/architecture/system-architecture-tick-incident-runbook.md b/design/architecture/system-architecture-tick-incident-runbook.md index 53cd6ea1b3..b09afae013 100644 --- a/design/architecture/system-architecture-tick-incident-runbook.md +++ b/design/architecture/system-architecture-tick-incident-runbook.md @@ -8,6 +8,8 @@ For the detailed tick design, see: - `design/architecture/system-architecture-tick-concepts-and-invariants.md` - `design/architecture/system-architecture-tick-failures-and-operations.md` +Validation and runtime-proof selection for changes to this runbook follows the shared [Validation and Runtime Proof workflow](../developer-workflows/validation-and-runtime-proof.md); record execution results in PR/CI evidence, and update the owning implementation tracker when capability or proof status changes. + Redis coordination behavior and reset flows are defined in: - `design/architecture/system-architecture-redis.md` @@ -53,7 +55,7 @@ Normal incident escalation groups by `` as described in `system-architecture-redis-reset-and-recovery.md`. - - In shared rulesets, sustained `tick_status{scope_class=~"^(region|game_instance|tenant|cluster)$",status="STALLED"} == 1`, a prolonged `DEGRADED` rollup, or continued queue/ratio pressure starts exact-scope enumeration and authoritative status lookup; none of these class-level signals alone identifies a region, sets its status, or authorizes intervention. +- If the stall is brief and authoritative runtime-health evidence shows recovery to `RUNNING` with queues draining, continue to monitor without intervention. Use class-level execution-time ratios as supporting evidence only when the deployment advertises and proves the metric capability and the required series are present and fresh; otherwise rely on authoritative runtime-health evidence and queue drain. +- **Target state only, once implemented and proven:** If the authoritative runtime-health/control-plane record reports the exact region as `STALLED` or `DEGRADED` long enough to require action, use the class-level tick-health paging conditions as supporting detection/escalation evidence and plan a **region-scoped** coordination reset for the affected `` as described in `system-architecture-redis-reset-and-recovery.md`. + - **Current deployments:** These thresholds classify the incident and escalation severity only; they do not authorize a reset. Use read-only inspection, preserve AOF and incident evidence, keep the affected scope fenced or stopped, and escalate through the fail-closed [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback). + - In shared rulesets, sustained `tick_status{scope_class,status="STALLED"} == 1`, a prolonged `DEGRADED` rollup, or continued queue/ratio pressure starts exact-scope enumeration and authoritative status lookup; none of these class-level signals alone identifies a region, sets its status, or authorizes intervention. - Treat the control-plane/runtime-health status and its forward-progress evidence as the intervention threshold. The current live authority is `GetRuntimeOwnershipStatus` with `ObserveRuntimeTickProgress`; target state is `RegionStatus` through `GetRegionTickStatus`. -- Only escalate to a **tenant-scoped** or **cluster-wide** reset if multiple regions for the same `` group show similar symptoms or if Redis incident runbooks indicate broader coordination corruption, and only after enumerating every affected game instance, namespace/scope pair, and region and passing the explicit blast-radius approval/gate required above. + - **Target state only, once implemented and proven:** Treat `tick_status{scope_class,status="STALLED"} == 1` sustained through the environment’s alert hold time as a class-level trigger for exact-scope enumeration and authoritative status lookup, not as an intervention threshold by itself. Sustained `DEGRADED` plus over-threshold execution-time ratios or queue growth may raise escalation priority, but region action still requires the exact authoritative region tuple/status above; current deployments treat these class-level signals as diagnostic/escalation evidence only. +- **Target state only, once implemented and proven:** Only escalate to a **tenant-scoped** or **cluster-wide** reset if multiple regions for the same `` group show similar symptoms or if Redis incident runbooks indicate broader coordination corruption, and only after enumerating every affected game instance, namespace/scope pair, and region and passing the explicit blast-radius approval/gate required above. +- **Current deployments:** A broader tenant/cluster blast-radius determination is evidence and escalation only; it does not authorize a reset or broader pause. Enumerate the affected scope from authoritative mapping evidence, preserve evidence, keep affected scopes fenced, and use the fail-closed [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback). ### Act (Stalled tick region) @@ -88,7 +93,7 @@ Normal incident escalation groups by `` using the Game Session controls described in the tick architecture and Redis reset docs; missing or mismatched namespace/scope/epoch evidence fails closed. - - **Executor fencing/drain gate:** The current owner-authoritative read is `GetRuntimeOwnershipStatus`, including its opaque `executorFence`; it does not itself pause or drain an executor. The live service has no exact regional executor-disable or drain API, so do not claim that the instance-wide pause or `ObserveRuntimeTickProgress` provides that control. Keep available admission/containment controls active, and before any reset or recovery mutation verify from owner status plus the deployed control-plane/log readback that the current executor has stopped claiming work and relinquished the applicable lease/fence. If no current-live control can establish or maintain that pause/fence, preserve any active broader containment, block further mutations, mark exact containment unverified, and escalate. In the target region model, require the Game Session owner’s exact region `executorFence` and an owner-supported drain acknowledgement before reset; do not synthesize either from Redis keys or metrics. + - **Executor fencing/drain gate:** The current owner-authoritative read is `GetRuntimeOwnershipStatus`, including its opaque `executorFence`; it does not itself pause or drain an executor. The live service has no exact regional executor-disable or drain API, so do not claim that the instance-wide pause or `ObserveRuntimeTickProgress` provides that control. Keep available admission/containment controls active, ensure no new executor instances attempt to acquire the region lease while inspecting metrics, and before any reset or recovery mutation verify from owner status plus the deployed control-plane/log readback that the current executor has stopped claiming work and relinquished the applicable lease/fence. If no current-live control can establish or maintain that pause/fence, preserve any active broader containment, block further mutations, mark exact containment unverified, and escalate. In the target region model, require the Game Session owner’s exact region `executorFence` and an owner-supported drain acknowledgement before reset; do not synthesize either from Redis keys or metrics. 2. **Inspect metrics and optional workflow traces** - Use the Tick Health dashboard to confirm: - The authoritative runtime-health/control-plane record identifies the exact region as stalled or degraded. @@ -107,7 +112,7 @@ Normal incident escalation groups by `` @@ -116,17 +121,17 @@ Normal incident escalation groups by `` keys as reset-tolerant observer hints; consumers reacquire leases and re-establish baselines from the active status/progress adapter and durable domain state. - - Do not delete domain data or non-coordination prefixes. + - **Target state only, once implemented and proven:** Do not delete domain data or non-coordination prefixes. 4. **Resume ticks and verify recovery** - - Resume tick scheduling for the region only after Game Session coordination cleanup and, **once the target Automation projections exist**, executable owner-reconciled Automation cleanup/rebuild and exact readback have completed, followed by the canonical post-reset smoke gate. In the current-live branch, the instance/deployment remains paused and non-accepting while that Automation recovery is unavailable; the current operator fallback has no executable Automation cleanup/rebuild and must not claim this target gate is complete. Resume additionally requires Automation admission-mode readback to show the intended post-incident mode and a verified executor start/drain gate; Game Session resume is not sufficient evidence that Automation has resumed safely. + - **Target state only, once implemented and proven:** Resume tick scheduling for the region only after Game Session coordination cleanup and, **once the target Automation projections exist**, executable owner-reconciled Automation cleanup/rebuild, exact readback, the canonical post-reset smoke gate, and all applicable recovery release gates have completed. Target-state resume additionally requires Automation admission-mode readback to show the intended post-incident mode and a verified executor start/drain gate; Game Session resume is not sufficient evidence that Automation has resumed safely. The current-live instance/deployment remains paused and non-accepting while that Automation recovery is unavailable; the current operator fallback has no executable Automation cleanup/rebuild and must not claim this target gate is complete. - Confirm via dashboards that: - The authoritative runtime-health/control-plane record reports the exact region as `RUNNING`. - When the target-only mode-aware metric capability and fresh required series are present, `tick_status{scope_class,status="RUNNING"}` and `tick_execution_time_ms_*` ratios fall back into healthy class-level envelopes. Otherwise, use authoritative forward-progress/runtime-health readback, available queue evidence, and structured logs; unavailable ratios remain unknown and do not block current-live verification. - Command and retry queue depths stabilize. - - When the replay-ledger capability is advertised and proved, the required `tick_effects_*` metric families and bounded-label proof are current, and every required series is present and fresh, review `tick_effects_pending_total{scope_class}` for the approved bounded scope bucket to ensure the ledger is draining and not accumulating new stuck rows. If that capability or any metric/freshness proof is absent, stale, invalid, or unproved, treat the metric as `unknown` and use exact complete-scope durable tick-ledger/batch state, `GetRuntimeOwnershipStatus` with `ObserveRuntimeTickProgress`, and structured Game Session logs instead. Replay-batch/controller-progress evidence is target-only and may be used only after its controller is implemented and proved. + - **Current deployments:** Do not resume or reopen the affected scope after this reset path. Use the fail-closed [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback): keep the scope fenced or stopped, use only the shipped pause/status surface and read-only inspection, preserve evidence, and escalate. ## Tick Scheduler Pressure @@ -248,7 +253,7 @@ When this section uses target-only `tick_effects_*` replay-ledger metrics, requi - If lag persists: - Treat as a coordination cleanup incident first (not a domain correctness incident) unless ledger/backlog signals also indicate stuck effects. - Prefer region-scoped remediation before tenant- or cluster-scoped actions. -- If cleanup lag is coupled with growing ledger backlog (`tick_effects_pending_total{scope_class}`) and stale `SCHEDULED` age, run replay-controller and ledger remediation flow in parallel. +- **Target state only, once implemented and proven:** If cleanup lag is coupled with growing ledger backlog (`tick_effects_pending_total{scope_class}`) and stale `SCHEDULED` age, the recovery controller may run replay-controller and ledger remediation flows in parallel. Current operators must use the fail-closed [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback) instead. ### Act (durable commit/coordination cleanup divergence) @@ -260,9 +265,9 @@ When this section uses target-only `tick_effects_*` replay-ledger metrics, requi - Validate Redis health (latency, memory pressure, and unreplicated-write exposure) using Redis coordination dashboards. 3. **Apply scoped remediation** - Resolve each affected scope from authoritative runtime/control-plane records and carry the complete tuple `` plus the current executor fence; the bounded metrics bucket is not sufficient evidence. - - **Current-live branch:** because any deployed containment boundary is at most instance-scoped, enumerate and record every affected region and namespace/scope under the ``, obtain the broader-scope approval gate, and apply only a deployed containment/fencing control that provides authoritative scope evidence. If none is available, preserve any active broader containment, block further mutations, mark exact containment unverified, and escalate. Use `GetRuntimeOwnershipStatus` plus `ObserveRuntimeTickProgress` only as evidence-only status and forward-progress reads. Require authoritative readback of that full enumeration and fence before any cleanup action; do not describe this as an exact regional pause or reset. - - **Target-state branch:** use the exact namespace/region-qualified pause and cleanup controls, with CAS/readback proving the carried tuple and executor fence at each mutating step. If a region remains stuck, execute the region-scoped coordination reset flow in `system-architecture-redis-reset-and-recovery.md`; missing or mismatched evidence fails closed. - - Where deployed controls establish containment, keep current-live instances/deployments paused and non-accepting while Automation projection recovery is unavailable. If no current-live control can establish or maintain that state, preserve any active broader containment, block further mutations, mark exact containment unverified, and escalate. Resume only after executable owner-reconciled recovery, authoritative full-scope readback, and the canonical smoke gate. If the authoritative durable ledger shows backlog also accumulating, trigger ledger replay-controller remediation for the same fully resolved scope. + - **Current-live branch:** because any deployed containment boundary is at most instance-scoped, enumerate and record every affected region and namespace/scope under the ``, obtain the broader-scope approval gate, and apply only a deployed containment/fencing control that provides authoritative scope evidence; if none is available, preserve any active broader containment, block further mutations, mark exact containment unverified, and escalate under the current-live [executor fencing/drain gate](#act-stalled-tick-region). Use `GetRuntimeOwnershipStatus` plus `ObserveRuntimeTickProgress` only as evidence-only status and forward-progress reads. Require authoritative readback of that full enumeration and fence before any cleanup action; do not describe this as an exact regional pause or reset. + - **Target state only, once implemented and proven:** use the exact namespace/region-qualified pause and cleanup controls, with CAS/readback proving the carried tuple and executor fence at each mutating step. If a region remains stuck, execute the region-scoped coordination reset flow in `system-architecture-redis-reset-and-recovery.md`; missing or mismatched evidence fails closed. + - Keep current-live instances/deployments paused and non-accepting while Automation projection recovery is unavailable. Resume only after executable owner-reconciled recovery, authoritative full-scope readback, and the canonical smoke gate; ledger backlog does not authorize replay-controller remediation on the current-live branch, which remains fail-closed containment and escalation. Target-state deployments may trigger replay-controller remediation only after the capability/proof gate in the canonical [Ledger Replay Controller](./system-architecture-tick-failures-and-operations.md#ledger-replay-controller) contract passes for the resolved scope. 4. **Verify convergence** - Confirm `tick_cleanup_lag_ms{scope_class}` returns to normal envelope. - Confirm `tick_coordination_cleared_total{scope_class}` catches up with durable commits for affected approved bounded scope buckets. @@ -302,9 +307,9 @@ Before **Detect**, **Decide**, or **Act** interprets any target-only `tick_effec Normal replay and re-enqueue in this section apply only to effects from the current authoritative `regionEpoch`. An old-epoch effect is never replayed through the current-epoch handlers merely because it remains `SCHEDULED`. 1. **Inspect ledger and domain state** - - Use SQL or service-level admin APIs to query `tick_effects` (or the equivalent ledger table) for the exact affected `` scope; resolve `playableStateNamespaceId` authoritatively and fail closed on missing, ambiguous, or mismatched namespace evidence; do not mix rows from another `playableStateNamespaceId`, `playableStateScope`, or `regionEpoch`: - - Identify the oldest `SCHEDULED` entries and carry each complete `tick_effects` ledger projection: ``. This storage projection remains linked to the stable root `EffectId` and any participant guard identity; `effectKey` is a ledger/lookup field, not a replacement for the other tuple fields. - - The complete ledger projection, together with its linked root `EffectId` and participant-guard evidence, is authoritative for effect-level replay and reconciliation only. Phase-specific execution identities remain authoritative in their owning phase records; do not use an `EffectId` to replace admission, staging, commit, or follow-up-leg identity. + - For target-state S1/S2, use SQL or service-level admin APIs to query `tick_effects` (or the equivalent ledger table) for the exact affected `` scope; do not mix rows from another `playableStateNamespaceId`, `playableStateScope`, or `regionEpoch`. The current-live schema may expose only the documented narrower `` scope; that limitation must remain explicit rather than being treated as namespace-complete S1/S2 evidence: + - Identify the oldest `SCHEDULED` entries and, for target-state S1/S2, carry and exact-validate each complete `tick_effects` ledger projection: ``. This storage projection is keyed by the persisted mutation `EffectId` and retains any enclosing root `EffectId` as lineage/reconciliation context; `playableStateNamespaceId` is a required exact-bound S1/S2 field, and `effectKey` is a ledger/lookup field, not a replacement for the other tuple fields. Current-live may lack that namespace field at its boundary and therefore cannot claim the target-state projection is complete. + - The complete ledger projection, together with its linked mutation `EffectId`, enclosing-root lineage, and participant-guard evidence, is authoritative for effect-level replay and reconciliation only. Phase-specific execution identities remain authoritative in their owning phase records; do not use an `EffectId` to replace admission, staging, commit, or follow-up-leg identity. - When the replay-ledger capability is advertised and proven and all required series are fresh, compare `tick_effects_pending_oldest_age_seconds{scope_class}` with `tick_effects_replay_convergence_budget_seconds{scope_class}` to distinguish “brief replay delay” from “budget breach that requires active remediation”. Otherwise, treat that comparison as `unknown` and use the exact durable ledger age/status, runtime-health, and structured-log evidence; do not infer a budget breach from missing or stale metrics. - For a small sample, inspect domain state (for example entity HP, inventory, room state) to determine whether the effects have already been applied. 2. **Classify outcomes** @@ -321,9 +326,10 @@ Normal replay and re-enqueue in this section apply only to effects from the curr - For “applied but not marked” rows: - Do not update ledger rows directly to `APPLIED` from ad hoc SQL, a generic admin endpoint, or a one-off script. - Select the verifier/reconcile branch from the deployment mode; do not require target-state fields from the current-live schema or weaken the target-state gate: - - **Current-live:** Run the service-owned verifier for the exact ledger projection and linked root `EffectId`, including `effectKey` and target aggregate identity, within the exact `` scope. Resolve `playableStateNamespaceId` from authoritative namespace-bound runtime evidence and fail closed on missing, ambiguous, or mismatched namespace evidence. Read `GetRuntimeOwnershipStatus` (the current instance-scoped ownership boundary) and require the current `regionEpoch` and opaque `executorFence` to match the batch/ledger ownership snapshot. Verify that the current selected-work manifest and its `manifest_digest` match the durable source and ledger projections and the expected participant evidence. This branch may be processed without `sealed_execution_context_digest` or `sealed_execution_context_ref`, which are not present at the current-live boundary. The service-owned verifier must atomically CAS the current owner/epoch/fence, require complete manifest and participant-evidence set equality, transition the matching `SCHEDULED` row(s) to `APPLIED`, and record replay-verification evidence (including the evidence digest/reference and `replay_ok` audit) in one durable transaction. Missing, extra, or conflicting evidence, or any owner/epoch/fence mismatch, affects zero rows and fails closed with no ledger mutation. The owning domain must prove the effect is already reflected in authoritative state or in its durable participant guard; a replay no-op is not a third ledger status. - - **Target-state:** Read the current region authority from `RegionStatus`/`GetRegionTickStatus` and require exact current `regionEpoch`/`executorFence` equality. Require exactly one immutable sealed execution-context binding: either `sealed_execution_context_digest` or `sealed_execution_context_ref` resolved to its immutable digest, with the referenced context and digest matching the batch and replay request. The complete participant-projection set, sealed context, current authority/fence, and every `SCHEDULED` ledger transition must pass the same evidence-qualified CAS; a missing, stale, mismatched, incomplete, extra, or conflicting value affects zero rows and fails closed with no ledger mutation. Target-only replay-ledger metrics are optional supporting evidence only when advertised and proved with fresh required series; absent, stale, or unproved series are `unknown` and do not replace this durable evidence. - - In either branch, replay no-op is an attempt outcome, not a third ledger status, and the verifier must not reconcile the same root effect identity across region epochs. + - **Maintenance admission applies to both branches:** Before a maintenance verifier CAS may mutate a ledger row, validate the exact ADR 0085 external maintenance handoff, durably persist it, and pass it unchanged with the reconciliation evidence. An owner may omit that maintenance handoff only for a specifically classified non-conflicting routine replay with durably recorded classification/evidence and applicable fence, epoch, and scope proof, as allowed by [Tick Failures & Operations](./system-architecture-tick-failures-and-operations.md); never infer this exemption from owner, epoch, executor, manifest, or participant proof alone. If neither the exact handoff nor the owner-recorded routine-replay evidence is complete, make no mutation and use the existing fail-closed [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback) and escalate. See [Redis Reset & Recovery](./system-architecture-redis-reset-and-recovery.md#coordination-reset-model) and [ADR 0085](./decisions/adr-0085-evidence-gated-coordination-replay-and-fenced-reset.md). + - **Current-live:** Run the service-owned verifier for the exact current-live ledger projection and its persisted mutation `EffectId` (retaining any enclosing root as lineage), including `effectKey` and target aggregate identity, within the narrower `` scope. Because `playableStateNamespaceId` is not persisted at this current-live boundary, this branch cannot establish namespace-complete S1/S2 binding and must not infer the namespace from `gameInstanceId`. Read `GetRuntimeOwnershipStatus` (the current instance-scoped ownership boundary) and require the current `regionEpoch` and opaque `executorFence` to match the batch/ledger ownership snapshot. Verify that the current selected-work manifest and its `manifest_digest` match the durable source and ledger projections and the expected participant evidence. This branch may be processed without `sealed_execution_context_digest` or `sealed_execution_context_ref`, which are not present at the current-live boundary. The service-owned verifier must atomically CAS the current owner/epoch/fence, require complete manifest and participant-evidence set equality, transition the matching `SCHEDULED` row(s) to `APPLIED`, and record replay-verification evidence (including the evidence digest/reference and `replay_ok` audit) in one durable transaction. Missing, extra, or conflicting evidence, or any owner/epoch/fence mismatch, affects zero rows and fails closed with no ledger mutation. The owning domain must prove the effect is already reflected in authoritative state or in its durable participant guard; a replay no-op is not a third ledger status. + - **Target-state:** Read the current region authority from `RegionStatus`/`GetRegionTickStatus` and require exact current `regionEpoch`/`executorFence` equality. For S1/S2, require the complete namespace-bound projection `` and exact-compare `playableStateNamespaceId` (as well as every other immutable scope, identity, timeline, and target field) across the ledger, manifest, sealed context, and participant set. Require exactly one immutable sealed execution-context binding: either `sealed_execution_context_digest` or `sealed_execution_context_ref` resolved to its immutable digest, with the referenced context and digest matching the batch and replay request. The complete participant-projection set, sealed context, current authority/fence, and every `SCHEDULED` ledger transition must pass the same evidence-qualified CAS; a missing, stale, mismatched, incomplete, extra, or conflicting value affects zero rows and fails closed with no ledger mutation. + - In either branch, replay no-op is an attempt outcome, not a third ledger status, and the verifier must not reconcile a mutation under a different persisted `EffectId` across region epochs; any enclosing `rootEffectId` remains lineage and reconciliation context rather than the effect-level identity. - If no verifier exists for that effect family, treat the row as not safely proven: retain it non-terminal as `SCHEDULED`/reconciliation-required and escalate to the owning service for positive evidence. Do not re-run or mark `ABANDONED` merely because a verifier is absent. - For current-epoch rows with positive durable evidence that the effect is unapplied and an evidence-qualified service-owned replay path: - If replay is safe, enqueue follow-up commands or trigger replay using the same idempotent handlers that tick execution uses. @@ -332,7 +338,7 @@ Normal replay and re-enqueue in this section apply only to effects from the curr - For old-epoch rows, first enumerate every durable old-epoch effect and follow-up independently of Redis hints. Use the authority-fenced attestation under the original `EffectId` described in [Inconclusive Old-Epoch Reconciliation Policy](./system-architecture-tick-failures-and-operations.md#inconclusive-old-epoch-reconciliation-policy); the affected scope cannot reopen while any row remains unresolved. A new epoch lineage may be created only after both the original effect and its source claim are authority-fenced terminal `ABANDONED`; an explicitly approved maintenance or saga/outbox flow may then create a fresh current-epoch identity with durable lineage and revalidated scope. No normal replay may create or drive that new lineage, and the original effect identity must not be re-driven across the epoch boundary. - For replay-controller starvation: - Reduce per-region replay batch monopolization or other hot-region pressure first. - - If the region remains starved, run scoped replay-controller remediation for the affected complete `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch)` after authoritative enumeration and exact validation; incomplete or caller-supplied namespace/scope evidence must fail closed before any replay or maintenance mutation. Escalate to broader reset actions only after that exact scope evidence is qualified. + - **Target state only, once implemented and proven:** If the region remains starved, run scoped replay-controller remediation for the affected complete `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch)` after authoritative enumeration and exact validation; this incident remediation is maintenance, not ordinary crash replay. Before its first mutation, validate the exact ADR 0085 external maintenance handoff, durably persist it, and pass it unchanged; ledger, owner, epoch, executor, or participant evidence alone does not authorize the maintenance operation. Missing or unproved handoff means no mutation: use the fail-closed [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback) and escalate. See [Redis Reset & Recovery](./system-architecture-redis-reset-and-recovery.md#coordination-reset-model) and [ADR 0085](./decisions/adr-0085-evidence-gated-coordination-replay-and-fenced-reset.md). Incomplete or caller-supplied namespace/scope evidence must also fail closed before any replay or maintenance mutation. Escalate to broader reset actions only after that exact scope evidence is qualified. Current operators must use the fail-closed [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback) instead. 4. **Prevent recurrence** - Review Game Session and domain handlers to ensure: - Ledger status transitions happen atomically with domain commits where required. @@ -344,14 +350,14 @@ Normal replay and re-enqueue in this section apply only to effects from the curr Correlation is a lookup aid, not proof of application. Always establish the exact deployment mode before selecting an identity, and verify the candidate against the complete durable ledger projection, current ownership boundary, and participant/domain evidence. -- **Current-live correlation:** Live admission requires a present durable `commandId` in the command ledger and selected-work manifest. The current `TickStagingService` may still expose a command-text hash/slot value for legacy reconciliation only; use it only as an explicitly legacy, non-authorizing lookup aid and verify any such candidate against the exact scope and epoch, the batch `manifest_digest`, the ledger row, its linked root `EffectId` and participant guards, and authoritative domain state before invoking the service-owned verifier. It is mutable implementation metadata, never a current-live admission or fallback identity, replacement for a missing root `EffectId`, or authority to transition a row to `APPLIED`. -- **Target-state correlation:** Use only the stable root `EffectId` and its complete concrete ledger/participant projection (including the typed participant-guard identity and target aggregate). `commandId`, `effectKey`, command text, and trace attributes may narrow a search but cannot establish identity, authorize reconciliation, or permit an `APPLIED` transition. +- **Current-live correlation:** Prefer the durable `commandId` when it is present in the command ledger and selected-work manifest. When it is absent from a legacy selected-work manifest, operators may use the documented `command-text::slot:` fallback only to locate a candidate. Newly created durable batches and selections reject entries without durable command IDs in `createBatchForTick` and `commandSelections`; this fallback is not a batch-creation or selection path. The text-and-slot value is only non-authorizing correlation: verify it against the exact scope and epoch, the batch `manifest_digest`, the ledger row, its linked root `EffectId` and participant guards, and authoritative domain state before invoking the service-owned verifier. The fallback is mutable implementation metadata, never a canonical identity, replacement for a missing root `EffectId`, or authority to transition a row to `APPLIED`. +- **Target-state correlation:** Use only the persisted mutation `EffectId` and its complete concrete ledger/participant projection, retaining any enclosing root `EffectId` as lineage/reconciliation context (including the typed participant-guard identity and target aggregate). `commandId`, `effectKey`, command text, and trace attributes may narrow a search but cannot establish identity, authorize reconciliation, or permit an `APPLIED` transition. ## Using Proved Workflow Traces During Tick Incidents For all of the scenarios above, workflow traces are optional diagnostics rather than the operational baseline: -For effect-level replay and reconciliation, the exact correlation input is the complete durable ledger projection linked to the stable root `EffectId`: ``. `playableStateNamespaceId` must be authoritatively resolved and exact-validated with the rest of the scope tuple; missing, ambiguous, or mismatched namespace evidence fails closed. `effectKey`, `targetAggregateType`, and the exact `targetAggregateId` remain required ledger/lookup fields; `effect_type` and other trace attributes are exploratory filters only and cannot establish an exact effect match, authorize reconciliation, or justify a ledger transition. Command, source-claim, coordinator, and completion identities remain authoritative for their own execution phases and must not be replaced by `EffectId`. +For target-state S1/S2 effect-level replay and reconciliation, the exact correlation input is the complete namespace-bound durable ledger projection keyed by the persisted mutation `EffectId` and retaining any enclosing root lineage: ``. Exact comparison must include `playableStateNamespaceId` and every other projection field before correlation or reconciliation. Current-live may use only its narrower documented projection without `playableStateNamespaceId`; that implementation limitation is not target-state S1/S2 proof and must not be silently filled by `gameInstanceId`. `effectKey`, `targetAggregateType`, and the exact `targetAggregateId` remain required ledger/lookup fields; `effect_type` and other trace attributes are exploratory filters only and cannot establish an exact effect match, authorize reconciliation, or justify a ledger transition. Command, source-claim, coordinator, and completion identities remain authoritative for their own execution phases and must not be replaced by `EffectId`. - Only when the environment advertises and proves the named workflow-tracing capability, use Jaeger to search for spans representing tick scheduling and execution (for example `tick_schedule`, `tick_execute`) filtered by `tenantId`, `gameInstanceId`, `playableStateNamespaceId`, `playableStateScope`, `regionId`, `regionEpoch`, and, where available, `tickId`; trace filters are diagnostic and never replace authoritative exact-scope validation. - When that capability is proved, inspect stalled regions for long-running or repeated spans for the same tick IDs and cross-reference domain service spans to identify downstream bottlenecks. diff --git a/design/architecture/system-architecture-ticks.md b/design/architecture/system-architecture-ticks.md index 9299ae8b06..9fd274605e 100644 --- a/design/architecture/system-architecture-ticks.md +++ b/design/architecture/system-architecture-ticks.md @@ -34,8 +34,9 @@ Current live substrate to keep in mind while reading: - the live durable ownership and command-status boundary is currently keyed by `{tenantId, gameInstanceId}`, not true `regionId` partitioning; - the live control-plane/status APIs are `GetRuntimeOwnershipStatus` and the canonical `GetGameplayCommandStatus`; the live scheduler progress feed is `ObserveRuntimeTickProgress` carrying `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)`; `StreamTickHeartbeats` and `GetRegionTickStatus` remain target-state follow-through; - the live `executorFence` is an opaque generation token used for compare-and-match stale-fence protection, not yet the richer numeric ordering model used in some target-state examples; -- the live `tick_batch` / `tick_effect` substrate is real, and the current gameplay-command manifest now carries current-boundary `enqueueSeq`, `sourceType`, `dueTickId`, and explicit claimed-source state plus digest-checked replay reuse. The live `enqueueSeq` comes from one database-wide sequence; the region-scoped, cross-source allocator that remains monotonic across epoch resets is target-state. Timer/retry/remote-follow-up source-claim breadth and the cross-region result-return contract described below are also target-state follow-through rather than fully shipped behavior. +- the live `tick_batch` / `tick_effect` substrate is real, and the current gameplay-command manifest now carries current-boundary `enqueueSeq`, `sourceType`, `dueTickId`, and explicit claimed-source state plus digest-checked replay reuse. The live `enqueueSeq` comes from one database-wide sequence; target `entity_enqueue_seq` is monotonic within the entity's current region epoch under accepted [ADR 0065](./decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md). Timer/retry/remote-follow-up source-claim breadth and the cross-region result-return contract described below are also target-state follow-through rather than fully shipped behavior. - the live Game Session automation handoff carries `scriptPatchVersion`, positive `scriptPinEpoch`, and `scriptPinControlPlaneRequestId` on `EnqueueAutomationCommandIfAbsentRequest`; Game Session compares the tuple with authoritative owner state and rejects incomplete or stale evidence before staging or duplicate replay. Exact tuple checks also remain at the live instance-bound Automation ingress, timer, and work-item admission boundaries. The handoff still lacks `commandOrdinal` and the full Trigger Identity required for target-state per-command diagnostics. Live gameplay staging requires a present, nonblank durable `commandId` before Redis enqueue or durable batch staging, and `TickStagingService` derives `effectKey` as `command:`; complete source/target binding and remote final-effect fence proof remain implementation gaps. +- Deterministic command-plan ordering, `planOrdinal`, and command-root allocation are proposed in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) and are not accepted tick requirements. The current `tickBatchId`/`effectKey` derivation does not establish any proposal-specific allocation behavior. --- @@ -52,6 +53,8 @@ Conceptually, FireMUD treats time as **localized pulses** rather than a single g - Per-service database transactions guarded by effect identity and idempotency, and - Replayable coordination via Redis and the tick effect ledger rather than a single cross-service ACID boundary. +The command-plan order, `planOrdinal`, and command-root allocation design remain pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). Tick selection, staging, and replay do not define those proposal details. The accepted effect contract continues to require one persisted mutation identity and immutable request digest across retries and participant guards; any conserved multi-participant operation still follows ADR 0053 atomicity, co-location, or reservation semantics. + For the precise cross-service transaction model and when sagas are required, see `system-architecture-transactions.md`. See `system-architecture-tick-concepts-and-invariants.md` for the full description of fairness guarantees and queueing rules. @@ -65,7 +68,7 @@ The canonical scheduler has two independently bounded lanes: The phases are ordered as follows: (1) due start-of-tick passive effects, (2) one selected actor action for each still-eligible entity, and (3) effects generated by those selected actor actions. Only phase-1 effects completed before phase-2 eligibility evaluation may change same-tick eligibility; work selected but not completed, or deferred by lane, per-entity, cost, or region budget overflow, affects a later tick. Passive or inbound work that becomes due after start selection is also deferred to a later tick; phase 3 does not drain it. A completed start-of-tick effect may make an entity ineligible to act. An actor-generated effect does not retrospectively remove an action that already executed, and neither lane may recursively grant another root actor action in the same tick. -Every work source declares its phase, lane, and cost class before admission. Within one entity's eligible queue, the persisted manifest orders work by `(priority, due_tick_id, entity_enqueue_seq, source_kind, commandId_or_effectKey)`, with due points normalized before selection. Across eligible entities, persisted rotating/deficit scheduling accounts for declared cost and advances only with the durable selected batch; bounded aging or `maxDeferralTicks` applies where declared. Each lane has separate per-entity count and cost caps, region-wide work budgets, bounded carry-over/backoff, and pressure metrics. Overflow is deferred without changing its persisted ordering inputs or retry/action/effect identity; a new source cannot silently introduce a custom scheduler. See [ADR 0065](./decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md). +Every work source declares its phase, lane, and cost class before admission. Within one entity's eligible queue, the persisted manifest orders work by `(priority, due_tick_id, entity_enqueue_seq, source_kind, commandId_or_effectKey)`, with due points normalized before selection. `entity_enqueue_seq` is allocated within the complete entity scope `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch, entityId)`; it is not a region-global or instance-only sequence. Across eligible entities, persisted rotating/deficit scheduling accounts for declared cost and advances only with the durable selected batch; bounded aging or `maxDeferralTicks` applies where declared. Each lane has separate per-entity count and cost caps, region-wide work budgets, bounded carry-over/backoff, and pressure metrics. Overflow is deferred without changing its persisted ordering inputs or retry/action/effect identity; a new source cannot silently introduce a custom scheduler. See [ADR 0065](./decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md). --- @@ -87,15 +90,16 @@ The tick heartbeat is the **canonical timeline** for each ` `region_epoch` mapping rather than treating the two names as competing fields. -Consumers that persist offsets must key stable consumer identity by `(tenantId, gameInstanceId, regionId, consumerId)` and store `regionEpoch` and `latestTickId` as mutable timeline state. Durable schedule identity is the scheduler-owned `scheduleInstanceId`; it excludes mutable runtime-region metadata (`runtimeRegionId`, `runtimeRegionEpoch`), due point, and exact pin/provenance. Trigger-instance de-duplication and candidate-audit identity use the complete event-scope due-candidate/firing identity owned by [Scripting Scheduler and Timers](./system-architecture-scripting-scheduler-and-timers.md#target-state-design) and [Normative Table 1](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields), including applicable runtime region/epoch, event/schema, exact patch/pin, dry-run, trigger mode, target selector, tagged due point, catch-up `resumeWindowId`, and schedule-owned script/plugin fields. This document does not redefine that schema or mutate the schedule itself. Any observed epoch jump is a reset boundary: state derived from the old epoch is discarded or reconciled from PostgreSQL before resuming. +Consumers that persist offsets must key stable consumer identity by `(tenantId, gameInstanceId, regionId, consumerId)` and store `regionEpoch` and `latestTickId` as mutable timeline state. For durable schedules, `scheduleInstanceId` is the immutable physical row-generation identity allocated under the materializing operation; it is not the stable logical continuity identity and is not sufficient for trigger uniqueness. The scheduler-owned stable continuity identity is mode-qualified as `(isDryRun, {stableOwnerKind, stableOwnerId, scheduleDefinitionId, playableStateNamespaceId, targetScopeType, targetScopeId})`, as owned by [Scripting Scheduler and Timers](./system-architecture-scripting-scheduler-and-timers.md#target-state-design) under [ADR 0110](./decisions/adr-0110-explicit-opt-in-schedule-continuity-across-script-transitions.md); compatible transitions may retain the same row generation, while reset or incompatible replacement can allocate a fresh `scheduleInstanceId` under that continuity model. Mutable runtime-region metadata (`runtimeRegionId`, `runtimeRegionEpoch`), due point, and exact pin/provenance remain schedule state or evidence rather than continuity identity. Trigger-instance de-duplication and candidate-audit identity instead use the complete event-scope due-candidate/firing identity owned by [Scripting Scheduler and Timers](./system-architecture-scripting-scheduler-and-timers.md#target-state-design) and [Normative Table 1](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields), including applicable runtime region/epoch, event/schema, exact patch/pin, dry-run, trigger mode, target selector, exactly one tagged due point (`dueTickId` or `dueAt`), catch-up `resumeWindowId`, and schedule-owned script/plugin fields. A wall-clock source may carry a separately assigned admission `due_tick_id` for tick ordering, but it does not become or alias the source `dueAt`; tick IDs and epoch-millisecond values are never compared. This document does not redefine that schema or mutate the schedule itself. Any observed epoch jump is a reset boundary: state derived from the old epoch is discarded or reconciled from PostgreSQL before resuming. ### Tick Commit Definition (Heartbeat Watermark) FireMUD uses two explicit tick boundaries for ``: - **`durable_committed`** (authoritative commit boundary): - - The Game Session tick effect ledger has reconciled each effect for that tick under authoritative evidence: `APPLIED` only when proven applied, `ABANDONED` only when proven unapplied, and inconclusive work remains nonterminal/reconciliation-required. There are no remaining `SCHEDULED` ledger rows for that tick. - - Target-state `RegionStatus.lastCommittedTickId` has been advanced to that `(regionEpoch, tickId)` as part of the same durable visibility boundary. In the current-live deployment, the committed tick fields on `RuntimeOwnershipStatus` advance under the same opaque fence; `ObserveRuntimeTickProgress` is the progress feed and does not replace that durable authority. + - The current-epoch commit predicate: terminal (`APPLIED` or `ABANDONED`) evidence is required, where the evidence policy permits terminalization, for every eligible ledger row in that tick's complete expected current-epoch participant set. Required-versus-optional classification affects command-result aggregation, not tick commit. Inconclusive old-epoch rows remain non-terminal reconciliation work outside this current-epoch commit predicate; they may still block unsafe next-tick progression, reset-scope convergence, or reopening. There are no remaining `SCHEDULED` ledger rows for that tick's batch. + - **Target-state only:** For a non-empty batch, `tick_batch.status` is `COMMITTED` in this same fenced durable visibility boundary; a `CREATED`, `REDIS_STAGED`, or otherwise non-committed batch cannot advertise committed progress. The current-live code retains `APPLIED` as its batch terminal status and uses the committed tick fields on `RuntimeOwnershipStatus` as its commit-authority watermark under the same opaque fence; `ObserveRuntimeTickProgress` is the progress feed and does not replace that durable authority. + - Target-state `RegionStatus.lastCommittedTickId` has been advanced to the complete `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)` scope as part of that same durable visibility boundary. - **`coordination_cleared`** (in-flight clearance boundary): - Redis staging/lock state for that tick is no longer in flight (for example, `tick:{tenantRegionTag}:pending` is cleared/abandoned and lock cleanup has completed). @@ -135,17 +139,17 @@ Target-state only (currently unavailable): once implemented, the Game Session Se - Once implemented, it is classified as **reset-tolerant** in the Redis reset policy matrix: region/tenant/cluster resets may drop both the event stream and any stored offsets without violating correctness. - Consumers must treat missing or truncated history as a signal to re-establish their baseline from the active deployment's canonical status/progress adapter and domain state rather than assuming every past event is available. The current live adapter is `GetRuntimeOwnershipStatus` plus `ObserveRuntimeTickProgress`; target-state deployments use `GetRegionTickStatus` plus `StreamTickHeartbeats`. -This event stream is an observer/wakeup hint used for reconnection timer replay hints and other out-of-band reporting. “Every N ticks” scheduling correctness comes from the active deployment's committed status/progress timeline (target-state heartbeat/RegionStatus) plus durable PostgreSQL schedules; tick events may reduce latency by prompting quicker work discovery, but missing or duplicated events must not change which schedules eventually fire. +This event stream is an observer/wakeup hint used for reconnection timer replay hints and other out-of-band reporting. “Every N ticks” scheduling correctness comes from the active deployment's committed status/progress timeline (target-state heartbeat/RegionStatus) plus durable PostgreSQL schedules; tick events may reduce latency by prompting quicker work discovery, but missing or duplicated events must not silently drop correctness-bearing one-shot intent or eligible durable work. Policy-governed recurring and advisory missed occurrences may be skipped as specified by the scheduler recovery policy. -Durable automation schedules and trigger-instance de-duplication remain PostgreSQL/domain-owned. In the target state, Account owns plan-driven quota values through tenant entitlement and plan-limit authority; the current Automation implementation instead uses service configuration for its limits. Live per-script and tenant-tier quota reservations/counters are Redis-backed enforcement state (for example, `automation:tenant-budget::tier:`). Redis quota counters are reset-tolerant and a reset may temporarily relax fairness; it does not change durable schedule or work truth. The target `tick-events:{tenantRegionTag}` stream and its offsets are separate best-effort coordination hints only; once implemented, losing or resetting those hints may delay next discovery but must not change which automation jobs are eventually executed or create duplicate durable claims. The current live path has no such stream or offsets and uses `ObserveRuntimeTickProgress`. The `script-scheduler:{tenantRegionTag}:lastTickId` projection is target-only and unimplemented, with no current reset operation; once delivered, it will be a similarly reset-tolerant discovery hint rather than an authority for automation work. +Durable automation schedules and trigger-instance de-duplication remain PostgreSQL/domain-owned. In the target state, Account owns plan-driven quota values through tenant entitlement and plan-limit authority; the current Automation implementation instead uses service configuration for its limits. Live per-script and tenant-tier quota reservations/counters are Redis-backed enforcement state (for example, `automation:tenant-budget::tier:`). Redis quota counters are reset-tolerant and a reset may temporarily relax fairness; it does not change durable schedule or work truth. The target `tick-events:{tenantRegionTag}` stream and its offsets, once implemented, are separate best-effort coordination hints only; losing or resetting those hints must not silently drop correctness-bearing one-shot intent or eligible durable work or create duplicate durable claims, but may affect discovery timing and policy-governed missed recurring/advisory firings, including declared `SKIP_MISSED`, cap-excluded, or terminal capacity-denial outcomes. The `script-scheduler:{tenantRegionTag}:lastTickId` projection is target-only and unimplemented, with no current reset operation; once delivered, it will be a similarly reset-tolerant discovery hint rather than an authority for automation work. Automation & Scripting Service instances typically: - In target-state deployments, establish long-lived gRPC subscriptions to `StreamTickHeartbeats` with `tenantId`, `gameInstanceId`, and `regionId`; every message must repeat that complete scope so consumers cannot rely on an implicit stream binding to disambiguate instances. - In the current live deployment, consume `ObserveRuntimeTickProgress` with the same complete runtime scope instead of assuming `StreamTickHeartbeats` is available. - In target-state deployments, once implemented, maintain per-region scheduler state in Redis as a derived discovery hint (for example `script-scheduler:{tenantRegionTag}:lastTickId`). Its value stores `{regionEpoch, latestTickId}` and never owns or persists `streamOffset`; the canonical per-consumer event-offset record remains `tick-events-offset:{tenantRegionTag}:{consumerId}`. The target scheduler must reject the hint when its epoch differs from the authoritative current epoch, discard it on reset, and rebuild it from the current canonical status/progress observation. This Redis projection is currently unimplemented and has no current reset operation; current live Automation instances must use `ObserveRuntimeTickProgress` and durable PostgreSQL schedules without reading or writing it. If the event stream is truncated, only each affected consumer's canonical event-offset record is invalidated for resumption; a target scheduler still validates or rebuilds its separate hint from canonical progress rather than using the hint as a stream offset. The event-offset identity is `(tenantId, gameInstanceId, regionId, consumerId)`, while `regionEpoch`, `tickId`, and the stream event offset are never key dimensions. -- After a due candidate passes the applicable schedule-admission checks, claim or insert a durable PostgreSQL trigger-instance/outbox row keyed by an **instance-aware** uniqueness projection before enqueueing any `onInterval` or other tick-derived trigger so duplicate heartbeat consumers or failover cannot create duplicate logical gameplay actions. Discovery of a due candidate alone does not create a firing claim or `scriptEventId`; a terminal/permanent or declared pre-admission skip is recorded as an immutable event-scope candidate audit under a deterministic `scheduleCandidateId` derived from the complete canonical event-scope due-candidate fields, while only owner-defined transient retryable reload, reconciliation, or authority-fence failures retain the original exact-tuple due candidate as fenced, retry-eligible nonterminal state with no firing claim or `scriptEventId` until settlement. The schedule's canonical natural-key fields participate as defined by the scheduler owner; a surrogate `scheduleInstanceId` is not an identity input or substitute. - - The complete trigger-instance due-candidate/firing/candidate-audit identity and its field-presence rules are owned by [Scripting Scheduler and Timers](./system-architecture-scripting-scheduler-and-timers.md#target-state-design) and [Normative Table 1](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields): applicable runtime region/epoch, event/schema, exact patch/pin, dry-run, trigger mode, target selector, tagged due point, catch-up `resumeWindowId`, and schedule-owned script/plugin fields. `automationDispatchId` plus `commandOrdinal` remains the per-command child identity and is not a replacement for the parent Trigger Identity. +- After a due candidate passes the applicable schedule-admission checks, claim or insert a durable PostgreSQL trigger-instance/outbox row keyed by an **instance-aware** uniqueness projection before enqueueing any `onInterval` or other tick-derived trigger so duplicate heartbeat consumers or failover cannot create duplicate logical gameplay actions. Discovery of a due candidate alone does not create a firing claim or `scriptEventId`; a terminal/permanent or declared pre-admission skip is recorded as an immutable event-scope candidate audit under a deterministic `scheduleCandidateId` derived from the complete canonical event-scope due-candidate fields, while only owner-defined transient retryable reload, reconciliation, or authority-fence failures retain the original exact-tuple due candidate as fenced, retry-eligible nonterminal state with no firing claim or `scriptEventId` until settlement. The schedule's canonical natural-key fields participate as defined by the scheduler owner; a surrogate `scheduleInstanceId` is only physical row-generation metadata and is not an identity input or substitute. + - The complete trigger-instance due-candidate/firing/candidate-audit identity and its field-presence rules are owned by [Scripting Scheduler and Timers](./system-architecture-scripting-scheduler-and-timers.md#target-state-design) and [Normative Table 1](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields): applicable runtime region/epoch, event/schema, exact patch/pin, dry-run, trigger mode, target selector, exactly one tagged due point (`dueTickId` or `dueAt`), catch-up `resumeWindowId`, and schedule-owned script/plugin fields. `automationDispatchId` plus `commandOrdinal` remains the per-command child identity and is not a replacement for the parent Trigger Identity. Target-state only: Before schedule admission resumes under a new `scriptPinEpoch`, an atomic durable or resumable-idempotent reconciliation must fence pending occurrences/claims from the old `scriptPinEpoch` and make old-epoch enqueue attempts fail. Reconciliation separates scheduler candidate-audit state from linked durable tick/effect/source-claim state: when durable evidence proves the linked effect was applied, its original durable identity remains terminal `APPLIED`; when evidence proves no firing/effect was accepted or applied, the linked effect/source claim may terminalize `ABANDONED` with its owner-defined explicit reset/reconciliation reason, while an applicable scheduler candidate is recorded only with its owner-defined canceled/permanent-skip outcome and bounded reason, never `APPLIED` or `ABANDONED`. An ambiguous or unreadable claim remains nonterminal/reconciliation-required under its original identity until reconciled. The new epoch cannot enqueue the same schedule occurrence unless it is explicitly represented by a distinct durable logical occurrence/due identity; candidate-audit identity and outcome remain immutable. Detailed transition and recovery semantics remain with [Scripting Scheduler and Timers](./system-architecture-scripting-scheduler-and-timers.md), [Transaction Strategies](./system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory), and the [Inconclusive Old-Epoch Reconciliation Policy](./system-architecture-tick-failures-and-operations.md#inconclusive-old-epoch-reconciliation-policy). See [current scripting runtime status](./system-architecture-scripting-runtime-execution.md#current-implementation-status) and the [Game Session implementation status](../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#script-pin-epoch-and-rollout-history-reconciliation). @@ -314,16 +318,17 @@ Normal lease handoff/rebalancing does **not** bump `regionEpoch`: `regionEpoch` For most deployments, region topology changes (splits, merges, or reassignments between executors) are applied between game instances or during maintenance windows so active sessions are not disrupted. -World Management owns region topology (layout and `` assignments scoped by `{tenantId, gameInstanceId}`) and may, over time, support “drain and split” or “merge” flows: +World Management owns region topology (layout and `` assignments scoped by `{tenantId, gameInstanceId}`) and may, over time, support “drain and split” or “merge” flows. These flows and the protocol below are target-state tooling, not current operator capabilities: the live durable ownership boundary remains instance-scoped, and no shipped split/merge cutover or region-scoped reset/rebuild controller currently exists. -- Split flows mark a region for split, freeze scheduling and new command intake, reconcile each in-flight and durable effect under authoritative evidence, bump `regionEpoch` when the ownership mapping changes, move entities to new `` assignments, and reset/rebuild coordination state from durable state before ticks resume. They do not move live Redis queues by renaming them under new prefixes. +- Split flows establish an admission barrier covering player front ends, supported Logging & Admin operator effect admission/forwarding, automation, timers, and remote-follow-up producers before freezing scheduling and new command intake; they then reconcile each in-flight and durable effect under authoritative evidence, bump `regionEpoch` when the ownership mapping changes, move entities to new `` assignments, and reset/rebuild coordination state from durable state before ticks resume. They do not move live Redis queues by renaming them under new prefixes. - Merge flows consolidate lightly used regions into a single region to reduce overhead. -### Topology Changes (Split/Merge) Protocol (Required Invariants) +### Topology Changes (Split/Merge) Protocol (Target-State Required Invariants) -Region split/merge operations interact directly with tick idempotency, Redis key ownership, and cross-region follow-ups. To keep these operations safe and deterministic, topology changes must follow a single, explicit protocol: +Region split/merge operations interact directly with tick idempotency, Redis key ownership, and cross-region follow-ups. Once the target topology cutover and recovery tooling is implemented and proven, topology changes must follow a single, explicit protocol: -1. **Freeze and fence** +1. **Admission barrier, freeze, and fence** + - Establish an admission barrier covering player front ends, supported Logging & Admin operator effect admission/forwarding, automation, timers, and remote-follow-up producers. Effects admitted before the barrier drain or reconcile under their owning lifecycle; no post-barrier effect is admitted until the cutover reopens. - Pause tick scheduling and new command intake for the affected region(s). - Wait for any in-flight `tick:{tenantRegionTag}:pending` work to commit or be recovered effect-by-effect to an evidence-qualified terminal state; inconclusive effects remain nonterminal/reconciliation-required. 2. **Converge durable outcomes** @@ -334,7 +339,7 @@ Region split/merge operations interact directly with tick idempotency, Redis key - If the operation changes region boundaries or re-homes entities to a different region mapping, bump `regionEpoch` for all affected `` pairs as part of the topology change (the same epoch-severing mechanism used by scoped coordination resets). - Only topology operations that preserve entity-to-region ownership exactly may skip an epoch bump, and those exceptions must be explicitly documented and audited in the maintenance record. 4. **Reset or migrate coordination state using shared key builders** - - First implementation resets/rebuilds coordination state from durable PostgreSQL state after the epoch bump instead of moving live Redis keys. + - Target-state first implementation resets/rebuilds coordination state from durable PostgreSQL state after the epoch bump instead of moving live Redis keys; this is unavailable until the reset/rebuild controller and its focused proof exist. - Future in-place migration may move only reset-tolerant, purely coordination structures (queues, timers, retry metadata) using versioned tooling that uses the shared key builders and Lua Script Registry descriptors. - Queue entries, timers, and retry records that are purely coordination state are not reconstructed from old Redis keys unless dedicated migration tooling re-derives them from durable intent under the new mapping. The default fate for accepted-but-unbound queued commands is the explicit command outcome above, not silent replay on the new epoch. - Do not hand-edit `tick:*`, `timer:*`, `retry:*`, or lease/lock keys. @@ -344,11 +349,15 @@ Region split/merge operations interact directly with tick idempotency, Redis key - **Target-state fallback:** If one transaction cannot cover the records, persist a fenced durable rollover intent containing the old/new identities, desired mapping, and sealed follow-up context; recovery retries/reconciles that intent until the new identity and link are durable and effect-by-effect evidence proves the old identity unapplied before marking it `ABANDONED`. Inconclusive work remains nonterminal/reconciliation-required. - Mark the old identity `ABANDONED` with a topology-change reason only when authoritative evidence proves it unapplied, replaying it under the new mapping is invalid, and no new target identity is required; otherwise preserve `APPLIED` or nonterminal/reconciliation-required state. - **Current drift:** The current follow-up path does not yet claim the complete atomic or recoverable rollover boundary. Until it is proven, a mapping-changing operation remains paused/fenced and must not mark an old follow-up `ABANDONED` solely because the mapping changed. -6. **Resume** - - Re-enable tick scheduling and command intake once the new mapping is in place and the region(s) are healthy. +6. **Resume (target-state release)** + - Re-enable tick scheduling and command intake only after the target mapping, durable reconciliation, coordination reset/rebuild, and owner-defined health/release evidence are complete. See `system-architecture-tick-concepts-and-invariants.md` and the World Management service docs for detailed topology guidance and operational runbooks. +### Current Topology Cutover Fallback + +The current runtime has no supported split/merge operation, region-partitioned durable ownership boundary, or topology reset/rebuild/resume controller. Do not move or rename live Redis queues, hand-edit coordination keys, flush/rebuild a topology scope, or invoke the target protocol. For an actual topology or reset incident, use only the shipped instance-scoped `PauseTicksForScope` / `GetRuntimeOwnershipStatus` boundary and read-only inspection, keep the affected instance paused/fenced or stopped, and escalate through [Redis Reset & Recovery](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback). The current instance-scoped resume endpoint is an ordinary pause control, not evidence that a mapping-changing cutover or reset/rebuild completed; it must not be used to release this fallback. + --- ## Per-Command Execution Phases @@ -382,7 +391,7 @@ See `system-architecture-tick-execution-flows.md` for the detailed algorithm, in Tick execution uses a **staging/commit pattern**: - Stage: compute intended effects and write them into Redis (`tick:{tenantRegionTag}:pending`) via Lua under the region lease. -- Commit: call into domain services, which apply changes using the region-scoped tick timeline `(regionEpoch, tickId)` and effect guards to ensure idempotency across replays and resets. +- Commit: call into domain services, which apply changes under the root/participant guard contract; the region-scoped tick timeline `(regionEpoch, tickId)` supplies ordering and fencing context across replays and resets. Full commit-pattern details are in `system-architecture-tick-execution-flows.md` and the Redis docs. @@ -414,21 +423,17 @@ Isolation and replay guarantees rely on: - Per-region leases and locks in Redis. - A shared coordination timeline `(regionEpoch, tickId)` per `` as described in the Redis architecture docs. -- Domain-level idempotency rules use `(regionEpoch, tickId)` as timeline ordering/fence context and use namespace-complete effect projections plus owner-local effect guards for logical identity. +- Domain-level idempotency rules use root/participant guards and namespace-complete effect projections for logical identity; `(regionEpoch, tickId)` remains ordering and fencing context rather than a universal mutation token. -Crash recovery replays staged ticks safely by re-invoking domain handlers; replays must not double-apply logical effects. Redis loss is evaluated against the measured `redis_unreplicated_write_window_slo_ms`; `ticks_exposed` is diagnostic only. The namespace-complete storage projection tuple `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)` identifies the ledger/storage view. `playableStateScope` is separately persisted and exact-validated evidence, while `regionEpoch` and `tickId` provide ordering/timeline context rather than guard uniqueness. Participant guard logical uniqueness is exactly `(rootEffectId, typedOperation, targetAggregateType, targetAggregateId)`. If an owner-local physical partition is used, it is storage placement only and cannot alter logical uniqueness or deduplication. The immutable request digest is bound to and compared by that participant guard. The combination of the coordination timeline, tick effect ledger, and per-service idempotency guards applies the ADR 0058 class-specific outcomes: each projection converges to a single terminal outcome (`APPLIED` or `ABANDONED`) only when the evidence policy permits terminalization; an inconclusive old-epoch projection remains reconciliation-required and non-terminal under its original root `EffectId`. See [ADR 0058](./decisions/adr-0058-class-specific-redis-loss-outcomes.md) and [Tick Failure and Operations](./system-architecture-tick-failures-and-operations.md#inconclusive-old-epoch-reconciliation-policy). +Crash recovery re-invokes a domain handler for a staged effect only when durable evidence proves that the `SCHEDULED` effect was unapplied and replay is safe under its owner contract; a missing response or ambiguous guard leaves the effect `SCHEDULED` and reconciliation-required. Replays must not double-apply logical effects. Redis loss is evaluated against the measured `redis_unreplicated_write_window_slo_ms`; `ticks_exposed` is diagnostic only. The namespace-complete storage projection tuple `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)` identifies the ledger/storage view; durable projections also retain the persisted mutation `EffectId`, enclosing root lineage where applicable, typed operation, immutable request digest, and required command/source bindings where allocated. `playableStateScope` is separately persisted and exact-validated evidence, while `regionEpoch` and `tickId` provide ordering/timeline context rather than guard uniqueness. Participant-guard logical uniqueness is the owner-declared runtime-family partition plus the persisted mutation `EffectId`, typed operation, and exact target aggregate. S1/S2 uses `(tenantId, playableStateNamespaceId)` and only an explicitly owner-classified S3 family uses `(tenantId, gameInstanceId)`; the partition must be sealed and exact-validated and cannot create a second guard or fork the same logical mutation. For S1/S2, `gameInstanceId` is separately exact-validated active-runtime authorization/fence evidence; for all families, `playableStateScope`, timeline, digest, and lineage remain immutable bound projection evidence rather than additional uniqueness dimensions. Command-root allocation detail remains pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). The combination of the coordination timeline, tick effect ledger, and per-service idempotency guards applies the ADR 0058 class-specific outcomes: each projection converges to a single terminal outcome (`APPLIED` or `ABANDONED`) only when the evidence policy permits terminalization; an inconclusive old-epoch projection remains reconciliation-required and non-terminal under its original mutation `EffectId`, with enclosing root lineage retained as reconciliation context. See [ADR 0058](./decisions/adr-0058-class-specific-redis-loss-outcomes.md) and [Tick Failure and Operations](./system-architecture-tick-failures-and-operations.md#inconclusive-old-epoch-reconciliation-policy). --- ## Timers and Time Scaling -Tick timers (cooldowns, regeneration, delayed effects) are: +Every scheduler/timer source carries exactly one tagged, persisted source due point: `dueTickId` for tick-based scheduling or immutable `dueAt` for wall-clock scheduling; it carries neither both nor neither as its source due point. Tick-based queued commands, retries, remote follow-ups, and tick timers use their persisted `dueTickId` directly. A wall-clock timer remains eligible from its immutable `dueAt` (`now >= dueAt`). Only wall-clock timer admission assigns a separate tick-ordering coordinate: once eligible, one durable firing-claim/admission transaction reads the authoritative target timeline and assigns/persists exactly one target `regionEpoch` and `due_tick_id` (normally the next committable tick), together with the source claim. Tick timers reuse their persisted `dueTickId` as both source due point and ordering coordinate. Retries and replays reuse the persisted target epoch and ordering coordinate and never recompute them from cadence or wall time. An epoch change follows old-epoch reconciliation and new admission; it never rebinds the old firing. The within-entity tuple uses the persisted admission `due_tick_id` for wall-clock timers and the persisted `dueTickId` for tick timers. Wall-clock timestamps and tick IDs are different domains and must not be compared numerically or aliased. -- Stored and scheduled via Redis timer keys. -- Aligned with the tick heartbeat and tick cadence. -- Subject to time-scaling rules that speed up or slow down perceived time while preserving ordering. -- Evaluated against absolute wall-clock `due_ms` values using caller-supplied `now_ms` in Lua (never Redis `TIME`); changing `tick_interval_ms` does not rescale already-scheduled timers. -- When a timer also has durable ordering/replay metadata, `due_ms` is the wall-clock firing input while the persisted `due_tick_id` is the canonical ordering and replay key. +Timer projections are stored and scheduled via Redis timer keys and remain aligned with the tick heartbeat and tick cadence. Time-scaling rules may speed up or slow down perceived time while preserving ordering, but a later cadence or time-scale change never rewrites an existing due point. Wall-clock eligibility uses caller-supplied `now_ms` in Lua (never Redis `TIME`); tick eligibility uses the committed region timeline. Tick-region timers and retry queues are **volatile coordination structures**, not durable schedules. After coordination resets or data loss, only timers/schedules that are also represented durably elsewhere (for example PostgreSQL-backed automation schedules or other explicit domain state) are expected to be recovered or re-derived. Gameplay features that require timers to survive resets must store the underlying intent durably and treat Redis timer entries as derived coordination indexes rather than as the only record of the timer. @@ -459,19 +464,19 @@ See `system-architecture-tick-failures-and-operations.md` for the full crash-rec ## Domain Idempotency Rules (Timeline Context + Owner Guards) -Domain services use the region-scoped tick timeline `(regionEpoch, tickId)` for ordering and fencing, not as the canonical idempotency token for a logical effect: +Domain services use the region-scoped tick timeline `(regionEpoch, tickId)` for ordering and fencing, not as the canonical idempotency token for a logical effect. The default mutation boundary is the mutation's stable persisted `EffectId` plus a participant guard containing the typed operation, exact target aggregate, and immutable request digest. A child mutation retains its persisted child `EffectId` and enclosing-root lineage. A narrow last-tick watermark is permitted only for an explicitly documented aggregate proven to receive at most one logical mutation per tick timeline; it must not replace the effect/participant guard for general command effects. Command-plan ordering and root-allocation details remain pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). -- Single-aggregate updates may use an epoch-aware “last applied tick” pattern (for example storing and comparing `(last_region_epoch, last_tick_id)` for the aggregate) only when the owning contract proves that at most one logical update for that aggregate can occur in each tick. Without that one-update-per-aggregate-per-tick invariant, each logical effect requires a participant guard derived from the stable root `EffectId`, typed operation, and target aggregate; a root-only ledger or guard is insufficient. The timeline tuple is ordering/fence context and is not sufficient idempotency identity. -- Multi-aggregate operations use explicit `tick_effect_guard` storage projections that retain the namespace-complete fields (for example `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)`) and link each row to the stable root `EffectId` plus its derived typed operation/target guard identity. `playableStateScope` is separately exact-validated evidence, and `regionEpoch`/`tickId` are ordering metadata; neither replaces the namespace nor creates guard uniqueness. +- Single-aggregate updates may use an epoch-aware “last applied tick” pattern (for example storing and comparing `(last_region_epoch, last_tick_id)` for the aggregate) only when the owning contract proves that at most one logical update for that aggregate can occur in each tick. Without that one-update-per-aggregate-per-tick invariant, each logical effect requires a participant guard derived from its persisted mutation `EffectId` (the root for a root mutation or the recorded child `EffectId` for a generated mutation), typed operation, and target aggregate; an enclosing root is lineage for a child mutation, and a root-only ledger or guard is insufficient. The timeline tuple is ordering/fence context and is not sufficient idempotency identity. +- Multi-aggregate operations use explicit `tick_effect_guard` storage projections that retain the namespace-complete fields (for example `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)`) and link each row to the enclosing root lineage plus the mutation's persisted root-or-child `EffectId` and derived typed operation/target guard identity. The guard uniqueness identity follows the owner-declared runtime family: S1/S2 uses the `(tenantId, playableStateNamespaceId)` partition plus `EffectId`, typed operation, and exact target aggregate, while only an explicit S3 family uses `(tenantId, gameInstanceId)` plus those identity fields. For S1/S2, `gameInstanceId` is separately exact-validated active-runtime authorization/fence evidence; `playableStateScope`, timeline, digest, and lineage remain immutable evidence, not uniqueness dimensions. Unknown or unclassified families fail closed and are never inferred to be S3. ### Tick Effect Identity and Idempotency Contract Effect identity and idempotency rules are defined jointly by: -- The `(regionEpoch, tickId)` carried on tick-driven calls as timeline ordering/fence context, not as the standalone logical identity of an effect. -- **Target-state effect identity:** Game Session assigns a stable root `EffectId` for each logical effect from admitted identity and tick context. Participant guard identities derive from that root effect, typed operation, and target aggregate; they bind the immutable request digest. Script-generated commands include `(automationDispatchId, commandOrdinal)` in their admitted operation identity; `scriptEventId` alone cannot distinguish fan-out commands. The current live path is documented above and remains a tracked implementation gap. +- The `(regionEpoch, tickId)` carried on tick-driven calls as ordering/fencing context. +- **Target-state effect identity:** Tick work carries the persisted mutation `EffectId`, typed operation, exact target aggregate, and immutable request digest used by the participant guard. Tick scheduling and `(regionEpoch, tickId)` provide ordering and fencing context; they do not replace that mutation identity. Command-plan ordering, `planOrdinal`, and root-allocation details remain pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). Script-generated command handoff identity remains distinct from handler correlation identity under the scripting owner contract. -The root identity is the canonical `EffectId` described in `system-architecture-transactions.md`; ledger records retain it and participant guards use its deterministic operation/target projection rather than ad-hoc keys. +The root identity and generated-child identity distinction is canonical in `system-architecture-transactions.md`; ledger records retain the enclosing root lineage, while participant guards use the mutation's persisted root-or-child `EffectId` with its deterministic operation/target projection rather than ad-hoc keys. The pending [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is non-authoritative. For the complete contract, ledger schema, and endpoint semantics, see `system-architecture-tick-failures-and-operations.md` and `system-architecture-transactions.md`. diff --git a/design/architecture/system-architecture-transactions.md b/design/architecture/system-architecture-transactions.md index 91d8a17259..db374b6d8d 100644 --- a/design/architecture/system-architecture-transactions.md +++ b/design/architecture/system-architecture-transactions.md @@ -6,9 +6,9 @@ Script evaluation and pin transitions are not a new transaction substrate. The s ## Implementation Status -The structured participant-guard request, shared `IdempotentEffectExecutor`, standardized tick-effect outcome metric, and replay-verification helper described below are target-state contracts. The current replay tables and helpers remain narrower and domain-local; complete propagation and validation of the root `EffectId`, typed operation, target aggregate, immutable request digest, complete participant set, and shared helper/metric behavior are not yet fully implemented or proven. The current local instance-bound scripting handoff retains and enforces the exact `(scriptPatchVersion, scriptPinEpoch)` tuple with its owner request evidence, including same-version old-epoch rejection; these lower-level pin checks do not make the live receiving RPC available. At the authenticated Game Session receiver, `EnqueueAutomationCommandIfAbsent` currently fails closed with `FAILED_PRECONDITION` / `automation_admission_receiver_fence_unavailable` before command or queue mutation ([Game Session API implementation status](./microservices/game-session-service/api-contracts.md#implementation-status)). Automation commits each emitted child’s durable `HANDOFF_IN_FLIGHT` intent before invoking Game Session outside a local transaction, then persists a definitive response separately; ambiguous post-dispatch failures remain unresolved. The durable evaluated-descriptor and reconciliation owner needed to recover every ambiguous handoff without re-entering the DSL are not implemented, and complete source/target remote tuple binding and remote final-effect fencing remain gaps. The target contract remains authoritative: matching requests may replay safely, while an operation, target, or digest mismatch fails closed. +The structured participant-guard request, shared `IdempotentEffectExecutor`, standardized tick-effect outcome metric, and replay-verification helper described below are target-state contracts. The current replay tables and helpers remain narrower and domain-local; complete propagation and validation of the persisted mutation `EffectId`, typed operation, target aggregate, owner-resolved S1/S2-versus-explicit-S3 guard partition, applicable `playableStateNamespaceId` and separately persisted `playableStateScope` evidence, separately validated active-instance fence, immutable request digest, complete participant set, and shared helper/metric behavior are not yet fully implemented or proven. Deterministic command-plan ordering, `planOrdinal`, and command-root allocation remain proposal-only requirements in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md), not current target state or proof obligations. Unknown or unclassified guard families must be rejected before any participant-guard allocation or admission; no implicit third partition exists. The current local instance-bound scripting handoff retains and enforces the exact `(scriptPatchVersion, scriptPinEpoch)` tuple with its owner request evidence, including same-version old-epoch rejection; these lower-level pin checks do not make the live receiving RPC available. At the authenticated Game Session receiver, `EnqueueAutomationCommandIfAbsent` currently fails closed with `FAILED_PRECONDITION` / `automation_admission_receiver_fence_unavailable` before command or queue mutation ([Game Session API implementation status](./microservices/game-session-service/api-contracts.md#implementation-status)). Automation commits each emitted child’s durable `HANDOFF_IN_FLIGHT` intent before invoking Game Session outside a local transaction, then persists a definitive response separately; ambiguous post-dispatch failures remain unresolved and do not authorize DSL re-entry. The durable evaluated-descriptor and reconciliation owner needed to recover every ambiguous handoff without re-entering the DSL are not implemented, and complete source/target remote tuple binding and full command identity also remain implementation gaps rather than weakened target invariants. The accepted effect contract remains authoritative: matching mutation identity and digest may replay safely, while an operation, target, namespace, scope, active-instance evidence, or digest mismatch fails closed. -Lifecycle and authoring workflows follow the same local-transaction boundary. World Management commits its lifecycle row/epoch with database compare-and-set; Temporal coordinates retries and waits but is not a transaction or authority. Replacement cutover follows the canonical [PREPARING-to-ACTIVE proof sequence](./system-architecture-versioning-runtime.md#realm-routing-contract-for-player-addressable-realms) and [Game Session cutover boundary](./microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary): World owns the lifecycle CAS and one-shot cutover hold, while the Game Session owner-local cutover transaction validates the hold id/fence, expected pointer version, and exact source and target `ACTIVE` proofs before its pointer CAS. World finalizes the hold only after authoritative Game Session readback proves the local pointer/audit/prepared-execution/source-cleanup/drain-fence transaction; no global transaction spans the services. A multi-owner Draft commit carries the complete [ADR 0129](./decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) binding, including target `tenantId`/`versionId`, request or proposal identity, exact `baseCommitId`, canonical revision order, proposed input/digest, and the complete affected `(owner, aggregateId, scopeId, epoch)` set. It performs compare-and-set in each owner database, records durable per-owner outcomes, and publishes through a synchronized read fence; it never uses a global epoch, silent merge, or distributed transaction. These are control-plane workflows and do not add a global ACID path to ordinary gameplay. +Lifecycle and authoring workflows follow the same local-transaction boundary. World Management commits its lifecycle row/epoch with database compare-and-set; Temporal coordinates retries and waits but is not a transaction or authority. Current instance termination performs Entity cleanup outside the World database transaction and commits the World-owned row cleanup plus final `TERMINATED` state in one local transaction after that acknowledgement. This closes partial World-local cleanup on failure but does not implement the target frozen multi-owner cleanup snapshot, acknowledgement set, or complete recovery proof. Replacement cutover follows the canonical [PREPARING-to-ACTIVE proof sequence](./system-architecture-versioning-runtime.md#realm-routing-contract-for-player-addressable-realms) and [Game Session cutover boundary](./microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary): World owns the lifecycle CAS and one-shot cutover hold, while the Game Session owner-local cutover transaction validates the hold id/fence, expected pointer version, and exact source and target `ACTIVE` proofs before its pointer CAS. World finalizes the hold only after authoritative Game Session readback proves the local pointer/audit/prepared-execution/source-cleanup/drain-fence transaction; no global transaction spans the services. A multi-owner Draft commit carries the complete [ADR 0129](./decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) binding, including target `tenantId`/`versionId`, request or proposal identity, exact `baseCommitId`, canonical revision order, proposed input/digest, and the complete affected `(owner, aggregateId, scopeId, epoch)` set. It performs compare-and-set in each owner database, records durable per-owner outcomes, and publishes through a synchronized read fence; it never uses a global epoch, silent merge, or distributed transaction. These are control-plane workflows and do not add a global ACID path to ordinary gameplay. --- @@ -32,6 +32,8 @@ Lifecycle and authoring workflows follow the same local-transaction boundary. Wo Commands whose temporary partial state could violate unique ownership, value conservation/non-negative balance, conditional exchange, irreversible consumption, premium entitlement, or external commitment do not use independent tick effects. They use one co-located authoritative transaction where possible, otherwise a durable reservation/escrow workflow with idempotent steps and transactional outbox delivery. Routine distributed two-phase commit is not a gameplay pattern. +The command-plan ordering, `planOrdinal`, and root-allocation design are proposed in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) and remain pending human review. This transaction contract does not assign a command-root order, allocation owner or key, or manifest binding. Under the accepted effect contract, each staged mutation uses its persisted `EffectId`, typed operation, exact target, and immutable request digest; any participant guard must validate that binding and fail closed on conflict. A conserved multi-participant operation still follows the applicable ADR 0053 co-location or reservation/escrow boundary; a shared effect identity does not create global transaction authority. + All real-time gameplay logic — movement, combat, item use, AI — is executed inside **ticks**. Each command is: - Pulled from the command queue @@ -80,23 +82,23 @@ If a proposed gameplay feature truly requires stronger semantics than this model ### Tick Effects Are At-Least-Once: Idempotency Is Mandatory -Tick execution is replayable: retries, failover, and Redis AOF replay can cause the same logical effect to be attempted more than once. For gameplay commands this is expected and safe only because tick-invoked domain mutations are required to be idempotent with respect to the stable root `EffectId` defined by the identifier glossary. - -- **Target-state identity contract:** Game Session assigns one stable root `EffectId` for the admitted logical effect. It preserves the intended pre/post state, required participant set, and status. A participant guard's uniqueness identity has exactly these inputs: the root `EffectId`, typed operation, and target aggregate. The guard row binds the immutable request digest and stores the outcome; outcome/status, evidence, and reconciliation fields are mutable guard-row state protected by compare-and-set (CAS), not uniqueness-identity inputs. A matching identity with a changed operation, target, or request digest fails closed. Ordinary retries and replay keep the root `EffectId`; deterministic child effects are used for derived reactions. -- **Post-abandon re-drive:** A fresh root is not an ordinary retry or replay. It is permitted only after the original effect is conclusively terminal `ABANDONED` and its source claim is terminalized, and only when recovery allocates a later `(regionEpoch, tickId)` coordinate, a fresh root `EffectId` and participant projections, and a new retry/source identity with durable lineage to the original identities. Until that allocation commits, the work remains recovery work and is not returned to an ordinary queue. -- **Command/effect boundary:** An accepted command lost before durable staging terminalizes only at command scope as `executionOutcome = LOST_BEFORE_STAGING` and `gameplayResult = NOT_APPLIED`; no effect ledger row is invented. Once an effect is durably claimed or staged, physical execution is at least once and its immutable identity/digest guard permits at most one logical mutation. Staged effects terminalize as `APPLIED` or `ABANDONED` only when authoritative evidence permits; inconclusive work remains `SCHEDULED`/reconciliation-required, explicitly including timeout, retry exhaustion, or missing coordination. `REPLAY_NOOP` is an `APPLIED` reason, never a third status. Command `SUCCESS`, `PARTIAL`, `FAILED`, `TIMEOUT`, and `NOT_APPLIED` remain derived player-result vocabulary under ADR 0053. See [ADR 0069](./decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md). -- **Single propagation contract:** The coordinator sends the root `EffectId`, typed operation, target, immutable request digest, and required-participant context. Participants validate them and atomically commit their guard with effect-visible rows before acknowledging. They do not generate a fresh identity or bind a guard to mutable payload. -- **Current live implementation gap:** The live Game Session proto does not yet carry `commandOrdinal` or the full Trigger Identity for this handoff. `TickStagingService` currently derives `effectKey` from `commandId`, falling back to a hash of command text plus the staging slot when no command id is available. That current fallback is not the target-state automation fan-out identity and must not be documented as though `(automationDispatchId, commandOrdinal)` were already enforced live. -- The canonical `effectKey` serialization is versioned, deterministic, and shared by all participants: before encoding, validate every identity-bearing and typed field against its declared type and domain, then serialize only canonical representations of the stable identity, per-effect discriminator or operation identity, and other fields in a fixed order with canonical UTF-8 length-prefixed values. Numeric values use canonical base-10 decimal representations where their type permits them; a participant must not independently stringify, normalize differently, or reorder the fields. The exact serialized bytes are reused unchanged on retry. -- Owning services implement durable idempotency guards (unique constraints, monotonic updates, transactional outbox) under the derived participant guard identity. Duplicate matching attempts become prior-result/no-op outcomes; a guard conflict fails closed. Each service persists its guard outcome and any outbox/reconciliation reference, while Game Session aggregates required participant outcomes under the root `EffectId`. -- **Generated effect chains:** Generated children carry immutable parent/root identity, `depth = parent.depth + 1`, a digest-covered deterministic child ordinal, and deterministic root-chain count/cost/per-target accounting. Only a child exceeding a bound is suppressed; committed parents and earlier children remain authoritative. Required/optional authored classification derives truthful `SUCCESS`, `PARTIAL`, or `FAILED` outcomes, and suppression evidence uses bounded metric dimensions with raw identities retained for audit. See [ADR 0075](./decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md). -- For gameplay-visible mutations, derived participant-guard rows backed by the stable root `EffectId` are the default idempotency boundary. Simpler `last_tick_id` watermark patterns are allowed only for aggregates explicitly documented as receiving at most one logical mutation per tick. +Tick execution is replayable: retries, failover, and Redis AOF replay can cause the same logical effect to be attempted more than once. For gameplay commands this is expected and safe only because tick-invoked domain mutations are required to be idempotent with respect to the stable persisted mutation `EffectId`—the root `EffectId` for a root mutation or the generated child's persisted `EffectId` for a child mutation—with any enclosing `rootEffectId` retained only as lineage and reconciliation context, as defined by the identifier glossary. + +- **Target-state identity and guard contract:** Participant-guard durability follows the owning runtime-family classification: S1/S2 owner families use `(tenantId, playableStateNamespaceId)` plus the owning mutation identity (`EffectId`, typed operation, and target aggregate), while only an explicitly owner-classified S3 family uses `(tenantId, gameInstanceId)` as its durable partition. For S1/S2, the active `gameInstanceId` remains separately exact-validated authorization/fence evidence and does not create a second guard identity; unknown or unclassified families are rejected before any participant-guard allocation or admission and are never inferred to be S3. A generated child mutation uses its persisted child `EffectId` and retains the enclosing root as lineage and reconciliation context. The guard row binds the immutable request digest and stores mutable outcome/evidence state under CAS. Matching replay returns the stored result, while a tenant, namespace, owning effect, operation, target, scope, active-instance evidence, or digest mismatch fails closed. Work explicitly outside playable-state scope must use an accepted owner-specific idempotency/partition contract; it cannot omit namespace/scope and proceed under this gameplay participant-guard contract. Command-root and generated-child allocation details remain pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). +- **Post-abandon re-drive:** A fresh mutation identity is not an ordinary retry or replay. After conclusive `ABANDONED` evidence and source terminalization, any re-drive follows its source owner's admission and identity contract and remains linked to the prior effect lineage. Ordinary retries and replay preserve the original mutation identity. Command-root re-drive allocation details remain pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). +- **Command/effect boundary:** An `ACCEPTED_VOLATILE` command lost before durable staging may terminalize only at command scope as `executionOutcome = LOST_BEFORE_STAGING` and `gameplayResult = NOT_APPLIED` while its ingress status is `RECEIVED` or `ENQUEUED` and no `tickBatchId` survives, and authoritative evidence proves no committed batch, effect materialization, or application; ingress status or a missing batch ID alone is insufficient. Otherwise the command remains unresolved for evidence-qualified reconciliation. An `ACCEPTED_DURABLE` command follows its feature-specific durable replay/re-drive contract instead. No effect ledger row is invented for either command unless an effect was durably claimed or staged. A durable pre-staging source/effect claim establishes recoverability but does not itself make physical execution at least once; only a staged or otherwise dispatchable effect enters physical execution, after which its immutable identity/digest guard permits at most one logical mutation. Staged effects terminalize as `APPLIED` or `ABANDONED` only when authoritative evidence permits; inconclusive work remains `SCHEDULED`/reconciliation-required, explicitly including timeout, retry exhaustion, or missing coordination. `REPLAY_NOOP` is an `APPLIED` reason, never a third status. Command `SUCCESS`, `PARTIAL`, `FAILED`, `TIMEOUT`, and `NOT_APPLIED` remain derived player-result vocabulary under ADR 0053. See [ADR 0069](./decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md). +- **Single propagation contract:** The coordinator sends the mutation's persisted `EffectId`, typed operation, target, immutable request digest, conditional owner-family partition, separately validated active-instance authorization/fence evidence, and required-participant context; generated children also carry their enclosing root/parent lineage binding. Participants validate the complete accepted effect binding and atomically commit their guard with effect-visible rows before acknowledging. They do not generate a fresh identity or bind a guard to mutable payload. Command-root `planOrdinal` propagation remains pending in ADR 0183. +- **Current live implementation gap:** The live Game Session proto does not yet carry `commandOrdinal` or the complete applicable Command-Handoff Identity for this handoff. Plan-root manifest/allocation behavior remains proposed in ADR 0183 and is not a current implementation gap against accepted target state. `TickStagingService` derives the live `effectKey` from `commandId`; it retains a deterministic command-text-plus-slot fallback helper for selection metadata, but durable tick batching rejects any queued entry without a `commandId` before staging or effect persistence. That fallback is therefore not a live staging, replay, or recovery identity. +- **Effect-key boundary:** `effectKey` remains a source-specific descriptor, ordering, or correlation field under its owning contract; it is not a substitute for persisted mutation identity. Existing source-specific validation or serialization may remain where already defined. Command-root allocation details, including the command row key and manifest binding, remain pending in ADR 0183. +- Owning services implement durable idempotency guards (unique constraints, monotonic updates, transactional outbox) under the derived participant guard identity. Duplicate matching attempts become prior-result/no-op outcomes; a guard conflict fails closed. Each service persists its guard outcome and any outbox/reconciliation reference, while Game Session aggregates required participant outcomes under the enclosing root `EffectId`. +- **Generated effect chains:** Generated children carry immutable parent/root identity, `depth = parent.depth + 1`, a stable child ordinal allocated and persisted by the owning contract for replay-stable reuse, and deterministic root-chain count/cost/per-target accounting. When generated work is associated with command work, its enclosing-root association follows the owner contract; command-plan association remains pending in ADR 0183. Otherwise, it retains its owner/source-specific identity. Only a child exceeding a bound is suppressed; committed parents and earlier children remain authoritative. Required/optional authored classification derives truthful `SUCCESS`, `PARTIAL`, or `FAILED` outcomes, and suppression evidence uses bounded metric dimensions with raw identities retained for audit. The owning contract's child-admission transaction must durably map its complete owner scope, enclosing root identity, immutable parent identity, and deterministic child ordinal to exactly one child `EffectId` using CAS, insert-if-absent, or an equivalent atomic boundary. The mapping is persisted before enqueue/apply; exact retries/replays read and reuse the persisted child identity, lineage, and accounting, while any scope, identity, lineage, ordinal, or immutable-request-digest conflict fails closed before enqueue/apply. This source-specific mapping does not replace participant-guard uniqueness (child `EffectId`, typed operation, exact target) or the separate Automation Command-Handoff/global-fanout identity contracts. See [ADR 0075](./decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md). Exact scalar/allocation details remain non-authoritative in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). +- For gameplay-visible mutations, derived participant-guard rows backed by the mutation's stable persisted root-or-child `EffectId` are the default idempotency boundary. Simpler `last_tick_id` watermark patterns are allowed only for aggregates explicitly documented as receiving at most one logical mutation per tick. - **Target-state shared idempotency helper contract (not yet fully implemented or proven):** To keep this contract consistent across services, tick-driven handlers use a shared idempotency helper from `common-data-runtime` (for example an `IdempotentEffectExecutor`) instead of ad-hoc “check or insert” patterns. The helper: - - **Target-state request shape:** Accepts a structured `ParticipantGuardRequest` containing the root `EffectId` (`rootEffectId`), typed operation, target aggregate type, target aggregate ID, and immutable request digest (`requestDigest`), plus callbacks for “apply-if-first” and “handle-replay”. - - **Target-state full-field replay validation:** Treats an existing guard as a valid replay only when all of those request fields match the persisted guard identity and digest; a changed operation, target aggregate, or digest fails closed and must not invoke the replay callback. + - **Target-state request shape:** Accepts a structured `ParticipantGuardRequest` containing the owner-resolved runtime-family classification and conditional durable partition—S1/S2 uses `(tenantId, playableStateNamespaceId)` plus the owning identity/effect, while only an explicitly owner-classified S3 uses `(tenantId, gameInstanceId)`—and separately carries the active `gameInstanceId` authorization/fence evidence for S1/S2. The request also contains mutation guard `EffectId` (`effectId`), typed operation, target aggregate type, target aggregate ID, applicable `playableStateNamespaceId` evidence, separately persisted server-derived `playableStateScope` evidence, and immutable request digest (`requestDigest`), plus callbacks for “apply-if-first” and “handle-replay”. A generated child request also carries its enclosing `rootEffectId` and parent/child lineage binding; for S1/S2, namespace is the uniqueness partition while scope and active-instance evidence are exact-validated sealed-context fences, and lineage fields do not replace the conditional partition, `effectId`, operation, and exact target in guard uniqueness. Unknown or unclassified families, or a request with no accepted owner-specific partition, are rejected before any participant-guard allocation or admission; they are never inferred to be S3. + - **Target-state full-field replay validation:** Treats an existing guard as a valid replay only when all of those request fields match the persisted guard identity, conditional allocation partition, namespace evidence, separately persisted scope evidence, separately validated active-instance authorization/fence evidence, and digest. A changed tenant, namespace, owning effect, operation, target aggregate, scope, active-instance evidence, or digest fails closed and must not invoke the replay callback; an S3 family additionally exact-compares its durable `gameInstanceId` partition. A work item explicitly outside playable-state scope must use an accepted owner-specific idempotency/partition contract; it cannot omit namespace/scope and proceed under this gameplay participant-guard contract. No family may omit its declared partition. - **Target-state guard behavior:** Encapsulates the canonical guard pattern (insert-if-absent, treat conflicts as replay) and throws well-defined exceptions on guard violations. - **Target-state standardized metric:** Emits a simple, standardized counter such as `tick_effect_outcome_total{service, effect_type, outcome}` so operators can distinguish first-apply vs replay behavior across services without per-tenant configuration. -- **Replay verification transaction (target state):** Replay evidence is not an audit-only side effect and is not proved by a root effect or one ledger row in isolation. The verifier reconstructs the complete expected concrete participant-projection set from the sealed required-participant and manifest context. It validates every expected participant guard and corresponding durable domain evidence, rejects missing, extra, partial, or conflicting projections, and CASes all required rows transactionally within their owning durable boundaries before the fenced Game Session reconciliation transaction records the result. A stale status, fence/context, missing evidence, incomplete set, set mismatch, or concurrent winner fails closed and rolls back/rejects or retries; external logs and audit streams are projections and cannot authorize a replay transition. +- **Replay verification transaction (target state):** Replay evidence is not an audit-only side effect and is not proved by a root effect or one ledger row in isolation. The verifier reconstructs the complete expected concrete participant-projection set from the sealed required-participant and manifest context. It validates every expected participant guard and corresponding durable domain evidence against the declared S1/S2 or explicit S3 partition, namespace/owning identity, and separately validated active-instance fence, rejects missing, extra, partial, or conflicting projections, and CASes all required rows transactionally within their owning durable boundaries before the fenced Game Session reconciliation transaction records the result. A stale status, fence/context, missing evidence, incomplete set, set mismatch, or concurrent winner fails closed and rolls back/rejects or retries; external logs and audit streams are projections and cannot authorize a replay transition. > 🔗 The canonical `EffectId` contract and per-side-effect patterns are defined in [Tick Effect Identity and Idempotency Contract](./system-architecture-ticks.md#tick-effect-identity-and-idempotency-contract). @@ -119,11 +121,13 @@ To prevent cross-instance collisions and make retries safe, spatial tick effects #### DROP/PICKUP targeting and actor-fence critical section -`DROP` and `PICKUP` keep the holder mutation in Entity Management, but their World fact read and Entity commit form one Game Session-controlled critical section. Game Session acquires an actor lock keyed by the complete gameplay scope, including `regionId`, and `actorEntityId`, captures the lock's opaque Redis token separately from the current `(regionId, regionEpoch, executorFence)` durable-authority tuple, and, before World validation, durably records one in-flight spatial critical-section barrier keyed by the existing scoped root identity `(tenantId, gameInstanceId, EffectId)` and bound to `actorEntityId`, `regionId`, `RoomInstanceRef`, `regionEpoch`, `executorFence`, and the canonical immutable `requestDigest`. The barrier is coordination/evidence state, not a second effect identity. `regionId` comes from Game Session's durable region authority and is propagated unchanged through World validation and any Game Logic re-resolution under the same root `EffectId` and unchanged `requestDigest`. Game Session retains the actor-lock token/lease and durable fence through the Entity-local transaction while asking World to validate the `TargetingFactSnapshot` location/version evidence. World returns an attestation bound to that same root `EffectId`, actor, `regionId`, `RoomInstanceRef`, `regionEpoch`, `executorFence`, and exact unchanged `requestDigest`. +`DROP` and `PICKUP` keep the holder mutation in Entity Management, but their World fact read and Entity commit form one Game Session-controlled critical section. Game Session acquires an actor lock keyed by the complete gameplay scope, including `regionId`, and `actorEntityId`, captures the lock's opaque Redis token separately from the current `(regionId, regionEpoch, executorFence)` durable-authority tuple, and, before World validation, durably records one in-flight spatial critical-section barrier keyed by the existing scoped root identity `(tenantId, gameInstanceId, EffectId)` and bound to `actorEntityId`, `regionId`, the exact `playableStateNamespaceId`, the separately exact-bound `playableStateScope`, `RoomInstanceRef`, `regionEpoch`, `executorFence`, and the canonical immutable `requestDigest`. The namespace and scope are barrier evidence, not additional uniqueness dimensions; barrier uniqueness remains `(tenantId, gameInstanceId, EffectId)`. The barrier is coordination/evidence state, not a second effect identity. `regionId` comes from Game Session's durable region authority and is propagated unchanged through World validation and any Game Logic re-resolution under the same root `EffectId` and unchanged `requestDigest`. Game Session retains the actor-lock token/lease and durable fence through the Entity-local transaction while asking World to validate the `TargetingFactSnapshot` location/version evidence. World returns an attestation bound to that same root `EffectId`, actor, `regionId`, exact `playableStateNamespaceId`, exact `playableStateScope`, `RoomInstanceRef`, `regionEpoch`, `executorFence`, and exact unchanged `requestDigest`. + +Game Session renews the actor-lock lease with that same opaque Redis lock token through Entity's commit acknowledgement and passes the attestation unchanged to Entity; the durable `executorFence` is validated separately at the barrier and Entity commit gates. Entity verifies the attestation's exact binding, including `regionId`, exact `playableStateNamespaceId`, and exact `playableStateScope`, against the request, participant guard, and canonical unchanged `requestDigest` for the same root `EffectId` in its local transaction before changing the holder. A missing, mismatched, or stale attestation (including a changed region, namespace, scope, epoch, or fence) commits no Entity mutation; the Game Session orchestrator invokes Game Logic to re-resolve the targeting facts under that same root `EffectId`, preserving the unchanged `requestDigest`, namespace, scope, and `regionId`. A changed request is rejected under the participant guard rather than reusing the root. Barrier creation, renewal, replay, terminalization, and reconciliation are durable, fence-checked transitions; each preserves and exact-compares the namespace and scope evidence, and Redis lock expiry cannot clear or terminalize the barrier. A lock-renewal failure or fence change fences the old orchestrator and leaves the durable barrier `RECONCILIATION_REQUIRED`. Handoff/recovery must drain or reconcile that barrier from durable guard/holder evidence, including the exact namespace and scope; a new owner may reconcile the exact root `EffectId`, but MOVE admission cannot authorize a conflicting actor move merely because the Redis lock expired, and must wait for terminal barrier evidence. Every `MOVE` for the actor must acquire the same actor lock and pass the barrier gate, so it cannot interleave between World validation and Entity commit. After Entity commits, the acknowledgement is recorded, and the barrier and lock are released, a later valid `MOVE` is permitted. This is serialization, durable barrier evidence, and fencing across local transactions, not a distributed World/Entity transaction. -Game Session renews the actor-lock lease with that same opaque Redis lock token through Entity's commit acknowledgement and passes the attestation unchanged to Entity; the durable `executorFence` is validated separately at the barrier and Entity commit gates. Entity verifies the attestation's exact binding, including `regionId`, against the request, participant guard, and canonical unchanged `requestDigest` for the same root `EffectId` in its local transaction before changing the holder. A missing, mismatched, or stale attestation (including a changed region, epoch, or fence) commits no Entity mutation; the Game Session orchestrator invokes Game Logic to re-resolve the targeting facts under that same root `EffectId`, preserving the unchanged `requestDigest` and `regionId`. A changed request is rejected under the participant guard rather than reusing the root. Barrier creation, renewal, and terminalization are durable, fence-checked transitions; Redis lock expiry cannot clear or terminalize the barrier. A lock-renewal failure or fence change fences the old orchestrator and leaves the durable barrier `RECONCILIATION_REQUIRED`. Handoff/recovery must drain or reconcile that barrier from durable guard/holder evidence; a new owner may reconcile the exact root `EffectId`, but MOVE admission cannot authorize a conflicting actor move merely because the Redis lock expired, and must wait for terminal barrier evidence. Every `MOVE` for the actor must acquire the same actor lock and pass the barrier gate, so it cannot interleave between World validation and Entity commit. After Entity commits, the acknowledgement is recorded, and the barrier and lock are released, a later valid `MOVE` is permitted. This is serialization, durable barrier evidence, and fencing across local transactions, not a distributed World/Entity transaction. +Any handoff or recovery path that performs maintenance or reset mutation on this barrier must carry the unchanged [ADR 0085](./decisions/adr-0085-evidence-gated-coordination-replay-and-fenced-reset.md) external maintenance handoff: exact `operationId`, external maintenance fence/lock binding, classifier, immutable evidence digest, and complete affected scope. `OwnerRoutineReplayExemption` is available only for explicitly classified, non-conflicting ordinary owner-local routine replay or reconciliation outside maintenance and reset; it cannot authorize these mutations. The actor Redis lock and durable `executorFence` remain separate execution aids and never substitute for the handoff. A missing or mismatched handoff leaves the barrier `RECONCILIATION_REQUIRED` and fails closed. These controls do not alter the accepted `(tenantId, gameInstanceId, EffectId)` identity or its exact request/namespace/scope evidence. -Focused proof must exercise stale location/version evidence, root/actor/room/epoch/fence or request-digest mismatches, Entity rejection before holder mutation, actor-lock lease expiry while the barrier is in flight, an owner crash after World validation and before Entity acknowledgement, lock-renewal failure, executor-fence change fencing the old orchestrator, handoff/recovery reconciliation of the exact root, an old Entity commit racing a new MOVE, and a valid `MOVE` after terminal barrier evidence. For `PICKUP`, a previously moved item is replay only when the stored participant guard matches the same root `EffectId`, immutable request digest, and exact destination container for that actor; another holder or a different destination is a conflict/stale/reconciliation outcome, never a generic replay. +Focused proof must exercise stale location/version evidence, root/actor/room/namespace/scope/epoch/fence or request-digest mismatches, Entity rejection before holder mutation, actor-lock lease expiry while the barrier is in flight, an owner crash after World validation and before Entity acknowledgement, lock-renewal failure, executor-fence change fencing the old orchestrator, handoff/recovery reconciliation of the exact root, an old Entity commit racing a new MOVE, and a valid `MOVE` after terminal barrier evidence. For `PICKUP`, a previously moved item is replay only when the stored participant guard matches the same root `EffectId`, immutable request digest, and exact destination container for that actor; another holder or a different destination is a conflict/stale/reconciliation outcome, never a generic replay. Select validation through the shared [Validation and Runtime Proof](../developer-workflows/validation-and-runtime-proof.md) workflow. Ambient world mutations (doors, hazards, weather) are treated as spatial effects for replay and idempotency purposes: @@ -142,41 +146,59 @@ Cross-service effect convergence has a single owner of record: - **Game Session Service** owns reconciliation orchestration and backlog durability for spatial/ambient effects. - World Management and Entity Management remain owners of their domain writes and idempotency guards, but they do not own cross-service retry scheduling. +**Current implementation status:** this reconciliation backlog, its typed `EffectReconciliationAuthority`, its durable backlog/authority schema, and the list/retry/acknowledgement control-plane interfaces below are target-only and unimplemented. Current Game Session persists `tick_batch` and `tick_effect` rows, but it has no implemented `effect_reconciliation_backlog` schema or API. Existing domain participant guards and remote-follow-up reconciliation do not establish this cross-service backlog surface. This paragraph records current status only; the owner and contract below remain normative target state. + Durable backlog contract: - Game Session persists one row per logical effect in a durable backlog table (for example `effect_reconciliation_backlog`) keyed by `(tenantId, gameInstanceId, effectId)`. - Minimum persisted fields: - - `effectType` - - `targetScope` (`RoomInstanceRef` or region scope) + - `effectType` (the typed operation/effect identity, not only a display category) + - `targetAggregateId` (the exact target aggregate identity) + - `targetScope` (the complete target scope, including the applicable namespace, region/epoch, and other scope-fence evidence; `RoomInstanceRef` or region scope is not sufficient by itself) + - `requestDigest` (the immutable digest of the normalized request and operation inputs) + - `sealedManifestRef` and `sealedManifestDigest` for the immutable participant/operation manifest, or an equivalent immutable reference whose read is mandatory before action + - `ownerFence`, `executorFence`, and applicable pin/version and namespace/scope evidence, when those guards apply to the effect - `expectedParticipants` (for example `WORLD`, `ENTITY`) - `participantAckState` (per participant applied/pending/final-failure) - `firstObservedAt`, `lastAttemptAt`, `attemptCount`, `nextAttemptAt` + - `backlogRevision` (a monotonic compare-and-set revision for control-plane actions) - `status` (`PENDING`, `CONVERGED`, `DEAD_LETTER`) - `lastErrorCode` / `lastErrorMessage` +- Every immutable guard field is binding evidence written with the initial backlog row; it is not an additional backlog uniqueness or partition dimension, and retries and acknowledgements must not rewrite it. A compact reference to the sealed effect ledger is acceptable only when every retry and acknowledgement atomically resolves that reference and exact-compares the complete guard before action. A missing, unreadable, stale, or mismatched guard is an identity conflict/reconciliation-required outcome and fails closed; it is never treated as a fresh effect or a permissive wildcard. - The reconciliation ledger's `status` is a closed enum of `PENDING`, `CONVERGED`, and `DEAD_LETTER`; it remains separate from the player-visible command result and is not expanded with `PARTIAL` or other command-result values. -- Inserts and status transitions must be idempotent on `(tenantId, gameInstanceId, effectId)` so duplicate scheduling does not create duplicate backlog rows. +- Inserts and status transitions must remain idempotent on `(tenantId, gameInstanceId, effectId)` so duplicate scheduling does not create duplicate backlog rows; guard fields such as namespace, scope, operation, target, and fence are exact-compared conflict/reconciliation evidence rather than new uniqueness dimensions. Every control-plane mutation also compares `backlogRevision` and the expected status and advances the revision atomically with its result. - Backlog rows must be indexed at minimum by `(status, nextAttemptAt)` and `(tenantId, status, firstObservedAt)` for retry scans and operator triage. - For participant ack semantics, `applied` means the owning service can serve the effect through its documented durable read surface for the corresponding fence token. It does not mean `accepted for later batch flush`. +- `EffectParticipantAcknowledgement/v1` is the typed target acknowledgement exchanged by each mutation owner and Game Session. It carries the participant key and owner, a stable acknowledgement identity, the complete immutable effect guard (or mandatory `sealedManifestRef` plus `sealedManifestDigest`), exact effect request digest, target aggregate, complete target scope, applicable owner/executor/pin/version fence, owner revision, durable `applied` or `no-op` result/read reference, acknowledgement status, and evidence digest. An exact identity/guard retry replays the stored acknowledgement; changed identity, guard, target, scope, digest, fence, or owner revision fails closed. Only exact durable `applied`/`no-op` acknowledgements for every member of the sealed participant manifest may advance the backlog to `CONVERGED`; pending, final-failure, stale, missing, or ambiguous evidence cannot do so. World and Entity expose this participant contract from their owner boundaries; Game Session remains the cross-service backlog authority. Retry and dead-letter policy: - Default retry strategy is bounded exponential backoff with jitter and no mutation of `EffectId`. -- Effects remain `PENDING` until all required participants acknowledge applied/no-op for the same `EffectId`. -- Effects move to `DEAD_LETTER` only after retry exhaustion or explicit operator action; no destructive compensation is issued from this path. -- Dead-letter rows remain replayable via explicit operator/API actions; replay must preserve original `EffectId`. +- A backlog row remains `PENDING` until either all required participants acknowledge applied/no-op for the same `EffectId`, allowing reconciliation to transition it to `CONVERGED`, or retry exhaustion or explicit audited operator action transitions the backlog row to `DEAD_LETTER` without terminalizing the underlying effect. +- `DEAD_LETTER` is a backlog retry-control status, not an effect-ledger outcome; no destructive compensation is issued from this path. The underlying effect ledger remains governed by the `APPLIED`/evidence-qualified `ABANDONED` contract and remains nonterminal when execution is inconclusive. +- Dead-letter backlog rows remain replayable via explicit operator/API actions; an authorized replay transitions the backlog row back to `PENDING` under the existing audit/recovery contract and preserves the original `EffectId`. Acknowledgement is separate attention/audit evidence: it leaves retry-control status `DEAD_LETTER`, never terminalizes or compensates the underlying effect, and records immutable acknowledgement time, actor, reason, action identity, and result. A later authorized retry CASes `DEAD_LETTER` to `PENDING` while preserving that acknowledgement history. Retention and lifecycle policy: -- `CONVERGED` rows are retained for 24 hours, then deleted by background GC. -- `DEAD_LETTER` rows are retained for 30 days minimum (or longer by policy) for incident analysis. -- GC jobs must be idempotent and rate-limited per tenant to avoid write spikes. +- The owning Game Session family must declare its ADR 0163 retention class, terminal/reference/blocker predicate, minimum configured horizon, safe watermark, hold behavior, and bounded GC cadence/batch. Cleanup is eligible only after that predicate and watermark prove that no producer retry, replay, restore, or downstream compatibility path can reference or resurrect the logical effect; nonterminal, inconclusive, and held rows remain blockers. +- Exact retention values are configuration-backed operational policy owned by the [Scaling Runbook](./system-architecture-scaling-runbook.md#data-retention-and-high-churn-tables), not universal durations in this transaction contract. GC remains owner-local, idempotent, and rate-limited per tenant to avoid write spikes. Required control-plane interfaces: - `ListEffectReconciliationBacklog(tenantId, status, olderThan, page)` for diagnostics. -- `RetryEffectReconciliation(tenantId, gameInstanceId, effectId)` for explicit replay from `DEAD_LETTER` or stuck `PENDING`. -- `AcknowledgeEffectDeadLetter(tenantId, gameInstanceId, effectId, reason)` for audited operator decisions. +- `RetryEffectReconciliation(tenantId, gameInstanceId, effectId, actionRequestId, actionDigest, expectedBacklogRevision, expectedStatus, authority: EffectReconciliationAuthority)` for explicit replay from `DEAD_LETTER` or stuck `PENDING`. +- `AcknowledgeEffectDeadLetter(tenantId, gameInstanceId, effectId, reason, actionRequestId, actionDigest, expectedBacklogRevision, expectedStatus, authority: EffectReconciliationAuthority)` for audited operator decisions. It records the immutable acknowledgement evidence while leaving the row in `DEAD_LETTER` and the underlying effect outcome unchanged. - Logging & Admin dashboards should consume these APIs; operators should not mutate backlog tables directly. +- `actionRequestId` is stable for one requested control-plane action. The unique, digest-bound action-intent row is keyed by the exact stable action-family request identity `(tenantId, gameInstanceId, effectId, actionRequestId)`; `actionType` is an immutable tuple member, not a deduplication partition, and the existing identity must be loaded and compared before selecting the retry or acknowledgement branch. For an owner-local backlog mutation, the intent row, backlog status/revision CAS, and final action result/outcome commit atomically in one owner-local transaction. For an external/authority or cross-service consequence, the owner must durably persist the intent with status `IN_PROGRESS` before the call. No action may execute without its intent. Reuse of the same request identity with a different action type or any other complete-tuple/digest difference fails closed as an identity conflict; it must not create a second intent row. `actionDigest` remains the API field name where useful and is the `mutationDigest/v1` value for the `effect-reconciliation-action/v1` action-family schema pair; it is not a competing `actionDigest/v1` digest owner. This family uses ADR 0047's exact seven top-level fields only: `scope` is the exact affected tenant/game/runtime scope; `target` is the effect identity plus exact target aggregate; `expectedVersion` is the expected backlog status and revision; `mutation` is the closed retry-or-ack action and its typed action inputs; and `auditReason` is the typed reason with explicit presence/value. `actionRequestId`, the opaque Account authorization reference, `EffectReconciliationAuthority` branch/reference/evidence, handoff/member evidence, actor/workload evidence, and reservation/fence fields remain excluded from the digest exactly as ADR 0047 requires and are separately exact-compared in the complete post-authorization/execution tuple. Absent and explicit `null` are distinct canonical values. The action-family mapping requires shared cross-language golden vectors, including absent/null cases, and explicit schema-version migration rules before any version change. +- Every `IN_PROGRESS` intent also records the current recovery owner/claim identity, a monotonic attempt fence, lease/deadline evidence, and the durable action identity used downstream. A successor may take over only through an owner-local CAS after lease expiry; stale owners and stale attempt fences are rejected before any backlog mutation or external call. The downstream owner or external operation must receive the stable action identity plus the current attempt fence, or an equivalent durable idempotency binding. Each intent has at most one terminal action result; a response is only a readback of that durable result. For an external/authority or cross-service consequence, the durable action remains `IN_PROGRESS` until readback reconciliation against the exact effect guard, handoff and sealed member-manifest evidence, current backlog status/revision, and current attempt fence determines whether the consequence is applied, already applied, or still inconclusive. An ambiguous action must not be blindly reissued or assigned a new identity; the same `actionRequestId`/digest resumes reconciliation, while a changed digest fails closed as an identity conflict. Concurrent retry and acknowledgement actions serialize through the backlog CAS, rather than last-writer-wins behavior. +- The durable action ledger/result stores the digest, actor/time, expected state, CAS result, recovery claim/attempt fence, and returned outcome. Owner-local proof covers crash before the intent or before the atomic transaction commits, plus response loss after the committed result (which replays that result). Separately, external or cross-service proof covers a successful downstream CAS/consequence before local result persistence or a lost external response; recovery must reconcile the still-`IN_PROGRESS` intent from exact evidence. Lease expiry, takeover, stale-owner rejection, and all ambiguous cases must preserve the same action identity and either replay the committed result, reconcile the consequence, or remain safely inconclusive without a second action identity. + +`EffectReconciliationAuthority` is a typed union/reference carried by both mutating requests: + +- `ExternalMaintenanceHandoff` is the unchanged ADR-0085 handoff: exact `operationId`, external maintenance fence/lock binding, classifier, immutable evidence digest, and complete affected scope. The handoff also contains either a sealed exact-effect manifest or an immutable selection predicate plus a frozen owner-resolved member manifest and digest. For each action, the owner atomically resolves the handoff and compares its operation/fence/classifier/evidence digest/affected scope and member membership with the selected effect's immutable guard and current backlog revision/status. A handoff authorizes only its bounded sealed member set; it is not globally single-use, and each member action is independently idempotent through `actionRequestId`/`actionDigest`. Scope widening, stale revision or fence, absent membership, or any mismatch fails closed. The handoff evidence digest does not replace the effect's request digest. +- `OwnerRoutineReplayExemption` is an owner-issued, durably recorded non-conflicting exemption. It carries the stable owner-recorded `exemptionId` (and the existing owner authorization/audit record link where applicable), the exact effect identity, exact target, complete affected scope, classification, and immutable evidence digest. The owner persists this record before the request and atomically reads it back and exact-compares those fields with `(tenantId, gameInstanceId, effectId)`, the target, and the requested scope before allowing replay or reconciliation. A caller cannot self-label a request as routine or supply an unverified exemption. + +For spatial or ambient maintenance or reset mutations invoked through either API, the unchanged ADR 0085 `ExternalMaintenanceHandoff` is always required and must resolve and match before mutation, including in recovery paths that perform maintenance or reset mutations; `OwnerRoutineReplayExemption` cannot authorize maintenance or reset. The handoff must also pass the common atomic effect-guard and backlog revision/status comparison; an authority valid for another effect, target, scope, or revision cannot authorize this action. Ordinary owner-local routine replay or reconciliation outside maintenance and reset may preserve the original `EffectId` only when the owner has explicitly classified it as non-conflicting and the recorded exemption matches. Missing, ambiguous, or contradictory handoff or exemption evidence fails closed. Existing operator authorization issuance and redemption policy remains owned by its canonical Account/Logging & Admin contract; this carrier links to that owner evidence rather than redefining it here. Operational SLOs and alerts: @@ -311,15 +333,16 @@ FireMUD uses a **shared short synchronous saga orchestration library**, not a se - Supports compensation. - Explicitly classified adopters apply the bundled migrations as part of their own startup; non-adopter startup must not create Saga tables. - `SagaRunner` emits a `sagas.active` metric and attaches a `correlationId` to logs for each orchestration using MDC. - - The current Saga Dashboard (`/sagas` and `/sagas/{id}/steps`) provided by the [Logging & Admin Service](./microservices/logging-admin-service/README.md) reads only Logging & Admin's own local Saga rows. It does not aggregate adopter-local Saga state; target cross-owner visibility requires owner read APIs plus a bounded aggregation/read model, and must distinguish an unknown/unavailable adopter from an empty result. + - The current Saga Dashboard (`/sagas` and `/sagas/{id}/steps`) provided by the [Logging & Admin Service](./microservices/logging-admin-service/README.md) reads only Logging & Admin's own local Saga rows. It does not aggregate adopter-local Saga state; target cross-owner visibility requires read-only owner status APIs plus a bounded aggregation/read model or fan-out, must distinguish an unknown/unavailable adopter from an empty result, and must not read foreign databases or acquire execution authority. This library is intentionally not FireMUD's durable workflow engine. World lifecycle, publish, and script-patch readiness now use Temporal because they need restart-safe continuation, stable workflow identity, and operator-visible runtime state independent of one service process. - **Execution Model**: - Steps are gRPC calls to owning services - Helper `GrpcSagaSteps.callWithRetry` wraps gRPC calls with basic retry logic - - All steps are **idempotent** - - Every retryable workflow has one durable workflow/request identity derived from stable business identity and workflow scope. Every logical step has a durable guard identity `(workflow/request identity, stable step name, deterministic occurrence key, execution role)` bound to an immutable request digest. Same identity plus same digest deduplicates/replays its recorded outcome; same identity plus a different digest fails closed. Run, process, retry-attempt, and message/delivery IDs are trace metadata only, never authoritative deduplication keys. See [ADR 0078](./decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md). + - The retry helper does not make every step **idempotent**; idempotency remains an owner-local implementation and proof obligation. + - **Target-state workflow and step guards:** Every retryable workflow has one durable workflow/request identity derived from stable business identity and workflow scope. Every logical step has a durable guard identity `(workflow/request identity, stable step name, deterministic occurrence key, execution role)` bound to an immutable request digest. Same identity plus same digest deduplicates/replays its recorded outcome; same identity plus a different digest fails closed. Run, process, retry-attempt, and message/delivery IDs are trace metadata only, never authoritative deduplication keys. See [ADR 0078](./decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md) and its [current Automation adopter mapping](./decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md#current-automation-adopter-mapping). + - **Current implementation status:** Durable guard storage, conflict enforcement, adopter migration, and focused retry/replay proof remain incomplete; the current `common-saga` persistence and Temporal helper do not establish this target contract universally. See [ADR 0078 implementation status](./decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md#implementation-status). - Each step runs inside a local `@Transactional` method for atomicity - Compensation logic is registered via hooks - Retried automatically or flagged for manual review @@ -397,9 +420,7 @@ This is a target-state branch illustration, not current implementation or proof. This design centralizes logic, improves visibility, and avoids coupling orchestration directly into gameplay services. The `common-saga` module provides a `SagaBuilder` class implementing this pattern. See [Shared Libraries Overview](./system-architecture-shared-libraries.md) for additional details. -A concrete adopter must satisfy [Mandatory Workflow Adopter Classification](#mandatory-workflow-adopter-classification) in its canonical owning-service architecture document or an accepted ADR before it exposes the library's accompanying Flyway migrations at `classpath:db/migration/saga`; module or convention inclusion alone does not establish Saga adoption. See [ADR 0080](./decisions/adr-0080-service-owned-schemas-with-adopter-local-shared-migrations.md). -Example saga flows are documented in [World Creation Workflow](./microservices/world-management-service/world-creation-workflow.md) -and in the Logging & Admin Service README. +A concrete adopter must satisfy [Mandatory Workflow Adopter Classification](#mandatory-workflow-adopter-classification) in its canonical owning-service architecture document or an accepted ADR before it exposes the library's accompanying Flyway migrations at `classpath:db/migration/saga`; module or convention inclusion alone does not establish Saga adoption. See [ADR 0080](./decisions/adr-0080-service-owned-schemas-with-adopter-local-shared-migrations.md). The migrations persist `saga_instance` and `saga_step` in each adopter's own schema. Short-saga examples and consequences are documented in the [Game Session Service runtime and data](./microservices/game-session-service/runtime-and-data.md) and the Logging & Admin Service README; the [World Creation Workflow](./microservices/world-management-service/world-creation-workflow.md) is the Temporal `world-lifecycle` adopter, not a Saga. ### Saga vs Temporal Boundary diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index fe66a4bd22..c781f02d55 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -169,3 +169,33 @@ Entry format: - Observation: the runtime audit flattened the active CLI observation into a generic unresolved-finding string before the controller's existing exact-identity overlap check could run. A controller regression with a mocked empty audit did not exercise that adapter interaction. - Expected pattern: preserve structured run/lock-owner/head/parent/patch evidence through the audit and test the real adapter-to-allocation path. Permit only positively verified same-candidate overlap; genuine pending findings and incomplete identities remain held. - Outcome: the bounded controller/runtime correction passes real-adapter overlap and refusal regressions; live request verification follows publication. The running CLI was not interrupted, and no duplicate Hosted request or private-state bypass was used. + +- `2026-10-01`: An ownership clarification is not a lane-wide stop + - Context: the human transferred the #2916 controller child to Overseer for review/fix cycles while Gameplay still owned #2839. Gameplay ended its turn after acknowledging the transfer, requiring an explicit resume. + - Observation: the child-only ownership boundary was incorrectly treated as a stopping point for the continuing parent assignment. + - Expected pattern: stop touching the transferred child, but continue the owned parent and independent review lanes. A coordination acknowledgement or status answer must not terminate the standing train without an explicit pause or actual blocker. + - Outcome: Gameplay resumed #2839, preserved the child untouched, adjudicated its complete saved CLI result, and dispatched the accepted parent-only corrections. + +- `2026-10-01`: Distinguish request admission contention from an active provider review + - Context: several closely launched #2839 Hosted/CLI commands produced a delayed Hosted refusal saying another Hosted request was active, without a new posted trigger; a guarded later request posted normally. + - Observation: the exact contention phase and cause remain unproven. That refusal alone does not establish that CodeRabbit is reviewing, and preparation delay consumes eligible Hosted windows independently of provider duration. + - Expected pattern: retain the canonical request handle and verify its actual posted or refused outcome. Investigate the narrow admission/lock boundary without bypassing duplicate-request or exact-identity safeguards; keep the other safe lane moving. + - Reconsideration trigger: investigate when the controller owner can reproduce the contention or another eligible Hosted window is lost; do not silently label an unposted request as an active review. + +- `2026-10-01`: Do not infer CLI exclusion from unpublished fixes + - Context: #2839's local corrections were committed at 06:20:21 UTC and Hosted finished at 06:25:38 UTC; Gameplay made no CLI attempt during that 5m 17s interval, incorrectly assuming the unpublished corrections prevented overlap. + - Observation: the live runner permits CLI on the exact published Hosted candidate, excluding local descendant changes. An unattempted safety assumption is not a demonstrated controller hold. + - Outcome: subsequent CLI requests ran independently. A later Hosted retry encountered a closed-#2750 reservation verification error before POST; its current record and attributable terminal review were valid on one read-only reproduction, and a canonical retry posted successfully. The original exception remains unknown because the wrapper hides its phase/cause; no record was edited or safety check bypassed. + - Expected pattern: use the canonical eligible channel, retain actual refusal evidence, and keep the other lane moving. Preserve safe phase/cause diagnostics for future reservation-verification failures rather than treating an unposted request as provider activity. + +- `2026-10-01`: Closed-PR history must not retain a Hosted execution slot + - Context: the repository-wide Hosted admission sweep reread the complete review history of merged #2750; an exception became an admission hold even though the live open-PR inventory had already excluded it. + - Outcome: the repair is published in #2916 and installed as a separately tested writer-build-5 backport. Confirmed closed PRs no longer require that historical network read. An exact, attributable, locally archived rate-limit response still holds the repository until its proven reset time, including a response whose terminal edit occurred after creation. No historical record, count, or taper decision was removed. + - Proof: 118 focused runtime tests, 883 tests against the compatible live-controller baseline, and 920 tests on the owning child passed. The original transient exception's underlying network cause remains unknown; the reproduced failure mode is now covered without weakening open-PR request safety or promoting an unmerged record schema. + - Observation: the Hosted admission inventory must distinguish active candidates from historical closed PRs before any history-dependent slot decision. + - Expected pattern: exclude confirmed closed PRs before reserving a Hosted execution slot; retain only exact, attributable rate-limit evidence as a repository-wide hold through its verified reset time. + +- `2026-10-01`: Keep validation-script inputs stable during execution + - Context: an architecture-contract run passed its test cases but then read a truncated final command after the same shell script was edited while its process was still running. A complete rerun against the finished script passed. + - Observation: a shell process may continue reading its script after earlier commands finish; editing that script during execution can invalidate the run independently of the corrected contract. + - Expected pattern: finish script edits before starting its validation, or discard the affected run as proof and rerun the complete named check after edits settle. Do not diagnose the resulting partial command as a missing repository tool without checking the input race. diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index b383ed5ba4..904bc1f8c6 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -4,7 +4,7 @@ This workstream establishes a complete, reviewable chain from FireMUD product ca ## Status -Completed phases: capability allocation, implementation/proof reconciliation, cross-domain convergence, structural enforcement, independent validation of prior parcel states, human-led adversarial review of all `183` historical queue/navigation rows in the remotely backed review archive, selective import of all `182` historical decision keys, and integration of four direct post-archive human decisions with family-local contract consolidation. Packets 3-4 apply ADRs 0051-0130 plus the no-ADR TICK-05 outcome. Packet 5 applies all `21` reviewed outcomes through ADRs 0131-0150, including the superseded `SOCIAL-01` provenance. Packet 6 and Packet 7 complete the historical imports through ADRs 0151-0178. Direct decisions `COMMERCE-02`, `HOSTED-TERMS-01`, `HOSTED-TERMS-02`, and `OPS-07` apply through ADRs 0179-0182 without changing Packet 1-7 totals. The separately tracked service-scan `MS-AA-TOKEN-REVOCATION` row remains the only excluded navigation alias. The canonical registry contains `180` ADR records; `172` carry completed review metadata and `11` are pre-formal, with overlap where accepted legacy pre-formal records now carry exact provenance. Source-archive identifiers remain archive-local evidence and may collide numerically with canonical ADRs, so each integration preserves canonical repository numbering rather than importing source numbers. +Completed phases: capability allocation, implementation/proof reconciliation, cross-domain convergence, structural enforcement, independent validation of prior parcel states, human-led adversarial review of all `183` historical queue/navigation rows in the remotely backed review archive, selective import of all `182` historical decision keys, and integration of five direct post-archive human decisions with family-local contract consolidation. Packets 3-4 apply ADRs 0051-0130 plus the no-ADR TICK-05 outcome. Packet 5 applies all `21` reviewed outcomes through ADRs 0131-0150, including the superseded `SOCIAL-01` provenance. Packet 6 and Packet 7 complete the historical imports through ADRs 0151-0178. Direct decisions `COMMERCE-02`, `HOSTED-TERMS-01`, `HOSTED-TERMS-02`, and `OPS-07` apply through ADRs 0179-0182, and `EDGE-WITHDRAWAL-01` applies through ADR 0184, without changing Packet 1-7 totals. The separately tracked service-scan `MS-AA-TOKEN-REVOCATION` row remains the only excluded navigation alias. The canonical registry contains `182` ADR records; `173` carry completed review metadata and `11` are pre-formal, with overlap where accepted legacy pre-formal records now carry exact provenance. ADR 0183 is a separately preserved pending proposal and is not counted as a reviewed or applied decision. Source-archive identifiers remain archive-local evidence and may collide numerically with canonical ADRs, so each integration preserves canonical repository numbering rather than importing source numbers. | Phase | Status | Output | | --- | --- | --- | @@ -15,8 +15,8 @@ Completed phases: capability allocation, implementation/proof reconciliation, cr | Code and proof reconciliation | Complete and independently validated | Per-capability implementation/verification states and evidence anchors in the domain trackers | | Cross-domain convergence | Complete and independently validated as a point-in-time baseline | [Frozen capability implementation reconciliation](./capability-implementation-reconciliation.md) | | Human-led adversarial decision review | Complete in the `design/adversarial-decision-review` source archive | Human-owned dispositions for all `183` queue/navigation rows | -| Accepted-decision application | Complete | All `182` historical decision keys plus the four direct post-archive decisions have checked applied provenance; the excluded `MS-AA-TOKEN-REVOCATION` navigation alias is not a distinct decision | -| Contract-authority consolidation | Baseline pass complete for ADRs 0001-0050 and major adjacent non-ADR families; Packets 3-7 are selectively applied through ADR 0178 and the direct post-archive decisions are integrated through ADR 0182; perform the planned whole-corpus authority review before declaring post-ADR design alignment complete | [Architecture contract authority map](../../architecture/README.md#contract-authority-map) and owner-link-plus-local-consequence conversions | +| Accepted-decision application | Complete | All `182` historical decision keys plus five direct post-archive decisions have checked applied provenance; the excluded `MS-AA-TOKEN-REVOCATION` navigation alias is not a distinct decision | +| Contract-authority consolidation | Baseline pass complete for ADRs 0001-0050 and major adjacent non-ADR families; Packets 3-7 are selectively applied through ADR 0178 and the direct post-archive decisions are integrated through ADRs 0179-0182 and 0184; perform the planned whole-corpus authority review before declaring post-ADR design alignment complete | [Architecture contract authority map](../../architecture/README.md#contract-authority-map) and owner-link-plus-local-consequence conversions | ### Corpus section programme status @@ -24,7 +24,7 @@ This is the sole live corpus section-status index for a fresh whole-corpus revie The preserved 5B implementation work has been rebuilt into #2826 Schema, the dependent #2827 Automation lifecycle/fence successor, #2828 Publication, and #2829 Retention. The superseded #2808, #2678, #2804, and #2679 PRs were closed only after hunk-level no-loss verification; their branches and private ledgers remain historical evidence rather than live section ownership. The replacement stack is based on the independently reviewed non-5B prerequisites #2824 and #2818. Overall 5B is complete only after all three semantic subunits taper and a cross-subunit synthesis is recorded; there is no separate overall 5B status row. -5B synthesis: Active at the three-cycle report boundary; paired whole-5B closure Cycle 1 was dry, Cycle 2 was productive, and corrected-state Cycle 3 was dry. Cycle 2's two independent reviewers produced three accepted obligation families after deduplication. The corrected stack now enforces coordinated `Recreate`, roll-forward-only deployment for the incompatible Automation V3 and Game Design V26 migration boundaries; quarantines only V13-marked unattested legacy full versions while preserving bundled and script-only rows; and explicitly classifies the two Automation plugin-history retention families without inventing a cleanup TTL. Cycle 3's two independent reviewers returned 18 and 19 raw observations with zero new accepted obligations, but this is only the first dry cycle after the Cycle 2 corrections. The required two consecutive corrected-state dry cycles have therefore not established whole-5B closure taper. +5B synthesis: Corpus discovery was accepted closed by Overseer at cumulative #2829 head `dce1d8246e3ff2bf9c3bfcb9649ae0e5c4181e6b`; no fourth closure cycle is required. Paired whole-5B closure Cycle 1 was dry, Cycle 2 produced three accepted obligation families after deduplication, and corrected-state Cycle 3 was dry (18 and 19 raw observations, zero new accepted obligations). The accepted corrections enforce coordinated `Recreate` and roll-forward-only deployment for incompatible Automation V3 and Game Design V26 migrations, quarantine only V13-marked unattested legacy full versions while preserving bundled and script-only rows, and classify the two Automation plugin-history retention families without inventing a cleanup TTL. This is a corpus-discovery judgment, not current-head review taper, capability completion, live proof, or merge readiness; current #2828/#2829 changes retain their own review and proof gates. | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | @@ -41,11 +41,11 @@ The preserved 5B implementation work has been rebuilt into #2826 Schema, the dep | 4A | Script ingress, sandbox, and runtime execution | Queued | — | — | | 4B | Scheduling, quotas, reload, and operational fairness | Queued | — | — | | 5A | API, message, identifier, tenant, time, and authorization primitives | Complete (corpus review; implementation gaps remain) | [#2813](https://github.com/benhook1013/FireMUD/pull/2813) | Three fresh whole-section passes each covered 17/17 substantive allocated sources: 8, 15, and 12 raw observations. The corrected-state third pass confirmed 12 useful already-owned handoffs, no new unowned root, and taper. The shared-library Redis status claim and conflicting operator incident/revocation guidance were corrected. gRPC outcomes, Account runtime-read exposure, numeric IDs, gameplay attestation, JWT/workload identity, Gateway connect-carrier and route inventory, and script-fence gaps remain with their service/shared-runtime owners; Redis role clients and descriptor foundation belong to 5C, and operator binding enforcement/readback plus terminal-reissuance design belong to 6D. This status does not claim those capabilities are implemented. | -| 5B-Schema | SQL/Flyway/jOOQ, schema and identifier migration | Merged | [#2826](https://github.com/benhook1013/FireMUD/pull/2826) | Six fresh whole-unit cycles reached two corrected-state dry cycles after the accepted Schema fixes. Retained-row adjudication, mixed-binary deployment evidence, and Docker-backed PostgreSQL proof remain explicit limits. Dependent #2827 carries the separately reviewed Automation lifecycle/fence successor and is not additional Schema scope. | -| 5B-Publication | Durable version/publication/readiness state | Corrected-head review pending; merge proof pending | [#2828](https://github.com/benhook1013/FireMUD/pull/2828) | Cycles 1–6 are historical review evidence only and do not establish taper on the current corrected head; a fresh whole-unit review must determine whether the current state has tapered. End-to-end full-version publication remains blocked, including the Game Logic owner digest failing closed without owner-local manifest/provenance. Live mounted-certificate/Temporal owner calls, mixed PostgreSQL upgrade/concurrency proof, version-scoped Automation content, exact Game Design template/asset mapping, readiness notification, and dedicated ability-schema attestation also remain open. | -| 5B-Retention | Retention classes, cleanup, horizons, contraction | Open, non-draft; ready for review | [#2829](https://github.com/benhook1013/FireMUD/pull/2829) | V4 execution/replay/retention work is preserved behind Publication through [#2879](https://github.com/benhook1013/FireMUD/pull/2879) and [#2882](https://github.com/benhook1013/FireMUD/pull/2882); no substantive fresh Retention review has begun on the linearized candidate. Historical review classified `plugin_runtime_request_history` as retry/idempotency receipt evidence and `plugin_runtime_events` as recovery/reconciliation plus lifecycle-audit evidence. Both remain ineligible for automatic deletion until measured horizons, holds, safe watermarks, bounded sweeps, and metrics exist. Recovery-aware dead-letter cleanup, cross-owner inequalities, and Docker-backed PostgreSQL proof remain open. | -| 5C | Redis roles and cache/rate-limit semantics | Queued | — | — | -| 5D | Idempotency, outbox, replay, saga, and workflow patterns | Queued | — | — | +| 5B-Schema | SQL/Flyway/jOOQ, schema and identifier migration | Merged; residual live proof pending | [#2826](https://github.com/benhook1013/FireMUD/pull/2826) | Six fresh whole-unit cycles reached two corrected-state dry cycles after accepted Schema fixes. Retained-row adjudication, mixed-binary deployment evidence, and Docker-backed PostgreSQL proof remain explicit limits. Dependent #2827 carries the separately reviewed Automation lifecycle/fence successor. | +| 5B-Publication | Durable version/publication/readiness state | Corrected-head review and merge proof pending | [#2828](https://github.com/benhook1013/FireMUD/pull/2828) | Historical Cycles 1–6 and the accepted whole-5B synthesis remain recorded, but do not establish taper on the moving corrected head. V27/V28 legacy-version quarantine and V26 stop-before-start/roll-forward-only scope migration remain required. End-to-end full-version publication, live mounted-certificate/Temporal calls, mixed PostgreSQL proof, version-scoped Automation content, Game Design mapping, readiness notification, and ability-schema attestation remain open. | +| 5B-Retention | Retention classes, cleanup, horizons, contraction | Open, non-draft; corrected-head review and merge proof pending | [#2829](https://github.com/benhook1013/FireMUD/pull/2829) | V4 execution/replay/retention work is preserved behind Publication through [#2879](https://github.com/benhook1013/FireMUD/pull/2879) and [#2882](https://github.com/benhook1013/FireMUD/pull/2882). Historical review classified `plugin_runtime_request_history` as retry/idempotency receipts and `plugin_runtime_events` as recovery/reconciliation plus lifecycle audit. Neither is eligible for automatic deletion before measured horizons, holds, safe watermarks, bounded sweeps, and metrics. Recovery-aware dead-letter cleanup, cross-owner inequalities, and Docker-backed PostgreSQL proof remain open. | +| 5C | Redis roles and cache/rate-limit semantics | Corpus review tapered; implementation/proof gaps remain | [#2839](https://github.com/benhook1013/FireMUD/pull/2839) | The combined 5C/5D successor preserves the #2661 Redis role, authority, reset, recovery, keyspace, and operational content behind #2829. Fifteen corrected-state whole-unit cycles ended with two dry cycles; parent reconciliation and exact-head validation are separate gates. | +| 5D | Idempotency, outbox, replay, saga, and workflow patterns | Corpus review tapered; implementation/proof gaps remain | [#2839](https://github.com/benhook1013/FireMUD/pull/2839) | The same successor preserves #2661 replay, effect identity, scheduler, tick, saga, workflow, and recovery content. Pending ADR 0183 remains a proposal without accepted authority. Parent reconciliation and exact-head validation are separate gates. | | 6A | Gateway routes, traffic planes, sharding, and close taxonomy | Queued | — | — | | 6B | WebSocket, Telnet, protocol bridge, and session transport | Queued | — | — | | 6C | Logging & Admin/operator ingress and action authorization | Queued | — | — | @@ -67,7 +67,7 @@ flowchart LR DESIGN_ALLOC --> SOURCE_INV[Source decision inventories]:::alignment SOURCE_INV --> HUMAN_QUEUE[Completed human-review queue]:::alignment HUMAN_QUEUE --> APPLY[Point-in-time application status]:::alignment - APPLY -->|target state after this parcel merges| APPLIED_DECISIONS[186 applied decision keys: 182 historical keys through ADR 0178 plus four direct decisions through ADR 0182, with owning design changes]:::status + APPLY -->|target state after this parcel merges| APPLIED_DECISIONS[187 applied decision keys: 182 historical keys through ADR 0178 plus five direct decisions through ADRs 0179-0182 and 0184, with owning design changes]:::status APPLIED_DECISIONS -. explains; does not replace .-> ARCH TAXONOMY --> TRACKER_ALLOC[Implementation-tracker allocation]:::alignment @@ -91,7 +91,7 @@ Product and architecture documents are normative within their stated boundaries. ## Decision Application Status -This table describes the repository target state, not merely completed human review. The completed review archive remains source evidence; all `182` historical outcomes and the four direct post-archive decisions are integrated. Decision integration is complete; the remaining work is the planned whole-corpus authority review. +This table describes the repository target state, not merely completed human review. The completed review archive remains source evidence; all `182` historical outcomes and the five direct post-archive decisions are integrated. Decision integration is complete; the remaining work is the planned whole-corpus authority review. | Decision parcel | Human review | Applied to `develop` | Contract consolidation | Implementation and proof | | --- | --- | --- | --- | --- | @@ -106,11 +106,11 @@ This table describes the repository target state, not merely completed human rev | Selective Packet 5 communication/moderation/social lane, six reviewed outcomes | Complete in the review archive | Checked provenance applied for `MOD-01`, `MS-GR-COMMUNICATION-ORCHESTRATION`, `MS-SOCIAL-RELATIONSHIP-AUTHORITY`, `MS-SOCIAL-HISTORY-DURABILITY`, and `MS-SOCIAL-OBSERVER-SHOUT-POLICY` through ADRs 0146-0150; `SOCIAL-01` is checked as superseded provenance by ADRs 0147, 0149, and 0150 | Family-local owner-link and local-consequence consolidation for owner-local moderation, communication classes/delivery, social relationship/value authority, type-specific history, and closed observer/profile-scoped shout behavior | Reconcile owning trackers only where accepted target state changes implementation/proof gaps | | Selective Packet 6 P0 operations/delivery lane, ten reviewed outcomes | Complete in the review archive | Checked provenance applied for the ten Packet 6 P0 outcomes through ADRs 0151-0159; `PREFLIGHT-01` and `PREFLIGHT-02` share ADR 0152 | Family-local owner-link and local-consequence consolidation for compliance, phased preflight/bindings, backup/recovery proof, rollout, health, and observability | Reconcile owning trackers only where accepted target state changes implementation/proof gaps | | Final Packet 6 P1-P3 and Packet 7 import, 32 reviewed outcomes | Complete in the review archive | Checked provenance applied for all previously remaining decision keys through ADRs 0160-0178; thirteen reviewed outcomes strengthen existing ADR or canonical-design authority without a new ADR | Family-local owner-link and local-consequence consolidation for observability, capacity, verification, control availability, scripting, tracing, identity, edge/session routing, Redis, protobuf, commands, shared libraries, promotion, production apply, and preview proof | Implementation, calibration, and focused proof gaps remain explicit in the domain trackers; proceed to the planned whole-corpus authority review | -| Direct post-archive human decisions | Human-approved: `COMMERCE-02` on 2026-08-23; `HOSTED-TERMS-01` and `HOSTED-TERMS-02` on 2026-08-24; shared refinement through 2026-08-25; `OPS-07` on 2026-09-06 | `COMMERCE-02`, `HOSTED-TERMS-01`, `HOSTED-TERMS-02`, and `OPS-07` are applied through ADRs 0179-0182 without changing historical Packet 1-7 counts | Family-local consolidation for licensing lanes, hosted-terms authority, Game Design mutation gating, changed-terms continuity, and separated hosted runtime/identity lifecycles; hosted controller rollout and hosted certificate proof remain open | Obtain NZ legal review before operative use and implement/prove only the selected official-hosting boundaries; marketplace, organization, signer, settlement, and live hosted identity machinery remain gated | +| Direct post-archive human decisions | Human-approved: `COMMERCE-02` on 2026-08-23; `HOSTED-TERMS-01` and `HOSTED-TERMS-02` on 2026-08-24; shared refinement through 2026-08-25; `OPS-07` on 2026-09-06; `EDGE-WITHDRAWAL-01` on 2026-09-24 | `COMMERCE-02`, `HOSTED-TERMS-01`, `HOSTED-TERMS-02`, and `OPS-07` are applied through ADRs 0179-0182; `EDGE-WITHDRAWAL-01` through ADR 0184, without changing historical Packet 1-7 counts | Family-local consolidation for licensing lanes, hosted-terms authority, Game Design mutation gating, changed-terms continuity, separated hosted runtime/identity lifecycles, and emergency TCP Proxy identity withdrawal | Obtain NZ legal review before operative use and implement/prove only the selected official-hosting boundaries; marketplace, organization, signer, settlement, and live hosted identity machinery remain gated | ## Contract Authority Consolidation Scope -Contract-authority consolidation applies to repeated normative product and architecture contracts whether or not an ADR records their rationale. ADRs organize the selective application process, but they are not the boundary of the deduplication work. PRs #2593 and #2594 complete the baseline pass for ADRs 0001-0050 and the major adjacent non-ADR contract families encountered across those design areas. Packets 3-7 (ADRs 0051-0178 plus TICK-05) and the direct decisions in ADRs 0179-0182 are now integrated with family-local consolidation without redefining that baseline. +Contract-authority consolidation applies to repeated normative product and architecture contracts whether or not an ADR records their rationale. ADRs organize the selective application process, but they are not the boundary of the deduplication work. PRs #2593 and #2594 complete the baseline pass for ADRs 0001-0050 and the major adjacent non-ADR contract families encountered across those design areas. Packets 3-7 (ADRs 0051-0178 plus TICK-05) and the direct decisions in ADRs 0179-0182 and 0184 are now integrated with family-local consolidation without redefining that baseline. Consolidation names one canonical owner for a target contract and reduces competing secondary definitions to owner links plus local API, persistence, transport, operational, user-visible, implementation-drift, or proof consequences. It is not editorial deduplication: useful examples, runbooks, evidence schemas, local constraints, and explanatory context remain where they serve their owning document. @@ -159,9 +159,9 @@ PR closure follows the hosted review evidence and judgment described by the [PR ## Automated Gates -Focused validation on 2026-09-09 Pacific/Auckland passed for the current `355` discovered sources (`352` allocated, `3` explicit exemptions) and `180` ADR records, with `172` carrying completed review metadata and `11` pre-formal records; those categories overlap for accepted legacy pre-formal records carrying exact provenance. Prior parcel validation remains historical evidence only. On 2026-08-28 Pacific/Auckland, the integrated local gates passed against the then-current `354` discovered sources (`351` allocated, `3` explicit exemptions) and `179` ADR records, with `171` carrying completed review metadata and `11` pre-formal records: implementation tracking covered `79` leaves across `10` trackers, the authorization-route matrix passed, the full architecture-document contract suite passed, `linkCheck` checked `6,537` links (`6,489` OK, `0` errors, `48` excluded), `lintMarkdown` checked `535` files (`0` issues), and `git diff --check` was clean. These listed gates are local documentation/structure checks only. The current port also includes controller, Kubernetes, workflow, and deployment-tooling implementation with focused local proof; its owning domain tracker remains authoritative for implementation and proof status. Live hosted-environment proof remains unavailable, and neither the target contracts nor local checks should be read as commit, PR, CI, or live-hosted proof. +Focused validation on 2026-09-09 Pacific/Auckland passed for the then-current `355` discovered sources (`352` allocated, `3` explicit exemptions) and `180` ADR records, with `172` carrying completed review metadata and `11` pre-formal records; those categories overlap for accepted legacy pre-formal records carrying exact provenance. Prior parcel validation remains historical evidence only. On 2026-08-28 Pacific/Auckland, the integrated local gates passed against the then-current `354` discovered sources (`351` allocated, `3` explicit exemptions) and `179` ADR records, with `171` carrying completed review metadata and `11` pre-formal records: implementation tracking covered `79` leaves across `10` trackers, the authorization-route matrix passed, the full architecture-document contract suite passed, `linkCheck` checked `6,537` links (`6,489` OK, `0` errors, `48` excluded), `lintMarkdown` checked `535` files (`0` issues), and `git diff --check` was clean. These listed gates are local documentation/structure checks only. The current port also includes controller, Kubernetes, workflow, and deployment-tooling implementation with focused local proof; its owning domain tracker remains authoritative for implementation and proof status. Live hosted-environment proof remains unavailable, and neither the target contracts nor local checks should be read as commit, PR, CI, or live-hosted proof. -- `python3 dev-tools/validation/check-design-capability-allocation.py` derives the product and architecture source sets, parses each allocation ledger, and reconciles the declared current coverage summary (`355` discovered sources, `352` allocated sources, and the canonical `2` governance/template exemptions plus `1` registry exemption). +- `python3 dev-tools/validation/check-design-capability-allocation.py` derives the product and architecture source sets, parses each allocation ledger, and reconciles the declared current coverage summary (`357` discovered sources, `354` allocated sources, and the canonical `2` governance/template exemptions plus `1` registry exemption). - all intended FireMUD user, creator, operator, runtime, authoring, automation, platform, and commercial concerns have a capability home; - every Markdown source under `design/product/**` and `design/architecture/**` is present and classified in the allocation ledger, including generated/index material, unless it is one of the two explicit governance/template exemptions or the decision-registry exemption; - mixed canonical documents have heading-level allocations where file-level allocation would hide a real ownership split; diff --git a/design/project-management/design-alignment/consequential-decision-inventory.md b/design/project-management/design-alignment/consequential-decision-inventory.md index 20b1e1c351..191c024fa7 100644 --- a/design/project-management/design-alignment/consequential-decision-inventory.md +++ b/design/project-management/design-alignment/consequential-decision-inventory.md @@ -51,16 +51,16 @@ The inventory is split into this control ledger and exhaustive source-scoped led - [Specialized runtime decisions](./decision-inventory-specialized-runtime.md) contains 54 decisions and stronger evidence for 20 cross-cutting decisions from 38 Redis, scripting, tick, identity, token, migration, shared-library, spatial, authorization, and tracing documents. - [Product and operations decisions](./decision-inventory-product-operations.md) contains 41 decisions and stronger evidence for 11 existing keys from the remaining 38 product, frontend, authoring, protocol, infrastructure, deployment, recovery, observability, and generated-settings sources. -The merged Packet 6 P1-P3 baseline covered `340` discovered sources (`337` allocated, `3` explicit exemptions), including `165` allocated ADR records through ADR 0167. Packet 7 added 11 ADR records through ADR 0178, the four earlier direct decisions add ADRs 0179-0182, and `EDGE-WITHDRAWAL-01` adds ADR 0184. The canonical allocation therefore covers all 356 discovered product and architecture sources: 353 allocated decision-bearing sources and 3 explicit exemptions (the ADR registry/index plus two microservice governance/template documents). The four disjoint source-scoped partitions account for all 174 non-ADR paths (`22 + 76 + 38 + 38`); 172 are allocated (`22 + 74 + 38 + 38`) and two microservice governance/template paths are explicit exemptions. The 182-path ADR partition contributes 181 allocated ADR records plus the exempt ADR registry/index, yielding `174 + 182 = 356` discovered, `172 + 181 = 353` allocated, and 3 exemptions. The decision evidence set is 354 sources: the 353 allocated sources plus the exempt ADR registry/index; the two exempt microservice governance/template documents are discovered but excluded from decision evidence. A source may provide evidence without producing a distinct decision row. The source-scoped ledgers preserve unique primary ownership for the historical reviewed keys; the five post-archive direct decisions have checked provenance in this control ledger. Cross-cutting evidence/reference rows may repeat existing keys across ledgers and do not add distinct keys. The microservice service-source ledger has 23 rows: 22 distinct non-alias service-source decisions (21 active plus the formal superseded `MS-GR-EQUIPMENT-BODY-LAYOUT`) plus the navigation-only historical service-scan alias `MS-AA-TOKEN-REVOCATION`. The removed `MS-PO-OWNER-REMEDIATION` key remains historical review evidence below and is not a service-source row. The completed historical human-review archive still has one row for each of its 182 decision keys plus the historical alias; the five direct decisions increase the current universe to 187 distinct keys and 188 key/navigation rows without changing that archive. Collectively, the inventories reference all 79 leaf capabilities in the taxonomy. +The merged Packet 6 P1-P3 baseline covered `340` discovered sources (`337` allocated, `3` explicit exemptions), including `165` allocated ADR records through ADR 0167. Packet 7 added 11 ADR records through ADR 0178, the four earlier direct decisions add ADRs 0179-0182, and `EDGE-WITHDRAWAL-01` adds accepted ADR 0184; separately, ADR 0183 is an allocated proposal pending human review and adds no accepted key. The canonical allocation therefore covers all 357 discovered product and architecture sources: 354 allocated decision-bearing sources and 3 explicit exemptions (the ADR registry/index plus two microservice governance/template documents). The four disjoint source-scoped partitions account for all 174 non-ADR paths (`22 + 76 + 38 + 38`); 172 are allocated (`22 + 74 + 38 + 38`) and two microservice governance/template paths are explicit exemptions. The 183-path ADR partition contributes 182 allocated ADR records plus the exempt ADR registry/index, yielding `174 + 183 = 357` discovered, `172 + 182 = 354` allocated, and 3 exemptions. The decision evidence set is 355 sources: the 354 allocated sources plus the exempt ADR registry/index; the two exempt microservice governance/template documents are discovered but excluded from decision evidence. A source may provide evidence without producing a distinct decision row. The source-scoped ledgers preserve unique primary ownership for the historical reviewed keys; the five post-archive direct decisions have checked provenance in this control ledger. Cross-cutting evidence/reference rows may repeat existing keys across ledgers and do not add distinct keys. The microservice service-source ledger has 23 rows: 22 distinct non-alias service-source decisions (21 active plus the formal superseded `MS-GR-EQUIPMENT-BODY-LAYOUT`) plus the navigation-only historical service-scan alias `MS-AA-TOKEN-REVOCATION`. The removed `MS-PO-OWNER-REMEDIATION` key remains historical review evidence below and is not a service-source row. The completed historical human-review archive still has one row for each of its 182 decision keys plus the historical alias; the five direct decisions increase the current universe to 187 distinct keys and 188 key/navigation rows without changing that archive. Collectively, the inventories reference all 79 leaf capabilities in the taxonomy. | Capability | Sources reviewed | Decisions inventoried | Human-review candidates | Coverage state | | --- | ---: | ---: | ---: | --- | -| Existing ADR set | 181 ADR records (173 with completed review metadata; 11 pre-formal records, with overlap where accepted legacy records now carry exact review provenance) plus the architecture decision registry/index | 9 original aliases within the 68 cross-cutting decisions; later reviewed records are allocated directly | Complete in the historical source archive; ADRs 0179-0182 and 0184 are direct post-archive decisions | Complete and allocated through ADR 0184 | +| Existing ADR set | 182 ADR records (173 with completed review metadata; 11 pre-formal records, with overlap where accepted legacy records now carry exact review provenance; ADR 0183 remains pending) plus the architecture decision registry/index | 9 original aliases within the 68 cross-cutting decisions; later reviewed records are allocated directly | Complete in the historical source archive; ADRs 0179-0182 and 0184 are direct post-archive decisions; ADR 0183 is pending human review | Complete and allocated through ADR 0184, with ADR 0183 preserved as pending | | Cross-cutting system architecture | 22 canonical sources plus ADRs | 68 | Complete in the source archive | Complete and independently audited | | Microservice architecture | 76 covered paths (74 allocated evidence paths; 2 explicit governance/template exemptions) | 23 service-source rows = 22 distinct decisions (21 active + formal superseded `MS-GR-EQUIPMENT-BODY-LAYOUT`) + excluded historical `MS-AA-TOKEN-REVOCATION` alias; `MS-PO-OWNER-REMEDIATION` remains historical review evidence; stronger evidence for 41 existing keys | Complete in the historical source archive plus direct `HOSTED-TERMS-01` provenance | Complete and independently audited | | Specialized runtime architecture | 38 sources | 54 new; stronger evidence for 20 existing keys | Complete in the source archive | Complete and independently audited | | Product and operations architecture | 38 sources | 41 new; stronger evidence for 11 existing keys | Complete in the historical source archive plus the four earlier direct post-archive decisions; `EDGE-WITHDRAWAL-01` is recorded in this control ledger | Complete and independently audited | -| **Decision keys / navigation rows** | **All 356 design sources: 353 allocated decision-bearing sources (172 allocated non-ADR documents and 181 ADR records), 1 exempt architecture decision registry/index, and 2 excluded governance/template exemptions; 353 allocated and 3 total exemptions** | **187 current decision keys; 188 navigation/key rows including one historical service-scan alias** | **All 183 historical queue/navigation rows reviewed in the source archive plus five direct human decisions** | **All 187 current decision keys have reviewed outcomes applied; Packet 1-7 remains complete through ADR 0178 and direct post-archive decisions are applied through ADR 0184** | +| **Decision keys / navigation rows** | **All 357 design sources: 354 allocated decision-bearing sources (172 allocated non-ADR documents and 182 ADR records), 1 exempt architecture decision registry/index, and 2 excluded governance/template exemptions; 354 allocated and 3 total exemptions** | **187 current decision keys; 188 navigation/key rows including one historical service-scan alias** | **All 183 historical queue/navigation rows reviewed in the source archive plus five direct human decisions** | **All 187 current reviewed decision keys have outcomes applied; pending ADR 0183 adds no accepted key; Packet 1-7 remains complete through ADR 0178 and direct post-archive decisions are applied through ADR 0184** | ## Legacy ADR Alias Navigation diff --git a/design/project-management/design-alignment/decision-inventory-cross-cutting.md b/design/project-management/design-alignment/decision-inventory-cross-cutting.md index 4228cedbe3..4886445561 100644 --- a/design/project-management/design-alignment/decision-inventory-cross-cutting.md +++ b/design/project-management/design-alignment/decision-inventory-cross-cutting.md @@ -131,7 +131,7 @@ The first 22 source-index entries are the counted cross-cutting partition. `WE`, | `TICK-01` | `GR-1.2` | `GR-1.3`, `GR-1.1`, `GR-4.1`, `AS-1.4` | What is the gameplay clock and fairness unit? Independently advancing regional hybrid ticks use separate deterministic actor-action and passive/inbound-effect lanes. The actor-action lane selects at most one root intentional actor action originated by an eligible entity per tick; passive/inbound effects are separately bounded and do not consume the target entity's actor-action slot. | `accepted-explicit` | H/hard | [ADR 0051](../../architecture/decisions/adr-0051-separate-actor-action-and-effect-lanes.md); `TK § Hybrid Tick Model`; `TK § Per-Command Execution Phases`; `OV § Game Loop / Tick Model` | One universal entity work slot, a real-time event loop, global ticks, or unrestricted per-entity concurrency. | Human review revised the universal work slot into actor-action and effect lanes; implementation and focused proof remain. | | `TICK-02` | `GR-1.3` | `GR-1.2`, `GR-1.4`, `SF-2.2`, `SF-2.3`, `PO-4.2` | How is tick authority fenced? An opaque Redis liveness token proves ephemeral lease possession; PostgreSQL independently installs a fresh never-reused durable `executorFence` by expected-epoch/prior-state CAS and persists only a non-secret token correlation; the same Redis token is revalidated before staging; Redis mutations compare token/epoch and durable writes compare fence/epoch. Renewal preserves the fence, reset advances epoch before Redis clear, and either authority outage stops new progress. | `accepted-explicit` | H/hard | [ADR 0052](../../architecture/decisions/adr-0052-redis-liveness-lease-with-durable-executor-fence.md); `TK § Region Authority and Tick Executor`; `TK § Tick Commit Definition (Heartbeat Watermark)`; `RD § Redis Coordination Invariants` | PostgreSQL-only expiring leases, Redis-only leases, a consensus service, or global coordinator. | Human review revised and accepted the dual-store install-and-revalidate protocol; true region partitioning and failure proof remain. | | `TICK-03` | `SF-2.4` | `GR-1.2`, `SF-2.3`, `GR-4.1`, `GR-2.2`, `GR-3.2` | Are gameplay commands globally atomic? Local transactions plus stable `EffectId`-guarded at-least-once effects remain the default, but every command declares required/optional effects, permitted terminal combinations, and whether `PARTIAL` is intentional before execution; `SUCCESS` requires every required effect to be durably applied or have durable, evidence-qualified stored replay/no-op proof; unresolved or merely replayable required work remains `PENDING`/reconciliation-required. Invariant-sensitive commands use one authoritative local transaction or durable reservation/escrow; recovery records `APPLIED`/`ABANDONED` only where the existing durable evidence policy permits, never by bulk terminalization. | `accepted-explicit` | H/hard | [ADR 0053](../../architecture/decisions/adr-0053-command-atomicity-by-invariant-class.md); `TX § In-Game Command Transactions (No Sagas Needed)`; `TX § When Gameplay Commands Must Not Depend on Global Atomicity` | Distributed transaction, synchronous two-phase commit, or compensating rollback. | Human review revised and accepted invariant-class atomicity; command-family classification and proof remain. | -| `TICK-04` | `SF-2.3` | `GR-2.2`, `GR-3.2`, `GR-4.1`, `GR-1.4`, `SF-1.2` | How are effects deduplicated and spatial ownership divided? World owns topology/location/occupancy/ambient state; Entity owns inventory/equipment/containment/ground; participant guard uniqueness is the root `EffectId` plus typed operation plus target aggregate. The immutable `requestDigest` is persisted and validated separately as guard metadata—changed metadata fails closed—but it is never part of uniqueness. Under ADR 0059, Game Logic propagates the Game Session-allocated causal floor and composes returned same-scope/epoch served-through proofs with opaque component versions. | `accepted-explicit` | H/hard | [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md); [ADR 0059](../../architecture/decisions/adr-0059-causal-floor-cross-service-presentation-reads.md); [ADR 0060](../../architecture/decisions/adr-0060-world-owned-ambient-facts-and-logic-owned-consequences.md); [identifier glossary](../../architecture/system-architecture-identifier-glossary.md) § `Cross-Service Causal-Read Fence Identity`; `TX § Tick Effects Are At-Least-Once: Idempotency Is Mandatory`; `TX § Spatial Effects: Location vs Containment (World ↔ Entity)`; `OV § Canonical Room Runtime Contract`; `TK § Tick Effect Identity and Idempotency Contract` | Shared room transaction or authoritative monolithic gameplay state. | Human review revised and accepted split spatial authority under ADR 0054 and causal-floor composition under ADR 0059; operation-bound guards, mutation preconditions, and proof remain. | +| `TICK-04` | `SF-2.3` | `GR-2.2`, `GR-3.2`, `GR-4.1`, `GR-1.4`, `SF-1.2` | How are effects deduplicated and spatial ownership divided? World owns topology/location/occupancy/ambient state; Entity owns inventory/equipment/containment/ground; participant guard uniqueness is the persisted mutation `EffectId` (root for a command-root mutation or one-time allocated opaque child for a generated/derived mutation) plus typed operation plus target aggregate, with the enclosing root retained as lineage where applicable. This is scoped shorthand for the owner-declared runtime-family partition: S1/S2 use `(tenantId, playableStateNamespaceId)`, explicit S3 uses `(tenantId, gameInstanceId)`, and an unknown or unclassified family fails closed. The immutable `requestDigest` is persisted and validated separately as guard metadata—changed metadata fails closed—but it is never part of uniqueness. The accepted TICK-04 decision does not select a generated-child allocator; any future allocator and replay binding remain non-authoritative pending the [ADR 0183 proposal](../../architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). Under ADR 0059, Game Logic propagates the Game Session-allocated causal floor and composes returned same-scope/epoch served-through proofs with opaque component versions. | `accepted-explicit` | H/hard | [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md); [ADR 0059](../../architecture/decisions/adr-0059-causal-floor-cross-service-presentation-reads.md); [ADR 0060](../../architecture/decisions/adr-0060-world-owned-ambient-facts-and-logic-owned-consequences.md); [identifier glossary](../../architecture/system-architecture-identifier-glossary.md) § `Cross-Service Causal-Read Fence Identity`; `TX § Tick Effects Are At-Least-Once: Idempotency Is Mandatory`; `TX § Spatial Effects: Location vs Containment (World ↔ Entity)`; `OV § Canonical Room Runtime Contract`; `TK § Tick Effect Identity and Idempotency Contract` | Shared room transaction or authoritative monolithic gameplay state. | Human review revised and accepted split spatial authority under ADR 0054 and causal-floor composition under ADR 0059; operation-bound guards, mutation preconditions, and proof remain. | | `TICK-05` | `SF-2.4` | `SF-2.3`, `GR-1.2`, `AS-1.5`, `PO-1.1` | Where do side effects and workflows run? Gameplay uses tick reconciliation; simple asynchronous delivery uses an outbox; bounded caller/worker-owned orchestration may use a local saga; restart-independent continuation, durable waits/signals, and operator-managed in-flight lifecycle use Temporal. | `accepted-explicit` | H/med | `TX § Tick-Adjacent Workflows (Outbox Boundary)`; `TX § Saga vs Temporal Boundary`; `TW § Canonical Usage Boundary` | Put every durable operation in Temporal or rebuild durable continuation from local sagas and outbox workers. | Human review accepted the three-way substrate boundary with a mandatory adopter test; implementation/proof remain adopter-specific and no new ADR is required while gameplay remains outside Temporal. | | `TICK-06` | `GR-2.1` | `GR-1.3`, `GR-1.4`, `SF-2.3`, `AA-3.3`, `PO-4.2` | How do cross-region effects and topology changes work? Durable asynchronous follow-ups use static live topology; maintenance split/merge freezes producers, drains and reconciles, bumps epochs, rebuilds coordination, and reopens only after explicit terminalization and health validation. | `accepted-explicit` | H/hard | [ADR 0055](../../architecture/decisions/adr-0055-durable-cross-region-effects-with-static-live-topology.md); `TK § Tick Regions and Parallel Execution`; `TK § Topology Changes (Split/Merge) Protocol (Required Invariants)`; `TX § Reconciliation Owner of Record (Spatial/Ambient Effects)` | Global locks, synchronous cross-region ticks, or automatic live topology migration. | Human review revised and accepted the static-topology/maintenance-cutover boundary; remote follow-up and migration proof remain. | | `TICK-07` | `AS-1.4` | `GR-1.2`, `GR-2.3`, `AS-1.5`, `SF-1.4` | How are timers recovered? Each timer declares its clock and recovery class; durable correctness work preserves identity, recurring schedules choose `SKIP_MISSED` or one bounded `COALESCE_ONE`, and advisory work may drop under its declared budget. | `accepted-explicit` | H/med | [ADR 0072](../../architecture/decisions/adr-0072-class-specific-timer-durability-and-recovery.md); `TK § Timers and Time Scaling`; `TK § Scheduler Recovery Semantics`; `SC § Validation & Admission Pipeline` | Replay every missed timer or treat all timers as durable commands. | Human review revised and accepted class-specific timer durability/recovery; scheduler implementation and proof remain partial. | @@ -172,7 +172,7 @@ The first 22 source-index entries are the counted cross-cutting partition. `WE`, | `SEC-02` | `SF-1.3` | `PO-3.2`, `PO-4.2`, `AA-1.3`, `PO-1.3` | How do Account JWT keys rotate and when is the boundary player-facing ready? Planned rotation prepublishes, proves validator visibility, promotes, overlaps through retiring-token expiry, and prunes; compromise/restore quarantines and hard-cuts the environment-wide issuer. Current shared HMAC is implementation debt and fails the readiness gate. | `accepted-explicit` | H/hard | `SE § JWT Key & JWKS Rotation Workflow`; [ADR-0014](../../architecture/decisions/adr-0014-phased-jwt-signing-key-rotation-and-readiness.md) | Use a maintenance-window hard cutover for every rotation, or adopt a non-exportable external signer while preserving the lifecycle protocol. | ADR-0014 records the revised human decision; issuance, validation, automation, convergence, and gate enforcement remain incomplete. | | `SEC-03` | `PO-2.2` | `SF-1.3`, `AA-1.3`, `PO-2.1`, `AA-2.1`, `EA-3.1` | Is plaintext Telnet accepted in production and is TOTP enforced? Public player-facing Telnet requires TLS; raw Telnet is local/test/private-only, and no TOTP transport gate is added. | `accepted-explicit` | H/hard | [ADR 0033](../../architecture/decisions/adr-0033-public-player-facing-telnet-requires-tls.md); `SE § Plaintext Telnet policy`; `AU § Implemented Status` | Preserve public plaintext with warnings/hardening, require TOTP, or add a secure-side-channel single-use ticket. | Revised and accepted by human decision; TLS protects the actual channel without imposing a factor that leaves the session exposed. | | `SEC-04` | `PO-1.1` | `PO-1.2`, `PO-1.3`, `PO-1.4`, `PO-2.1`, `GR-1.1`, `AR-3.3` | Where do administrative and session-lifecycle writes enter? The target external operator boundary sends moderation, runtime flags, quota overrides, admission control, tick/coordination remediation, and session-lifecycle operations through Gateway to Logging/Admin; domain services retain mutation authority. Current Game Session `/sessions*` routes remain owner-local/internal and are not evidence that target Logging/Admin forwarding is live. The moderation policy-input/audit mutation is currently unavailable/gated pending its action-family schema, shared cross-language `mutationDigest/v1` golden vectors, Account-owned authorization-reference issuance, and Logging & Admin receiving-boundary validation/redemption; `EvaluateModerationPolicy` remains a separate live read consumed at the owner enforcement boundaries, and no domain-owner redemption or enforcement is part of that persistence path. Quota overrides, broader remediation, and other owner mutations without a complete route/proof remain gated or target-only. | `accepted-explicit` | H/med | `OV § Admin Entry Points and Traffic Surfaces`; `OV § Core Operator Action Backing Contracts (Canonical)`; `RM § Notes on Movement and Moderation Contracts`; [ADR-0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md) (human review completed 2026-07-19; revised); [ADR-0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md) (human review completed 2026-07-19; revised) | Direct domain admin endpoints or a separate operator write plane. | ADR-0047 and ADR-0048 are accepted, revised, and human-reviewed; action-family implementation and proof remain partial where the route or owner contract is gated. | -| `ADMIN-01` | `PO-1.1` | `PO-1.3`, `PO-1.4`, `SF-2.3`, `GR-1.1`, `PO-4.1` | What backs operator writes and forwarding? Logging & Admin durably records one logical mutation under one `controlPlaneRequestId`; only ADR 0048-permitted transport retries reuse the exact authority-bound tuple, and the domain owner deduplicates them while atomically persisting the mutation and idempotent result. Lost responses and final-audit failures use read-only reconciliation under that identifier rather than redelivering an ambiguous mutation. Observability is not a write dependency, and region-scoped Game Session mutations execute at the current lease owner under the current gameplay fence. | `accepted-explicit` | H/hard | [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md); `OV § Core Operator Action Backing Contracts (Canonical)`; `OV § Admin Entry Points and Traffic Surfaces`; `RM § Notes on Movement and Moderation Contracts` | Let operators write domain stores directly, use best-effort forwarding or distributed transactions, let dashboards determine write success, or let a session front-end mutate region-owned coordination without lease-owner forwarding. | Human review revised and accepted durable intent, owner-local idempotency, explicit uncertain outcomes, and fenced lease-owner forwarding; implementation and focused proof remain. | +| `ADMIN-01` | `PO-1.1` | `PO-1.3`, `PO-1.4`, `SF-2.3`, `GR-1.1`, `PO-4.1` | What backs operator writes and forwarding? Logging & Admin durably records one logical mutation under the applicable action-family request identity: `controlPlaneRequestId` for non-moderation mutations, `policyIntentRequestId` for local moderation policy intent, and `ownerEnforcementRequestId` for moderation owner-enforcement commands; moderation may carry `controlPlaneRequestId` only as correlation. Only ADR 0048-permitted transport retries reuse the exact authority-bound tuple, and the domain owner deduplicates them while atomically persisting the mutation and idempotent result. Lost responses and final-audit failures use read-only reconciliation under that applicable identity rather than redelivering an ambiguous mutation. Observability is not a write dependency, and region-scoped Game Session mutations execute at the current lease owner under the current gameplay fence. | `accepted-explicit` | H/hard | [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md); [ADR 0146](../../architecture/decisions/adr-0146-owner-local-moderation-enforcement.md) (`MOD-01`); `OV § Core Operator Action Backing Contracts (Canonical)`; `OV § Admin Entry Points and Traffic Surfaces`; `RM § Notes on Movement and Moderation Contracts` | Let operators write domain stores directly, use best-effort forwarding or distributed transactions, let dashboards determine write success, or let a session front-end mutate region-owned coordination without lease-owner forwarding. | Human review revised and accepted durable intent, owner-local idempotency, explicit uncertain outcomes, and fenced lease-owner forwarding; implementation and focused proof remain. | | `MOD-01` | `PO-1.2` | `EA-2.4`, `AA-1.3`, `PO-1.3`, `PO-4.1` | Logging & Admin owns moderation ingress, policy intent, moderation cases, and audit, then forwards a typed digest-bound idempotent command to the enforcement owner. Appeal cases are a distinct bounded case type governed separately by ADR 0142. Account durably owns `platform_access_ban`, its authentication-generation/account-wide revocation consequence, and Account owner-local restriction/security state; protective `account_security_lock` remains separate Account policy/recovery state. Game Session durably owns `gameplay_ban`; Social durably owns `chat_mute` and `chat_ban`; routine enforcement reads owner-local state without a Logging & Admin RPC. | `accepted-explicit` | H/hard | [ADR 0146](../../architecture/decisions/adr-0146-owner-local-moderation-enforcement.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); `OV § Moderation, Restriction, and Appeal Authority (Canonical)`; [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); `RM § Notes on Movement and Moderation Contracts` | Versioned distributed policy snapshots, synchronous central checks, centralized enforcement, or best-effort notification after audit success. | Human review completed 2026-07-20; `revised`. Current synchronous `PLAY` and chat-send checks are implementation drift; owner commands, monotonic enforcement records, active-binding containment, and lifecycle proof remain incomplete. | | `SEC-05` | `SF-1.3` | `AA-1.3`, `AA-2.1`, `PO-2.4`, `PO-1.2` | Who owns brute-force and abuse controls? Edge services own transport pressure, Account exclusively owns credential abuse without failed-attempt hard locks, and Game Session owns local fast-path post-auth command budgets with optional coarse shared backstops. | `accepted-explicit` | H/hard | [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); `SE § Brute-Force Defense and Abuse Handling`; `GW § Rate Limiting & Abuse Protection` | Let the edge lock accounts, centralize all limits in Account, durably lock after a failure threshold, or retain a distributed Redis operation for every gameplay command. | Revised and accepted by human decision; trusted source propagation, non-enumerating graduated throttles, fail-closed new login, and local command buckets preserve security without an attacker-triggered denial or gameplay datastore dependency. | | `OPS-01` | `PO-3.1` | `AR-1.5`, `PO-3.3`, `PO-4.4`, `SF-1.1` | What artifact is promoted? One canonical build records exact source/build/platform lineage; the staged OCI manifest or index digest and all production-supported child digests promote without rebuild. Tags are aliases, and changed cross-registry copies require mapped destination staging. Platform and game-content attestations remain separate. | `accepted-explicit` | H/med | [ADR 0097](../../architecture/decisions/adr-0097-git-and-ci-validated-single-operator-promotion-evidence.md); `CI § Building and Pushing Images`; `CI § Promotion & Rollback Model`; `VR § Game Version Publishing` | Rebuild separately per environment, promote mutable tags, or treat an unproved platform child/cross-registry copy as the staged artifact. | `accepted` on 2026-07-21 with multi-architecture, copy, and lineage clarification; current builder and fail-open attestation drift remain implementation gaps. | diff --git a/design/project-management/design-alignment/design-capability-allocation.md b/design/project-management/design-alignment/design-capability-allocation.md index 3d9778e824..9b6eb9efad 100644 --- a/design/project-management/design-alignment/design-capability-allocation.md +++ b/design/project-management/design-alignment/design-capability-allocation.md @@ -24,7 +24,7 @@ This file intentionally owns the detailed allocation-validation history; the des - Final combined Packet 5 tail and Packet 6 P0 validation record on 2026-08-25 Pacific/Auckland (2026-08-24 UTC): all active ADRs 0146-0159 are allocated; `linkCheck` checked `6,039` total links (`6,002` OK, `37` excluded, `0` errors); `lintMarkdown` checked `509` files (`0` issues); allocation reported `332` sources (`329` allocated, `3` explicit exemptions); ADR review status was `146` reviewed / `11` pre-formal; architecture doc contracts, allocation regression `28` tests, ADR review regression `141` tests, and authorization-route regression `216` tests passed; the focused preflight, player-experience evidence, player-experience runner, and observability-validator contract tests passed; and Ruff, ShellCheck, Python syntax, and `git diff --check` were clean. No environment-backed runtime proof is required for validating this allocation ledger itself. That ledger-only exemption does not waive runtime-proof requirements for the allocated architecture documents or operational validation tooling; changes requiring canonical fresh-image rebuild-and-boot proof must retain and report that requirement separately. - Packet 6 P1-P3 allocation state: ADRs 0160-0167 add 8 reviewed records, bringing the canonical source set to `340` discovered sources (`337` allocated, `3` explicit exemptions) and the ADR registry to `165` records. The final reviewed import through Packet 7 ADRs 0168-0178 adds 11 more ADR records (19 reviewed records across both parcels), yielding `351` discovered sources (`348` allocated, `3` explicit exemptions) and `176` ADR records. Those review categories overlap where accepted legacy pre-formal records now carry exact review metadata. This structural state does not upgrade implementation or runtime proof for the allocated decisions; final parcel validation is reported by the design-alignment workstream rather than inferred from allocation arithmetic. - The four post-archive direct human decisions `COMMERCE-02`, `HOSTED-TERMS-01`, `HOSTED-TERMS-02`, and `OPS-07` add ADRs 0179-0182 without changing the completed historical Packet 1-7 archive. They bring the canonical source set to `355` discovered sources (`352` allocated, `3` explicit exemptions) and the ADR registry to `180` records. The marketplace, hosted-terms, signer, and billing-lifecycle boundaries remain future or pre-launch target state. This allocation entry records allocation authority and target-state boundaries only; for ADR 0182, only local/static prerequisite evidence exists, while live activation, certificate issuance, and consumer convergence remain unproved. It does not establish broader implementation status, focused proof, or environment-backed runtime proof. -- The later direct human `EDGE-WITHDRAWAL-01` decision adds ADR 0184 to the current source set without changing the historical Packet 1-7 archive or the four earlier direct-decision outcomes. The current allocation is `356` discovered sources (`353` allocated, `3` explicit exemptions) and `181` ADR records. Emergency withdrawal remains unproved in a live hosted environment; this source allocation is not runtime proof. ADR 0183 is reserved by a separate stacked proposal and is not imported into this direct-to-`develop` decision record. +- The pending AI-authored ADR 0183 proposal and the later direct human `EDGE-WITHDRAWAL-01` decision in accepted ADR 0184 add two allocated ADR sources to the four post-archive decisions above. The current canonical source set is `357` discovered sources (`354` allocated, `3` explicit exemptions), including `182` ADR records plus the registry/index exemption. ADR 0183 remains `Proposed - Pending Human Review` with `AI-AUTHORED-PENDING` provenance; its mechanical renumbering preserves the proposal but does not accept it. ADR 0184's emergency withdrawal remains unproved in a live hosted environment; this allocation is not runtime proof. - Historical baseline allocation-validator run on 2026-08-27 Pacific/Auckland: `python3 dev-tools/validation/check-design-capability-allocation.py` passed with `340` discovered sources (`337` allocated, `3` explicit exemptions). This records the Packet 6 baseline allocation coverage only and does not claim implementation or runtime proof. - Pre-licensing-integration allocation and ADR review-status baseline on 2026-08-28 Pacific/Auckland: allocation validation passed with `351` discovered sources (`348` allocated, `3` explicit exemptions), and ADR review-status validation passed with `168` reviewed ADRs and `11` pre-formal records. ADRs 0002, 0007, and 0008 are overlapping records present in both the reviewed count and the 11 pre-formal records, so the deduplicated registry total is `168 + 11 - 3 = 176` before licensing integration. These are historical baseline/provenance facts, separate from implementation or runtime proof. - Licensing-integration validation on 2026-08-28 Pacific/Auckland: allocation validation passed with `354` discovered sources (`351` allocated, `3` explicit exemptions); ADR review-status validation passed with `171` reviewed ADRs and `11` pre-formal records; implementation tracking passed with `79` leaves across `10` trackers; the authorization-route matrix and full architecture-document contract suite passed; `linkCheck` checked `6,537` links (`6,489` OK, `0` errors, `48` excluded); `lintMarkdown` checked `535` files (`0` issues); and `git diff --check` was clean. ADRs 0002, 0007, and 0008 are overlapping records present in both the reviewed count and the 11 pre-formal records, so the deduplicated registry total is `171 + 11 - 3 = 179` after licensing integration. These checks establish documentation and structural consistency for the integration only; they do not claim commit, PR, CI, or runtime proof. @@ -46,16 +46,16 @@ This file intentionally owns the detailed allocation-validation history; the des | Infrastructure | 6 | 6 | 0 | 100% classified | | Generated references | 2 | 2 | 0 | 100% classified | | Microservice architecture | 76 | 74 | 0; 2 explicit governance/template exemptions | 100% classified | -| Architecture decisions | 182 | 181 | 0; 1 registry exemption | 100% classified | +| Architecture decisions | 183 | 182 | 0; 1 registry exemption | 100% classified | | Product documentation | 7 | 7 | 0 | 100% classified | -| **Total** | **356** | **353** | **0; 3 explicit exemptions** | **100% classified** | +| **Total** | **357** | **354** | **0; 3 explicit exemptions** | **100% classified** | ## Allocation Ledger | Design source | Heading or scope | Primary capability | Secondary handoffs | Source class | Notes or gap | | --- | --- | --- | --- | --- | --- | | [Microservice architecture allocation](./design-capability-allocation-microservices.md) | All 76 files under `design/architecture/microservices/**` | Per-source allocation | Per-source handoffs | Service design, contract, runtime/data, configuration, operations, and reference sources | All 76 files are accounted for as 74 allocated sources plus 2 exempt governance/template files: `service-documentation-structure.md` and `service-template.md`; complete path-set coverage | -| [Architecture decision registry](../../architecture/decisions/README.md) | Registry plus 181 ADRs | Per-record allocation | Per-record affected capabilities | Decision record | The registry is an index; reviewed, accepted, superseded, and withdrawn records remain distinguishable | +| [Architecture decision registry](../../architecture/decisions/README.md) | Registry plus 182 ADRs | Per-record allocation | Per-record affected capabilities | Decision record | The registry is an index; reviewed, accepted, superseded, withdrawn, and pending records remain distinguishable | | [System architecture allocation](./design-capability-allocation-system.md) | All 83 direct architecture, 6 infrastructure, and 2 generated sources | Per-source allocation | Per-source handoffs | Normative design, runbook, reference, index, and generated sources | Complete path-set coverage | | [Product documentation](../../product/README.md#canonical-sources) | All 7 files under `design/product/**` | Per-source allocation | Per-source product behavior scope | Requirements, taxonomy, index, and observable product behavior | Complete path-set coverage | @@ -244,6 +244,7 @@ This file intentionally owns the detailed allocation-validation history; the des | `design/architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md` | `AA-1` | `AR-1`, `EA-3`, `PO-1`, `SF-2` | Accepted | | `design/architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md` | `PO-1` | `AA-1`, `AR-1`, `EA-3`, `SF-2` | Accepted | | `design/architecture/decisions/adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md` | `PO-3` | `PO-1`, `PO-4`, `SF-1` | Accepted | +| `design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md` | `GR-1` | `GR-4`, `AS-1`, `SF-1`, `SF-2`, `PO-4` | Proposed - Pending Human Review | | `design/architecture/decisions/adr-0184-emergency-tcp-proxy-identity-withdrawal.md` | `SF-1` | `PO-2`, `PO-3`, `PO-4` | Accepted | ADR 0121 is superseded by [ADR 0114](../../architecture/decisions/adr-0114-command-plan-preview-dry-run-isolation.md); its historical capability allocation remains recorded above. diff --git a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md index 7a04624770..1f892e4376 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -16,7 +16,7 @@ The exact-base publication-provenance candidates in this stack are not yet live. ### Game Session receiver candidate -The Game Session receiver candidate retains lower-level helper behavior for admitting the exact local patch/base/pin tuple, persisting the admitted base on commands through an additive migration, comparing it on retries, and using it for command-status publication links. Focused owner tests cover those helper paths and missing/mismatched-base rejection, but do not prove live authenticated receiver admission: the authenticated local and remote receiver gates fail closed with `FAILED_PRECONDITION` / `automation_admission_receiver_fence_unavailable` before mutation. Historical command rows and pre-upgrade pins without a proven base remain fail-closed; live database migration, cross-service deployment, and the distinct-instance remote target tuple remain open as recorded below. See the [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status). +The Game Session receiver candidate retains lower-level helper behavior for admitting the exact local patch/base/pin tuple, persisting the admitted base on commands through an additive migration, comparing it on retries, and using it for command-status publication links. Its authenticated `EnqueueAutomationCommandIfAbsent` and `ScheduleRemoteFollowup` receiving RPCs are currently gated before live mutation because the separate Automation admission-epoch receiver fence is absent; both fail closed with `FAILED_PRECONDITION` / `automation_admission_receiver_fence_unavailable`. The gate and its successor activation requirement are recorded in the [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status). Focused lower-level owner tests cover exact tuple and missing/mismatched-base rejection, but do not prove successful end-to-end receiver admission. Historical command rows and pre-upgrade pins without a proven base remain fail-closed; live database migration, cross-service deployment, and the distinct-instance remote target tuple remain open as recorded below. ### Other current runtime boundaries @@ -24,10 +24,16 @@ Current residual: the legacy NPC formation REST controllers are removed and `/fo The current Automation queue reset/rebuild/resume path is unavailable and must fail closed regardless of the observed status mix; a non-atomic status preflight cannot authorize the target PENDING-only workflow. The owner-reconciled target recovery and its proof remain outstanding. +Routed, unassigned runtime obligation for Automation `AS-1.1`/`AS-1.2`: the current instance-tagged queue key, `ScriptWorkItem` row/identity lookup, queue pointer, and `outboxWorkItemId`-only claim do not establish namespace isolation. Canonical target identity and queue behavior are owned by the [normative scripting identity contract](../../architecture/system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) and [DSL Reference and Lifecycle](../../architecture/system-architecture-scripting-dsl-reference-and-lifecycle.md#implementation-status). This tracker records the current isolation gap and its routed, unassigned status only; it selects no topology or reset capability, establishes no available queue reset/rebuild path, and promotes no implementation status. + +After DSL evaluation, a retryable fanout fence, handoff preflight failure, or uncertain child result cannot automatically return the parent to `PENDING_EVALUATION`: the current schema has no frozen evaluated descriptor or complete child-recovery ledger. The executor retains its durable `EVALUATING` or `HANDOFF_IN_FLIGHT` evidence for explicit reconciliation. This fail-closed boundary does not implement the stage-aware recovery aggregate required by [ADR 0107](../../architecture/decisions/adr-0107-stage-aware-script-dead-letter-recovery.md). + The production executor selects pending candidates without claiming them, then commits each `PENDING_EVALUATION -> EVALUATING` claim in its own transaction before processing that item in a separate transaction. A worker stop between those commits can still leave an unprocessed `EVALUATING` row; this crash window remains a target recovery gap. The Game Session client maps ordinary runtime transport failures to an unavailable response and bounded backoff. If processing fails or an inner participating transaction marks the processing transaction rollback-only, the processing transaction rolls back while the previously committed claim remains unresolved `EVALUATING`; the bounded batch continues with eligible siblings and does not requeue or retry that item in the same invocation. Focused unit proof covers separate transaction boundaries and a simulated processing-commit rollback after a remote effect, but does not exercise real Spring proxy rollback-only propagation or PostgreSQL crash/concurrency behavior. There is still no durable evaluation-owner lease, stage/descriptor marker, or complete child ledger to distinguish an uncertain handoff. Stale evaluation-owner reconciliation, fencing, and database-backed crash/concurrency proof remain recovery gaps; age alone cannot authorize retry or cleanup. The scheduled terminal cleanup locks and rechecks each eligible `HANDED_OFF` or `CANCELED` parent and its handoff children, detaches retained audit links, then deletes only completed, unheld handoff children older than the same status-specific cutoff and eligible parents in one transaction. A newer handoff child, retained replay result, or active handoff hold blocks parent deletion; replay results and audit evidence are not age-disposed by this parent cleanup. Separately, `ScriptHandoffEventRepository.deleteExpiredRetentionEvidence` deletes completed, unheld, watermark-expired handoff children in ordered batches of at most 500 when all siblings are eligible and no replay receipt is retained. It requires an existing parent that is terminal but not `DEAD_LETTERED`; orphaned children with a missing parent are not eligible. The existing parent need not meet its status-specific age cutoff, and the method has no current scheduled caller. Automatic `DEAD_LETTERED` parent age- and row-cap deletion fails closed because the live schema cannot prove whole-bundle recovery disposition or evidence-retention eligibility. V4 now persists a monotonic failure-generation field and immutable replay request/result receipts, but the recovery aggregate, complete expected-child ledger, and recovery/rollback-diagnosis horizon remain incomplete. Repository unit proof covers the bounded child-only query, consistent parent-before-child cleanup lock order, and fail-closed dead-letter paths; PostgreSQL retention cases exist but require Docker/Testcontainers and remain unexecuted in the current local environment. +The composed migration order remains V2 → V3 → V4. V3 creates `next_eligible_at` and its eligibility index; V4 retains both, relaxes the column to nullable, and adds failure-generation, replay-receipt, and retention evidence without a second column or index creation. The V4 shape contract checks this combined order, while the Flyway/PostgreSQL integration case checks the resulting schema when Docker is available; local executed database proof remains pending. + The `xmax = 0` insert discriminator used by the `ScriptWorkItem` and `ScriptEventAudit` repositories has PostgreSQL integration cases for INSERT-versus-conflict-update behavior in [AutomationClaimAndRetentionRepositoryIntegrationTest](../../../services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java); those Testcontainers cases compile but are skipped locally without Docker, so executed PostgreSQL proof remains outstanding. Bootstrap/dev `UpdateScript` now uses one PostgreSQL upsert for the durable `(tenantId, version, name)` definition identity enforced by the `scripts` table/RPC, distinct from the runtime patch/script identity `(tenantId, scriptPatchVersion, scriptId)`, preserving explicit-ID CAS for internal callers and replacing bindings within the service transaction. Focused repository unit proof executes; PostgreSQL cases for one-statement persistence, concurrent definition identity, complete binding replacement, and rollback are compiled but skipped without Docker. They are not executed database proof. This bounded upload path does not satisfy the separate production publication/readiness contract. @@ -63,7 +69,7 @@ These links add decision provenance only; they do not upgrade Automation impleme ## Final Reviewed-Import Status and Proof Gaps -- `AS-1.6`: [ADR 0166](../../architecture/decisions/adr-0166-attributable-script-breakers-and-tenant-first-fairness.md) is applied as decision provenance. Current quota and tier budgets are partial foundations; breaker authority, audited reset, general priority scheduling, priority-sensitive queue-delay/starvation emission, the ADR 0166 cluster-ceiling capability (distinct from the current dry-run `SCRIPT_TEST_MAX_CLUSTER_CONCURRENCY` capacity), concurrency policy, and focused fairness proof remain gaps. +- `AS-1.6`: [ADR 0166](../../architecture/decisions/adr-0166-attributable-script-breakers-and-tenant-first-fairness.md) is applied as decision provenance. Current quota and tier budgets are partial foundations; breaker authority, audited reset, general priority scheduling, priority-sensitive queue-delay/starvation emission, the ADR 0166 cluster-ceiling capability (distinct from the current dry-run `SCRIPT_TEST_MAX_CLUSTER_CONCURRENCY` capacity), concurrency policy, and focused fairness proof remain gaps. The live dry-run capacity counter uses the separate Cache/Rate-Limit `automation:test:capacity:*` family; its reset/ACL inventory remains part of the incomplete Redis-role convergence. - `AS-1.1`: [ADR 0172](../../architecture/decisions/adr-0172-parent-event-and-frozen-handler-execution-identity.md) supersedes ADR 0001. Current ingress, storage, retry, scheduler, audit, and handoff convergence and focused proof remain incomplete. - `AS-1.5`: Human review retained [ADR 0002](../../architecture/decisions/adr-0002-automation-handoff-reliability-and-success-semantics.md). Current duplicate recovery and child-dispatch/readback proof remain incomplete, so this capability stays partial. - `AS-1.6`: [ADR 0173](../../architecture/decisions/adr-0173-registry-classified-reload-admission-policy.md) supersedes ADR 0003. Current implementation lacks the registry-classified `RELOADING`/`retryAfterMs` behavior, null-safe policy identity and atomic first-claim convergence, and `REJECT_VISIBLE`/`DURABLE_RETRY`/`SKIP_RECONCILE` producer behavior; existing readiness/plugin/admission tests do not prove the transient-denial retry lifecycle. These are implementation and proof gaps; ADR 0173 owns the normative reload policy semantics. @@ -118,6 +124,7 @@ Queued player commands persist `targetEntityId`, `regionId`, `regionEpoch`, and Matched handlers materialize durable `script_work_items` with event, handler, source, plugin, routing, scope, quota, and admission provenance. Ordinary work can be claimed through the explicit `PENDING_EVALUATION` to `EVALUATING` transition, evaluated from persisted script definitions, canceled durably for patch/plugin rollback or drain, and dead-lettered/replayed under compatibility gates. Tenant-readiness `onLoad` follows readiness-owner terminalization and generic dead-letter replay rejects it with `onload_not_replayable`; stale readiness work remains unreclaimed. Handler-scoped `script_event_audit` rows remain distinct from ingress audit and record cancellation and terminal outcomes. Current status: `VersionServiceImpl.publishScriptPatchVersion` in Game Design calls `AutomationScriptingClient.notifyScriptVersionUpdate`, which sends `NotifyScriptVersionUpdate` with an empty `affectedScripts` list. Automation's `ScriptVersionServiceImpl.notifyUpdate` returns before creating readiness state and skips the conditional `script-patch-readiness` Temporal tracking hook, so normal script-patch publication currently establishes neither a readiness candidate nor a workflow. Focused unit coverage proves the direct non-empty notification delegation/hook path and separately proves that an empty list skips that hook; it does not prove end-to-end readiness for normal publication. The non-empty path now rejects a missing or duplicate requested definition before readiness admission, but still lacks an immutable expected-handler manifest, swallows notification/response failures, and can reuse/latest-select across changed base or release identities; these gaps remain. Target ownership and the expected-handler/terminal-outcome contract are canonical in [ADR 0115](../../architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md). +The readiness refresh path still needs explicit recovery for activity retry exhaustion so an `ONLOAD_RUNNING` projection cannot remain stranded; mixed live/dry-run proof must also ensure dry-run `onLoad` work cannot advance the live readiness projection. These remain target implementation and proof gaps. The readiness correction now stores a nullable canonical script-set manifest and nullable `readiness_generation` in V2 so retained V1 projections remain readable but cannot be replayed without their original evidence. New identities receive a tenant-local generation under the readiness advisory lock; this is only the current-projection fence and does not provide the source accepted-publication sequence required by [ADR 0115](../../architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md). Retries compare the exact sorted script set, and legacy rows with no manifest or generation fail closed. The current-generation check, `onLoad` admission, schedule refresh, and pinned schedule reconciliation now run under one PostgreSQL transaction and shared tenant lock. A durable database progress bit is written in that transaction. A `READY` retry repairs schedule state without re-admitting `onLoad`; process-local registry rebuilding runs after that commit under a fresh lock and current-generation check. This closes the local check-then-effect race for a newer generation that is already accepted, but the notification contract still cannot distinguish a delayed older source publication from a newer one; source publication ordering, complete producer manifest, and base/request binding remain open. The partial unique index still rejects retained duplicate active rows rather than rewriting them. Focused unit proof covers changed-set rejection, newer-generation fencing, downstream failure, and `READY` retry behavior. PostgreSQL concurrency and rollback scenarios were not run by this bounded validation; this slice does not change Temporal workflow integration, empty-notification handling, source publication ordering, or readiness recovery. @@ -139,6 +146,8 @@ Game Session advances durable `lastCommittedTickId` after successful tick cycles Runtime-scope changes fence tick and wall-clock due points before work is minted. Stale due points are dropped with `runtime_scope_changed`, the `automation_script_timer_runtime_fence_dropped_total` metric, and old-scope audit identity rather than being re-emitted under a new region epoch. Emitted and skipped rows retain the current routing bundle. Timer audit reads expose due-point identity, plugin provenance, routing, and persisted-versus-skipped outcomes. The ownership model is explicitly best effort and does not imply stronger timer guarantees; richer scheduler dashboards and a later leader-checkpoint substrate are outside this first model. +Current scheduler residuals remain beyond the bounded substrate above: ordinary runtime observation/reconciliation can reseed an existing millisecond `nextDueAt` after a fired one-shot was cleared, and the duplicate-work path then leaves the overdue point stuck or rediscoverable. Timer candidate and work-item uniqueness also omit `targetScopeType`/`targetScopeId`, so distinct non-entity bindings can collide. The current timer metric producer uses raw `eventType`/optional `reason` labels and emits an undefined fired family rather than the bounded catalog; these are implementation drifts from the [scheduler due-state contract](../../architecture/system-architecture-scripting-scheduler-and-timers.md#target-state-design), [scheduler identity contract](../../architecture/system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields), and [Normative Table 4](../../architecture/system-architecture-scripting-normative-contract-tables.md#table-4-metrics-label-matrix). Focused proof for re-observation preservation, duplicate/cross-binding exclusion, and canonical metric schemas remains absent. + Tick-aligned materialization derives the next future `nextDueTickId`. Scheduler materialization and plugin activation preflight ignore enabled plugin rows whose persisted observed runtime scope differs from current Game Session ownership, with exact `runtimeRegionId` and `runtimeRegionEpoch` checks; scoped plugin-policy convergence uses the same fence. ### Execution Budgets, Quotas, and Isolation @@ -164,13 +173,15 @@ The evaluator's `recordOutcome` producer now conforms to [normative Table 4](../ The queue status below is an implementation description, not a recovery authorization: current reset/rebuild/resume is unavailable and must fail closed for every status mix because no atomic PENDING-only/CAS gate exists. The target owner-reconciled workflow remains target-only. -Automation never writes Game Session tick keys directly. The live queue uses instance-aware `automation:queue:{tenantInstanceTag}:*` pointers containing a documented outbox-pointer envelope (`schemaVersion`, `outboxWorkItemId`, and bounded identity metadata); the retired `automation:tick:*` staging path is not part of the live design. Quota counters use `automation:quota::`. Queue pointers are derived coordination indexes, not work truth: Redis drain deduplicates by `outboxWorkItemId`. The callable `rebuildPendingWorkItemIndex` selects only `PENDING_EVALUATION` and has no stale, owner, or compare-and-set gate, so current queue reset/resume is unavailable and must fail closed; no live scheduled rebuild invokes it, and a non-atomic status preflight cannot authorize the safe PENDING-only path. Bounded duplicate-pointer recovery remains the owner-controlled gap defined in the [scripting runtime rebuild contract](../../architecture/system-architecture-scripting-runtime-execution.md#current-queue-rebuild-concurrency-gap). Health inspection reports `automation_queue_orphaned_entries_total` and `automation_queue_oldest_entry_age_seconds`, and the executor drains pointers for discovery before claiming PostgreSQL work, falling back to durable scanning if Redis discovery fails. +Automation never writes Game Session tick keys directly. The live queue uses instance-aware `automation:queue:{tenantInstanceTag}:*` pointers containing a documented outbox-pointer envelope (`schemaVersion`, `outboxWorkItemId`, and bounded identity metadata); the retired `automation:tick:*` staging path is not part of the live design. Quota counters use `automation:quota::`. Queue pointers are derived coordination indexes, not work truth: Redis drain deduplicates by `outboxWorkItemId` and removes pointers with atomic `LPOP`, leaving unconsumed suffixes available when a pointer budget is reached. The callable `rebuildPendingWorkItemIndex` selects only `PENDING_EVALUATION` rows, but has no owner or compare-and-set gate, so current queue reset/resume is unavailable and must fail closed; no live scheduled rebuild invokes it, and a non-atomic status preflight cannot authorize the safe PENDING-only path or establish a safe disposition for `EVALUATING` rows. Bounded duplicate-pointer recovery remains the owner-controlled gap defined in the [scripting runtime rebuild contract](../../architecture/system-architecture-scripting-runtime-execution.md#current-queue-rebuild-concurrency-gap). Health inspection reports `automation_queue_orphaned_entries_total` and `automation_queue_oldest_entry_age_seconds`, and the executor drains pointers for discovery before claiming PostgreSQL work, falling back to durable scanning if Redis discovery fails. + +Current enqueue/rebuild is RPUSH-only (with no target pointer TTL or maximum length), and `tenantInstanceTag` still concatenates raw IDs, so retention, memory-pressure, and collision-safe opaque encoding remain unproved. Canonical queue and Redis mechanics are owned by [Scripting Runtime Execution](../../architecture/system-architecture-scripting-runtime-execution.md) and [Redis](../../architecture/system-architecture-redis.md); this tracker records the current implementation gaps. -Game Session retains a lower-level idempotent `EnqueueAutomationCommandIfAbsent` helper that persists automation dispatch/work-item correlation before tick staging. Authenticated receiver-admission status is recorded in the [Game Session receiver candidate status](#game-session-receiver-candidate) and [Game Session API implementation status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status), so helper tests are not live receiver-admission proof. Durable tick staging/replay and final tuple recheck remain implemented. Numeric gameplay `targetEntityId` is captured as `characterId`; Automation assigns a per-command `automationDispatchId` and preserves the routing bundle across current local-helper and durable remote-follow-up paths. The live enqueue proto still omits Trigger Identity, `commandOrdinal`, immutable `lane`, and `cost_class`; complete dispatch-plus-ordinal handoff identity, lane/cost conflict and digest checks, readback, retry/recovery preservation, and end-to-end proof remain gaps. The canonical handoff identity is defined in [Scripting & Automation: Cross-Service Contracts, section 2](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary), and tick lane semantics remain owned by [Tick Concepts & Invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md). +Game Session retains a lower-level idempotent `EnqueueAutomationCommandIfAbsent` helper that persists automation dispatch/work-item correlation on the gameplay command ledger before tick staging. The authenticated receiver RPC remains fail-closed before live mutation because its Automation admission-epoch receiver fence is absent; lower-level helper proofs do not establish live receiver admission. See the [Game Session receiver candidate status](#game-session-receiver-candidate) and [Game Session API implementation status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status). The separate durable tick staging/replay and final tuple recheck remain implemented and do not establish that the receiver admitted a request. Numeric gameplay `targetEntityId` is captured as `characterId` so durable execution can resolve an active session without a caller-owned `sessionId`. Automation assigns a per-command `automationDispatchId`, preserves the full routing bundle, and retains helper paths for local admission or durable remote follow-up to a different target runtime scope. Before re-enqueuing an existing `ACCEPTED` but unstaged Automation command, the lower-level admission helper revalidates the request's captured region identity and epoch against current runtime ownership and rejects unavailable, paused, or advanced ownership without mutation; already-materialized or terminal exact retries retain stored-result readback behavior. Once receiver admission is available, lane assignment follows the canonical [Tick Concepts & Invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md); this tracker records no separate lane rule. The current `scheduleFollowup` terminal-timeout/late-result path can reopen an existing terminal coordinator/follow-up pair; this remains the implementation/proof gap recorded in Game Session runtime/data. The live Game Session enqueue proto/storage remains narrower than the target automation handoff contract: it does not yet carry full Trigger Identity, `commandOrdinal`, immutable `lane`, or `cost_class`, so complete child identity, lane/cost conflict and digest checks, deduplication, readback, retry, recovery preservation, and enforcement remain unimplemented or unproved. Canonical handoff mechanics are owned by [ADR 0063](../../architecture/decisions/adr-0063-durable-per-dispatch-script-handoff.md), [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), and [Scripting Contracts](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary). This tracker records the local actor-path consequence and current gap. The target remote-follow-up contract is owned by [Scripting & Automation: Cross-Service Contracts](../../architecture/system-architecture-scripting-contracts.md#3-version-fencing-rollback-safety). Current `ScriptHandoffEvent` persistence and readback now carry the source `scriptPinEpoch`, but they do not yet bind the source tuple to the target tuple or prove downstream target admission against that binding. The legacy target-side `trigger_script_event` path is therefore deterministically disabled until the complete source/target tuple-plus-owner binding exists: missing, malformed, or mismatched tuple evidence is a terminal fail-closed outcome, while unavailable authority remains non-admitted and retryable. Same-instance cross-region work and semantic target `UNPINNED` handling remain subject to that owner contract. -For plugin-originated remote follow-ups, the exact `(pluginId, pluginVersionId, bindingId)` plus captured Automation-owned `(pluginActivationEpoch, lifecycleRevision)` and fresh lifecycle/publication/policy evidence remain independent fences across Automation persistence/handoff and Game Session final execution, separate from Command-Handoff child identity and dedupe. Unavailable, displaced, disabled, revoked, activation-epoch-mismatched, or lifecycle-revision-mismatched evidence fails closed; current plugin-originated follow-up persistence and proof remain partial. +Automation's current handoff does not yet carry or prove complete command-level mapping or deduplication. Command-plan ordering, `planOrdinal`, and root allocation are pending proposal-only requirements in [ADR 0183](../../architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md), not accepted target/proof gaps. The bounded evaluator supports command-specific `targetEntityId`, structured `commandAlias` plus templated `arguments`, `when`/`unless` conditions, and multi-target `targetEntityIds[]` fan-out with stable command ordinals. **Target state:** durable handoff history is per command and preserves rendered command text, script/plugin/source/dispatch identity, captured plugin `(pluginActivationEpoch, lifecycleRevision)` when applicable, target scope, remote coordinator/follow-up ids, and later Game Session gameplay execution/outcome plus remote-state tail. Target `ListScriptHandoffEvents` directly filters by remote scope, remote ids, origin identity, command id, target entity, routing bundle, and source/state instead of reconstructing history from payloads; its exhaustive plugin-backed output retains the captured lifecycle revision beside the activation epoch. The current handoff storage/proto remains narrower and does not yet prove this target projection. @@ -194,11 +205,14 @@ Game Session pin reads remain distinct: `GetPinnedScriptPatchVersion` reports pi ## Active Gaps +- `AS-1.4` scheduler ordering is current implementation drift: `ScriptScheduleInstanceServiceImpl` sorts candidates by clock lane first, then that lane's due point (`dueTickId` for tick candidates or epoch-millisecond `dueAt` for wall-clock candidates), then `priorityTag`, and finally schedule key, with round-robin grouping applied only after that sort. Lane/due-point order can therefore outrank priority; due-point comparison is lane-local and does not compare the distinct clock domains. The target ordering and fairness contract is owned by the [scheduler and timer lifecycle](../../architecture/system-architecture-scripting-scheduler-and-timers.md#catch-up-truncation-must-use-one-stable-fairness-algorithm). No scheduler algorithm change is claimed by this tracker. +- The live clock-lane key is `wallClock ? 1 : 0` (tick candidates precede wall-clock candidates); the recorded drift is the lane and due-point precedence over priority, not a claim that wall-clock candidates always run first. - The evaluator is intentionally bounded to persisted script definitions, structured command emission, simple conditions, and target fan-out. Richer graph/runtime evaluation, compiled artifacts, and a broader sandbox execution seam are not implemented and require a separate runtime slice. - Script-driven generation and richer procedural population are not established gameplay slices; the current runtime does not provide the broader procedural-population flow described by the target architecture. - The first scheduler ownership model is complete, but richer scheduler dashboards and a later explicit leader-checkpoint substrate are not part of it. TICK-01 lane declaration, actor-versus-passive selection, cost-class enforcement, and focused proof remain unimplemented; any future timer, retry, remote, or script-generated source must declare its lane and cost class and use the existing selected-work, region-fence, routing, quota, and durable-result contracts. - The accepted [ADR 0072](../../architecture/decisions/adr-0072-class-specific-timer-durability-and-recovery.md) timer classes, durable resume-window identity, and `SKIP_MISSED`/`COALESCE_ONE` outcomes do not promote the current best-effort scheduler to complete recovery; durable correctness-bearing timer intent and focused recovery proof remain gaps. - [ADR 0063](../../architecture/decisions/adr-0063-durable-per-dispatch-script-handoff.md) and [ADR 0064](../../architecture/decisions/adr-0064-stage-qualified-script-outcomes.md) require one durable child dispatch per emitted command and separate ingress, handler, and command outcome authorities. Current handoff paths remain bounded/partial where downstream execution-disposition readback and stage-qualified proof are absent. +- The accepted ADR 0069 implementation and proof gap covers effect identity, replay, and terminal outcomes. Automation-to-Game-Session handoff mapping and deduplication remain implementation gaps under [Scripting Contracts](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary); command-plan/root allocation details remain proposal-only in [ADR 0183](../../architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). The [Game Session tracker](./game-session-runtime-and-tick-coordination.md) records related implementation and proof status. - [ADR 0075](../../architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md), [ADR 0076](../../architecture/decisions/adr-0076-failure-class-specific-durable-tick-retries.md), and [ADR 0078](../../architecture/decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md) are target contracts only: generated-chain budgets, class-specific durable retry owners, and adopter-side digest-conflict guards remain unimplemented or unproved in this runtime. - Additional publish-adjacent or script-patch rollout Temporalization is not implemented by this tracker. It is justified only by a concrete long-lived workflow need; surviving short synchronous saga seams remain explicitly scoped for the later boundary cleanup. - Custom event families and future gameplay lifecycle producers do not yet exist as additional implementation families. They must extend the manifest-backed ingress and payload contract rather than create local semantics. diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index 68772ed81e..deabb15fca 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -20,12 +20,14 @@ Adjudicated current recovery gap: the live queue-to-pending transition can leave Game Session remains the pin and rollout-history owner. Current implementation/proof persists the pin epoch, exposes the owner tuple on pinned-version and convergence reads, and commits pin/rollback through a durable request digest/result ledger with owner-row locking, expected-current-pin CAS, deterministic conflict/failure results, and exact previous/resulting tuple readback. Instance-bound Automation ingress, work-item, schedule/timer, and replay paths carry and validate positive `scriptPinEpoch`; retained lower-level Game Session Automation admission and duplicate-replay helpers compare the complete owner tuple, while the authenticated receiving APIs remain gated as recorded in the [Game Session API implementation status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status). Durable tick staging/replay and final-effect fencing enforce the tuple for work that reaches those boundaries. Remaining gaps include commit-time proof that external Game Design publication and Automation readiness remain valid through the local commit (the current protocol has no immutable preparation attestation or cross-owner CAS), complete history readback, source/target remote tuple binding, complete command identity, and remote final-effect fencing/proof. Automation readiness and observed-pin projections remain non-authoritative. Canonical rollout semantics and the remaining cross-service proof boundary are linked from [Scripting & Automation: Rollout and Rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md#pin-compare-and-set-preconditions) and the [canonical runtime-execution owner](../../architecture/system-architecture-scripting-runtime-execution.md#normative-target-contract). -The retained lower-level local admission helper implements the exact `(scriptPatchVersion, scriptPinEpoch, scriptPinControlPlaneRequestId)` tuple for instance-scoped Automation commands. It compares the tuple with the locked current `GameInstance` before fresh admission or duplicate replay, commits durable `gameplay_command` admission before Redis materialization, locks and rechecks the tuple while sealing fresh or replayed tick work, retains the tuple in the sealed work manifest, and compares it again immediately before final gameplay effects. The live `EnqueueAutomationCommandIfAbsent` receiving API currently rejects before command or queue mutation, so these helper checks are not live end-to-end receiver admission proof; see the [Game Session API implementation status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status). Non-script player commands remain unchanged. Remote Automation follow-ups retain their separate legacy source/target path; this slice does not widen it. The combined three-service `check -PfullCheck` completed successfully. Its recorded test results were Automation 713 unit tests executed and 20 integration tests skipped; the current Game Session exact-head check records 1,591 unit tests total (1,574 executed and 17 skipped), 125 integration tests total (18 executed and 107 skipped), and 38 cross-service tests total (1 executed and 37 skipped); and Game Design 132 unit tests executed with 9 integration tests skipped. The focused exact-pin and forward-migration tests were also forced to rerun successfully. PostgreSQL/Testcontainers-backed migration and integration cases that remain skipped are not local runtime proof. +The retained lower-level local admission helper implements the exact `(scriptPatchVersion, scriptPinEpoch, scriptPinControlPlaneRequestId)` tuple for instance-scoped Automation commands. It compares the tuple with the locked current `GameInstance` before fresh admission or duplicate replay, commits durable `gameplay_command` admission before Redis materialization, locks and rechecks the tuple while sealing fresh or replayed tick work, retains the tuple in the sealed work manifest, and compares it again immediately before final gameplay effects. Before re-enqueuing an existing `ACCEPTED` but unstaged Automation command, this lower-level helper also revalidates the request's captured region identity and epoch against current runtime ownership and rejects unavailable, paused, or advanced ownership without mutation; already-materialized or terminal exact retries retain stored-result readback behavior. The live `EnqueueAutomationCommandIfAbsent` receiving API currently rejects before command or queue mutation, so these helper checks are not live end-to-end receiver admission proof; see the [Game Session API implementation status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status). Non-script player commands remain unchanged. Remote Automation follow-ups retain their separate legacy source/target path; this slice does not widen it. The combined three-service `check -PfullCheck` completed successfully. Its recorded test results were Automation 713 unit tests executed and 20 integration tests skipped; the current Game Session exact-head check records 1,591 unit tests total (1,574 executed and 17 skipped), 125 integration tests total (18 executed and 107 skipped), and 38 cross-service tests total (1 executed and 37 skipped); and Game Design 132 unit tests executed with 9 integration tests skipped. The focused exact-pin and forward-migration tests were also forced to rerun successfully. PostgreSQL/Testcontainers-backed migration and integration cases that remain skipped are not local runtime proof. Target rollback requires the scoped Automation admission barrier to pause new script admission before the pin/epoch commit and remain active through exact-artifact and schedule reconciliation/convergence; ordinary gameplay ticks continue on the routine fenced path. A full gameplay pause is valid only for a declared unfenced effect family, migration, or compatibility transition that cannot enforce the final `scriptPinEpoch` fence. Schedule reconciliation follows [ADR 0110](../../architecture/decisions/adr-0110-explicit-opt-in-schedule-continuity-across-script-transitions.md)'s explicit opt-in continuity policy: cancel-and-recreate is the default, only explicitly compatible opted-in intervals preserve continuity, and one-shot timers remain outside that continuity rule. This script-specific boundary is distinct from the runtime `regionEpoch`, which fences broader region ownership and tick execution. Implementation and proof remain partial: current pause/purge seams and region fences do not prove that target. See [ADR 0103](../../architecture/decisions/adr-0103-single-authority-script-pins-with-exact-version-execution.md), [ADR 0106](../../architecture/decisions/adr-0106-epoch-fenced-script-rollback-without-routine-gameplay-pause.md), [ADR 0109](../../architecture/decisions/adr-0109-game-session-owned-script-rollout-history.md), and [ADR 0110](../../architecture/decisions/adr-0110-explicit-opt-in-schedule-continuity-across-script-transitions.md) for target boundaries; proof remains deferred to the focused Game Session/Automation transition suites. Distinct-instance remote follow-up has retained lower-level coordinator/follow-up persistence and handoff helpers. The authenticated `ScheduleRemoteFollowup` receiving API currently fails closed before coordinator, follow-up, or queue mutation, so those helpers are not a live receiving path; see the [Game Session API implementation status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status). Current `ScriptHandoffEvent` persistence and the handoff wire retain the source `scriptPinEpoch` and source owner-request evidence, but do not yet retain or enforce the complete source/target pin-tuple binding. The remaining target implementation/proof gap is source revalidation, target admission under a frozen target tuple, complete source/target fencing and retry/replay proof, and plugin `pluginActivationEpoch`/owner `lifecycleRevision` propagation where applicable. The legacy target-side `trigger_script_event` path is deterministically disabled until that durable source/target binding exists; it must not derive a Trigger ingress tuple from mutable target state or generic patch metadata. Game Session's local plugin projection, lexicographic lifecycle-fence CAS, durable lifecycle install acknowledgement, and exact final revision fence are also not implemented or proved. Game Session owns the remote coordinator/follow-up records and its local plugin projection; Automation owns authoritative plugin activation/lifecycle state and the owner `pluginActivationEpoch`/`lifecycleRevision` fence evidence. The tuple, fence, durable install acknowledgement, and exact final revision requirements remain cross-service target obligations; see the [canonical scripting contract](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary), [ADR 0119](../../architecture/decisions/adr-0119-epoch-fenced-per-instance-plugin-activation.md), and [normative remote-follow-up tuple-binding contract](../../architecture/system-architecture-scripting-normative-contract-tables.md#remote-follow-up-tuple-binding-normative) for target semantics. +Current command/effect and Automation handoff paths use narrower identities and do not yet implement the accepted effect-identity, replay, and terminal-outcome contracts. Deterministic command-plan ordering, `planOrdinal`, and root allocation remain pending proposal-only requirements in [ADR 0183](../../architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). See [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md) for accepted effect semantics and [Scripting Contracts](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary) for the handoff boundary. + ## Packet 4 Status and Proof Gaps - `GR-1.1` / `GR-1.4`: [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) adds the runtime local consequence that admission and reconnects must use the active playable-state namespace and `playableStateScope`/instance fence. Existing pointer, handoff, drain, and route-swap gaps remain; current Game Session evidence does not prove replacement-state migration or cleanup. Concretely, the `game_instances` schema/entity/repository and `PreparedVersionUpgrade` persistence have no `playableStateNamespaceId` or `playableStateScope`, and prepared cutover records version/remap and target-pointer facts only; this remains a partial implementation gap rather than evidence that current cutover carries stable namespace/scope identity. @@ -40,7 +42,7 @@ These links add decision provenance only; they do not upgrade any Game Session i | `GR-1.1` Session front-end and execution routing | `partial`: WebSocket handshake/session bootstrap, protocol parsing, normalized routing, takeover-safe transport registration, and ordinary-gameplay local/remote admission are live; authenticated Automation receiver admission remains gated before mutation (see [Game Session API implementation status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status)); lease-owner forwarding for independently partitioned regions is not | `proven`: [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java), [GameSessionWebSocketHandshakeInterceptorTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java), [SessionRoutingNormalizationServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java), and [GameSessionGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java) cover the shipped front-door and routing seams | [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [reconnection](../../architecture/system-architecture-reconnection.md) | [WebSocket handler](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [handshake interceptor](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [session routing normalization](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [Game Session gRPC](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java) | [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [GameSessionWebSocketHandshakeInterceptorTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [SessionRoutingNormalizationServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java) | `GR-1.3` ownership/fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); gateway/TCP edge behavior remains a secondary handoff | The API contract requires front-end-to-lease-owner forwarding to be fenced, with retry/ambiguity handling. The current owner boundary is game-instance scoped and does not implement that forwarding or true region partitioning; no new design decision is recorded. | | `GR-1.2` Tick timelines, action fairness, queues, and scheduling | `partial`: current bounded scheduler, per-entity queue selection, gameplay-command ordering (including timer/automation-origin work only after materialization as gameplay commands with retained provenance/order fields), durable batch/effect staging, pressure signals, and sealed selected-work manifests for gameplay commands are live; directly selected timer/retry/remote-follow-up source-claim manifests remain target-state; it still uses universal work-item selection and does not implement the accepted separate actor-action/passive-effect lane classification, phase budgets, or lane-preserving retry contract; the complete in-place command-status lifecycle accepted by [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) is not | `drift-found`: the shipped scheduler and queue/effect seams have focused proof, but lane/source classification, separate lane budgets, and passive/inbound non-actor-turn behavior are not proved; the accepted command-status lifecycle in [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) remains unimplemented and is not fully proved | [ticks](../../architecture/system-architecture-ticks.md); [tick concepts and invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md); [tick execution flows](../../architecture/system-architecture-tick-execution-flows.md); [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) | [TickScheduler](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickScheduler.java); [TickStagingService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickStagingService.java); [TickBatchExecutionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java); [TickServiceImpl](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickServiceImpl.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game-session-service.proto](../../../protos/game-session/v1/game_session_service.proto) | [TickSchedulerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickSchedulerTest.java); [TickStagingServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickStagingServiceTest.java); [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java); [TickServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickServiceImplTest.java) | `AS-1.4` timer progress and `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); `GR-1.3` ownership in this tracker | Add the [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) acknowledgement dimensions, authoritative attempt history, bound-tick summary, convergence contract, persistence, and focused proof to `GetGameplayCommandStatus`; separately add TICK-01 source classification, lane/cost metadata, phase budgets, lane-preserving retry identity, and focused actor/passive scheduling proof; adaptive timing and true region-wide scheduling remain separate gaps. | | `GR-1.3` Region leases, fencing, and executor coordination | `partial`: durable runtime ownership, epoch/fence snapshots, pause/resume, stale-owner rejection/requeue, and current runtime-progress publication are live at the game-instance boundary; the TICK-02 Redis lease plus durable executor-fence install/revalidate handshake and true region takeover boundary remain target-state | `proven`: current tests cover fence/scope admission, tick progress, stale execution, and operator reads, but do not prove the TICK-02 lease/fence handshake or takeover reconciliation | [tick concepts and invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md) | [RuntimeRegionStatus](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/RuntimeRegionStatus.java); [runtime ownership read](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java); [TickRuntimeProgressService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickRuntimeProgressService.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [TickServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickServiceImplTest.java); [TickRuntimeProgressServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickRuntimeProgressServiceTest.java); [AutomationGameplayCommandAdmissionSupportTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java) (lower-level helper proof only, not live end-to-end receiver proof); [GameSessionControlPlaneGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | `GR-1.1` front-end routing in this tracker; `AS-1.1` ingress and `AS-1.4` timers in [Automation runtime tracker](./automation-and-scheduler-runtime.md); Redis lease coordination is the shared infrastructure handoff | The current durable owner row and lease boundary are game-instance scoped. Add proof for Redis lease acquisition/loss before and after durable fence installation, same-token revalidation, stale-fence rejection, and takeover reconciliation; true region-partitioned leases, cluster scheduling, and front-end forwarding remain unimplemented. | -| `GR-1.4` Runtime recovery, replay, and reconciliation | `partial`: durable command/batch/effect recovery, manifest-digest repair, stale-fence requeue, fenced re-drive of accepted-but-unmaterialized commands, remote result reconciliation, and bounded restart/reset paths are live; queue/pending loss before durable batch materialization and recovery of `STAGED` batches/effects after Redis loss remain unimplemented; lane-preserving replay and the complete TICK-02 takeover reconciliation remain target-state follow-through | `unverified`: focused unit recovery tests execute exact accepted-row re-drive, serializer-free identity/payload-idempotent queue/pending behavior, and retryability on Redis/eligibility races; the real-Redis serializer integration test is present but skipped when Docker is unavailable, so production Lua execution and broader proof for lane/cost preservation across recovery, Redis-loss recovery of `STAGED` state, or the Redis lease plus durable-fence takeover handshake remain deferred | [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md); [tick execution flows](../../architecture/system-architecture-tick-execution-flows.md); [reconnection](../../architecture/system-architecture-reconnection.md); [Game Session operations](../../architecture/microservices/game-session-service/operations.md); [ADR 0013](../../architecture/decisions/adr-0013-bounded-invisible-non-edge-restart-recovery.md) | [DatabaseGameplayCommandRecoveryService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryService.java); [GameplayCommandRepository](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [TickQueueControlService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickQueueControlService.java); [TickStagingService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickStagingService.java); [TickBatchExecutionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java); [RemoteFollowupRuntimeServiceImpl](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImpl.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [DatabaseGameplayCommandRecoveryServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryServiceTest.java); [TickQueueControlServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java); [TickQueueControlServiceRedisIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceRedisIntegrationTest.java); [AutomationGameplayCommandAdmissionSupportTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java) (lower-level helper proof only, not live end-to-end receiver proof); [TickStagingServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickStagingServiceTest.java); [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java); [RemoteFollowupRuntimeServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImplTest.java); [RemoteFollowupDrainServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupDrainServiceImplTest.java); [DefaultDurableRemoteFollowupExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableRemoteFollowupExecutionServiceTest.java) | `GR-1.2` queue/replay and `GR-1.3` fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); downstream domain services own effect application/reconciliation | Downstream effect ledgers and replay/idempotency consumers beyond the migrated command families, full non-edge restart recovery, broader payload/work-source recovery, and a durable replay/reconciliation controller for Redis-loss `STAGED` command/batch state remain; add focused proof for lane/cost preservation, current epoch/fence validation, old-fence takeover reconciliation, and broader payload/work-source recovery; ADR 0013 is accepted and owns the bounded invisible non-edge restart target. | +| `GR-1.4` Runtime recovery, replay, and reconciliation | `partial`: durable command/batch/effect recovery, manifest-digest repair, stale-fence requeue, remote result reconciliation, and bounded restart/reset paths are live; startup recovery re-enqueues old accepted-but-unstaged commands under their existing identity and leaves them `ACCEPTED` when Redis, identity, eligibility, or a raced transition prevents safe materialization; queue/pending loss before durable batch materialization and recovery of `STAGED` batches/effects after Redis loss remain unimplemented; lane-preserving replay and the complete TICK-02 takeover reconciliation remain target-state follow-through | `drift-found`: focused unit recovery tests cover accepted-row re-drive, unchanged retryable state on uncertainty, serializer-free identity/payload-idempotent queue/pending behavior, remote reconciliation, and retryability on Redis/eligibility races, but do not provide combined PostgreSQL/real-Redis restart proof, lane/cost preservation, Redis-loss recovery of `STAGED` state, or the Redis lease plus durable-fence takeover handshake; the real-Redis serializer integration test is present but skipped when Docker is unavailable | [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md); [tick execution flows](../../architecture/system-architecture-tick-execution-flows.md); [reconnection](../../architecture/system-architecture-reconnection.md); [Game Session operations](../../architecture/microservices/game-session-service/operations.md); [ADR 0013](../../architecture/decisions/adr-0013-bounded-invisible-non-edge-restart-recovery.md) | [DatabaseGameplayCommandRecoveryService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryService.java); [GameplayCommandRepository](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [TickQueueControlService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickQueueControlService.java); [TickStagingService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickStagingService.java); [TickBatchExecutionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java); [RemoteFollowupRuntimeServiceImpl](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImpl.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [DatabaseGameplayCommandRecoveryServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryServiceTest.java); [TickQueueControlServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java); [TickQueueControlServiceRedisIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceRedisIntegrationTest.java); [AutomationGameplayCommandAdmissionSupportTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java) (lower-level helper proof only, not live end-to-end receiver proof); [TickStagingServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickStagingServiceTest.java); [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java); [RemoteFollowupRuntimeServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImplTest.java); [RemoteFollowupDrainServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupDrainServiceImplTest.java); [DefaultDurableRemoteFollowupExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableRemoteFollowupExecutionServiceTest.java) | `GR-1.2` queue/replay and `GR-1.3` fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); downstream domain services own effect application/reconciliation | Downstream effect ledgers and replay/idempotency consumers beyond the migrated command families, full non-edge restart recovery, broader payload/work-source recovery, and a durable replay/reconciliation controller for Redis-loss `STAGED` command/batch state remain; add focused proof for lane/cost preservation, current epoch/fence validation, old-fence takeover reconciliation, and broader payload/work-source recovery; ADR 0013 is accepted and owns the bounded invisible non-edge restart target. | ### GR-1.2 Command-Status Dimensions @@ -50,7 +52,7 @@ The [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command- | --- | --- | --- | --- | | Acknowledgement (`ackLevel`) | `not implemented`: the live enqueue response exposes acceptance and `commandId`, but no canonical `ACCEPTED_VOLATILE`/`ACCEPTED_DURABLE` acknowledgement dimension is persisted or returned | `not proven`: no focused proof covers acknowledgement-level persistence or same-ID acknowledgement replay under [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) | `open`: add the durable field, status projection, ingress mapping, and focused retry/failover proof without adding a parallel status API | | Ingress (`ingressStatus`) | `partial`: the live command row uses progress values such as `ACCEPTED`, `STAGED`, `DRAINED`, and `RETRY_QUEUED` through `executionOutcome`; the canonical `RECEIVED`/`ENQUEUED`/`BOUND_TO_BATCH`/`TERMINAL` dimension is not yet separate | `partial`: current command-ingress, staging, and recovery tests prove the live progress paths, but not the canonical mapping required by [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) | `open`: persist and return `ingressStatus`, map legacy progress values, and prove reset/retry convergence | -| Execution outcome (`executionOutcome`) | `partial`: durable storage and status projection are live, including recovery outcomes, and rollback purge writes the canonical `ABANDONED` execution outcome with `NOT_APPLIED` plus a structured reason; complete canonical mapping across all terminal paths is not implemented | `partial`: [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java) and recovery tests cover current terminal updates and rollback purge scopes; complete [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) mapping across every terminal path is not yet proved | `open`: converge terminal vocabulary and prove every terminal path, including rollback purge, returns one durable outcome and reason | +| Execution outcome (`executionOutcome`) | `partial`: durable storage and status projection are live, including recovery outcomes; the current rollback-purge branch writes `ABANDONED`/`NOT_APPLIED` for an explicitly retryable command when it finds a durable prior tick-effect binding, but does not require authoritative evidence that the effect was unapplied; canonical evidence-qualified mapping across all terminal paths is not implemented | `partial`: [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java) and recovery tests cover current terminal updates and rollback purge scopes, but do not prove authoritative prior-effect outcome evidence or the complete [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) mapping | `open`: enforce evidence-qualified terminal outcomes and prove every terminal path, including rollback purge, returns one justified durable outcome and reason | | Gameplay result (`gameplayResult`) | `partial`: durable storage and status projection are live for current command and remote-result paths, but the canonical independent result vocabulary is not fully enforced across all terminal paths | `partial`: migrated effect and remote-runtime tests cover current success/failure/result propagation; a complete [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) proof for `SUCCESS`, `PARTIAL`, `FAILED`, `TIMEOUT`, and `NOT_APPLIED` is not recorded | `open`: retain this as a separate player/result-facing projection, add terminal mapping coverage, and prove it cannot be inferred solely from `executionOutcome` | ## Canonical Design Sources @@ -79,29 +81,34 @@ After ingress validation, rate and queue-target resolution, Game Session writes Current pointer-CAS status/proof: routed Automation and remote gameplay-command insertion uses one PostgreSQL `INSERT ... SELECT` guarded by exactly one total current pointer row for the tenant/game-instance target, with that sole row matching the normalized world/realm selectors, pointer version, and required nonblank playable-state scope. Missing, mismatched, or ambiguous authority fails retryably before the insert. Existing pointer updates use expected-version CAS, and pointer creation serializes on the runtime target and fails closed when another route already owns it. Focused unit and compile proof has passed for this path, but live PostgreSQL/Testcontainers concurrency proof is unavailable locally and remains required before claiming full proof. This current pointer-CAS note does not establish target stable-namespace or `realmId` completeness. -The current command lifecycle is explicit: `ACCEPTED` means durable identity exists but staging has not succeeded; `STAGED` means Redis staging succeeded; `DRAINED` means a durable tick batch consumed the staged command; `RETRY_QUEUED` means an abandoned attempt was returned for another attempt; `FAILED` means staging failed before gameplay application; and `LOST_BEFORE_STAGING` is a terminal result only when an explicit recovery or control action determines that accepted work must not be staged. Startup recovery does not assign that terminal result: it re-drives matching `ACCEPTED`/`staged_at IS NULL` rows through the fenced identity/payload-aware queue materializer, while Redis or payload ambiguity leaves the row `ACCEPTED` and retryable. Batch drain and abandonment update command rows, so status is not ingress-only. +The current command lifecycle is explicit: `ACCEPTED` means durable identity exists but staging has not succeeded; `STAGED` means Redis staging succeeded; `DRAINED` means a durable tick batch consumed the staged command; `RETRY_QUEUED` means an abandoned attempt was returned for another attempt; and `FAILED` means staging failed before gameplay application. For live startup-loss recovery, target `LOST_BEFORE_STAGING` is the terminal recovery state only for explicitly volatile/no-batch accepted work that never reached staging. Live startup recovery re-enqueues old `ACCEPTED` rows under the same command identity and leaves the row `ACCEPTED` when materialization is uncertain or fails, so durable accepted work remains retryable rather than being terminalized without evidence. Batch drain and abandonment update command rows, so status is not ingress-only. -`commandId` is carried in enqueue responses, Redis tick payloads, logs/MDC, batch manifests, effect rows, retries, and remote execution. `GetGameplayCommandStatus` is the single canonical Game Session read and currently resolves the command-id identity `(tenantId, gameInstanceId, commandId)`. The automation-handoff identity `(tenantId, gameInstanceId, regionId, regionEpoch, automationDispatchId)` is the accepted target lookup but is not implemented by the live resolver; both identities are defined by [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md), and this tracker records their current and target status below. The read exposes `enqueueSeq`, the latest selected queue-source kind/state/ordinal and due-point tuple, lifecycle and routing data, and remote correlation/result fields. Logging & Admin exposes the implemented command-id read at `GET /gameplay-commands/{tenantId}/{gameInstanceId}/{commandId}` and validates tenant and game-instance identity before trusting the response. +`commandId` is carried in enqueue responses, Redis tick payloads, logs/MDC, batch manifests, effect rows, retries, and remote execution. `GetGameplayCommandStatus` is the single canonical Game Session read and currently resolves the command-id identity `(tenantId, gameInstanceId, commandId)`. The automation status lookup/correlation key `(tenantId, gameInstanceId, regionId, regionEpoch, automationDispatchId)` is the accepted target lookup but is not implemented by the live resolver; it is not the complete Command-Handoff Identity defined by the scripting normative contract table, which additionally carries command ordinal and applicable source/target scope fields. This tracker records the status lookup keys and their current/target status below under [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md). The read exposes `enqueueSeq`, the latest selected queue-source kind/state/ordinal and due-point tuple, lifecycle and routing data, and remote correlation/result fields. Logging & Admin exposes the implemented command-id read at `GET /gameplay-commands/{tenantId}/{gameInstanceId}/{commandId}` and validates tenant and game-instance identity before trusting the response. | Status lookup identity | Implementation status | Proof status | | --- | --- | --- | | Command-id `(tenantId, gameInstanceId, commandId)` | `implemented` at the current durable ledger boundary; the canonical ADR 0016 status dimensions remain the `partial`/`not implemented` items classified above | `proven` for the current ledger read by [GameSessionControlPlaneGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java); the canonical dimensions remain only partially proved as classified above | | Automation-handoff `(tenantId, gameInstanceId, regionId, regionEpoch, automationDispatchId)` | `not implemented`: the proto carries the tuple and automation admission persists its identity, but the live status resolver still requires `command_id` and does not resolve this tuple | `not proven`: no focused `GetGameplayCommandStatus` proof establishes tuple lookup, tenant/scope validation, or status convergence through that identity | -Rollback queue purge controls cover script-patch and plugin-version scopes. Their ingress `reason` is required and non-blank. Enqueue and purge share renewable queue-mutation and tick leases; purge writes durable terminal state before post-commit Redis queue/pending cleanup, and tick staging discards stale payloads whose durable command is missing or no longer executable. The canonical [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) mapping uses `executionOutcome=LOST_BEFORE_STAGING` before durable batch binding and `executionOutcome=ABANDONED` only for an explicitly retryable command with a prior durable tick-effect binding. Both use `gameplayResult=NOT_APPLIED` and the required structured terminal-reason pair `failureCode=ROLLBACK_PURGED` plus `failureMessage=`, with `completedAt`. `GetGameplayCommandStatus` returns those durable fields. Focused unit proof covers both purge scopes, lock contention, commit-ordered cleanup, durable binding classification, and blank-reason rejection. Batch-bound work outside the explicit retry queue and already-applied work remain outside this purge path. +Rollback queue purge controls cover script-patch and plugin-version scopes. Their ingress `reason` is required and non-blank. Enqueue and purge share renewable queue-mutation and tick leases; purge writes durable terminal state before post-commit Redis queue/pending cleanup, and tick staging discards stale payloads whose durable command is missing or no longer executable. `GetGameplayCommandStatus` remains the existing status API for durable command state. Canonical purge eligibility and fencing are owned by [the queued-command purge contract](../../architecture/system-architecture-scripting-control-plane-operations.md#game-session-purge-queued-tick-commands-rollback-support); terminal status dimensions are owned by [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md). Existing focused unit proof covers both purge scopes, lock contention, commit-ordered cleanup, current durable-binding classification, and blank-reason rejection, but does not prove the authoritative outcome evidence or no-batch fence required by the target contract. + +Current purge implementation/proof is narrower than the target mapping above: `TickQueueControlService.purgeCandidate` checks only `GameplayCommandRepository.hasDurableTickEffect(commandId)` and then classifies the row. When a binding exists, `RETRY_QUEUED` is enough for the current code to write `ABANDONED`/`NOT_APPLIED`; it does not obtain authoritative evidence that the prior effect was unapplied. When no binding is found, the path also lacks one atomic owner-defined CAS proving no surviving batch, effect, or source claim. Concurrent staging, drain, or effect-claim races are therefore not excluded, and focused purge tests do not establish either target proof. The target contract remains unchanged; this is an implementation/proof gap and no runtime fix is claimed here. ### Scheduler and Queue Pressure -The scheduler has bounded fan-out: one runtime scope can have at most one pending or running tick. Overlapping pulses merge instead of accumulating debt, executor rejection is observable, and gameplay and automation/script ticks use disjoint Redis key namespaces. The scheduler records scheduled, merged, rejected, and paused-cycle counters, queue-depth signals, pressure summaries, and conservative consecutive-cycle thresholds for sustained rejection, elevated merging, and high executor queue depth. Threshold crossings produce alert counters and consecutive-cycle gauges, and canonical alert rules consume the exported gauges. +The live `TickScheduler` provides the bounded pulse-scheduling substrate and its focused proof is summarized in the canonical [Tick System and Runtime Design](../../architecture/system-architecture-ticks.md) and [tick incident runbook](../../architecture/system-architecture-tick-incident-runbook.md). Its current deduplication key is only `(tenantId, gameInstanceId)`; target region partitioning, exact active-namespace evidence, and the accepted lane/budget scheduling contract remain implementation and proof gaps. Scheduler-pressure observability and alert semantics remain owned by those canonical sources rather than duplicated in this tracker. The policy is observability-first. Pressure is an operator alert/input and does not automatically change gameplay timing. The tick incident runbook has a dedicated scheduler-pressure flow. There is no dedicated queue/lease scheduler or broader game-logic action scheduler at this boundary. ### Durable Batches, Effects, and Source Contracts -Redis queue-to-pending staging currently creates one durable `tick_batch` with `tickBatchId`, tenant/game scope, `batchSource`, status, solo-tick requirement, command count, expected effect count, selected-work manifest JSON and digest, ownership snapshot, and timestamps. Each selected gameplay command creates one durable `tick_effect` with stable `effectId`, batch and command links, effect key/type, target aggregate, status, failure code/message, and timestamps. Target aggregates narrow to the known character or entity when the command provides one instead of always using the game instance. This live manifest persistence is gameplay-command-only; timer, retry, and remote-follow-up source-claim manifests remain target-state and are not implied by the current batch fields. +Redis queue-to-pending staging currently creates one durable `tick_batch` with `tickBatchId`, tenant/game scope, `batchSource`, status, solo-tick requirement, command count, expected effect count, selected-work manifest JSON and digest, ownership snapshot, and timestamps. Each selected gameplay command creates one durable `tick_effect` with a stable same-batch `effectKey` (currently derived from `commandId`) and an `effectId` currently derived from `tickBatchId` plus that key, along with batch and command links, effect type, target aggregate, status, failure code/message, and timestamps. Target aggregates narrow to the known character or entity when the command provides one instead of always using the game instance. Current batch/manifest persistence does not yet prove exact active-namespace evidence throughout admission, replay, replacement, and fresh-playtest isolation, but namespace remains evidence rather than a tick-batch uniqueness dimension. This live manifest persistence is gameplay-command-only; timer, retry, and remote-follow-up source-claim manifests remain target-state and are not implied by the current batch fields. Batch states are `STAGED`, `DRAINED`, `APPLIED`, and `ABANDONED`. Effect states are `STAGED`, `DRAINED`, `APPLIED`, `REPLAY_NOOP`, `REJECTED`, and `ABANDONED`. Existing pending work is correlated to an older staged batch or to a bounded `PENDING_REPLAY` batch created during recovery. The current tick boundary requires durable command identity; it does not retain a no-`commandId` recovery path. +The live executor currently persists `REPLAY_NOOP` and `REJECTED` effect statuses, and can mark a batch `APPLIED` once no `DRAINED` rows remain without requiring every effect to be `APPLIED` or evidence-qualified `ABANDONED`. This is implementation drift from the accepted [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md) and [transaction effect contract](../../architecture/system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory); focused participant-set and batch-aggregation proof remains absent. Those owners define the target status and recovery mapping. + +The stale-fence path is a concrete instance of that drift: for a non-remote gameplay-command batch, `TickBatchExecutionService.executeDurableEffects` routes a stale-ownership `DRAINED` batch to `abandonStaleDrainedBatch`, which marks every remaining `DRAINED` effect `ABANDONED` and requeues its commands without domain evidence. Remote-followup batches instead route to `markRemoteFollowupBatchAbandoned` and do not requeue gameplay commands. The stale-fence handling can therefore terminalize unfinished effects without evidence that they were unapplied; an effect that started before the fence changed can be replayed and applied twice. Focused stale-fence proof remains absent; target settlement and replay authority are defined by [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md) and the [transaction effect contract](../../architecture/system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory). Legacy `TickStaging` rows with `commandId='-'` remain unresolved: the current parser and Lua path fail closed, and no authoritative drain, migration, or command-correlation proof exists for them. The sealed gameplay-command selected-work manifest is the current replay contract. It records explicit `regionId`, `enqueueSeq`/comparable source ordering, source kind/type and state, due tick/point, target and routing facts, automation dispatch/work-item identity, script/plugin provenance, and source-state metadata. `enqueueSeq` is used as `sourceOrdinal` where available instead of a transient batch slot. Durable command and remote-follow-up rows also persist their latest origin-source and queue-source tuples so status and operator reads do not need to parse manifests or payload JSON. Complete timer/retry/remote-follow-up source-claim manifests remain target-state follow-through; timer/automation-origin work appears in the current sealed manifest only after materialization as a gameplay command with its provenance and ordering fields retained. @@ -115,6 +122,7 @@ After Redis drain commit, Game Session executes `DRAINED` effects from the durab Malformed or orphaned tick queue/pending entries have no token-fenced atomic quarantine and convergent-removal implementation or proof; a separate-check `LREM` is not an authorized cleanup path. Stale drain, fresh-stage rollback, and manifest-mismatch repair requeue actual commands, advance their queue-source state deliberately, and increment `tick_requeued_action_total` by action count and durable source (`player`, `automation`, bounded `remote_followup`, or `unknown`). Requeue preserves sealed source identity, comparable ordinal, due point, and source state; mutable command-row state cannot replace the sealed ordering facts. Only the first current migrated command families consume the post-drain effect seam, while pure views remain direct reads. +The accepted effect identity, replay, and terminal-outcome rules are not yet fully persisted or proved; see [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md). Command-plan/root allocation and replay details remain proposal-only in [ADR 0183](../../architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). The [Scripting Contracts](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary) owns the separate Automation handoff boundary. ### Gameplay Mutation Consumers @@ -126,7 +134,7 @@ The item command handler records `gamesession.command.item.*` invocation and fai ### Ownership, Epochs, and Fencing -`runtime_region_status` is the current durable owner-of-record keyed by the live tenant/game boundary. It stores explicit `regionId`, `regionEpoch`, opaque `executorFence`, owner service and instance identity, paused state, `lastCommittedTickBatchId`, and backlog truth. Tick processing observes this row and refreshes owner identity from the shared runtime identity. Pause, resume, and recovery advance the durable epoch/fence timeline; the fence is an opaque generation token and is compared for equality/freshness rather than treated as a numeric sequence. +`runtime_region_status` is the current durable owner-of-record keyed by the live tenant/game boundary. It stores explicit `regionId`, `regionEpoch`, opaque `executorFence`, owner service and instance identity, paused state, `lastCommittedTickBatchId`, and backlog truth. The current schema also retains the unscoped unique index `idx_runtime_region_status_tenant_region` on `(tenant_id, region_id)` even though canonical region scope includes `gameInstanceId`; ordinary writes therefore collide when two game instances reuse a region id. This collision is implementation drift, not proof of globally unique regions. Separately, `RuntimeRegionStatusRepository.findByTenantIdAndRegionId` omits `gameInstanceId` and can select the wrong instance if legacy or constraint-bypassing data ever contains multiple matching rows. These are distinct implementation/proof gaps; duplicate-row ambiguity is not the normal consequence of the still-active unique index. Active-namespace evidence must still be exact-bound in selected work and replay, but it does not extend region-ownership identity. Tick processing observes this row and refreshes owner identity from the shared runtime identity. Pause, resume, and recovery advance the durable epoch/fence timeline; the fence is an opaque generation token and is compared for equality/freshness rather than treated as a numeric sequence. Batch creation seals the owner `regionEpoch`/`executorFence` and `regionId`. Drain/finalization rejects a changed owner, rolls pending work back to the queue, and abandons the batch with `STALE_EXECUTOR_FENCE`. Before applying `DRAINED` effects, the executor checks the same snapshot again; stale effects are not sent to domain handlers, are abandoned, and their commands are requeued for a fresh fenced batch. `lastCommittedTickBatchId` advances only on durable batch drain. @@ -136,10 +144,12 @@ The canonical `GetRuntimeOwnershipStatus` read returns owner, scope, epoch/fence Cross-region remote runtime remains partial. Current Game Session implementation has durable coordinator/follow-up persistence and handoff, bounded duplicate-window paging and per-entity de-duplication, durable result recording/replay, terminal follow-up replay, late-result handling, and selected reconciliation branches; the focused proof for those slices is recorded in [Validation and Proof](#validation-and-proof). Current storage and wire rows still lack the complete source/target projection and sealed handler-input manifest needed for exact source/target tuple binding, replay, and fencing. The remaining fair-due selection, source-claim ordering/manifests, terminal/result/reconciliation convergence, terminal-failure mirroring, missing-coordinator recovery, origin reconciliation, and plugin lifecycle-fence propagation are not implemented or proved. -Origin timeout cannot currently terminalize scheduled or claimed target follow-up work: that requires coordinator-side arbitration/CAS plus authoritative proof that the target work was unapplied; current origin reconciliation lacks that implementation and proof. +The current `remote_followup` uniqueness index on `(tenant_id, target_region_id, target_region_epoch, effect_key)` omits `target_game_instance_id`, while repository reads include it; this is implementation drift, not target behavior. Persisted row fields remain canonical even when the original command row is absent, with payload JSON as optional enrichment. Origin timeout cannot currently terminalize scheduled or claimed target follow-up work: that requires coordinator-side arbitration/CAS plus authoritative proof that the target work was unapplied; current origin reconciliation lacks that implementation and proof. The complete target contract is owned by the [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md), [tick failure contract](../../architecture/system-architecture-tick-failures-and-operations.md#cross-region-follow-up-record-contract-required), [scripting contract](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary), [ADR 0055](../../architecture/decisions/adr-0055-durable-cross-region-effects-with-static-live-topology.md), [ADR 0066](../../architecture/decisions/adr-0066-durable-asynchronous-cross-region-result-arbitration.md), [ADR 0071](../../architecture/decisions/adr-0071-durable-tick-commit-before-fenced-coordination-cleanup.md), and [ADR 0119](../../architecture/decisions/adr-0119-epoch-fenced-per-instance-plugin-activation.md). This tracker records only current implementation and proof status; target field, identity, outcome, scope, and reconciliation requirements remain in those canonical owners. +Origin reconciliation remains target-state and is not yet fully implemented or proved. The live result-inbox path has partial late-result handling, but serialized result-versus-timeout arbitration, immutable terminal/retry proof, and documented compensation ownership remain unimplemented or unproved. See the canonical owner contracts immediately above for target sequencing, terminal outcomes, and compensation; this tracker records only implementation/proof status. Current remote due/backlog gauges use durable owned-region truth. + ### Operator Readback and Facade Boundaries Game Session control-plane reads are canonical and bounded. The runtime-state read for `(tenantId, gameInstanceId)` returns the current runtime version plus the resolved launch descriptor, version/release identifiers, and script-patch pin metadata including the persisted pin `controlPlaneRequestId`; `GetGameSessionPinConvergence` provides the direct pin-convergence read used by rollback/promotion orchestration. The live `GetGameSessionPinConvergenceResponse`/adapter now also exposes `observed_script_pin_epoch` alongside `observed_pinned_script_patch_version`, `last_observed_control_plane_request_id`, `observed_at_ms`, `is_stale`, and publication, providing exact epoch readback on that surface. Pin/rollback writes now carry tagged expected-current-pin CAS input and persist a durable request digest/result ledger with exact replay and deterministic conflict/precondition outcomes; their responses include previous/resulting epochs. The target `GetScriptPinTransitionWorkflowStatus` read is not exposed and remains required for authoritative timeout-consumer workflow state, deadline, generation, and terminal-evidence readback. Its `is_stale` age signal is not the Automation projection tuple (`projection_as_of_ms`, `projection_lag_ms`, `is_projection_stale`), which the target Game Session read does not currently define. These workflow-status, remaining Automation source/target tuple-binding, and exact history/rollout proof gaps remain. `GameSessionControlPlaneGrpcService` is the transport, authorization, and application-error delegation layer; `GameSessionCommandControlPlaneService` owns gameplay-command status projection, staged automation-command admission, alias validation, remote-result/status mapping, and publication lookup helpers. The remaining remote runtime read/delegation collaborators keep the facade from carrying a second domain implementation. Current control-plane handlers preserve normal-response application mappings, while the [gRPC owner contract](../../architecture/system-architecture-grpc.md#outcome-and-transport-classification) governs typed domain results versus canonical non-OK failures. Stable mutation identities remain the reconciliation boundary; exact per-RPC classification and focused proof are implementation gaps. @@ -156,7 +166,11 @@ Game Session owns the implemented runtime feature-flag mutation and persists the ### Validation and Proof -The recorded proof covers durable command identity and sanitized persistence, restart/Redis-loss recovery at the ingress and ownership boundaries, accepted-but-never-staged convergence, single-record retry/replay updates, command correlation, batch/effect creation, manifest-digest replay repair, stale drain and post-drain fence rejection, durable `DRAINED` resumption, source-tuple preservation through timer/retry/remote claim-release transitions, fair selection in the local scheduler/queue path, and operator DTO/request mapping. Focused remote-runtime tests cover payload validation, bounded duplicate-window paging and de-duplication for due follow-up candidates, bounded durable result recording/replay, already-terminal follow-up replay, late-result handling, and selected reconciliation branches; this does not establish the full remote-follow-up fair-due-selection contract. They do not establish complete exact replay, general target-command convergence, complete terminal-failure mirroring, safe missing-coordinator recovery, or full origin reconciliation; those remain the target gaps described above. +The recorded proof covers durable command identity and sanitized persistence, restart/Redis-loss recovery at the ingress and ownership boundaries, single-record retry/replay updates, command correlation, batch/effect creation, manifest-digest replay repair, stale drain and post-drain fence rejection, durable `DRAINED` resumption, source-tuple preservation through timer/retry/remote claim-release transitions, fair selection in the local scheduler/queue path, and operator DTO/request mapping. Focused remote-runtime tests cover payload validation, bounded duplicate-window paging and de-duplication for due follow-up candidates, bounded durable result recording/replay, already-terminal follow-up replay, late-result handling, and selected reconciliation branches; this does not establish the full remote-follow-up fair-due-selection contract. They do not establish complete exact replay, safe accepted-but-never-staged convergence, general target-command convergence, complete terminal-failure mirroring, safe missing-coordinator recovery, or full origin reconciliation; those remain the target gaps described above. + +Current handling proof for accepted-but-never-staged work is limited to the live [recovery helper](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryService.java) and its [focused test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryServiceTest.java): they show that old `ACCEPTED` unstaged rows are re-enqueued under their original identity and remain `ACCEPTED` when Redis, identity, eligibility, or a raced transition makes the outcome uncertain. This is focused unit evidence, not combined PostgreSQL/real-Redis restart proof or proof of safe `STAGED` recovery after Redis loss. For live startup-loss recovery, only explicitly volatile/no-batch work may use `LOST_BEFORE_STAGING`; rollback purge retains its separate durable outcome mapping under [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md). Deterministic remote-result replay, paused-origin/late-result reconciliation, target-command convergence, and tenant/scope/id guards therefore remain proof gaps rather than completed coverage. + +Run-owned Compose mutation and teardown are implemented and proved at their bounded scope, but Game Session implementation and proof do not yet establish persistent/shared restricted-synthetic identity/namespace/fence isolation or independently isolated two-transport mutating parity. Shared/player-facing whole-stack reset is prohibited, and fixture teardown is not Coordination Redis reset authority; see the canonical [player-flow smoke and reset contract](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). The focused validation commands recorded for the live slices are `./gradlew :game-session-service:test --tests 'net.firedevops.firemud.gamesession.service.impl.TickStagingServiceTest' --tests 'net.firedevops.firemud.gamesession.service.impl.TickBatchExecutionServiceTest' --tests 'net.firedevops.firemud.gamesession.service.impl.TickServiceImplTest'`, the corresponding `RemoteFollowupRuntimeServiceImplTest` and `DefaultDurableRemoteFollowupExecutionServiceTest`, `dev-tools/validation/run-locked-gradle.sh :game-session-service:check -PfullCheck`, and `dev-tools/validation/run-locked-gradle.sh :logging-admin-service:check -PfullCheck`. Logging & Admin point/list/status controller and service tests cover successful reads, tenant guards, invalid enums, and fail-closed response mismatches for the listed control-plane routes; `/actuator/settings/effective` is outside that coverage pending route-aware authorization and cross-tenant denial proof. Game Session control-plane contract tests cover the upstream reads and fencing. The scheduler has a real bounded `ThreadPoolTaskExecutor` pressure proof including threshold trip and recovery reset. Lifecycle, feature-authority, and migrated command suites provide the corresponding focused proofs. @@ -165,11 +179,14 @@ The recorded Markdown and contract checks for these slices include `./gradlew li ## Active Gaps - TICK-03 is now the accepted command-level boundary: required versus optional effects, permitted terminal combinations, intentional `PARTIAL`, and stronger atomicity routing must be classified per command family. Current implementation and proof remain partial; no status promotion is implied. -- TICK-04 makes Game Session the durable owner of cross-service effect intent, required-participant status, retry, and reconciliation. The runtime still needs operation/digest-bound participant guards, stable root `EffectId` reuse, and focused crash/retry/dead-letter proof across World and Entity. -- Replacement cutover remains partial at the Game Session boundary: the target requires binding World’s one-shot `cutoverHoldId`/`cutoverHoldFence` and exact source/target `ACTIVE` proofs in the local pointer, audit, prepared-execution, source-cleanup, and drain-fence transaction, then proving post-swap readback before World finalization. The current wire/durable record/reconciler has no complete hold binding or safe-abort/finalization proof; it must not infer success from a pointer write or an in-memory termination request. +- TICK-04 remains partial and proof remains incomplete: operation/digest-bound participant guards and focused crash/retry/dead-letter coverage across World and Entity are still gaps under accepted contracts. Command-plan admission, `planOrdinal`, and root allocation are proposal-only in ADR 0183 and are not implementation or proof gaps unless that proposal is accepted. ADR 0069 owns effect identity, replay, and terminal-outcome rules; ADR 0071 owns durable tick commit before fenced coordination cleanup. +- Replacement cutover remains partial at the Game Session boundary: the current wire/durable record/reconciler has no complete proof of exact cross-service cutover binding, post-swap readback, safe abort, or finalization, and must not infer success from a pointer write or an in-memory termination request. See the canonical [World Management replacement cutover hold contract](../../architecture/microservices/world-management-service/api-contracts.md#replacement-cutover-hold-contract) and [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md). - The current Game Session movement seam is a room-binding/projection seam, not World-authoritative location/occupancy mutation. The target World-owned authoritative mutation path remains unimplemented/unproved, and `DROP`/`PICKUP` still lack proof that the World actor-location precondition remains valid through the Entity commit. - Ownership is durable only at the current game-instance queue boundary. True region-partitioned execution, a cluster scheduler, and lease-owner forwarding from session front ends are not implemented. +- The current runtime-status schema/repository still exposes unscoped `(tenant, region)` uniqueness/read behavior, despite the complete region scope including `gameInstanceId`; the remote-followup schema similarly uses `(tenant, target-region, target-epoch, effect_key)` uniqueness while repository reads include target instance scope. These are concrete implementation/proof gaps; no target contract should be inferred from the current indexes, and no migration is claimed here. +- Durable-first commit and fenced coordination cleanup remain partial: current implementation and focused proof do not yet establish the target `durable_committed` boundary. [ADR 0071](../../architecture/decisions/adr-0071-durable-tick-commit-before-fenced-coordination-cleanup.md) owns the canonical commit/cleanup contract; this tracker records only the current implementation and proof status. +- Region split/merge remains an operator-controlled cutover. Current implementation and proof do not establish the [ADR 0055](../../architecture/decisions/adr-0055-durable-cross-region-effects-with-static-live-topology.md) producer-wide admission barrier across player fronts, supported operator forwarding, automation, timers, and remote-follow-up producers; pausing only the current tick/command loop is not sufficient. - The scheduler has no adaptive gameplay-timing feedback loop. Pressure remains observable and operator-driven; changing gameplay timing requires preview or production-like data and a deliberate decision. - Only the current built-in state-changing command families consume the durable effect path. Later authored or game-defined authoritative mutations must use it; read-only views remain direct by design. - Timer, retry, and remote-follow-up work is live only after materialization as gameplay commands with retained provenance and ordering fields; directly selected source-claim manifests for those sources remain target-state. The three current remote payload families are live, but any new work-source or payload family still needs explicit durable source, ordering, ownership, fence, replay, result, and operator-read contracts. No side channel is part of the current implementation. The accepted [ADR 0055](../../architecture/decisions/adr-0055-durable-cross-region-effects-with-static-live-topology.md), [ADR 0066](../../architecture/decisions/adr-0066-durable-asynchronous-cross-region-result-arbitration.md), and [ADR 0077](../../architecture/decisions/adr-0077-durable-global-effect-fanout-and-lightweight-idle-ticks.md) do not claim those broader implementation families are complete. diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 8df39a9ab6..9658bd53ef 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -79,11 +79,11 @@ The live transfer contract deliberately rejects an already-moved item by default ### Durable Effects and Replay Guards -Game Session persists a stable same-batch `effectKey` and deterministically derives `effectId` from `tickBatchId` plus that key. The current key vocabulary is `command:` when a durable command id exists, or `command-text::slot:` for a queue entry without one. Same-batch duplicate keys are rejected. Durable drained effects resume after restart and, after an ownership-fence check, converge to `APPLIED`, `REPLAY_NOOP`, or `REJECTED`; stale executors abandon and requeue rather than applying under the wrong fence. +Current Game Session implementation persists a stable same-batch `effectKey` and derives `effectId` from `tickBatchId` plus that key (`command:`); durable tick staging/replay rejects missing or blank command IDs before effect selection, so the private helper's defensive `command-text::slot:` branch is unreachable in the live tick path and is not a no-commandId recovery identity. Same-batch duplicate keys are rejected. Focused replay tests exercise restart drain, ownership-fence checks, stale-executor requeue, and local result mappings (`APPLIED`, `REPLAY_NOOP`, and `REJECTED`); they do not establish canonical cross-service participant-guard identity, effect terminalization, or proof that an ambiguous or rejected attempt cannot be reapplied. The command-linked identity does not establish the accepted effect identity/replay contract, which remains unimplemented and unproved here. Command-plan and root-allocation specifics remain proposal-only under [ADR 0183](../../architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). See [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md) for the accepted effect rules and [Transaction Strategies](../../architecture/system-architecture-transactions.md#command-atomicity-and-outcome-aggregation) for participant-guard behavior. -Owning domains provide the duplicate-application boundary rather than relying on one global guard table. Movement uses an `effectId`-keyed idempotency service tied to session-context mutation. Entity Management has a mutation replay row per `{tenantId,effectId}` for the bounded item/equipment/container path, and a separate `ApplyActorCondition` replay path that uses the temporary `sourceId` adapter; duplicate delivery returns the stored response on those exercised paths. This is not replay-proof coverage for every Entity mutation ingress: blank-`effectId` compatibility requests bypass the ledger, and the actor-condition adapter does not yet expose a dedicated replay field. Game Session has local replay records per `{tenantId,sessionId,effectId}` for `SAY`, `WHISPER`, `TELL`, `AFK`, `BLOCK`, and the bounded authored-action path, re-delivering actor-facing output without re-invoking the mutation handler. Social Groups persists `effect_id` with a `{tenantId,effectId}` uniqueness boundary and can return the stored chat DTO for a duplicate whose first row was already committed; concurrent first-apply replay remains unproved. +The bounded owner-local replay implementations are: Movement's `effectId`-keyed idempotency service tied to session-context mutation; Entity Management's one mutation replay row per `{tenantId,effectId}` for validated, nonblank effect IDs, with the applied protobuf response for item, equipment, and container mutations, plus a separate `ApplyActorCondition` path that uses the temporary `sourceId` adapter. The focused Entity proof is limited to those nonblank-ID item/equipment/container and actor-condition paths: Entity mutation paths that accept blank effect IDs can bypass the replay table, while `ApplyActorCondition` rejects blank source identity before replay lookup. The Entity replay record also does not bind canonical target/scope/fence/request-digest evidence, so operation-only reuse is not proven fail-closed. Game Session has local replay records per `{tenantId,sessionId,effectId}` for `SAY`, `WHISPER`, `TELL`, `AFK`, `BLOCK`, and the bounded authored-action path, re-delivering actor-facing output without re-invoking the mutation handler. Social Groups persists `effect_id` with a `{tenantId,effectId}` uniqueness boundary and can return the stored chat DTO for a sequential duplicate whose first row was already committed; concurrent first-apply replay remains unproved. These are implementation boundaries and proof status, not the target participant-guard contract. -The shared execution helper also keeps Game Session communication, AFK, action-state, and authored-action replay lookup/save/delivery behavior aligned. Metrics distinguish first apply and replay/no-op outcomes through `gamesession.durable.effect.execution{command,effect_status,gameplay_result}` and Entity Management mutation execution metrics. This is a bounded adoption set, not a universal cross-service guard table; future authoritative mutation families must adopt the same durable-identity and owning-domain boundary. +The shared execution helper currently keeps Game Session communication, AFK, action-state, and authored-action replay lookup/save/delivery behavior aligned. Existing metrics distinguish first-apply and replay/no-op outcomes through `gamesession.durable.effect.execution{command,effect_status,gameplay_result}` and Entity Management mutation execution metrics. This remains a bounded adoption set rather than a universal cross-service guard table; broader participant-guard propagation and cross-service replay proof remain incomplete. The target root/participant binding and outcome aggregation are owned by [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md) and [Transaction Strategies](../../architecture/system-architecture-transactions.md#command-atomicity-and-outcome-aggregation). Replay-status qualification: the GR-3.2 implementation and verification entries below describe the nonblank-`effectId` item/equipment/container replay-ledger path only. Those mutation requests still have a blank-ID compatibility direct-execution path that bypasses the Entity replay ledger. `ApplyActorCondition` is a separate exception: it has no dedicated `effectId`; its temporary adapter carries the durable ID in `sourceId`, which Entity uses as the replay key and source provenance. Existing replay tests therefore do not establish safe replay protection for every mutation ingress; focused proof and full-ingress replay readiness remain blocked until each ingress has a valid trusted replay identity. @@ -123,10 +123,11 @@ Damage, mitigation, resistances, combat timing, body-region resolution, defeat, ## Active Gaps - Accepted TICK-03 requires command-level required/optional effect classification and invariant-sensitive routing; current gameplay families do not yet provide complete classification or terminal-outcome proof. See [ADR 0053](../../architecture/decisions/adr-0053-command-atomicity-by-invariant-class.md) and its [tick failure/operations owner](../../architecture/system-architecture-tick-failures-and-operations.md). -- Accepted TICK-04 requires one durable root `EffectId` with operation/target/request-digest-bound participant guards and causal read composition. Existing replay proof is domain-bounded and does not prove the cross-service guard, stale-precondition, or mixed-floor cases. See [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md) and its [identifier-glossary owner](../../architecture/system-architecture-identifier-glossary.md). +- Accepted TICK-04 remains an implementation and proof gap: current replay paths do not establish cross-service operation/target/request-digest-bound participant guards, causal read composition, stale-precondition handling, or mixed-floor handling. The canonical mutation identity, participant-guard, and root/child lineage rules are owned by [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md), [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), and the [identifier glossary](../../architecture/system-architecture-identifier-glossary.md); pending generated-child allocation is recorded only in the non-authoritative [ADR 0183 proposal](../../architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). This tracker records implementation and proof status only. - [ADR 0059](../../architecture/decisions/adr-0059-causal-floor-cross-service-presentation-reads.md) accepts a causal floor plus actual opaque World/Entity component versions; current LOOK composition still has scope-marker compatibility behavior, bounded stale-floor retry, and final read-fence error mapping gaps. This tracker does not claim the accepted presentation identity is implemented. - [ADR 0060](../../architecture/decisions/adr-0060-world-owned-ambient-facts-and-logic-owned-consequences.md) and [ADR 0061](../../architecture/decisions/adr-0061-single-owner-spatial-mutations-across-split-authority.md) keep ambient/location facts in World, item holders in Entity, and root outcomes/reconciliation in Game Session. Current gameplay has no complete cross-owner mutation/targeting proof; the accepted ownership direction does not promote current item or movement seams. -- [ADR 0056](../../architecture/decisions/adr-0056-one-hot-path-fan-out-owner.md), [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), and [ADR 0075](../../architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md) are target contracts only: transitive two-participant proof, one-logical-effect terminal convergence, and deterministic chain count/cost/per-target suppression remain unimplemented or unproved for broader gameplay families. +- Reachable tenant-access-checked administrative `POST`/`DELETE` inventory/equipment mutation handlers persist `ItemInstance` and `ItemStack` through Entity outside Game Session effect, tick, and barrier admission and do not require character ownership. `ScopedCharacterResolver` verifies tenant, character, and playable-state scope; persistence outside Game Session admission remains a gap. The current paths do not establish an admin-role check or an approved owner/admin contract. +- Broader gameplay families remain unimplemented or unproved against the target contracts owned by [ADR 0056](../../architecture/decisions/adr-0056-one-hot-path-fan-out-owner.md), [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), [ADR 0075](../../architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md), and the canonical [Transactions generated-effect-chain contract](../../architecture/system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory). - The parent inventory slice remains partially implemented as a domain: manual happy-path verification over both WebSocket and Telnet is still unchecked, and later nested-container UX, crafting/material flows, banking/vendor/mail/trade, loot generation, scripted item behavior, durability, and richer client filtering are not implemented. - Broader holder families must reuse the direct-holder and guarded-handoff model. Cross-domain transfer replay is not implicit; it needs an explicit caller-owned contract. Stronger audit invariant/alert tooling is also future work. @@ -135,7 +136,7 @@ Damage, mitigation, resistances, combat timing, body-region resolution, defeat, - Generic authored stat/condition definitions, release-catalog enforcement as a full authoring system, broader effect kinds, generic resource-cost mutation, cooldown lifecycle, multi-effect action execution, and combat-facing effect consumption remain future work. The intended catalog is versioned DML frozen into a release bundle; Entity Management must reject unknown or stale keys rather than invent defaults, and starter profiles must materialize ordinary editable DML rather than hidden runtime fallback. The current typed payload is still a transitional continuous-source contract. The locked `EffectDeclaration` model distinguishes `CONTINUOUS` read-time sources, which never persist derived resource values, from idempotent `INSTANT` mutations under a resolved plan; future condition application uses authored `REPLACE`, `REFRESH`, `STACK`, or `PARALLEL` and duration policy, while cooldowns remain a sibling timed-state type. - The future actor-state contract keeps capacity-change policy, floor transitions, disposition, conditions/equipment overlays, action-admission tags, command capability policy, costs, and cooldowns as separate concerns. Resource floors have no implicit `health`, death, victory, corpse, loot, respawn, or revival meaning; continuous sources cannot override disposition admission, and durable instant mutations must own explicit lifecycle transitions. - The future action-admission contract uses a release-pinned DML `ActionAdmissionTag` catalog and ordered required `admissionTags`. Command-capability and login/play stage gates run first; disposition and continuous overlays may deny but never grant forbidden behavior, and unknown, stale, or omitted required tags fail closed. -- The broad authored target-resolution and structured-outcome model is not live: cross-actor target sets, canonical candidate/fact snapshots, target-resolution evidence, `ResolvedEffectPlan` application, remote legs, semantic presentation events, and general required/optional outcomes remain design work beyond the self-targeted v1 path. The locked boundary is Game Logic-owned resolution from frozen policies and owner fact snapshots/tokens, followed by idempotent Entity Management application; Game Session must not choose final actor identities. Candidate selection is explicitly bounded and deterministic, observation failures must not disclose hidden facts, same-region required legs commit atomically or reject, and cross-region legs use durable follow-up coordination rather than claimed distributed atomicity. The future `GameplayActionOutcome` separates source `commitState` from `completionState`, carries ordered target-leg outcomes, and drives idempotent semantic presentation events rather than treating free-form text as gameplay truth. +- The broad authored target-resolution and structured-outcome capability remains unimplemented and unproved beyond the self-targeted v1 path: cross-actor target sets, multi-effect composition, cross-region outcomes, and the wider typed primitive catalogue remain gaps. Canonical ownership is defined by [ADR 0112](../../architecture/decisions/adr-0112-typed-bounded-gameplay-effect-extension.md), with target-plan resolution in the [Game Logic API contracts](../../architecture/microservices/game-logic-service/api-contracts.md) and validated actor/effect mutation in the [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); this tracker records the current capability and proof gap only. - Reusable DML observation, targeting, and selection policies define `SOURCE` plus keyed target sets, `EXACTLY_ONE`, bounded `UP_TO_N`, or `ALL_ELIGIBLE` cardinality, and player-selected, canonical-order, ranked, or effect-id-seeded selection. Resolution records candidates, fact snapshots, policy identity, ranking or seed, selected targets, and owner fence/version tokens. Missing or stale facts fail closed; token mismatch re-resolves under the same effect id before mutation. - Resource costs and cooldowns remain future actor-state execution work. Game Design declarations carry typed costs, cooldowns, and `ON_EXECUTION` or `ON_EFFECT_SUCCESS` commit policy; Entity Management must atomically validate and consume resources, create durable cooldown records, and apply same-region effects under one idempotent effect id. Game Session timers are reconstructible wake-up projections, concurrent actions serialize at the authoritative mutation, queue acceptance consumes nothing, and cross-region failure has no implicit refund. Capacity changes use authored preserve/shift/clamp policy, and floor transitions are explicit one-shot lifecycle events rather than implicit death or victory semantics. - No unified persisted actor runtime, NPC runtime actors, generic actor targeting/communication, or actor-state linkage exists. The locked core is an opaque `actorId` with tenant/game-instance context, `actorKind`, display name, presence state, and disposition, linking player actors to account/character and NPC actors to runtime instances; `PLAYER` and `NPC` are first kinds, with later `PET`/`SUMMON`, and gods/admins remain player overlays. diff --git a/design/project-management/implementation-tracking/platform-operations-and-delivery.md b/design/project-management/implementation-tracking/platform-operations-and-delivery.md index f7ecd03037..4245d17195 100644 --- a/design/project-management/implementation-tracking/platform-operations-and-delivery.md +++ b/design/project-management/implementation-tracking/platform-operations-and-delivery.md @@ -66,7 +66,7 @@ These links record implementation and proof gaps; they do not claim that the cor | `PO-2.3` Client protocol negotiation and structured protocol extensions | `partial` | `drift-found`: existing Telnet/WebSocket projection and transport tests cover current behavior, but schema-version compatibility and unsupported-version handling are not implemented/proven | [MUD client protocol](../../architecture/system-architecture-mud-client-protocol.md); [protocol bridging](../../architecture/system-architecture-protocol-bridging.md); [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md) | [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [WebSocketOutputProjector.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjector.java) | [TelnetServerHandlerTest.java](../../../services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandlerTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [WebSocketOutputProjectorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java) | [Player experience](./player-experience-commands-and-communication.md); [player access](./player-access-and-session.md) | Richer smart-client capabilities and first-party protocol extensions remain. Future focused proof must cover the sanitized bridge matrix: supported Telnet controls, unsupported options/subnegotiation, opaque markers, byte/line limits, and exact post-filter forwarding. The supported structured-client contract still needs explicit schema-version compatibility/unsupported-version proof; every envelope must retain a deterministic plain-text projection for Telnet and generic text WebSocket. | | `PO-2.4` Edge limits, backpressure, close taxonomy, and retry behavior | `partial`: current retry-count/delay handling, rate limits, close metrics, and bounded connection controls are live | `drift-found`: current tests prove the shipped attempt-based bridge, not ADR 0013's elapsed-time cutoff, bounded stall/rebind buffer, or terminal-versus-rebindable classification | [Gateway](../../architecture/system-architecture-gateway.md); [ADR 0007](../../architecture/decisions/adr-0007-edge-sharding-and-close-taxonomy.md); [ADR 0013](../../architecture/decisions/adr-0013-bounded-invisible-non-edge-restart-recovery.md); [ADR 0170](../../architecture/decisions/adr-0170-fenced-command-forwarding-and-authoritative-region-transition.md) | [GameplayWebSocketBridgeProperties.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GameplayWebSocketBridgeProperties.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [GameplayWebSocketObservability.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketObservability.java); [IpConnectionLimiterImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/IpConnectionLimiterImpl.java); [GatewayRateLimiterConfig.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfig.java) | [GameplayWebSocketObservabilityTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketObservabilityTest.java); [GameplayWebSocketBridgeHandlerTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java); [GatewayRateLimiterConfigTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfigTest.java) | [Player access](./player-access-and-session.md); [player experience](./player-experience-commands-and-communication.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md) | Elapsed recovery cutoff, bounded stall/rebind handling, outcome classification, and focused proof remain incomplete. | | `PO-3.1` Packaging, CI/CD, deployment, promotion, and infrastructure topology | `partial` | `proven` for current packaging/deployment checks only; exact-plan authorization and evidence remain incomplete | [CI/CD](../../architecture/system-architecture-cicd.md); [infrastructure](../../architecture/infrastructure/README.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0097](../../architecture/decisions/adr-0097-git-and-ci-validated-single-operator-promotion-evidence.md); [ADR 0177](../../architecture/decisions/adr-0177-exact-plan-authorized-automated-production-deployment.md) | [build.gradle.kts](../../../build.gradle.kts); [runtime-images.yml](../../../.github/workflows/runtime-images.yml); [apps.yaml](../../../k8s/helm/firemud/templates/apps.yaml); [prod kustomization.yaml](../../../k8s/overlays/prod/kustomization.yaml) | [preview-eligibility-contract.sh](../../../dev-tools/tests/preview-eligibility-contract.sh); [smoke-image-env-contract.sh](../../../dev-tools/tests/smoke-image-env-contract.sh); [validate-helm.sh](../../../dev-tools/validation/validate-helm.sh); [validate-kustomize-overlays.sh](../../../dev-tools/deploy/validate-kustomize-overlays.sh) | [Authoring](./game-authoring-publishing-and-activation.md) | Current packaging and deployment checks pass, but exact-plan authorized deployment, promotion enforcement, attestation lineage, applicable maturity-scoped protobuf compatibility, and controller-authoritative recovery compatibility remain incomplete. | -| `PO-3.2` Environment, configuration, secret, certificate, and service-discovery delivery | `partial` | `proven` for local/static hosted identity contracts; live rollout remains unproved | [Environment/secrets](../../architecture/infrastructure/environment-and-secrets-overview.md); [deployment environments](../../architecture/infrastructure/deployment-environments.md); [ADR 0032](../../architecture/decisions/adr-0032-kubernetes-native-secret-delivery-without-mandatory-vault.md); [ADR 0152](../../architecture/decisions/adr-0152-phased-environment-bound-deployment-preflight-and-expected-bindings.md); [ADR 0171](../../architecture/decisions/adr-0171-separated-redis-role-processes-and-owned-keyspaces.md); [ADR 0182](../../architecture/decisions/adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md) | [preflight.py](../../../dev-tools/deploy/preflight.py); [hosted identity controller bootstrap](../../../dev-tools/hosted/controller/bootstrap-hosted-identity-controller.sh); [hosted identity controller kustomization](../../../k8s/hosted-identity-controller/kustomization.yaml); [shared-config.yaml](../../../k8s/helm/firemud/templates/shared-config.yaml); [JwtAuthProperties.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtAuthProperties.java) | [preflight-contract.sh](../../../dev-tools/tests/preflight-contract.sh); [secret-compliance-contract.sh](../../../dev-tools/tests/secret-compliance-contract.sh); [check-grpc-transport-config.sh](../../../dev-tools/validation/check-grpc-transport-config.sh); [validate-kustomize-overlays.sh](../../../dev-tools/deploy/validate-kustomize-overlays.sh); [helm-jwks-contract.sh](../../../dev-tools/tests/helm-jwks-contract.sh); [hosted-identity-controller-manifest-contract.sh](../../../dev-tools/tests/hosted-identity-controller-manifest-contract.sh); [hosted-identity-controller-workflow-contract.sh](../../../dev-tools/tests/hosted-identity-controller-workflow-contract.sh) | [Shared runtime](./shared-runtime-contracts-and-persistence.md); [player access](./player-access-and-session.md) | Secret/certificate custody, encryption/RBAC/audit evidence, credential rotation, outage continuity, served-certificate/consumer convergence, and live-cluster preflight proof remain incomplete. The hosted controller contract is local/static evidence only; binding-reference and fingerprint validators do not establish canonical operator binding-generation, operation identity, overlap, and readback evidence; the richer binding record remains target-only. Exact operator-rendered controller egress now removes broad CIDRs and statically covers the observed API, public probe, explicit Traefik TCP/8443 post-DNAT target, TCP Proxy TCP/2323 post-NodePort-DNAT target, Telnet, and scoped Gateway destinations, but PO-3.2 remains incomplete until the complete live allow/deny matrix, CNI post-DNAT behavior, and served Gateway↔TCP Proxy bridge proof are established. | +| `PO-3.2` Environment, configuration, secret, certificate, and service-discovery delivery | `partial` | `proven` for local/static hosted identity contracts; live rollout remains unproved | [Environment/secrets](../../architecture/infrastructure/environment-and-secrets-overview.md); [deployment environments](../../architecture/infrastructure/deployment-environments.md); [ADR 0032](../../architecture/decisions/adr-0032-kubernetes-native-secret-delivery-without-mandatory-vault.md); [ADR 0152](../../architecture/decisions/adr-0152-phased-environment-bound-deployment-preflight-and-expected-bindings.md); [ADR 0171](../../architecture/decisions/adr-0171-separated-redis-role-processes-and-owned-keyspaces.md); [ADR 0182](../../architecture/decisions/adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md) | [preflight.py](../../../dev-tools/deploy/preflight.py); [hosted identity controller bootstrap](../../../dev-tools/hosted/controller/bootstrap-hosted-identity-controller.sh); [hosted identity controller kustomization](../../../k8s/hosted-identity-controller/kustomization.yaml); [shared-config.yaml](../../../k8s/helm/firemud/templates/shared-config.yaml); [JwtAuthProperties.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtAuthProperties.java) | [preflight-contract.sh](../../../dev-tools/tests/preflight-contract.sh); [secret-compliance-contract.sh](../../../dev-tools/tests/secret-compliance-contract.sh); [check-grpc-transport-config.sh](../../../dev-tools/validation/check-grpc-transport-config.sh); [validate-kustomize-overlays.sh](../../../dev-tools/deploy/validate-kustomize-overlays.sh); [helm-jwks-contract.sh](../../../dev-tools/tests/helm-jwks-contract.sh); [hosted-identity-controller-manifest-contract.sh](../../../dev-tools/tests/hosted-identity-controller-manifest-contract.sh); [hosted-identity-controller-workflow-contract.sh](../../../dev-tools/tests/hosted-identity-controller-workflow-contract.sh) | [Shared runtime](./shared-runtime-contracts-and-persistence.md); [player access](./player-access-and-session.md) | Secret/certificate custody, encryption/RBAC/audit evidence, credential rotation, outage continuity, served-certificate/consumer convergence, and live-cluster preflight proof remain incomplete. The hosted controller contract is local/static evidence only; binding-reference and fingerprint validators do not establish canonical operator binding-generation, operation identity, overlap, and readback evidence; the richer binding record remains target-only. Exact operator-rendered controller egress now removes broad CIDRs and statically covers the observed API, public probe, explicit Traefik TCP/8443 post-DNAT target, TCP Proxy TCP/2323 post-NodePort-DNAT target, Telnet, and scoped Gateway destinations, but PO-3.2 remains incomplete until the complete live allow/deny matrix, CNI post-DNAT behavior, served Gateway↔TCP Proxy bridge proof, and concrete Redis role-profile configuration—including an internal Coordination Redis `maxmemory` bound—are implemented and proved. Configuration and per-environment sizing remain owned by Platform Operations/6D. | | `PO-3.3` Object storage, CDN, registry, and platform asset delivery infrastructure | `partial` | `proven` | [Asset storage](../../architecture/microservices/game-design-service/asset-storage.md); [infrastructure](../../architecture/infrastructure/README.md) | [AssetStoreConfig.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/config/AssetStoreConfig.java); [AssetController.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/controller/AssetController.java); [V10__version_asset_artifact.sql](../../../services/game-design-service/src/main/resources/db/migration/V10__version_asset_artifact.sql); [MinIO deployment.yaml](../../../k8s/minio/deployment.yaml); [runtime-images.yml](../../../.github/workflows/runtime-images.yml) | [AssetExportServiceImplTest.java](../../../services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java); [VersionAssetArtifactRepositoryIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryIntegrationTest.java); [validate-helm.sh](../../../dev-tools/validation/validate-helm.sh); [smoke-image-env-contract.sh](../../../dev-tools/tests/smoke-image-env-contract.sh) | [Authoring](./game-authoring-publishing-and-activation.md); [player experience](./player-experience-commands-and-communication.md) | Production CDN lifecycle, richer registry operations, and creator-facing asset delivery remain. | | `PO-3.4` Backup, restore, disaster recovery, and self-hosted recovery | `partial` | `drift-found`: bounded online-dump and backup-verifier helper/image contract checks, non-executing restore wiring, reset, and restart seams are proven locally; no live backup existence/reachability is proven, and the broader recovery capability remains unproven | [Backup/recovery](../../architecture/system-architecture-backup-recovery.md); [recovery evidence](../../architecture/system-architecture-backup-recovery-evidence-and-compliance.md); [CI/CD](../../architecture/system-architecture-cicd.md) | [schedule.yaml](../../../k8s/velero/schedule.yaml); [verify-backups-cronjob.yaml](../../../k8s/velero/verify-backups-cronjob.yaml); [manual-backup-restore.yml](../../../.github/workflows/manual-backup-restore.yml); [pg-dump-rotate.sh](../../../dev-tools/backups/pg-dump-rotate.sh); [restore-cluster.sh](../../../dev-tools/restores/restore-cluster.sh); [reset-service-db.sh](../../../dev-tools/restores/reset-service-db.sh); [smoke-backup-verifier-image.sh](../../../dev-tools/backups/smoke-backup-verifier-image.sh) | [verify-backups.sh](../../../dev-tools/backups/verify-backups.sh); [verify-backups-velero-contract.sh](../../../dev-tools/tests/verify-backups-velero-contract.sh); [verify-backups-cronjob-contract.sh](../../../dev-tools/tests/verify-backups-cronjob-contract.sh); [backup-verifier-image-contract.sh](../../../dev-tools/tests/backup-verifier-image-contract.sh); [reset-service-db-contract.sh](../../../dev-tools/tests/reset-service-db-contract.sh); [verify-restart-state.sh](../../../dev-tools/verify-restart-state.sh) | [Shared runtime](./shared-runtime-contracts-and-persistence.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md) | The [Backup helper README](../../../dev-tools/backups/README.md) documents the helper boundaries. Measured verified-point RPO, immutable artifact and restore lineage, readable restore execution, environment-wide cold-start quarantine and reconciliation, post-restore trust reset, recovery-controller continuation, and controlled traffic reopen remain unimplemented or unproven. | | `PO-4.1` Logging, metrics, tracing, dashboards, and alerting | `partial` | `drift-found` | [ADR 0017](../../architecture/decisions/adr-0017-capability-gated-operational-tracing.md); [ADR 0162](../../architecture/decisions/adr-0162-profile-aware-asynchronous-end-to-end-log-queryability-evidence.md); [ADR 0167](../../architecture/decisions/adr-0167-allowlisted-sensitive-trace-attributes.md); [Logging/monitoring](../../architecture/system-architecture-logging-monitoring.md); [tracing](../../architecture/system-architecture-tracing.md) | [RuntimeIdentity.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/runtime/RuntimeIdentity.java); [MetricsInterceptor.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/MetricsInterceptor.java); [GameplayWebSocketObservability.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketObservability.java); [prometheus-rules-firemud.yaml](../../../k8s/monitoring/prometheus-rules-firemud.yaml) | [check-metrics-cardinality.py](../../../dev-tools/observability/check-metrics-cardinality.py); [validate-observability-contract.py](../../../dev-tools/observability/validate-observability-contract.py); [player-experience-smoke-runner-contract.sh](../../../dev-tools/tests/player-experience-smoke-runner-contract.sh); [GameplayWebSocketObservabilityTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketObservabilityTest.java) | [Shared runtime](./shared-runtime-contracts-and-persistence.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [player experience](./player-experience-commands-and-communication.md) | ADR 0017 level 1 (baseline observability) is the highest current advertisement: metrics and structured logs are the dependable surface, while generic RPC spans/export and trace-log correlation are best-effort. No named workflow has level-2 end-to-end proof; service-scoped sampling (level 3), tenant/game-instance/region sampling (level 4), broad region enrichment, embedded dashboards, and recovery-participant convergence observability remain unproved. The missing-source alert is fail-safe gap detection only and does not establish recovery readiness. The current profile overlays install only the applicable deadman rules; the player-flow canary and public-path blackbox alert families remain target-only and uninstalled pending deployment-owned gates. Capability-aware installation, deployment-owned external alert authority, atomic profile-transition cleanup, residual-series handling, and live proof remain implementation gaps. | diff --git a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md index f0fb8deece..6453350fcc 100644 --- a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md +++ b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md @@ -56,7 +56,7 @@ The following current-state findings refine the existing partial/drift status; o - `SF-2.1`: Game Design’s historical `version.revision_ids` relationship was dropped before revisions were assigned to the latest tenant version, so immutable revision/version history is not proven. Retained-data disposition or a verified no-data boundary remains open; see [Versioning & Runtime Configuration](../../architecture/system-architecture-versioning-runtime.md#implementation-status). - `SF-2.1` / `SF-2.3`: Account’s connect-token path remains a bounded Redis map without durable issuance-operation, encrypted-response, or atomic exact-request-claim support. A read-then-mint/unconditional-write race can produce different tokens for one request identity, and the exact-result/recovery contract remains unimplemented. Current evidence and owner status are recorded in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). - `SF-2.2`: Gateway’s replay/deny/readiness implementation remains unaligned with the canonical Redis key grammar, reset, catalog, and proof boundaries; its current marker and the Account Redis map remain implementation drift. See [Redis](../../architecture/system-architecture-redis.md) and [Gateway Service](../../architecture/microservices/spring-cloud-gateway/README.md#implementation-status). -- `SF-2.1` / `SF-2.2`: Redis role-specific clients remain unimplemented: current Game Session correctness state and cache consumers can share one generic endpoint/template despite separate deployed coordination and cache Redis roles. Compose can route the generic binding to the eviction-enabled cache Redis, while base Kubernetes supplies no generic hostname and the default `redis` endpoint may be unavailable. A role-qualified client refactor plus focused routing, eviction-isolation, and readiness proof remain open; this tracker records the consequence without implementing that refactor. +- `SF-2.1` / `SF-2.2`: Redis role-specific clients remain unimplemented: current Game Session correctness state and cache consumers can share one generic endpoint/template despite separate deployed coordination and cache Redis roles. Compose can route the generic binding to the eviction-enabled cache Redis, while base Kubernetes supplies no generic hostname and the default `redis` endpoint may be unavailable. A role-qualified client refactor plus focused routing, eviction-isolation, and readiness proof remain open. The checked Coordination configs also lack an internal Redis `maxmemory` bound; external container/pod limits do not satisfy that requirement. This role-profile configuration gap remains jointly owned by shared runtime 5C and Platform Operations/6D; this tracker records the consequence without implying implementation. - `SF-1.2` / `SF-2.1`: Entity’s durable S1/S2 schema lacks the target namespace identity across character, inventory, equipment, and holder/containment associations, and nullable `item_stacks` uniqueness is paired with find-then-create writes. Migration, repository, isolation, and concurrency proof remain open; see [Entity Runtime and Data](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status). - `SF-2.1` / `SF-2.4`: Game Design-to-World publication currently uses a remote Draft-state pre-check before WMS mutation, without a durable WMS owner-freeze row or exact publication fence, so mutation can race publication. The implementation and proof gap is recorded in [World Management Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status) and [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#publication-freeze-and-owner-handoff). - `SF-2.1`: `version_asset` and release-bundle referential-integrity proof remains incomplete for tenant-qualified ownership and cross-tenant readback; see [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#table-structure). diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index ac9a74c746..a8ccf449ab 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -15,6 +15,8 @@ This tracker is the permanent reader-facing implementation record for world runt - `GR-2.1` / `AR-3.1`: World termination keeps Entity Management cleanup outside an open World transaction, retains `TERMINATING` while cleanup is pending or fails, and commits local runtime-row cleanup with the `TERMINATED` lifecycle state in one local transaction. [World Management Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status) owns this current consequence. [WorldLifecycleCommandServiceImplTest](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java) covers the local control flow and RPC/transaction separation; live PostgreSQL rollback/crash/concurrency proof is not claimed. The separate terminal fast path still does not compare `terminationRequestId`, as recorded below. - `GR-2.1` / `SF-2.3`: The synchronous termination seam returns a `TERMINATED` snapshot before checking a supplied `terminationRequestId`; mismatched terminal retries therefore are not fail-closed, and exact identity/conflict proof remains incomplete. See [World Management Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status). - `GR-2.1` / `SF-2.1`: Versioned topology and spawn schemas carry tenant/version columns but use scalar parent foreign keys, so the database does not enforce child/parent scope equality. Composite ownership enforcement (or an equivalent owner-local guard) and database readback proof remain incomplete; this is separate from sentinel-default and hierarchy/version-graph backfill drift. See [World Management Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status). +- `GR-2.1` / `AR-1.5`: The WMS design handoff performs only a remote Game Design Draft-state check before its local mutation transaction. Durable owner-freeze acknowledgement and commit-bound `versionStateEpoch`/`publicationFence` evidence are absent, so a pre-check can race publication; the target handoff and race semantics belong to [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#publication-freeze-and-owner-handoff), with local status and proof consequences in [World Management Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status). +- `GR-2.1` / `AR-3.1`: The current Temporal lifecycle signal implementation keeps one mutable pending slot per operation and can overwrite repeated requests or process activate plus terminate against a stale epoch; this race and its focused proof remain incomplete. The target durable signal/update contract and conflict semantics are owned by [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md). These links add decision provenance only; they do not upgrade world runtime, lifecycle, or Draft mutation status. diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index c27ce76a58..8fac6f243a 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -8,6 +8,15 @@ import re root = pathlib.Path(".") obsolete_public_resume_signature = "`resume(operationId, expectedPhase, scope, maintenanceLockToken, evidenceRef)`" +obsolete_scope_resume_window_identity = re.compile( + r"<(?=[^<>]*\btenantId\b)" + r"(?=[^<>]*\bgameInstanceId\b)" + r"(?=[^<>]*\bregionId\b)" + r"(?=[^<>]*\bregionEpoch\b)" + r"(?=[^<>]*\bisDryRun\b)" + r"(?=[^<>]*\bplayableStateScope\b)" + r"(?=[^<>]*\bresumeGeneration\b)[^<>]*>" +) obsolete_gameplay_session_selector = "session:game:{tenantInstanceTag}" obsolete_gameplay_character_index = "session:game:index:character:{tenantGameplayTag}::" obsolete_gameplay_character_index_with_scope = "session:game:index:character:{tenantGameplayTag}:::" @@ -1701,10 +1710,74 @@ require_contains( require_contains( "design/architecture/system-architecture-scripting-contracts.md", [ + "The `(automationDispatchId, commandOrdinal)` pair is only an identity suffix and is insufficient by itself", + "Participant-guard identity follows the owner-classified rules in [Transaction Strategies](./system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory): S1/S2 use the `(tenantId, playableStateNamespaceId)` partition, and only explicitly classified S3 uses `(tenantId, gameInstanceId)`; `playableStateScope` and `requestDigest` are exact-validated evidence, not uniqueness dimensions, and unclassified families fail before admission.", "always-isolated test-only breaker or gate", "no environment, tenant, or request opt-in may cross that boundary", ], ) +require_absent( + "design/architecture/system-architecture-scripting-contracts.md", + ["(automationDispatchId, commandOrdinal)` pair is only a display suffix"], +) +require_contains( + "design/architecture/microservices/entity-management-service/operations.md", + [ + "a conflict-safe insert or a same-transaction savepoint around marker handling while keeping the marker and mutation atomic, never an isolated marker transaction", + "Actual PostgreSQL concurrent proof remains unavailable.", + "retain the admitted command/source identity for source evidence, and use the complete Command-Handoff Identity for automation handoff and deduplication", + "the handoff identity is not a mandatory input to root `EffectId` allocation or lookup", + "Root allocation and lookup details remain proposal-only under pending [ADR 0183]", + ], +) +require_absent( + "design/architecture/microservices/entity-management-service/operations.md", + ["is an input to allocating or looking up that command's stable root `EffectId`"], +) +require_contains( + "design/architecture/microservices/game-session-service/runtime-and-data.md", + [ + "A new identity may be re-driven only after authoritative participant/domain evidence conclusively terminalizes the original effect as `ABANDONED` and the owning source command/claim is terminalized; ordinary retry/replay retains the original command/effect identity.", + "A new identity may be re-driven only after that conclusive terminalization and terminalization of the owning source command/claim; ordinary retry/replay must retain the original command/effect identity.", + "Root allocation details remain proposal-only under [ADR 0183]", + ], +) +require_absent( + "design/architecture/microservices/game-session-service/runtime-and-data.md", + [ + "only a conclusive post-abandon re-drive allocates a new command ID and root", + "A post-abandon re-drive is the only path that may allocate a new command ID/root", + ], +) +require_contains( + "design/architecture/microservices/game-design-service/version-control.md", + [ + "Current Game Design revision rows reference concrete domain objects", + "Target durable commits will group those revisions and retain their domain-object references", + "that branch/commit model and its APIs are not implemented, while current version-scoped revision history remains available", + ], +) +require_contains( + "design/architecture/system-architecture-redis-reset-and-recovery.md", + [ + "Before any future rebuild can release that scope, owner reconciliation must establish a definitive stage-aware disposition for ambiguous post-DSL handoffs from a durable evaluated descriptor, retaining durable handoff intent without replaying the DSL, then complete owner CAS fencing and exact readback.", + ], +) +require_contains( + "design/architecture/system-architecture-scripting-event-registry.md", + [ + "Gameplay/runtime and scheduler candidate identity also includes the exact Game Session `(scriptPatchVersion, scriptPinEpoch)` tuple", + "The paired nonblank `scriptPinControlPlaneRequestId` and captured `lifecycleRevision` travel alongside as required, exact-compared non-identity owner/fence evidence; they are excluded from candidate, firing-claim, work-item, and derived event identity.", + ], +) +require_contains( + "design/architecture/system-architecture-ticks.md", + [ + "Only wall-clock timer admission assigns a separate tick-ordering coordinate", + "Tick timers reuse their persisted `dueTickId` as both source due point and ordering coordinate.", + "Wall-clock timestamps and tick IDs are different domains and must not be compared numerically or aliased.", + ], +) require_absent( "design/architecture/system-architecture-scripting-contracts.md", ["separate breaker or explicitly opt-in per environment/tenant"], @@ -1728,6 +1801,27 @@ require_contains( "it is not persisted breaker authority and does not own transition history or reset", ], ) +require_contains( + "design/architecture/system-architecture-scripting-runtime-execution.md", + [ + "Target state also preserves any admission/execution-start charge markers already reached in the separate durable handler charge record", + "as defined by [Scripting Quotas & Operations](./system-architecture-scripting-quotas-and-operations.md#budget-accounting-rules)", + "that record and its linkage are not claimed as current implementation", + ], +) +require_absent( + "design/architecture/system-architecture-scripting-runtime-execution.md", + ["the separate durable handler charge record preserves any admission/execution-start charge markers already reached"], +) +require_contains( + "design/architecture/system-architecture-scripting-observability-contract.md", + [ + "`eventType`", + "`eventSchemaVersion` (admitted event and payload contract version, including tenant-readiness `onLoad`; see [normative Table 1](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields))", + "`scriptPatchVersion`", + "absent with `scriptPinEpoch` for pre-instance requests such as tenant-readiness `onLoad`, while `scriptPatchVersion` remains required", + ], +) require_contains( "design/architecture/microservices/automation-scripting-service/sandbox-runtime-design.md", [ @@ -1817,7 +1911,7 @@ require_section_contains( "`lastResetValidationEvidence`", "bounded `validationEvidence`", "`resetReason` is absent from lifecycle and trip rows", - "persisted non-identity `playableStateNamespaceId` evidence", + "`playableStateNamespaceId` is the immutable playable-state identity/allocation dimension", "`currentRuntimePlayableStateNamespaceId`", "The normalized exact scope is `(tenantId, gameInstanceId, regionId)`, where an omitted or blank `regionId` selects the exact empty/unscoped row and never a wildcard", "For both this mutation and `GetAutomationDrainStatus`, `tenantId` and `gameInstanceId` are required nonblank after normalization", @@ -1836,6 +1930,23 @@ require_contains( "durable successful Set acknowledgement (`APPLIED` or `ALREADY_APPLIED`)", ], ) +require_contains( + "design/architecture/system-architecture-scripting-control-plane-operations.md", + [ + "no surviving durable batch, effect ledger, or source/effect claim", + "atomic owner-defined no-batch/version-fenced check wins", + "A matching binding and `RETRY_QUEUED` status alone do not prove `NOT_APPLIED`", + "inconclusive work remains nonterminal and reconciliation-required", + ], +) +require_contains( + "design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md", + [ + "does not require authoritative evidence that the effect was unapplied", + "`RETRY_QUEUED` is enough for the current code to write `ABANDONED`/`NOT_APPLIED`", + "no runtime fix is claimed here", + ], +) require_contains( "design/architecture/system-architecture-scripting-rollout-and-rollback.md", [ @@ -1847,6 +1958,14 @@ require_contains( require_contains( "design/architecture/system-architecture-tick-incident-runbook.md", [ + "**Maintenance admission applies to both branches:**", + "Before a maintenance verifier CAS may mutate a ledger row, validate the exact ADR 0085 external maintenance handoff, durably persist it, and pass it unchanged with the reconciliation evidence.", + "An owner may omit that maintenance handoff only for a specifically classified non-conflicting routine replay with durably recorded classification/evidence and applicable fence, epoch, and scope proof", + "never infer this exemption from owner, epoch, executor, manifest, or participant proof alone.", + "If neither the exact handoff nor the owner-recorded routine-replay evidence is complete, make no mutation and use the existing fail-closed [Current Operator Fallback]", + "this incident remediation is maintenance, not ordinary crash replay.", + "Before its first mutation, validate the exact ADR 0085 external maintenance handoff, durably persist it, and pass it unchanged", + "Missing or unproved handoff means no mutation: use the fail-closed [Current Operator Fallback]", "may be applied as an initial emergency fence", "For any reset or recovery mutation, Automation must be contained before relying on Game Session tick/region containment", "complete affected scope set from the authoritative durable PostgreSQL/runtime inventory", @@ -1902,64 +2021,126 @@ require_absent( require_contains( "design/architecture/system-architecture-scripting-scheduler-and-timers.md", [ - "resume-window record per ``", - "its `resumeWindowId` is ``", - "retains the authoritative `playableStateNamespaceId` as immutable non-identity scope evidence", + "Durable `script_schedule_instances` rows in PostgreSQL are authoritative schedule state; Redis keys are rebuildable coordination projections, as defined by [ADR 0072](./decisions/adr-0072-class-specific-timer-durability-and-recovery.md).", + "resume-window record per ``", + "its `resumeWindowId` is ``", + "The server-derived `playableStateScope` is persisted separately as immutable policy/routing/authorization/migration-fence evidence and is exact-validated; it is not part of the window identity.", "missing or mismatched evidence fails closed without changing any canonical identity tuple", ], ) require_contains( - "design/architecture/system-architecture-scripting-dsl-for-designers.md", + "design/architecture/decisions/adr-0091-class-specific-script-timer-clocks-and-recovery.md", [ - "`resumeWindowId` identified by ``", - "one-tenant, one-mode ID", + "The authoritative `playableStateNamespaceId` is part of the due and resume-window identity", + "server-derived `playableStateScope` remains immutable policy/routing/authorization/migration-fence evidence", + "is exact-validated alongside that identity, and is not a uniqueness discriminator", + "`resumeWindowId` identity", ], ) -require_absent( +for resume_identity_path in ( + "design/architecture/system-architecture-scripting-scheduler-and-timers.md", + "design/architecture/decisions/adr-0072-class-specific-timer-durability-and-recovery.md", + "design/architecture/decisions/adr-0091-class-specific-script-timer-clocks-and-recovery.md", + "design/architecture/system-architecture-scripting-normative-contract-tables.md", + "design/architecture/system-architecture-scripting-dsl-for-designers.md", +): + resume_identity_text = (root / resume_identity_path).read_text(encoding="utf-8") + if obsolete_scope_resume_window_identity.search(resume_identity_text): + raise SystemExit( + f"{resume_identity_path}: contains a scope-based resume-window identity tuple" + ) +require_contains( "design/architecture/system-architecture-scripting-dsl-for-designers.md", [ - "`resumeWindowId` identified by ``", + "`resumeWindowId` identified by ``", + "one-tenant, one-mode ID", + "the server-derived `playableStateScope` is retained as immutable policy/routing/authorization/fence evidence and is exact-validated alongside that identity", ], ) require_contains( "design/architecture/decisions/adr-0072-class-specific-timer-durability-and-recovery.md", [ - "resume-window record per runtime scope, epoch, and `isDryRun` mode", - "`resumeWindowId` is the exact tuple ``", + "resume-window record per playable-state namespace/runtime scope, epoch, and `isDryRun` mode", + "`resumeWindowId` is the exact tuple ``", + "the server-derived `playableStateScope` is retained and exact-validated as immutable policy/routing/authorization/fence evidence, not as a uniqueness input", "each prior epoch's `OPEN` resume window, independently for each `isDryRun` mode", + "the target window must exclude them and cannot rediscover or remint their pending work under new candidate, firing-claim, or event identities", + "This does not prevent the target window from selecting independently reconciled candidates under the new exact pin", + ], +) +require_contains( + "design/architecture/system-architecture-ticks.md", + [ + "stable continuity identity is mode-qualified as `(isDryRun, {stableOwnerKind, stableOwnerId, scheduleDefinitionId, playableStateNamespaceId, targetScopeType, targetScopeId})`", + "[Scripting Scheduler and Timers](./system-architecture-scripting-scheduler-and-timers.md#target-state-design) under [ADR 0110]", ], ) require_contains( "design/architecture/system-architecture-scripting-normative-contract-tables.md", [ - "resume window identified by ``", - "Durable compare-and-set creates or reuses one `OPEN` window per runtime scope, epoch, and `isDryRun` mode", + "resume window identified by ``", + "Durable compare-and-set creates or reuses one `OPEN` window per namespace/runtime identity, epoch, and `isDryRun` mode", + "the server-derived `playableStateScope` is retained as immutable exact-validated policy/routing/authorization/migration-fence evidence for that window and is excluded from its identity, with missing or mismatched evidence fencing admission", ], ) +for non_resume_scope_fixture in ( + "", + "", +): + if obsolete_scope_resume_window_identity.fullmatch(non_resume_scope_fixture): + raise SystemExit( + "non-resume-window scope validation tuple was incorrectly rejected: " + f"{non_resume_scope_fixture}" + ) +for obsolete_resume_identity_fixture in ( + "", + "", + ( + "" + ), +): + if obsolete_scope_resume_window_identity.fullmatch(obsolete_resume_identity_fixture) is None: + raise SystemExit( + "scope-based resume-window identity fixture was not rejected: " + f"{obsolete_resume_identity_fixture}" + ) +canonical_resume_identity_fixture = ( + "" +) +if obsolete_scope_resume_window_identity.fullmatch(canonical_resume_identity_fixture): + raise SystemExit("canonical namespace-owned resume-window identity was rejected") require_contains( - "design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md", + "design/architecture/system-architecture-scripting-normative-contract-tables.md", [ "The canonical scheduler preimage fields are serialized in this fixed order:", "`resumeWindowId` is absent for non-catch-up triggers", "Fields marked `when ...` are omitted, not replaced by empty or sentinel values", ], ) -adr0001 = ( +require_contains( + "design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md", + [ + "[Table 1's Scheduler Candidate Identity Preimage](../system-architecture-scripting-normative-contract-tables.md#scheduler-candidate-identity-preimage-normative)" + ], +) +normative_contract_tables = ( root - / "design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md" + / "design/architecture/system-architecture-scripting-normative-contract-tables.md" ).read_text(encoding="utf-8") preimage_matches = re.findall( r"The canonical scheduler preimage fields are serialized in this fixed order: `([^`]+)`", - adr0001, + normative_contract_tables, ) if len(preimage_matches) != 1: raise SystemExit( - "adr-0001-scripting-event-ingress-idempotency-identity.md: expected exactly one canonical scheduler preimage" + "system-architecture-scripting-normative-contract-tables.md: expected exactly one canonical scheduler preimage" ) expected_scheduler_preimage = [ "tenantId", "gameInstanceId", - "playableStateScope", + "playableStateNamespaceId", "stableOwnerKind", "stableOwnerId", "regionId", @@ -1988,7 +2169,7 @@ actual_scheduler_preimage = [ ] if actual_scheduler_preimage != expected_scheduler_preimage: raise SystemExit( - "adr-0001-scripting-event-ingress-idempotency-identity.md: canonical scheduler preimage fields/order drifted" + "system-architecture-scripting-normative-contract-tables.md: canonical scheduler preimage fields/order drifted" ) specialized_inventory = ( root / "design/project-management/design-alignment/decision-inventory-specialized-runtime.md" @@ -2050,6 +2231,7 @@ require_contains( "bounded batches per complete recovery scope ``", "fairness cursors and deficit/cost accounting are keyed by the complete recovery scope", "service startup for each complete recovery scope", + "`entity_enqueue_seq` is allocated monotonically within the complete allocation scope `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch, entityId)`", ], ) require_absent( @@ -2058,6 +2240,79 @@ require_absent( "bounded batches per ``", "scheduling across regions rather than draining one region completely", "service startup for each region to converge", + "complete allocation scope `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch)`", + ], +) +for tick_commit_path in ( + "design/architecture/system-architecture-tick-execution-flows.md", + "design/architecture/system-architecture-ticks.md", +): + require_contains( + tick_commit_path, + [ + "current-epoch commit predicate: terminal (`APPLIED` or `ABANDONED`) evidence", + "every eligible ledger row in that tick's complete expected current-epoch participant set", + "Inconclusive old-epoch rows remain non-terminal reconciliation work outside this current-epoch commit predicate", + "may still block unsafe next-tick progression, reset-scope convergence, or reopening", + ], + ) + require_absent( + tick_commit_path, + [ + "every required participant in that tick's complete expected current-epoch participant set", + "An inconclusive old-epoch row remains non-terminal and blocks this advancement", + "inconclusive old-epoch work remains non-terminal and prevents this boundary", + ], + ) + +require_contains( + "design/architecture/system-architecture-ticks.md", + [ + "every eligible ledger row in that tick's complete expected current-epoch participant set", + "Required-versus-optional classification affects command-result aggregation, not tick commit", + "`entity_enqueue_seq` is allocated within the complete entity scope `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch, entityId)`", + ], +) +require_contains( + "design/architecture/system-architecture-scripting-examples-and-patterns.md", + [ + "The current authenticated receiving RPCs fail closed with `FAILED_PRECONDITION` (`automation_admission_receiver_fence_unavailable`) before mutation", + "prove neither local tick-queue acceptance nor remote follow-up scheduling", + "the target Trigger Identity additionally requires `playableStateNamespaceId`, which current `TriggerScriptEventRequest` does not carry", + "The current request carries `playableStateScope` separately as exact-validated policy/routing/authorization/migration-fence evidence, not as an identity field", + "**Target-state audit contract:** An audit record is written to `script_event_audit` for each resolved handler Trigger Identity", + "Current `TriggerScriptEventRequest` has no `playableStateNamespaceId`; its `playableStateScope` remains separate evidence and cannot substitute for the target namespace identity", + ], +) +require_absent( + "design/architecture/system-architecture-scripting-examples-and-patterns.md", + [ + "For same-scope targets, `ENQUEUED` means Game Session accepted the command into the local tick queue", + "for distinct target scopes, `REMOTE_SCHEDULED` means only that the remote follow-up was scheduled", + ], +) +require_contains( + "design/architecture/system-architecture-tick-incident-runbook.md", + [ + "if none is available, preserve any active broader containment, block further mutations, mark exact containment unverified, and escalate", + "current-live [executor fencing/drain gate](#act-stalled-tick-region)", + ], +) +require_contains( + "design/architecture/system-architecture-gateway.md", + [ + "Before normal release, old Gateway replay writers must be drained or authoritatively blocked", + "the complete tagged replay state and readiness/fence state must be authoritative", + "If any old-version writer or admission remains allowed, release additionally requires a separately proven cross-version guard", + "none is currently implemented or proven, so that mixed-version release path remains forbidden", + ], +) +require_contains( + "design/architecture/system-architecture-redis-ops-access.md", + [ + "Quarantine release and Cache-reset admission remain fail-closed until the [Gateway replay-quarantine release gate](./system-architecture-gateway.md#tenant-aware-edge-connect-token-gameplay-handshake) is proven", + "the current untagged replay state and generic writer do not satisfy it", + "If old-version writers/admission cannot be excluded, release additionally requires a separately proven cross-version guard, which is not currently implemented or proven", ], ) @@ -2070,6 +2325,9 @@ automation_runtime = ( game_design_version_control = ( root / "design/architecture/microservices/game-design-service/version-control.md" ).read_text(encoding="utf-8") +game_design_operations = ( + root / "design/architecture/microservices/game-design-service/operations.md" +).read_text(encoding="utf-8") deployment_environments = ( root / "design/architecture/infrastructure/deployment-environments.md" ).read_text(encoding="utf-8") @@ -2201,6 +2459,574 @@ for path, text in ( if term not in text: raise SystemExit(f"{path}: missing Game Design V26 rollout-compatibility term {term!r}") +for term in ( + "This implemented success path is behind the required participant digest gate", + "ordinary full-version requests currently cannot reach it because Game Logic rejects the required full-version participant request", + "script-patch publication does not require the Game Logic participant", + "[Version Control](./version-control.md#owner-to-owner-digest-authorization-and-tenant-identity)", +): + if term not in game_design_operations: + raise SystemExit( + "design/architecture/microservices/game-design-service/operations.md: " + f"missing full-version publication availability qualification {term!r}" + ) + +require_contains( + "design/architecture/system-architecture-tick-incident-runbook.md", + [ + "record execution results in PR/CI evidence, and update the owning implementation tracker when capability or proof status changes", + ], +) +require_absent( + "design/architecture/system-architecture-tick-incident-runbook.md", + ["record execution results in PR/CI evidence or the owning implementation tracker"], +) +require_contains( + "design/architecture/system-architecture-scripting-runtime-execution.md", + [ + "one `script_work_items` row carries the applicable identity from the pre-DSL trigger through evaluation and handoff processing", + "separate evaluated-work-item records and descriptor replay remain target-state only", + ], +) +require_contains( + "design/architecture/decisions/adr-0091-class-specific-script-timer-clocks-and-recovery.md", + [ + "A stale or mismatched presented scope fails closed for reuse until authoritative evidence is reconciled and exact validation succeeds", + "Only reconciled matching scope with unchanged authority may reuse the existing namespace-keyed identity", + "an authority-proven scope transition starts a new playable-state lifecycle and namespace", + "[Timer Resume Rule](../system-architecture-scripting-scheduler-and-timers.md#timer-resume-rule-normative)", + ], +) +require_absent( + "design/architecture/decisions/adr-0091-class-specific-script-timer-clocks-and-recovery.md", + ["stale presented scope with unchanged authority may reuse the existing identity"], +) + +require_contains( + "design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md", + [ + "Under this proposal, a command root's enclosing root would be its own persisted `EffectId`", + "its parent would be explicitly absent (`null`)", + "retry and replay would reuse the same scalar and binding", + ], +) +require_contains( + "design/architecture/microservices/automation-scripting-service/sandbox-runtime-design.md", + [ + "source tenant/game-instance ownership (`tenantId`, `gameInstanceId`) and `playableStateNamespaceId`/region identity", + "optional distinct target game-instance ownership and namespace/region identity", + "[normative Command-Handoff Identity](../../system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state)", + ], +) +require_contains( + "design/architecture/microservices/world-management-service/world-creation-workflow.md", + [ + "canonical Temporal workflow ID is `world-lifecycle::game-instance:`, stable per `(tenantId, gameInstanceId)`", + ], +) +require_contains( + "design/architecture/system-architecture-temporal-workflows.md", + [ + "for World lifecycle it is `game-instance`", + "For World lifecycle it is `gameInstanceId`, a domain identity scoped by `tenantId` and `scopeKey`, not necessarily a globally unique token", + "`world-lifecycle` uses `gameInstanceId` as its business key within the `tenantId` and `game-instance` scope", + ], +) +require_contains( + "design/architecture/system-architecture-tick-incident-runbook.md", + [ + "Before a maintenance verifier CAS may mutate a ledger row, validate the exact ADR 0085 external maintenance handoff", + "An owner may omit that maintenance handoff only for a specifically classified non-conflicting routine replay with durably recorded classification/evidence and applicable fence, epoch, and scope proof", + "never infer this exemption from owner, epoch, executor, manifest, or participant proof alone", + ], +) +require_contains( + "design/architecture/system-architecture-transactions.md", + [ + "authoritative evidence proves no committed batch, effect materialization, or application", + "ingress status or a missing batch ID alone is insufficient", + "Otherwise the command remains unresolved for evidence-qualified reconciliation", + ], +) +require_contains( + "design/architecture/system-architecture-transactions.md", + [ + "For spatial or ambient maintenance or reset mutations invoked through either API", + "including in recovery paths that perform maintenance or reset mutations", + "Ordinary owner-local routine replay or reconciliation outside maintenance and reset may preserve the original `EffectId` only when the owner has explicitly classified it as non-conflicting and the recorded exemption matches.", + ], +) +require_absent( + "design/architecture/system-architecture-transactions.md", + [ + "For spatial or ambient maintenance, recovery, or reset mutations invoked through either API", + ], +) +require_contains( + "design/architecture/system-architecture-redis-ops-access.md", + [ + "stream publication uses `XADD` with bounded `MAXLEN` as a best-effort coordination hint, not durable stream or work authority", + "[Tick Events & Heartbeat Stream](./system-architecture-ticks.md#tick-events--heartbeat-stream)", + "its workload-facing principal is read-only (`GET`) for offset keys", + "absent that registration Automation uses the owner API/heartbeat contract and receives no direct stream or offset grant", + ], +) +require_contains( + "design/architecture/system-architecture-redis.md", + [ + "every eligible ledger row in that tick's complete expected current-epoch participant set", + "required-versus-optional classification affects command-result aggregation, not tick commit", + "serialized scheduler payloads use `regionEpoch`, while the tick-event offset record uses `region_epoch`", + "Each serialized value must include `{tenantId, gameInstanceId, regionId, consumerId, region_epoch, latestTickId, streamOffset}`", + "The producer and reader remain unimplemented", + ], +) +require_contains( + "design/architecture/system-architecture-gateway.md", + [ + "logical typed Gateway-owned probe", + "one pinned Coordination Redis connection", + "While shared readiness remains `QUARANTINED`", + "disposable marker at `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::`", + "then immediately issues configured `WAITAOF` on that same connection with no intervening write", + "Cleanup is a separate exact-operation/fence-guarded write and readback after acknowledgement and evidence readback", + "does not accept or consume a player JWT, real `jti` replay marker, or browser-deny marker", + "Normal player consume remains `OPEN`-only and is never invoked during quarantine", + "only the coordinator may authorize reopening after the deadline, exact fenced probe evidence, and all other owner release gates succeed", + "callers cannot supply key material or redirect a probe to player replay/deny prefixes", + "Its marker uses a finite bounded expiry", + "Gateway's owner-local helper performs the readiness compare-and-set", + "The operation and its producer/consumer proof are currently unimplemented", + ], +) +require_contains( + "design/architecture/system-architecture-redis-ops-access.md", + [ + "require Gateway's typed recovery probe over the existing authenticated owning-service transport boundary only; that boundary provides authenticated transport, but no recovery endpoint is implemented while shared readiness remains `QUARANTINED`", + "Existing ACL-denial probes may also run through the documented isolated disposable/protected harness", + "key-scoped denials use a protected probe namespace that cannot contain shared deployment data", + "`FLUSHALL`, `FLUSHDB`, and `SCRIPT FLUSH` denials run only against an isolated disposable target with required cleanup/readback and never real tick state", + "Normal player consume remains `OPEN`-only and is not invoked for this recovery proof", + "timeout, malformed, below-threshold, or uncertain results fail closed", + "This probe remains target-only and unimplemented, so the checklist is not yet executable for this gate", + "[ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md)", + "[Gateway replay readiness](./system-architecture-gateway.md#tenant-aware-edge-connect-token-gameplay-handshake)", + "[reset policy matrix](./system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary)", + ], +) +require_absent( + "design/architecture/system-architecture-redis-ops-access.md", + ["a fresh canonical replay-consume invocation on the same pinned Redis connection"], +) +require_contains( + "design/architecture/system-architecture-redis.md", + [ + "Gateway owns only the shared replay-domain exception: `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, and the separately registered recovery-only `gateway:connect-token:{gateway-connect-token-replay-v1}:probe:*`", + "Participant-guard uniqueness also includes the owner-declared runtime-family partition: S1/S2 use `(tenantId, playableStateNamespaceId)`, while only explicitly declared S3 uses `(tenantId, gameInstanceId)`; unknown or unclassified families fail closed.", + "The immutable `requestDigest` binds that identity but is not a uniqueness field or partition substitute; other scope and tick values remain exact evidence.", + ], +) +require_contains( + "design/architecture/decisions/adr-0011-gameplay-session-front-end-and-region-execution.md", + [ + "## Supersession\n\n- Replacement ADR: [ADR 0170](./adr-0170-fenced-command-forwarding-and-authoritative-region-transition.md)", + ], +) +require_contains( + "design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md", + [ + "## Supersession\n\n- Replacement ADR: [ADR 0172](./adr-0172-parent-event-and-frozen-handler-execution-identity.md)", + ], +) +require_contains( + "design/architecture/decisions/adr-0009-coordination-redis-ownership-boundary.md", + [ + "Gateway Service owns the exact connect-token replay, browser-deny, readiness/fence, and recovery-probe key families in the pinned `gateway-connect-token-replay-v1` domain: `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`, `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::`, as defined by [ADR 0029](./adr-0029-single-use-gameplay-connect-token-carriage.md).", + "These are bounded Gateway-owned replay and recovery records, not wildcard access or a broader non-owner participation grant.", + ], +) +require_contains( + "design/architecture/microservices/game-design-service/operations.md", + [ + "`VersionPublishCommandServiceImpl` normally records terminal `FAILED` and returns the attempt snapshot for publication failures; `TemporalVersionPublishActivitiesImpl` catches only `PendingReconciliationException` and returns `PENDING`.", + ], +) +require_contains( + "design/architecture/system-architecture-gateway.md", + [ + "When the latest expiry of an affected token is known, the quarantine deadline also covers that token's `exp + firemud.gateway.connectTokenClockSkewMs`; the deadline is the later of these bounds, and admission must never reopen before it.", + "This deadline rule is defined by [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md).", + ], +) +require_contains( + "design/architecture/system-architecture-identifier-glossary.md", + [ + "The owner must allocate and durably persist each generated child's ordinal and owner-scope/root/parent/ordinal-to-child-`EffectId` mapping under the accepted owner contract; deterministic child-ID derivation is only proposed by pending [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) and is not current target.", + ], +) +require_contains( + "design/architecture/system-architecture-transactions.md", + [ + "Any handoff or recovery path that performs maintenance or reset mutation on this barrier must carry the unchanged [ADR 0085](./decisions/adr-0085-evidence-gated-coordination-replay-and-fenced-reset.md) external maintenance handoff: exact `operationId`, external maintenance fence/lock binding, classifier, immutable evidence digest, and complete affected scope.", + "`OwnerRoutineReplayExemption` is available only for explicitly classified, non-conflicting ordinary owner-local routine replay or reconciliation outside maintenance and reset; it cannot authorize these mutations.", + "A missing or mismatched handoff leaves the barrier `RECONCILIATION_REQUIRED` and fails closed.", + ], +) +require_contains( + "design/architecture/system-architecture-redis-ops-access.md", + [ + "Gateway's typed readiness-probe operation", + "[Gateway replay readiness](./system-architecture-gateway.md#tenant-aware-edge-connect-token-gameplay-handshake)", + "currently unimplemented, so the checklist is not yet executable for this gate", + "The probe runs while shared readiness remains `QUARANTINED`", + "Only the recovery coordinator may authorize reopening after the deadline, exact fenced probe evidence, and every other release gate", + ], +) +require_contains( + "design/architecture/decisions/adr-0029-single-use-gameplay-connect-token-carriage.md", + [ + "trusted recovery coordinator invokes Gateway's separate typed recovery probe through Gateway's existing authenticated owner-maintenance boundary while shared readiness remains `QUARANTINED`", + "Gateway-generated disposable marker under `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::`", + "This probe neither accepts nor consumes a player JWT, real `jti` replay marker, or browser-deny marker, and it never writes shared readiness", + "Gateway's owner-local helper alone performs the fenced compare-and-set to `state=OPEN`", + "The coordinator does not receive raw Redis authority", + "callers cannot supply a key, nonce, player `jti`, or marker value", + "The probe marker has a finite bounded expiry", + "Gateway immediately issues the configured `WAITAOF` acknowledgement on that same pinned connection with no intervening write", + "Only after that acknowledgement and evidence readback may cleanup run as a separate exact-fence-guarded write with readback", + "The probe operation and its producer/consumer proof are target-only and currently unimplemented", + ], +) +require_contains( + "design/architecture/system-architecture-redis-reset-and-recovery.md", + [ + "`gateway:connect-token:{gateway-connect-token-replay-v1}:probe::`", + "While readiness remains `QUARANTINED`, the trusted recovery coordinator invokes Gateway's separate typed probe", + "Only the recovery coordinator may authorize reopening after the deadline, exact fenced probe evidence, and every other owner release gate", + "Gateway owns the probe key, nonce, and marker value; callers cannot redirect it to a player `jti` or deny prefix", + "The probe marker has a finite bounded expiry", + "no current deny-marker, readiness, replay-fence, or recovery-probe writer", + ], +) +require_contains( + "design/architecture/system-architecture-redis-ops-access.md", + [ + "`gateway:connect-token:{gateway-connect-token-replay-v1}:probe:*` only", + "it neither consumes player credentials nor writes shared readiness", + "immediately issues configured `WAITAOF` on that connection with no intervening write", + "guarded cleanup/readback follows the acknowledgement", + ], +) +require_contains( + "design/architecture/system-architecture-redis-cheatsheet.md", + [ + "`gateway:connect-token:{gateway-connect-token-replay-v1}:probe::`", + "The typed probe runs only while shared readiness is `QUARANTINED`", + "Gateway alone supplies its exact key/nonce/value; callers cannot redirect it to player keys", + "The marker has a finite bounded expiry", + "Gateway's owner-local helper performs the readiness CAS through its authenticated maintenance API", + "The probe is currently unimplemented", + ], +) +require_contains( + "design/architecture/system-architecture-redis.md", + [ + "a separate Gateway-generated disposable recovery-probe marker", + "The probe marker is not a player `jti` or deny marker", + "Normal consume is never called during quarantine", + "the recovery coordinator alone may reopen after exact fenced proof and all owner gates", + ], +) +require_contains( + "design/architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md", + [ + "owner-defined child ordinal allocated and persisted by the owning contract for replay-stable reuse", + "Persisted lineage, owner-defined ordinals, digests, and accounting make admission and suppression replay-stable", + "owner-scope/root/parent/ordinal mapping to each child `EffectId` is one atomic durable admission record", + ], +) +require_contains( + "design/architecture/decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md", + [ + "recorded owner-allocated child ordinals", + "owner-defined ordinal and durable owner-scope/root/parent/ordinal-to-child-`EffectId` mapping are mandatory and replay-stable under accepted [ADR 0075]", + "Only scalar choices and additional allocator mechanics remain pending in [ADR 0183]", + "owner-allocated persisted child ordinals and replay-stable mappings", + ], +) +require_contains( + "design/architecture/system-architecture-scripting-dsl-reference-and-lifecycle.md", + [ + "Only after all applicable handler-scoped gates pass does each admitted resolved handler create a durable parent work item", + "A trigger with no admitted handlers creates no parent work items", + "The exact per-handler gates remain owned by [Normative Table 2]", + ], +) +require_contains( + "design/architecture/system-architecture-tick-execution-flows.md", + [ + "The coordinator and origin-addressed result also retain the complete original source scope", + "originPlayableStateNamespaceId", + "originPlayableStateScope", + "The current live coordinator and result projection schemas do not yet carry the complete source and target tuples", + "this remains target-state contract, not a claim of schema implementation", + ], +) +require_contains( + "services/spring-cloud-gateway/src/main/resources/openapi.yaml", + [ + "Current REST route mutations require a Bearer JWT accepted by the gateway's", + "privileged-role predicate, which currently accepts global or tenant-scoped", + "acceptance of tenant-scoped roles is implementation drift", + "The target management contract requires exact operator authentication and", + "global privileged authorization on an internal dev/test-only surface", + ], +) +require_contains( + "design/architecture/system-architecture-redis-usage-and-profiles.md", + [ + "This projection responsibility does not assign the current physical `gameplaypresence:session:` or `accountrecentpresence::` prefixes to the Coordination Redis role", + "their storage-role classification and target key contract remain unproven", + ], +) +require_contains( + "design/architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md", + [ + "Derived reactions retain their owner-defined child ordinal", + "complete owner-scope/root/parent/ordinal-to-child-`EffectId` mapping before enqueue/apply", + "This accepted child-identity contract is owned by [ADR 0075]", + "Pending [ADR 0183]", + "it does not gate or redefine the accepted child mapping", + ], +) +require_contains( + "design/architecture/decisions/README.md", + [ + "Depth, cost, and count bounds with replay-stable owner-defined child identity and lineage", + "Pending command-plan ordering, `planOrdinal`, command-root allocation, UUIDv7 scalar, canonical serialization, and additional child/fan-out allocation mechanics", + ], +) +require_absent( + "design/architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md", + ["Derived reactions use deterministic child effect identities"], +) +require_absent( + "design/architecture/decisions/README.md", + ["generated-child/fan-out allocation design"], +) +require_contains( + "design/architecture/microservices/entity-management-service/runtime-and-data.md", + [ + "a conflict-safe marker insert or a same-transaction savepoint around marker handling", + "preserving marker/mutation atomicity and never isolating marker insertion in a separate transaction", + "[Entity Management Operations implementation status](./operations.md#implementation-status)", + "Real PostgreSQL concurrent first-apply/replay proof remains unavailable", + ], +) +require_absent( + "design/architecture/microservices/entity-management-service/runtime-and-data.md", + ["a conflict-safe marker insert or isolated marker transaction"], +) +require_contains( + "design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md", + [ + "The live result-inbox path has partial late-result handling", + "serialized result-versus-timeout arbitration, immutable terminal/retry proof, and documented compensation ownership remain unimplemented or unproved", + "See the canonical owner contracts immediately above for target sequencing, terminal outcomes, and compensation", + ], +) +require_absent( + "design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md", + ["the owner must reconcile durable results before timeout, require matching scope/epoch evidence"], +) +require_contains( + "design/architecture/system-architecture-scripting-scheduler-and-timers.md", + [ + "The end-to-end lifecycle and reload behavior in this target-state section", + "**Target state only:** Redis timer indexes, scheduler progress hints, queue pointers", + "This reload sequence is target-state behavior", + "current PostgreSQL schedule-definition and schedule-instance substrate", + ], +) +require_contains( + "design/architecture/system-architecture-redis-lua-patterns.md", + [ + "While an untagged legacy `jti` marker may still represent a token accepted in its original window, replay admission remains blocked.", + "absence of a tagged target key alone never proves the legacy token unused", + "Resolving that continuity condition does not release quarantine: all ADR 0029 deadline, exact fenced probe, old-writer, and owner release gates still apply.", + ], +) +require_contains( + "design/architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md", + [ + "the original positive `reservationClaimFence` stored in that tuple", + "its fresh reservation/recovery claim and fence are separate, independently validated execution authority", + "they do not replace or rewrite the original tuple fence", + "Exact tuple comparison and current owner/fence validation remain required before evaluation, dispatch, or reference delivery", + "This CAS and enrichment preserve the original reservation claim fence as immutable tuple evidence", + "the separately current fresh reservation/recovery claim and fence before redeeming the exact reference", + ], +) +require_absent( + "design/architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md", + ["`reservationOwnerId`, current positive `reservationClaimFence`"], +) +require_contains( + "design/architecture/microservices/game-session-service/runtime-and-data.md", + [ + "Failures before the durable `STAGED` update leave the command `ACCEPTED`", + "failures after that update and before durable `tick_batch`/`tick_effect` creation can leave `STAGED` without a batch/effect", + "there is no recovery path for a `STAGED` command without a corresponding `tick_batch`/`tick_effect`", + ], +) +require_absent( + "design/architecture/microservices/game-session-service/runtime-and-data.md", + ["A crash or Redis loss in either window can strand a `STAGED` command"], +) +require_contains( + "design/architecture/system-architecture-tick-incident-runbook.md", + [ + "ledger backlog does not authorize replay-controller remediation on the current-live branch", + "Target-state deployments may trigger replay-controller remediation only after the capability/proof gate", + "[Ledger Replay Controller](./system-architecture-tick-failures-and-operations.md#ledger-replay-controller)", + ], +) +require_absent( + "design/architecture/system-architecture-tick-incident-runbook.md", + ["If ledger backlog also accumulates, trigger ledger replay-controller remediation"], +) +require_contains( + "design/architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md", + [ + "atomic owner-defined CAS/version-fenced transition on the authoritative command record", + "if concurrent staging wins, the loss transition affects zero rows", + "positive authoritative evidence that no batch committed, no effect was materialized, and no domain application occurred", + "ingress status or a missing batch/effect identifier alone is insufficient", + "[Transactions](../system-architecture-transactions.md)", + "[Tick Failures and Operations](../system-architecture-tick-failures-and-operations.md)", + ], +) +require_absent( + "design/architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md", + ["with no surviving durable `tickBatchId`, effect ledger, or source/effect claim"], +) +require_contains( + "design/architecture/microservices/game-design-service/modding-framework.md", + [ + "complete owner-defined participant binding", + "Any participant-binding, operation, target, or digest conflict fails closed", + "[Transactions guard contract](../../system-architecture-transactions.md)", + "[ADR 0069](../../decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md)", + ], +) +require_contains( + "design/architecture/system-architecture-redis-cheatsheet.md", + [ + "the later of the detection-time deadline (the 30-second maximum token lifetime plus two configured clock-skew intervals) and any later known affected-token `exp` plus one clock-skew interval", + "Admission remains closed until that deadline passes and the required fresh disposable-marker, durability-acknowledgement, and shared readiness proof succeeds", + "[ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md)", + ], +) +require_contains( + "design/architecture/system-architecture-redis.md", + [ + "shared readiness quarantined under an advanced `replayAdmissionFence`", + "during that quarantine, an absent `jti` marker alone never proves first use", + "[ADR 0029 readiness proof](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md)", + ], +) +require_contains( + "design/architecture/system-architecture-redis.md", + [ + "the target `session:connect-token:v1:*` exact-input issuance-result projections", + "The current legacy result map remains a separate unversioned `session:connect-token:*` family", + "both families remain Account-owned", + "Gateway owns only the shared replay-domain exception", + "it never owns the Account auth or connect-token issuance prefixes", + ], +) +require_absent( + "design/architecture/system-architecture-redis.md", + ["the target `session:connect-token:*` exact-input issuance-result projections"], +) +require_contains( + "design/architecture/system-architecture-redis-incident-runbook.md", + [ + "**Target state only, once the canonical gated coordination-maintenance operation is implemented and proven:** Execute the [Canonical Coordination Reset Sequence]", + "**Current deployments:** Do not execute the reset or mutate raw coordination keys. Preserve evidence, keep the affected scope fenced or stopped, use only the shipped `PauseTicksForScope` / `GetRuntimeOwnershipStatus` boundary and `coord_ops_ro` read-only inspection, then follow the [Current Operator Fallback]", + ], +) +require_contains( + "design/architecture/system-architecture-redis-ops-access.md", + [ + "require Gateway's typed recovery probe over the existing authenticated owning-service transport boundary only; that boundary provides authenticated transport, but no recovery endpoint is implemented", + "This probe remains target-only and unimplemented", + ], +) +require_contains( + "design/architecture/system-architecture-scripting-contracts.md", + [ + "parent `outboxWorkItemId` is retained only as correlation and is not part of that identity", + "applicable distinct target runtime fields (`targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetRegionId`, `targetRegionEpoch`)", + "[Table 2 identity owner](./system-architecture-scripting-normative-contract-tables.md#table-2-command-handoff-identity)", + ], +) +require_absent( + "design/architecture/system-architecture-scripting-contracts.md", + ["complete Command-Handoff Identity, including `outboxWorkItemId` as parent correlation"], +) +require_contains( + "design/architecture/system-architecture-scripting-normative-contract-tables.md", + [ + "Core-owned schedules include their schedule-owned `scriptId`; plugin-owned schedules use their schedule-owned `pluginId`, `pluginVersionId`, and `bindingId` without adding a synthetic `scriptId`", + "`scheduleDefinitionId` participates in the stable logical continuity key and the complete durable row/trigger-claim identity, but is never sufficient as a standalone row or claim identity", + ], +) +require_absent( + "design/architecture/system-architecture-scripting-normative-contract-tables.md", + ["The logical identity therefore includes schedule-owned `scriptId` and any schedule-owned `pluginId`"], +) +require_contains( + "design/architecture/system-architecture-tick-concepts-and-invariants.md", + [ + "accept explicit caller-supplied `currentTickId`", + "the AOF records the script's write effects and restart replays those recorded commands", + "it does not rerun the Lua script with the original `ARGV` values", + "[Redis scripting and effects-replication documentation](https://redis.io/docs/latest/develop/interact/programmability/eval-intro/)", + ], +) +require_absent( + "design/architecture/system-architecture-tick-concepts-and-invariants.md", + ["AOF replay reuses the same arguments"], +) +require_contains( + "design/architecture/system-architecture-gateway.md", + [ + "While shared readiness remains `QUARANTINED`", + "Normal player consume remains `OPEN`-only and is never invoked during quarantine", + "only the coordinator may authorize reopening after the deadline, exact fenced probe evidence, and all other owner release gates succeed", + "issuance and player admission remain closed", + "not a new public RPC or an implemented operation", + ], +) +require_contains( + "design/architecture/system-architecture-redis-usage-and-profiles.md", + [ + "The checked Coordination configurations", + "do not set an internal Redis `maxmemory` bound", + "Every non-ephemeral Coordination Redis profile must configure an explicit finite positive Redis `maxmemory` bound", + ], +) +require_contains( + "design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md", + [ + "Proposed - Pending Human Review", + "Every clause in this Decision section is a proposal, conditional on human acceptance", + "do not extend the independently accepted owner-defined child ordinal and durable owner-scope/root/parent/ordinal-to-child-`EffectId` mapping", + "This exact scalar format is not an accepted cross-service requirement today", + ], +) + print("architecture doc contracts passed") PY diff --git a/dev-tools/validation/check-design-capability-allocation.py b/dev-tools/validation/check-design-capability-allocation.py index 50c106047f..9c543175a1 100644 --- a/dev-tools/validation/check-design-capability-allocation.py +++ b/dev-tools/validation/check-design-capability-allocation.py @@ -684,6 +684,15 @@ def adr_allocation(primary: str, classification: str, *secondary: str) -> tuple[ "design/architecture/decisions/adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md": adr_allocation( "PO-3", "Accepted", "PO-1", "PO-4", "SF-1" ), + "design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md": adr_allocation( + "GR-1", + "Proposed - Pending Human Review", + "GR-4", + "AS-1", + "SF-1", + "SF-2", + "PO-4", + ), "design/architecture/decisions/adr-0184-emergency-tcp-proxy-identity-withdrawal.md": adr_allocation( "SF-1", "Accepted", "PO-2", "PO-3", "PO-4" ), diff --git a/services/automation-scripting-service/src/main/resources/openapi.yaml b/services/automation-scripting-service/src/main/resources/openapi.yaml index aff8e55a67..73017e9e76 100644 --- a/services/automation-scripting-service/src/main/resources/openapi.yaml +++ b/services/automation-scripting-service/src/main/resources/openapi.yaml @@ -1,7 +1,10 @@ openapi: 3.0.3 info: title: Automation Scripting Service API - description: API for NPC automation and script management + description: >- + This OpenAPI document currently describes only the GET /ping health-check + endpoint; it defines no tenant- or subject-scoped operations or + authentication. version: 1.0.0 license: name: PolyForm Noncommercial License 1.0.0 diff --git a/services/game-session-service/src/main/resources/openapi.yaml b/services/game-session-service/src/main/resources/openapi.yaml index b7e7840e60..db419a6961 100644 --- a/services/game-session-service/src/main/resources/openapi.yaml +++ b/services/game-session-service/src/main/resources/openapi.yaml @@ -1,4 +1,4 @@ -openapi: 3.0.3 +openapi: 3.1.0 info: title: Game Session Service API description: API for managing active game sessions @@ -8,7 +8,8 @@ info: url: https://polyformproject.org/licenses/noncommercial/1.0.0 servers: - url: https://api.firemud.com -security: [] +security: + - bearerAuth: [] components: securitySchemes: bearerAuth: @@ -59,11 +60,34 @@ components: type: integer status: type: string + ResultStatus: + type: string + enum: [SUCCESS, ERROR] + ErrorDetail: + type: object + properties: + code: + type: string + message: + type: string + RefreshRolesResponse: + type: object + properties: + status: + $ref: '#/components/schemas/ResultStatus' + data: + type: string + example: refreshed + error: + oneOf: + - $ref: '#/components/schemas/ErrorDetail' + - type: 'null' paths: /ping: get: summary: Health check endpoint operationId: ping + security: [] responses: '200': description: Pong response @@ -99,6 +123,10 @@ paths: $ref: '#/components/schemas/GameInstanceDto' '400': description: Invalid request + '401': + description: Missing or invalid Bearer JWT + '403': + description: Caller lacks a privileged role under the current predicate /sessions/{sessionId}/stop: post: summary: Stop a running session @@ -121,6 +149,10 @@ paths: $ref: '#/components/schemas/GameInstanceDto' '400': description: Invalid session ID + '401': + description: Missing or invalid Bearer JWT + '403': + description: Caller lacks a privileged role under the current predicate /sessions/{sessionId}/restart: post: summary: Restart a stopped session @@ -143,3 +175,38 @@ paths: $ref: '#/components/schemas/GameInstanceDto' '400': description: Invalid session ID + '401': + description: Missing or invalid Bearer JWT + '403': + description: Caller lacks a privileged role under the current predicate + /sessions/{sessionId}/refresh-roles: + post: + summary: Acknowledge a session role refresh request + description: >- + Current behavior requires a privileged Bearer JWT and returns an + acknowledgement (`data: refreshed`); the service currently only logs + the request and does not refresh session roles. Target behavior is an + internal_workload route requiring the exact mTLS workload identity of + the allowlisted Logging & Admin Service, with no end-user token. That + target mTLS authorization and role-refresh mutation are not implemented + yet. + operationId: refreshRoles + parameters: + - in: path + name: sessionId + required: true + schema: + type: integer + responses: + '200': + description: ApiResponse acknowledgement; current implementation is a no-op + content: + application/json: + schema: + $ref: '#/components/schemas/RefreshRolesResponse' + '400': + description: Invalid session ID + '401': + description: Missing or invalid Bearer JWT + '403': + description: Caller lacks a privileged role under the current predicate diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/SessionRoleControllerTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/SessionRoleControllerTest.java index fca180be06..9a25c31569 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/SessionRoleControllerTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/SessionRoleControllerTest.java @@ -48,7 +48,8 @@ void refreshRolesReturnsOk() throws Exception { HttpHeaders.AUTHORIZATION, "Bearer " + PlatformAdminJwtTestSupport.privilegedToken(jwtUtil))) .andExpect(status().isOk()) - .andExpect(jsonPath("$.data").value("refreshed")); + .andExpect(jsonPath("$.data").value("refreshed")) + .andExpect(jsonPath("$.error").value(org.hamcrest.Matchers.nullValue())); } @Test diff --git a/services/logging-admin-service/src/main/resources/openapi.yaml b/services/logging-admin-service/src/main/resources/openapi.yaml index 9cf5fac9db..301a5cc89e 100644 --- a/services/logging-admin-service/src/main/resources/openapi.yaml +++ b/services/logging-admin-service/src/main/resources/openapi.yaml @@ -1506,9 +1506,15 @@ components: paths: /ping: get: - summary: Health check endpoint + summary: Privileged HTTP health check endpoint + description: >- + Current HTTP behavior requires a privileged Bearer JWT through the + shared interceptor, whose `hasPrivilegedRole()` predicate accepts both + global and tenant-scoped privileged roles, so this is not proof of a + global-role-only boundary. The target Public/infra health + classification uses platform health policy; this route has not + converged to that exact target. operationId: ping - security: [] responses: '200': description: Pong response @@ -1516,6 +1522,10 @@ paths: application/json: schema: $ref: '#/components/schemas/ApiResponseString' + '401': + description: Missing or invalid Bearer JWT + '403': + description: Caller lacks a privileged role under the current predicate /command-registry/built-in-aliases/{alias}: get: summary: Validate one built-in command alias diff --git a/services/spring-cloud-gateway/src/main/resources/openapi.yaml b/services/spring-cloud-gateway/src/main/resources/openapi.yaml index 8132a3332e..916009491d 100644 --- a/services/spring-cloud-gateway/src/main/resources/openapi.yaml +++ b/services/spring-cloud-gateway/src/main/resources/openapi.yaml @@ -1,15 +1,26 @@ openapi: 3.0.3 info: title: Spring Cloud Gateway API - description: API for dynamic route management + description: >- + Current REST route mutations require a Bearer JWT accepted by the gateway's + privileged-role predicate, which currently accepts global or tenant-scoped + privileged roles; acceptance of tenant-scoped roles is implementation drift. + The target management contract requires exact operator authentication and + global privileged authorization on an internal dev/test-only surface. version: 1.0.0 license: name: PolyForm Noncommercial License 1.0.0 url: https://polyformproject.org/licenses/noncommercial/1.0.0 servers: - url: https://api.firemud.com -security: [] +security: + - bearerAuth: [] components: + securitySchemes: + bearerAuth: + type: http + scheme: bearer + bearerFormat: JWT schemas: GatewayRoute: type: object @@ -31,6 +42,7 @@ paths: get: summary: Health check operationId: ping + security: [] responses: '200': description: Pong response @@ -66,6 +78,10 @@ paths: $ref: '#/components/schemas/GatewayRoute' '400': description: Invalid route configuration + '401': + description: Missing or invalid Bearer JWT + '403': + description: Caller lacks a privileged role under the current predicate /routes/{routeId}: delete: summary: Remove a gateway route @@ -89,3 +105,7 @@ paths: example: removed '400': description: Invalid route ID + '401': + description: Missing or invalid Bearer JWT + '403': + description: Caller lacks a privileged role under the current predicate