diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 2a1d03f7ea..b614b2e7e0 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -2,7 +2,7 @@ ## Implementation Status -The source-first stage retains the published World fixture verifier, demo seeder and prepare/activate dispatch until the canonical runtime swap. The strengthened fixed capability and Game Design receipt remain required; the active verifier does not adopt the new canonical Game Session allocation read. This retention supplies no new canonical activation, admission, Entity placement or operational-region authority. The canonical run-owned ordering remains defined in [Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence); [the World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#canonical-fixture-launch-receiving-boundary) records candidate proof and remaining handoffs. +The source-first stage retains the published World fixture verifier, demo seeder and predecessor lifecycle dispatch while canonical preparation remains an explicit source operation. `RunOwnedCanonicalWorldLaunchEvidenceProvider` authenticates the canonical Game Session allocation; the package-private canonical preparation owner composes source/Version intake and fixed-preset materialization. The registered generic prepare RPC retains its predecessor behavior. Canonical activation, first admission, Entity placement and operational-region authority remain unavailable. [The World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status) records current proof and staging limits; [Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence) owns the complete target ordering. This API contract is target-state canonical; implementation coverage is partial and must not be inferred from target examples alone. @@ -14,6 +14,8 @@ This API contract is target-state canonical; implementation coverage is partial - The registered `ApplyWorldDesignMutation` RPC now fails closed with an error-only `FAILED_PRECONDITION` before request parsing, remote reads, or mutation-service dispatch because complete Draft caller/tenant authorization and owner publication proof are unavailable. The owner-local mutation algorithm remains present but is unreachable through this registered ingress. This containment does not implement the target authenticated Game Design caller/tenant authorization or the owner freeze below; the separate digest-read gap and legacy REST generation-rule gap remain open. - Required executable migration/proof gate: `./gradlew :world-management-service:test :game-logic-service:test :game-session-service:test :tcp-proxy-service:crossServiceTest`. This gate must update the bridge, callers, examples, and checked-in proof together and pass before the target examples below may be treated as current. This document does not claim that the gate exists or passes. +Canonical source intake and Version association revalidate the fixed Game Session URI, leaf and retained evidence before owner access. Authenticated remote reads precede the World owner transaction; the explicit canonical preparation operation retains independently allocated private keys and committed readback. It is separate from the retained bootstrap and generic prepare RPC. Canonical activation, hold acquisition/finalization and initial placement remain closed. The [storage contract](./runtime-and-data.md#fixed-fixture-preparing-owner) owns persistence; [the World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#fixed-fixture-source-and-version-owner-preparation) distinguishes historical composition proof from current qualification. + ## gRPC APIs - `GetRoom` – retrieves room data including exits and environmental effects through `RoomInstanceRef`. @@ -285,7 +287,7 @@ Operator procedure: use the scoped World reconciliation log fields to identify t The opt-in run-owned fixture is disabled by default. Target integration requires a fixed-server provider to independently read the immutable capability and source receipt, verify the authenticated same-namespace Game Session peer and World leaf/CA pins, and compare the exact Game Design descriptor and Game Session allocation before any World effect. Requests cannot select file paths, certificate identities or evidence. This boundary grants neither default-denied Game Design bundle/version/artifact RPC authority nor player admission. The complete wire and comparison contract belongs to [Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence). -The retained published demo seeder and fixture `PREPARING`/`ACTIVE` dispatch remain available for the predecessor bootstrap. Canonical World materialization and activation are not composed with the explicit canonical Game Session launch/read owner or the canonical initial-admission hold and first-`OPEN` path. The active `RunOwnedWorldLaunchEvidenceProvider` verifies the fixed capability and source receipt, authenticates the Game Session peer, and compares the Game Design launch descriptor; it does not read the canonical Game Session allocation. The separate canonical producer and fixed allocation read are described in the [Game Session API](../game-session-service/api-contracts.md#implementation-status). Retained fixture binding-digest and original preparing-epoch columns describe predecessor storage and do not authorize a new lifecycle transition or replay. Current capability and revision-specific proof are recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#canonical-fixture-launch-receiving-boundary). +The retained published demo seeder and fixture `PREPARING`/`ACTIVE` dispatch remain available for the predecessor bootstrap; the registered generic prepare RPC retains that path. The retained `RunOwnedWorldLaunchEvidenceProvider` supplies predecessor evidence. Explicit canonical source preparation instead uses `RunOwnedCanonicalWorldLaunchEvidenceProvider`, which authenticates and reads the actual canonical Game Session allocation, then the World owner composes source/Version intake with fixed-preset materialization. The qualified source/preparation proof is recorded in the [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#canonical-fixture-launch-receiving-boundary); canonical Game Session producer/read behavior is in the [Game Session API](../game-session-service/api-contracts.md#implementation-status). This qualified preparation does not establish canonical lifecycle activation, hold acquisition/finalization, or first `OPEN`, which remain unavailable here. Retained fixture binding-digest and original preparing-epoch columns describe predecessor storage and do not authorize a new lifecycle transition or replay. ## Instance Termination Contract diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index 67b9ec31a9..e0ceabade0 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -11,15 +11,27 @@ - The registered `ApplyWorldDesignMutation` handler now fails closed before its former remote Game Design Draft-state read or local mutation dispatch. The owner-local mutation algorithm remains in `WorldDesignMutationServiceImpl`, but no registered ingress reaches it; the owner has no durable version-freeze row, Game Design `versionStateEpoch`, or `publicationFence`. This is containment, not proof of Published-template immutability or completed write authorization. The target freeze/acknowledgement protocol is canonical in [Game Design Version Control](../game-design-service/version-control.md#publication-freeze-and-owner-handoff). - The target WMS publication owner contract, including `BeginVersionPublicationFreeze` and the outcome-typed `CompleteVersionPublication` terminal handoff, is specified in [World Management API Contracts](./api-contracts.md#publication-freeze-and-terminal-handoff-target-state). The current proto, DTOs, client adapter, persistence schema, handlers, and focused race/retry proof do not implement those surfaces: `ApplyWorldDesignMutation` still has no publication request, Game Design epoch, or WMS `publicationFence` fields. The registered RPC remains closed until the complete caller/tenant authorization and owner publication proof are implemented; no digest, preflight state read, or Temporal completion may be promoted to freeze or terminal owner evidence. - Procedural-generation persistence has a current identity gap: `V21__scoped_generation_rules.sql` creates a unique index over nullable `scope_type`/`scope_id`. Under PostgreSQL, multiple NULLs are distinct, so unscoped rows can duplicate the same `(tenant_id, version_id, name)` and destabilize deterministic generation-rule identity/digests. The current scope-aware repository lookup also compares nullable scope columns with SQL `=`, so it cannot retrieve an unscoped row. The target schema and mutation path must either prohibit unscoped rows or provide an explicit null-safe schema/query uniqueness contract, with focused proof; procedural-generation readiness remains blocked until that contract is enforced. -- The current termination command returns a `TERMINATED` snapshot before comparing the supplied `terminationRequestId`. A different request identity therefore appears successful instead of conflicting with the terminal operation. The target requires exact request-identity replay and fail-closed mismatch handling, with focused terminal retry/conflict proof; this remains an implementation/proof blocker. -- The current termination orchestration keeps the Entity Management cleanup RPC outside an open World transaction, preserves `TERMINATING` while remote cleanup or local finalization is incomplete, and commits local runtime-row cleanup with the `TERMINATED` lifecycle state in one local transaction. [WorldLifecycleCommandServiceImplTest](../../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java) covers the owner-local control flow and RPC/transaction separation at unit level; it does not provide live PostgreSQL rollback, crash, or concurrency proof. This does not close the terminal request-identity mismatch above or the Temporal lost-response gaps below. +- The source-first termination correction compares a terminal retry’s `terminationRequestId` before returning the retained snapshot. Different identities fail closed; matching retries retain the existing request-ID replay semantics. `WorldLifecycleCommandServiceImplTest` source unit cases cover matching retained `TERMINATED` replay and mismatched-ID rejection. Separate controlled predecessor owner and PostgreSQL proof qualifies cleanup-failure retention, rollback, and local finalization; controlled predecessor PostgreSQL and authenticated mTLS proof also covers same-identity replay and different-identity conflict. The full frozen-owner-snapshot acknowledgement and final-CAS workflow and Temporal retry behavior remain unqualified. The [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status) records detailed proof attribution and the broader lifecycle gaps. +- The current termination orchestration keeps the Entity Management cleanup RPC outside an open World transaction, preserves `TERMINATING` while remote cleanup or local finalization is incomplete, and commits local runtime-row cleanup with the `TERMINATED` lifecycle state in one local transaction. [WorldLifecycleCommandServiceImplTest](../../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java) covers the owner-local control flow and RPC/transaction separation at unit level; it does not provide live PostgreSQL rollback, crash, or concurrency proof. Temporal lost-response gaps remain as described below. - The current Weather path fails closed while its aggregate selector and typed effect fence remain unresolved: `WorldEventServiceImpl.scheduleEvent` rejects `WEATHER_CHANGE` before persistence, and the due-event sweep leaves retained Weather rows unprocessed without changing `region_instance.weather`. Region-bearing non-Weather scheduling also rejects a region outside the event's exact tenant/game-instance scope. This is containment, not Weather implementation or a disposition for retained Weather events; the owner still needs the accepted selector, effect identity/fence, safe reconciliation, and production-shaped proof before admitting Weather. - The non-Weather due-event query now requires a referenced `region_instance` to match the event's tenant/game-instance scope, and the processor defensively leaves a returned mismatch unprocessed. Focused service tests cover wrong-scope and valid rows, and Docker-backed PostgreSQL integration proof covers Weather exclusion, exact tenant/game-instance scope, and single-claim `SKIP LOCKED` behavior; local execution requires Docker/Testcontainers. `V16` still has only a scalar region FK, so retained-data/composite-ownership migration and readback remain separate open work. -- For an in-progress termination, the Temporal orchestrator waits for a World lifecycle snapshot with status `TERMINATED` and the exact `(tenantId, gameInstanceId)`; it does not derive a terminal-epoch threshold from the retry argument. Focused proof is in [TemporalWorldLifecycleOrchestratorTest](../../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/TemporalWorldLifecycleOrchestratorTest.java). Temporal lifecycle activity retries do not yet preserve business idempotency after a local commit: activation/failure validate the supplied epoch before checking their terminal state, so a lost response retries stale, and StartSession compensation can fail to reconcile an already-`ACTIVE` world. The operation identity/result must be durable and retries must reconcile exact results; compensation must be ACTIVE-aware. After fail/terminate completes the long-lived workflow, the current orchestrator still signals that closed workflow on an exact terminal retry instead of reconciling the durable terminal row. These current gaps require focused lost-response, compensation, closed-workflow retry, and terminal-result proof. -- The source-first boundary retains the published fixture bootstrap while canonical source preparation and runtime adoption remain separate. Canonical World materialization, association, holds and first-`OPEN` remain unavailable; retained bootstrap execution does not establish that authority. The complete target ordering and replay contract remain in [Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence); current implementation and proof limits belong to [the World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#canonical-fixture-launch-receiving-boundary). +- For an in-progress termination, the Temporal orchestrator waits for a World lifecycle snapshot with status `TERMINATED` and the exact `(tenantId, gameInstanceId)`; it does not derive a terminal-epoch threshold from the retry argument. Focused proof is in [TemporalWorldLifecycleOrchestratorTest](../../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/TemporalWorldLifecycleOrchestratorTest.java). An ordinary activation retry against `ACTIVE` accepts the positive current epoch or the immediately preceding `PREPARING` epoch; older epochs remain rejected. Failure-epoch retry after a lost response, durable Temporal operation identity/result reconciliation, and ACTIVE-aware StartSession compensation remain gaps. After fail/terminate completes the long-lived workflow, the current orchestrator still signals that closed workflow on an exact terminal retry instead of reconciling the durable terminal row. These gaps require focused lost-response, compensation, closed-workflow retry, and terminal-result proof. +- The source-first boundary retains the published fixture bootstrap and separates explicit canonical source preparation from runtime adoption. Canonical World materialization has a bounded owner implementation; it is not selected by the generic prepare RPC. Canonical activation, holds and first-`OPEN` remain unavailable. The complete target ordering remains in [Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence); current implementation and proof limits belong to [the World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). ## Template and Runtime Ownership +### Fixed fixture PREPARING owner + +The fixed fixture uses existing World source intake, Version identity, canonical association and preparation owners. Its synchronous prepare entry independently verifies the exact current Game Session peer and both remote producers before short World transactions. World allocates its own private tenant, Version and instance keys; Game Session private keys remain provenance. The retained association binds the original immutable fixture policy, source/Version evidence, launch descriptor and Game Session allocation response. A fresh read nonce can change on retry without changing the retained plan; every stable allocation and sealed policy field must still match. + +The owner materializes the exact sealed fixed preset into one region, one zone, two rooms and two reciprocal exits in each template and runtime graph, with their explicit authored/runtime mappings. Both existing transaction-local manifest owners require exact table, operation, row, owner binding and expected content. They consume each manifest once; naked writes, substitutions and unconsumed manifests fail. Independent committed readback compares the original association, complete topology and preparation seal against the original `PREPARING` lifecycle epoch 1 and row version 0. A Demo Region content row supplies no operational-region assignment. + +The SQL read owner permits writable `READ COMMITTED` while materialization verifies its own writes, and read-only `REPEATABLE READ` or `SERIALIZABLE` for independent committed readback. Other access/isolation combinations fail with SQLSTATE `23514`. A standalone Java readback may run without an ambient Java transaction; PostgreSQL's implicit writable `READ COMMITTED` statement remains supported. + +The PREPARING-only storage extension preserves the immutable V1008–V1039 donor artifacts and the immediate V1009.1 legacy UPDATE repair. Published V1040/V1041 remain unchanged; forward V1042 restores explicit required-field checks. Forward V1042.1 schema-qualifies execution-terminal lookups to the World service schema, V1042.2 applies the read-owner transaction access/isolation combinations above, V1042.3 gives forbidden fixture row updates their own diagnostic without changing guard predicates or authority, V1042.4 requires all ten copied realm, catalog, playtest and release fields to equal the retained World row, and V1042.5 requires both complete fixed ROOM template/runtime mappings at independent readback. Forward V1042.6 requires complete Draft terminal bindings to evaluate to TRUE and binds an APPLIED initial-location result to its own operation; it preserves the remaining owner checks and grants no admission authority. Installed V1042.7 permits only the retained predecessor transitions `PREPARING -> ACTIVE`, `PREPARING -> FAILED_PRE_ACTIVATION`, `ACTIVE -> TERMINATING`, and `TERMINATING -> TERMINATED`. For each transition, both rows must have all seventeen canonical, provenance, realm, catalog, and allocation fields absent while retaining the original valid fixture binding, PREPARING epoch, and identity; the transition-specific status, epoch, row-version, and terminal-evidence predicates remain enforced by the migration. This is a bounded predecessor storage exception, not a second runtime target. Forward [V1042.8](../../../../services/world-management-service/src/main/resources/db/migration/V1042.8__world_terminal_affected_unit_validation.sql) adds terminal affected-unit validation that refuses missing, null, or foreign-owner identity, unknown `scopeType`, and epochs outside the nonnegative BIGINT range. It preserves canonical decimal-string `expectedEpoch` values and existing numeric JSON counter forms alongside the existing owner/history guards. Forward V1042.9 permits legitimate guard-owned inserts in the same top-level transaction, including a savepoint, while rejecting late attachment to historical publication attempts; V1042.11 stamps preparation rows with the server-owned full transaction ID only after manifest validation; Account-binding and APPLIED-result digests bind their exact retained bytes. A start-location receipt uses the shared `WorldDraftStartLocationEvidence` length-framed semantic digest over its schema, namespace, operation, request, commit, authorization fence, Account binding, graph binding, canonical tenant, canonical Version, ROOM selector and graph digest; its retained JSON must describe that same tuple and digest. Forward V1042.13 corrects the receipt predicates installed by V1042.12 while preserving the valid Account-binding and APPLIED-result byte checks. Published prior SQL remains unchanged, and these validations grant no new authority. Human schema 1 retains nullable realm/catalog metadata, while Human schemas 1 and 2 require their original binding operation and release digest. Schemas 2 and 3 require a non-null positive catalog revision. Canonical fixture activation and Human activation-operation requirements remain closed, as do other later fixture World row mutations, hold acquire/finalize, initial placement, and player-admission owners. Retire the V1042.7 exception forward only after old writers are drained and legitimate cleanup settles. The [Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence) owns complete launch and replay ordering; the [tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#fixed-fixture-preparing-owner-preparation) records migration history and physical proof. + +V1042.6 validates the `ck_world_draft_terminal_binding` CHECK against every existing `world_draft_terminal_outcome` row when the migration runs. Current PostgreSQL proof exercises the old and strict predicates through a test-local table and an upgrade path with an empty production terminal table; it does not establish compatibility with arbitrary retained rows in external databases. Before a retained-data deployment, require either a verified no-data boundary or explicit owner disposition/mapping with exact readback, unchanged migration history, and applicable owner-safety proof. No incompatible required row or external data disposition has been demonstrated. See the [tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#packet-4-status-and-proof-gaps). + ### Authored-world source retention A fresh intake completes its authenticated Game Design source read before opening the short World owner transaction. The allocator retains its association and legacy-table safety locks, with a transaction-local one-second limit for each lock wait that preserves a tighter positive caller limit. Lock timeout and deadlock failures return `UNAVAILABLE` without committed intake evidence; exact retries retain the original request identity. This does not register or activate the passive service. @@ -49,10 +61,10 @@ World templates follow the same stability rules as entity templates: ## Character Location Ownership -Target ownership (not current storage): World Management is the authoritative owner of character and NPC location for each game instance. The current implementation has live `room_instance` topology and a Game Session room-binding seam, but no authoritative character/NPC location or occupancy persistence. +World Management is the authoritative owner of character and NPC location for each game instance. The schema includes guarded `character_location` and immutable initial-location operation storage from V1019. These are retained owner evidence: canonical first-placement execution and activation remain unavailable, and the registered runtime does not write this family. Live `room_instance` topology and a Game Session room-binding seam do not establish authoritative occupancy. -- Target owner tables such as `character_location` and `npc_location` would live in this service’s schema and be written only by World Management logic as part of movement, instancing, and world-creation flows invoked by Game Session; those tables and the write family are absent from the current schema, migrations, and runtime implementation. -- Once implemented, other services, including Entity Management and Game Session, will treat those tables as read-only and rely on World Management gRPC APIs or cached projections. Current room reads and the Game Session binding do not establish that target authority. +- Only World-owned operations may write location as part of movement, instancing and world creation invoked by Game Session. The initial-placement storage preserves its exact admission hold and APPLIED operation binding. V1042.10 rejects DELETE and TRUNCATE on `character_location`, preserving the existing V1019 operation-history guard; it grants no placement, movement or cleanup authority. `npc_location` and generalized occupancy execution remain unimplemented. +- Other services, including Entity Management and Game Session, treat World location storage as read-only and rely on World Management gRPC APIs or cached projections. Current room reads and the Game Session binding do not establish location authority. - Target rule: derived caches or denormalized views of location must be refreshed from World Management rather than persisting independent authoritative location fields. Target ownership: World Management is the fact owner for targeting predicates over location, occupancy, range, and mutable room state. Its bounded `TargetingFactSnapshot` responses contain only the compiled source/candidate facts for the requested `RoomInstanceRef` scope and a current world location/version token. For `DROP` and `PICKUP`, the target attestation carries `regionId` from Game Session's durable region authority alongside `RoomInstanceRef`, `regionEpoch`, `executorFence`, the same root `EffectId`, and the unchanged immutable `requestDigest`; World validates its own token and rejects mismatched scope, epoch, or fence. The canonical barrier, Game Logic re-resolution, and Entity commit binding are defined in [Transaction Strategies](../../system-architecture-transactions.md#drop-pickup-targeting-and-actor-fence-critical-section) and [ADR 0054](../../decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md). The current proto/request and focused proof do not yet demonstrate this path. @@ -61,7 +73,7 @@ Target ownership: World Management is the fact owner for targeting predicates ov Movement, drops, pickups, and room presence are cross-service by design: -- Target: World Management is authoritative for occupancy/location and room-scoped persistent ambient state keyed by runtime `RoomInstanceRef`; current `room_instance` topology and ambient rows do not include the absent character/NPC location or occupancy write family. Weather is an explicit exception while its target aggregate remains unresolved: the owner must choose and accept a region-scoped or room-scoped selector before any Weather identity or mutation can be defined. Weather mutation admission and reconciliation remain fenced and non-mutating until that selector is accepted, including writes represented by `world_event` and `region_instance.weather`. Initial Weather scheduling during world creation and generic `WEATHER_CHANGE` event scheduling/application follow the same rule: while the selector is unresolved they are explicitly deferred and non-mutating, so no Weather event row is inserted or processed and `region_instance.weather` is not changed. +- Target: World Management is authoritative for occupancy/location and room-scoped persistent ambient state keyed by runtime `RoomInstanceRef`; current `room_instance` topology and ambient rows do not supply the unavailable authoritative location/occupancy execution family. Weather is an explicit exception while its target aggregate remains unresolved: the owner must choose and accept a region-scoped or room-scoped selector before any Weather identity or mutation can be defined. Weather mutation admission and reconciliation remain fenced and non-mutating until that selector is accepted, including writes represented by `world_event` and `region_instance.weather`. Initial Weather scheduling during world creation and generic `WEATHER_CHANGE` event scheduling/application follow the same rule: while the selector is unresolved they are explicitly deferred and non-mutating, so no Weather event row is inserted or processed and `region_instance.weather` is not changed. - Entity Management is authoritative for containment and item instances, including synthetic room-ground containers keyed by the same `RoomInstanceRef`. - All spatial effects must carry the target `RoomInstanceRef` and a canonical tick root `EffectId`; correctness-sensitive mutations also carry exact epoch and relevant owner-state preconditions. - `DROP` and `PICKUP` use the canonical Game Session barrier/attestation sequence before the Entity-local holder commit; World Management owns only the World fact validation and attestation issuance. The binding and handoff rules are defined in [Transaction Strategies](../../system-architecture-transactions.md#drop-pickup-targeting-and-actor-fence-critical-section) and [ADR 0054](../../decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md). The current proto/request and focused proof do not yet demonstrate this validation path. @@ -114,7 +126,7 @@ When changing Redis usage or adding prefixes here, follow the [Redis Design Chec - `world_instance_status`, or equivalent lifecycle state, tracks the ADR 0123 transitions `PREPARING -> ACTIVE`, `PREPARING -> FAILED_PRE_ACTIVATION`, `PREPARING -> TERMINATING`, `FAILED_PRE_ACTIVATION -> TERMINATING`, `ACTIVE -> TERMINATING`, and `TERMINATING -> TERMINATED`. - `FAILED_PRE_ACTIVATION` is terminal for admission by that `gameInstanceId`, not proof that cleanup completed; separate owner-scoped cleanup progress may continue. Recovery is modeled as provisioning a new `gameInstanceId` and rerunning world creation. - `world_instance_lifecycle_lock`, or equivalent fenced token, enforces single-writer lifecycle transitions per `(tenantId, gameInstanceId)`. -- Target-only: `character_location` and `npc_location` would record current rooms and instance occupancy. These tables are absent from the current schema and runtime; live `room_instance` rows describe topology, while the Game Session room binding is not authoritative World location. +- `character_location` and its initial-operation ledger retain the guarded initial-placement storage shape, with execution still closed. `npc_location` and generalized occupancy persistence remain target-only. Live `room_instance` rows describe topology; the Game Session room binding is not authoritative World location. ### Replacement cutover hold ownership @@ -159,7 +171,7 @@ The exhaustive S1/S2/S3 rules, unknown-state fail-closed behavior, namespace mod - current `world_instance` lifecycle rows (lifecycle/provisioning state, not replacement payload); - `region_instance`, `zone_instance`, `room_instance`, `room_instance_exit`; - legacy `instance` rows (explicit replacement mapping `EXCLUDED`; cleanup is the separate zone-scoped legacy-instance operation, not parent `InstanceTermination`); - - Target-only/absent in the current initial slice: `character_location`, `npc_location`, and occupancy rows; + - `character_location` has a retained guarded initial-placement schema, with execution closed; `npc_location` and generalized occupancy rows remain target-only. This replacement classification does not authorize deleting retained initial-placement evidence; - ambient runtime state such as weather, door state, hazard state, instanced events, and instance-scoped schedules; - `world_event` rows tied to a specific `gameInstanceId`. - Target-only/absent in current persistence: `population_schedule_instance` rows keyed by `gameInstanceId`; 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 78307bfb5b..802977ed6b 100644 --- a/design/architecture/microservices/world-management-service/world-creation-workflow.md +++ b/design/architecture/microservices/world-management-service/world-creation-workflow.md @@ -15,9 +15,9 @@ The cross-platform workflow placement and adopter-proof requirements are owned b ## Implementation Status -The current first implementation cut exposes four synchronous lifecycle commands: `PrepareWorldInstance`, `ActivatePreparedWorldInstance`, `FailPreparedWorldInstance`, and `TerminateWorldInstance`. The first three create, admit, or fail a prepared instance; `TerminateWorldInstance(tenantId, gameInstanceId, expectedLifecycleEpoch, terminationRequestId)` is the only live cleanup seam. Game Session reads fresh lifecycle state through `GetWorldInstanceLifecycle` immediately before termination. Termination accepts `ACTIVE -> TERMINATING`, invokes the current Entity cleanup seam, deletes the runtime `world_event`, `room_instance_exit`, `room_instance`, `zone_instance`, and `region_instance` subset, and then saves `TERMINATED` while retaining terminal lifecycle evidence. It does not yet implement the target frozen required-owner snapshot and ownership-registry revision, per-owner durable acknowledgements, complete registered World-owned cleanup, or final all-owner lifecycle CAS. A `TERMINATED` fast path returns before comparing `terminationRequestId`, so a mismatched terminal retry is incorrectly reported as success rather than an idempotency conflict; exact terminal identity comparison and focused retry/conflict proof remain required. The current lifecycle tests prove this synchronous cleanup path only; they do not prove `TERMINATING` retention across owner failure/retry, frozen-snapshot acknowledgement, final fenced CAS, or matching-versus-mismatched terminal retry outcomes. These live commands are not proof of the target cross-service termination workflow. +The current first implementation cut exposes four synchronous lifecycle commands: `PrepareWorldInstance`, `ActivatePreparedWorldInstance`, `FailPreparedWorldInstance`, and `TerminateWorldInstance`. The first three create, admit, or fail a prepared instance; `TerminateWorldInstance(tenantId, gameInstanceId, expectedLifecycleEpoch, terminationRequestId)` is the only live cleanup seam. Game Session reads fresh lifecycle state through `GetWorldInstanceLifecycle` immediately before termination. Termination accepts `ACTIVE -> TERMINATING`, invokes the current Entity cleanup seam, deletes the runtime `world_event`, `room_instance_exit`, `room_instance`, `zone_instance`, and `region_instance` subset, and then saves `TERMINATED` while retaining terminal lifecycle evidence. It does not yet implement the target frozen required-owner snapshot and ownership-registry revision, per-owner durable acknowledgements, complete registered World-owned cleanup, or final all-owner lifecycle CAS. A `TERMINATED` retry now compares `terminationRequestId` before returning: a different request identity fails with `IDEMPOTENCY_CONFLICT`, while a matching identity returns the retained snapshot. Existing `WorldLifecycleCommandServiceImplTest` source unit cases cover matching retained replay and mismatched-ID rejection. Separately, controlled retained-predecessor owner and PostgreSQL proof covers `TERMINATING` retention when Entity cleanup fails, rollback, and successful local finalization. Controlled predecessor fixtures also prove same-identity replay and different-identity rejection over native PostgreSQL and authenticated mTLS socket paths. These tests remain limited to that predecessor fixture scope; they do not prove the full frozen-owner-snapshot acknowledgement and final-CAS workflow or Temporal retry/recovery behavior. These live commands are not proof of the target cross-service termination workflow. -The run-owned Compose fixture uses the existing synchronous prepare and activate commands only after the fixed-server World evidence provider validates the complete immutable receipt, exact Game Session TLS caller, World recipient pins, and current Game Design descriptor. The world row retains the original preparing epoch and complete fixture binding digest; an exact `ACTIVE` lost-response replay with identical evidence at that original epoch returns without another lifecycle transition. This local boundary is default-off and does not seed an active row or add production read permission. Its canonical evidence and replay contract is owned by [System Architecture: Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence); physical PostgreSQL and authenticated transport proof remain pending. +The run-owned fixture remains disabled by default. The retained predecessor bootstrap prepares through the generic `PrepareWorldInstance` RPC; activation and `ACTIVE` replay remain available through the existing lifecycle commands. Canonical preparation is a separate explicit prepare-only World owner operation and is not dispatched by the generic prepare RPC. World retains the original `PREPARING` epoch and complete fixture binding digest for exact prepare replay. Canonical activation and `ACTIVE` replay for the explicit canonical fixture variant remain closed. The canonical evidence and replay contract is owned by [Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence), and current controlled native proof and packaged runtime limits are recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#fixed-fixture-preparing-owner-preparation). World creation consumes a previously resolved immutable launch descriptor for the attempt. At minimum this descriptor carries: @@ -170,7 +170,7 @@ If retries are exhausted before admission: The target guard must be enforced with the step’s durable writes so “step completed” cannot be recorded without the corresponding instance rows. The current World Management implementation preserves `controlPlaneRequestId`, lifecycle fencing, and the implemented `generationConfigRevision` in its command paths; the target `generationRequestId` occurrence identity and its propagation remain unimplemented. It also does not yet demonstrate the complete occurrence/role/digest-bound guard or fail-closed conflict behavior across workflow retries. Current lifecycle tests prove the implemented lifecycle and idempotency seams, not the full ADR 0078 retry, conflict, crash, replay, and durable-guard proof; that implementation and proof drift remains open. -The current `TemporalWorldLifecycleOrchestrator` workflow ID is derived only from ``, even though the prepared request also carries `controlPlaneRequestId` and `launchDescriptorId`. When Temporal reports `AlreadyStarted`, the orchestrator ignores the exception and queries the existing workflow without exact-comparing those launch identities or their request digest. The current activation wait also requires a later `ACTIVE` snapshot/epoch within a fixed ten-second polling window; an exact retry can therefore time out while the existing workflow is still in `PREPARING` or processing the activation signal. In addition, activation and failure activities validate the old epoch before their terminal-state check, so a response lost after a local commit retries as stale; StartSession compensation can consequently leave an already-`ACTIVE` World row orphaned. Once fail or terminate marks the long-lived workflow complete, the orchestrator also signals that closed workflow on a later exact terminal retry rather than reconciling the durable terminal row. These are current identity, replay/conflict, compensation, and terminal-reconciliation gaps; durable operation results, ACTIVE-aware compensation, durable-row reconciliation before signaling, and focused lost-response/closed-workflow proof remain required. +The current `TemporalWorldLifecycleOrchestrator` workflow ID is derived only from ``, even though the prepared request also carries `controlPlaneRequestId` and `launchDescriptorId`. When Temporal reports `AlreadyStarted`, the orchestrator ignores the exception and queries the existing workflow without exact-comparing those launch identities or their request digest. The current activation wait also requires a later `ACTIVE` snapshot/epoch within a fixed ten-second polling window; an exact retry can therefore time out while the existing workflow is still in `PREPARING` or processing the activation signal. An ordinary activation retry against `ACTIVE` accepts the positive current epoch or the immediately preceding `PREPARING` epoch; older epochs remain rejected. Failure-epoch retry after a lost response remains unresolved. StartSession compensation can consequently leave an already-`ACTIVE` World row orphaned. Once fail or terminate marks the long-lived workflow complete, the orchestrator also signals that closed workflow on a later exact terminal retry rather than reconciling the durable terminal row. These are current identity, replay/conflict, compensation, and terminal-reconciliation gaps; durable operation results, ACTIVE-aware compensation, durable-row reconciliation before signaling, and focused lost-response/closed-workflow proof remain required. 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`. diff --git a/design/architecture/system-architecture-testing.md b/design/architecture/system-architecture-testing.md index 750a85e4f5..4747fb0855 100644 --- a/design/architecture/system-architecture-testing.md +++ b/design/architecture/system-architecture-testing.md @@ -181,6 +181,8 @@ Unknown, partial, stale, contradictory, or unavailable reset, mutation, or clean The source-first Game Session code isolates canonical `STARTING` preparation in `RunOwnedCanonicalLaunchPreparationOwner`: its fixed-evidence preparation method is explicit and has no scheduler, while `GetRunOwnedFixtureLaunchAssociation` reads only the actual canonical owner allocation. The published `RunOwnedInitialAdmissionFixtureCoordinator` scheduled bootstrap and `GameInstanceServiceImpl` behavior remain in place pending coherent canonical adoption; the explicit preparation path is not wired into that bootstrap. This separation does not establish scheduled canonical allocation, canonical World fixture materialization or activation, or canonical first-`OPEN`; the retained bootstrap is a separate staged implementation. The World preparation and first-`OPEN` paragraphs below define the complete target ordering, not proof that the current owner stage implements them. Owning service trackers retain candidate-specific physical and packaged proof limits. +Canonical World source/Version preparation is likewise an explicit owner operation, separate from the retained generic fixture bootstrap. Its source carrier is `RunOwnedCanonicalWorldLaunchEvidence`; the registered generic prepare RPC does not select this canonical materialization. Current source, authentication and physical proof limits belong to the owning service trackers. + The isolated authored-world fixture is an explicit `RUN_OWNED_FIXTURE` authority variant in the existing Game Design policy, Game Session catalog/launch and initial-admission owners, and World source/Version/association/preparation owners. It is available only to the fixed, independently verified run-owned Compose capability under default-off server configuration. The claim commitment, existing UUIDv5 derivation, run/project/operation, claim lock, both recipient URI/DER leaf pins and shared CA pin remain bound throughout. Parsed common capability, receipt, protobuf or policy records are wire data; their shape, digest or successful decoding alone grants no authority. Generic `StartSession` and player ingress cannot select or construct the trusted fixture carrier. The immutable source receipt has exactly fourteen envelope fields, including `creationEvidence`, `sourceEvidence`, `launchReadEvidence` and `fixturePolicySeal`. Fresh creation evidence retains its ten fields `{schemaVersion, targetNamespace, creationRequestId, operationId, requestDigest, canonicalTenantId, sourceGameRowId, sourceGameTenantKey, provenanceKind, evidenceDigest}`. The thirteen-field source evidence retains its actual registration request, owner operation, digest, canonical tenant, source row/key and provenance independently. The fixture operation UUID deliberately equals the source **registration request** UUID, as issued by the producer and checked by the codec. Creation request, creation owner operation, source owner operation and descriptor identities keep their own semantic roles; creation-request equality is not inferred, and no universal pairwise inequality rule replaces actual owner evidence. The current production fixture producer explicitly uses the fixture operation UUID as its creation request ID, so its creation request and source registration request IDs are equal. This is producer behavior; the codec permits distinct creation and registration request IDs and retains their independent semantic roles. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 3ec90dc4ce..531c662afa 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -80,3 +80,9 @@ Entry format: - Observation: a mostly up-to-date run passed, but cold-build speed and total memory use remain unmeasured; worker, test, and code-generation JVMs add separate memory, and the hosted runner remains explicitly configured at 2500m. - Expected pattern: treat the setting as a qualified local choice, not a repository-wide memory guarantee or a change to hosted sizing. - Reconsideration trigger: fresh OOM/GC thrashing or a concrete need to measure cold-build memory. + +- `2026-10-15`: Verify the complete absolute patch destination after the first write + - Context: Gameplay’s World digest-guard helper verified its checkout but mistyped the absolute migration path, creating a file in a similarly named sibling directory outside Git. This is distinct from the earlier relative-path incident: an absolute path alone does not identify the intended checkout. + - Observation: Verifying the checkout did not prevent a typo in the absolute patch target. The helper reported the mistake; Main compared the misplaced and intended files byte-for-byte, removed only the confirmed new duplicate, and preserved the sibling directories. No misplaced file was published. + - Expected pattern: Compare every patch target with the pinned worktree path, then inspect the first written file at that absolute destination before continuing. This destination check remains manual. + - Reconsideration trigger: enforce destination verification at the native patch boundary, or repeat measurement disproves the risk; completion of migration review alone does not resolve it. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 5d6ae36808..c59b471e0e 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -12,6 +12,12 @@ The ordinary World producer emits digest schema 3 for its tagged Entity-referenc The coherent receiving successor for [PR #3196](https://github.com/benhook1013/FireMUD/pull/3196) is prepared on the latest qualified parent `d7f78ebbb5e2d13bfd73885202c0742c41e3f94b` from [PR #3189](https://github.com/benhook1013/FireMUD/pull/3189). Its coherent boundary includes Game Design/shared-contract/caller/proof paths, preserved Logging receiving paths, and bounded CI/process repairs. The PR’s generated scope section records its current path count. The ten earlier Account/process prerequisite paths are inherited from the preparation parent rather than duplicated. The current local composition gate and source proofs have the exact attribution below. The published CLI2 source `371f0dcedc75690aadb7cb267b4a19ddbc8c16ff` passed its exact-head Validation, CodeQL, License and Security gates. Current review fixes require new published-source CI; Hosted/CLI review and rebuilt packaged receiver proof remain separate gates. Earlier results retain their original source attribution. +### Source-first World composition proof + +Game Design's fixed source and Version readers retain qualified controlled receiving proof through the readiness-child carries; the shared PREPARING composition and exact run attribution are recorded once in [World Runtime and Movement](./world-runtime-and-movement.md#fixed-fixture-preparing-owner-preparation). + +Game Design's default-off, operation-scoped wrappers register the existing source and Version read kernels. Exact configuration, peer, selector and preexisting-owner checks follow the [owning API contract](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status); no new wire service or fixture flag is introduced. On the historical receiving Game Design cut, 510 unit results retained their earlier fresh execution on unchanged production inputs, and 142 native PostgreSQL-backed cases executed freshly, including 22 fixture cases. Historical producer → persisted Game Session `STARTING` → World `PREPARING` composition across three production mTLS handlers is recorded in [World Runtime and Movement](./world-runtime-and-movement.md#fixed-fixture-preparing-owner-preparation). The source-first reconstruction keeps real Game Design and Game Session protected owner-read transports. The cross-service run attribution for [RunOwnedFixtureOwnerCompositionCrossServiceTest](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java) is recorded in [World Runtime and Movement](./world-runtime-and-movement.md#canonical-fixture-launch-receiving-boundary). The test exercised actual Game Design and Game Session protected owner-read transports over TLS/PostgreSQL, while invoking the explicit canonical World owner with controlled peer/certificate evidence through reflection. It does not exercise a registered canonical World production RPC or qualify canonical World activation. The fixed read adapters were registered in a real managed annotation context with their actual producer owners. The final native parent-file enumeration correction passed nine fresh storage-upgrade cases, formatting and required static checks; the other native postimages retained their preceding execution attribution. Complete Spring Boot and packaged fresh/restart remain unqualified, and no genuine Gameplay handoff is closed. + ### Closed fixture policy producer The successor to the guarded World owner stage uses Game Design's existing fresh creation, source registration, Version/bundle, descriptor and realm-policy owners to publish the fixed run-owned receipt only after independent committed readback. Forward [V1031](../../../services/game-design-service/src/main/resources/db/migration/V1031__run_owned_fixture_policy_owner_seal.sql) keeps Human and fixture policy headers mutually exclusive: fixture policy supplies no Human capture, terminal or Account-protection children, and the existing Human capture foreign key remains mandatory for Human rows. The original migration artifacts and predecessor Human owner bytes remain unchanged. @@ -128,7 +134,7 @@ The published `888f` GDS foundation slice contains source-operation/outbox stora | `AR-2.1` Typed settings, defaults, scopes, and precedence | `partial` | `proven` for typed settings metadata/defaults, persisted overrides, effective resolution, and command-capability resolution seams; selected presets, operator bootstrap/runtime layers, safety caps, complete precedence proof, and all scoped consumers remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedEffectiveSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolver.java); [FiremudCommandCapabilitiesProperties.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/FiremudCommandCapabilitiesProperties.java); [platform settings publication](../../../config/settings/platform-settings-publication.json); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [platform operations](./platform-operations-and-delivery.md); [world runtime](./world-runtime-and-movement.md) | Partial: typed defaults, scopes, persisted overrides, and effective resolution exist, but selected presets, operator bootstrap/runtime layers, caps, and their precedence proof are not implemented. ADR 0012 is accepted and owns the target precedence and constraint contract. | | `AR-2.2` Feature, command, profile, and capability policy | `partial` | `proven` for command-capability resolution, feature-flag, published-command admission, and interpreter seams; complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [player command model](../../architecture/system-architecture-player-command-model.md); [feature flags](../../architecture/microservices/game-design-service/feature-flags.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0124](../../architecture/decisions/adr-0124-materialized-starter-profiles-with-conservative-draft-upgrades.md) | [EffectiveCommandCapabilitiesSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolver.java); [FeatureFlagServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/FeatureFlagServiceImpl.java); [AggregatingTextCommandRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistry.java); [AdmittedTextCommandRegistryResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java); [AggregatingTextCommandRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java); [AdmittedTextCommandRegistryResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolverTest.java); [TextCommandInterpreterCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java) | [player experience](./player-experience-commands-and-communication.md); [player access](./player-access-and-session.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: command capability resolution, feature flags, and published command admission exist, but the complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage are not implemented. ADR 0124 defines materialized starter-profile content and conservative Draft upgrades; implementation and focused proof remain incomplete. | | `AR-2.3` Tenant/game overrides, safety caps, validation, and effective configuration | `partial` | `proven` only for tenant/game settings persistence, validation, functional effective resolution/readback, and resolver seams; the current route authorization does not enforce tenant binding: the shared classifier accepts a tenant-scoped privileged role for any tenant and the controller accepts unbound tenant or session selectors, so cross-tenant effective-settings reads are currently possible. Cross-tenant denial proof is tracked separately and remains unproved. Safety caps, presets, complete hot-reload/invalidation, and all scoped consumers also remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedSettingsAuthorityReader.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedSettingsAuthorityReader.java); [GameDesignSettingsAuthorityClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/GameDesignSettingsAuthorityClient.java); [EffectiveSettingsController.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveSettingsControllerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerIntegrationTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [platform operations](./platform-operations-and-delivery.md) | Partial: tenant/game persistence, validation, and functional effective readback/resolver seams exist, but route-aware authorization, scoped/global role binding, cross-tenant denial proof, safety caps, presets, complete hot-reload/invalidation, and all scoped consumers remain incomplete under accepted [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md); implementation and proof gaps remain. | -| `AR-3.1` Runtime instance launch, lifecycle, and termination | `partial` | `unverified`: Game Session lifecycle and World activation, failure, and termination seams remain proven. Legacy numeric-only tenant/template/version resolution remains fail-closed and does not authorize launch; authenticated source-bound v1 descriptor resolution and exact readback are implemented, while candidate-specific source/receipt proof and current PostgreSQL, packaged Compose/restart, and later protected-activation proof remain unproved. Automation `READY` join, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [V11 launch descriptor](../../../services/game-design-service/src/main/resources/db/migration/V11__launch_descriptor_framework.sql); [V12 world activation](../../../services/world-management-service/src/main/resources/db/migration/V12__world_instance_activation.sql); [V34.1 authored source operations](../../../services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql); [V35 descriptor source binding](../../../services/game-design-service/src/main/resources/db/migration/V35__authored_source_launch_descriptor_binding.sql); [V41 source delivery](../../../services/game-design-service/src/main/resources/db/migration/V41__world_authored_source_delivery.sql); [GameAuthoredWorldSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepository.java); [GameAuthoredWorldSourceDeliveryRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java); [CompleteLaunchBindingService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingService.java); [CompleteLaunchBindingServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java); [CompleteLaunchBindingDto.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/CompleteLaunchBindingDto.java) | [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [LaunchDescriptorServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GameInstanceServiceLifecycleIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [GameAuthoredWorldSourceRepositoryIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java); [GameAuthoredWorldSourceDeliveryIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java); [CompleteLaunchBindingServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java); [CompleteLaunchBindingServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java); [CanonicalLaunchGrpcAuthWiringTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java) | [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: authenticated source-bound v1 resolution and exact descriptor readback are live; numeric-only tenant/template/version fields do not authorize launch. Candidate-specific source/receipt proof and physical Compose/Docker/PostgreSQL/mTLS smoke remain unvalidated. Automation `READY`, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. Accepted replacement namespace and database-authoritative lifecycle decisions now define the target boundary; namespace-aware cutover and owner cleanup acknowledgement remain unproved. `ResolveLaunchDescriptor`, `GetLaunchDescriptor`, and `GetCompleteLaunchBinding` are registered in the base and production gRPC public-method lists to bypass bearer validation, and each retains its method-specific same-namespace mTLS peer check. Production `GetCompleteLaunchBinding` authenticates exact same-namespace candidate peers, then returns `PERMISSION_DENIED` before request validation or owner reads. | +| `AR-3.1` Runtime instance launch, lifecycle, and termination | `partial` | `unverified`: Game Session lifecycle and World activation, failure, and termination seams remain proven. Legacy numeric-only tenant/template/version resolution remains fail-closed and does not authorize launch; authenticated source-bound v1 descriptor resolution and exact readback are implemented, while candidate-specific source/receipt proof and current PostgreSQL, packaged Compose/restart, and later protected-activation proof remain unproved. Automation `READY` join, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [V11 launch descriptor](../../../services/game-design-service/src/main/resources/db/migration/V11__launch_descriptor_framework.sql); [V12 world activation](../../../services/world-management-service/src/main/resources/db/migration/V12__world_instance_activation.sql); [V34.1 authored source operations](../../../services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql); [V35 descriptor source binding](../../../services/game-design-service/src/main/resources/db/migration/V35__authored_source_launch_descriptor_binding.sql); [V41 source delivery](../../../services/game-design-service/src/main/resources/db/migration/V41__world_authored_source_delivery.sql); [GameAuthoredWorldSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepository.java); [GameAuthoredWorldSourceDeliveryRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java); [CompleteLaunchBindingService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingService.java); [CompleteLaunchBindingServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java); [CompleteLaunchBindingDto.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/CompleteLaunchBindingDto.java); [RunOwnedFixtureOwnerReadAuthorization.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerReadAuthorization.java); [RunOwnedFixtureAuthoredWorldSourceReadGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldSourceReadGrpcService.java); [RunOwnedFixtureAuthoredWorldVersionStateGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldVersionStateGrpcService.java) | [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [LaunchDescriptorServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GameInstanceServiceLifecycleIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [GameAuthoredWorldSourceRepositoryIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java); [GameAuthoredWorldSourceDeliveryIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java); [CompleteLaunchBindingServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java); [CompleteLaunchBindingServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java); [CanonicalLaunchGrpcAuthWiringTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java); [RunOwnedFixtureOwnerReadAuthorizationTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerReadAuthorizationTest.java); [RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java); [RunOwnedFixtureOwnerCompositionCrossServiceTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java) | [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: authenticated source-bound v1 resolution and exact descriptor readback are live; numeric-only tenant/template/version fields do not authorize launch. Candidate-specific source/receipt proof and physical Compose/Docker/PostgreSQL/mTLS smoke remain unvalidated. Automation `READY`, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. Accepted replacement namespace and database-authoritative lifecycle decisions now define the target boundary; namespace-aware cutover and owner cleanup acknowledgement remain unproved. `ResolveLaunchDescriptor`, `GetLaunchDescriptor`, and `GetCompleteLaunchBinding` are registered in the base and production gRPC public-method lists to bypass bearer validation, and each retains its method-specific same-namespace mTLS peer check. Production `GetCompleteLaunchBinding` authenticates exact same-namespace candidate peers, then returns `PERMISSION_DENIED` before request validation or owner reads. | | `AR-3.2` Release readiness, compatibility, and propagation | `partial` | `proven` for publish-gate, digest-read, release-bundle, launch-descriptor, and compatibility-check seams; target-commit convergence, coordinated digest-schema adoption, Automation readiness propagation, complete attestation tuples, and environment-promotion behavior remain unproved. | [Promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [Game Design version control](../../architecture/microservices/game-design-service/version-control.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md) | [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [WorldDraftDesignDigestServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java); [InstanceCutoverCompatibilityServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImpl.java); [V14 recorded participant digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql) | [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [EntityDraftDesignDigestServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java); [InstanceCutoverCompatibilityServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: publish gates, digest reads, release bundles, and compatibility checks exist, but actual target-commit convergence, coordinated digest schema adoption, Automation readiness propagation, and complete environment-promotion evidence are not established. Accepted publication, asset, and procedural-generation decisions now define the target readiness and convergence contracts; complete digest/attestation tuples, Automation readiness propagation, and promotion evidence remain incomplete. | | `AR-3.3` Cutover, rollback, hotfix, and script-patch activation | `partial` | `proven` for prepared cutover, pointer-CAS, patch pin/readiness, and plugin activation seams; complete live hotfix/rollback orchestration and downstream runtime-ready, alias, and binding convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [scripting control-plane API](../../architecture/system-architecture-scripting-control-plane-api.md); [scripting rollout and rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md) | [VersionUpgradePreparationServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/VersionUpgradePreparationServiceImpl.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [GameSessionVersionUpgradeControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionVersionUpgradeControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java) | [VersionUpgradePreparationServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/VersionUpgradePreparationServiceImplTest.java); [InstanceCutoverCompatibilityServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [ScriptPatchPinProjectionServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPinProjectionServiceImplTest.java); [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java) | [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: prepared cutover, pointer CAS, patch pin/readiness, and plugin activation seams exist, but complete live hotfix/rollback orchestration and all downstream runtime-ready, alias, and binding convergence remain incomplete. Accepted release-tuple and asset-lifecycle decisions now define immutable runtime selection and CAS-governed publication; complete cutover, rollback, hotfix, and downstream binding enforcement remain incomplete. | | `AR-3.4` Playtest forks, reset, expiry, and isolation | `not-implemented` | `unverified` | [Playtest fork boundary](../../architecture/system-architecture-versioning-runtime.md); [creator journeys](../../product/user-journeys/creators.md); [multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | No production anchor: no playtest-fork implementation exists. Adjacent context only: [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java) provides ordinary launch/termination; [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) has no fork/reset contract; [V1 baseline](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) has no playtest-fork state. | No focused executable proof: no fork/playtest production boundary exists to exercise. | [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [player access](./player-access-and-session.md) | Not implemented: no fork creation/snapshot copy, reset, expiry automation, isolation, or admission contract was found in production code, schema, proto, config, or focused tests. ADR 0122 and ADR 0123 define adjacent namespace/lifecycle boundaries; they do not claim that playtest fork behavior is implemented or proved. | 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 32689f5585..200ebb8b62 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -8,9 +8,65 @@ This is a non-normative implementation tracker for world runtime and movement. C ### Canonical fixture launch receiving boundary -The source-first front retains the published World fixed-evidence verifier, scheduled demo topology and fixture preparation/activation dispatch while the canonical replacement is prepared separately. It consumes the strengthened closed capability and Game Design receipt without requiring the new canonical Game Session association from the running bootstrap. Mandatory canonical-association adoption, World materialization and first-`OPEN` move together to the later coherent runtime swap; this retained path does not establish canonical World/Entity/operational-region authority. The reconstructed boundary passed three World PostgreSQL and two real mTLS cases with controlled upstream evidence, alongside actual Game Design producer and Game Session source-storage cases. Its 33 unchanged World unit cases retain their preceding successful execution; affected static checks and the final two-case TLS rerun pass. Fresh source-built baseline and same-version restart both passed WebSocket and Telnet `WORLDS`/`LOGIN`/`PLAY`/`LOOK`; fixture mode was disabled for these packaged runs, so they qualify only the ordinary default-off baseline, not the enabled retained fixture coordinator. Original-capability teardown removed the claimed project containers, network and volumes. Canonical owner-chain closure remains open. +The forward V1042.13 correction passes the complete World check in 2m30s with 88 freshly executed native cases, zero failures, errors or skips, and generation, static, formatting and documentation checks. The 343 unchanged World units and three focused Common receipt-codec cases passed freshly in the preceding invocation and are reused by this corrected gate; the earlier unchanged Common source retains its full-module qualification below. The physical digest case now uses the real `WorldDraftStartLocationEvidence` encoding, proves fresh installation and installed V1042.12-to-V1042.13 upgrade, retained rows/bytes/`xmin`, guard identities/security/grants and history, and rejects both receipt-side and APPLIED-side payload/field mismatches. The first gate failed in the controlled clone’s permission setup before those new assertions; copying function definitions does not copy ACLs, so the clone now explicitly removes PUBLIC execution. That failed run remains separate evidence. At front `5f0082a868709bf0076a18ca7c065431a462235b`, rebuilt fresh bootstrap and same-version restart both pass WebSocket and Telnet `WORLDS` → `LOGIN` → `PLAY` → `LOOK` with fixture mode disabled. Original-capability teardown returned outer exit `0` (`29783`); independent label-filtered Docker inspection found zero containers for exact project `firemud-smoke-gameplay3211-semantic-sql-20261015-151841`. This qualifies the ordinary default-off runtime baseline only. The corrected #3220/#4247 selected-publication component-producer run passed in 5m34 with 468 fresh World units, 94 fresh World native cases and 20 fresh Game Design cross-service cases, zero issues, including `WorldSelectedPublicationPostgresIntegrationTest.currentDefaultAppliedFreezeInventoryTerminalAndIndependentOwnerReadback`. It exercised the real selected-publication producer path with controlled upstream authority and does not establish a genuine protected handoff, canonical activation or first admission. Root's fresh Sol high five-file material-scope assessment (`0ae0e67f`, 15:37:34) reports no issues or independent contract expansion; the existing Hosted allocation remains retained. Current-head CI and final CLI findings remain pending. -Historical canonical-adoption candidate `4cee3da213ad2b4d1ba27a4bbb7e418efee88a8a` after [PR #3203](https://github.com/benhook1013/FireMUD/pull/3203) passed the World whole-service/static/documentation gate in 2m43s: 292 fresh unit and 65 fresh integration cases (63 PostgreSQL, two controlled mTLS socket cases), zero failures/errors/skips. That candidate refused fixture writes and proved passive storage/retention; its results do not qualify the current retained-bootstrap reconstruction. The socket cases used controlled remote handlers, and all four genuine canonical owner handoffs remain open. +The historical receiving gate for #3220 at `f297062e2e4581a131859084f20aad89288dccf2` exposed a receipt-digest mismatch inherited from #3211 V1042.12. Its real selected-publication producer computes the shared framed-field digest, while the installed SQL compares that digest with SHA-256 of receipt JSON that already embeds it. The earlier controlled digest test used a raw-byte-hash placeholder and did not qualify this producer contract. The full receiving gate failed one of 94 fresh World native cases before APPLIED persistence; 556 Common, 468 World and 527 Game Design unit cases, 125 Game Design native cases and 20 cross-service cases passed. Packaged proof did not run after that failure. Forward V1042.13 (above) corrects this receipt-digest mismatch; the corrected selected-publication component-producer proof is recorded above. This failed gate remains historical evidence with its original attribution. + +At source `84691119f0595dc99695ec4da1b5ee3799ce8a41`, after normally receiving develop `5f47c8e07f527302c3cb1be299188a45c5c1a77f` and its Jackson 2.22.3/3.2.3 updates, the complete Common and World gate passes in 4m23s: 489 fresh Common unit cases, 343 fresh World unit cases and 88 fresh World integrations, with zero failures, errors or skips. Generation, formatting, static analysis and documentation checks pass. Rebuilt fresh bootstrap and same-version restart both pass WebSocket and Telnet `WORLDS` → `LOGIN` → `PLAY` → `LOOK` with fixture mode off. Original-capability cleanup succeeds, the outer resource session returns zero, and the exact project `firemud-smoke-gameplay3211-hosted264-20261015-132328` retains zero containers. This qualifies the ordinary predecessor baseline and the stated source/storage cases; earlier failed runs remain failed evidence, and the unknown Docker kill initiator remains unexplained. Current published-head CI, remaining allocated review, genuine authority and enabled canonical fixture activation remain separate obligations. + +The Hosted `342` test correction at source `35fcb6473ec05a0f7301b34dabff5f4c765a1e91` passes 17 fresh version-identity unit cases and three fresh guarded-capture PostgreSQL cases in a 44-second affected static, formatting and documentation gate. The digest-4 serialized control with the original commit and the altered-commit probe both reach the retained schema-3 attempt’s FROZEN source/checkpoint refusal branch; this is branch coverage, not isolated proof that commit mismatch causes denial. All four remote version-evidence substitutions are verified to reach their read. + +The separate cleanup-diagnostic source `41b9da5d16c8f548e2948aacfade91e42e3fb80b` passes the affected terminal/location PostgreSQL case freshly, plus static, formatting and documentation checks in 37 seconds. Rebuilt fresh bootstrap and same-version restart both pass WebSocket and Telnet `WORLDS` → `LOGIN` → `PLAY` → `LOOK` with fixture mode off. Original-capability cleanup returns zero and the exact project `firemud-smoke-gameplay3211-pg-cleanup-20261015-125934` has zero containers. The preceding unfiltered `e18eadf4a281d3e2ff291363e315bc58157220dc` run passed 343 fresh World units and 87 of 88 fresh integrations; its remaining PostgreSQL connection refusal is retained as failed evidence. Exact-container Docker history shows SIGKILL immediately after startup, with no identified initiator. Cleanup now preserves a primary failure and attempts both schema removals; this diagnostic change does not repair or explain that kill. The unchanged Common cases retain their preceding attribution. No new unfiltered World pass, genuine authority or enabled fixture activation is claimed. + +The CLI `fa98` correction at source `edb83757d1b139fae3cca75fbf5b50b4569ed2cf` adds the installed V1042.12 entry to the literal migration-history expectation, requires the exact lifecycle-stale diagnostic in ordinary replay refusal tests, and aligns the canonical storage and scoped observation text. The affected PostgreSQL class passes all 13 freshly executed cases in the corrected 48-second gate; the affected lifecycle unit class passes all 32 freshly executed cases in a separate 20-second gate, with static, formatting and documentation checks. The preceding unfiltered `9cf7359ff95078f9a3084bd98faadd5c69fe0806` run passed 489 Common and 343 World unit cases plus 86 of 88 integrations; its two migration-list failures remain failed evidence. No new unfiltered service pass or rebuilt fresh/restart result is claimed for this correction. + +The Hosted 264 correction at source `7e729cdd3265ea3c149e60e1e33e489119f686e3` adds forward V1042.12 to bind the existing Account, receipt and APPLIED-result digests to their retained byte fields in both installed guards. One freshly executed PostgreSQL case passes all positive and mismatched-pair probes, real fresh/upgrade migration installation, and function/trigger/ACL/history and retained row-byte/`xmin` preservation. The four other affected current-frontier cases passed at `906bf78dbb67c204bf7c9c54a137c2c314644eb8`; their source remains unchanged. Generation, integration static analysis and documentation checks pass. The new case uses controlled table clones and schema-rebound installed functions, so it qualifies the stated predicate repair rather than genuine Account authorization or production APPLIED creation. The original failed metadata-query attempt remains separate failed evidence. + +The Hosted 553 repair at source `b24a57c869224ef16295c59e250d29cacb30c99c`, normally receiving develop `0eec7066508da50d0a9216b91f94a60281cc13c3`, passes the complete World check: 343 fresh unit cases and 87 fresh integrations (85 PostgreSQL and two controlled mTLS), with zero failures, errors or skips. Generation, formatting, static checks and documentation checks pass. Owner reads preserve retryable gRPC transport statuses while retaining permanent invalid-evidence denial. Forward V1042.10 adds retained-location removal guards; V1042.11 stamps preparations with their server-owned top-level full transaction ID after exact manifest validation. Physical proof covers legitimate schema-4 selector retention under a savepoint, server overwrite of forged stamps, postcommit and historical NULL-stamp refusal, actual fixture manifests, retained rows and xmin, migration history, and function/trigger/security/grant preservation. Published predecessor migrations remain unchanged. The isolated selector probe uses controlled table clones and installed function bodies; these cases do not establish genuine Account authority or canonical owner activation. + +Rebuilt fresh bootstrap and same-version restart at that source both pass WebSocket and Telnet `WORLDS` → `LOGIN` → `PLAY` → `LOOK`. Original-capability cleanup succeeds; the outer session finishes successfully at 2026-10-15 11:31:50 UTC and the exact project `firemud-smoke-gameplay3211-hosted553-20261015-112637` retains zero containers. Fixture mode is forced off, so this qualifies the ordinary predecessor baseline only. Current published-head CI and allocated review remain separate completion obligations. + +The CLI 518 review correction on source `224f72d0d18b4f458a6e555500cb7ec37df8c962` permanently fences canonical-provider client creation after shutdown and uses forward V1042.9 to support legitimate savepoint insertion without allowing late attachment to historical publication attempts. Published migrations remain unchanged. The full PostgreSQL run at `ec2f60c7e7b62935f5ce0f8a8396a91a64e607c5` passes all 86 cases, including real fixture materialization under a savepoint, server overwrite of forged transaction stamps, exact late-attachment refusal, and V1042.8-to-V1042.9 preservation of original row values, xmin, migration history and installed function/trigger identity, security and grants. That overall gate fails only on nullable count reads in the two new test cases. After those reads use the exact-one-row API, the final affected gate passes in 41 seconds and freshly reruns both corrected cases; the other 84 retain the preceding execution. The unchanged 340 World units and five affected Game Session cases retain their preceding fresh run, while the 489 Common units retain their 10:00–10:01 execution. No new unfiltered 86-case run is claimed. Rebuilt fresh and restart status is recorded separately below; controlled storage proof does not establish genuine Account/Game Design authority or enabled canonical admission. + +Rebuilt fresh bootstrap and same-version restart on that source both pass WebSocket and Telnet `WORLDS` → `LOGIN` → `PLAY` → `LOOK`. Original-capability cleanup succeeds and the exact run-owned project retains zero containers. Fixture mode is forced off, so this qualifies the ordinary predecessor baseline only. The subsequent normal develop carry changes only the Kubernetes Redis exporter image pin; all affected source, build and Compose postimages remain unchanged. Current published-head CI and allocated review remain required. + +The current source-first reconstruction separates canonical World evidence and explicit owner preparation from the retained predecessor bootstrap. `RunOwnedCanonicalWorldLaunchEvidenceProvider` reads the actual canonical Game Session source allocation; explicit owner preparation composes World source/Version and fixed-preset storage. The generic prepare RPC retains predecessor dispatch, while the published verifier, scheduled demo topology, and fixture preparation/activation dispatch remain available to the retained bootstrap. At World candidate `4ae539f3e4538b22891477a90ffd3015f534356f`, the earlier full check used 336 World unit cases reused unchanged from the prior fresh R3 execution and ran 83 fresh World integrations (81 PostgreSQL and two controlled mTLS), plus one fresh Game Design cross-service case, with zero failures, errors, or skips. At Game Design source commit `46074cf976759e3fb19cafc0bea7d16e544db555`, 519 unit and 141 native cases passed fresh. Generation, static, formatting, link, and Markdown checks passed. The canonical full World check at receiving HEAD `7c33684ac8666356fc444f2293ab2afa60a62a6f` passed in 2m37 with 338 fresh unit and 83 fresh native cases (81 PostgreSQL and two controlled mTLS), with zero failures, errors, or skips; `generateJooq`, service check, static, formatting, link, and Markdown gates passed. Fresh cross-service execution `14792` exercised World candidate `4ae539f3e4538b22891477a90ffd3015f534356f` with Game Design source commit `46074cf976759e3fb19cafc0bea7d16e544db555`; receiving execution `7500` reran that case on World source commit `2807d8b8d76cc8a4f4e86e20d255fcac58bc381e` after redistribution. The case exercised actual Game Design and Game Session protected owner-read paths with TLS/PostgreSQL. World explicit-owner invocation used controlled peer/certificate evidence through reflection, not a registered canonical World production RPC. SQL probes used controlled tables/rows and retained-byte/`xmin` checks; they do not establish current Human authority. This qualifies the stated source, SQL, and owner proof, while canonical World activation, holds, first-`OPEN`, and genuine handoffs remain open. + +The qualified #3206 predecessor passed its rebuilt baseline and same-version restart over WebSocket and Telnet `WORLDS`/`LOGIN`/`PLAY`/`LOOK` with authenticated teardown; its packaged scripts forced fixture mode off, so those results qualify only the ordinary default-off baseline. The current candidate’s rebuilt fresh default-off baseline passed WebSocket and Telnet `WORLDS`/`LOGIN`/`PLAY`/`LOOK`. For source `7c33684ac8666356fc444f2293ab2afa60a62a6f`, same-version restart passed both transports and original-capability cleanup succeeded; the exact project `gameplay3211-h2-fixes-20261015-080832` had zero containers at 08:13 UTC. Its packaged scripts force fixture mode off, so this qualifies only the ordinary default-off baseline, not the enabled fixture flow or canonical admission/first-`OPEN`. + +The V1042.7 predecessor storage exception and its exact transition predicates are owned by [World runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md#fixed-fixture-preparing-owner). The four predecessor transitions and failure/termination owner boundaries are physically qualified at the controlled scope below, including exact peer/certificate checks, unresolved-hold refusal, Entity-cleanup failure retention, rollback and local finalization. The SQL and migration probes use controlled tables/rows and retained-value, byte and `xmin` comparisons; they do not establish current Human authority or a retained deployment cohort. Canonical fixture activation and Human guards remain closed. The storage exception is temporary; its retirement conditions are defined by the owning contract. + +Historical qualification before this source-first separation: + +The canonical launch-owner predecessor added authenticated fixed Game Session `STARTING` allocation readback and refused World fixture preparation/activation before owner effects. The historical PREPARING successor below composed the World-owned sealed topology through the synchronous prepare RPC; bootstrap, activation and admission remain unavailable. That source read grants no World lifecycle, first admission, Entity or operational-region authority. After the ordinary carry of [PR #3203](https://github.com/benhook1013/FireMUD/pull/3203) at `3ae5fffd4aec52101739c78d89cd6bd0ce5f9935`, the selected successor at `4cee3da213ad2b4d1ba27a4bbb7e418efee88a8a` passed its World whole-service check, formatting, static analysis and documentation checks in 2m43s: 292 fresh unit cases and 65 fresh service integration cases, with zero failures, errors or skips. The integration cases comprise 63 PostgreSQL-backed cases and two controlled mTLS socket tests. The socket cases qualify authentication and exact echo against controlled remote handlers; the database cases qualify before-effects refusal and independent passive storage, original rows/bytes/`xmin`, constraints and CAS. They establish neither a live remote Game Session producer, complete-commit producer, World activation nor packaged runtime. All four genuine handoffs remain open. + +### Fixed fixture source and Version owner preparation + +The local follow-on implements typed source intake and Version association after exact current Game Session peer revalidation, with independent source/Version reads and committed World receipt readback. Focused unit cases cover before-effects peer/caller denial, transaction ordering, source substitution, exact replay, retained Version state/epoch conflicts and missing or substituted readback. The whole World gate passes 306 fresh unit cases and 65 fresh service integrations, with formatting and static checks. Those earlier integrations comprise 63 PostgreSQL-backed cases and two controlled mTLS socket cases; they did not exercise the new typed overloads against a live producer. The complete PREPARING owner phase below separately qualifies actual producer/socket composition and materialization. Activation, holds, admission and packaged fresh/restart remain unqualified. The [API contract](../../architecture/microservices/world-management-service/api-contracts.md#implementation-status) owns the local authorization boundary; no genuine handoff is closed. + +### Fixed fixture PREPARING owner preparation + +The terminal Hosted fix batch is qualified at `9e7c82733de22a61d06b1c614400f4169c990d66`, after carrying the fresh-first-entry seeder proof from readiness `eb5919603622be08808d41612e2391428a9ea53f` and producer `683f5079de05cb9a46d06afaef9d480280d637a3`. Initial fixed-preset planning rejects script/remap overrides before canonical allocation/materialization; earlier independently valid typed intake can already commit. Null intake transaction results retain their storage-evidence classification, and reconstructed fixture associations use byte-content value equality. Forward V1042 restores explicit required-field checks without changing published V1040/V1041 or the 33 donor postimages. + +Historical qualification before V1042.1–V1042.3: owning generation and affected static/format/documentation checks pass. R249 freshly executes 318 World units and 17 Game Design fixture/native cases, including the corrected first-entry commit/rollback case and actual three-production-handler PREPARING composition. Its 22 selected Game Design unit results are reused from their earlier unchanged execution. R251 passes 11 freshly executed focused PostgreSQL cases in 49 seconds; the other 65 unchanged World native cases retain R250 attribution. That historical proof includes fresh 76-file default installation, installed 34→40→75→76 upgrade, an owner-created controlled fixture at 75, all retained row values/bytes/`xmin`, legacy rollback, and actual installed CHECK expressions rejecting required NULL fields as FALSE rather than UNKNOWN. The two preceding failures were obsolete test comparisons after intentional fixture creation, not migration mutation; their raw failed results remain separately retained. Schema-1 Human CHECK-expression proof does not establish authorized historical Human row creation. Packaged startup/restart, activation, holds, admission and all four genuine handoffs remain open. + +The 79-file frontier added V1042.1 for service-schema execution-terminal lookup, V1042.2 for fixed-preset read transaction isolation and V1042.3 for fixture-row mutation diagnostics, bringing the default World inventory to 79 files. The later qualified PostgreSQL suites exercised that frontier and preserved parent upgrades; their attribution is separate from R249/R251 above. The three-service PREPARING proof now belongs to Game Design's dedicated cross-service suite; ordinary Game Design integration tests have no Game Session or World application resources on their classpath. Fixture prepare responses echo the original authenticated Game Session tenant, instance and Version keys while independently retained World rows keep their private keys. The CLI4 correction qualifies 324 fresh World unit cases and 77 native service cases with zero failures, errors or skips, plus the actual Game Design/Game Session/World three-service cross-service case. Game Design's full run executed 517 unit and 141 native cases; two transaction-status assertions initially failed and then passed in the 11-case focused owner rerun after explicitly excluding unsupported nesting from connection-acquisition retries. The 141 native cases passed on the subsequent full run; the earlier isolated container-port refusal remains unexplained and its failed evidence is retained. Owning static, formatting and documentation checks pass. Activation and packaged/runtime authority remain open. + +The Hosted4 owner-copy correction added forward V1042.4, bringing that World inventory to 80 files without changing prior migration bytes. It compares all ten copied realm, catalog, playtest and release fields against the retained World row. Eleven unchanged focused PostgreSQL cases retain their passing execution from the initial correction run; the corrected owner-transaction regression independently passes all ten mismatch variants, preserving every stored row and `xmin`. That regression uses a test-only row fault between the actual one-use execution guard and owner-copy validator, with all production guards retained and the injected trigger/function removed afterward. The earlier failed test setup and identifier-length attempts remain failed evidence. Generation passed before the focused correction; final formatting and static checks passed in a separate 33-second gate, followed by a 20-second documentation gate. These are controlled storage proofs, with activation, Account/Entity authority and packaged admission still unavailable. + +The CLI6 correction adds forward V1042.5, bringing that frontier to 81 files. Fixed-preset readback requires both complete ROOM matches. Twelve focused World PostgreSQL cases and ten Game Design unit cases execute freshly with zero failures, errors or skips; generation, static, formatting and documentation checks pass in one 1m 28s gate. The room regression uses test-local copies of the installed read function with each room-name expectation changed independently: the earlier any-room predicate accepts the mismatch, the corrected predicate rejects it, all stored rows and `xmin` remain unchanged, and the original installed read still succeeds. This proves the predicate against controlled read expectations rather than bypassing storage guards to manufacture corrupt rows. The Game Design cases exercise authorized repository and transaction failures, including corrected permanent Version transaction errors reported as `INTERNAL` rather than retryable `UNAVAILABLE`. Earlier failed compile and status-mapping attempts remain failed evidence. Actual three-owner composition retains its earlier attribution; activation and packaged admission remain unqualified. + +The Hosted5 correction adds forward V1042.6, bringing that World inventory to 82 files without changing published V1010/V1019 or other migration bytes. The complete terminal-binding conjunction must evaluate to TRUE, and an APPLIED location result must match its own operation identity. Thirteen World PostgreSQL cases execute freshly with zero failures, errors or skips in the corrected 1m34s gate, with static, formatting and documentation checks. Twelve Game Design Realm policy PostgreSQL cases passed in the preceding invocation and retain that unchanged-source execution; that overall invocation failed at compilation of the new World test due to an ambiguous assertion overload. The controlled probes copy the installed CHECK and deferred function: all eight required keys are tested absent and JSON null, and the old borrowed-operation counterexample is accepted before repair and denied afterward while matching identity succeeds. Original function/trigger metadata, migration history and untouched production location rows are verified. These are predicate proofs, not Account-authorized production abort or placement. Activation, packaged fresh/restart and genuine player admission remain unqualified. + +The normal carry of readiness child `a9e5f7a925555e5e0c0bcf7d78756966c7521d5f` on producer `493990e46f6f98785ed9f834633d97ca68c56022` is qualified at receiving merge `f24354e05410176bf695451c6b0fe6d3b1510c48`: 22 affected Game Design unit cases, all 17 selected fixture/native cases and all 17 TCP cross-service cases execute freshly with zero failures, errors or skips. Game Design static/format checks and documentation checks pass. Constructor-injected creation/policy owners preserve the unique typed reads and actual three-service PREPARING composition; the corrected parent harness supplies the actual Game Logic HTTP endpoint and retains ports across restart. These remain controlled native fixtures, with earlier broader owner proof separately attributed; no claimed packaged runtime, genuine handoff or activation authority is established. + +The corrected receiving child `7ab19d077f021b044b2d45409d892324c6204a48` restores the exact original Game Session V1005/V1006 artifacts and adds forward V1011. Its normal carry at `ec340c6a41a53127ca6fb3b57c399c12c843108e` passes ten freshly executed Game Session original-history PostgreSQL cases and 17 freshly executed Game Design fixture cases, including the actual three-service mTLS composition, with zero failures, errors or skips. Owning generation, affected formatting, documentation and the pinned-parent Flyway check pass. This re-establishes the affected original-history and producer composition boundary; unchanged broader owner proof retains its separate attribution below. Actual deployment cohorts and mixed original/edited histories remain unqualified, and no genuine handoff is closed. + +Receiving qualification after the normal carry of readiness [PR #3210](https://github.com/benhook1013/FireMUD/pull/3210) at `f9e62a9b99850dc9cb526635e416f25e91f0e908` passes on local merge `a5f76d8cfa2092f01ccfe6ad0641878b8adc362b`: 486 Common unit cases, 515 Game Design unit cases and 142 native integrations, and 314 World unit cases and 75 native integrations execute freshly with zero failures, errors or skips. Whole-service static, formatting and documentation checks pass. The native three-service case retains actual authenticated producer/owner handlers and independently committed PREPARING readback under controlled capabilities and PKI. Earlier failed runs and their source attribution remain distinct; this result does not establish a cause for interrupted PostgreSQL test containers or qualify an already-applied alternate Game Session V1005/V1006 history. Published exact-head CI, packaged fixture startup/restart and genuine handoff closure remain separate. + +Historical qualification before V1042–V1042.3: the local owner successor contained the complete migration dependency frontier and a PREPARING-only extension, with 35 added SQL paths within 75 complete World plus Saga history files. Main verified all 33 preserved V1008–V1039/V1009.1 donor postimages byte-for-byte. On the local `3e3cd7902cf238cb2756682502f8f45833e37df7` baseline plus archived owner postimages, the whole World check passed formatting/static validation, 307 unit results were reused from their preceding fresh execution, and 75 integrations were freshly executed (73 PostgreSQL-backed and two controlled mTLS). Game Design separately passed all 142 freshly executed integrations, including actual GDS producer → persisted GS `STARTING` → World `PREPARING` over three production mTLS socket handlers. The subsequent correction to native parent-file enumeration passed nine freshly executed storage-upgrade cases and all required Game Design static checks; its 510 unit results were reused from earlier unchanged production inputs. Exact source and XML archives retained these separate scopes. The synchronous prepare entry used fresh remote reads before SQL and preserved ordinary `REQUIRED` transactions. + +At that historical frontier, the 75-file default-order installation, installed 34→40→75 upgrade, schema-2 snapshot retention at that 75-file frontier, exact topology/manifest readback, rollback/races and reconstructed-owner retry passed physical execution. The GDS fixed read adapters were registered in a real managed annotation context with actual producer owners before serving their production handlers. Controlled test capabilities and PKI remained distinct from an actual claimed Compose deployment; complete packaged/Spring Boot fresh/restart proof remained open. Historical pre-1037 canonical Human schema-1 allocation retention was unconstructed because its genuine preparation/execution prerequisites were unavailable; no fake Account protection or disabled storage guard supplied that coverage. Historical guarded positive storage was explicitly pinned to 1007.1 and did not qualify current Account/APPLIED authority. Fixture bootstrap, activation, hold acquire/finalize, first OPEN prerequisites and initial placement stayed unavailable; no Entity or operational-region evidence was claimed. The [storage contract](../../architecture/microservices/world-management-service/runtime-and-data.md#fixed-fixture-preparing-owner) owns the local persistence consequence. All four genuine handoffs remain open. ### Guarded graph capture and frozen owner stage @@ -38,7 +94,7 @@ The later storage-classification and typed launch-scope correction `6d41311efe75 This tracker is the permanent reader-facing implementation record for world runtime, room reads, movement, lifecycle orchestration, and Draft topology mutation. Canonical target-state design remains under [design/architecture](../../architecture/README.md). -The retained initial-admission code includes the typed Game Session workload-only acquire RPC, durable World holds, lifecycle-row termination serialization and fail-closed reconciliation. The source-first reconstruction retains the published coordinator and World fixture PREPARING/ACTIVE dispatch for the existing bootstrap. Canonical Game Session STARTING preparation and authenticated association read are explicit source operations, separate from that running bootstrap. They do not establish canonical World materialization, lifecycle, hold or first-OPEN authority. General owner integration, strict Account JOIN and production activation remain open. Current proof is qualified in [Current Status](#current-status) and the canonical owner boundary remains in [World runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md). +The retained initial-admission code includes the typed Game Session workload-only acquire RPC, durable World holds, lifecycle-row termination serialization and fail-closed reconciliation. The source-first reconstruction retains the published coordinator and World fixture PREPARING/ACTIVE dispatch for the existing bootstrap. Canonical Game Session STARTING preparation and authenticated association read are explicit source operations, separate from that running bootstrap. The separate explicit canonical World owner prepares source/Version/materialization; it is not selected by the generic prepare RPC. Canonical activation, hold and first-OPEN authority remain open. General owner integration, strict Account JOIN and production activation remain open. Current proof is qualified in [Current Status](#current-status) and the canonical owner boundary remains in [World runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md). The subsequent World/Game Design review-fix gate verifies fixed immutable graph/result/evidence serialization across application-mapper changes and direct PostgreSQL frozen-capture rejection/immutability guards. All 295 World unit cases passed in the preceding combined gate and were reused by the final World gate; all 64 PostgreSQL integrations ran freshly in that final gate, with no failures, errors or skips, plus World and affected Game Design static/formatting checks and Markdown/link validation. The Game Design gate passed 507 fresh unit cases, including the controlled schema-3 wire/gate and schema-2/4 refusal cases. Its broader PostgreSQL run selected 136 cases: 120 passed and 16 failed before assertions because a fixture endpoint refused connections; the cause remains unknown, so the full Game Design physical gate is not established by this run. This component proof does not qualify the missing complete-commit producer, positive live frozen capture, packaged runtime or activation. @@ -46,8 +102,8 @@ The subsequent World/Game Design review-fix gate verifies fixed immutable graph/ - `GR-2.1` / `AR-3.1`: [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) requires world runtime state to distinguish the durable playable-state namespace and `playableStateScope` from a disposable instance and to classify owner data before replacement. Current world instance and lifecycle evidence remains partial; no exhaustive S1/S2/S3 mapping or cleanup proof is claimed. - `AR-3.1`: [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) records the database lifecycle row/epoch and Temporal coordination boundary. Existing prepare/activate/terminate caveats, including blocking calls and missing stages, remain active gaps. -- `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` / `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, RPC/transaction separation, matching retained `TERMINATED` replay, and mismatched-ID rejection. Controlled predecessor PostgreSQL and authenticated mTLS proof also covers terminal-identity replay and conflict; the full frozen-owner-snapshot acknowledgement and final-CAS workflow and Temporal retry proof remain unqualified. The following capability note records V1042.8's controlled SQL-probe scope and its limits. +- `GR-2.1` / `SF-2.3`: Existing `WorldLifecycleCommandServiceImplTest` unit cases cover ordinary activation accepting the positive current epoch or immediately preceding `PREPARING` epoch and rejecting an older epoch, plus matching retained `TERMINATED` replay and mismatched-ID rejection. Separately, controlled predecessor owner and PostgreSQL proof qualifies cleanup-failure retention, rollback, and local finalization; controlled predecessor PostgreSQL and authenticated mTLS proof covers terminal-identity replay and conflict. The installed V1042.8 body probe passed at 08:07:58.960 UTC: it preserved the V1042.7 upgrade function OID, security, grants, trigger, and empty production rows; valid numeric-JSON and canonical decimal-string forms were accepted, while 13 malformed cases failed with SQLSTATE `23514`. The native [WorldTerminalAndLocationOwnerGuardsPostgresIntegrationTest](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldTerminalAndLocationOwnerGuardsPostgresIntegrationTest.java) V1042.6 upgrade path exercises omitted and JSON-null binding keys against test-local copies of the old and strict predicates, and the upgraded production terminal table is empty. It proves the `IS TRUE` predicate delta and empty-table upgrade only; V1042.6 validates every existing terminal row, so compatibility with arbitrary retained rows in external databases remains unproved. No incompatible required row or external disposition is established. This controlled V1042.8 empty-row probe does not qualify Human authority; the full frozen-owner-snapshot acknowledgement and final-CAS workflow and Temporal retry proof remain open. See the [World runtime and data owner](../../architecture/microservices/world-management-service/runtime-and-data.md#fixed-fixture-preparing-owner) and [V1042.8 migration](../../../services/world-management-service/src/main/resources/db/migration/V1042.8__world_terminal_affected_unit_validation.sql). - `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 registered `ApplyWorldDesignMutation` handler fails closed before any remote Game Design Draft read or local mutation dispatch. The owner-local mutation algorithm exists, but the live handoff is unavailable while complete caller/tenant authorization and publication proof are missing. World has no durable version-freeze row or commit-bound `versionStateEpoch`/`publicationFence` evidence; the registered ingress remains closed. 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). @@ -58,7 +114,7 @@ These links add decision provenance only; they do not upgrade world runtime, lif | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `GR-2.1` World topology, rooms, regions, and runtime instances | `partial`: the authored-world source-retention boundary is implemented through `WorldAuthoredSourceIntakeRepository`, `WorldAuthoredVersionIdentityRepository`, `WorldCompleteLaunchBindingRepository`, and `WorldDesignPublicationFenceRepository`, with migrations `V23.1`–`V27.2`; the guarded graph/capture stage adds `V1003`–`V1007.1`, without establishing that external databases applied them. This retained evidence does not activate a runtime or establish gameplay admission. Its focused source, identity, launch-binding, and publication-fence proof is recorded above and linked below. Version-scoped topology and the owner-local Draft mutation algorithm exist, but registered `ApplyWorldDesignMutation` ingress fails closed before dispatch pending complete caller/tenant authorization and owner publication proof; instance lifecycle exists, while generation still has hardcoded inputs, initial event scheduling is absent, and lifecycle prepare/activate retain blocking attestation calls. The retained initial-admission hold contributes to the `AR-3.1` lifecycle handoff through lifecycle serialization and exact owner-proof reconciliation; current fixture preparation does not acquire it. The published coordinator, seeder and fixture preparation/activation dispatch remain available for the retained bootstrap. Separate canonical STARTING preparation and association read are source operations; controlled source proof does not establish canonical materialization, lifecycle, hold or first-OPEN authority. Accepted publication and procedural-generation decisions now define World-owned topology, request-bounded replay, atomic visibility, explicit replacement, and sparse/full-grid boundaries; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | `audited`: World retains lifecycle and initial-admission hold storage and read boundaries. The retained bootstrap verifies the closed Game Design receipt using its published World fixed-evidence path; source-built baseline and same-version restart pass both transports with fixture mode disabled, qualifying only the ordinary default-off baseline; there is no current packaged proof of the enabled retained fixture coordinator. The separate canonical source preparation/read boundary does not qualify canonical materialization, lifecycle, hold or first-OPEN effects. | [World Management ownership](../../architecture/microservices/world-management-service/README.md); [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [initial-admission bind hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [InitialAdmissionBindHoldServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java); [InitialAdmissionBindHoldRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java); [V18 version-scoped templates](../../../services/world-management-service/src/main/resources/db/migration/V18__version_scoped_world_templates.sql); [V19 mutation ledger](../../../services/world-management-service/src/main/resources/db/migration/V19__world_design_mutation_ledger.sql); [V23 initial-admission hold](../../../services/world-management-service/src/main/resources/db/migration/V23__initial_admission_bind_hold.sql); [V23.1 source intake](../../../services/world-management-service/src/main/resources/db/migration/V23.1__world_authored_source_intake.sql); [V24 tenant mutation guard](../../../services/world-management-service/src/main/resources/db/migration/V24__world_canonical_tenant_mutation_guard.sql); [V25 publication fence](../../../services/world-management-service/src/main/resources/db/migration/V25__world_design_publication_fence.sql); [V26 launch binding](../../../services/world-management-service/src/main/resources/db/migration/V26__world_complete_launch_binding.sql); [V27 version identity](../../../services/world-management-service/src/main/resources/db/migration/V27__world_authored_version_identity.sql); [V27.1 publication owner binding](../../../services/world-management-service/src/main/resources/db/migration/V27.1__world_publication_owner_binding.sql); [V27.2 legacy tenant claim concurrency](../../../services/world-management-service/src/main/resources/db/migration/V27.2__world_legacy_tenant_claim_concurrency.sql); [V1003 authored graph snapshot](../../../services/world-management-service/src/main/resources/db/migration/V1003__world_authored_graph_snapshot.sql); [V1004 guarded region commits](../../../services/world-management-service/src/main/resources/db/migration/V1004__world_guarded_region_draft_commits.sql); [V1005 guarded UUID topology commits](../../../services/world-management-service/src/main/resources/db/migration/V1005__world_guarded_uuid_topology_commits.sql); [V1006 canonical frozen topology](../../../services/world-management-service/src/main/resources/db/migration/V1006__world_canonical_frozen_topology.sql); [V1007 digest schema 3 capture](../../../services/world-management-service/src/main/resources/db/migration/V1007__world_digest_schema3_capture.sql); [V1007.1 legacy update fastpath](../../../services/world-management-service/src/main/resources/db/migration/V1007.1__world_restore_stable_legacy_update_fastpath.sql); [WorldDraftTopologyCommitRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java); [WorldAuthoredGraphSnapshotCapture.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java); [RunOwnedWorldLaunchEvidenceProvider.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java); [RunOwnedWorldLaunchEvidence.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java); [V23.0.1 fixture binding](../../../services/world-management-service/src/main/resources/db/migration/V23.0.1__world_run_owned_fixture_launch_binding.sql) | [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [InitialAdmissionBindHoldServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java); [InitialAdmissionBindHoldRepositoryTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java); [InitialAdmissionBindHoldPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java); [RunOwnedWorldLaunchEvidenceProviderTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java); [RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java); [RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java); [WorldAuthoredSourceIntakeServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java); [WorldAuthoredVersionIdentityServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java); [WorldCompleteLaunchBindingServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java); [WorldDesignPublicationFenceCommittedReadTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceCommittedReadTest.java); [WorldAuthoredSourceIntakeIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java); [WorldAuthoredVersionIdentityIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java); [WorldCompleteLaunchBindingIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java); [WorldDesignPublicationFenceIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java); [WorldDesignPublicationFenceEvidenceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java); [WorldPublicationOwnerBindingMigrationIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPublicationOwnerBindingMigrationIntegrationTest.java); [WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java); [WorldGuardedAuthoredTopologyPlanTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredTopologyPlanTest.java) | [AR-3.1 lifecycle in Game Authoring](./game-authoring-publishing-and-activation.md); [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md) | Canonical fixture materialization, activation, continuous Account protection, hold acquisition and first OPEN remain unavailable; packaged runtime proof is limited to the ordinary default-off baseline with fixture mode disabled. Genuine owner handoffs, hold/termination race and restart recovery, strict Account JOIN and generalized runtime-ID migration remain open. Earlier tests retain their recorded revision attribution; source or fixture read evidence supplies no activation authority. | +| `GR-2.1` World topology, rooms, regions, and runtime instances | `partial`: the authored-world source-retention boundary is implemented through `WorldAuthoredSourceIntakeRepository`, `WorldAuthoredVersionIdentityRepository`, `WorldCompleteLaunchBindingRepository`, and `WorldDesignPublicationFenceRepository`, with migrations `V23.1`–`V27.2`; the guarded graph/capture stage adds `V1003`–`V1007.1`, without establishing that external databases applied them. This retained evidence does not activate a runtime or establish gameplay admission. Its focused source, identity, launch-binding, and publication-fence proof is recorded above and linked below. Version-scoped topology and the owner-local Draft mutation algorithm exist, but registered `ApplyWorldDesignMutation` ingress fails closed before dispatch pending complete caller/tenant authorization and owner publication proof; instance lifecycle exists, while generation still has hardcoded inputs, initial event scheduling is absent, and lifecycle prepare/activate retain blocking attestation calls. The retained initial-admission hold contributes to the `AR-3.1` lifecycle handoff through lifecycle serialization and exact owner-proof reconciliation; current fixture preparation does not acquire it. The retained published bootstrap remains separate from explicit canonical source preparation. The canonical owner materializes the sealed fixed preset at PREPARING epoch 1 and row version 0, but the generic RPC does not dispatch it; current source, SQL and owner proof is qualified above. Its concrete implementation includes [RunOwnedCanonicalWorldLaunchEvidenceProvider.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceProvider.java), [RunOwnedCanonicalWorldLaunchEvidence.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidence.java), [WorldAuthoredSourceIntakeService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java), [WorldAuthoredVersionIdentityService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityService.java), and [V1042.7](../../../services/world-management-service/src/main/resources/db/migration/V1042.7__world_predecessor_fixture_lifecycle_staging.sql). Canonical activation, holds and first OPEN remain unavailable. Packaged runtime proof is limited to the ordinary default-off baseline with fixture mode disabled; it does not qualify the enabled retained fixture coordinator or canonical admission. Accepted publication and procedural-generation decisions now define World-owned topology, request-bounded replay, atomic visibility, explicit replacement, and sparse/full-grid boundaries; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | `audited`: World retains lifecycle and initial-admission hold storage and read boundaries. Explicit canonical source preparation verifies the sealed receipt and authenticated Game Session STARTING allocation before owner storage; the generic RPC retains predecessor bootstrap behavior. The current source-first source and owner proof is qualified at the exact scope recorded above; bounded V1042.7 predecessor transition/failure/termination owner guards are qualified at the controlled proof scope recorded above. Canonical activation, holds and first OPEN remain unavailable. | [World Management ownership](../../architecture/microservices/world-management-service/README.md); [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [initial-admission bind hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [InitialAdmissionBindHoldServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java); [InitialAdmissionBindHoldRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java); [V18 version-scoped templates](../../../services/world-management-service/src/main/resources/db/migration/V18__version_scoped_world_templates.sql); [V19 mutation ledger](../../../services/world-management-service/src/main/resources/db/migration/V19__world_design_mutation_ledger.sql); [V23 initial-admission hold](../../../services/world-management-service/src/main/resources/db/migration/V23__initial_admission_bind_hold.sql); [V23.1 source intake](../../../services/world-management-service/src/main/resources/db/migration/V23.1__world_authored_source_intake.sql); [V24 tenant mutation guard](../../../services/world-management-service/src/main/resources/db/migration/V24__world_canonical_tenant_mutation_guard.sql); [V25 publication fence](../../../services/world-management-service/src/main/resources/db/migration/V25__world_design_publication_fence.sql); [V26 launch binding](../../../services/world-management-service/src/main/resources/db/migration/V26__world_complete_launch_binding.sql); [V27 version identity](../../../services/world-management-service/src/main/resources/db/migration/V27__world_authored_version_identity.sql); [V27.1 publication owner binding](../../../services/world-management-service/src/main/resources/db/migration/V27.1__world_publication_owner_binding.sql); [V27.2 legacy tenant claim concurrency](../../../services/world-management-service/src/main/resources/db/migration/V27.2__world_legacy_tenant_claim_concurrency.sql); [V1003 authored graph snapshot](../../../services/world-management-service/src/main/resources/db/migration/V1003__world_authored_graph_snapshot.sql); [V1004 guarded region commits](../../../services/world-management-service/src/main/resources/db/migration/V1004__world_guarded_region_draft_commits.sql); [V1005 guarded UUID topology commits](../../../services/world-management-service/src/main/resources/db/migration/V1005__world_guarded_uuid_topology_commits.sql); [V1006 canonical frozen topology](../../../services/world-management-service/src/main/resources/db/migration/V1006__world_canonical_frozen_topology.sql); [V1007 digest schema 3 capture](../../../services/world-management-service/src/main/resources/db/migration/V1007__world_digest_schema3_capture.sql); [V1007.1 legacy update fastpath](../../../services/world-management-service/src/main/resources/db/migration/V1007.1__world_restore_stable_legacy_update_fastpath.sql); [WorldDraftTopologyCommitRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java); [WorldAuthoredGraphSnapshotCapture.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java); [RunOwnedWorldLaunchEvidenceProvider.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java); [RunOwnedWorldLaunchEvidence.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java); [RunOwnedWorldFixedPresetResources.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResources.java); [WorldCanonicalInstanceAssociationRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java); [V1040 canonical association](../../../services/world-management-service/src/main/resources/db/migration/V1040__world_run_owned_fixture_canonical_association.sql); [V1041 fixed-preset preparation](../../../services/world-management-service/src/main/resources/db/migration/V1041__world_run_owned_fixed_preset_preparation.sql); [V1042 required-field checks](../../../services/world-management-service/src/main/resources/db/migration/V1042__world_canonical_association_required_field_checks.sql); [V1042.1 terminal schema](../../../services/world-management-service/src/main/resources/db/migration/V1042.1__world_execution_terminal_service_schema.sql); [V1042.2 read transactions](../../../services/world-management-service/src/main/resources/db/migration/V1042.2__world_fixed_preset_read_transaction.sql); [V1042.3 mutation diagnostics](../../../services/world-management-service/src/main/resources/db/migration/V1042.3__world_fixture_row_mutation_diagnostic.sql); [V1042.4 owner-copy checks](../../../services/world-management-service/src/main/resources/db/migration/V1042.4__world_fixture_association_owner_copy_checks.sql); [V1042.5 complete room readback](../../../services/world-management-service/src/main/resources/db/migration/V1042.5__world_fixed_preset_complete_room_readback.sql); [V1042.6 terminal and location ownership](../../../services/world-management-service/src/main/resources/db/migration/V1042.6__world_terminal_binding_and_location_operation_checks.sql); [V1042.7 predecessor lifecycle staging](../../../services/world-management-service/src/main/resources/db/migration/V1042.7__world_predecessor_fixture_lifecycle_staging.sql); [V1042.8 terminal affected-unit validation](../../../services/world-management-service/src/main/resources/db/migration/V1042.8__world_terminal_affected_unit_validation.sql); [V1042.9 guard subtransactions](../../../services/world-management-service/src/main/resources/db/migration/V1042.9__world_same_transaction_guard_subtransactions.sql); [V1042.10 initial-location retention](../../../services/world-management-service/src/main/resources/db/migration/V1042.10__world_initial_location_retention_guards.sql); [V1042.11 preparation transaction stamp](../../../services/world-management-service/src/main/resources/db/migration/V1042.11__world_preparation_full_transaction_stamp.sql); [V1042.12 receipt byte digests](../../../services/world-management-service/src/main/resources/db/migration/V1042.12__world_graph_application_receipt_byte_digests.sql); [V1042.13 start-location semantic receipt digest](../../../services/world-management-service/src/main/resources/db/migration/V1042.13__world_start_location_semantic_receipt_digest.sql); [V23.0.1 fixture binding](../../../services/world-management-service/src/main/resources/db/migration/V23.0.1__world_run_owned_fixture_launch_binding.sql) | [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [InitialAdmissionBindHoldServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java); [InitialAdmissionBindHoldRepositoryTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java); [InitialAdmissionBindHoldPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java); [RunOwnedWorldLaunchEvidenceProviderTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java); [RunOwnedCanonicalWorldLaunchEvidenceProviderTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceProviderTest.java); [RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest.java); [WorldCanonicalInstanceExecutionTerminalSchemaPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionTerminalSchemaPostgresIntegrationTest.java); [WorldTerminalAndLocationOwnerGuardsPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldTerminalAndLocationOwnerGuardsPostgresIntegrationTest.java); [RunOwnedWorldFixedPresetResourcesTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesTest.java); [RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [RunOwnedFixtureOwnerCompositionCrossServiceTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java); [RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java); [RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java); [WorldAuthoredSourceIntakeServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java); [WorldAuthoredVersionIdentityServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java); [WorldCompleteLaunchBindingServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java); [WorldDesignPublicationFenceCommittedReadTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceCommittedReadTest.java); [WorldAuthoredSourceIntakeIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java); [WorldAuthoredVersionIdentityIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java); [WorldCompleteLaunchBindingIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java); [WorldDesignPublicationFenceIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java); [WorldDesignPublicationFenceEvidenceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java); [WorldPublicationOwnerBindingMigrationIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPublicationOwnerBindingMigrationIntegrationTest.java); [WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java); [WorldGuardedAuthoredTopologyPlanTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredTopologyPlanTest.java) | [AR-3.1 lifecycle in Game Authoring](./game-authoring-publishing-and-activation.md); [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md) | Bounded fixture PREPARING materialization remains qualified by its controlled native proof; canonical activation, continuous Account protection, hold acquisition and first OPEN remain unavailable. Genuine owner handoffs, hold/termination race and restart recovery, strict Account JOIN and generalized runtime-ID migration remain open. Earlier tests retain their recorded revision attribution; source or fixture read evidence supplies no activation authority. | | `GR-2.2` Location, occupancy, movement, exits, and spatial reads | `partial` | `audited` | [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [World runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [system architecture](../../architecture/system-architecture-overview.md); [spatial and ambient effects](../../architecture/system-architecture-spatial-and-ambient-effects-catalog.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [WorldManagementGrpcService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java); [LookAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/LookAggregationService.java); [MoveAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/MoveAggregationService.java); [MoveCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/MoveCommandHandler.java); [room contract](../../../protos/world-management/v1/world_management_service.proto) | [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [LookAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/LookAggregationServiceTest.java); [MoveAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/MoveAggregationServiceTest.java); [MoveCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java); [movement idempotency test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java) | [authoring](./game-authoring-publishing-and-activation.md); [gameplay](./gameplay-rules-entities-and-effects.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [player experience](./player-experience-commands-and-communication.md) | Partial: directional LOOK and movement primitives exist, but the WMS `ListRoomOccupants` handler and target-only `character_location`/`npc_location` location and occupancy persistence are absent. Live `room_instance` topology and the Game Session room binding are not the World-owned location authority, and the final LOOK identity is not yet the causal floor plus opaque World/Entity component versions; served-through proofs remain separate participant validation evidence. DROP/PICKUP also lack the target World `TargetingFactSnapshot` location/version validation in the Entity-local commit. [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md) remains applied; implementation and proof gaps remain. Accepted full-grid topology decision now defines density-independent movement semantics and opaque scalable representation; large-grid identity, chunk/root finalization, base-plus-delta recovery, and movement-policy proof remain incomplete. | | `GR-2.3` Ambient, environmental, and scheduled world state | `partial` | `audited` | [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [World runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [spatial and ambient effects](../../architecture/system-architecture-spatial-and-ambient-effects-catalog.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md) | [WorldEventServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldEventServiceImpl.java); [WorldManagementGrpcService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java); [RoomSnapshotDto.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/RoomSnapshotDto.java); [V3 world events](../../../services/world-management-service/src/main/resources/db/migration/V3__world_events.sql); [V16 runtime event scope](../../../services/world-management-service/src/main/resources/db/migration/V16__runtime_world_event_scope.sql) | [WorldEventServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldEventServiceImplTest.java); [RoomSnapshotDtoTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/dto/RoomSnapshotDtoTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java) | [authoring](./game-authoring-publishing-and-activation.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [gameplay](./gameplay-rules-entities-and-effects.md) | Partial: scheduled non-Weather event processing and ambient snapshot shape exist, but `ApplyRoomAmbientStatePatch` has no Java handler, durable effect-idempotency and general ambient patches are absent, and the creation workflow does not schedule initial events. Live `WorldEventService` rejects new `WEATHER_CHANGE` scheduling and leaves retained Weather rows unprocessed; the unresolved selector/fenced effect contract still blocks safe ambient mutation, so current code is not proof of the target World-owned fenced ambient-mutation contract. [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md) remains the target owner; its World-side handler, durable replay guard, and focused proof remain unimplemented. | @@ -115,7 +171,7 @@ These links add decision provenance only; they do not upgrade world runtime, lif - World creation, activation, failure, termination, and the retry/repair lifecycle use the canonical `world-lifecycle` Temporal workflow when Temporal is enabled. The workflow owns prepare, activate, fail, and terminate orchestration and follows the shared `common-temporal` workflow identity and task-queue conventions. - When Temporal is not enabled, `WorldInstanceActivationService` delegates to the same extracted command service so local non-Temporal application contexts still boot and use the same lifecycle commands. - `GetWorldInstanceLifecycle` exposes deterministic workflow identity and Temporal execution status to operators through the control-plane read surface. The existing class-A pre-activation versus class-B gameplay boundary is preserved; gameplay runtime, tick execution, and live in-world mutation remain outside the Temporal path. -- For an in-progress termination, the orchestrator waits for a `TERMINATED` snapshot matching the exact tenant and game instance without deriving a terminal epoch from the retry argument; [TemporalWorldLifecycleOrchestratorTest](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/TemporalWorldLifecycleOrchestratorTest.java) covers current-epoch retry, initial termination completion, and refusal of nonterminal or wrong-scope snapshots. Temporal activation/failure retries do not yet preserve business operation identity/results after a lost response: the command checks the old epoch before its terminal-state idempotency check, and StartSession compensation is not ACTIVE-aware. Exact terminal retries can also signal a closed workflow after Temporal marks fail/terminate complete. Durable operation-result reconciliation, ACTIVE-aware compensation, durable-row reconciliation before signaling, and focused retry/closed-workflow proof remain incomplete. Prepare and activate still perform blocking Game Design attestation calls inside transactional command methods; the no-open-transaction-across-blocking-gRPC invariant remains incomplete there. +- For an in-progress termination, the orchestrator waits for a `TERMINATED` snapshot matching the exact tenant and game instance without deriving a terminal epoch from the retry argument; [TemporalWorldLifecycleOrchestratorTest](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/TemporalWorldLifecycleOrchestratorTest.java) covers current-epoch retry, initial termination completion, and refusal of nonterminal or wrong-scope snapshots. An ordinary activation retry against `ACTIVE` accepts the positive current epoch or the immediately preceding `PREPARING` epoch, and older epochs are rejected by existing unit cases. Failure-epoch retry after a lost response and durable Temporal operation identity/result reconciliation remain incomplete, as does ACTIVE-aware StartSession compensation. Exact terminal retries can also signal a closed workflow after Temporal marks fail/terminate complete. Durable operation-result reconciliation, ACTIVE-aware compensation, durable-row reconciliation before signaling, and focused retry/closed-workflow proof remain incomplete. Prepare and activate still perform blocking Game Design attestation calls inside transactional command methods; the no-open-transaction-across-blocking-gRPC invariant remains incomplete there. - World Management owns world-change notification production for Game Session and Automation, while Game Session owns gameplay-session/tick sharding, leases, and coordination. The current notification path and broader shard/load-balancing behavior are not a completed substitute for those ownership boundaries. ### Draft World Topology, Generation, and Mutation Authority @@ -147,9 +203,9 @@ These links add decision provenance only; they do not upgrade world runtime, lif - World Management still needs the authoritative character/session location-transition mutation contract used by live movement; the current Game Session binding update is not a substitute for that ownership boundary. - Prepare and activate lifecycle commands still hold local transactions across blocking Game Design attestation reads; they need the same staged/fenced transaction separation already used around termination cleanup. - The current Weather path is fail-closed while its selector and typed effect fence remain unresolved: new `WEATHER_CHANGE` scheduling is rejected before persistence, retained Weather rows remain unprocessed and non-mutating, and region-bearing non-Weather events require exact tenant/game-instance scope matching. Focused service proof covers the containment and valid non-Weather path; PostgreSQL integration proof covers Weather exclusion, exact tenant/game-instance scope, and single-claim `SKIP LOCKED` behavior. Safe Weather admission and retained-row reconciliation remain open. -- Temporal activation/failure retries still lack durable operation-result reconciliation after a lost response, and StartSession compensation does not reconcile an already-`ACTIVE` world. Exact retries after fail/terminate workflow completion can signal a closed workflow instead of returning the durable terminal result; focused retry, compensation, and closed-workflow proof remains absent. +- Failure-epoch retry and Temporal activation/failure retries still lack durable operation-result reconciliation after a lost response; ordinary activation against `ACTIVE` accepts the current or immediately preceding `PREPARING` epoch, with older epochs rejected. StartSession compensation does not reconcile an already-`ACTIVE` world. Exact retries after fail/terminate workflow completion can signal a closed workflow instead of returning the durable terminal result; focused retry, compensation, and closed-workflow proof remains absent. - Replacement cutover still lacks the World-owned one-shot hold record/readback contract: exact source/target `ACTIVE` epoch locking, the nonterminal-hold termination predicate, hold-bound Game Session pointer transaction, safe abort/finalize reconciliation, diagnostic-only expiry, and focused proof. This remains target implementation drift; it does not introduce a new world lifecycle state. -- Canonical Game Session `STARTING` creation with independent readback belongs to the explicit `RunOwnedCanonicalLaunchPreparationOwner` call; its write has no scheduler, and its fixed allocation read is a separate authenticated source operation. Canonical World materialization/activation, the canonical initial-admission hold and first `OPEN` remain unqualified here. The retained published seeder and fixture `PREPARING`/`ACTIVE` dispatch remain available for the predecessor bootstrap; `RunOwnedInitialAdmissionFixtureCoordinator` follows the legacy World hold and admission-owner path. The packaged fresh/restart `PLAY`/`LOOK` verification ran with fixture mode disabled, so it proves the ordinary default-off baseline, not the enabled fixture coordinator. General `StartSession` retries, strict Account `JOIN` validation through commit, production activation, hold/termination race and restart recovery remain open; World expiry is diagnostic and ambiguous outcomes never release a termination fence. See the canonical [initial-admission bind hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract), [Game Session API](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status), and [focused integration proof](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java). +- Canonical Game Session `STARTING` creation with independent readback belongs to the explicit `RunOwnedCanonicalLaunchPreparationOwner` call; its write has no scheduler, and its fixed allocation read is a separate authenticated source operation. The retained published seeder and fixture `PREPARING`/`ACTIVE` dispatch remain available for the predecessor bootstrap; `RunOwnedInitialAdmissionFixtureCoordinator` follows the legacy World hold and admission-owner path. The source-first World source/Version and fixed-preset preparation, together with predecessor lifecycle/owner proof, is qualified under [Current Status](#canonical-fixture-launch-receiving-boundary). Canonical activation, hold acquisition/finalization, and first `OPEN` remain unqualified. The packaged fresh/restart `PLAY`/`LOOK` verification ran with fixture mode disabled, so it proves the ordinary default-off baseline, not the enabled fixture coordinator or canonical admission. General `StartSession` retries, strict Account `JOIN` validation through commit, production activation, hold/termination race and restart recovery remain open; World expiry is diagnostic and ambiguous outcomes never release a termination fence. See the canonical [initial-admission bind hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract), [Game Session API](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status), and [focused integration proof](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java). - Starter-region preparation still persists hard-coded `SimpleDungeonGenerator` metadata and does not consume the frozen published generation inputs and provenance required by the launch descriptor. - Initial world-event scheduling is absent from the current prepare path despite being canonical lifecycle step 2. - Omitted optional terrain/population stages have no durable `SKIPPED_NOT_REQUIRED` outcome or operator-facing projection, so current lifecycle status cannot distinguish intentional omission from not-started or failed work. diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/TlsCertificateWatcherTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/TlsCertificateWatcherTest.java index fe2f9580a1..7592dc7b64 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/TlsCertificateWatcherTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/TlsCertificateWatcherTest.java @@ -399,6 +399,7 @@ void callbackFailureDoesNotStopWatching(@TempDir Path directory) throws Exceptio AtomicInteger attempts = new AtomicInteger(); CountDownLatch firstAttempt = new CountDownLatch(1); CountDownLatch successfulRetry = new CountDownLatch(1); + CountDownLatch allowSuccessfulRetry = new CountDownLatch(1); WatcherCounts baseline = watcherCounts(TlsCertificateWatcher.health()); try (TlsCertificateWatcher watcher = @@ -410,12 +411,24 @@ void callbackFailureDoesNotStopWatching(@TempDir Path directory) throws Exceptio firstAttempt.countDown(); throw new IllegalStateException("simulated reload failure"); } + try { + // Keep failure observable until the test has checked unhealthy aggregate state. + allowSuccessfulRetry.await(); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while awaiting test recovery", exception); + } successfulRetry.countDown(); })) { - Files.writeString(certificate, "certificate-2"); - assertTrue(firstAttempt.await(5, TimeUnit.SECONDS)); - awaitUnhealthy(watcher); - assertHealthDelta(baseline, 1, 0, 1, TlsCertificateWatcher.health()); + try { + Files.writeString(certificate, "certificate-2"); + assertTrue(firstAttempt.await(5, TimeUnit.SECONDS)); + awaitUnhealthy(watcher); + assertHealthDelta(baseline, 1, 0, 1, TlsCertificateWatcher.health()); + } finally { + allowSuccessfulRetry.countDown(); + } assertTrue(successfulRetry.await(5, TimeUnit.SECONDS)); assertTrue(attempts.get() >= 2); diff --git a/services/game-design-service/build.gradle.kts b/services/game-design-service/build.gradle.kts index f404aca6d2..f8f3d405f2 100644 --- a/services/game-design-service/build.gradle.kts +++ b/services/game-design-service/build.gradle.kts @@ -20,6 +20,9 @@ testing { named("integrationTest") { sources.java.srcDir("src/sharedTest/java") } + named("crossServiceTest") { + sources.java.srcDir("src/sharedTest/java") + } } } @@ -28,5 +31,8 @@ dependencies { implementation(libs.aws.sdk.s3) testCompileOnly(libs.spotbugs.annotations) add("integrationTestCompileOnly", libs.spotbugs.annotations) + add("crossServiceTestCompileOnly", libs.spotbugs.annotations) + add("crossServiceTestImplementation", project(":game-session-service")) + add("crossServiceTestImplementation", project(":world-management-service")) testImplementation(libs.bouncycastle.pkix) } diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java new file mode 100644 index 0000000000..db5e87639d --- /dev/null +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java @@ -0,0 +1,915 @@ +package crossservice.net.firedevops.firemud.gamedesign.data; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; + +import io.grpc.Context; +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.ResolvedGrpcTlsMaterial; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; +import net.firedevops.firemud.gamedesign.data.RunOwnedFixtureOwnerReadAuthorization; +import net.firedevops.firemud.gamedesign.data.TestDataSeederIntegrationSupport; +import net.firedevops.firemud.gamedesign.service.impl.RunOwnedFixtureAuthoredWorldSourceReadGrpcService; +import net.firedevops.firemud.gamedesign.service.impl.RunOwnedFixtureAuthoredWorldVersionStateGrpcService; +import net.firedevops.firemud.gamedesign.v1.AuthoredWorldSourceReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.AuthoredWorldVersionStateServiceGrpc; +import net.firedevops.firemud.gamesession.data.RunOwnedCanonicalLaunchPreparationOwner; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.service.impl.GameSessionControlPlaneGrpcService; +import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidence; +import net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidenceProvider; +import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldFixedPresetResources; +import net.firedevops.firemud.worldmanagement.service.impl.WorldLifecycleCommandServiceImpl; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationRepository; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.boot.DefaultApplicationArguments; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Import; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.PlatformTransactionManager; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SpringBootTest( + classes = GameDesignServiceApplication.class, + properties = { + "spring.profiles.active=test", + "spring.config.import=file:src/main/resources/application.yml", + "firemud.smoke.seed-demo-runtime.enabled=true", + "FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=false", + "spring.flyway.clean-disabled=false", + "firemud.auth.jwt-secret=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "firemud.grpc.plaintext=true", + "firemud.grpc.workload-namespace=dev", + "spring.grpc.server.port=0", + "asset.store.endpoint=http://localhost:9000", + "asset.store.bucket=test-bucket", + "asset.store.region=us-east-1", + "asset.store.access-key=test-access-key", + "asset.store.secret-key=test-secret-key" + }) +@Import(NoGrpcServerTestConfiguration.class) +class RunOwnedFixtureOwnerCompositionCrossServiceTest extends TestDataSeederIntegrationSupport { + @Container + static PostgreSQLContainer composedGameSessionPostgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static PostgreSQLContainer composedWorldPostgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void actualProducerAndCanonicalOwnersComposeOverMutualTlsOwnerReads(@TempDir Path testDirectory) + throws Exception { + assertThat(environment.getRequiredProperty("spring.application.name")) + .isEqualTo("game-design-service"); + var applicationNameOrigin = + environment.getPropertySources().stream() + .filter(source -> source.containsProperty("spring.application.name")) + .map( + source -> + org.springframework.boot.origin.OriginLookup.getOrigin( + source, "spring.application.name")) + .filter(java.util.Objects::nonNull) + .findFirst() + .orElseThrow( + () -> new AssertionError("spring.application.name has no config data origin")); + while (applicationNameOrigin + instanceof org.springframework.boot.origin.PropertySourceOrigin wrapper) { + applicationNameOrigin = + java.util.Objects.requireNonNull( + wrapper.getOrigin(), "spring.application.name origin wrapper has no concrete parent"); + } + assertThat(applicationNameOrigin) + .as("origin for spring.application.name: %s", applicationNameOrigin) + .isInstanceOf(org.springframework.boot.origin.TextResourceOrigin.class); + Path actualApplicationConfig = + java.util.Objects.requireNonNull( + ((org.springframework.boot.origin.TextResourceOrigin) applicationNameOrigin) + .getResource()) + .getFile() + .toPath() + .toRealPath(); + Path expectedApplicationConfig = Path.of("src/main/resources/application.yml").toRealPath(); + assertThat(actualApplicationConfig) + .withFailMessage( + "spring.application.name came from %s, expected GDS config %s", + actualApplicationConfig, expectedApplicationConfig) + .isEqualTo(expectedApplicationConfig); + + Map> postgresProperties = new LinkedHashMap<>(); + PostgresBackedServiceTestSupport.registerPostgresService( + postgresProperties::put, postgres, "game_design_service"); + String expectedFlywayLocations = + postgresProperties.get("spring.flyway.locations").get().toString(); + assertThat( + java.util.Arrays.stream(flyway.getConfiguration().getLocations()) + .map(org.flywaydb.core.api.Location::getDescriptor) + .toList()) + .containsExactlyInAnyOrder(expectedFlywayLocations.split(",")); + + Fixture fixture = prepareFixture(testDirectory); + configureSeeder(fixture); + seeder.run(new DefaultApplicationArguments(new String[] {})); + byte[] originalReceipt = Files.readAllBytes(fixture.receiptPath()); + var capability = + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .parseCapability(Files.readAllBytes(fixture.capabilityPath())); + var receipt = + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .parseSourceReceipt(originalReceipt, capability); + var gsDatabase = + composedOwnerDatabase(composedGameSessionPostgres, "game-session-service", "composed_gs"); + var worldDatabase = + composedOwnerDatabase(composedWorldPostgres, "world-management-service", "composed_world"); + assertThat( + worldDatabase + .dsl() + .fetchSingle( + "SELECT count(*) AS count FROM flyway_schema_history " + + "WHERE success AND type='SQL' AND version IS NOT NULL") + .get("count", Long.class)) + .isEqualTo(worldDatabase.versionedSqlMigrationCount()); + assertThat( + worldDatabase + .dsl() + .fetch( + "SELECT version FROM flyway_schema_history WHERE success " + + "AND version IN ('1009', '1009.1', '1010') ORDER BY installed_rank") + .getValues("version", String.class)) + .containsExactly("1009", "1009.1", "1010"); + // Consume unused real allocator values to exercise unequal private Version/instance numbers. + // Numeric values can naturally coincide across services; authority comes from typed owner + // bindings. + worldDatabase + .dsl() + .fetchSingle( + "SELECT nextval(pg_get_serial_sequence('world_authored_version_identity', 'local_version_key'))"); + worldDatabase + .dsl() + .fetchSingle("SELECT nextval('world_canonical_private_game_instance_key_seq')"); + worldDatabase.dsl().fetchSingle("SELECT nextval('world_instance_id_seq')"); + var catalog = + new GameSessionCanonicalRealmCatalogRepository( + gsDatabase.dsl(), gsDatabase.transactions(), NAMESPACE); + var launchOwner = + new GameSessionCanonicalInstanceLaunchRepository( + gsDatabase.dsl(), gsDatabase.transactions(), NAMESPACE, catalog); + var beanFactory = new org.springframework.beans.factory.support.StaticListableBeanFactory(); + beanFactory.addBean("actualLaunchOwner", launchOwner); + var gsTls = + fixedReadTls( + fixture, + fixture.gameSessionCertificatePath(), + fixture.gameSessionCertificatePath().resolveSibling("game-session.key")); + var worldTls = + fixedReadTls( + fixture, + fixture.worldManagementCertificatePath(), + fixture.worldManagementCertificatePath().resolveSibling("world-management.key")); + var preparationOwner = + new RunOwnedCanonicalLaunchPreparationOwner( + true, + fixture.capabilityPath().toString(), + fixture.receiptPath().toString(), + fixture.runId(), + fixture.composeProjectName(), + gsTls, + beanFactory.getBeanProvider(GameSessionCanonicalInstanceLaunchRepository.class), + NAMESPACE); + // The explicit production owner verifies real producer files and original mounted pins, + // creates the canonical STARTING allocation, and independently reads it back. No test-only GS + // carrier or scheduled coordinator path is used. + var startingOwnerEvidence = preparationOwner.prepareFixedVerifiedFixtureLaunch(); + var gsEvidence = startingOwnerEvidence.launchEvidence(); + var starting = startingOwnerEvidence.launch(); + assertThat(launchOwner.readVerifiedFixtureLaunch(gsEvidence)).isEqualTo(starting); + assertThat(starting.catalog().association().sourceEvidence()) + .isEqualTo(receipt.creationEvidence()); + assertThat(starting.catalog().snapshot().sourceIntakeReceipt().source()) + .isEqualTo(receipt.sourceEvidence()); + assertThat(starting.status()) + .isEqualTo( + net.firedevops.firemud.common.gamesession + .CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus + .STARTING); + assertThat(starting.rowVersion()).isZero(); + var registry = new io.micrometer.core.instrument.simple.SimpleMeterRegistry(); + var gsHandler = org.mockito.Mockito.spy(actualGsFixtureReadHandler(registry)); + gsHandler.configureRunOwnedFixtureLaunchAssociationReadBoundary( + preparationOwner, true, NAMESPACE); + var gdsLeaf = + issueFixedReadLeaf( + fixture, + "composed-game-design-server", + "spiffe://firemud/ns/dev/sa/game-design-service", + true); + var channels = new CopyOnWriteArrayList(); + var factory = composedChannelFactory(channels); + var servers = new java.util.ArrayList(); + net.firedevops.firemud.worldmanagement.client.GameDesignClient remoteDesign = null; + RunOwnedCanonicalWorldLaunchEvidenceProvider provider = null; + WorldLifecycleCommandServiceImpl commands = null; + var fixedOwnerContext = actualFixedReadContext(fixture); + try { + Server gdsServer = + fixedProductionServer( + fixture, + gdsLeaf, + Set.of( + "gamedesign.v1.GameDesignService/GetLaunchDescriptor", + AuthoredWorldSourceReadServiceGrpc.getResolveAuthoredWorldSourceMethod() + .getFullMethodName(), + AuthoredWorldVersionStateServiceGrpc.getGetAuthoredWorldVersionStateMethod() + .getFullMethodName()), + gameDesignGrpcService, + fixedOwnerContext.getBean(RunOwnedFixtureAuthoredWorldSourceReadGrpcService.class), + fixedOwnerContext.getBean(RunOwnedFixtureAuthoredWorldVersionStateGrpcService.class)); + servers.add(gdsServer); + Server gsServer = + fixedProductionServer( + fixture, + new FixedReadLeaf( + fixture.gameSessionCertificatePath(), + fixture.gameSessionCertificatePath().resolveSibling("game-session.key")), + Set.of( + net.firedevops.firemud.gamesession.v1.GameSessionControlPlaneServiceGrpc + .getGetRunOwnedFixtureLaunchAssociationMethod() + .getFullMethodName()), + gsHandler); + servers.add(gsServer); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("127.0.0.1:" + gdsServer.getPort()); + endpoints.setGameSessionService("127.0.0.1:" + gsServer.getPort()); + remoteDesign = + new net.firedevops.firemud.worldmanagement.client.GameDesignClient( + endpoints, + worldTls, + factory, + net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer.noop()); + ReflectionTestUtils.invokeMethod(remoteDesign, "init"); + provider = + new RunOwnedCanonicalWorldLaunchEvidenceProvider( + true, + fixture.capabilityPath().toString(), + fixture.receiptPath().toString(), + fixture.runId(), + fixture.composeProjectName(), + worldTls, + remoteDesign, + endpoints, + factory, + NAMESPACE); + var entityClient = + org.mockito.Mockito.mock( + net.firedevops.firemud.worldmanagement.client.EntityManagementClient.class); + commands = + actualWorldFixtureCommands( + worldDatabase, + provider, + remoteDesign, + entityClient, + endpoints, + worldTls, + factory, + registry); + var initialProvider = provider; + var initialCommands = commands; + var bundle = receipt.launchReadEvidence().publishedReleaseBundle(); + var originalGdsRows = fixedReadOwnerRows(); + var originalGsRows = allComposedOwnerRows(gsDatabase.dsl()); + RunOwnedCanonicalWorldLaunchEvidence worldEvidence = + withControlledGameSessionPeer(fixture, provider::requireAuthenticatedEvidence); + var request = exactPreparedWorldRequest(worldEvidence); + var emptyWorldRows = allComposedOwnerRows(worldDatabase.dsl()); + org.mockito.Mockito.clearInvocations(authoredWorldSourceRepository); + var changedSource = changedPreparedSourceEvidence(receipt.sourceEvidence()); + org.mockito.Mockito.doReturn(java.util.Optional.of(changedSource)) + .when(authoredWorldSourceRepository) + .read(any(UUID.class), any(UUID.class), any(String.class), any(String.class)); + org.assertj.core.api.Assertions.assertThatThrownBy( + () -> + withControlledGameSessionPeer( + fixture, + () -> + ReflectionTestUtils.invokeMethod( + initialCommands, "prepareRunOwnedFixture", request, worldEvidence))) + .isInstanceOf(RuntimeException.class); + assertThat(allComposedOwnerRows(worldDatabase.dsl())).isEqualTo(emptyWorldRows); + org.mockito.Mockito.verify(authoredWorldSourceRepository) + .read(any(UUID.class), any(UUID.class), any(String.class), any(String.class)); + org.mockito.Mockito.doCallRealMethod() + .when(authoredWorldSourceRepository) + .read(any(UUID.class), any(UUID.class), any(String.class), any(String.class)); + var prepared = + withControlledGameSessionPeer( + fixture, + () -> + (net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto) + ReflectionTestUtils.invokeMethod( + initialCommands, "prepareRunOwnedFixture", request, worldEvidence)); + assertThat(prepared).isNotNull(); + assertThat(prepared.status()).isEqualTo("PREPARING"); + assertThat(prepared.lifecycleEpoch()).isEqualTo(1L); + assertThat(prepared.tenantId()).isEqualTo(request.tenantId()); + assertThat(prepared.gameInstanceId()).isEqualTo(request.gameInstanceId()); + assertThat(prepared.versionId()).isEqualTo(request.versionId()); + var association = + independentlyReadWorldFixture(worldDatabase.dsl(), starting.gameInstanceUuid()); + var privateKeys = association.worldPrivateKeys(); + // Tenant numbers may coincide; typed World owner receipts establish independent authority. + assertThat(privateKeys.tenantId()) + .isEqualTo(association.runOwnedFixture().sourceIntakeReceipt().localTenantKey()); + assertThat(association.runOwnedFixture().sourceIntakeReceipt().source()) + .isEqualTo(receipt.sourceEvidence()); + assertThat(association.runOwnedFixture().sourceIntakeReceipt().sourceOperationId()) + .isEqualTo(receipt.sourceEvidence().operationId()); + assertThat(association.versionIdentity().sourceIntakeReceipt()) + .isEqualTo(association.runOwnedFixture().sourceIntakeReceipt()); + assertThat(association.versionIdentity().versionStateEvidence().sourceEvidence()) + .isEqualTo(receipt.sourceEvidence()); + assertThat(association.versionIdentity().versionStateEvidence().canonicalVersionId()) + .isEqualTo(UUID.fromString(bundle.getCanonicalVersionId())); + assertThat(privateKeys.versionId()) + .isEqualTo(association.versionIdentity().localVersionKey()); + assertThat(association.identity().canonicalGameInstanceId()) + .isEqualTo(starting.gameInstanceUuid()); + assertThat(association.runOwnedFixture().gameSessionTenantId()) + .isEqualTo(starting.catalog().association().gameSessionTenantId()); + assertThat(association.runOwnedFixture().gameSessionGameInstanceId()) + .isEqualTo(starting.gameInstanceId()); + assertThat(privateKeys.gameInstanceId()).isNotEqualTo(starting.gameInstanceId()); + assertThat(privateKeys.versionId()).isNotEqualTo(bundle.getVersionId()); + var stored = + new net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository( + worldDatabase.dsl()) + .findById(association.worldInstanceId()) + .orElseThrow(); + assertThat(stored.getStatus()).isEqualTo("PREPARING"); + assertThat(stored.getTenantId()).isEqualTo(privateKeys.tenantId()); + assertThat(stored.getGameInstanceId()).isEqualTo(privateKeys.gameInstanceId()); + assertThat(stored.getVersionId()).isEqualTo(privateKeys.versionId()); + assertThat(stored.getLifecycleEpoch()).isEqualTo(1L); + assertThat(stored.getRowVersion()).isZero(); + var materialized = + RunOwnedWorldFixedPresetResources.readCommitted( + worldDatabase.dsl(), + association, + association.runOwnedFixture().sourceIntakeReceipt(), + association.versionIdentity()); + assertThat(materialized.regionCount()).isEqualTo(1); + assertThat(materialized.zoneCount()).isEqualTo(1); + assertThat(materialized.roomCount()).isEqualTo(2); + assertThat(materialized.exitCount()).isEqualTo(2); + assertThat(materialized.presetContentDigest()) + .isEqualTo( + RunOwnedWorldFixedPresetResources.plan( + association, + association.runOwnedFixture().sourceIntakeReceipt(), + association.versionIdentity()) + .expectedContentDigest()); + assertThat(worldDatabase.dsl().fetchCount(DSL.table("world_authored_topology_identity"))) + .isEqualTo(6); + var definition = RunOwnedWorldFixedPresetResources.definition(); + var expectedTemplateIds = new java.util.ArrayList(); + expectedTemplateIds.add(definition.region().templateId()); + expectedTemplateIds.add(definition.zone().templateId()); + definition.rooms().forEach(room -> expectedTemplateIds.add(room.templateId())); + definition.exits().forEach(exit -> expectedTemplateIds.add(exit.templateId())); + assertThat( + worldDatabase + .dsl() + .fetch("SELECT template_id FROM world_authored_topology_identity") + .getValues("template_id", UUID.class)) + .containsExactlyInAnyOrderElementsOf(expectedTemplateIds); + assertThat( + worldDatabase.dsl().fetchCount(DSL.table("region_instance")) + + worldDatabase.dsl().fetchCount(DSL.table("zone_instance")) + + worldDatabase.dsl().fetchCount(DSL.table("room_instance")) + + worldDatabase.dsl().fetchCount(DSL.table("room_instance_exit"))) + .isEqualTo(6); + assertThat(worldDatabase.dsl().fetchCount(DSL.table("world_instance"))).isOne(); + assertThat(worldDatabase.dsl().fetchCount(DSL.table("initial_admission_bind_hold"))).isZero(); + assertThat(worldDatabase.dsl().fetchCount(DSL.table("world_canonical_player_admission_hold"))) + .isZero(); + assertThat( + worldDatabase + .dsl() + .fetchCount(DSL.table("world_canonical_instance_activation_operation"))) + .isZero(); + assertThat(worldDatabase.dsl().fetchCount(DSL.table("world_entity_spawn_binding"))).isZero(); + assertThat( + worldDatabase + .dsl() + .fetchSingle( + "SELECT count(*) AS count FROM room_instance_exit outward JOIN room_instance_exit inward " + + "ON outward.from_room_instance_record_id=inward.to_room_instance_record_id " + + "AND outward.to_room_instance_record_id=inward.from_room_instance_record_id " + + "WHERE outward.direction='NORTH' AND inward.direction='SOUTH'") + .get("count", Long.class)) + .isOne(); + var worldRows = allComposedOwnerRows(worldDatabase.dsl()); + assertThat( + withControlledGameSessionPeer( + fixture, + () -> + (net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto) + ReflectionTestUtils.invokeMethod( + initialCommands, + "prepareRunOwnedFixture", + request, + initialProvider.requireAuthenticatedEvidence()))) + .isEqualTo(prepared); + var reread = independentlyReadWorldFixture(worldDatabase.dsl(), starting.gameInstanceUuid()); + assertThat( + RunOwnedWorldFixedPresetResources.readCommitted( + worldDatabase.dsl(), + reread, + reread.runOwnedFixture().sourceIntakeReceipt(), + reread.versionIdentity())) + .isEqualTo(materialized); + assertThat(allComposedOwnerRows(worldDatabase.dsl())).isEqualTo(worldRows); + assertThat(allComposedOwnerRows(gsDatabase.dsl())).isEqualTo(originalGsRows); + assertThat(fixedReadOwnerRows()).isEqualTo(originalGdsRows); + assertThat(Files.readAllBytes(fixture.receiptPath())).containsExactly(originalReceipt); + // A caller-selected GS allocation mismatch is refused by the actual canonical owner before + // any additional materialization. + var mismatchedRequest = + new net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest( + request.tenantId(), + starting.gameInstanceId() + 1, + request.gameTemplateId(), + request.controlPlaneRequestId(), + request.launchDescriptorId(), + request.versionId(), + request.scriptPatchVersion(), + request.runtimeFlagsJson(), + request.generationConfigRevision(), + request.releaseBundleId(), + request.publishedReleaseBundleRef(), + request.versionStateEpoch(), + request.remapSetId()); + org.assertj.core.api.Assertions.assertThatThrownBy( + () -> + withControlledGameSessionPeer( + fixture, + () -> + ReflectionTestUtils.invokeMethod( + initialCommands, + "prepareRunOwnedFixture", + mismatchedRequest, + worldEvidence))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(allComposedOwnerRows(worldDatabase.dsl())).isEqualTo(worldRows); + org.mockito.Mockito.verifyNoInteractions(entityClient); + // Reconstruct actual World owners and all remote readers, retaining the original allocation. + ReflectionTestUtils.invokeMethod(commands, "closeRunOwnedWorldFixtureOwners"); + provider.closeGameSessionFixtureClient(); + remoteDesign.close(); + remoteDesign = + new net.firedevops.firemud.worldmanagement.client.GameDesignClient( + endpoints, + worldTls, + factory, + net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer.noop()); + ReflectionTestUtils.invokeMethod(remoteDesign, "init"); + provider = + new RunOwnedCanonicalWorldLaunchEvidenceProvider( + true, + fixture.capabilityPath().toString(), + fixture.receiptPath().toString(), + fixture.runId(), + fixture.composeProjectName(), + worldTls, + remoteDesign, + endpoints, + factory, + NAMESPACE); + commands = + actualWorldFixtureCommands( + worldDatabase, + provider, + remoteDesign, + entityClient, + endpoints, + worldTls, + factory, + registry); + var replayProvider = provider; + var replayCommands = commands; + var replayEvidence = + withControlledGameSessionPeer(fixture, provider::requireAuthenticatedEvidence); + assertThat( + withControlledGameSessionPeer( + fixture, + () -> + (net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto) + ReflectionTestUtils.invokeMethod( + replayCommands, "prepareRunOwnedFixture", request, replayEvidence))) + .isEqualTo(prepared); + assertThat(allComposedOwnerRows(worldDatabase.dsl())).isEqualTo(worldRows); + var reads = + org.mockito.ArgumentCaptor.forClass( + net.firedevops.firemud.gamesession.v1.GetRunOwnedFixtureLaunchAssociationRequest + .class); + org.mockito.Mockito.verify(gsHandler, org.mockito.Mockito.atLeast(2)) + .getRunOwnedFixtureLaunchAssociation(reads.capture(), any()); + assertThat(reads.getAllValues()) + .extracting(value -> value.getReadRequestId()) + .doesNotHaveDuplicates(); + // This is a controlled caller-context check, not a registered World RPC. A different leaf + // claiming the Game Session identity is rejected before any upstream owner read. + org.mockito.Mockito.clearInvocations( + gsHandler, launchDescriptorService, fixtureReadback, fixturePolicy); + var otherGsLeaf = + issueFixedReadLeaf(fixture, "different-game-session-client", SESSION_URI_SAN, false); + var wrongSessionCertificate = readCertificate(otherGsLeaf.certificate()); + org.assertj.core.api.Assertions.assertThatThrownBy( + () -> + withControlledPeer( + wrongSessionCertificate, replayProvider::requireAuthenticatedEvidence)) + .isInstanceOf( + RunOwnedCanonicalWorldLaunchEvidenceProvider + .InvalidRunOwnedCanonicalWorldLaunchEvidenceException.class); + org.mockito.Mockito.verifyNoInteractions( + gsHandler, launchDescriptorService, fixtureReadback, fixturePolicy, entityClient); + assertThat(allComposedOwnerRows(worldDatabase.dsl())).isEqualTo(worldRows); + assertThat(allComposedOwnerRows(gsDatabase.dsl())).isEqualTo(originalGsRows); + assertThat(fixedReadOwnerRows()).isEqualTo(originalGdsRows); + assertThat(Files.readAllBytes(fixture.receiptPath())).containsExactly(originalReceipt); + } finally { + try { + try { + if (commands != null) + ReflectionTestUtils.invokeMethod(commands, "closeRunOwnedWorldFixtureOwners"); + } finally { + try { + if (provider != null) provider.closeGameSessionFixtureClient(); + } finally { + if (remoteDesign != null) remoteDesign.close(); + } + } + } finally { + for (Server server : servers) server.shutdownNow(); + for (ManagedChannel channel : channels) channel.shutdownNow(); + try { + for (ManagedChannel channel : channels) + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + for (Server server : servers) + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } finally { + fixedOwnerContext.close(); + registry.close(); + } + } + } + } + + private GameSessionControlPlaneGrpcService actualGsFixtureReadHandler( + io.micrometer.core.instrument.MeterRegistry registry) throws Exception { + // Its public production constructor has package-private legacy parameter types. No fixture + // positive response or owner is mocked; only these unrelated, unused dependencies are doubles. + var constructor = GameSessionControlPlaneGrpcService.class.getConstructors()[0]; + var parameters = constructor.getParameterTypes(); + Object[] arguments = new Object[parameters.length]; + for (int index = 0; index < parameters.length; index++) { + arguments[index] = + parameters[index].isInstance(registry) + ? registry + : org.mockito.Mockito.mock(parameters[index]); + } + return (GameSessionControlPlaneGrpcService) constructor.newInstance(arguments); + } + + private org.springframework.context.annotation.AnnotationConfigApplicationContext + actualFixedReadContext(Fixture fixture) { + var context = new org.springframework.context.annotation.AnnotationConfigApplicationContext(); + context + .getEnvironment() + .getPropertySources() + .addFirst( + new org.springframework.core.env.MapPropertySource( + "actualImmutableFixture", + Map.ofEntries( + Map.entry("FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED", "true"), + Map.entry("firemud.grpc.workload-namespace", NAMESPACE), + Map.entry("FIREMUD_SMOKE_RUN_ID", fixture.runId()), + Map.entry("FIREMUD_SMOKE_COMPOSE_PROJECT_NAME", fixture.composeProjectName()), + Map.entry( + "FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH", + fixture.capabilityPath().toString()), + Map.entry( + "FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH", + fixture.receiptPath().toString()), + Map.entry( + "FIREMUD_SMOKE_GAME_SESSION_LEAF_CERT_PATH", + fixture.gameSessionCertificatePath().toString()), + Map.entry( + "FIREMUD_SMOKE_WORLD_MANAGEMENT_LEAF_CERT_PATH", + fixture.worldManagementCertificatePath().toString()), + Map.entry("firemud.grpc.ca-cert", fixture.caCertificatePath().toString())))); + context.getBeanFactory().registerSingleton("committedLaunchReadback", fixtureReadback); + context.getBeanFactory().registerSingleton("preexistingPolicyOwner", fixturePolicy); + context.getBeanFactory().registerSingleton("actualSourceOwner", authoredWorldSourceRepository); + context.getBeanFactory().registerSingleton("actualTransactions", transactionManager); + context.register( + RunOwnedFixtureOwnerReadAuthorization.class, + RunOwnedFixtureAuthoredWorldSourceReadGrpcService.class, + RunOwnedFixtureAuthoredWorldVersionStateGrpcService.class); + try { + context.refresh(); + assertThat(context.getBean(RunOwnedFixtureOwnerReadAuthorization.class)).isNotNull(); + return context; + } catch (RuntimeException | Error failure) { + context.close(); + throw failure; + } + } + + private CommonGrpcClientProperties fixedReadTls(Fixture fixture, Path certificate, Path key) { + var tls = new CommonGrpcClientProperties(); + tls.setCertChain(certificate.toString()); + tls.setPrivateKey(key.toString()); + tls.setCaCert(fixture.caCertificatePath().toString()); + return tls; + } + + private T withControlledGameSessionPeer( + Fixture fixture, java.util.concurrent.Callable work) throws Exception { + return withControlledPeer(readCertificate(fixture.gameSessionCertificatePath()), work); + } + + private T withControlledPeer( + X509Certificate certificate, java.util.concurrent.Callable work) throws Exception { + var peer = GrpcPeerIdentity.fromCertificate(certificate).orElseThrow(); + var peerCertificate = GrpcPeerCertificateEvidence.fromCertificate(certificate).orElseThrow(); + return Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .withValue(GrpcPeerCertificateEvidence.CONTEXT_KEY, peerCertificate) + .call(work); + } + + private X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest + exactPreparedWorldRequest(RunOwnedCanonicalWorldLaunchEvidence evidence) { + var descriptor = evidence.launchDescriptor(); + var association = evidence.gameSessionAssociation(); + return new net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest( + association.gameSessionTenantId(), + association.gameInstanceId(), + descriptor.gameTemplateId(), + evidence.capability().operationId(), + descriptor.launchDescriptorId(), + descriptor.versionId(), + descriptor.scriptPatchVersionPresent() ? descriptor.scriptPatchVersion() : null, + descriptor.runtimeFlagsJson(), + descriptor.generationConfigRevision(), + descriptor.releaseBundleId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + descriptor.remapSetIdPresent() ? descriptor.remapSetId() : null); + } + + private AuthoredWorldSourceEvidence changedPreparedSourceEvidence( + AuthoredWorldSourceEvidence original) { + String changedDisplayName = original.worldDisplayName() + " changed"; + long changedSourceRowId = + original.sourceGameRowId() == Long.MAX_VALUE ? 1L : original.sourceGameRowId() + 1L; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + original.targetNamespace(), + original.registrationRequestId(), + original.canonicalTenantId(), + original.tenantSlug(), + original.worldSlug(), + changedDisplayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + original.targetNamespace(), + original.registrationRequestId(), + original.operationId(), + requestDigest, + original.canonicalTenantId(), + original.tenantSlug(), + original.worldSlug(), + changedDisplayName, + changedSourceRowId, + original.sourceGameTenantKey(), + original.provenanceKind()); + return new AuthoredWorldSourceEvidence( + original.schemaVersion(), + original.targetNamespace(), + original.registrationRequestId(), + original.operationId(), + requestDigest, + original.canonicalTenantId(), + original.tenantSlug(), + original.worldSlug(), + changedDisplayName, + changedSourceRowId, + original.sourceGameTenantKey(), + original.provenanceKind(), + evidenceDigest); + } + + private ComposedOwnerDatabase composedOwnerDatabase( + PostgreSQLContainer container, String service, String schema) { + var dataSource = + new DriverManagerDataSource( + container.getJdbcUrl(), container.getUsername(), container.getPassword()); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setSchema(schema); + Flyway ownerFlyway = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations( + "filesystem:" + + Path.of("..", service, "src/main/resources/db/migration") + .toAbsolutePath() + .normalize(), + "filesystem:" + + Path.of("../common-saga/src/main/resources/db/migration/saga") + .toAbsolutePath() + .normalize()) + .load(); + ownerFlyway.migrate(); + long versionedSqlMigrationCount = + java.util.Arrays.stream(ownerFlyway.info().all()) + .filter(migration -> migration.getVersion() != null) + .filter(migration -> "SQL".equals(migration.getType().name())) + .count(); + return new ComposedOwnerDatabase( + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES), + new DataSourceTransactionManager(dataSource), + versionedSqlMigrationCount); + } + + private record ComposedOwnerDatabase( + DSLContext dsl, PlatformTransactionManager transactions, long versionedSqlMigrationCount) {} + + private static GrpcChannelFactory composedChannelFactory( + java.util.List channels) { + return new GrpcChannelFactory() { + @Override + public ManagedChannel buildChannel( + String target, + int port, + CommonGrpcClientProperties properties, + boolean keepAlive, + ResolvedGrpcTlsMaterial material) + throws javax.net.ssl.SSLException { + ManagedChannel channel = super.buildChannel(target, port, properties, keepAlive, material); + channels.add(channel); + return channel; + } + }; + } + + private Server fixedProductionServer( + Fixture fixture, FixedReadLeaf leaf, Set methods, io.grpc.BindableService... handlers) + throws Exception { + var builder = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + leaf.certificate().toFile(), leaf.privateKey().toFile())) + .trustManager(fixture.caCertificatePath().toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()); + var auth = + new AuthTokenInterceptor( + new JwtUtil("testsecretkeytestsecretkeytest1234", 60_000L), methods); + for (var handler : handlers) + builder.addService( + ServerInterceptors.intercept(handler, new GrpcPeerIdentityInterceptor(), auth)); + return builder.build().start(); + } + + private WorldLifecycleCommandServiceImpl actualWorldFixtureCommands( + ComposedOwnerDatabase database, + RunOwnedCanonicalWorldLaunchEvidenceProvider provider, + net.firedevops.firemud.worldmanagement.client.GameDesignClient design, + net.firedevops.firemud.worldmanagement.client.EntityManagementClient entities, + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory factory, + io.micrometer.core.instrument.MeterRegistry registry) { + var commands = + new WorldLifecycleCommandServiceImpl( + new net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository( + database.dsl()), + new net.firedevops.firemud.worldmanagement.repository.RegionInstanceRepository( + database.dsl()), + new net.firedevops.firemud.worldmanagement.repository.ZoneRepository(database.dsl()), + new net.firedevops.firemud.worldmanagement.repository.ZoneInstanceRepository( + database.dsl()), + new net.firedevops.firemud.worldmanagement.repository.RoomRepository(database.dsl()), + new net.firedevops.firemud.worldmanagement.repository.RoomExitRepository( + database.dsl()), + new net.firedevops.firemud.worldmanagement.repository.RoomInstanceRepository( + database.dsl()), + new net.firedevops.firemud.worldmanagement.repository.RoomInstanceExitRepository( + database.dsl()), + new net.firedevops.firemud.worldmanagement.repository.WorldEventRepository( + database.dsl()), + new net.firedevops.firemud.worldmanagement.config.WorldProperties(), + design, + entities, + registry, + database.transactions(), + null, + provider, + database.dsl(), + endpoints, + tls, + factory, + NAMESPACE); + ReflectionTestUtils.invokeMethod(commands, "initMetrics"); + return commands; + } + + private net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociation + independentlyReadWorldFixture(DSLContext world, UUID canonicalInstance) { + return new WorldCanonicalInstanceAssociationRepository( + world, + new net.firedevops.firemud.worldmanagement.tenant.WorldCompleteLaunchBindingRepository( + world), + new net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository( + world), + new net.firedevops.firemud.worldmanagement.tenant + .WorldAuthoredVersionIdentityRepository(world)) + .readOwnerAssociation(canonicalInstance) + .orElseThrow(); + } + + private Map allComposedOwnerRows(DSLContext owner) { + Map rows = new LinkedHashMap<>(); + for (String table : + owner + .fetch( + "SELECT table_name FROM information_schema.tables WHERE table_schema=current_schema() " + + "AND table_type='BASE TABLE' ORDER BY table_name") + .getValues("table_name", String.class)) { + String qualified = DSL.name(table).toString(); + rows.put( + table, + owner + .fetch( + "SELECT row_to_json(t)::text AS bytes, xmin::text AS row_version FROM " + + qualified + + " t ORDER BY row_to_json(t)::text") + .formatJSON()); + } + return rows; + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidence.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidence.java new file mode 100644 index 0000000000..74abd1f5f2 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidence.java @@ -0,0 +1,331 @@ +package net.firedevops.firemud.worldmanagement.data; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; +import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; + +/** + * World-local verified projection of one run-owned fixture handoff. + * + *

The package-private constructor restricts creation to the fixed-server evidence provider. The + * public wire records themselves remain untrusted data and are never accepted as this carrier. + */ +public final class RunOwnedCanonicalWorldLaunchEvidence { + private static final String BINDING_DOMAIN = "firemud-world-run-owned-launch-binding/v1"; + + private final RunOwnedInitialAdmissionFixtureWireCodec.Capability capability; + private final RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt sourceReceipt; + private final AuthoredWorldLaunchDescriptorEvidence launchDescriptor; + private final CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult + gameSessionAssociation; + private final byte[] capabilityBytes; + private final byte[] sourceReceiptBytes; + private final String gameSessionLeafSha256; + private final String worldManagementUriSan; + private final String worldManagementLeafSha256; + private final String caCertificateSha256; + + RunOwnedCanonicalWorldLaunchEvidence( + RunOwnedInitialAdmissionFixtureWireCodec.Capability capability, + RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt sourceReceipt, + AuthoredWorldLaunchDescriptorEvidence launchDescriptor, + byte[] capabilityBytes, + byte[] sourceReceiptBytes, + String gameSessionLeafSha256, + String worldManagementUriSan, + String worldManagementLeafSha256, + String caCertificateSha256, + CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult gameSessionAssociation) { + this.capability = Objects.requireNonNull(capability, "capability"); + this.sourceReceipt = Objects.requireNonNull(sourceReceipt, "sourceReceipt"); + this.launchDescriptor = Objects.requireNonNull(launchDescriptor, "launchDescriptor"); + this.capabilityBytes = Objects.requireNonNull(capabilityBytes, "capabilityBytes").clone(); + this.sourceReceiptBytes = + Objects.requireNonNull(sourceReceiptBytes, "sourceReceiptBytes").clone(); + this.gameSessionLeafSha256 = + Objects.requireNonNull(gameSessionLeafSha256, "gameSessionLeafSha256"); + this.worldManagementUriSan = + Objects.requireNonNull(worldManagementUriSan, "worldManagementUriSan"); + this.worldManagementLeafSha256 = + Objects.requireNonNull(worldManagementLeafSha256, "worldManagementLeafSha256"); + this.caCertificateSha256 = Objects.requireNonNull(caCertificateSha256, "caCertificateSha256"); + this.gameSessionAssociation = + Objects.requireNonNull(gameSessionAssociation, "gameSessionAssociation"); + requireExactGameSessionFixtureAssociation( + this.capability, this.sourceReceipt, this.gameSessionAssociation); + } + + /** Revalidates the original fixed caller before a subsequent source-owner operation. */ + public void requireFixedGameSessionPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + GrpcPeerCertificateEvidence certificate = GrpcPeerCertificateEvidence.current(); + if (SessionContext.hasAuthenticatedCallerContext() + || peer == null + || certificate == null + || !peer.isService("game-session-service") + || !peer.isInNamespace("dev") + || !peer.uri().equals(capability.gameSessionUriSan()) + || !certificate.leafSha256().equals(capability.gameSessionLeafSha256()) + || !certificate.leafSha256().equals(gameSessionLeafSha256)) { + throw new SecurityException( + "Run-owned fixture owner operation requires its original fixed Game Session peer"); + } + } + + /** Retained policy provenance only; the digest alone supplies no owner authority. */ + public String fixtureProvenanceDigest() { + return sourceReceipt.fixturePolicySeal().evidenceDigest(); + } + + public RunOwnedInitialAdmissionFixtureWireCodec.Capability capability() { + return capability; + } + + public RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt sourceReceipt() { + return sourceReceipt; + } + + public AuthoredWorldLaunchDescriptorEvidence launchDescriptor() { + return launchDescriptor; + } + + /** Exact authenticated allocation read from the existing Game Session launch owner. */ + public CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult gameSessionAssociation() { + return gameSessionAssociation; + } + + /** The readback identifies the private Game Session keys; it grants no World write authority. */ + public void requireGameSessionAllocation(long tenantId, long gameInstanceId) { + if (tenantId != gameSessionAssociation.gameSessionTenantId() + || gameInstanceId != gameSessionAssociation.gameInstanceId()) { + throw new IllegalArgumentException( + "RUN_OWNED_WORLD_GAME_SESSION_ALLOCATION_MISMATCH: request differs from authenticated Game Session owner read"); + } + } + + public String gameSessionLeafSha256() { + return gameSessionLeafSha256; + } + + public String worldManagementUriSan() { + return worldManagementUriSan; + } + + public String worldManagementLeafSha256() { + return worldManagementLeafSha256; + } + + public String caCertificateSha256() { + return caCertificateSha256; + } + + /** Verifies the complete request tuple against the descriptor and committed owner snapshots. */ + public void requireMatches(PreparedWorldInstanceRequest request) { + Objects.requireNonNull(request, "request"); + var bundle = sourceReceipt.launchReadEvidence().publishedReleaseBundle(); + var artifact = sourceReceipt.launchReadEvidence().versionAssetArtifactState(); + var version = sourceReceipt.launchReadEvidence().versionState(); + var source = sourceReceipt.sourceEvidence(); + boolean publishedOrActive = + version.getVersionState() + == net.firedevops.firemud.gamedesign.v1.VersionLifecycleState + .VERSION_LIFECYCLE_STATE_PUBLISHED + || version.getVersionState() + == net.firedevops.firemud.gamedesign.v1.VersionLifecycleState + .VERSION_LIFECYCLE_STATE_ACTIVE; + if (request.tenantId() <= 0L + || request.gameInstanceId() <= 0L + || request.gameTemplateId() != capability.gameTemplateId() + || !capability.operationId().equals(request.controlPlaneRequestId()) + || !sourceReceipt.fixtureOperationId().equals(request.controlPlaneRequestId()) + || !launchDescriptor.launchDescriptorId().equals(request.launchDescriptorId()) + || launchDescriptor.gameTemplateId() != request.gameTemplateId() + || launchDescriptor.versionId() != request.versionId() + || !Objects.equals( + launchDescriptor.scriptPatchVersionPresent() + ? launchDescriptor.scriptPatchVersion() + : null, + normalizeBlank(request.scriptPatchVersion())) + || !effectiveRuntimeFlags(request.runtimeFlagsJson()) + .equals(launchDescriptor.runtimeFlagsJson()) + || !launchDescriptor.generationConfigRevision().equals(request.generationConfigRevision()) + || launchDescriptor.releaseBundleId() != request.releaseBundleId() + || !launchDescriptor.publishedReleaseBundleRef().equals(request.publishedReleaseBundleRef()) + || launchDescriptor.versionStateEpoch() != request.versionStateEpoch() + || !Objects.equals( + launchDescriptor.remapSetIdPresent() ? launchDescriptor.remapSetId() : null, + normalizeBlank(request.remapSetId())) + || bundle.getId() != request.releaseBundleId() + || bundle.getVersionId() != request.versionId() + || !bundle.getPublishedReleaseBundleRef().equals(request.publishedReleaseBundleRef()) + || !bundle.getGenerationConfigRevision().equals(request.generationConfigRevision()) + || artifact.getVersionId() != request.versionId() + || artifact.getArtifactState() + != net.firedevops.firemud.gamedesign.v1.ArtifactState.ARTIFACT_STATE_PUBLISHED + || !artifact.getManifestHash().equals(bundle.getManifestHash()) + || version.getVersionId() != request.versionId() + || !publishedOrActive + || version.getVersionStateEpoch() != request.versionStateEpoch() + || !source.targetNamespace().equals("dev") + || !Long.toString(capability.tenantId()).equals(source.sourceGameTenantKey()) + || !launchDescriptor.canonicalTenantId().equals(source.canonicalTenantId()) + || !launchDescriptor.worldSlug().equals(source.worldSlug()) + || !launchDescriptor.authoredWorldSourceOperationId().equals(source.operationId()) + || !launchDescriptor.authoredWorldSourceEvidenceDigest().equals(source.evidenceDigest()) + || launchDescriptor.requestedScriptPatchVersionPresent() + || launchDescriptor.sourceVersionIdPresent() + || launchDescriptor.targetVersionIdPresent() + || launchDescriptor.requestedRuntimeFlagsJsonPresent() + || launchDescriptor.remapSetIdPresent() + || !request.controlPlaneRequestId().equals(launchDescriptor.controlPlaneRequestId())) { + throw new IllegalArgumentException( + "RUN_OWNED_WORLD_LAUNCH_EVIDENCE_MISMATCH: prepared request differs from committed fixture evidence"); + } + requireGameSessionAllocation(request.tenantId(), request.gameInstanceId()); + requireExactGameSessionFixtureAssociation(capability, sourceReceipt, gameSessionAssociation); + } + + static void requireExactGameSessionFixtureAssociation( + RunOwnedInitialAdmissionFixtureWireCodec.Capability capability, + RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt sourceReceipt, + CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult gameSessionAssociation) { + var expectedPolicy = + new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicyRequest( + capability, + sourceReceipt.creationEvidence(), + sourceReceipt.sourceEvidence(), + sourceReceipt.launchReadEvidence()); + byte[] expectedPolicyBytes = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestBytes( + capability, + sourceReceipt.creationEvidence(), + sourceReceipt.sourceEvidence(), + sourceReceipt.launchReadEvidence()); + if (!gameSessionAssociation + .request() + .fixtureOperationId() + .toString() + .equals(capability.operationId()) + || !gameSessionAssociation + .request() + .targetNamespace() + .equals(sourceReceipt.sourceEvidence().targetNamespace()) + || !gameSessionAssociation + .request() + .expectedFixturePolicyEvidenceDigest() + .equals(sourceReceipt.fixturePolicySeal().evidenceDigest()) + || !gameSessionAssociation.fixturePolicySeal().equals(sourceReceipt.fixturePolicySeal()) + || !Objects.equals(gameSessionAssociation.fixturePolicyRequest(), expectedPolicy) + || !Arrays.equals(gameSessionAssociation.fixturePolicyRequestBytes(), expectedPolicyBytes) + || !gameSessionAssociation + .canonicalTenantId() + .equals(sourceReceipt.sourceEvidence().canonicalTenantId()) + || !gameSessionAssociation + .canonicalVersionId() + .toString() + .equals( + sourceReceipt + .launchReadEvidence() + .publishedReleaseBundle() + .getCanonicalVersionId())) { + throw new IllegalArgumentException( + "RUN_OWNED_WORLD_GAME_SESSION_FIXTURE_ASSOCIATION_MISMATCH: owner read differs from immutable fixture receipt"); + } + } + + /** + * Returns the durable digest for the immutable evidence, exact request, target instance, and + * original PREPARING epoch using the repository's length-framed digest convention. + */ + public String bindingDigest(PreparedWorldInstanceRequest request, long preparingEpoch) { + requireMatches(request); + if (preparingEpoch <= 0L) { + throw new IllegalArgumentException("RUN_OWNED_WORLD_LAUNCH_EPOCH_INVALID"); + } + StringBuilder preimage = new StringBuilder(); + appendDigestField(preimage, "domain", BINDING_DOMAIN); + appendDigestField(preimage, "capabilityBytesSha256", sha256Hex(capabilityBytes)); + appendDigestField(preimage, "sourceReceiptBytesSha256", sha256Hex(sourceReceiptBytes)); + appendDigestField(preimage, "runId", capability.runId()); + appendDigestField(preimage, "composeProjectName", capability.composeProjectName()); + appendDigestField(preimage, "fixtureOperationId", capability.operationId()); + appendDigestField(preimage, "gameSessionUriSan", capability.gameSessionUriSan()); + appendDigestField(preimage, "gameSessionLeafSha256", gameSessionLeafSha256); + appendDigestField(preimage, "worldManagementUriSan", worldManagementUriSan); + appendDigestField(preimage, "worldManagementLeafSha256", worldManagementLeafSha256); + appendDigestField(preimage, "caCertificateSha256", caCertificateSha256); + appendDigestField( + preimage, "sourceEvidenceDigest", sourceReceipt.sourceEvidence().evidenceDigest()); + appendDigestField(preimage, "descriptorRequestDigest", launchDescriptor.requestDigest()); + appendDigestField(preimage, "descriptorResultDigest", launchDescriptor.resultDigest()); + appendDigestField(preimage, "tenantId", Long.toString(request.tenantId())); + appendDigestField(preimage, "gameInstanceId", Long.toString(request.gameInstanceId())); + appendDigestField(preimage, "gameTemplateId", Long.toString(request.gameTemplateId())); + appendDigestField(preimage, "controlPlaneRequestId", request.controlPlaneRequestId()); + appendDigestField(preimage, "launchDescriptorId", request.launchDescriptorId()); + appendDigestField(preimage, "versionId", Long.toString(request.versionId())); + appendDigestField( + preimage, "scriptPatchVersion", nullToEmpty(normalizeBlank(request.scriptPatchVersion()))); + appendDigestField( + preimage, "runtimeFlagsJson", effectiveRuntimeFlags(request.runtimeFlagsJson())); + appendDigestField(preimage, "generationConfigRevision", request.generationConfigRevision()); + appendDigestField(preimage, "releaseBundleId", Long.toString(request.releaseBundleId())); + appendDigestField(preimage, "publishedReleaseBundleRef", request.publishedReleaseBundleRef()); + appendDigestField(preimage, "versionStateEpoch", Long.toString(request.versionStateEpoch())); + appendDigestField(preimage, "remapSetId", nullToEmpty(normalizeBlank(request.remapSetId()))); + appendDigestField(preimage, "preparingLifecycleEpoch", Long.toString(preparingEpoch)); + return sha256Hex(preimage.toString().getBytes(StandardCharsets.UTF_8)); + } + + byte[] capabilityBytes() { + return capabilityBytes.clone(); + } + + byte[] sourceReceiptBytes() { + return sourceReceiptBytes.clone(); + } + + private static String effectiveRuntimeFlags(String value) { + String normalized = normalizeBlank(value); + return normalized == null ? "{}" : value; + } + + private static String normalizeBlank(String value) { + return value == null || value.isBlank() ? null : value; + } + + private static String nullToEmpty(String value) { + return value == null ? "" : value; + } + + private static void appendDigestField(StringBuilder preimage, String name, String value) { + String normalized = nullToEmpty(value); + int nameByteLength = name.getBytes(StandardCharsets.UTF_8).length; + int valueByteLength = normalized.getBytes(StandardCharsets.UTF_8).length; + preimage + .append(nameByteLength) + .append(':') + .append(name) + .append(valueByteLength) + .append(':') + .append(normalized); + } + + private static String sha256Hex(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceProvider.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceProvider.java new file mode 100644 index 0000000000..f9f486f779 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceProvider.java @@ -0,0 +1,500 @@ +package net.firedevops.firemud.worldmanagement.data; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import jakarta.annotation.PreDestroy; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Collection; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationClient; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.smoke.RunOwnedFixtureImmutableFileReader; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; +import net.firedevops.firemud.worldmanagement.client.GameDesignClient; +import net.firedevops.firemud.worldmanagement.client.GameDesignClient.LaunchDescriptorReadback; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.ClassPathResource; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +/** + * Fixed-server reader and verifier for the run-owned World launch fixture. + * + *

Request data cannot select paths, principals, or evidence. Every call rereads and revalidates + * the configured immutable files and reads the exact authenticated Game Design and Game Session + * owner projections. The Game Session STARTING association is provenance only; it grants no World + * materialization or activation authority. + */ +@Component +public final class RunOwnedCanonicalWorldLaunchEvidenceProvider { + private static final Logger logger = + LoggerFactory.getLogger(RunOwnedCanonicalWorldLaunchEvidenceProvider.class); + private static final int MAX_WIRE_BYTES = 16 * 1024; + private static final int MAX_CERTIFICATE_BYTES = 1024 * 1024; + private static final String GAME_SESSION_URI_SAN = + RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN; + private static final String WORLD_MANAGEMENT_URI_SAN = + RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN; + private static final Pattern SAFE_ID = Pattern.compile("[a-z0-9][a-z0-9-]{0,127}"); + + private final boolean enabled; + private final String capabilityPath; + private final String sourceReceiptPath; + private final String runId; + private final String composeProjectName; + private final CommonGrpcClientProperties grpcProperties; + private final GameDesignClient gameDesignClient; + private final ServiceEndpointsProperties serviceEndpoints; + private final GrpcChannelFactory grpcChannelFactory; + private final GameSessionFixtureClientFactory gameSessionFixtureClientFactory; + private final String workloadNamespace; + private volatile CanonicalGameInstanceLaunchAssociationClient gameSessionFixtureClient; + private boolean closed; + + @Autowired + public RunOwnedCanonicalWorldLaunchEvidenceProvider( + @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}") boolean enabled, + @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH:}") String capabilityPath, + @Value("${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH:}") String sourceReceiptPath, + @Value("${FIREMUD_SMOKE_RUN_ID:}") String runId, + @Value("${FIREMUD_SMOKE_COMPOSE_PROJECT_NAME:}") String composeProjectName, + CommonGrpcClientProperties grpcProperties, + GameDesignClient gameDesignClient, + ServiceEndpointsProperties serviceEndpoints, + GrpcChannelFactory grpcChannelFactory, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this( + enabled, + capabilityPath, + sourceReceiptPath, + runId, + composeProjectName, + grpcProperties, + gameDesignClient, + serviceEndpoints, + grpcChannelFactory, + workloadNamespace, + (endpoints, properties, factory, namespace) -> + new CanonicalGameInstanceLaunchAssociationClient( + endpoints, properties, factory, namespace)); + } + + RunOwnedCanonicalWorldLaunchEvidenceProvider( + boolean enabled, + String capabilityPath, + String sourceReceiptPath, + String runId, + String composeProjectName, + CommonGrpcClientProperties grpcProperties, + GameDesignClient gameDesignClient, + ServiceEndpointsProperties serviceEndpoints, + GrpcChannelFactory grpcChannelFactory, + String workloadNamespace, + GameSessionFixtureClientFactory gameSessionFixtureClientFactory) { + this.enabled = enabled; + this.capabilityPath = capabilityPath; + this.sourceReceiptPath = sourceReceiptPath; + this.runId = runId; + this.composeProjectName = composeProjectName; + this.grpcProperties = Objects.requireNonNull(grpcProperties, "grpcProperties"); + this.gameDesignClient = Objects.requireNonNull(gameDesignClient, "gameDesignClient"); + this.serviceEndpoints = serviceEndpoints == null ? null : serviceEndpoints.copy(); + this.grpcChannelFactory = grpcChannelFactory; + this.gameSessionFixtureClientFactory = + Objects.requireNonNull(gameSessionFixtureClientFactory, "gameSessionFixtureClientFactory"); + this.workloadNamespace = workloadNamespace; + } + + /** Whether the server selected the run-owned fixture mode at startup. */ + public boolean isEnabled() { + return enabled; + } + + /** + * Independently loads the fixed evidence and verifies both authenticated owner readbacks. + * Returned Game Session STARTING state is source evidence only and does not authorize World + * writes or activation. + */ + public RunOwnedCanonicalWorldLaunchEvidence requireAuthenticatedEvidence() { + VerificationStage stage = VerificationStage.ENABLED; + try { + if (!enabled) { + throw invalidEvidence(); + } + + stage = VerificationStage.RUN_BINDING; + requireExpectedRunBinding(runId, composeProjectName); + + stage = VerificationStage.CAPABILITY_FILE; + byte[] capabilityBytes = readImmutableWireFile(capabilityPath); + stage = VerificationStage.RECEIPT_FILE; + byte[] receiptBytes = readImmutableWireFile(sourceReceiptPath); + + stage = VerificationStage.WIRE_PARSE; + var capability = RunOwnedInitialAdmissionFixtureWireCodec.parseCapability(capabilityBytes); + var receipt = + RunOwnedInitialAdmissionFixtureWireCodec.parseSourceReceipt(receiptBytes, capability); + if (!runId.equals(capability.runId()) + || !composeProjectName.equals(capability.composeProjectName()) + || !runId.equals(receipt.runId()) + || !composeProjectName.equals(receipt.composeProjectName())) { + throw invalidEvidence(); + } + + stage = VerificationStage.WORLD_CERTIFICATE_PINS; + CertificatePins worldPins = configuredWorldCertificatePins(grpcProperties); + if (!GAME_SESSION_URI_SAN.equals(capability.gameSessionUriSan()) + || !WORLD_MANAGEMENT_URI_SAN.equals(capability.worldManagementUriSan()) + || !worldPins.uriSan().equals(capability.worldManagementUriSan()) + || !worldPins.leafSha256().equals(capability.worldManagementLeafSha256()) + || !worldPins.caSha256().equals(capability.caCertificateSha256()) + || !worldPins.caSha256().equals(receipt.caCertificateSha256()) + || !worldPins.uriSan().equals(receipt.worldManagementUriSan()) + || !worldPins.leafSha256().equals(receipt.worldManagementLeafSha256())) { + throw invalidEvidence(); + } + + stage = VerificationStage.GAME_SESSION_PEER; + requireAuthenticatedGameSessionPeer(capability); + + try { + stage = VerificationStage.DESCRIPTOR_PARSE; + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest = + expectedDescriptorRequest(capability, receipt); + AuthoredWorldLaunchDescriptorEvidence receiptDescriptor = + AuthoredWorldLaunchDescriptorGrpcCodec.fromLaunchDescriptorMessage( + expectedRequest, receipt.launchReadEvidence().launchDescriptor()); + + stage = VerificationStage.OWNER_DESCRIPTOR_READ; + LaunchDescriptorReadback readback = + gameDesignClient.getLaunchDescriptor( + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + freshReadRequestId(expectedRequest), + expectedRequest, + receiptDescriptor.resultDigest())); + + stage = VerificationStage.OWNER_DESCRIPTOR_COMPARE; + if (!receiptDescriptor.equals(readback.evidence()) + || !receipt.launchReadEvidence().launchDescriptor().equals(readback.message())) { + throw invalidEvidence(); + } + + stage = VerificationStage.GAME_SESSION_FIXTURE_READ; + var fixtureReadRequest = + new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest( + freshFixtureReadRequestId(UUID.fromString(capability.operationId())), + receipt.sourceEvidence().targetNamespace(), + UUID.fromString(capability.operationId()), + receipt.fixturePolicySeal().evidenceDigest()); + CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult gameSessionAssociation = + gameSessionFixtureClient() + .readFixture(fixtureReadRequest, capability.gameSessionLeafSha256()); + stage = VerificationStage.GAME_SESSION_FIXTURE_COMPARE; + + return new RunOwnedCanonicalWorldLaunchEvidence( + capability, + receipt, + receiptDescriptor, + capabilityBytes, + receiptBytes, + capability.gameSessionLeafSha256(), + worldPins.uriSan(), + worldPins.leafSha256(), + worldPins.caSha256(), + gameSessionAssociation); + } catch (RuntimeException exception) { + if (exception instanceof InvalidRunOwnedCanonicalWorldLaunchEvidenceException invalid) { + throw invalid; + } + if (isRetryableOwnerReadFailure(stage, exception)) { + throw exception; + } + throw invalidEvidence(); + } + } catch (RuntimeException exception) { + logger.warn("Run-owned World launch evidence verification rejected; stage={}", stage); + throw exception; + } + } + + private static boolean isRetryableOwnerReadFailure( + VerificationStage stage, RuntimeException exception) { + if (!(exception instanceof StatusRuntimeException statusException) + || (stage != VerificationStage.OWNER_DESCRIPTOR_READ + && stage != VerificationStage.GAME_SESSION_FIXTURE_READ)) { + return false; + } + return statusException.getStatus().getCode() == Status.Code.UNAVAILABLE + || statusException.getStatus().getCode() == Status.Code.DEADLINE_EXCEEDED; + } + + private static UUID freshFixtureReadRequestId(UUID fixtureOperationId) { + UUID readRequestId; + do { + readRequestId = UUID.randomUUID(); + } while (readRequestId.equals(fixtureOperationId)); + return readRequestId; + } + + private synchronized CanonicalGameInstanceLaunchAssociationClient gameSessionFixtureClient() { + if (closed) { + throw invalidEvidence(); + } + if (gameSessionFixtureClient != null) { + return gameSessionFixtureClient; + } + if (serviceEndpoints == null + || grpcChannelFactory == null + || !StringUtils.hasText(workloadNamespace)) { + throw invalidEvidence(); + } + CanonicalGameInstanceLaunchAssociationClient created = + gameSessionFixtureClientFactory.create( + serviceEndpoints, grpcProperties, grpcChannelFactory, workloadNamespace); + try { + created.init(); + gameSessionFixtureClient = created; + return created; + } catch (IOException | RuntimeException failure) { + try { + created.close(); + } catch (IOException ignored) { + // Keep the fixed content-free rejection; certificate paths never enter logs. + } + throw invalidEvidence(); + } + } + + @PreDestroy + public synchronized void closeGameSessionFixtureClient() { + closed = true; + CanonicalGameInstanceLaunchAssociationClient current = gameSessionFixtureClient; + gameSessionFixtureClient = null; + if (current != null) { + try { + current.close(); + } catch (IOException failure) { + logger.warn("Run-owned World Game Session owner client did not close cleanly"); + } + } + } + + private static AuthoredWorldLaunchDescriptorEvidence.Request expectedDescriptorRequest( + RunOwnedInitialAdmissionFixtureWireCodec.Capability capability, + RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt receipt) { + var source = receipt.sourceEvidence(); + return new AuthoredWorldLaunchDescriptorEvidence.Request( + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_TARGET_NAMESPACE, + capability.operationId(), + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + capability.gameTemplateId(), + false, + null, + false, + null, + false, + null, + false, + null); + } + + private static UUID freshReadRequestId(AuthoredWorldLaunchDescriptorEvidence.Request request) { + UUID readRequestId; + do { + readRequestId = UUID.randomUUID(); + } while (readRequestId.equals(request.authoredWorldSourceOperationId()) + || readRequestId.toString().equals(request.controlPlaneRequestId())); + return readRequestId; + } + + private static void requireAuthenticatedGameSessionPeer( + RunOwnedInitialAdmissionFixtureWireCodec.Capability capability) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + GrpcPeerCertificateEvidence certificate = GrpcPeerCertificateEvidence.current(); + if (peer == null + || certificate == null + || !GAME_SESSION_URI_SAN.equals(capability.gameSessionUriSan()) + || !peer.uri().equals(GAME_SESSION_URI_SAN) + || !peer.isService("game-session-service") + || !peer.isInNamespace("dev") + || !certificate.leafSha256().equals(capability.gameSessionLeafSha256()) + || SessionContext.hasAuthenticatedCallerContext()) { + throw invalidEvidence(); + } + } + + private static CertificatePins configuredWorldCertificatePins( + CommonGrpcClientProperties properties) { + if (properties.isPlaintext() + || blank(properties.getCertChain()) + || blank(properties.getCaCert())) { + throw invalidEvidence(); + } + try { + List chain = certificates(readConfiguredTlsFile(properties.getCertChain())); + List authorities = + certificates(readConfiguredTlsFile(properties.getCaCert())); + if (chain.isEmpty() || authorities.size() != 1) { + throw invalidEvidence(); + } + X509Certificate leaf = chain.getFirst(); + X509Certificate ca = authorities.getFirst(); + String uriSan = + GrpcPeerIdentity.fromCertificate(leaf) + .map(GrpcPeerIdentity::uri) + .filter(WORLD_MANAGEMENT_URI_SAN::equals) + .orElseThrow(RunOwnedCanonicalWorldLaunchEvidenceProvider::invalidEvidence); + if (ca.getBasicConstraints() < 0) { + throw invalidEvidence(); + } + leaf.checkValidity(); + ca.checkValidity(); + leaf.verify(ca.getPublicKey()); + return new CertificatePins(fingerprint(leaf), uriSan, fingerprint(ca)); + } catch (IOException | GeneralSecurityException | RuntimeException exception) { + if (exception instanceof InvalidRunOwnedCanonicalWorldLaunchEvidenceException invalid) { + throw invalid; + } + throw invalidEvidence(); + } + } + + private static byte[] readConfiguredTlsFile(String configuredPath) throws IOException { + byte[] bytes; + if (configuredPath.startsWith("classpath:")) { + ClassPathResource resource = + new ClassPathResource(configuredPath.substring("classpath:".length())); + try (InputStream input = resource.getInputStream()) { + bytes = input.readNBytes(MAX_CERTIFICATE_BYTES + 1); + } + } else { + try (InputStream input = Files.newInputStream(Path.of(configuredPath))) { + bytes = input.readNBytes(MAX_CERTIFICATE_BYTES + 1); + } + } + if (bytes.length == 0 || bytes.length > MAX_CERTIFICATE_BYTES) { + throw new IOException("Configured certificate file is outside the accepted size bound"); + } + return bytes; + } + + private static List certificates(byte[] encoded) throws IOException { + try { + Collection parsed = + CertificateFactory.getInstance("X.509") + .generateCertificates(new ByteArrayInputStream(encoded)); + return parsed.stream() + .filter(X509Certificate.class::isInstance) + .map(X509Certificate.class::cast) + .toList(); + } catch (java.security.cert.CertificateException exception) { + throw new IOException("Configured certificate could not be parsed", exception); + } + } + + private static String fingerprint(X509Certificate certificate) { + try { + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded())); + } catch (NoSuchAlgorithmException | java.security.cert.CertificateEncodingException exception) { + throw invalidEvidence(); + } + } + + private static byte[] readImmutableWireFile(String configuredPath) { + if (blank(configuredPath)) { + throw invalidEvidence(); + } + Path path; + try { + path = Path.of(configuredPath); + } catch (RuntimeException exception) { + throw invalidEvidence(); + } + if (!path.isAbsolute()) { + throw invalidEvidence(); + } + return RunOwnedFixtureImmutableFileReader.readBoundedImmutableFile( + path, MAX_WIRE_BYTES, RunOwnedCanonicalWorldLaunchEvidenceProvider::invalidEvidence); + } + + private static void requireExpectedRunBinding(String expectedRunId, String expectedProject) { + if (!safeId(expectedRunId) || !safeId(expectedProject)) { + throw invalidEvidence(); + } + } + + private static boolean safeId(String value) { + return value != null && SAFE_ID.matcher(value).matches(); + } + + private static boolean blank(String value) { + return value == null || value.isBlank(); + } + + private static InvalidRunOwnedCanonicalWorldLaunchEvidenceException invalidEvidence() { + return new InvalidRunOwnedCanonicalWorldLaunchEvidenceException(); + } + + private record CertificatePins(String leafSha256, String uriSan, String caSha256) {} + + @FunctionalInterface + interface GameSessionFixtureClientFactory { + CanonicalGameInstanceLaunchAssociationClient create( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace); + } + + private enum VerificationStage { + ENABLED, + RUN_BINDING, + CAPABILITY_FILE, + RECEIPT_FILE, + WIRE_PARSE, + WORLD_CERTIFICATE_PINS, + GAME_SESSION_PEER, + DESCRIPTOR_PARSE, + OWNER_DESCRIPTOR_READ, + OWNER_DESCRIPTOR_COMPARE, + GAME_SESSION_FIXTURE_READ, + GAME_SESSION_FIXTURE_COMPARE + } + + /** Content-free failure so malformed or secret-bearing fixture bytes never reach logs. */ + public static final class InvalidRunOwnedCanonicalWorldLaunchEvidenceException + extends IllegalArgumentException { + private InvalidRunOwnedCanonicalWorldLaunchEvidenceException() { + super("Run-owned World launch evidence is invalid"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResources.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResources.java new file mode 100644 index 0000000000..8fd648bf0b --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResources.java @@ -0,0 +1,1299 @@ +package net.firedevops.firemud.worldmanagement.data; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadGrpcCodec; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociation; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.JacksonException; +import tools.jackson.databind.json.JsonMapper; + +/** + * The canonical fixed topology used by the explicitly trusted local run-owned fixture. + * + *

The preset is a typed expected-content definition. Its seal is calculated before any resource + * write and binds the fixture claim, both external owners, the Game Design policy seal, and the + * actual World source and Version allocations. It never reads or adopts the legacy demo rows. + */ +public final class RunOwnedWorldFixedPresetResources { + public static final String PRESET_ID = "firemud-demo-topology-v1"; + private static final int PRESET_SCHEMA_VERSION = 1; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final String CONTENT_DOMAIN = "firemud-world-run-owned-fixed-preset-content/v1"; + private static final String BINDING_DOMAIN = "firemud-world-run-owned-fixed-preset-binding/v1"; + private static final UUID NAMESPACE = UUID.fromString("71ea88a0-6c91-5b2a-a618-b6b59dba9491"); + + private static final RegionDefinition REGION = + new RegionDefinition(templateId("REGION", "demo-region"), "Demo Region", 1.0, 0L); + private static final ZoneDefinition ZONE = + new ZoneDefinition(templateId("ZONE", "demo-zone"), REGION.templateId(), "Demo Zone"); + private static final RoomDefinition STARTER_ROOM = + new RoomDefinition( + templateId("ROOM", "candle-lit-antechamber"), + ZONE.templateId(), + "Candle-lit Antechamber", + "Stalactites drip along the northern wall while a faint draft carries the smell of damp" + + " earth from the lower tunnels. Torches flicker in alcoves, casting motion into the" + + " shadowy archway to the north."); + private static final RoomDefinition SECONDARY_ROOM = + new RoomDefinition( + templateId("ROOM", "smiths-annex"), + ZONE.templateId(), + "Smith's Annex", + "An anvil, banked coals, and orderly tool racks mark this alcove as a working annex off" + + " the starter chamber."); + private static final List EXITS = + List.of( + new ExitDefinition( + templateId("ROOM_EXIT", "starter-to-annex-north"), + STARTER_ROOM.templateId(), + SECONDARY_ROOM.templateId(), + "NORTH", + 1), + new ExitDefinition( + templateId("ROOM_EXIT", "annex-to-starter-south"), + SECONDARY_ROOM.templateId(), + STARTER_ROOM.templateId(), + "SOUTH", + 1)); + + private static final String CONTENT_DIGEST = contentDigest(); + + private RunOwnedWorldFixedPresetResources() {} + + /** Returns the immutable expected topology definition shared with the local demo seeder. */ + public static Definition definition() { + return new Definition(PRESET_ID, REGION, ZONE, List.of(STARTER_ROOM, SECONDARY_ROOM), EXITS); + } + + /** + * Builds a complete authorization plan before any World resource write is permitted. + * + *

The inputs must be the typed results of World source intake, World Version association, and + * the fixed-server authenticated launch-evidence provider. Parsed wire data alone is not + * accepted. + */ + public static FixedPresetPlan plan( + RunOwnedCanonicalWorldLaunchEvidence evidence, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + WorldAuthoredVersionIdentityReceipt versionReceipt) { + RunOwnedCanonicalWorldLaunchEvidence typedEvidence = + Objects.requireNonNull(evidence, "evidence"); + typedEvidence.requireFixedGameSessionPeer(); + var descriptor = typedEvidence.launchDescriptor(); + if (descriptor.scriptPatchVersionPresent() || descriptor.remapSetIdPresent()) { + throw new IllegalArgumentException( + "RUN_OWNED_WORLD_FIXED_PRESET_OVERRIDES_UNSUPPORTED: fixed preset requires absent script patch and remap set overrides"); + } + Objects.requireNonNull(sourceReceipt, "sourceReceipt"); + Objects.requireNonNull(versionReceipt, "versionReceipt"); + + var fixture = typedEvidence.sourceReceipt(); + var capability = typedEvidence.capability(); + var gameSession = typedEvidence.gameSessionAssociation(); + var versionState = versionReceipt.versionStateEvidence(); + var bundle = fixture.launchReadEvidence().publishedReleaseBundle(); + var artifact = fixture.launchReadEvidence().versionAssetArtifactState(); + var versionLifecycle = versionState.versionState(); + boolean publishedOrActive = + versionLifecycle + == net.firedevops.firemud.gamedesign.v1.VersionLifecycleState + .VERSION_LIFECYCLE_STATE_PUBLISHED + || versionLifecycle + == net.firedevops.firemud.gamedesign.v1.VersionLifecycleState + .VERSION_LIFECYCLE_STATE_ACTIVE; + if (gameSession == null + || !sourceReceipt.source().equals(fixture.sourceEvidence()) + || !sourceReceipt.targetNamespace().equals(descriptor.targetNamespace()) + || !capability.worldManagementUriSan().equals(typedEvidence.worldManagementUriSan()) + || !sourceReceipt.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !sourceReceipt.worldSlug().equals(descriptor.worldSlug()) + || !sourceReceipt.sourceOperationId().equals(descriptor.authoredWorldSourceOperationId()) + || !sourceReceipt + .sourceEvidenceDigest() + .equals(descriptor.authoredWorldSourceEvidenceDigest()) + || !descriptor.controlPlaneRequestId().equals(capability.operationId()) + || descriptor.gameTemplateId() != capability.gameTemplateId() + || !sourceReceipt.equals(versionReceipt.sourceIntakeReceipt()) + || !versionReceipt.canonicalTenantId().equals(sourceReceipt.canonicalTenantId()) + || !versionReceipt.canonicalVersionId().equals(gameSession.canonicalVersionId()) + || !versionReceipt.canonicalVersionId().toString().equals(bundle.getCanonicalVersionId()) + || versionReceipt.gameDesignVersionId() != descriptor.versionId() + || versionState.request().versionId() != descriptor.versionId() + || versionState.versionStateEpoch() != descriptor.versionStateEpoch() + || !publishedOrActive + || !versionState.sourceEvidence().equals(sourceReceipt.source()) + || bundle.getVersionId() != descriptor.versionId() + || bundle.getId() != descriptor.releaseBundleId() + || !bundle.getPublishedReleaseBundleRef().equals(descriptor.publishedReleaseBundleRef()) + || !bundle.getGenerationConfigRevision().equals(descriptor.generationConfigRevision()) + || artifact.getVersionId() != descriptor.versionId() + || artifact.getArtifactState() + != net.firedevops.firemud.gamedesign.v1.ArtifactState.ARTIFACT_STATE_PUBLISHED + || !artifact.getManifestHash().equals(bundle.getManifestHash()) + || !gameSession.request().fixtureOperationId().toString().equals(capability.operationId()) + || !fixture.fixtureOperationId().equals(capability.operationId()) + || !fixture.fixturePolicySeal().operationId().toString().equals(capability.operationId()) + || !gameSession.canonicalTenantId().equals(sourceReceipt.canonicalTenantId()) + || !gameSession.fixturePolicySeal().equals(fixture.fixturePolicySeal()) + || !fixture + .fixturePolicySeal() + .evidenceDigest() + .equals(typedEvidence.fixtureProvenanceDigest()) + || !gameSession + .request() + .expectedFixturePolicyEvidenceDigest() + .equals(fixture.fixturePolicySeal().evidenceDigest()) + || !"SHARED".equals(capability.stateScope()) + || !"NEW_GAME_ROW".equals(sourceReceipt.source().provenanceKind()) + || sourceReceipt.localTenantKey() <= 0 + || versionReceipt.localVersionKey() <= 0) { + throw new IllegalArgumentException( + "RUN_OWNED_WORLD_FIXED_PRESET_EVIDENCE_MISMATCH: fixed preset requires exact authenticated claim, source, descriptor, bundle, policy seal, and World owner receipts"); + } + + var policyRequest = gameSession.fixturePolicyRequest(); + if (!Objects.equals(policyRequest.capability(), capability) + || !Objects.equals(policyRequest.sourceEvidence(), sourceReceipt.source()) + || !Objects.equals(policyRequest.launchReadEvidence(), fixture.launchReadEvidence()) + || !Objects.equals(policyRequest.creationEvidence(), fixture.creationEvidence())) { + throw new IllegalArgumentException( + "RUN_OWNED_WORLD_FIXED_PRESET_POLICY_MISMATCH: Game Session retained a different GDS fixture policy request"); + } + + PreparedWorldInstanceRequest originalRequest = + new PreparedWorldInstanceRequest( + gameSession.gameSessionTenantId(), + gameSession.gameInstanceId(), + capability.gameTemplateId(), + capability.operationId(), + descriptor.launchDescriptorId(), + descriptor.versionId(), + descriptor.scriptPatchVersionPresent() ? descriptor.scriptPatchVersion() : null, + descriptor.runtimeFlagsJson(), + descriptor.generationConfigRevision(), + descriptor.releaseBundleId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + descriptor.remapSetIdPresent() ? descriptor.remapSetId() : null); + typedEvidence.requireMatches(originalRequest); + String lifecycleBindingDigest = "sha256:" + typedEvidence.bindingDigest(originalRequest, 1L); + String gameSessionResponseBytesDigest = + sha256Raw( + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toFixtureResponse(gameSession) + .toByteArray()); + + return sealPlan( + capability, + gameSession, + sourceReceipt, + versionReceipt, + descriptor, + bundle, + lifecycleBindingDigest, + gameSessionResponseBytesDigest); + } + + /** Rebuilds the expected plan from immutable, typed World-owner receipts for restart reads. */ + public static FixedPresetPlan plan( + WorldCanonicalInstanceAssociation association, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + WorldAuthoredVersionIdentityReceipt versionReceipt) { + Objects.requireNonNull(association, "association"); + Objects.requireNonNull(sourceReceipt, "sourceReceipt"); + Objects.requireNonNull(versionReceipt, "versionReceipt"); + var fixture = association.runOwnedFixture(); + var gameSession = fixture.gameSessionAssociation(); + var policyRequest = gameSession.fixturePolicyRequest(); + RunOwnedInitialAdmissionFixtureWireCodec.Capability capability = policyRequest.capability(); + var sourceEvidence = policyRequest.sourceEvidence(); + var launchReadEvidence = policyRequest.launchReadEvidence(); + var creationEvidence = policyRequest.creationEvidence(); + var descriptor = + AuthoredWorldLaunchDescriptorGrpcCodec.fromLaunchDescriptorMessage( + new AuthoredWorldLaunchDescriptorEvidence.Request( + sourceEvidence.targetNamespace(), + capability.operationId(), + sourceEvidence.canonicalTenantId(), + sourceEvidence.worldSlug(), + sourceEvidence.operationId(), + sourceEvidence.evidenceDigest(), + capability.gameTemplateId(), + false, + null, + false, + null, + false, + null, + false, + null), + launchReadEvidence.launchDescriptor()); + var versionState = versionReceipt.versionStateEvidence(); + var bundle = launchReadEvidence.publishedReleaseBundle(); + var artifact = launchReadEvidence.versionAssetArtifactState(); + var versionLifecycle = versionState.versionState(); + boolean publishedOrActive = + versionLifecycle + == net.firedevops.firemud.gamedesign.v1.VersionLifecycleState + .VERSION_LIFECYCLE_STATE_PUBLISHED + || versionLifecycle + == net.firedevops.firemud.gamedesign.v1.VersionLifecycleState + .VERSION_LIFECYCLE_STATE_ACTIVE; + var identity = association.identity(); + var localKeys = fixture.worldPrivateKeys(); + String fixtureOperationId = fixture.fixtureOperationId().toString(); + String lifecycleBindingDigest = fixture.preparationInputDigest(); + byte[] exactResponseBytes = fixture.gameSessionAssociationResponseBytes(); + String gameSessionResponseBytesDigest = sha256Raw(exactResponseBytes); + if (exactResponseBytes.length == 0 + || !lifecycleBindingDigest.matches("sha256:[0-9a-f]{64}") + || !fixtureOperationId.equals(capability.operationId()) + || !association.versionIdentity().equals(versionReceipt) + || !fixture.sourceIntakeReceipt().equals(sourceReceipt) + || !sourceReceipt.source().equals(sourceEvidence) + || !identity.canonicalGameInstanceId().equals(gameSession.gameInstanceUuid()) + || !identity.targetNamespace().equals(sourceReceipt.targetNamespace()) + || !identity.canonicalTenantId().equals(sourceReceipt.canonicalTenantId()) + || !identity.worldSlug().equals(sourceReceipt.worldSlug()) + || !identity.playableStateNamespaceId().equals(gameSession.playableStateNamespaceId()) + || !identity.playableStateScope().equals(capability.stateScope()) + || identity.publicProduction() != capability.publicProductionRealm() + || !identity.canonicalRealmId().equals(gameSession.canonicalRealmId()) + || identity.catalogRevision() != gameSession.catalogRevision() + || !identity.controlPlaneRequestId().equals(fixtureOperationId) + || !sourceReceipt.targetNamespace().equals(descriptor.targetNamespace()) + || !sourceReceipt.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !sourceReceipt.worldSlug().equals(descriptor.worldSlug()) + || !sourceReceipt.sourceOperationId().equals(descriptor.authoredWorldSourceOperationId()) + || !sourceReceipt + .sourceEvidenceDigest() + .equals(descriptor.authoredWorldSourceEvidenceDigest()) + || descriptor.gameTemplateId() != capability.gameTemplateId() + || !sourceReceipt.equals(versionReceipt.sourceIntakeReceipt()) + || !versionReceipt.canonicalTenantId().equals(sourceReceipt.canonicalTenantId()) + || !versionReceipt.canonicalVersionId().equals(gameSession.canonicalVersionId()) + || !versionReceipt.canonicalVersionId().toString().equals(bundle.getCanonicalVersionId()) + || versionReceipt.gameDesignVersionId() != descriptor.versionId() + || versionState.request().versionId() != descriptor.versionId() + || versionState.versionStateEpoch() != descriptor.versionStateEpoch() + || !publishedOrActive + || !versionState.sourceEvidence().equals(sourceReceipt.source()) + || bundle.getVersionId() != descriptor.versionId() + || bundle.getId() != descriptor.releaseBundleId() + || !bundle.getPublishedReleaseBundleRef().equals(descriptor.publishedReleaseBundleRef()) + || !bundle.getGenerationConfigRevision().equals(descriptor.generationConfigRevision()) + || artifact.getVersionId() != descriptor.versionId() + || artifact.getArtifactState() + != net.firedevops.firemud.gamedesign.v1.ArtifactState.ARTIFACT_STATE_PUBLISHED + || !artifact.getManifestHash().equals(bundle.getManifestHash()) + || descriptor.scriptPatchVersionPresent() + || descriptor.remapSetIdPresent() + || !gameSession.request().fixtureOperationId().toString().equals(fixtureOperationId) + || !gameSession.fixturePolicySeal().operationId().toString().equals(fixtureOperationId) + || !gameSession + .fixturePolicySeal() + .evidenceDigest() + .equals(fixture.fixtureProvenanceDigest()) + || !gameSession + .request() + .expectedFixturePolicyEvidenceDigest() + .equals(gameSession.fixturePolicySeal().evidenceDigest()) + || !Objects.equals(policyRequest.capability(), capability) + || !Objects.equals(policyRequest.sourceEvidence(), sourceReceipt.source()) + || !Objects.equals(policyRequest.launchReadEvidence(), launchReadEvidence) + || !Objects.equals(policyRequest.creationEvidence(), creationEvidence) + || !"NEW_GAME_ROW".equals(sourceReceipt.source().provenanceKind()) + || !"SHARED".equals(capability.stateScope()) + || localKeys.tenantId() != sourceReceipt.localTenantKey() + || localKeys.versionId() != versionReceipt.localVersionKey() + || localKeys.gameInstanceId() <= 0 + || sourceReceipt.localTenantKey() <= 0 + || versionReceipt.localVersionKey() <= 0) { + throw new IllegalArgumentException( + "RUN_OWNED_WORLD_FIXED_PRESET_RETAINED_EVIDENCE_MISMATCH: retained typed World association, source, Version, descriptor, bundle, or fixture policy differs"); + } + + return sealPlan( + capability, + gameSession, + sourceReceipt, + versionReceipt, + descriptor, + bundle, + lifecycleBindingDigest, + gameSessionResponseBytesDigest); + } + + private static FixedPresetPlan sealPlan( + RunOwnedInitialAdmissionFixtureWireCodec.Capability capability, + CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult gameSession, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + WorldAuthoredVersionIdentityReceipt versionReceipt, + AuthoredWorldLaunchDescriptorEvidence descriptor, + PublishedReleaseBundle bundle, + String lifecycleBindingDigest, + String gameSessionResponseBytesDigest) { + var versionState = versionReceipt.versionStateEvidence(); + FixedPresetPlan unsealed = + new FixedPresetPlan( + PRESET_SCHEMA_VERSION, + PRESET_ID, + capability.operationId(), + capability.claimDigest(), + gameSession.fixturePolicySeal().requestDigest(), + gameSession.fixturePolicySeal().evidenceDigest(), + sha256Raw(gameSession.fixturePolicyRequestBytes()), + lifecycleBindingDigest, + gameSessionResponseBytesDigest, + sourceReceipt.targetNamespace(), + sourceReceipt.canonicalTenantId(), + sourceReceipt.worldSlug(), + sourceReceipt.operationId(), + sourceReceipt.sourceOperationId(), + sourceReceipt.sourceEvidenceDigest(), + sourceReceipt.receiptDigest(), + sourceReceipt.localTenantKey(), + versionReceipt.operationId(), + versionReceipt.canonicalVersionId(), + versionReceipt.gameDesignVersionId(), + versionState.evidenceDigest(), + versionReceipt.localVersionKey(), + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + descriptor.runtimeFlagsJson(), + descriptor.versionId(), + descriptor.releaseBundleId(), + descriptor.publishedReleaseBundleRef(), + bundle.getManifestHash(), + descriptor.generationConfigRevision(), + descriptor.versionStateEpoch(), + gameSession.gameSessionTenantId(), + gameSession.gameInstanceId(), + gameSession.gameInstanceUuid(), + gameSession.canonicalTenantId(), + gameSession.canonicalVersionId(), + gameSession.playableStateNamespaceId(), + gameSession.canonicalRealmId(), + capability.stateScope(), + capability.publicProductionRealm(), + gameSession.catalogRevision(), + capability.gameTemplateId(), + CONTENT_DIGEST, + REGION, + ZONE, + List.of(STARTER_ROOM, SECONDARY_ROOM), + EXITS, + ""); + return unsealed.withPresetSealDigest(presetSealDigest(unsealed)); + } + + /** + * Writes the preset and its retained preparation result inside the caller's owner transaction. + */ + public static MaterializedFixedPreset materialize( + DSLContext dsl, + RunOwnedCanonicalWorldLaunchEvidence fixtureEvidence, + FixedPresetPlan plan, + long worldInstanceId, + long privateGameInstanceKey) { + Objects.requireNonNull(fixtureEvidence, "fixtureEvidence").requireFixedGameSessionPeer(); + Objects.requireNonNull(plan, "plan"); + requireCurrentFixtureMatchesRetainedPlan(fixtureEvidence, plan); + Objects.requireNonNull(dsl, "dsl"); + requirePositive(worldInstanceId, "worldInstanceId"); + requirePositive(privateGameInstanceKey, "privateGameInstanceKey"); + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Run-owned fixed preset materialization requires the existing World owner transaction"); + } + requireOriginalPreparingRow(dsl, plan, worldInstanceId, privateGameInstanceKey); + Record row = + dsl.fetchOne( + "SELECT * FROM world_materialize_run_owned_fixed_preset(?, ?, ?, ?)", + plan.planJson(), + plan.expectedContentDigest(), + worldInstanceId, + privateGameInstanceKey); + MaterializedFixedPreset result = + requireResult(row, plan, worldInstanceId, privateGameInstanceKey); + requireOriginalPreparingRow(dsl, plan, worldInstanceId, privateGameInstanceKey); + return result; + } + + /** + * Independently reconstructs the retained result and verifies all fixed resources after commit. + * + *

Call this from the existing separate committed-read transaction, including on exact replay + * after a process restart. + */ + public static MaterializedFixedPreset readCommitted( + DSLContext dsl, FixedPresetPlan plan, long worldInstanceId, long privateGameInstanceKey) { + Objects.requireNonNull(dsl, "dsl"); + Objects.requireNonNull(plan, "plan"); + requirePositive(worldInstanceId, "worldInstanceId"); + requirePositive(privateGameInstanceKey, "privateGameInstanceKey"); + requireOriginalPreparingRow(dsl, plan, worldInstanceId, privateGameInstanceKey); + Record row = + dsl.fetchOne( + "SELECT * FROM world_read_run_owned_fixed_preset(?, ?, ?, ?)", + plan.planJson(), + plan.expectedContentDigest(), + worldInstanceId, + privateGameInstanceKey); + MaterializedFixedPreset result = + requireResult(row, plan, worldInstanceId, privateGameInstanceKey); + requireOriginalPreparingRow(dsl, plan, worldInstanceId, privateGameInstanceKey); + return result; + } + + /** Reconstructs the expected plan from the independently reloaded association on every replay. */ + public static MaterializedFixedPreset readCommitted( + DSLContext dsl, + WorldCanonicalInstanceAssociation association, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + WorldAuthoredVersionIdentityReceipt versionReceipt) { + Objects.requireNonNull(association, "association"); + FixedPresetPlan plan = plan(association, sourceReceipt, versionReceipt); + return readCommitted( + dsl, + plan, + association.worldInstanceId(), + association.runOwnedFixture().worldPrivateKeys().gameInstanceId()); + } + + /** The retained seal survives retries; only the independent GS read correlation may change. */ + private static void requireCurrentFixtureMatchesRetainedPlan( + RunOwnedCanonicalWorldLaunchEvidence evidence, FixedPresetPlan plan) { + var capability = evidence.capability(); + var receipt = evidence.sourceReceipt(); + var source = receipt.sourceEvidence(); + var gs = evidence.gameSessionAssociation(); + var descriptor = evidence.launchDescriptor(); + PreparedWorldInstanceRequest request = + new PreparedWorldInstanceRequest( + gs.gameSessionTenantId(), + gs.gameInstanceId(), + capability.gameTemplateId(), + capability.operationId(), + descriptor.launchDescriptorId(), + descriptor.versionId(), + descriptor.scriptPatchVersionPresent() ? descriptor.scriptPatchVersion() : null, + descriptor.runtimeFlagsJson(), + descriptor.generationConfigRevision(), + descriptor.releaseBundleId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + descriptor.remapSetIdPresent() ? descriptor.remapSetId() : null); + evidence.requireMatches(request); + // This original binding commits exact immutable capability/receipt bytes and all recipients. + // The GS response digest in the retained plan keeps its original read nonce; it is never + // rebuilt. + if (!plan.fixtureOperationId().equals(capability.operationId()) + || !plan.claimDigest().equals(capability.claimDigest()) + || !plan.lifecycleBindingDigest().equals("sha256:" + evidence.bindingDigest(request, 1L)) + || !plan.fixturePolicyRequestDigest().equals(receipt.fixturePolicySeal().requestDigest()) + || !plan.fixturePolicyEvidenceDigest().equals(receipt.fixturePolicySeal().evidenceDigest()) + || !plan.fixturePolicyBytesDigest().equals(sha256Raw(gs.fixturePolicyRequestBytes())) + || !plan.targetNamespace().equals(gs.request().targetNamespace()) + || !plan.targetNamespace().equals(source.targetNamespace()) + || !plan.canonicalTenantId().equals(source.canonicalTenantId()) + || !plan.worldSlug().equals(source.worldSlug()) + || !plan.sourceOperationId().equals(source.operationId()) + || !plan.sourceEvidenceDigest().equals(source.evidenceDigest()) + || !plan.gameSessionGameInstanceUuid().equals(gs.gameInstanceUuid()) + || !plan.gameSessionCanonicalTenantId().equals(gs.canonicalTenantId()) + || !plan.gameSessionCanonicalVersionId().equals(gs.canonicalVersionId()) + || plan.gameSessionTenantId() != gs.gameSessionTenantId() + || plan.gameSessionGameInstanceId() != gs.gameInstanceId() + || !plan.playableStateNamespaceId().equals(gs.playableStateNamespaceId()) + || !plan.canonicalRealmId().equals(gs.canonicalRealmId()) + || plan.catalogRevision() != gs.catalogRevision() + || !plan.playableStateScope().equals(capability.stateScope()) + || plan.publicProduction() != capability.publicProductionRealm() + || gs.currentGameInstanceStatus() + != net.firedevops.firemud.common.gamesession + .CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus + .STARTING + || gs.currentRowVersion() != 0L + || !plan.presetSealDigest().equals(presetSealDigest(plan))) { + throw new IllegalArgumentException( + "RUN_OWNED_WORLD_FIXED_PRESET_RETRY_MISMATCH: current fixed peer evidence differs from the original sealed owner plan"); + } + } + + /** Qualifies only the immutable original PREPARING row, never activation or later lifecycle. */ + private static void requireOriginalPreparingRow( + DSLContext dsl, FixedPresetPlan plan, long worldInstanceId, long privateGameInstanceKey) { + Record row = dsl.fetchOne("SELECT * FROM world_instance WHERE id = ?", worldInstanceId); + if (row == null + || !"PREPARING".equals(row.get("status", String.class)) + || !Long.valueOf(1L).equals(row.get("lifecycle_epoch", Long.class)) + || !Long.valueOf(0L).equals(row.get("row_version", Long.class)) + || !Long.valueOf(1L) + .equals(row.get("run_owned_fixture_preparing_lifecycle_epoch", Long.class)) + || !"RUN_OWNED_FIXTURE".equals(row.get("canonical_authority_kind", String.class)) + || !Long.valueOf(plan.worldLocalTenantKey()).equals(row.get("tenant_id", Long.class)) + || !Long.valueOf(plan.worldLocalVersionKey()).equals(row.get("version_id", Long.class)) + || !Long.valueOf(privateGameInstanceKey).equals(row.get("game_instance_id", Long.class)) + || !plan.gameSessionGameInstanceUuid() + .equals(row.get("canonical_game_instance_id", UUID.class)) + || !plan.fixtureOperationId().equals(row.get("control_plane_request_id", String.class)) + || !plan.fixturePolicyEvidenceDigest() + .equals(row.get("fixture_provenance_digest", String.class)) + || !plan.lifecycleBindingDigest() + .equals("sha256:" + row.get("run_owned_fixture_binding_sha256", String.class))) { + throw new IllegalStateException( + "RUN_OWNED_WORLD_FIXED_PRESET_PREPARING_MISMATCH: fixed materialization/readback requires the original PREPARING allocation"); + } + } + + private static MaterializedFixedPreset requireResult( + Record row, FixedPresetPlan plan, long worldInstanceId, long privateGameInstanceKey) { + if (row == null) { + throw new IllegalStateException( + "RUN_OWNED_WORLD_FIXED_PRESET_RESULT_MISSING: retained resource result was not found"); + } + MaterializedFixedPreset result = + new MaterializedFixedPreset( + requiredLong(row, "world_instance_id"), + requiredLong(row, "tenant_id"), + requiredLong(row, "private_game_instance_key"), + requiredLong(row, "version_id"), + requiredText(row, "preset_id"), + requiredText(row, "preset_content_digest"), + requiredText(row, "preset_binding_digest"), + requiredText(row, "graph_sha256"), + requiredInt(row, "region_count"), + requiredInt(row, "zone_count"), + requiredInt(row, "room_count"), + requiredInt(row, "exit_count")); + if (result.worldInstanceId() != worldInstanceId + || result.tenantId() != plan.worldLocalTenantKey() + || result.privateGameInstanceKey() != privateGameInstanceKey + || result.versionId() != plan.worldLocalVersionKey() + || !result.presetId().equals(plan.presetId()) + || !result.presetContentDigest().equals(plan.expectedContentDigest()) + || !result.presetBindingDigest().equals(plan.presetSealDigest()) + || !result.graphSha256().equals(plan.expectedGraphSha256()) + || result.regionCount() != 1 + || result.zoneCount() != 1 + || result.roomCount() != 2 + || result.exitCount() != 2) { + throw new IllegalStateException( + "RUN_OWNED_WORLD_FIXED_PRESET_RESULT_MISMATCH: retained preparation or resource readback differs from the complete expected preset"); + } + return result; + } + + private static String presetSealDigest(FixedPresetPlan plan) { + MessageDigest digest = newDigest(); + add(digest, BINDING_DOMAIN); + add(digest, plan.presetId()); + add(digest, plan.expectedContentDigest()); + add(digest, plan.targetNamespace()); + add(digest, plan.fixtureOperationId()); + add(digest, plan.claimDigest()); + add(digest, plan.fixturePolicyRequestDigest()); + add(digest, plan.fixturePolicyEvidenceDigest()); + add(digest, plan.fixturePolicyBytesDigest()); + add(digest, plan.lifecycleBindingDigest()); + add(digest, plan.gameSessionResponseBytesDigest()); + add(digest, plan.canonicalTenantId().toString()); + add(digest, plan.worldSlug()); + add(digest, plan.worldSourceIntakeOperationId().toString()); + add(digest, plan.sourceOperationId().toString()); + add(digest, plan.sourceEvidenceDigest()); + add(digest, plan.sourceReceiptDigest()); + add(digest, Long.toString(plan.worldLocalTenantKey())); + add(digest, plan.worldVersionIdentityOperationId().toString()); + add(digest, plan.canonicalVersionId().toString()); + add(digest, Long.toString(plan.gameDesignVersionId())); + add(digest, plan.versionEvidenceDigest()); + add(digest, Long.toString(plan.worldLocalVersionKey())); + add(digest, plan.launchDescriptorId()); + add(digest, plan.descriptorRequestDigest()); + add(digest, plan.descriptorResultDigest()); + add(digest, plan.descriptorRuntimeFlagsJson()); + add(digest, Long.toString(plan.launchGameDesignVersionId())); + add(digest, Long.toString(plan.releaseBundleId())); + add(digest, plan.publishedReleaseBundleRef()); + add(digest, plan.manifestHash()); + add(digest, plan.generationConfigRevision()); + add(digest, Long.toString(plan.versionStateEpoch())); + add(digest, Long.toString(plan.gameSessionTenantId())); + add(digest, Long.toString(plan.gameSessionGameInstanceId())); + add(digest, plan.gameSessionGameInstanceUuid().toString()); + add(digest, plan.gameSessionCanonicalTenantId().toString()); + add(digest, plan.gameSessionCanonicalVersionId().toString()); + add(digest, plan.playableStateNamespaceId().toString()); + add(digest, plan.canonicalRealmId().toString()); + add(digest, plan.playableStateScope()); + add(digest, Boolean.toString(plan.publicProduction())); + add(digest, Long.toString(plan.catalogRevision())); + add(digest, Long.toString(plan.gameTemplateId())); + return digestText(digest.digest()); + } + + private static String contentDigest() { + MessageDigest digest = newDigest(); + add(digest, CONTENT_DOMAIN); + add(digest, PRESET_ID); + add(digest, "REGION"); + add(digest, REGION.templateId().toString()); + add(digest, REGION.name()); + add(digest, Double.toHexString(REGION.spacingMultiplier())); + add(digest, Long.toString(REGION.generationSeed())); + add(digest, "ZONE"); + add(digest, ZONE.templateId().toString()); + add(digest, ZONE.parentRegionTemplateId().toString()); + add(digest, ZONE.name()); + for (RoomDefinition room : List.of(STARTER_ROOM, SECONDARY_ROOM)) { + add(digest, "ROOM"); + add(digest, room.templateId().toString()); + add(digest, room.parentZoneTemplateId().toString()); + add(digest, room.name()); + add(digest, room.description()); + } + for (ExitDefinition exit : EXITS) { + add(digest, "ROOM_EXIT"); + add(digest, exit.templateId().toString()); + add(digest, exit.fromRoomTemplateId().toString()); + add(digest, exit.toRoomTemplateId().toString()); + add(digest, exit.direction()); + add(digest, Integer.toString(exit.cost())); + } + return digestText(digest.digest()); + } + + private static UUID templateId(String family, String logicalName) { + return UUID.nameUUIDFromBytes( + (NAMESPACE + "/" + PRESET_ID + "/" + family + "/" + logicalName) + .getBytes(StandardCharsets.UTF_8)); + } + + private static void add(MessageDigest digest, String value) { + byte[] bytes = Objects.requireNonNull(value, "digest value").getBytes(StandardCharsets.UTF_8); + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); + digest.update(bytes); + } + + private static String sha256Raw(byte[] bytes) { + return digestText(newDigest().digest(bytes)); + } + + private static String digestText(byte[] digest) { + return "sha256:" + HexFormat.of().formatHex(digest); + } + + private static MessageDigest newDigest() { + try { + return MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException(exception); + } + } + + private static String planJson(FixedPresetPlan plan) { + Map root = new LinkedHashMap<>(); + root.put("schemaVersion", plan.schemaVersion()); + root.put("presetId", plan.presetId()); + root.put("fixtureOperationId", plan.fixtureOperationId()); + root.put("claimDigest", plan.claimDigest()); + root.put("fixturePolicyRequestDigest", plan.fixturePolicyRequestDigest()); + root.put("fixturePolicyEvidenceDigest", plan.fixturePolicyEvidenceDigest()); + root.put("fixturePolicyBytesDigest", plan.fixturePolicyBytesDigest()); + root.put("lifecycleBindingDigest", plan.lifecycleBindingDigest()); + root.put("gameSessionResponseBytesDigest", plan.gameSessionResponseBytesDigest()); + root.put("targetNamespace", plan.targetNamespace()); + root.put("canonicalTenantId", plan.canonicalTenantId().toString()); + root.put("worldSlug", plan.worldSlug()); + root.put("worldSourceIntakeOperationId", plan.worldSourceIntakeOperationId().toString()); + root.put("sourceOperationId", plan.sourceOperationId().toString()); + root.put("sourceEvidenceDigest", plan.sourceEvidenceDigest()); + root.put("sourceReceiptDigest", plan.sourceReceiptDigest()); + root.put("worldLocalTenantKey", plan.worldLocalTenantKey()); + root.put("worldVersionIdentityOperationId", plan.worldVersionIdentityOperationId().toString()); + root.put("canonicalVersionId", plan.canonicalVersionId().toString()); + root.put("gameDesignVersionId", plan.gameDesignVersionId()); + root.put("versionEvidenceDigest", plan.versionEvidenceDigest()); + root.put("worldLocalVersionKey", plan.worldLocalVersionKey()); + root.put("launchDescriptorId", plan.launchDescriptorId()); + root.put("descriptorRequestDigest", plan.descriptorRequestDigest()); + root.put("descriptorResultDigest", plan.descriptorResultDigest()); + root.put("descriptorRuntimeFlagsJson", plan.descriptorRuntimeFlagsJson()); + root.put("launchGameDesignVersionId", plan.launchGameDesignVersionId()); + root.put("releaseBundleId", plan.releaseBundleId()); + root.put("publishedReleaseBundleRef", plan.publishedReleaseBundleRef()); + root.put("manifestHash", plan.manifestHash()); + root.put("generationConfigRevision", plan.generationConfigRevision()); + root.put("versionStateEpoch", plan.versionStateEpoch()); + root.put("gameSessionTenantId", plan.gameSessionTenantId()); + root.put("gameSessionGameInstanceId", plan.gameSessionGameInstanceId()); + root.put("gameSessionGameInstanceUuid", plan.gameSessionGameInstanceUuid().toString()); + root.put("gameSessionCanonicalTenantId", plan.gameSessionCanonicalTenantId().toString()); + root.put("gameSessionCanonicalVersionId", plan.gameSessionCanonicalVersionId().toString()); + root.put("playableStateNamespaceId", plan.playableStateNamespaceId().toString()); + root.put("canonicalRealmId", plan.canonicalRealmId().toString()); + root.put("playableStateScope", plan.playableStateScope()); + root.put("publicProduction", plan.publicProduction()); + root.put("catalogRevision", plan.catalogRevision()); + root.put("gameTemplateId", plan.gameTemplateId()); + root.put("expectedContentDigest", plan.expectedContentDigest()); + root.put("presetSealDigest", plan.presetSealDigest()); + root.put("topology", topologyJson()); + try { + return JSON.writeValueAsString(root); + } catch (JacksonException exception) { + throw new IllegalStateException("Fixed preset plan could not be serialized", exception); + } + } + + private static List> topologyJson() { + List> rows = new ArrayList<>(); + rows.add( + object( + "family", "REGION", + "templateId", REGION.templateId().toString(), + "name", REGION.name(), + "spacingMultiplier", REGION.spacingMultiplier(), + "generationSeed", REGION.generationSeed())); + rows.add( + object( + "family", "ZONE", + "templateId", ZONE.templateId().toString(), + "parentRegionTemplateId", ZONE.parentRegionTemplateId().toString(), + "name", ZONE.name())); + for (RoomDefinition room : List.of(STARTER_ROOM, SECONDARY_ROOM)) { + rows.add( + object( + "family", "ROOM", + "templateId", room.templateId().toString(), + "parentZoneTemplateId", room.parentZoneTemplateId().toString(), + "name", room.name(), + "description", room.description())); + } + for (ExitDefinition exit : EXITS) { + rows.add( + object( + "family", "ROOM_EXIT", + "templateId", exit.templateId().toString(), + "fromRoomTemplateId", exit.fromRoomTemplateId().toString(), + "toRoomTemplateId", exit.toRoomTemplateId().toString(), + "direction", exit.direction(), + "cost", exit.cost())); + } + return List.copyOf(rows); + } + + private static Map object(Object... fields) { + if ((fields.length & 1) != 0) throw new IllegalArgumentException("JSON fields are incomplete"); + Map values = new LinkedHashMap<>(); + for (int index = 0; index < fields.length; index += 2) { + values.put((String) fields[index], fields[index + 1]); + } + return values; + } + + private static long requiredLong(Record row, String column) { + Long value = row.get(column, Long.class); + if (value == null || value <= 0L) throw invalidResult(); + return value; + } + + private static int requiredInt(Record row, String column) { + Integer value = row.get(column, Integer.class); + if (value == null || value < 0) throw invalidResult(); + return value; + } + + private static String requiredText(Record row, String column) { + String value = row.get(column, String.class); + if (value == null || value.isBlank()) throw invalidResult(); + return value; + } + + private static IllegalStateException invalidResult() { + return new IllegalStateException( + "RUN_OWNED_WORLD_FIXED_PRESET_RESULT_INVALID: owner result is incomplete"); + } + + private static void requirePositive(long value, String name) { + if (value <= 0L) throw new IllegalArgumentException(name + " must be positive"); + } + + public record Definition( + String presetId, + RegionDefinition region, + ZoneDefinition zone, + List rooms, + List exits) { + public Definition { + rooms = List.copyOf(rooms); + exits = List.copyOf(exits); + } + + public String expectedContentDigest() { + return CONTENT_DIGEST; + } + } + + public record RegionDefinition( + UUID templateId, String name, double spacingMultiplier, long generationSeed) {} + + public record ZoneDefinition(UUID templateId, UUID parentRegionTemplateId, String name) {} + + public record RoomDefinition( + UUID templateId, UUID parentZoneTemplateId, String name, String description) {} + + public record ExitDefinition( + UUID templateId, + UUID fromRoomTemplateId, + UUID toRoomTemplateId, + String direction, + int cost) {} + + public static final class FixedPresetPlan { + private final int schemaVersion; + private final String presetId; + private final String fixtureOperationId; + private final String claimDigest; + private final String fixturePolicyRequestDigest; + private final String fixturePolicyEvidenceDigest; + private final String fixturePolicyBytesDigest; + private final String lifecycleBindingDigest; + private final String gameSessionResponseBytesDigest; + private final String targetNamespace; + private final UUID canonicalTenantId; + private final String worldSlug; + private final UUID worldSourceIntakeOperationId; + private final UUID sourceOperationId; + private final String sourceEvidenceDigest; + private final String sourceReceiptDigest; + private final long worldLocalTenantKey; + private final UUID worldVersionIdentityOperationId; + private final UUID canonicalVersionId; + private final long gameDesignVersionId; + private final String versionEvidenceDigest; + private final long worldLocalVersionKey; + private final String launchDescriptorId; + private final String descriptorRequestDigest; + private final String descriptorResultDigest; + private final String descriptorRuntimeFlagsJson; + private final long launchGameDesignVersionId; + private final long releaseBundleId; + private final String publishedReleaseBundleRef; + private final String manifestHash; + private final String generationConfigRevision; + private final long versionStateEpoch; + private final long gameSessionTenantId; + private final long gameSessionGameInstanceId; + private final UUID gameSessionGameInstanceUuid; + private final UUID gameSessionCanonicalTenantId; + private final UUID gameSessionCanonicalVersionId; + private final UUID playableStateNamespaceId; + private final UUID canonicalRealmId; + private final String playableStateScope; + private final boolean publicProduction; + private final long catalogRevision; + private final long gameTemplateId; + private final String expectedContentDigest; + private final RegionDefinition region; + private final ZoneDefinition zone; + private final List rooms; + private final List exits; + private final String presetSealDigest; + + private FixedPresetPlan( + int schemaVersion, + String presetId, + String fixtureOperationId, + String claimDigest, + String fixturePolicyRequestDigest, + String fixturePolicyEvidenceDigest, + String fixturePolicyBytesDigest, + String lifecycleBindingDigest, + String gameSessionResponseBytesDigest, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID worldSourceIntakeOperationId, + UUID sourceOperationId, + String sourceEvidenceDigest, + String sourceReceiptDigest, + long worldLocalTenantKey, + UUID worldVersionIdentityOperationId, + UUID canonicalVersionId, + long gameDesignVersionId, + String versionEvidenceDigest, + long worldLocalVersionKey, + String launchDescriptorId, + String descriptorRequestDigest, + String descriptorResultDigest, + String descriptorRuntimeFlagsJson, + long launchGameDesignVersionId, + long releaseBundleId, + String publishedReleaseBundleRef, + String manifestHash, + String generationConfigRevision, + long versionStateEpoch, + long gameSessionTenantId, + long gameSessionGameInstanceId, + UUID gameSessionGameInstanceUuid, + UUID gameSessionCanonicalTenantId, + UUID gameSessionCanonicalVersionId, + UUID playableStateNamespaceId, + UUID canonicalRealmId, + String playableStateScope, + boolean publicProduction, + long catalogRevision, + long gameTemplateId, + String expectedContentDigest, + RegionDefinition region, + ZoneDefinition zone, + List rooms, + List exits, + String presetSealDigest) { + this.schemaVersion = schemaVersion; + this.presetId = Objects.requireNonNull(presetId); + this.fixtureOperationId = Objects.requireNonNull(fixtureOperationId); + this.claimDigest = Objects.requireNonNull(claimDigest); + this.fixturePolicyRequestDigest = Objects.requireNonNull(fixturePolicyRequestDigest); + this.fixturePolicyEvidenceDigest = Objects.requireNonNull(fixturePolicyEvidenceDigest); + this.fixturePolicyBytesDigest = Objects.requireNonNull(fixturePolicyBytesDigest); + this.lifecycleBindingDigest = Objects.requireNonNull(lifecycleBindingDigest); + this.gameSessionResponseBytesDigest = Objects.requireNonNull(gameSessionResponseBytesDigest); + this.targetNamespace = Objects.requireNonNull(targetNamespace); + this.canonicalTenantId = Objects.requireNonNull(canonicalTenantId); + this.worldSlug = Objects.requireNonNull(worldSlug); + this.worldSourceIntakeOperationId = Objects.requireNonNull(worldSourceIntakeOperationId); + this.sourceOperationId = Objects.requireNonNull(sourceOperationId); + this.sourceEvidenceDigest = Objects.requireNonNull(sourceEvidenceDigest); + this.sourceReceiptDigest = Objects.requireNonNull(sourceReceiptDigest); + this.worldLocalTenantKey = worldLocalTenantKey; + this.worldVersionIdentityOperationId = + Objects.requireNonNull(worldVersionIdentityOperationId); + this.canonicalVersionId = Objects.requireNonNull(canonicalVersionId); + this.gameDesignVersionId = gameDesignVersionId; + this.versionEvidenceDigest = Objects.requireNonNull(versionEvidenceDigest); + this.worldLocalVersionKey = worldLocalVersionKey; + this.launchDescriptorId = Objects.requireNonNull(launchDescriptorId); + this.descriptorRequestDigest = Objects.requireNonNull(descriptorRequestDigest); + this.descriptorResultDigest = Objects.requireNonNull(descriptorResultDigest); + this.descriptorRuntimeFlagsJson = Objects.requireNonNull(descriptorRuntimeFlagsJson); + this.launchGameDesignVersionId = launchGameDesignVersionId; + this.releaseBundleId = releaseBundleId; + this.publishedReleaseBundleRef = Objects.requireNonNull(publishedReleaseBundleRef); + this.manifestHash = Objects.requireNonNull(manifestHash); + this.generationConfigRevision = Objects.requireNonNull(generationConfigRevision); + this.versionStateEpoch = versionStateEpoch; + this.gameSessionTenantId = gameSessionTenantId; + this.gameSessionGameInstanceId = gameSessionGameInstanceId; + this.gameSessionGameInstanceUuid = Objects.requireNonNull(gameSessionGameInstanceUuid); + this.gameSessionCanonicalTenantId = Objects.requireNonNull(gameSessionCanonicalTenantId); + this.gameSessionCanonicalVersionId = Objects.requireNonNull(gameSessionCanonicalVersionId); + this.playableStateNamespaceId = Objects.requireNonNull(playableStateNamespaceId); + this.canonicalRealmId = Objects.requireNonNull(canonicalRealmId); + this.playableStateScope = Objects.requireNonNull(playableStateScope); + this.publicProduction = publicProduction; + this.catalogRevision = catalogRevision; + this.gameTemplateId = gameTemplateId; + this.expectedContentDigest = Objects.requireNonNull(expectedContentDigest); + this.region = Objects.requireNonNull(region); + this.zone = Objects.requireNonNull(zone); + this.rooms = List.copyOf(rooms); + this.exits = List.copyOf(exits); + this.presetSealDigest = Objects.requireNonNull(presetSealDigest); + } + + private FixedPresetPlan withPresetSealDigest(String digest) { + return new FixedPresetPlan( + schemaVersion, + presetId, + fixtureOperationId, + claimDigest, + fixturePolicyRequestDigest, + fixturePolicyEvidenceDigest, + fixturePolicyBytesDigest, + lifecycleBindingDigest, + gameSessionResponseBytesDigest, + targetNamespace, + canonicalTenantId, + worldSlug, + worldSourceIntakeOperationId, + sourceOperationId, + sourceEvidenceDigest, + sourceReceiptDigest, + worldLocalTenantKey, + worldVersionIdentityOperationId, + canonicalVersionId, + gameDesignVersionId, + versionEvidenceDigest, + worldLocalVersionKey, + launchDescriptorId, + descriptorRequestDigest, + descriptorResultDigest, + descriptorRuntimeFlagsJson, + launchGameDesignVersionId, + releaseBundleId, + publishedReleaseBundleRef, + manifestHash, + generationConfigRevision, + versionStateEpoch, + gameSessionTenantId, + gameSessionGameInstanceId, + gameSessionGameInstanceUuid, + gameSessionCanonicalTenantId, + gameSessionCanonicalVersionId, + playableStateNamespaceId, + canonicalRealmId, + playableStateScope, + publicProduction, + catalogRevision, + gameTemplateId, + expectedContentDigest, + region, + zone, + rooms, + exits, + digest); + } + + public int schemaVersion() { + return schemaVersion; + } + + public String presetId() { + return presetId; + } + + public String fixtureOperationId() { + return fixtureOperationId; + } + + public String claimDigest() { + return claimDigest; + } + + public String fixturePolicyRequestDigest() { + return fixturePolicyRequestDigest; + } + + public String fixturePolicyEvidenceDigest() { + return fixturePolicyEvidenceDigest; + } + + public String fixturePolicyBytesDigest() { + return fixturePolicyBytesDigest; + } + + public String targetNamespace() { + return targetNamespace; + } + + public UUID canonicalTenantId() { + return canonicalTenantId; + } + + public String worldSlug() { + return worldSlug; + } + + public UUID worldSourceIntakeOperationId() { + return worldSourceIntakeOperationId; + } + + public UUID sourceOperationId() { + return sourceOperationId; + } + + public String sourceEvidenceDigest() { + return sourceEvidenceDigest; + } + + public String sourceReceiptDigest() { + return sourceReceiptDigest; + } + + public long worldLocalTenantKey() { + return worldLocalTenantKey; + } + + public UUID worldVersionIdentityOperationId() { + return worldVersionIdentityOperationId; + } + + public UUID canonicalVersionId() { + return canonicalVersionId; + } + + public long gameDesignVersionId() { + return gameDesignVersionId; + } + + public String versionEvidenceDigest() { + return versionEvidenceDigest; + } + + public long worldLocalVersionKey() { + return worldLocalVersionKey; + } + + public String launchDescriptorId() { + return launchDescriptorId; + } + + public String descriptorRequestDigest() { + return descriptorRequestDigest; + } + + public String descriptorResultDigest() { + return descriptorResultDigest; + } + + public String descriptorRuntimeFlagsJson() { + return descriptorRuntimeFlagsJson; + } + + public long launchGameDesignVersionId() { + return launchGameDesignVersionId; + } + + public long releaseBundleId() { + return releaseBundleId; + } + + public String publishedReleaseBundleRef() { + return publishedReleaseBundleRef; + } + + public String manifestHash() { + return manifestHash; + } + + public String generationConfigRevision() { + return generationConfigRevision; + } + + public long versionStateEpoch() { + return versionStateEpoch; + } + + public long gameSessionTenantId() { + return gameSessionTenantId; + } + + public long gameSessionGameInstanceId() { + return gameSessionGameInstanceId; + } + + public UUID gameSessionGameInstanceUuid() { + return gameSessionGameInstanceUuid; + } + + public UUID gameSessionCanonicalTenantId() { + return gameSessionCanonicalTenantId; + } + + public UUID gameSessionCanonicalVersionId() { + return gameSessionCanonicalVersionId; + } + + public String lifecycleBindingDigest() { + return lifecycleBindingDigest; + } + + public String gameSessionResponseBytesDigest() { + return gameSessionResponseBytesDigest; + } + + public UUID playableStateNamespaceId() { + return playableStateNamespaceId; + } + + public UUID canonicalRealmId() { + return canonicalRealmId; + } + + public String playableStateScope() { + return playableStateScope; + } + + public boolean publicProduction() { + return publicProduction; + } + + public long catalogRevision() { + return catalogRevision; + } + + public long gameTemplateId() { + return gameTemplateId; + } + + public String expectedContentDigest() { + return expectedContentDigest; + } + + public RegionDefinition region() { + return region; + } + + public ZoneDefinition zone() { + return zone; + } + + public List rooms() { + return rooms; + } + + public List exits() { + return exits; + } + + public String presetSealDigest() { + return presetSealDigest; + } + + public String expectedGraphSha256() { + return sha256Raw(planJson().getBytes(StandardCharsets.UTF_8)).substring("sha256:".length()); + } + + public String planJson() { + return RunOwnedWorldFixedPresetResources.planJson(this); + } + } + + public record MaterializedFixedPreset( + long worldInstanceId, + long tenantId, + long privateGameInstanceKey, + long versionId, + String presetId, + String presetContentDigest, + String presetBindingDigest, + String graphSha256, + int regionCount, + int zoneCount, + int roomCount, + int exitCount) {} +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java index 34d4f6ec2d..e0b10ea562 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java @@ -1,19 +1,32 @@ package net.firedevops.firemud.worldmanagement.service.impl; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.MeterRegistry; import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; +import java.io.IOException; import java.time.Instant; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.function.Supplier; import net.firedevops.firemud.common.LoggingUtil; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; import net.firedevops.firemud.worldmanagement.client.GameDesignClient; import net.firedevops.firemud.worldmanagement.config.WorldProperties; +import net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidence; +import net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidenceProvider; +import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldFixedPresetResources; import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidence; import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceProvider; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; @@ -36,13 +49,25 @@ import net.firedevops.firemud.worldmanagement.repository.ZoneInstanceRepository; import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; import net.firedevops.firemud.worldmanagement.service.WorldLifecycleCommandService; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeService; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociation; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCompleteLaunchBindingRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository; +import org.jooq.DSLContext; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionOperations; +import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; @Service @@ -72,12 +97,26 @@ public class WorldLifecycleCommandServiceImpl implements WorldLifecycleCommandSe private final MeterRegistry meterRegistry; private final TransactionOperations transactionOperations; private final RunOwnedWorldLaunchEvidenceProvider runOwnedWorldLaunchEvidenceProvider; + private final RunOwnedCanonicalWorldLaunchEvidenceProvider + runOwnedCanonicalWorldLaunchEvidenceProvider; + + private final DSLContext dsl; + private final PlatformTransactionManager fixtureTransactionManager; + private final ServiceEndpointsProperties serviceEndpoints; + private final CommonGrpcClientProperties grpcClientProperties; + private final GrpcChannelFactory grpcChannelFactory; + private final String workloadNamespace; + + private volatile RunOwnedWorldFixtureOwners runOwnedWorldFixtureOwners; + + private final TransactionOperations fixtureTransactionOperations; + private final TransactionOperations prepareTransactionOperations; + private boolean fixtureOwnersClosed; private Counter prepareCounter; private Counter activateCounter; private Counter failCounter; - @Autowired public WorldLifecycleCommandServiceImpl( WorldInstanceRepository worldInstanceRepository, RegionInstanceRepository regionInstanceRepository, @@ -112,6 +151,54 @@ public WorldLifecycleCommandServiceImpl( runOwnedWorldLaunchEvidenceProvider); } + @Autowired + public WorldLifecycleCommandServiceImpl( + WorldInstanceRepository worldInstanceRepository, + RegionInstanceRepository regionInstanceRepository, + ZoneRepository zoneRepository, + ZoneInstanceRepository zoneInstanceRepository, + RoomRepository roomRepository, + RoomExitRepository roomExitRepository, + RoomInstanceRepository roomInstanceRepository, + RoomInstanceExitRepository roomInstanceExitRepository, + WorldEventRepository worldEventRepository, + WorldProperties worldProperties, + GameDesignClient gameDesignClient, + EntityManagementClient entityManagementClient, + MeterRegistry meterRegistry, + PlatformTransactionManager transactionManager, + RunOwnedWorldLaunchEvidenceProvider runOwnedWorldLaunchEvidenceProvider, + RunOwnedCanonicalWorldLaunchEvidenceProvider runOwnedCanonicalWorldLaunchEvidenceProvider, + DSLContext dsl, + ServiceEndpointsProperties serviceEndpoints, + CommonGrpcClientProperties grpcClientProperties, + GrpcChannelFactory grpcChannelFactory, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this( + worldInstanceRepository, + regionInstanceRepository, + zoneRepository, + zoneInstanceRepository, + roomRepository, + roomExitRepository, + roomInstanceRepository, + roomInstanceExitRepository, + worldEventRepository, + worldProperties, + gameDesignClient, + entityManagementClient, + meterRegistry, + transactionTemplate(transactionManager), + runOwnedWorldLaunchEvidenceProvider, + runOwnedCanonicalWorldLaunchEvidenceProvider, + dsl, + transactionManager, + serviceEndpoints, + grpcClientProperties, + grpcChannelFactory, + workloadNamespace); + } + WorldLifecycleCommandServiceImpl( WorldInstanceRepository worldInstanceRepository, RegionInstanceRepository regionInstanceRepository, @@ -161,6 +248,152 @@ public WorldLifecycleCommandServiceImpl( MeterRegistry meterRegistry, TransactionOperations transactionOperations, RunOwnedWorldLaunchEvidenceProvider runOwnedWorldLaunchEvidenceProvider) { + this( + worldInstanceRepository, + regionInstanceRepository, + zoneRepository, + zoneInstanceRepository, + roomRepository, + roomExitRepository, + roomInstanceRepository, + roomInstanceExitRepository, + worldEventRepository, + worldProperties, + gameDesignClient, + entityManagementClient, + meterRegistry, + transactionOperations, + runOwnedWorldLaunchEvidenceProvider, + null, + null, + null, + null, + null, + null, + null); + } + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The injected owner bundle is an internal collaborator; construction only initializes fields, acquires no resources, and this service has no finalizer.") + WorldLifecycleCommandServiceImpl( + WorldInstanceRepository worldInstanceRepository, + RegionInstanceRepository regionInstanceRepository, + ZoneRepository zoneRepository, + ZoneInstanceRepository zoneInstanceRepository, + RoomRepository roomRepository, + RoomExitRepository roomExitRepository, + RoomInstanceRepository roomInstanceRepository, + RoomInstanceExitRepository roomInstanceExitRepository, + WorldEventRepository worldEventRepository, + WorldProperties worldProperties, + GameDesignClient gameDesignClient, + EntityManagementClient entityManagementClient, + MeterRegistry meterRegistry, + TransactionOperations transactionOperations, + RunOwnedWorldLaunchEvidenceProvider runOwnedWorldLaunchEvidenceProvider, + DSLContext dsl, + RunOwnedWorldFixtureOwners runOwnedWorldFixtureOwners) { + this( + worldInstanceRepository, + regionInstanceRepository, + zoneRepository, + zoneInstanceRepository, + roomRepository, + roomExitRepository, + roomInstanceRepository, + roomInstanceExitRepository, + worldEventRepository, + worldProperties, + gameDesignClient, + entityManagementClient, + meterRegistry, + transactionOperations, + runOwnedWorldLaunchEvidenceProvider, + null, + dsl, + null, + null, + null, + null, + null); + this.runOwnedWorldFixtureOwners = + Objects.requireNonNull(runOwnedWorldFixtureOwners, "runOwnedWorldFixtureOwners"); + } + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The injected owner bundle is an internal collaborator; construction only initializes fields, acquires no resources, and this service has no finalizer.") + WorldLifecycleCommandServiceImpl( + WorldInstanceRepository worldInstanceRepository, + RegionInstanceRepository regionInstanceRepository, + ZoneRepository zoneRepository, + ZoneInstanceRepository zoneInstanceRepository, + RoomRepository roomRepository, + RoomExitRepository roomExitRepository, + RoomInstanceRepository roomInstanceRepository, + RoomInstanceExitRepository roomInstanceExitRepository, + WorldEventRepository worldEventRepository, + WorldProperties worldProperties, + GameDesignClient gameDesignClient, + EntityManagementClient entityManagementClient, + MeterRegistry meterRegistry, + TransactionOperations transactionOperations, + RunOwnedCanonicalWorldLaunchEvidenceProvider runOwnedCanonicalWorldLaunchEvidenceProvider, + DSLContext dsl, + RunOwnedWorldFixtureOwners runOwnedWorldFixtureOwners) { + this( + worldInstanceRepository, + regionInstanceRepository, + zoneRepository, + zoneInstanceRepository, + roomRepository, + roomExitRepository, + roomInstanceRepository, + roomInstanceExitRepository, + worldEventRepository, + worldProperties, + gameDesignClient, + entityManagementClient, + meterRegistry, + transactionOperations, + null, + runOwnedCanonicalWorldLaunchEvidenceProvider, + dsl, + null, + null, + null, + null, + null); + this.runOwnedWorldFixtureOwners = + Objects.requireNonNull(runOwnedWorldFixtureOwners, "runOwnedWorldFixtureOwners"); + } + + private WorldLifecycleCommandServiceImpl( + WorldInstanceRepository worldInstanceRepository, + RegionInstanceRepository regionInstanceRepository, + ZoneRepository zoneRepository, + ZoneInstanceRepository zoneInstanceRepository, + RoomRepository roomRepository, + RoomExitRepository roomExitRepository, + RoomInstanceRepository roomInstanceRepository, + RoomInstanceExitRepository roomInstanceExitRepository, + WorldEventRepository worldEventRepository, + WorldProperties worldProperties, + GameDesignClient gameDesignClient, + EntityManagementClient entityManagementClient, + MeterRegistry meterRegistry, + TransactionOperations transactionOperations, + RunOwnedWorldLaunchEvidenceProvider runOwnedWorldLaunchEvidenceProvider, + RunOwnedCanonicalWorldLaunchEvidenceProvider runOwnedCanonicalWorldLaunchEvidenceProvider, + DSLContext dsl, + PlatformTransactionManager fixtureTransactionManager, + ServiceEndpointsProperties serviceEndpoints, + CommonGrpcClientProperties grpcClientProperties, + GrpcChannelFactory grpcChannelFactory, + String workloadNamespace) { this.worldInstanceRepository = worldInstanceRepository; this.regionInstanceRepository = regionInstanceRepository; this.zoneRepository = zoneRepository; @@ -176,6 +409,29 @@ public WorldLifecycleCommandServiceImpl( this.meterRegistry = meterRegistry; this.transactionOperations = transactionOperations; this.runOwnedWorldLaunchEvidenceProvider = runOwnedWorldLaunchEvidenceProvider; + this.runOwnedCanonicalWorldLaunchEvidenceProvider = + runOwnedCanonicalWorldLaunchEvidenceProvider; + this.dsl = dsl; + this.fixtureTransactionManager = fixtureTransactionManager; + this.serviceEndpoints = serviceEndpoints; + this.grpcClientProperties = grpcClientProperties; + this.grpcChannelFactory = grpcChannelFactory; + this.workloadNamespace = workloadNamespace; + PlatformTransactionManager prepareTransactionManager = fixtureTransactionManager; + if (prepareTransactionManager == null + && transactionOperations instanceof TransactionTemplate template) { + prepareTransactionManager = template.getTransactionManager(); + } + // Ordinary preparation retains its original REQUIRED boundary. Fixture reads execute before + // any transaction, then its owners use their separate short READ_COMMITTED transactions. + this.prepareTransactionOperations = + prepareTransactionManager == null + ? transactionOperations + : new TransactionTemplate(prepareTransactionManager); + this.fixtureTransactionOperations = + fixtureTransactionManager == null + ? transactionOperations + : fixtureTransactionTemplate(fixtureTransactionManager); } WorldLifecycleCommandServiceImpl( @@ -215,6 +471,15 @@ private static TransactionTemplate transactionTemplate( return transactionTemplate; } + private static TransactionTemplate fixtureTransactionTemplate( + PlatformTransactionManager transactionManager) { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + return transaction; + } + @PostConstruct void initMetrics() { prepareCounter = meterRegistry.counter("world_instance_prepare_total"); @@ -222,11 +487,160 @@ void initMetrics() { failCounter = meterRegistry.counter("world_instance_fail_total"); } + /** + * Runs the explicit canonical source-preparation stage through the original PREPARING allocation. + * Generic lifecycle calls retain the published runtime-evidence contract. + */ + WorldInstanceLifecycleSnapshotDto prepareRunOwnedFixture( + PreparedWorldInstanceRequest originalGameSessionRequest, + RunOwnedCanonicalWorldLaunchEvidence fixtureEvidence) { + Objects.requireNonNull(fixtureEvidence, "fixtureEvidence").requireFixedGameSessionPeer(); + requireNoAmbientFixtureReadTransaction(); + if (!canonicalFixtureModeEnabled()) throw fixtureWritesUnavailable(); + fixtureEvidence.requireMatches(originalGameSessionRequest); + RunOwnedWorldFixtureOwners owners = requireRunOwnedWorldFixtureOwners(); + var sourceReceipt = owners.sourceIntakeService().intakeRunOwnedFixture(fixtureEvidence); + var versionIdentity = + owners.versionIdentityService().associateRunOwnedFixture(fixtureEvidence, sourceReceipt); + // Check the current owner observation before resource writes. Allocation retains the original + // GS response bytes; that retained response, rather than a fresh read nonce, seals the plan. + RunOwnedWorldFixedPresetResources.plan(fixtureEvidence, sourceReceipt, versionIdentity); + WorldCanonicalInstanceAssociation allocated = + executeFixtureOwnerTransaction( + () -> { + owners + .associationRepository() + .lockRunOwnedFixtureInOwnerTransaction( + fixtureEvidence, originalGameSessionRequest); + owners + .publicationFenceRepository() + .lockOpen( + new OwnerBinding( + sourceReceipt.targetNamespace(), + sourceReceipt.canonicalTenantId(), + versionIdentity.canonicalVersionId(), + versionIdentity.operationId(), + versionIdentity.gameDesignVersionId(), + sourceReceipt.intakeRequestId(), + sourceReceipt.operationId(), + sourceReceipt.requestDigest(), + sourceReceipt.sourceOperationId(), + sourceReceipt.sourceEvidenceDigest(), + sourceReceipt.receiptDigest())); + WorldCanonicalInstanceAssociation association = + owners + .associationRepository() + .allocateRunOwnedFixtureInOwnerTransaction( + fixtureEvidence, + originalGameSessionRequest, + sourceReceipt, + versionIdentity); + var retainedPlan = + RunOwnedWorldFixedPresetResources.plan( + association, sourceReceipt, versionIdentity); + RunOwnedWorldFixedPresetResources.materialize( + dsl, + fixtureEvidence, + retainedPlan, + association.worldInstanceId(), + association.worldPrivateKeys().gameInstanceId()); + return association; + }); + WorldCanonicalInstanceAssociation committed = + owners + .associationRepository() + .readRunOwnedFixtureAssociation(fixtureEvidence, originalGameSessionRequest); + requireSameFixtureAllocation(allocated, committed); + RunOwnedWorldFixedPresetResources.readCommitted( + dsl, + committed, + committed.runOwnedFixture().sourceIntakeReceipt(), + committed.versionIdentity()); + WorldInstance materialized = + worldInstanceRepository + .findById(committed.worldInstanceId()) + .orElseThrow( + () -> + new IllegalStateException( + "RUN_OWNED_WORLD_INSTANCE_MISSING: committed fixture World row is missing")); + var keys = committed.worldPrivateKeys(); + PreparedWorldInstanceRequest worldRequest = + new PreparedWorldInstanceRequest( + keys.tenantId(), + keys.gameInstanceId(), + originalGameSessionRequest.gameTemplateId(), + originalGameSessionRequest.controlPlaneRequestId(), + originalGameSessionRequest.launchDescriptorId(), + keys.versionId(), + originalGameSessionRequest.scriptPatchVersion(), + originalGameSessionRequest.runtimeFlagsJson(), + originalGameSessionRequest.generationConfigRevision(), + originalGameSessionRequest.releaseBundleId(), + originalGameSessionRequest.publishedReleaseBundleRef(), + originalGameSessionRequest.versionStateEpoch(), + originalGameSessionRequest.remapSetId()); + if (!Objects.equals(materialized.getId(), committed.worldInstanceId()) + || !Objects.equals(materialized.getTenantId(), keys.tenantId()) + || !Objects.equals(materialized.getGameInstanceId(), keys.gameInstanceId()) + || !Objects.equals(materialized.getVersionId(), keys.versionId()) + || !STATUS_PREPARING.equals(materialized.getStatus()) + || !Long.valueOf(1L).equals(materialized.getLifecycleEpoch()) + || !Long.valueOf(0L).equals(materialized.getRowVersion()) + || !Long.valueOf(1L).equals(materialized.getRunOwnedFixturePreparingLifecycleEpoch()) + || !committed + .runOwnedFixture() + .preparationInputDigest() + .equals("sha256:" + materialized.getRunOwnedFixtureBindingSha256()) + || !materialized + .getRunOwnedFixtureBindingSha256() + .equals(fixtureEvidence.bindingDigest(originalGameSessionRequest, 1L)) + || !samePreparedRequest(materialized, worldRequest) + || materialized.getFailureReason() != null + || materialized.getTerminationRequestId() != null + || materialized.getTerminatedAt() != null) { + throw fixtureEvidenceMismatch(); + } + prepareCounter.increment(); + WorldInstanceLifecycleSnapshotDto materializedSnapshot = snapshot(materialized); + return new WorldInstanceLifecycleSnapshotDto( + originalGameSessionRequest.tenantId(), + originalGameSessionRequest.gameInstanceId(), + materializedSnapshot.gameTemplateId(), + materializedSnapshot.controlPlaneRequestId(), + materializedSnapshot.launchDescriptorId(), + originalGameSessionRequest.versionId(), + materializedSnapshot.releaseBundleId(), + materializedSnapshot.generationConfigRevision(), + materializedSnapshot.publishedReleaseBundleRef(), + materializedSnapshot.versionStateEpoch(), + materializedSnapshot.lifecycleEpoch(), + materializedSnapshot.status(), + materializedSnapshot.remapSetId(), + materializedSnapshot.workflowId(), + materializedSnapshot.workflowFamily(), + materializedSnapshot.workflowRunId(), + materializedSnapshot.workflowStatus()); + } + + private T executeFixtureOwnerTransaction(Supplier operation) { + if (fixtureTransactionOperations == null) throw fixtureEvidenceUnavailable(); + return Objects.requireNonNull( + fixtureTransactionOperations.execute(status -> operation.get()), + "Fixture owner transaction returned no retained allocation"); + } + @Override - @Transactional @Timed(value = "world.prepareInstance") public WorldInstanceLifecycleSnapshotDto prepareWorldInstance( PreparedWorldInstanceRequest request) { + if (prepareTransactionOperations == null) return preparePublishedWorldInstance(request); + return Objects.requireNonNull( + prepareTransactionOperations.execute(status -> preparePublishedWorldInstance(request)), + "Ordinary preparation transaction returned no World snapshot"); + } + + private WorldInstanceLifecycleSnapshotDto preparePublishedWorldInstance( + PreparedWorldInstanceRequest request) { validatePrepareRequest(request); RunOwnedWorldLaunchEvidence fixtureEvidence = configuredFixtureEvidence(); if (fixtureEvidence != null) { @@ -254,24 +668,18 @@ public WorldInstanceLifecycleSnapshotDto prepareWorldInstance( .orElse(null); if (existing != null) { if (existing.getRunOwnedFixtureBindingSha256() != null) { - if (fixtureEvidence == null) { - throw fixtureEvidenceUnavailable(); - } + if (fixtureEvidence == null) throw fixtureEvidenceUnavailable(); requireRunOwnedFixtureBinding(existing, fixtureEvidence, request); return snapshot(existing); } - if (fixtureEvidence != null) { - throw fixtureIdentityConflict(); - } + if (fixtureEvidence != null) throw fixtureIdentityConflict(); if (!samePreparedRequest(existing, request)) { throw new IllegalArgumentException( "INVALID_ARGUMENT: gameInstanceId already exists with different activation inputs"); } return snapshot(existing); } - if (fixtureEvidence == null) { - validateAttestedLaunchInputs(request); - } + if (fixtureEvidence == null) validateAttestedLaunchInputs(request); WorldInstance worldInstance = new WorldInstance(); worldInstance.setTenantId(request.tenantId()); worldInstance.setGameInstanceId(request.gameInstanceId()); @@ -328,14 +736,12 @@ public WorldInstanceLifecycleSnapshotDto activatePreparedWorldInstance( long tenantId, long gameInstanceId, long expectedLifecycleEpoch) { WorldInstance worldInstance = requireWorldInstance(tenantId, gameInstanceId); if (worldInstance.getRunOwnedFixtureBindingSha256() != null) { - if (!fixtureModeEnabled()) { - throw fixtureEvidenceUnavailable(); - } + if (!fixtureModeEnabled()) throw fixtureEvidenceUnavailable(); RunOwnedWorldLaunchEvidence fixtureEvidence = runOwnedWorldLaunchEvidenceProvider.requireAuthenticatedEvidence(); worldInstance = requireLockedWorldInstance(tenantId, gameInstanceId); - PreparedWorldInstanceRequest preparedRequest = preparedRequest(worldInstance); - requireRunOwnedFixtureBinding(worldInstance, fixtureEvidence, preparedRequest); + PreparedWorldInstanceRequest existingRequest = preparedRequest(worldInstance); + requireRunOwnedFixtureBinding(worldInstance, fixtureEvidence, existingRequest); if (STATUS_ACTIVE.equals(worldInstance.getStatus())) { long preparingEpoch = worldInstance.getRunOwnedFixturePreparingLifecycleEpoch(); if (worldInstance.getLifecycleEpoch() != preparingEpoch + 1L @@ -347,13 +753,19 @@ public WorldInstanceLifecycleSnapshotDto activatePreparedWorldInstance( } requireLifecycleEpoch(worldInstance, expectedLifecycleEpoch); } else { - if (fixtureModeEnabled()) { - throw fixtureIdentityConflict(); - } - requireLifecycleEpoch(worldInstance, expectedLifecycleEpoch); + if (fixtureModeEnabled()) throw fixtureIdentityConflict(); if (STATUS_ACTIVE.equals(worldInstance.getStatus())) { + Long currentLifecycleEpoch = worldInstance.getLifecycleEpoch(); + if (expectedLifecycleEpoch <= 0L + || currentLifecycleEpoch == null + || currentLifecycleEpoch <= 0L + || (expectedLifecycleEpoch != currentLifecycleEpoch + && currentLifecycleEpoch - 1L != expectedLifecycleEpoch)) { + throw lifecycleEpochMismatch(); + } return snapshot(worldInstance); } + requireLifecycleEpoch(worldInstance, expectedLifecycleEpoch); } if (!STATUS_PREPARING.equals(worldInstance.getStatus())) { throw new IllegalArgumentException( @@ -410,25 +822,149 @@ private void requireRunOwnedFixtureBinding( } private RunOwnedWorldLaunchEvidence configuredFixtureEvidence() { - if (!fixtureModeEnabled()) { - return null; - } + if (!fixtureModeEnabled()) return null; return runOwnedWorldLaunchEvidenceProvider.requireAuthenticatedEvidence(); } + private static void requireSameFixtureAllocation( + WorldCanonicalInstanceAssociation expected, WorldCanonicalInstanceAssociation actual) { + if (!expected.isRunOwnedFixture() + || !actual.isRunOwnedFixture() + || expected.worldInstanceId() != actual.worldInstanceId() + || !expected.identity().equals(actual.identity()) + || !expected.worldPrivateKeys().equals(actual.worldPrivateKeys()) + || !expected.versionIdentity().equals(actual.versionIdentity()) + || !expected + .runOwnedFixture() + .sourceIntakeReceipt() + .equals(actual.runOwnedFixture().sourceIntakeReceipt()) + || !expected + .runOwnedFixture() + .preparationInputDigest() + .equals(actual.runOwnedFixture().preparationInputDigest()) + || !expected + .runOwnedFixture() + .fixtureProvenanceDigest() + .equals(actual.runOwnedFixture().fixtureProvenanceDigest()) + || !java.util.Arrays.equals( + expected.runOwnedFixture().gameSessionAssociationResponseBytes(), + actual.runOwnedFixture().gameSessionAssociationResponseBytes())) { + throw fixtureEvidenceMismatch(); + } + } + + private synchronized RunOwnedWorldFixtureOwners requireRunOwnedWorldFixtureOwners() { + if (fixtureOwnersClosed) throw fixtureEvidenceUnavailable(); + if (runOwnedWorldFixtureOwners != null) { + return runOwnedWorldFixtureOwners; + } + if (!canonicalFixtureModeEnabled() + || dsl == null + || fixtureTransactionManager == null + || serviceEndpoints == null + || grpcClientProperties == null + || grpcChannelFactory == null + || workloadNamespace == null + || !"dev".equals(workloadNamespace)) { + throw fixtureEvidenceUnavailable(); + } + + AuthoredWorldSourceClient sourceClient = + new AuthoredWorldSourceClient( + serviceEndpoints, grpcClientProperties, grpcChannelFactory, workloadNamespace); + AuthoredWorldVersionStateClient versionStateClient = + new AuthoredWorldVersionStateClient( + serviceEndpoints, grpcClientProperties, grpcChannelFactory, workloadNamespace); + try { + sourceClient.init(); + versionStateClient.init(); + WorldAuthoredSourceIntakeRepository sourceRepository = + new WorldAuthoredSourceIntakeRepository(dsl); + WorldAuthoredVersionIdentityRepository versionRepository = + new WorldAuthoredVersionIdentityRepository(dsl); + WorldAuthoredSourceIntakeService sourceIntakeService = + new WorldAuthoredSourceIntakeService( + sourceClient, sourceRepository, fixtureTransactionManager, workloadNamespace); + WorldAuthoredVersionIdentityService versionIdentityService = + new WorldAuthoredVersionIdentityService( + versionStateClient, + versionRepository, + sourceRepository, + fixtureTransactionManager, + workloadNamespace); + WorldCanonicalInstanceAssociationRepository associationRepository = + new WorldCanonicalInstanceAssociationRepository( + dsl, + new WorldCompleteLaunchBindingRepository(dsl), + sourceRepository, + versionRepository); + runOwnedWorldFixtureOwners = + new RunOwnedWorldFixtureOwners( + sourceClient, + versionStateClient, + sourceIntakeService, + versionIdentityService, + associationRepository, + new WorldDesignPublicationFenceRepository(dsl, sourceRepository)); + return runOwnedWorldFixtureOwners; + } catch (IOException | RuntimeException failure) { + closeFixtureClient(sourceClient, "authored-source"); + closeFixtureClient(versionStateClient, "authored-Version"); + throw new IllegalStateException( + "RUN_OWNED_WORLD_FIXTURE_OWNER_UNAVAILABLE: authenticated fixture owner clients could not initialize", + failure); + } + } + + @PreDestroy + synchronized void closeRunOwnedWorldFixtureOwners() { + fixtureOwnersClosed = true; + RunOwnedWorldFixtureOwners owners = runOwnedWorldFixtureOwners; + runOwnedWorldFixtureOwners = null; + if (owners != null) { + owners.close(); + } + } + + private static void closeFixtureClient(AutoCloseable client, String label) { + try { + client.close(); + } catch (Exception closeFailure) { + logger.warn("Run-owned World {} owner client did not close cleanly", label); + } + } + + private static void requireNoAmbientFixtureReadTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Run-owned World evidence reads require no ambient transaction"); + } + } + + private static IllegalArgumentException fixtureEvidenceMismatch() { + return new IllegalArgumentException( + "RUN_OWNED_WORLD_LAUNCH_EVIDENCE_MISMATCH: stored fixture binding or prepared identity changed"); + } + private boolean fixtureModeEnabled() { return runOwnedWorldLaunchEvidenceProvider != null && runOwnedWorldLaunchEvidenceProvider.isEnabled(); } + private boolean canonicalFixtureModeEnabled() { + return runOwnedCanonicalWorldLaunchEvidenceProvider != null + && runOwnedCanonicalWorldLaunchEvidenceProvider.isEnabled(); + } + private static IllegalArgumentException fixtureEvidenceUnavailable() { return new IllegalArgumentException( "RUN_OWNED_WORLD_LAUNCH_EVIDENCE_UNAVAILABLE: fixture-bound lifecycle requires verified run evidence"); } - private static IllegalArgumentException fixtureEvidenceMismatch() { + private static IllegalArgumentException fixtureWritesUnavailable() { return new IllegalArgumentException( - "RUN_OWNED_WORLD_LAUNCH_EVIDENCE_MISMATCH: stored fixture binding or prepared identity changed"); + "RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE: fixture mutation requires its verified owner"); } private static IllegalArgumentException fixtureIdentityConflict() { @@ -442,11 +978,38 @@ private static IllegalArgumentException lifecycleEpochMismatch() { } @Override - @Transactional @Timed(value = "world.failPreparedInstance") public WorldInstanceLifecycleSnapshotDto failPreparedWorldInstance( long tenantId, long gameInstanceId, long expectedLifecycleEpoch, String reason) { - WorldInstance worldInstance = requireWorldInstance(tenantId, gameInstanceId); + if (fixtureModeEnabled()) { + requireNoAmbientFixtureReadTransaction(); + RunOwnedWorldLaunchEvidence fixtureEvidence = + runOwnedWorldLaunchEvidenceProvider.requireAuthenticatedEvidence(); + return executeOwnedLifecycleTransaction( + () -> + failPreparedWorldInstanceOwned( + tenantId, gameInstanceId, expectedLifecycleEpoch, reason, fixtureEvidence)); + } + if (prepareTransactionOperations == null) { + return failPreparedWorldInstanceOwned( + tenantId, gameInstanceId, expectedLifecycleEpoch, reason, null); + } + return Objects.requireNonNull( + prepareTransactionOperations.execute( + status -> + failPreparedWorldInstanceOwned( + tenantId, gameInstanceId, expectedLifecycleEpoch, reason, null)), + "Ordinary failure transaction returned no World snapshot"); + } + + private WorldInstanceLifecycleSnapshotDto failPreparedWorldInstanceOwned( + long tenantId, + long gameInstanceId, + long expectedLifecycleEpoch, + String reason, + RunOwnedWorldLaunchEvidence fixtureEvidence) { + WorldInstance worldInstance = requireLockedWorldInstance(tenantId, gameInstanceId); + requireLegacyFixtureLifecycleOwner(worldInstance, fixtureEvidence); requireLifecycleEpoch(worldInstance, expectedLifecycleEpoch); if (STATUS_FAILED_PRE_ACTIVATION.equals(worldInstance.getStatus())) { return snapshot(worldInstance); @@ -491,15 +1054,17 @@ public WorldInstanceLifecycleSnapshotDto terminateWorldInstance( if (terminationRequestId == null || terminationRequestId.isBlank()) { throw new IllegalArgumentException("INVALID_ARGUMENT: terminationRequestId is required"); } + RunOwnedWorldLaunchEvidence fixtureEvidence = configuredFixtureEvidence(); WorldInstance worldInstance = - executeLocalTermination( + executeOwnedLifecycleTransaction( () -> beginOrResumeTermination( tenantId, gameInstanceId, expectedLifecycleEpoch, terminationRequestId, - reason)); + reason, + fixtureEvidence)); if (STATUS_TERMINATED.equals(worldInstance.getStatus())) { return snapshot(worldInstance); } @@ -513,10 +1078,11 @@ public WorldInstanceLifecycleSnapshotDto terminateWorldInstance( cleanupResponse.getError().getCode() + ": " + cleanupResponse.getError().getMessage()); } WorldInstanceLifecycleSnapshotDto terminatedSnapshot = - executeLocalTermination( + executeOwnedLifecycleTransaction( () -> { WorldInstance finalWorldInstance = requireLockedWorldInstance(tenantId, gameInstanceId); + requireLegacyFixtureLifecycleOwner(finalWorldInstance, fixtureEvidence); if (!terminationRequestId.equals(finalWorldInstance.getTerminationRequestId())) { throw new IllegalArgumentException( "INVALID_WORLD_INSTANCE_STATE: world instance termination request changed before finalization"); @@ -547,9 +1113,15 @@ private WorldInstance beginOrResumeTermination( long gameInstanceId, long expectedLifecycleEpoch, String terminationRequestId, - String reason) { + String reason, + RunOwnedWorldLaunchEvidence fixtureEvidence) { WorldInstance worldInstance = requireLockedWorldInstance(tenantId, gameInstanceId); + requireLegacyFixtureLifecycleOwner(worldInstance, fixtureEvidence); if (STATUS_TERMINATED.equals(worldInstance.getStatus())) { + if (!terminationRequestId.equals(worldInstance.getTerminationRequestId())) { + throw new IllegalArgumentException( + "IDEMPOTENCY_CONFLICT: world instance terminated under a different request id"); + } return worldInstance; } if (STATUS_ACTIVE.equals(worldInstance.getStatus())) { @@ -576,11 +1148,11 @@ private WorldInstance beginOrResumeTermination( "INVALID_WORLD_INSTANCE_STATE: world instance is not in ACTIVE or TERMINATING state"); } - private T executeLocalTermination(java.util.function.Supplier termination) { + private T executeOwnedLifecycleTransaction(java.util.function.Supplier operation) { if (transactionOperations == null) { - return termination.get(); + return operation.get(); } - return transactionOperations.execute(status -> termination.get()); + return transactionOperations.execute(status -> operation.get()); } private WorldInstance requireLockedWorldInstance(long tenantId, long gameInstanceId) { @@ -599,6 +1171,18 @@ private void cleanupWorldRuntimeState(long tenantId, long gameInstanceId) { regionInstanceRepository.deleteByTenantIdAndGameInstanceId(tenantId, gameInstanceId); } + private void requireLegacyFixtureLifecycleOwner( + WorldInstance worldInstance, RunOwnedWorldLaunchEvidence fixtureEvidence) { + boolean fixtureBound = worldInstance.getRunOwnedFixtureBindingSha256() != null; + if (fixtureModeEnabled()) { + if (!fixtureBound) throw fixtureIdentityConflict(); + if (fixtureEvidence == null) throw fixtureEvidenceUnavailable(); + requireRunOwnedFixtureBinding(worldInstance, fixtureEvidence, preparedRequest(worldInstance)); + } else if (fixtureBound) { + throw fixtureEvidenceUnavailable(); + } + } + private void validatePrepareRequest(PreparedWorldInstanceRequest request) { if (request.tenantId() <= 0L || request.gameInstanceId() <= 0L @@ -797,6 +1381,21 @@ private String normalizeBlank(String value) { return value == null || value.isBlank() ? null : value; } + record RunOwnedWorldFixtureOwners( + AuthoredWorldSourceClient sourceClient, + AuthoredWorldVersionStateClient versionStateClient, + WorldAuthoredSourceIntakeService sourceIntakeService, + WorldAuthoredVersionIdentityService versionIdentityService, + WorldCanonicalInstanceAssociationRepository associationRepository, + WorldDesignPublicationFenceRepository publicationFenceRepository) + implements AutoCloseable { + @Override + public void close() { + closeFixtureClient(sourceClient, "authored-source"); + closeFixtureClient(versionStateClient, "authored-Version"); + } + } + private void requireSupportedReleaseAttestationSchema(String schemaVersion) { if (!SUPPORTED_RELEASE_ATTESTATION_SCHEMA_VERSION.equals(schemaVersion)) { throw new IllegalArgumentException( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java index 873d90e4bd..d1c46d6b69 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.worldmanagement.tenant; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; import java.util.Objects; import java.util.Optional; import java.util.UUID; @@ -11,6 +12,7 @@ import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec.ReadRequest; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidence; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -153,6 +155,121 @@ public WorldAuthoredSourceIntakeReceipt intake( return readback; } + /** + * Retains the exact fresh source already sealed by the trusted fixed run-owned fixture. This + * overload is intentionally typed to the provider-created carrier; raw fixture files and caller + * supplied source DTOs cannot invoke the owner path. + */ + public WorldAuthoredSourceIntakeReceipt intakeRunOwnedFixture( + RunOwnedCanonicalWorldLaunchEvidence fixtureEvidence) { + Objects.requireNonNull(fixtureEvidence, "fixtureEvidence"); + fixtureEvidence.requireFixedGameSessionPeer(); + requireNoAmbientTransaction(); + if (SessionContext.hasAuthenticatedCallerContext()) { + throw new SecurityException( + "Run-owned fixture source intake rejects authenticated end-user caller context"); + } + + var trustedReceipt = fixtureEvidence.sourceReceipt(); + AuthoredWorldSourceEvidence expectedSource = trustedReceipt.sourceEvidence(); + UUID fixtureOperationId = UUID.fromString(fixtureEvidence.capability().operationId()); + UUID intakeRequestId = fixtureSourceIntakeRequestId(fixtureOperationId); + validateSchemaAndNamespace(SCHEMA_VERSION, workloadNamespace); + validateRequest( + workloadNamespace, + intakeRequestId, + expectedSource.canonicalTenantId(), + expectedSource.worldSlug(), + expectedSource.operationId(), + expectedSource.evidenceDigest()); + if (!fixtureOperationId.toString().equals(trustedReceipt.fixtureOperationId()) + || !workloadNamespace.equals(expectedSource.targetNamespace()) + || !fixtureEvidence + .launchDescriptor() + .canonicalTenantId() + .equals(expectedSource.canonicalTenantId()) + || !fixtureEvidence.launchDescriptor().worldSlug().equals(expectedSource.worldSlug()) + || !fixtureEvidence + .launchDescriptor() + .authoredWorldSourceOperationId() + .equals(expectedSource.operationId()) + || !fixtureEvidence + .launchDescriptor() + .authoredWorldSourceEvidenceDigest() + .equals(expectedSource.evidenceDigest())) { + throw new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "Run-owned fixture evidence differs from its exact Game Design source owner binding"); + } + + Optional prior = + repository.read(workloadNamespace, intakeRequestId); + if (prior.isPresent()) { + return requireReceiptForRequest( + prior.orElseThrow(), + intakeRequestId, + expectedSource.canonicalTenantId(), + expectedSource.worldSlug(), + expectedSource.operationId(), + expectedSource.evidenceDigest(), + expectedSource); + } + + AuthoredWorldSourceEvidence current = + sourceClient.read( + new ReadRequest( + workloadNamespace, + newReadRequestId(intakeRequestId), + expectedSource.operationId(), + expectedSource.canonicalTenantId(), + expectedSource.worldSlug())); + requireFreshSourceForRequest( + current, + expectedSource.canonicalTenantId(), + expectedSource.worldSlug(), + expectedSource.operationId(), + expectedSource.evidenceDigest()); + if (!expectedSource.equals(current)) { + throw new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "Authenticated Game Design source differs from the immutable run-owned fixture receipt"); + } + + WorldAuthoredSourceIntakeReceipt accepted = + ownerTransaction.execute( + status -> repository.acceptFresh(workloadNamespace, intakeRequestId, current)); + if (accepted == null) { + throw new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "Run-owned fixture source intake owner transaction returned no receipt"); + } + requireReceiptForRequest( + accepted, + intakeRequestId, + expectedSource.canonicalTenantId(), + expectedSource.worldSlug(), + expectedSource.operationId(), + expectedSource.evidenceDigest(), + expectedSource); + WorldAuthoredSourceIntakeReceipt readback = + repository + .read(workloadNamespace, intakeRequestId) + .orElseThrow( + () -> + new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "Run-owned fixture source intake is missing after its owner commit")); + requireReceiptForRequest( + readback, + intakeRequestId, + expectedSource.canonicalTenantId(), + expectedSource.worldSlug(), + expectedSource.operationId(), + expectedSource.evidenceDigest(), + expectedSource); + if (!accepted.equals(readback)) { + throw new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "Run-owned fixture source intake changed during independent commit readback"); + } + return readback; + } + /** Reads only an exact committed receipt; it never re-reads Game Design or allocates state. */ public Optional readCommittedReceipt( int schemaVersion, @@ -370,6 +487,17 @@ private static UUID newReadRequestId(UUID intakeRequestId) { return readRequestId; } + private static UUID fixtureSourceIntakeRequestId(UUID fixtureOperationId) { + UUID requestId = + UUID.nameUUIDFromBytes( + ("firemud-world-run-owned-fixture-source-intake/v1:" + fixtureOperationId) + .getBytes(StandardCharsets.UTF_8)); + if (NIL_UUID.equals(requestId) || fixtureOperationId.equals(requestId)) { + throw new IllegalArgumentException("Run-owned fixture source intake identity is invalid"); + } + return requestId; + } + private static void requireNonNil(UUID value, String name) { if (value == null || NIL_UUID.equals(value)) { throw new IllegalArgumentException(name + " must be a non-nil UUID"); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityService.java index 778ab294e8..3263814463 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityService.java @@ -7,9 +7,11 @@ import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidence; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -70,6 +72,89 @@ public WorldAuthoredVersionIdentityReceipt associate( long gameDesignVersionId, UUID readRequestId) { requireAuthenticatedGameDesignCaller(); + return associateInternal( + targetNamespace, + canonicalTenantId, + worldSlug, + sourceOperationId, + sourceEvidenceDigest, + expectedCanonicalVersionId, + gameDesignVersionId, + readRequestId, + null, + null); + } + + /** + * Reads and retains the exact canonical Version already committed by the trusted run-owned launch + * fixture. The typed provider carrier is required; raw selectors cannot use this owner path or + * bypass the ordinary authenticated Game Design entry point. + */ + public WorldAuthoredVersionIdentityReceipt associateRunOwnedFixture( + RunOwnedCanonicalWorldLaunchEvidence fixtureEvidence, + WorldAuthoredSourceIntakeReceipt sourceReceipt) { + Objects.requireNonNull(fixtureEvidence, "fixtureEvidence"); + fixtureEvidence.requireFixedGameSessionPeer(); + Objects.requireNonNull(sourceReceipt, "sourceReceipt"); + requireNoAmbientTransaction(); + if (SessionContext.hasAuthenticatedCallerContext()) { + throw new SecurityException( + "Run-owned fixture Version identity rejects authenticated end-user caller context"); + } + + var trustedSource = fixtureEvidence.sourceReceipt().sourceEvidence(); + var gs = fixtureEvidence.gameSessionAssociation(); + if (gs == null + || !workloadNamespace.equals(trustedSource.targetNamespace()) + || !sourceReceipt.source().equals(trustedSource) + || !sourceReceipt.targetNamespace().equals(workloadNamespace) + || !sourceReceipt.canonicalTenantId().equals(trustedSource.canonicalTenantId()) + || !sourceReceipt.worldSlug().equals(trustedSource.worldSlug()) + || !sourceReceipt.sourceOperationId().equals(trustedSource.operationId()) + || !sourceReceipt.sourceEvidenceDigest().equals(trustedSource.evidenceDigest()) + || !gs.fixturePolicySeal().equals(fixtureEvidence.sourceReceipt().fixturePolicySeal()) + || !gs.canonicalTenantId().equals(trustedSource.canonicalTenantId()) + || !gs.canonicalVersionId() + .toString() + .equals( + fixtureEvidence + .sourceReceipt() + .launchReadEvidence() + .publishedReleaseBundle() + .getCanonicalVersionId()) + || fixtureEvidence + .sourceReceipt() + .launchReadEvidence() + .publishedReleaseBundle() + .getVersionId() + != fixtureEvidence.launchDescriptor().versionId()) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "Run-owned fixture evidence differs from the exact source, Version, or Game Session owner binding"); + } + return associateInternal( + workloadNamespace, + trustedSource.canonicalTenantId(), + trustedSource.worldSlug(), + trustedSource.operationId(), + trustedSource.evidenceDigest(), + gs.canonicalVersionId(), + fixtureEvidence.launchDescriptor().versionId(), + UUID.randomUUID(), + sourceReceipt, + fixtureEvidence); + } + + private WorldAuthoredVersionIdentityReceipt associateInternal( + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest, + UUID expectedCanonicalVersionId, + long gameDesignVersionId, + UUID readRequestId, + WorldAuthoredSourceIntakeReceipt expectedSourceReceipt, + RunOwnedCanonicalWorldLaunchEvidence expectedFixtureEvidence) { requireNoAmbientTransaction(); validateRequest( targetNamespace, @@ -84,6 +169,10 @@ public WorldAuthoredVersionIdentityReceipt associate( WorldAuthoredSourceIntakeReceipt sourceReceipt = readExactSourceIntake( canonicalTenantId, worldSlug, sourceOperationId, sourceEvidenceDigest); + if (expectedSourceReceipt != null && !expectedSourceReceipt.equals(sourceReceipt)) { + throw new WorldAuthoredVersionIdentityRepository.RegistrationConflictException( + "Run-owned fixture Version identity differs from the exact committed World source receipt"); + } requireFreshReadRequestId(readRequestId, expectedCanonicalVersionId, sourceReceipt); Optional prior = @@ -91,7 +180,11 @@ public WorldAuthoredVersionIdentityReceipt associate( workloadNamespace, canonicalTenantId, worldSlug, expectedCanonicalVersionId); if (prior.isPresent()) { return requireSameIdentity( - prior.orElseThrow(), sourceReceipt, expectedCanonicalVersionId, gameDesignVersionId); + prior.orElseThrow(), + sourceReceipt, + expectedCanonicalVersionId, + gameDesignVersionId, + expectedFixtureEvidence); } Optional priorByGameDesignVersion = repository.readByGameDesignVersion( @@ -101,7 +194,8 @@ public WorldAuthoredVersionIdentityReceipt associate( priorByGameDesignVersion.orElseThrow(), sourceReceipt, expectedCanonicalVersionId, - gameDesignVersionId); + gameDesignVersionId, + expectedFixtureEvidence); } AuthoredWorldVersionStateEvidence.Request currentRequest = @@ -124,6 +218,9 @@ public WorldAuthoredVersionIdentityReceipt associate( "Game Design source-qualified Version identity evidence is unavailable or invalid", exception); } + if (expectedFixtureEvidence != null) { + requireFixtureVersionStateMatches(expectedFixtureEvidence, current); + } requireCurrentEvidence(current, currentRequest, sourceReceipt, expectedCanonicalVersionId); WorldAuthoredVersionIdentityReceipt accepted; @@ -142,7 +239,8 @@ public WorldAuthoredVersionIdentityReceipt associate( committed.orElseThrow(), sourceReceipt, expectedCanonicalVersionId, - gameDesignVersionId); + gameDesignVersionId, + expectedFixtureEvidence); } Optional claimedSelector = repository.readByGameDesignVersion( @@ -156,7 +254,8 @@ public WorldAuthoredVersionIdentityReceipt associate( claimedSelector.orElseThrow(), sourceReceipt, expectedCanonicalVersionId, - gameDesignVersionId); + gameDesignVersionId, + expectedFixtureEvidence); } throw ownerFailure; } @@ -164,7 +263,12 @@ public WorldAuthoredVersionIdentityReceipt associate( throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( "World owner transaction returned no Version identity receipt"); } - requireSameIdentity(accepted, sourceReceipt, expectedCanonicalVersionId, gameDesignVersionId); + requireSameIdentity( + accepted, + sourceReceipt, + expectedCanonicalVersionId, + gameDesignVersionId, + expectedFixtureEvidence); Optional committed = repository.readByCanonicalVersion( @@ -178,7 +282,12 @@ public WorldAuthoredVersionIdentityReceipt associate( sourceReceipt, readExactSourceIntake( canonicalTenantId, worldSlug, sourceOperationId, sourceEvidenceDigest)); - requireSameIdentity(readback, sourceReceipt, expectedCanonicalVersionId, gameDesignVersionId); + requireSameIdentity( + readback, + sourceReceipt, + expectedCanonicalVersionId, + gameDesignVersionId, + expectedFixtureEvidence); if (!accepted.equals(readback)) { throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( "World Version identity changed during independent commit readback"); @@ -186,11 +295,37 @@ public WorldAuthoredVersionIdentityReceipt associate( return readback; } + private static void requireFixtureVersionStateMatches( + RunOwnedCanonicalWorldLaunchEvidence fixtureEvidence, + AuthoredWorldVersionStateEvidence current) { + if (current == null) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "Game Design returned no current Version state for the sealed run-owned fixture"); + } + var expected = fixtureEvidence.sourceReceipt().launchReadEvidence().versionState(); + if (current.versionState() != expected.getVersionState() + || current.versionStateEpoch() != expected.getVersionStateEpoch() + || current.request().versionId() != fixtureEvidence.launchDescriptor().versionId() + || !current + .canonicalVersionId() + .toString() + .equals( + fixtureEvidence + .sourceReceipt() + .launchReadEvidence() + .publishedReleaseBundle() + .getCanonicalVersionId())) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "Current Game Design Version state differs from the exact sealed fixture snapshot"); + } + } + private WorldAuthoredVersionIdentityReceipt requireSameIdentity( WorldAuthoredVersionIdentityReceipt receipt, WorldAuthoredSourceIntakeReceipt sourceReceipt, UUID expectedCanonicalVersionId, - long gameDesignVersionId) { + long gameDesignVersionId, + RunOwnedCanonicalWorldLaunchEvidence expectedFixtureEvidence) { if (!receipt.targetNamespace().equals(workloadNamespace) || !receipt.sourceIntakeReceipt().equals(sourceReceipt) || !receipt.canonicalTenantId().equals(sourceReceipt.canonicalTenantId()) @@ -200,6 +335,9 @@ private WorldAuthoredVersionIdentityReceipt requireSameIdentity( throw new WorldAuthoredVersionIdentityRepository.RegistrationConflictException( "World Version identity scope, source intake, or selector conflicts with its first claim"); } + if (expectedFixtureEvidence != null) { + requireFixtureVersionStateMatches(expectedFixtureEvidence, receipt.versionStateEvidence()); + } return receipt; } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociation.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociation.java new file mode 100644 index 0000000000..4be3824534 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociation.java @@ -0,0 +1,671 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.gamesession.v1.GetRunOwnedFixtureLaunchAssociationResponse; + +/** + * Owner-local immutable correlation between a claimed canonical Game Session instance and one + * insert-born World instance row. + * + *

This association is not Game Session producer authentication, released-content authority, + * lifecycle state, activation, JOIN, or admission proof. A caller must establish the authenticated + * same-namespace producer and complete canonical prepare/materialization proof independently. + */ +public record WorldCanonicalInstanceAssociation( + CanonicalIdentity identity, + long worldInstanceId, + WorldCompleteLaunchBindingReceipt completeLaunchBinding, + WorldAuthoredVersionIdentityReceipt versionIdentity, + WorldPrepareFields worldPrepareFields, + RunOwnedFixture runOwnedFixture) { + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + + /** Existing Human association constructor retained at its call sites. */ + public WorldCanonicalInstanceAssociation( + CanonicalIdentity identity, + long worldInstanceId, + WorldCompleteLaunchBindingReceipt completeLaunchBinding, + WorldAuthoredVersionIdentityReceipt versionIdentity, + WorldPrepareFields worldPrepareFields) { + this( + identity, + worldInstanceId, + completeLaunchBinding, + versionIdentity, + worldPrepareFields, + null); + } + + public WorldCanonicalInstanceAssociation { + Objects.requireNonNull(identity, "identity"); + requirePositive(worldInstanceId, "worldInstanceId"); + if (runOwnedFixture == null) { + Objects.requireNonNull(completeLaunchBinding, "completeLaunchBinding"); + Objects.requireNonNull(versionIdentity, "versionIdentity"); + Objects.requireNonNull(worldPrepareFields, "worldPrepareFields"); + if (worldInstanceId != worldPrepareFields.worldInstanceId()) { + throw new IllegalArgumentException( + "World association row id differs from its prepare fields"); + } + requireExactLaunchEvidence(identity, completeLaunchBinding, versionIdentity); + worldPrepareFields.requireMatches(identity, completeLaunchBinding, versionIdentity); + } else { + if (completeLaunchBinding != null || worldPrepareFields != null) { + throw new IllegalArgumentException( + "Run-owned fixture association cannot carry Human launch or graph preparation fields"); + } + Objects.requireNonNull(versionIdentity, "versionIdentity"); + runOwnedFixture.requireMatches(identity, worldInstanceId, versionIdentity); + } + } + + public UUID canonicalVersionId() { + if (runOwnedFixture != null) return runOwnedFixture.canonicalVersionId(); + return completeLaunchBinding.evidence().releaseAttestation().canonicalVersionId(); + } + + public UUID launchBindingOperationId() { + if (runOwnedFixture != null) return null; + return completeLaunchBinding.operationId(); + } + + public UUID versionIdentityOperationId() { + return versionIdentity.operationId(); + } + + public boolean isRunOwnedFixture() { + return runOwnedFixture != null; + } + + /** World-private numeric keys are kept distinct from the authenticated Game Session keys. */ + public WorldPrivateKeys worldPrivateKeys() { + if (runOwnedFixture != null) return runOwnedFixture.worldPrivateKeys(); + return new WorldPrivateKeys( + worldPrepareFields.privateTenantKey(), + worldPrepareFields.privateGameInstanceKey(), + worldPrepareFields.localVersionKey()); + } + + public record WorldPrivateKeys(long tenantId, long gameInstanceId, long versionId) { + public WorldPrivateKeys { + requirePositive(tenantId, "tenantId"); + requirePositive(gameInstanceId, "gameInstanceId"); + requirePositive(versionId, "versionId"); + } + } + + /** Typed persisted fixture association; it is not an attestation or graph proof. */ + public record RunOwnedFixture( + WorldPrivateKeys worldPrivateKeys, + long gameSessionTenantId, + long gameSessionGameInstanceId, + long gameTemplateId, + UUID fixtureOperationId, + String fixtureProvenanceDigest, + String preparationInputDigest, + long preparingLifecycleEpoch, + byte[] gameSessionAssociationResponseBytes, + CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult gameSessionAssociation, + WorldAuthoredSourceIntakeReceipt sourceIntakeReceipt) { + public RunOwnedFixture { + Objects.requireNonNull(worldPrivateKeys, "worldPrivateKeys"); + requirePositive(gameSessionTenantId, "gameSessionTenantId"); + requirePositive(gameSessionGameInstanceId, "gameSessionGameInstanceId"); + requirePositive(gameTemplateId, "gameTemplateId"); + requireNonNil(fixtureOperationId, "fixtureOperationId"); + requireDigest(fixtureProvenanceDigest, "fixtureProvenanceDigest"); + requireDigest(preparationInputDigest, "preparationInputDigest"); + if (preparingLifecycleEpoch != 1L) { + throw new IllegalArgumentException( + "Fixture association requires its original PREPARING epoch"); + } + gameSessionAssociationResponseBytes = + Objects.requireNonNull( + gameSessionAssociationResponseBytes, "gameSessionAssociationResponseBytes") + .clone(); + Objects.requireNonNull(gameSessionAssociation, "gameSessionAssociation"); + Objects.requireNonNull(sourceIntakeReceipt, "sourceIntakeReceipt"); + if (gameSessionAssociationResponseBytes.length == 0) { + throw new IllegalArgumentException( + "Exact Game Session fixture response bytes are required"); + } + try { + var decoded = + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureResponse( + gameSessionAssociation.request(), + GetRunOwnedFixtureLaunchAssociationResponse.parseFrom( + gameSessionAssociationResponseBytes)); + if (!decoded.equals(gameSessionAssociation) + || !Arrays.equals( + gameSessionAssociationResponseBytes, + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toFixtureResponse(decoded) + .toByteArray())) { + throw new IllegalArgumentException( + "Stored Game Session fixture response bytes differ from their exact decoded result"); + } + } catch (com.google.protobuf.InvalidProtocolBufferException invalid) { + throw new IllegalArgumentException( + "Stored Game Session fixture response bytes are invalid", invalid); + } + } + + @Override + public byte[] gameSessionAssociationResponseBytes() { + return gameSessionAssociationResponseBytes.clone(); + } + + @Override + public boolean equals(Object other) { + if (this == other) return true; + if (!(other instanceof RunOwnedFixture value)) return false; + return gameSessionTenantId == value.gameSessionTenantId + && gameSessionGameInstanceId == value.gameSessionGameInstanceId + && gameTemplateId == value.gameTemplateId + && preparingLifecycleEpoch == value.preparingLifecycleEpoch + && worldPrivateKeys.equals(value.worldPrivateKeys) + && fixtureOperationId.equals(value.fixtureOperationId) + && fixtureProvenanceDigest.equals(value.fixtureProvenanceDigest) + && preparationInputDigest.equals(value.preparationInputDigest) + && Arrays.equals( + gameSessionAssociationResponseBytes, value.gameSessionAssociationResponseBytes) + && gameSessionAssociation.equals(value.gameSessionAssociation) + && sourceIntakeReceipt.equals(value.sourceIntakeReceipt); + } + + @Override + public int hashCode() { + int result = + Objects.hash( + worldPrivateKeys, + gameSessionTenantId, + gameSessionGameInstanceId, + gameTemplateId, + fixtureOperationId, + fixtureProvenanceDigest, + preparationInputDigest, + preparingLifecycleEpoch, + gameSessionAssociation, + sourceIntakeReceipt); + return 31 * result + Arrays.hashCode(gameSessionAssociationResponseBytes); + } + + public UUID canonicalVersionId() { + return gameSessionAssociation.canonicalVersionId(); + } + + private void requireMatches( + CanonicalIdentity identity, + long worldInstanceId, + WorldAuthoredVersionIdentityReceipt versionIdentity) { + var gs = gameSessionAssociation; + var policy = gs.fixturePolicyRequest(); + var capability = policy.capability(); + var source = policy.sourceEvidence(); + if (gs.gameSessionTenantId() != gameSessionTenantId + || gs.gameInstanceId() != gameSessionGameInstanceId + || !gs.gameInstanceUuid().equals(identity.canonicalGameInstanceId()) + || !gs.canonicalTenantId().equals(identity.canonicalTenantId()) + || !gs.request().targetNamespace().equals(identity.targetNamespace()) + || !source.worldSlug().equals(identity.worldSlug()) + || !gs.playableStateNamespaceId().equals(identity.playableStateNamespaceId()) + || !capability.stateScope().equals(identity.playableStateScope()) + || capability.publicProductionRealm() != identity.publicProduction() + || !gs.canonicalRealmId().equals(identity.canonicalRealmId()) + || gs.catalogRevision() != identity.catalogRevision() + || !fixtureOperationId.equals(gs.request().fixtureOperationId()) + || !identity.controlPlaneRequestId().equals(fixtureOperationId.toString()) + || !fixtureProvenanceDigest.equals(gs.fixturePolicySeal().evidenceDigest()) + || !identity.canonicalTenantId().equals(source.canonicalTenantId()) + || !identity.targetNamespace().equals(source.targetNamespace()) + || !identity.worldSlug().equals(source.worldSlug()) + || !identity.worldSlug().equals(capability.worldSlug()) + || !sourceIntakeReceipt.source().equals(source) + || !sourceIntakeReceipt.targetNamespace().equals(identity.targetNamespace()) + || !sourceIntakeReceipt.canonicalTenantId().equals(identity.canonicalTenantId()) + || !sourceIntakeReceipt.worldSlug().equals(identity.worldSlug()) + || worldPrivateKeys.tenantId() != sourceIntakeReceipt.localTenantKey() + || worldPrivateKeys.versionId() != versionIdentity.localVersionKey() + || versionIdentity.sourceIntakeReceipt().localTenantKey() + != sourceIntakeReceipt.localTenantKey() + || !versionIdentity.sourceIntakeReceipt().equals(sourceIntakeReceipt) + || !versionIdentity.canonicalVersionId().equals(gs.canonicalVersionId()) + || versionIdentity.versionStateEvidence().versionState() + != policy.launchReadEvidence().versionState().getVersionState() + || versionIdentity.gameDesignVersionId() + != policy.launchReadEvidence().launchDescriptor().getVersionId() + || versionIdentity.versionStateEvidence().versionStateEpoch() + != policy.launchReadEvidence().versionState().getVersionStateEpoch() + || versionIdentity.versionStateEvidence().versionStateEpoch() + != policy.launchReadEvidence().launchDescriptor().getVersionStateEpoch() + || gameTemplateId != capability.gameTemplateId() + || !identity.controlPlaneRequestId().equals(capability.operationId()) + || !"NEW_GAME_ROW".equals(sourceIntakeReceipt.source().provenanceKind())) { + throw new IllegalArgumentException( + "Run-owned fixture association differs from the exact owner allocation or World source/Version receipts"); + } + requirePositive(worldInstanceId, "worldInstanceId"); + } + } + + /** + * Immutable canonical Game Session identity and owner scope, excluding transient read metadata. + */ + public record CanonicalIdentity( + UUID canonicalGameInstanceId, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID playableStateNamespaceId, + String playableStateScope, + boolean publicProduction, + UUID canonicalRealmId, + long catalogRevision, + String controlPlaneRequestId) { + public CanonicalIdentity { + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(worldSlug, "worldSlug"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + requireNonNil(canonicalRealmId, "canonicalRealmId"); + requirePositive(catalogRevision, "catalogRevision"); + if (!"SHARED".equals(playableStateScope)) { + throw new IllegalArgumentException( + "This association slice accepts SHARED only; ISOLATED/playtest identity requires the missing lifecycle/generation carrier"); + } + if (!publicProduction) { + throw new IllegalArgumentException( + "This association slice requires explicit public-production evidence; false or absent evidence is denied"); + } + requireText(controlPlaneRequestId, "controlPlaneRequestId", 128); + } + } + + /** + * Exact caller-owned selector and expected digests for Gameplay's owner-read RPC. + * + *

The read request UUID and expected digests are transient request metadata; the repository + * validates the separate response echo and does not persist this request identity. + */ + public record GameSessionReadRequest( + UUID readRequestId, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID canonicalGameInstanceId, + String controlPlaneRequestId, + String launchDescriptorId, + String expectedDescriptorRequestDigest, + String expectedDescriptorResultDigest, + String expectedReleaseAttestationEvidenceDigest) { + public GameSessionReadRequest { + requireNonNil(readRequestId, "readRequestId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + requireText(controlPlaneRequestId, "controlPlaneRequestId", 128); + requireText(launchDescriptorId, "launchDescriptorId", 64); + requireDigest(expectedDescriptorRequestDigest, "expectedDescriptorRequestDigest"); + requireDigest(expectedDescriptorResultDigest, "expectedDescriptorResultDigest"); + requireDigest( + expectedReleaseAttestationEvidenceDigest, "expectedReleaseAttestationEvidenceDigest"); + } + } + + /** + * Typed copy of Gameplay's owner-read response, kept separate from its request selector. + * + *

The echoed fields are checked against {@link GameSessionReadRequest}. Current status and row + * version are transient Game Session projection only; neither is frozen into the association or + * treated as World lifecycle authority. + */ + public record GameSessionReadEvidence( + UUID readRequestId, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID canonicalGameInstanceId, + String controlPlaneRequestId, + String launchDescriptorId, + String descriptorRequestDigest, + String descriptorResultDigest, + String releaseAttestationEvidenceDigest, + UUID playableStateNamespaceId, + String playableStateScope, + boolean publicProduction, + UUID canonicalRealmId, + long catalogRevision, + String currentGameSessionStatus, + long currentGameSessionRowVersion, + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence releaseAttestation) { + public GameSessionReadEvidence { + requireNonNil(readRequestId, "readRequestId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + requireNonNil(canonicalRealmId, "canonicalRealmId"); + requirePositive(catalogRevision, "catalogRevision"); + requireText(controlPlaneRequestId, "controlPlaneRequestId", 128); + requireText(launchDescriptorId, "launchDescriptorId", 64); + requireDigest(descriptorRequestDigest, "descriptorRequestDigest"); + requireDigest(descriptorResultDigest, "descriptorResultDigest"); + requireDigest(releaseAttestationEvidenceDigest, "releaseAttestationEvidenceDigest"); + if (!"SHARED".equals(playableStateScope)) { + throw new IllegalArgumentException( + "This association slice accepts SHARED only; ISOLATED/playtest identity requires the missing lifecycle/generation carrier"); + } + if (!publicProduction) { + throw new IllegalArgumentException( + "This association slice requires explicit public-production evidence; false or absent evidence is denied"); + } + requireText(currentGameSessionStatus, "currentGameSessionStatus", 32); + requireNonNegative(currentGameSessionRowVersion, "currentGameSessionRowVersion"); + Objects.requireNonNull(descriptor, "descriptor"); + Objects.requireNonNull(releaseAttestation, "releaseAttestation"); + descriptor.requireValid(); + new CompleteLaunchBindingEvidence(descriptor, releaseAttestation); + if (!targetNamespace.equals(descriptor.targetNamespace()) + || !canonicalTenantId.equals(descriptor.canonicalTenantId()) + || !worldSlug.equals(descriptor.worldSlug()) + || !controlPlaneRequestId.equals(descriptor.controlPlaneRequestId()) + || !launchDescriptorId.equals(descriptor.launchDescriptorId()) + || !descriptorRequestDigest.equals(descriptor.requestDigest()) + || !descriptorResultDigest.equals(descriptor.resultDigest()) + || !releaseAttestationEvidenceDigest.equals(releaseAttestation.evidenceDigest())) { + throw new IllegalArgumentException( + "Game Session launch-association response differs from its typed complete launch evidence"); + } + } + + public CanonicalIdentity canonicalIdentity() { + return new CanonicalIdentity( + canonicalGameInstanceId, + targetNamespace, + canonicalTenantId, + worldSlug, + playableStateNamespaceId, + playableStateScope, + publicProduction, + canonicalRealmId, + catalogRevision, + controlPlaneRequestId); + } + } + + /** + * Non-authorizing persistence input. The transient Game Session read correlation/status fields + * are not association identity; the exact complete binding and source/version receipts are. + */ + public record Claim( + GameSessionReadRequest gameSessionRequest, + GameSessionReadEvidence gameSessionRead, + long worldInstanceId, + WorldCompleteLaunchBindingReceipt completeLaunchBinding, + WorldAuthoredVersionIdentityReceipt versionIdentity) { + public Claim { + Objects.requireNonNull(gameSessionRequest, "gameSessionRequest"); + Objects.requireNonNull(gameSessionRead, "gameSessionRead"); + requirePositive(worldInstanceId, "worldInstanceId"); + Objects.requireNonNull(completeLaunchBinding, "completeLaunchBinding"); + Objects.requireNonNull(versionIdentity, "versionIdentity"); + requireExactReadEcho(gameSessionRequest, gameSessionRead); + CanonicalIdentity identity = gameSessionRead.canonicalIdentity(); + requireExactLaunchEvidence(identity, completeLaunchBinding, versionIdentity); + if (!gameSessionRead.descriptor().equals(completeLaunchBinding.evidence().descriptor()) + || !gameSessionRead + .releaseAttestation() + .equals(completeLaunchBinding.evidence().releaseAttestation()) + || !gameSessionRead + .launchDescriptorId() + .equals(completeLaunchBinding.descriptor().launchDescriptorId()) + || !gameSessionRead + .descriptorRequestDigest() + .equals(completeLaunchBinding.descriptor().requestDigest()) + || !gameSessionRead + .descriptorResultDigest() + .equals(completeLaunchBinding.descriptor().resultDigest()) + || !gameSessionRead + .releaseAttestationEvidenceDigest() + .equals(completeLaunchBinding.evidence().releaseAttestation().evidenceDigest())) { + throw new IllegalArgumentException( + "Game Session read projection differs from the original World V26 complete binding"); + } + } + + public UUID canonicalGameInstanceId() { + return gameSessionRead.canonicalGameInstanceId(); + } + + public CanonicalIdentity identity() { + return gameSessionRead.canonicalIdentity(); + } + + public String targetNamespace() { + return gameSessionRead.targetNamespace(); + } + + public UUID canonicalTenantId() { + return gameSessionRead.canonicalTenantId(); + } + + public String worldSlug() { + return gameSessionRead.worldSlug(); + } + + public UUID playableStateNamespaceId() { + return gameSessionRead.playableStateNamespaceId(); + } + + public String playableStateScope() { + return gameSessionRead.playableStateScope(); + } + + public String controlPlaneRequestId() { + return gameSessionRead.controlPlaneRequestId(); + } + + public String launchDescriptorId() { + return gameSessionRead.launchDescriptorId(); + } + + public String descriptorRequestDigest() { + return gameSessionRead.descriptorRequestDigest(); + } + + public String descriptorResultDigest() { + return gameSessionRead.descriptorResultDigest(); + } + + public String releaseAttestationDigest() { + return gameSessionRead.releaseAttestationEvidenceDigest(); + } + + public UUID canonicalVersionId() { + return completeLaunchBinding.evidence().releaseAttestation().canonicalVersionId(); + } + + public long localTenantKey() { + return completeLaunchBinding.sourceIntakeReceipt().localTenantKey(); + } + + public long localVersionKey() { + return versionIdentity.localVersionKey(); + } + + public UUID launchBindingOperationId() { + return completeLaunchBinding.operationId(); + } + + public UUID versionIdentityOperationId() { + return versionIdentity.operationId(); + } + } + + /** Exact immutable subset of the legacy row created by World's existing prepare owner. */ + public record WorldPrepareFields( + long worldInstanceId, + long privateTenantKey, + long privateGameInstanceKey, + long gameTemplateId, + String controlPlaneRequestId, + String launchDescriptorId, + long localVersionKey, + String scriptPatchVersion, + String runtimeFlagsJson, + String generationConfigRevision, + long releaseBundleId, + String publishedReleaseBundleRef, + long versionStateEpoch, + String remapSetId) { + public WorldPrepareFields { + requirePositive(worldInstanceId, "worldInstanceId"); + requirePositive(privateTenantKey, "privateTenantKey"); + requirePositive(privateGameInstanceKey, "privateGameInstanceKey"); + requirePositive(gameTemplateId, "gameTemplateId"); + requireText(controlPlaneRequestId, "controlPlaneRequestId", 128); + requireText(launchDescriptorId, "launchDescriptorId", 64); + requirePositive(localVersionKey, "localVersionKey"); + requireText(runtimeFlagsJson, "runtimeFlagsJson", Integer.MAX_VALUE); + requireText(generationConfigRevision, "generationConfigRevision", 128); + requirePositive(releaseBundleId, "releaseBundleId"); + requireText(publishedReleaseBundleRef, "publishedReleaseBundleRef", 128); + requirePositive(versionStateEpoch, "versionStateEpoch"); + requireOptionalText(scriptPatchVersion, "scriptPatchVersion", 100); + requireOptionalText(remapSetId, "remapSetId", 64); + } + + /** + * Compares immutable prepare and release inputs only; lifecycle state, epoch, termination, and + * timestamps are intentionally not part of this association. + */ + public void requireMatches( + CanonicalIdentity identity, + WorldCompleteLaunchBindingReceipt completeLaunchBinding, + WorldAuthoredVersionIdentityReceipt versionIdentity) { + Objects.requireNonNull(identity, "identity"); + Objects.requireNonNull(completeLaunchBinding, "completeLaunchBinding"); + Objects.requireNonNull(versionIdentity, "versionIdentity"); + var descriptor = completeLaunchBinding.descriptor(); + String expectedScriptPatch = + descriptor.scriptPatchVersionPresent() ? descriptor.scriptPatchVersion() : null; + String expectedRemapSet = descriptor.remapSetIdPresent() ? descriptor.remapSetId() : null; + if (privateTenantKey != completeLaunchBinding.sourceIntakeReceipt().localTenantKey() + || gameTemplateId != descriptor.gameTemplateId() + || !controlPlaneRequestId.equals(identity.controlPlaneRequestId()) + || !controlPlaneRequestId.equals(descriptor.controlPlaneRequestId()) + || !launchDescriptorId.equals(descriptor.launchDescriptorId()) + || localVersionKey != versionIdentity.localVersionKey() + || !Objects.equals(scriptPatchVersion, expectedScriptPatch) + || !runtimeFlagsJson.equals(descriptor.runtimeFlagsJson()) + || !generationConfigRevision.equals(descriptor.generationConfigRevision()) + || releaseBundleId != descriptor.releaseBundleId() + || !publishedReleaseBundleRef.equals(descriptor.publishedReleaseBundleRef()) + || versionStateEpoch != descriptor.versionStateEpoch() + || !Objects.equals(remapSetId, expectedRemapSet)) { + throw new IllegalArgumentException( + "World instance row differs from the exact canonical launch prepare inputs"); + } + } + } + + private static void requireExactLaunchEvidence( + CanonicalIdentity identity, + WorldCompleteLaunchBindingReceipt binding, + WorldAuthoredVersionIdentityReceipt versionIdentity) { + var descriptor = binding.evidence().descriptor(); + var release = binding.evidence().releaseAttestation(); + var source = binding.sourceIntakeReceipt(); + if (!identity.targetNamespace().equals(binding.targetNamespace()) + || !identity.canonicalTenantId().equals(binding.canonicalTenantId()) + || !identity.worldSlug().equals(binding.worldSlug()) + || !identity.controlPlaneRequestId().equals(binding.controlPlaneRequestId()) + || !identity.targetNamespace().equals(descriptor.targetNamespace()) + || !identity.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !identity.worldSlug().equals(descriptor.worldSlug()) + || !identity.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId()) + || !identity.targetNamespace().equals(release.targetNamespace()) + || !identity.canonicalTenantId().equals(release.canonicalTenantId()) + || !identity.worldSlug().equals(release.worldSlug()) + || !descriptor.authoredWorldSourceOperationId().equals(source.sourceOperationId()) + || !descriptor.authoredWorldSourceEvidenceDigest().equals(source.sourceEvidenceDigest()) + || !source.equals(versionIdentity.sourceIntakeReceipt()) + || !identity.targetNamespace().equals(versionIdentity.targetNamespace()) + || !identity.canonicalTenantId().equals(versionIdentity.canonicalTenantId()) + || !identity.worldSlug().equals(versionIdentity.worldSlug()) + || !release.canonicalVersionId().equals(versionIdentity.canonicalVersionId()) + || descriptor.versionId() != versionIdentity.gameDesignVersionId() + || versionIdentity.sourceIntakeReceipt().localTenantKey() != source.localTenantKey()) { + throw new IllegalArgumentException( + "Canonical instance claim differs from its exact World launch/source/version evidence"); + } + } + + private static void requireExactReadEcho( + GameSessionReadRequest request, GameSessionReadEvidence response) { + if (!request.readRequestId().equals(response.readRequestId()) + || !request.targetNamespace().equals(response.targetNamespace()) + || !request.canonicalTenantId().equals(response.canonicalTenantId()) + || !request.worldSlug().equals(response.worldSlug()) + || !request.canonicalGameInstanceId().equals(response.canonicalGameInstanceId()) + || !request.controlPlaneRequestId().equals(response.controlPlaneRequestId()) + || !request.launchDescriptorId().equals(response.launchDescriptorId()) + || !request.expectedDescriptorRequestDigest().equals(response.descriptorRequestDigest()) + || !request.expectedDescriptorResultDigest().equals(response.descriptorResultDigest()) + || !request + .expectedReleaseAttestationEvidenceDigest() + .equals(response.releaseAttestationEvidenceDigest())) { + throw new IllegalArgumentException( + "Game Session launch-association response does not echo the exact read request tuple and expected digests"); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static void requirePositive(long value, String label) { + if (value <= 0L) { + throw new IllegalArgumentException(label + " must be positive"); + } + } + + private static void requireNonNegative(long value, String label) { + if (value < 0L) { + throw new IllegalArgumentException(label + " must not be negative"); + } + } + + private static void requireText(String value, String label, int maxLength) { + if (value == null || value.isBlank() || value.length() > maxLength) { + throw new IllegalArgumentException(label + " must be nonblank and within its storage bound"); + } + } + + private static void requireDigest(String value, String label) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be a lowercase SHA-256 digest"); + } + } + + private static void requireOptionalText(String value, String label, int maxLength) { + if (value != null && (value.isBlank() || value.length() > maxLength)) { + throw new IllegalArgumentException( + label + " must be absent or nonblank within its storage bound"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java new file mode 100644 index 0000000000..0daf9e996c --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java @@ -0,0 +1,1990 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.sql.Connection; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadGrpcCodec; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.v1.GetRunOwnedFixtureLaunchAssociationResponse; +import net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidence; +import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * World-local storage and exact readback for a claimed canonical instance association. + * + *

This component has no public transport and does not authenticate Game Session. A positive + * owner readback only returns retained correlation; JOIN, ACTIVE, and admission remain unavailable + * until an authenticated same-namespace producer and complete prepare/materialization proof are + * integrated by the lifecycle owner. + */ +public final class WorldCanonicalInstanceAssociationRepository { + private static final Table ASSOCIATION = + DSL.table(DSL.name("world_canonical_instance_association")); + private static final Table WORLD_INSTANCE = DSL.table(DSL.name("world_instance")); + private static final Table COMPLETE_BINDING = + DSL.table(DSL.name("world_complete_launch_binding")); + private static final Table SOURCE_INTAKE = DSL.table(DSL.name("world_authored_source_intake")); + private static final Table VERSION_IDENTITY = + DSL.table(DSL.name("world_authored_version_identity")); + private static final JsonMapper CLOSED_JSON = + JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + + private static final Field SCHEMA_VERSION = field("schema_version", Short.class); + private static final Field CANONICAL_GAME_INSTANCE_ID = + field("canonical_game_instance_id", UUID.class); + private static final Field CANONICAL_TARGET_NAMESPACE = + field("canonical_target_namespace", String.class); + private static final Field CANONICAL_TENANT_ID = field("canonical_tenant_id", UUID.class); + private static final Field CANONICAL_WORLD_SLUG = + field("canonical_world_slug", String.class); + private static final Field PLAYABLE_STATE_NAMESPACE_ID = + field("playable_state_namespace_id", UUID.class); + private static final Field PLAYABLE_STATE_SCOPE = + field("playable_state_scope", String.class); + private static final Field PUBLIC_PRODUCTION = field("public_production", Boolean.class); + private static final Field CANONICAL_REALM_ID = field("canonical_realm_id", UUID.class); + private static final Field CATALOG_REVISION = field("catalog_revision", Long.class); + private static final Field PLAYTEST_LIFECYCLE_ID = + field("playtest_lifecycle_id", UUID.class); + private static final Field PLAYTEST_STATE_GENERATION = + field("playtest_state_generation", Long.class); + private static final Field CONTROL_PLANE_REQUEST_ID = + field("control_plane_request_id", String.class); + private static final Field WORLD_INSTANCE_ID = field("world_instance_id", Long.class); + private static final Field LAUNCH_BINDING_OPERATION_ID = + field("canonical_launch_binding_operation_id", UUID.class); + private static final Field VERSION_IDENTITY_OPERATION_ID = + field("version_identity_operation_id", UUID.class); + private static final Field CANONICAL_VERSION_ID = field("canonical_version_id", UUID.class); + private static final Field LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field PRIVATE_GAME_INSTANCE_KEY = + field("private_game_instance_key", Long.class); + private static final Field GAME_TEMPLATE_ID = field("game_template_id", Long.class); + private static final Field LAUNCH_DESCRIPTOR_ID = + field("launch_descriptor_id", String.class); + private static final Field LOCAL_VERSION_KEY = field("local_version_key", Long.class); + private static final Field SCRIPT_PATCH_VERSION = + field("script_patch_version", String.class); + private static final Field RUNTIME_FLAGS_JSON = field("runtime_flags_json", String.class); + private static final Field GENERATION_CONFIG_REVISION = + field("generation_config_revision", String.class); + private static final Field RELEASE_BUNDLE_ID = field("release_bundle_id", Long.class); + private static final Field PUBLISHED_RELEASE_BUNDLE_REF = + field("published_release_bundle_ref", String.class); + private static final Field VERSION_STATE_EPOCH = field("version_state_epoch", Long.class); + private static final Field REMAP_SET_ID = field("remap_set_id", String.class); + private static final Field INTAKE_OPERATION_ID = field("intake_operation_id", UUID.class); + private static final Field INTAKE_REQUEST_ID = field("intake_request_id", UUID.class); + private static final Field SOURCE_OPERATION_ID = field("source_operation_id", UUID.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + field("source_evidence_digest", String.class); + private static final Field INTAKE_REQUEST_DIGEST = + field("intake_request_digest", String.class); + private static final Field INTAKE_RECEIPT_DIGEST = + field("intake_receipt_digest", String.class); + private static final Field DESCRIPTOR_REQUEST_DIGEST = + field("descriptor_request_digest", String.class); + private static final Field DESCRIPTOR_RESULT_DIGEST = + field("descriptor_result_digest", String.class); + private static final Field RELEASE_ATTESTATION_DIGEST = + field("release_attestation_digest", String.class); + private static final Field CANONICAL_AUTHORITY_KIND = + field("canonical_authority_kind", String.class); + private static final Field FIXTURE_PROVENANCE_DIGEST = + field("fixture_provenance_digest", String.class); + private static final Field GAME_SESSION_TENANT_ID = + field("game_session_tenant_id", Long.class); + private static final Field GAME_SESSION_GAME_INSTANCE_ID = + field("game_session_game_instance_id", Long.class); + private static final Field GAME_DESIGN_VERSION_ID = + field("game_design_version_id", Long.class); + private static final Field PREPARATION_INPUT_DIGEST = + field("preparation_input_digest", String.class); + private static final Field PREPARING_LIFECYCLE_EPOCH = + field("preparing_lifecycle_epoch", Long.class); + private static final Field GAME_SESSION_ASSOCIATION_RESPONSE_BYTES = + field("game_session_association_response_bytes", byte[].class); + + private static final Field INSTANCE_ID = field("id", Long.class); + private static final Field INSTANCE_TENANT_ID = field("tenant_id", Long.class); + private static final Field INSTANCE_GAME_INSTANCE_ID = + field("game_instance_id", Long.class); + private static final Field INSTANCE_GAME_TEMPLATE_ID = + field("game_template_id", Long.class); + private static final Field INSTANCE_CONTROL_PLANE_REQUEST_ID = + field("control_plane_request_id", String.class); + private static final Field INSTANCE_LIFECYCLE_EPOCH = field("lifecycle_epoch", Long.class); + private static final Field INSTANCE_STATUS = field("status", String.class); + private static final Field INSTANCE_LAUNCH_DESCRIPTOR_ID = + field("launch_descriptor_id", String.class); + private static final Field INSTANCE_VERSION_ID = field("version_id", Long.class); + private static final Field INSTANCE_SCRIPT_PATCH_VERSION = + field("script_patch_version", String.class); + private static final Field INSTANCE_RUNTIME_FLAGS_JSON = + field("runtime_flags_json", String.class); + private static final Field INSTANCE_GENERATION_CONFIG_REVISION = + field("generation_config_revision", String.class); + private static final Field INSTANCE_RELEASE_BUNDLE_ID = + field("release_bundle_id", Long.class); + private static final Field INSTANCE_PUBLISHED_RELEASE_BUNDLE_REF = + field("published_release_bundle_ref", String.class); + private static final Field INSTANCE_VERSION_STATE_EPOCH = + field("version_state_epoch", Long.class); + private static final Field INSTANCE_REMAP_SET_ID = field("remap_set_id", String.class); + private static final Field INSTANCE_CANONICAL_GAME_INSTANCE_ID = + field("canonical_game_instance_id", UUID.class); + private static final Field INSTANCE_CANONICAL_TARGET_NAMESPACE = + field("canonical_target_namespace", String.class); + private static final Field INSTANCE_CANONICAL_TENANT_ID = + field("canonical_tenant_id", UUID.class); + private static final Field INSTANCE_CANONICAL_WORLD_SLUG = + field("canonical_world_slug", String.class); + private static final Field INSTANCE_PLAYABLE_STATE_NAMESPACE_ID = + field("playable_state_namespace_id", UUID.class); + private static final Field INSTANCE_PLAYABLE_STATE_SCOPE = + field("playable_state_scope", String.class); + private static final Field INSTANCE_PUBLIC_PRODUCTION = + field("public_production", Boolean.class); + private static final Field INSTANCE_CANONICAL_REALM_ID = + field("canonical_realm_id", UUID.class); + private static final Field INSTANCE_CATALOG_REVISION = + field("catalog_revision", Long.class); + private static final Field INSTANCE_PLAYTEST_LIFECYCLE_ID = + field("playtest_lifecycle_id", UUID.class); + private static final Field INSTANCE_PLAYTEST_STATE_GENERATION = + field("playtest_state_generation", Long.class); + private static final Field INSTANCE_LAUNCH_BINDING_OPERATION_ID = + field("canonical_launch_binding_operation_id", UUID.class); + private static final Field INSTANCE_CANONICAL_AUTHORITY_KIND = + field("canonical_authority_kind", String.class); + private static final Field INSTANCE_FIXTURE_PROVENANCE_DIGEST = + field("fixture_provenance_digest", String.class); + private static final Field INSTANCE_GAME_SESSION_TENANT_ID = + field("game_session_tenant_id", Long.class); + private static final Field INSTANCE_GAME_SESSION_GAME_INSTANCE_ID = + field("game_session_game_instance_id", Long.class); + private static final Field INSTANCE_GAME_DESIGN_VERSION_ID = + field("game_design_version_id", Long.class); + private static final Field INSTANCE_FIXTURE_BINDING_SHA256 = + field("run_owned_fixture_binding_sha256", String.class); + private static final Field INSTANCE_FIXTURE_PREPARING_EPOCH = + field("run_owned_fixture_preparing_lifecycle_epoch", Long.class); + + private static final Field BINDING_OPERATION_ID = + DSL.field(DSL.name("binding_operation_id"), UUID.class); + private static final Field BINDING_CANONICAL_TENANT_ID = + field("canonical_tenant_id", UUID.class); + private static final Field BINDING_CANONICAL_VERSION_ID = + field("canonical_version_id", UUID.class); + private static final Field BINDING_TARGET_NAMESPACE = + field("target_namespace", String.class); + private static final Field BINDING_WORLD_SLUG = field("world_slug", String.class); + private static final Field BINDING_CONTROL_PLANE_REQUEST_ID = + field("control_plane_request_id", String.class); + private static final Field BINDING_INTAKE_OPERATION_ID = + field("intake_operation_id", UUID.class); + private static final Field BINDING_INTAKE_REQUEST_ID = + field("intake_request_id", UUID.class); + private static final Field BINDING_LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field BINDING_SOURCE_OPERATION_ID = + field("source_operation_id", UUID.class); + private static final Field BINDING_SOURCE_EVIDENCE_DIGEST = + field("source_evidence_digest", String.class); + private static final Field BINDING_INTAKE_RECEIPT_DIGEST = + field("intake_receipt_digest", String.class); + private static final Field BINDING_DESCRIPTOR_REQUEST_DIGEST = + field("descriptor_request_digest", String.class); + private static final Field BINDING_DESCRIPTOR_RESULT_DIGEST = + field("descriptor_result_digest", String.class); + private static final Field BINDING_RELEASE_ATTESTATION_DIGEST = + field("release_attestation_digest", String.class); + private static final Field BINDING_DESCRIPTOR_JSON = + field("descriptor_json", String.class); + private static final Field BINDING_RELEASE_ATTESTATION_JSON = + field("release_attestation_json", String.class); + + private static final Field SOURCE_OPERATION_ID_KEY = + DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field SOURCE_SCHEMA_VERSION = field("schema_version", Short.class); + private static final Field SOURCE_TARGET_NAMESPACE = + field("target_namespace", String.class); + private static final Field SOURCE_INTAKE_REQUEST_ID = + field("intake_request_id", UUID.class); + private static final Field SOURCE_REQUEST_DIGEST = field("request_digest", String.class); + private static final Field SOURCE_LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field SOURCE_EVIDENCE_SCHEMA_VERSION = + field("source_schema_version", Short.class); + private static final Field SOURCE_REGISTRATION_REQUEST_ID = + field("source_registration_request_id", UUID.class); + private static final Field SOURCE_SOURCE_OPERATION_ID = + field("source_operation_id", UUID.class); + private static final Field SOURCE_SOURCE_REQUEST_DIGEST = + field("source_request_digest", String.class); + private static final Field SOURCE_CANONICAL_TENANT_ID = + field("canonical_tenant_id", UUID.class); + private static final Field SOURCE_TENANT_SLUG = field("tenant_slug", String.class); + private static final Field SOURCE_WORLD_SLUG = field("world_slug", String.class); + private static final Field SOURCE_WORLD_DISPLAY_NAME = + field("world_display_name", String.class); + private static final Field SOURCE_GAME_ROW_ID = field("source_game_row_id", Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + field("source_game_tenant_key", String.class); + private static final Field SOURCE_PROVENANCE_KIND = + field("source_provenance_kind", String.class); + private static final Field SOURCE_SOURCE_EVIDENCE_DIGEST = + field("source_evidence_digest", String.class); + private static final Field SOURCE_RECEIPT_DIGEST = field("receipt_digest", String.class); + + private static final Field VERSION_OPERATION_ID = + DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field VERSION_TARGET_NAMESPACE = + field("target_namespace", String.class); + private static final Field VERSION_CANONICAL_TENANT_ID = + field("canonical_tenant_id", UUID.class); + private static final Field VERSION_WORLD_SLUG = field("world_slug", String.class); + private static final Field VERSION_CANONICAL_VERSION_ID = + field("canonical_version_id", UUID.class); + private static final Field VERSION_GAME_DESIGN_VERSION_ID = + field("game_design_version_id", Long.class); + private static final Field VERSION_LOCAL_VERSION_KEY = + field("local_version_key", Long.class); + private static final Field VERSION_INTAKE_OPERATION_ID = + field("intake_operation_id", UUID.class); + private static final Field VERSION_INTAKE_REQUEST_ID = + field("intake_request_id", UUID.class); + private static final Field VERSION_LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field VERSION_INTAKE_REQUEST_DIGEST = + field("intake_request_digest", String.class); + private static final Field VERSION_SOURCE_OPERATION_ID = + field("source_operation_id", UUID.class); + private static final Field VERSION_SOURCE_EVIDENCE_DIGEST = + field("source_evidence_digest", String.class); + private static final Field VERSION_INTAKE_RECEIPT_DIGEST = + field("intake_receipt_digest", String.class); + private static final Field VERSION_STATE_SCHEMA_VERSION = + field("version_state_schema_version", Short.class); + private static final Field VERSION_STATE_READ_REQUEST_ID = + field("version_state_read_request_id", UUID.class); + private static final Field VERSION_STATE_STATE = + field("version_state_state", String.class); + private static final Field VERSION_STATE_EVIDENCE_EPOCH = + field("version_state_epoch", Long.class); + private static final Field VERSION_STATE_EVIDENCE_DIGEST = + field("version_state_evidence_digest", String.class); + private static final Field VERSION_STATE_EVIDENCE_JSON = + field("version_state_evidence_json", String.class); + + private final DSLContext dsl; + private final WorldCompleteLaunchBindingRepository launchBindingRepository; + private final WorldAuthoredSourceIntakeRepository sourceIntakeRepository; + private final WorldAuthoredVersionIdentityRepository versionIdentityRepository; + + public WorldCanonicalInstanceAssociationRepository( + DSLContext dsl, + WorldCompleteLaunchBindingRepository launchBindingRepository, + WorldAuthoredSourceIntakeRepository sourceIntakeRepository, + WorldAuthoredVersionIdentityRepository versionIdentityRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + this.launchBindingRepository = + Objects.requireNonNull(launchBindingRepository, "launchBindingRepository"); + this.sourceIntakeRepository = + Objects.requireNonNull(sourceIntakeRepository, "sourceIntakeRepository"); + this.versionIdentityRepository = + Objects.requireNonNull(versionIdentityRepository, "versionIdentityRepository"); + } + + /** + * Retains an exact non-authorizing claim in the caller's short writable READ COMMITTED World + * transaction, after the same transaction created or selected its exact canonical World row. + * + *

This method does not commit the caller's transaction. The caller must commit, then use + * {@link #readOwnerAssociation(UUID)} as a separate committed read before reporting storage + * success. An exact retry compares the immutable V26 descriptor/release bytes and V23/V27 source + * and Version provenance already supplied in {@code claim}; it never re-resolves Game Design. + */ + public void retainClaimInOwnerTransaction(WorldCanonicalInstanceAssociation.Claim claim) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(claim, "claim"); + + Record worldRow = lockWorldInstance(claim.worldInstanceId()); + WorldCanonicalInstanceAssociation.WorldPrepareFields prepareFields = + toWorldPrepareFields(worldRow); + requireInsertBornIdentity(worldRow, claim); + prepareFields.requireMatches( + claim.identity(), claim.completeLaunchBinding(), claim.versionIdentity()); + requireExactImmutableOwnerEvidence(claim); + + Record existing = findConflict(claim); + if (existing != null) { + requireSameStoredClaim(existing, claim, prepareFields); + return; + } + + int inserted = + dsl.insertInto(ASSOCIATION) + .set(SCHEMA_VERSION, (short) 2) + .set(CANONICAL_GAME_INSTANCE_ID, claim.canonicalGameInstanceId()) + .set(CANONICAL_TARGET_NAMESPACE, claim.targetNamespace()) + .set(CANONICAL_TENANT_ID, claim.canonicalTenantId()) + .set(CANONICAL_WORLD_SLUG, claim.worldSlug()) + .set(PLAYABLE_STATE_NAMESPACE_ID, claim.playableStateNamespaceId()) + .set(PLAYABLE_STATE_SCOPE, claim.playableStateScope()) + .set(PUBLIC_PRODUCTION, claim.identity().publicProduction()) + .set(CANONICAL_REALM_ID, claim.identity().canonicalRealmId()) + .set(CATALOG_REVISION, claim.identity().catalogRevision()) + .set(PLAYTEST_LIFECYCLE_ID, (UUID) null) + .set(PLAYTEST_STATE_GENERATION, (Long) null) + .set(CONTROL_PLANE_REQUEST_ID, claim.controlPlaneRequestId()) + .set(WORLD_INSTANCE_ID, prepareFields.worldInstanceId()) + .set(LAUNCH_BINDING_OPERATION_ID, claim.launchBindingOperationId()) + .set(VERSION_IDENTITY_OPERATION_ID, claim.versionIdentityOperationId()) + .set(CANONICAL_VERSION_ID, claim.canonicalVersionId()) + .set(LOCAL_TENANT_KEY, prepareFields.privateTenantKey()) + .set(PRIVATE_GAME_INSTANCE_KEY, prepareFields.privateGameInstanceKey()) + .set(GAME_TEMPLATE_ID, prepareFields.gameTemplateId()) + .set(LAUNCH_DESCRIPTOR_ID, prepareFields.launchDescriptorId()) + .set(LOCAL_VERSION_KEY, prepareFields.localVersionKey()) + .set(SCRIPT_PATCH_VERSION, prepareFields.scriptPatchVersion()) + .set(RUNTIME_FLAGS_JSON, prepareFields.runtimeFlagsJson()) + .set(GENERATION_CONFIG_REVISION, prepareFields.generationConfigRevision()) + .set(RELEASE_BUNDLE_ID, prepareFields.releaseBundleId()) + .set(PUBLISHED_RELEASE_BUNDLE_REF, prepareFields.publishedReleaseBundleRef()) + .set(VERSION_STATE_EPOCH, prepareFields.versionStateEpoch()) + .set(REMAP_SET_ID, prepareFields.remapSetId()) + .set( + INTAKE_OPERATION_ID, + claim.completeLaunchBinding().sourceIntakeReceipt().operationId()) + .set( + INTAKE_REQUEST_ID, + claim.completeLaunchBinding().sourceIntakeReceipt().intakeRequestId()) + .set( + SOURCE_OPERATION_ID, + claim.completeLaunchBinding().sourceIntakeReceipt().sourceOperationId()) + .set( + SOURCE_EVIDENCE_DIGEST, + claim.completeLaunchBinding().sourceIntakeReceipt().sourceEvidenceDigest()) + .set( + INTAKE_REQUEST_DIGEST, + claim.completeLaunchBinding().sourceIntakeReceipt().requestDigest()) + .set( + INTAKE_RECEIPT_DIGEST, + claim.completeLaunchBinding().sourceIntakeReceipt().receiptDigest()) + .set( + DESCRIPTOR_REQUEST_DIGEST, + claim.completeLaunchBinding().descriptor().requestDigest()) + .set( + DESCRIPTOR_RESULT_DIGEST, claim.completeLaunchBinding().descriptor().resultDigest()) + .set( + RELEASE_ATTESTATION_DIGEST, + claim.completeLaunchBinding().evidence().releaseAttestation().evidenceDigest()) + .onConflictDoNothing() + .execute(); + + Record stored = findConflict(claim); + if (stored == null) { + throw new InvalidAssociationEvidenceException( + "World canonical instance association is missing after its owner claim"); + } + requireSameStoredClaim(stored, claim, prepareFields); + if (inserted == 0) { + // The complete exact compare above is the only idempotent conflict outcome. + return; + } + } + + /** + * Serializes the existing fixture operation and canonical instance before any publication-owner + * or source/Version row lock. Reacquiring these transaction-scoped locks during allocation is + * safe. + */ + public void lockRunOwnedFixtureInOwnerTransaction( + RunOwnedCanonicalWorldLaunchEvidence fixtureEvidence, + PreparedWorldInstanceRequest gameSessionRequest) { + Objects.requireNonNull(fixtureEvidence, "fixtureEvidence").requireFixedGameSessionPeer(); + requireWritableReadCommittedOwnerTransaction(); + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Run-owned World fixture locking requires a physical writable READ COMMITTED owner transaction"); + } + }); + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + if (!"read committed".equals(state.get("isolation", String.class)) + || !"off".equals(state.get("read_only", String.class))) { + throw new IllegalStateException( + "Run-owned World fixture locking requires a physical writable READ COMMITTED owner transaction"); + } + Objects.requireNonNull(fixtureEvidence, "fixtureEvidence"); + Objects.requireNonNull(gameSessionRequest, "gameSessionRequest"); + fixtureEvidence.requireMatches(gameSessionRequest); + var gs = fixtureEvidence.gameSessionAssociation(); + if (gs == null) { + throw new InvalidAssociationEvidenceException( + "Run-owned fixture locking requires the exact verified Game Session association"); + } + String lockIdentity = + gs.request().targetNamespace() + + ":" + + gs.canonicalTenantId() + + ":" + + fixtureEvidence.capability().operationId(); + dsl.fetchOne("SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", lockIdentity); + dsl.fetchOne( + "SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", + "canonical-game-instance:" + gs.gameInstanceUuid()); + } + + /** + * Allocates and retains one fresh World-local run-owned fixture row and its canonical association + * in the caller's writable READ COMMITTED owner transaction. This is the fixture arm of the + * existing association owner; it does not adopt a prior numeric row or reuse Game Session or Game + * Design private keys as World keys. + */ + public WorldCanonicalInstanceAssociation allocateRunOwnedFixtureInOwnerTransaction( + RunOwnedCanonicalWorldLaunchEvidence fixtureEvidence, + PreparedWorldInstanceRequest gameSessionRequest, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + WorldAuthoredVersionIdentityReceipt versionIdentity) { + Objects.requireNonNull(fixtureEvidence, "fixtureEvidence").requireFixedGameSessionPeer(); + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(fixtureEvidence, "fixtureEvidence"); + Objects.requireNonNull(gameSessionRequest, "gameSessionRequest"); + Objects.requireNonNull(sourceReceipt, "sourceReceipt"); + Objects.requireNonNull(versionIdentity, "versionIdentity"); + lockRunOwnedFixtureInOwnerTransaction(fixtureEvidence, gameSessionRequest); + + var gs = fixtureEvidence.gameSessionAssociation(); + if (gs == null + || !sourceReceipt.equals(versionIdentity.sourceIntakeReceipt()) + || !sourceReceipt.source().equals(fixtureEvidence.sourceReceipt().sourceEvidence()) + || !sourceReceipt.targetNamespace().equals(gs.request().targetNamespace()) + || !fixtureEvidence + .fixtureProvenanceDigest() + .equals(gs.fixturePolicySeal().evidenceDigest()) + || !fixtureEvidence + .capability() + .operationId() + .equals(gameSessionRequest.controlPlaneRequestId()) + || !sourceReceipt.canonicalTenantId().equals(versionIdentity.canonicalTenantId()) + || !sourceReceipt.worldSlug().equals(versionIdentity.worldSlug()) + || !fixtureEvidence + .launchDescriptor() + .canonicalTenantId() + .equals(sourceReceipt.canonicalTenantId()) + || !fixtureEvidence.launchDescriptor().worldSlug().equals(sourceReceipt.worldSlug()) + || fixtureEvidence.launchDescriptor().versionId() != versionIdentity.gameDesignVersionId() + || !versionIdentity.canonicalVersionId().equals(gs.canonicalVersionId()) + || !"NEW_GAME_ROW".equals(sourceReceipt.source().provenanceKind())) { + throw new InvalidAssociationEvidenceException( + "Run-owned fixture allocation differs from the exact Game Session, World source, or Version owner readbacks"); + } + + lockFixtureSourceAndVersionOwners(sourceReceipt, versionIdentity); + + WorldAuthoredSourceIntakeReceipt storedSource = + sourceIntakeRepository + .readInOwnerActivationTransaction( + sourceReceipt.targetNamespace(), sourceReceipt.intakeRequestId()) + .orElseThrow( + () -> + new InvalidAssociationEvidenceException( + "Run-owned fixture lost its retained World source intake")); + WorldAuthoredVersionIdentityReceipt storedVersion = + versionIdentityRepository + .readByCanonicalVersionInOwnerActivationTransaction( + versionIdentity.targetNamespace(), + versionIdentity.canonicalTenantId(), + versionIdentity.worldSlug(), + versionIdentity.canonicalVersionId()) + .orElseThrow( + () -> + new InvalidAssociationEvidenceException( + "Run-owned fixture lost its retained World Version identity")); + if (!storedSource.equals(sourceReceipt) || !storedVersion.equals(versionIdentity)) { + throw new InvalidAssociationEvidenceException( + "Run-owned fixture World source or Version receipt changed before allocation"); + } + + String fixtureOperationId = fixtureEvidence.capability().operationId(); + + Record existing = + findFixtureConflict( + gs.gameInstanceUuid(), + gs.request().targetNamespace(), + gs.canonicalTenantId(), + fixtureOperationId, + sourceReceipt.localTenantKey()); + if (existing != null) { + if (required(existing, SCHEMA_VERSION) != 3) { + throw new RegistrationConflictException( + "Run-owned fixture cannot adopt a historical or Human canonical association"); + } + WorldCanonicalInstanceAssociation stored = toAssociation(existing, false, true); + requireSameRunOwnedFixture( + stored, fixtureEvidence, gameSessionRequest, sourceReceipt, versionIdentity); + return stored; + } + + Record preexistingWorldRow = + dsl.selectFrom(WORLD_INSTANCE) + .where( + INSTANCE_CANONICAL_GAME_INSTANCE_ID + .eq(gs.gameInstanceUuid()) + .or( + INSTANCE_TENANT_ID + .eq(sourceReceipt.localTenantKey()) + .and(INSTANCE_CONTROL_PLANE_REQUEST_ID.eq(fixtureOperationId)))) + .fetchOne(); + if (preexistingWorldRow != null) { + throw new RegistrationConflictException( + "Run-owned fixture cannot adopt an existing World instance row without its exact fixture association"); + } + + long instanceId = nextPositiveSequenceValue("world_instance_id_seq"); + long privateGameInstanceKey = + nextPositiveSequenceValue("world_canonical_private_game_instance_key_seq"); + var capability = fixtureEvidence.capability(); + var descriptor = fixtureEvidence.launchDescriptor(); + var source = sourceReceipt.source(); + String fixtureBindingSha256 = fixtureEvidence.bindingDigest(gameSessionRequest, 1L); + String preparationInputDigest = "sha256:" + fixtureBindingSha256; + byte[] associationResponseBytes = + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toFixtureResponse(gs).toByteArray(); + String runtimeFlagsJson = descriptor.runtimeFlagsJson(); + + WorldCanonicalInstanceAssociation.CanonicalIdentity identity = + new WorldCanonicalInstanceAssociation.CanonicalIdentity( + gs.gameInstanceUuid(), + gs.request().targetNamespace(), + gs.canonicalTenantId(), + source.worldSlug(), + gs.playableStateNamespaceId(), + capability.stateScope(), + capability.publicProductionRealm(), + gs.canonicalRealmId(), + gs.catalogRevision(), + fixtureOperationId); + WorldCanonicalInstanceAssociation.WorldPrivateKeys worldPrivateKeys = + new WorldCanonicalInstanceAssociation.WorldPrivateKeys( + sourceReceipt.localTenantKey(), + privateGameInstanceKey, + versionIdentity.localVersionKey()); + + Map worldRow = + runOwnedFixtureWorldInstanceRow( + instanceId, + worldPrivateKeys, + fixtureEvidence, + identity, + fixtureBindingSha256, + runtimeFlagsJson); + Map associationRow = + runOwnedFixtureAssociationRow( + identity, + instanceId, + worldPrivateKeys, + fixtureEvidence, + sourceReceipt, + versionIdentity, + preparationInputDigest, + associationResponseBytes, + runtimeFlagsJson); + + dsl.fetchOne( + "SELECT world_allocate_run_owned_fixture_instance(?::jsonb, ?::jsonb)", + writeJson(worldRow), + writeJson(associationRow)); + Record storedWorld = lockWorldInstance(instanceId); + requireInsertBornFixtureIdentity( + storedWorld, + instanceId, + identity, + worldPrivateKeys, + gameSessionRequest, + fixtureEvidence, + fixtureBindingSha256); + Record storedAssociation = findByCanonicalGameInstance(identity.canonicalGameInstanceId()); + if (storedAssociation == null || required(storedAssociation, SCHEMA_VERSION) != 3) { + throw new InvalidAssociationEvidenceException( + "Run-owned fixture canonical association is missing after atomic allocation"); + } + requireSameRunOwnedFixture( + toAssociation(storedAssociation, false, true), + fixtureEvidence, + gameSessionRequest, + sourceReceipt, + versionIdentity); + + WorldCanonicalInstanceAssociation.RunOwnedFixture runOwnedFixture = + new WorldCanonicalInstanceAssociation.RunOwnedFixture( + worldPrivateKeys, + gs.gameSessionTenantId(), + gs.gameInstanceId(), + descriptor.gameTemplateId(), + UUID.fromString(fixtureOperationId), + fixtureEvidence.fixtureProvenanceDigest(), + preparationInputDigest, + 1L, + associationResponseBytes, + gs, + sourceReceipt); + return new WorldCanonicalInstanceAssociation( + identity, instanceId, null, versionIdentity, null, runOwnedFixture); + } + + private Map runOwnedFixtureWorldInstanceRow( + long worldInstanceId, + WorldCanonicalInstanceAssociation.WorldPrivateKeys worldPrivateKeys, + RunOwnedCanonicalWorldLaunchEvidence evidence, + WorldCanonicalInstanceAssociation.CanonicalIdentity identity, + String fixtureBindingSha256, + String runtimeFlagsJson) { + var descriptor = evidence.launchDescriptor(); + Map row = new LinkedHashMap<>(); + row.put(INSTANCE_ID.getName(), worldInstanceId); + row.put(INSTANCE_TENANT_ID.getName(), worldPrivateKeys.tenantId()); + row.put(INSTANCE_GAME_INSTANCE_ID.getName(), worldPrivateKeys.gameInstanceId()); + row.put(INSTANCE_GAME_TEMPLATE_ID.getName(), descriptor.gameTemplateId()); + row.put(INSTANCE_CONTROL_PLANE_REQUEST_ID.getName(), identity.controlPlaneRequestId()); + row.put(INSTANCE_LAUNCH_DESCRIPTOR_ID.getName(), descriptor.launchDescriptorId()); + row.put(INSTANCE_VERSION_ID.getName(), worldPrivateKeys.versionId()); + row.put( + INSTANCE_SCRIPT_PATCH_VERSION.getName(), + descriptor.scriptPatchVersionPresent() ? descriptor.scriptPatchVersion() : null); + row.put(INSTANCE_RUNTIME_FLAGS_JSON.getName(), runtimeFlagsJson); + row.put(INSTANCE_GENERATION_CONFIG_REVISION.getName(), descriptor.generationConfigRevision()); + row.put(INSTANCE_RELEASE_BUNDLE_ID.getName(), descriptor.releaseBundleId()); + row.put( + INSTANCE_PUBLISHED_RELEASE_BUNDLE_REF.getName(), descriptor.publishedReleaseBundleRef()); + row.put(INSTANCE_VERSION_STATE_EPOCH.getName(), descriptor.versionStateEpoch()); + row.put( + INSTANCE_REMAP_SET_ID.getName(), + descriptor.remapSetIdPresent() ? descriptor.remapSetId() : null); + row.put(INSTANCE_CANONICAL_GAME_INSTANCE_ID.getName(), identity.canonicalGameInstanceId()); + row.put(INSTANCE_CANONICAL_TARGET_NAMESPACE.getName(), identity.targetNamespace()); + row.put(INSTANCE_CANONICAL_TENANT_ID.getName(), identity.canonicalTenantId()); + row.put(INSTANCE_CANONICAL_WORLD_SLUG.getName(), identity.worldSlug()); + row.put(INSTANCE_PLAYABLE_STATE_NAMESPACE_ID.getName(), identity.playableStateNamespaceId()); + row.put(INSTANCE_PLAYABLE_STATE_SCOPE.getName(), identity.playableStateScope()); + row.put(INSTANCE_PUBLIC_PRODUCTION.getName(), identity.publicProduction()); + row.put(INSTANCE_CANONICAL_REALM_ID.getName(), identity.canonicalRealmId()); + row.put(INSTANCE_CATALOG_REVISION.getName(), identity.catalogRevision()); + row.put(INSTANCE_PLAYTEST_LIFECYCLE_ID.getName(), (UUID) null); + row.put(INSTANCE_PLAYTEST_STATE_GENERATION.getName(), (Long) null); + row.put(INSTANCE_LAUNCH_BINDING_OPERATION_ID.getName(), (UUID) null); + row.put(INSTANCE_CANONICAL_AUTHORITY_KIND.getName(), "RUN_OWNED_FIXTURE"); + row.put(INSTANCE_FIXTURE_PROVENANCE_DIGEST.getName(), evidence.fixtureProvenanceDigest()); + row.put( + INSTANCE_GAME_SESSION_TENANT_ID.getName(), + evidence.gameSessionAssociation().gameSessionTenantId()); + row.put( + INSTANCE_GAME_SESSION_GAME_INSTANCE_ID.getName(), + evidence.gameSessionAssociation().gameInstanceId()); + row.put(INSTANCE_GAME_DESIGN_VERSION_ID.getName(), descriptor.versionId()); + row.put(INSTANCE_FIXTURE_BINDING_SHA256.getName(), fixtureBindingSha256); + row.put(INSTANCE_FIXTURE_PREPARING_EPOCH.getName(), 1L); + row.put(INSTANCE_LIFECYCLE_EPOCH.getName(), 1L); + row.put(INSTANCE_STATUS.getName(), "PREPARING"); + return row; + } + + private Map runOwnedFixtureAssociationRow( + WorldCanonicalInstanceAssociation.CanonicalIdentity identity, + long worldInstanceId, + WorldCanonicalInstanceAssociation.WorldPrivateKeys worldPrivateKeys, + RunOwnedCanonicalWorldLaunchEvidence evidence, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + WorldAuthoredVersionIdentityReceipt versionIdentity, + String preparationInputDigest, + byte[] gameSessionResponseBytes, + String runtimeFlagsJson) { + var descriptor = evidence.launchDescriptor(); + Map row = new LinkedHashMap<>(); + row.put(SCHEMA_VERSION.getName(), (short) 3); + row.put(CANONICAL_GAME_INSTANCE_ID.getName(), identity.canonicalGameInstanceId()); + row.put(CANONICAL_TARGET_NAMESPACE.getName(), identity.targetNamespace()); + row.put(CANONICAL_TENANT_ID.getName(), identity.canonicalTenantId()); + row.put(CANONICAL_WORLD_SLUG.getName(), identity.worldSlug()); + row.put(PLAYABLE_STATE_NAMESPACE_ID.getName(), identity.playableStateNamespaceId()); + row.put(PLAYABLE_STATE_SCOPE.getName(), identity.playableStateScope()); + row.put(PUBLIC_PRODUCTION.getName(), identity.publicProduction()); + row.put(CANONICAL_REALM_ID.getName(), identity.canonicalRealmId()); + row.put(CATALOG_REVISION.getName(), identity.catalogRevision()); + row.put(PLAYTEST_LIFECYCLE_ID.getName(), (UUID) null); + row.put(PLAYTEST_STATE_GENERATION.getName(), (Long) null); + row.put(CONTROL_PLANE_REQUEST_ID.getName(), identity.controlPlaneRequestId()); + row.put(WORLD_INSTANCE_ID.getName(), worldInstanceId); + row.put(LAUNCH_BINDING_OPERATION_ID.getName(), (UUID) null); + row.put(VERSION_IDENTITY_OPERATION_ID.getName(), versionIdentity.operationId()); + row.put(CANONICAL_VERSION_ID.getName(), versionIdentity.canonicalVersionId()); + row.put(LOCAL_TENANT_KEY.getName(), worldPrivateKeys.tenantId()); + row.put(PRIVATE_GAME_INSTANCE_KEY.getName(), worldPrivateKeys.gameInstanceId()); + row.put(GAME_TEMPLATE_ID.getName(), descriptor.gameTemplateId()); + row.put(LAUNCH_DESCRIPTOR_ID.getName(), descriptor.launchDescriptorId()); + row.put(LOCAL_VERSION_KEY.getName(), worldPrivateKeys.versionId()); + row.put( + SCRIPT_PATCH_VERSION.getName(), + descriptor.scriptPatchVersionPresent() ? descriptor.scriptPatchVersion() : null); + row.put(RUNTIME_FLAGS_JSON.getName(), runtimeFlagsJson); + row.put(GENERATION_CONFIG_REVISION.getName(), descriptor.generationConfigRevision()); + row.put(RELEASE_BUNDLE_ID.getName(), descriptor.releaseBundleId()); + row.put(PUBLISHED_RELEASE_BUNDLE_REF.getName(), descriptor.publishedReleaseBundleRef()); + row.put(VERSION_STATE_EPOCH.getName(), descriptor.versionStateEpoch()); + row.put( + REMAP_SET_ID.getName(), descriptor.remapSetIdPresent() ? descriptor.remapSetId() : null); + row.put(INTAKE_OPERATION_ID.getName(), sourceReceipt.operationId()); + row.put(INTAKE_REQUEST_ID.getName(), sourceReceipt.intakeRequestId()); + row.put(SOURCE_OPERATION_ID.getName(), sourceReceipt.sourceOperationId()); + row.put(SOURCE_EVIDENCE_DIGEST.getName(), sourceReceipt.sourceEvidenceDigest()); + row.put(INTAKE_REQUEST_DIGEST.getName(), sourceReceipt.requestDigest()); + row.put(INTAKE_RECEIPT_DIGEST.getName(), sourceReceipt.receiptDigest()); + row.put(DESCRIPTOR_REQUEST_DIGEST.getName(), descriptor.requestDigest()); + row.put(DESCRIPTOR_RESULT_DIGEST.getName(), descriptor.resultDigest()); + row.put(RELEASE_ATTESTATION_DIGEST.getName(), (String) null); + row.put(CANONICAL_AUTHORITY_KIND.getName(), "RUN_OWNED_FIXTURE"); + row.put(FIXTURE_PROVENANCE_DIGEST.getName(), evidence.fixtureProvenanceDigest()); + row.put( + GAME_SESSION_TENANT_ID.getName(), evidence.gameSessionAssociation().gameSessionTenantId()); + row.put( + GAME_SESSION_GAME_INSTANCE_ID.getName(), + evidence.gameSessionAssociation().gameInstanceId()); + row.put(GAME_DESIGN_VERSION_ID.getName(), descriptor.versionId()); + row.put(PREPARATION_INPUT_DIGEST.getName(), preparationInputDigest); + row.put(PREPARING_LIFECYCLE_EPOCH.getName(), 1L); + row.put( + GAME_SESSION_ASSOCIATION_RESPONSE_BYTES.getName(), + "\\x" + HexFormat.of().formatHex(gameSessionResponseBytes)); + return row; + } + + private Record findFixtureConflict( + UUID canonicalGameInstanceId, + String namespace, + UUID canonicalTenantId, + String fixtureOperationId, + long worldTenantId) { + var rows = + dsl.selectFrom(ASSOCIATION) + .where( + CANONICAL_GAME_INSTANCE_ID + .eq(canonicalGameInstanceId) + .or( + CANONICAL_TARGET_NAMESPACE + .eq(namespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(CONTROL_PLANE_REQUEST_ID.eq(fixtureOperationId))) + .or( + FIXTURE_PROVENANCE_DIGEST + .isNotNull() + .and(CONTROL_PLANE_REQUEST_ID.eq(fixtureOperationId)))) + .fetch(); + if (rows.size() > 1) { + throw new RegistrationConflictException( + "Run-owned fixture identity or operation has multiple World associations"); + } + if (!rows.isEmpty()) return rows.getFirst(); + + Record worldRow = + dsl.selectFrom(WORLD_INSTANCE) + .where( + INSTANCE_CANONICAL_GAME_INSTANCE_ID + .eq(canonicalGameInstanceId) + .or( + INSTANCE_TENANT_ID + .eq(worldTenantId) + .and(INSTANCE_CONTROL_PLANE_REQUEST_ID.eq(fixtureOperationId)))) + .fetchOne(); + if (worldRow != null) { + throw new RegistrationConflictException( + "Run-owned fixture operation or shared canonical UUID is already bound to a World row"); + } + return null; + } + + private static void requireSameRunOwnedFixture( + WorldCanonicalInstanceAssociation stored, + RunOwnedCanonicalWorldLaunchEvidence evidence, + PreparedWorldInstanceRequest request, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + WorldAuthoredVersionIdentityReceipt versionIdentity) { + var expectedGs = evidence.gameSessionAssociation(); + var actual = stored.runOwnedFixture(); + if (actual == null) { + throw new RegistrationConflictException( + "Run-owned fixture retry resolved to a Human association"); + } + String expectedPreparationDigest = + "sha256:" + evidence.bindingDigest(request, actual.preparingLifecycleEpoch()); + if (!stored.isRunOwnedFixture() + || !stored.versionIdentity().equals(versionIdentity) + || !stored.identity().canonicalGameInstanceId().equals(expectedGs.gameInstanceUuid()) + || !stored.identity().targetNamespace().equals(expectedGs.request().targetNamespace()) + || !stored.identity().canonicalTenantId().equals(expectedGs.canonicalTenantId()) + || !stored.identity().worldSlug().equals(sourceReceipt.worldSlug()) + || !stored.identity().controlPlaneRequestId().equals(evidence.capability().operationId()) + || !actual.sourceIntakeReceipt().equals(sourceReceipt) + || !actual.fixtureOperationId().toString().equals(evidence.capability().operationId()) + || !actual.fixtureProvenanceDigest().equals(evidence.fixtureProvenanceDigest()) + || !actual.preparationInputDigest().equals(expectedPreparationDigest) + || actual.gameSessionTenantId() != expectedGs.gameSessionTenantId() + || actual.gameSessionGameInstanceId() != expectedGs.gameInstanceId() + || !sameFixtureLaunchAllocation(actual.gameSessionAssociation(), expectedGs) + || actual.worldPrivateKeys().tenantId() != sourceReceipt.localTenantKey() + || actual.worldPrivateKeys().versionId() != versionIdentity.localVersionKey() + || !Objects.equals(actual.gameTemplateId(), evidence.launchDescriptor().gameTemplateId())) { + throw new RegistrationConflictException( + "Run-owned fixture retry differs from the original World allocation, policy seal, or owner receipts"); + } + } + + private static boolean sameFixtureLaunchAllocation( + CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult stored, + CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult current) { + return stored.request().targetNamespace().equals(current.request().targetNamespace()) + && stored.request().fixtureOperationId().equals(current.request().fixtureOperationId()) + && stored + .request() + .expectedFixturePolicyEvidenceDigest() + .equals(current.request().expectedFixturePolicyEvidenceDigest()) + && stored.gameSessionTenantId() == current.gameSessionTenantId() + && stored.gameInstanceId() == current.gameInstanceId() + && stored.canonicalTenantId().equals(current.canonicalTenantId()) + && stored.gameInstanceUuid().equals(current.gameInstanceUuid()) + && stored.canonicalVersionId().equals(current.canonicalVersionId()) + && stored.canonicalRealmId().equals(current.canonicalRealmId()) + && stored.playableStateNamespaceId().equals(current.playableStateNamespaceId()) + && stored.catalogRevision() == current.catalogRevision() + && java.util.Arrays.equals( + stored.fixturePolicyRequestBytes(), current.fixturePolicyRequestBytes()) + && stored.fixturePolicySeal().equals(current.fixturePolicySeal()); + } + + /** + * Independently reads and reconstructs one immutable owner association after the write + * transaction commits. A present result is non-authorizing and carries no lifecycle status. + */ + public Optional readOwnerAssociation( + UUID canonicalGameInstanceId) { + requireNoActiveTransaction("World canonical instance association read"); + return readOwnerAssociation(canonicalGameInstanceId, false); + } + + /** + * Resolves only the provider-authenticated fixture UUID to its retained World-private keys. The + * external Game Session allocation tuple is checked against the original immutable binding; it is + * never used as a World key. + */ + public WorldCanonicalInstanceAssociation readRunOwnedFixtureAssociation( + RunOwnedCanonicalWorldLaunchEvidence evidence, + PreparedWorldInstanceRequest originalGameSessionRequest) { + Objects.requireNonNull(evidence, "evidence").requireFixedGameSessionPeer(); + requireNoActiveTransaction("Run-owned World fixture association read"); + Objects.requireNonNull(evidence, "evidence"); + Objects.requireNonNull(originalGameSessionRequest, "originalGameSessionRequest"); + evidence.requireMatches(originalGameSessionRequest); + var gameSession = evidence.gameSessionAssociation(); + if (gameSession == null) { + throw new InvalidAssociationEvidenceException( + "Authenticated Game Session fixture allocation is unavailable"); + } + WorldCanonicalInstanceAssociation stored = + readOwnerAssociation(gameSession.gameInstanceUuid()) + .orElseThrow( + () -> + new InvalidAssociationEvidenceException( + "Run-owned World fixture association is not retained")); + requireFixtureAssociationMatches(stored, evidence, originalGameSessionRequest); + return stored; + } + + /** Reconstructs the association without leaving the lifecycle owner's verified snapshot. */ + Optional readOwnerAssociationInOwnerTransaction( + UUID canonicalGameInstanceId) { + requireReadOnlyRepeatableReadOwnerTransaction(); + return readOwnerAssociation(canonicalGameInstanceId, true); + } + + /** Reuses the exact immutable source reconstruction inside a writable activation transaction. */ + Optional readOwnerAssociationInActivationTransaction( + UUID canonicalGameInstanceId) { + requireWritableActivationTransaction(); + return readOwnerAssociation(canonicalGameInstanceId, true, true); + } + + /** + * Locks and verifies the immutable fixture association inside a writable lifecycle transaction. + */ + public WorldCanonicalInstanceAssociation readRunOwnedFixtureAssociationInActivationTransaction( + RunOwnedCanonicalWorldLaunchEvidence evidence, + PreparedWorldInstanceRequest originalGameSessionRequest) { + Objects.requireNonNull(evidence, "evidence").requireFixedGameSessionPeer(); + requireWritableActivationTransaction(); + Objects.requireNonNull(evidence, "evidence"); + Objects.requireNonNull(originalGameSessionRequest, "originalGameSessionRequest"); + evidence.requireMatches(originalGameSessionRequest); + var gameSession = evidence.gameSessionAssociation(); + if (gameSession == null) { + throw new InvalidAssociationEvidenceException( + "Authenticated Game Session fixture allocation is unavailable"); + } + WorldCanonicalInstanceAssociation stored = + readOwnerAssociation(gameSession.gameInstanceUuid(), true, true) + .orElseThrow( + () -> + new InvalidAssociationEvidenceException( + "Run-owned World fixture association is not retained")); + requireFixtureAssociationMatches(stored, evidence, originalGameSessionRequest); + return stored; + } + + /** Fixture activation remains unavailable after PREPARING-only materialization. */ + public void activateRunOwnedFixtureInOwnerTransaction( + WorldCanonicalInstanceAssociation association, long expectedEpoch, long expectedRowVersion) { + throw new IllegalStateException( + "RUN_OWNED_WORLD_ACTIVATION_UNAVAILABLE: fixture activation requires the later canonical lifecycle and hold composition"); + } + + private static void requireFixtureAssociationMatches( + WorldCanonicalInstanceAssociation stored, + RunOwnedCanonicalWorldLaunchEvidence evidence, + PreparedWorldInstanceRequest originalGameSessionRequest) { + if (!stored.isRunOwnedFixture()) { + throw new RegistrationConflictException( + "Run-owned fixture cannot adopt a Human canonical World association"); + } + var fixture = stored.runOwnedFixture(); + requireSameRunOwnedFixture( + stored, + evidence, + originalGameSessionRequest, + fixture.sourceIntakeReceipt(), + stored.versionIdentity()); + } + + private void lockFixtureSourceAndVersionOwners( + WorldAuthoredSourceIntakeReceipt sourceReceipt, + WorldAuthoredVersionIdentityReceipt versionIdentity) { + Record tenant = + dsl.fetchOne( + "SELECT local_tenant_key FROM world_authored_source_tenant_association " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? FOR SHARE", + sourceReceipt.targetNamespace(), + sourceReceipt.canonicalTenantId()); + Record source = + dsl.fetchOne( + "SELECT receipt_digest FROM world_authored_source_intake " + + "WHERE target_namespace = ? AND intake_request_id = ? " + + "AND operation_id = ? FOR SHARE", + sourceReceipt.targetNamespace(), + sourceReceipt.intakeRequestId(), + sourceReceipt.operationId()); + Record version = + dsl.fetchOne( + "SELECT operation_id FROM world_authored_version_identity " + + "WHERE operation_id = ? AND target_namespace = ? " + + "AND canonical_tenant_id = ? AND world_slug = ? " + + "AND canonical_version_id = ? FOR SHARE", + versionIdentity.operationId(), + versionIdentity.targetNamespace(), + versionIdentity.canonicalTenantId(), + versionIdentity.worldSlug(), + versionIdentity.canonicalVersionId()); + if (tenant == null + || !Objects.equals( + tenant.get("local_tenant_key", Long.class), sourceReceipt.localTenantKey()) + || source == null + || !Objects.equals( + source.get("receipt_digest", String.class), sourceReceipt.receiptDigest()) + || version == null) { + throw new InvalidAssociationEvidenceException( + "Run-owned fixture source or Version owner row changed before World allocation"); + } + } + + private Optional readOwnerAssociation( + UUID canonicalGameInstanceId, boolean inOwnerSnapshot) { + return readOwnerAssociation(canonicalGameInstanceId, inOwnerSnapshot, false); + } + + private Optional readOwnerAssociation( + UUID canonicalGameInstanceId, boolean inOwnerSnapshot, boolean inActivationTransaction) { + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + Record row = + inActivationTransaction + ? dsl.selectFrom(ASSOCIATION) + .where(CANONICAL_GAME_INSTANCE_ID.eq(canonicalGameInstanceId)) + .forUpdate() + .fetchOne() + : findByCanonicalGameInstance(canonicalGameInstanceId); + if (row == null) { + return Optional.empty(); + } + return Optional.of(toAssociation(row, inOwnerSnapshot, inActivationTransaction)); + } + + private WorldCanonicalInstanceAssociation toAssociation( + Record row, boolean inOwnerSnapshot, boolean inActivationTransaction) { + try { + short schemaVersion = required(row, SCHEMA_VERSION); + if (schemaVersion == 3) { + return toRunOwnedFixtureAssociation(row, inOwnerSnapshot, inActivationTransaction); + } + if (schemaVersion != 2) { + throw new IllegalArgumentException( + "Historical World canonical instance association lacks launch-captured catalog identity"); + } + String namespace = required(row, CANONICAL_TARGET_NAMESPACE); + UUID tenantId = required(row, CANONICAL_TENANT_ID); + String worldSlug = required(row, CANONICAL_WORLD_SLUG); + String controlRequestId = required(row, CONTROL_PLANE_REQUEST_ID); + UUID bindingOperationId = required(row, LAUNCH_BINDING_OPERATION_ID); + UUID intakeRequestId = required(row, INTAKE_REQUEST_ID); + WorldCompleteLaunchBindingRepository.StoredBinding storedBinding = + (inActivationTransaction + ? launchBindingRepository.readInOwnerActivationTransaction( + namespace, tenantId, controlRequestId) + : inOwnerSnapshot + ? launchBindingRepository.readInOwnerReadOnlyRepeatableRead( + namespace, tenantId, controlRequestId) + : launchBindingRepository.read(namespace, tenantId, controlRequestId)) + .orElseThrow( + () -> + new InvalidAssociationEvidenceException( + "World canonical association lost its immutable launch binding")); + if (!storedBinding.operationId().equals(bindingOperationId)) { + throw new InvalidAssociationEvidenceException( + "World canonical association substituted its complete launch binding"); + } + WorldAuthoredSourceIntakeReceipt sourceReceipt = + (inActivationTransaction + ? sourceIntakeRepository.readInOwnerActivationTransaction( + namespace, intakeRequestId) + : inOwnerSnapshot + ? sourceIntakeRepository.readInOwnerReadOnlyRepeatableRead( + namespace, intakeRequestId) + : sourceIntakeRepository.read(namespace, intakeRequestId)) + .orElseThrow( + () -> + new InvalidAssociationEvidenceException( + "World canonical association lost its original source intake")); + WorldCompleteLaunchBindingReceipt completeBinding = + launchBindingRepository.toReceipt(storedBinding, sourceReceipt); + UUID canonicalVersionId = required(row, CANONICAL_VERSION_ID); + WorldAuthoredVersionIdentityReceipt versionIdentity = + (inActivationTransaction + ? versionIdentityRepository.readByCanonicalVersionInOwnerActivationTransaction( + namespace, tenantId, worldSlug, canonicalVersionId) + : inOwnerSnapshot + ? versionIdentityRepository + .readByCanonicalVersionInOwnerReadOnlyRepeatableRead( + namespace, tenantId, worldSlug, canonicalVersionId) + : versionIdentityRepository.readByCanonicalVersion( + namespace, tenantId, worldSlug, canonicalVersionId)) + .orElseThrow( + () -> + new InvalidAssociationEvidenceException( + "World canonical association lost its UUID-to-private-Version receipt")); + WorldCanonicalInstanceAssociation.CanonicalIdentity identity = + new WorldCanonicalInstanceAssociation.CanonicalIdentity( + required(row, CANONICAL_GAME_INSTANCE_ID), + namespace, + tenantId, + worldSlug, + required(row, PLAYABLE_STATE_NAMESPACE_ID), + required(row, PLAYABLE_STATE_SCOPE), + required(row, PUBLIC_PRODUCTION), + required(row, CANONICAL_REALM_ID), + required(row, CATALOG_REVISION), + controlRequestId); + if (row.get(PLAYTEST_LIFECYCLE_ID) != null || row.get(PLAYTEST_STATE_GENERATION) != null) { + throw new InvalidAssociationEvidenceException( + "Persisted playtest association lacks the current producer's conditional lifecycle/generation proof"); + } + long worldInstanceId = required(row, WORLD_INSTANCE_ID); + Record worldRow = readWorldInstance(worldInstanceId); + WorldCanonicalInstanceAssociation.WorldPrepareFields prepareFields = + toWorldPrepareFields(worldRow); + requireInsertBornIdentity(worldRow, identity, completeBinding.operationId()); + prepareFields.requireMatches(identity, completeBinding, versionIdentity); + requireStoredAssociationColumns( + row, identity, worldInstanceId, completeBinding, versionIdentity, prepareFields); + return new WorldCanonicalInstanceAssociation( + identity, worldInstanceId, completeBinding, versionIdentity, prepareFields); + } catch (RuntimeException exception) { + if (exception instanceof InvalidAssociationEvidenceException) { + throw exception; + } + throw new InvalidAssociationEvidenceException( + "Persisted World canonical instance association is invalid", exception); + } + } + + private WorldCanonicalInstanceAssociation toRunOwnedFixtureAssociation( + Record row, boolean inOwnerSnapshot, boolean inActivationTransaction) { + if (!"RUN_OWNED_FIXTURE".equals(required(row, CANONICAL_AUTHORITY_KIND)) + || row.get(LAUNCH_BINDING_OPERATION_ID) != null + || row.get(RELEASE_ATTESTATION_DIGEST) != null) { + throw new InvalidAssociationEvidenceException( + "Fixture association contains a Human launch or release authority field"); + } + String namespace = required(row, CANONICAL_TARGET_NAMESPACE); + UUID canonicalTenantId = required(row, CANONICAL_TENANT_ID); + String worldSlug = required(row, CANONICAL_WORLD_SLUG); + String fixtureOperationId = required(row, CONTROL_PLANE_REQUEST_ID); + UUID fixtureOperation = UUID.fromString(fixtureOperationId); + String fixtureDigest = required(row, FIXTURE_PROVENANCE_DIGEST); + byte[] responseBytes = required(row, GAME_SESSION_ASSOCIATION_RESPONSE_BYTES); + GetRunOwnedFixtureLaunchAssociationResponse response; + try { + response = GetRunOwnedFixtureLaunchAssociationResponse.parseFrom(responseBytes); + } catch (com.google.protobuf.InvalidProtocolBufferException invalid) { + throw new InvalidAssociationEvidenceException( + "Persisted Game Session fixture association response is invalid", invalid); + } + var request = + new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest( + UUID.fromString(response.getReadRequestId()), + namespace, + fixtureOperation, + fixtureDigest); + var gs = + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureResponse(request, response); + long worldInstanceId = required(row, WORLD_INSTANCE_ID); + WorldCanonicalInstanceAssociation.CanonicalIdentity identity = + new WorldCanonicalInstanceAssociation.CanonicalIdentity( + required(row, CANONICAL_GAME_INSTANCE_ID), + namespace, + canonicalTenantId, + worldSlug, + required(row, PLAYABLE_STATE_NAMESPACE_ID), + required(row, PLAYABLE_STATE_SCOPE), + required(row, PUBLIC_PRODUCTION), + required(row, CANONICAL_REALM_ID), + required(row, CATALOG_REVISION), + fixtureOperationId); + UUID canonicalVersionId = required(row, CANONICAL_VERSION_ID); + WorldAuthoredSourceIntakeReceipt sourceReceipt = + (inActivationTransaction + ? sourceIntakeRepository.readInOwnerActivationTransaction( + namespace, required(row, INTAKE_REQUEST_ID)) + : inOwnerSnapshot + ? sourceIntakeRepository.readInOwnerReadOnlyRepeatableRead( + namespace, required(row, INTAKE_REQUEST_ID)) + : sourceIntakeRepository.read(namespace, required(row, INTAKE_REQUEST_ID))) + .orElseThrow( + () -> + new InvalidAssociationEvidenceException( + "Run-owned fixture association lost its exact World source intake")); + WorldAuthoredVersionIdentityReceipt versionIdentity = + (inActivationTransaction + ? versionIdentityRepository.readByCanonicalVersionInOwnerActivationTransaction( + namespace, canonicalTenantId, worldSlug, canonicalVersionId) + : inOwnerSnapshot + ? versionIdentityRepository.readByCanonicalVersionInOwnerReadOnlyRepeatableRead( + namespace, canonicalTenantId, worldSlug, canonicalVersionId) + : versionIdentityRepository.readByCanonicalVersion( + namespace, canonicalTenantId, worldSlug, canonicalVersionId)) + .orElseThrow( + () -> + new InvalidAssociationEvidenceException( + "Run-owned fixture association lost its exact World Version identity")); + WorldCanonicalInstanceAssociation.WorldPrivateKeys worldPrivateKeys = + new WorldCanonicalInstanceAssociation.WorldPrivateKeys( + required(row, LOCAL_TENANT_KEY), + required(row, PRIVATE_GAME_INSTANCE_KEY), + required(row, LOCAL_VERSION_KEY)); + WorldCanonicalInstanceAssociation.RunOwnedFixture fixture = + new WorldCanonicalInstanceAssociation.RunOwnedFixture( + worldPrivateKeys, + required(row, GAME_SESSION_TENANT_ID), + required(row, GAME_SESSION_GAME_INSTANCE_ID), + required(row, GAME_TEMPLATE_ID), + fixtureOperation, + fixtureDigest, + required(row, PREPARATION_INPUT_DIGEST), + required(row, PREPARING_LIFECYCLE_EPOCH), + responseBytes, + gs, + sourceReceipt); + + Record worldRow = readWorldInstance(worldInstanceId); + requireStoredFixtureAssociationColumns( + row, identity, worldInstanceId, fixture, versionIdentity); + requireStoredFixtureWorldRow(worldRow, row, identity, fixture, versionIdentity); + return new WorldCanonicalInstanceAssociation( + identity, worldInstanceId, null, versionIdentity, null, fixture); + } + + private static void requireStoredFixtureAssociationColumns( + Record row, + WorldCanonicalInstanceAssociation.CanonicalIdentity identity, + long worldInstanceId, + WorldCanonicalInstanceAssociation.RunOwnedFixture fixture, + WorldAuthoredVersionIdentityReceipt versionIdentity) { + var source = fixture.sourceIntakeReceipt(); + var versionState = versionIdentity.versionStateEvidence(); + AuthoredWorldLaunchDescriptorEvidence descriptor = runOwnedFixtureDescriptor(fixture); + if (required(row, SCHEMA_VERSION) != 3 + || !"RUN_OWNED_FIXTURE".equals(required(row, CANONICAL_AUTHORITY_KIND)) + || !Objects.equals( + required(row, CANONICAL_GAME_INSTANCE_ID), identity.canonicalGameInstanceId()) + || !Objects.equals(required(row, CANONICAL_TARGET_NAMESPACE), identity.targetNamespace()) + || !Objects.equals(required(row, CANONICAL_TENANT_ID), identity.canonicalTenantId()) + || !Objects.equals(required(row, CANONICAL_WORLD_SLUG), identity.worldSlug()) + || !Objects.equals( + required(row, PLAYABLE_STATE_NAMESPACE_ID), identity.playableStateNamespaceId()) + || !Objects.equals(required(row, PLAYABLE_STATE_SCOPE), identity.playableStateScope()) + || !Objects.equals(required(row, PUBLIC_PRODUCTION), identity.publicProduction()) + || !Objects.equals(required(row, CANONICAL_REALM_ID), identity.canonicalRealmId()) + || !Objects.equals(required(row, CATALOG_REVISION), identity.catalogRevision()) + || row.get(PLAYTEST_LIFECYCLE_ID) != null + || row.get(PLAYTEST_STATE_GENERATION) != null + || !Objects.equals( + required(row, CONTROL_PLANE_REQUEST_ID), identity.controlPlaneRequestId()) + || !Objects.equals(required(row, WORLD_INSTANCE_ID), worldInstanceId) + || row.get(LAUNCH_BINDING_OPERATION_ID) != null + || !Objects.equals( + required(row, VERSION_IDENTITY_OPERATION_ID), versionIdentity.operationId()) + || !Objects.equals( + required(row, CANONICAL_VERSION_ID), versionIdentity.canonicalVersionId()) + || !Objects.equals(required(row, LOCAL_TENANT_KEY), fixture.worldPrivateKeys().tenantId()) + || !Objects.equals( + required(row, PRIVATE_GAME_INSTANCE_KEY), fixture.worldPrivateKeys().gameInstanceId()) + || !Objects.equals(required(row, GAME_TEMPLATE_ID), fixture.gameTemplateId()) + || !Objects.equals(required(row, LOCAL_VERSION_KEY), fixture.worldPrivateKeys().versionId()) + || !Objects.equals(required(row, GAME_SESSION_TENANT_ID), fixture.gameSessionTenantId()) + || !Objects.equals( + required(row, GAME_SESSION_GAME_INSTANCE_ID), fixture.gameSessionGameInstanceId()) + || !Objects.equals( + required(row, GAME_DESIGN_VERSION_ID), versionIdentity.gameDesignVersionId()) + || !Objects.equals(required(row, LAUNCH_DESCRIPTOR_ID), descriptor.launchDescriptorId()) + || !Objects.equals(required(row, GAME_TEMPLATE_ID), descriptor.gameTemplateId()) + || !Objects.equals( + row.get(SCRIPT_PATCH_VERSION), + descriptor.scriptPatchVersionPresent() ? descriptor.scriptPatchVersion() : null) + || !Objects.equals(required(row, RUNTIME_FLAGS_JSON), descriptor.runtimeFlagsJson()) + || !Objects.equals( + required(row, GENERATION_CONFIG_REVISION), descriptor.generationConfigRevision()) + || !Objects.equals(required(row, RELEASE_BUNDLE_ID), descriptor.releaseBundleId()) + || !Objects.equals( + required(row, PUBLISHED_RELEASE_BUNDLE_REF), descriptor.publishedReleaseBundleRef()) + || !Objects.equals( + row.get(REMAP_SET_ID), descriptor.remapSetIdPresent() ? descriptor.remapSetId() : null) + || !Objects.equals(required(row, DESCRIPTOR_REQUEST_DIGEST), descriptor.requestDigest()) + || !Objects.equals(required(row, DESCRIPTOR_RESULT_DIGEST), descriptor.resultDigest()) + || !Objects.equals( + required(row, FIXTURE_PROVENANCE_DIGEST), fixture.fixtureProvenanceDigest()) + || !Objects.equals( + required(row, PREPARATION_INPUT_DIGEST), fixture.preparationInputDigest()) + || !Objects.equals( + required(row, PREPARING_LIFECYCLE_EPOCH), fixture.preparingLifecycleEpoch()) + || row.get(RELEASE_ATTESTATION_DIGEST) != null + || !Objects.equals(required(row, INTAKE_OPERATION_ID), source.operationId()) + || !Objects.equals(required(row, INTAKE_REQUEST_ID), source.intakeRequestId()) + || !Objects.equals(required(row, SOURCE_OPERATION_ID), source.sourceOperationId()) + || !Objects.equals(required(row, SOURCE_EVIDENCE_DIGEST), source.sourceEvidenceDigest()) + || !Objects.equals(required(row, INTAKE_REQUEST_DIGEST), source.requestDigest()) + || !Objects.equals(required(row, INTAKE_RECEIPT_DIGEST), source.receiptDigest()) + || !Objects.equals(required(row, VERSION_STATE_EPOCH), versionState.versionStateEpoch())) { + throw new InvalidAssociationEvidenceException( + "Persisted run-owned fixture association differs from its immutable World and external owner evidence"); + } + } + + private static void requireStoredFixtureWorldRow( + Record row, + Record associationRow, + WorldCanonicalInstanceAssociation.CanonicalIdentity identity, + WorldCanonicalInstanceAssociation.RunOwnedFixture fixture, + WorldAuthoredVersionIdentityReceipt versionIdentity) { + String preparationInputDigest = fixture.preparationInputDigest(); + if (row == null + || !"RUN_OWNED_FIXTURE".equals(row.get(INSTANCE_CANONICAL_AUTHORITY_KIND, String.class)) + || !Objects.equals( + row.get(INSTANCE_CANONICAL_GAME_INSTANCE_ID, UUID.class), + identity.canonicalGameInstanceId()) + || !Objects.equals( + row.get(INSTANCE_CANONICAL_TARGET_NAMESPACE, String.class), identity.targetNamespace()) + || !Objects.equals( + row.get(INSTANCE_CANONICAL_TENANT_ID, UUID.class), identity.canonicalTenantId()) + || !Objects.equals( + row.get(INSTANCE_CANONICAL_WORLD_SLUG, String.class), identity.worldSlug()) + || !Objects.equals( + row.get(INSTANCE_PLAYABLE_STATE_NAMESPACE_ID, UUID.class), + identity.playableStateNamespaceId()) + || !Objects.equals( + row.get(INSTANCE_PLAYABLE_STATE_SCOPE, String.class), identity.playableStateScope()) + || !Objects.equals( + row.get(INSTANCE_PUBLIC_PRODUCTION, Boolean.class), identity.publicProduction()) + || !Objects.equals( + row.get(INSTANCE_CANONICAL_REALM_ID, UUID.class), identity.canonicalRealmId()) + || !Objects.equals( + row.get(INSTANCE_CATALOG_REVISION, Long.class), identity.catalogRevision()) + || row.get(INSTANCE_LAUNCH_BINDING_OPERATION_ID, UUID.class) != null + || !Objects.equals( + row.get(INSTANCE_FIXTURE_PROVENANCE_DIGEST, String.class), + fixture.fixtureProvenanceDigest()) + || !Objects.equals( + row.get(INSTANCE_GAME_SESSION_TENANT_ID, Long.class), fixture.gameSessionTenantId()) + || !Objects.equals( + row.get(INSTANCE_GAME_SESSION_GAME_INSTANCE_ID, Long.class), + fixture.gameSessionGameInstanceId()) + || !Objects.equals( + row.get(INSTANCE_GAME_DESIGN_VERSION_ID, Long.class), + versionIdentity.gameDesignVersionId()) + || !Objects.equals( + row.get(INSTANCE_TENANT_ID, Long.class), fixture.worldPrivateKeys().tenantId()) + || !Objects.equals( + row.get(INSTANCE_GAME_INSTANCE_ID, Long.class), + fixture.worldPrivateKeys().gameInstanceId()) + || !Objects.equals( + row.get(INSTANCE_VERSION_ID, Long.class), fixture.worldPrivateKeys().versionId()) + || !Objects.equals( + row.get(INSTANCE_FIXTURE_BINDING_SHA256, String.class), + preparationInputDigest.substring("sha256:".length())) + || !Objects.equals( + row.get(INSTANCE_FIXTURE_PREPARING_EPOCH, Long.class), + fixture.preparingLifecycleEpoch()) + || fixture.preparingLifecycleEpoch() != 1L + || !Objects.equals( + row.get(INSTANCE_LIFECYCLE_EPOCH, Long.class), fixture.preparingLifecycleEpoch()) + || !"PREPARING".equals(row.get(INSTANCE_STATUS, String.class)) + || !Objects.equals(row.get("row_version", Long.class), 0L) + || !Objects.equals( + row.get(INSTANCE_CONTROL_PLANE_REQUEST_ID, String.class), + identity.controlPlaneRequestId()) + || !Objects.equals( + row.get(INSTANCE_GAME_TEMPLATE_ID, Long.class), + required(associationRow, GAME_TEMPLATE_ID)) + || !Objects.equals( + row.get(INSTANCE_LAUNCH_DESCRIPTOR_ID, String.class), + required(associationRow, LAUNCH_DESCRIPTOR_ID)) + || !Objects.equals( + row.get(INSTANCE_SCRIPT_PATCH_VERSION, String.class), + associationRow.get(SCRIPT_PATCH_VERSION, String.class)) + || !Objects.equals( + row.get(INSTANCE_RUNTIME_FLAGS_JSON, String.class), + required(associationRow, RUNTIME_FLAGS_JSON)) + || !Objects.equals( + row.get(INSTANCE_GENERATION_CONFIG_REVISION, String.class), + required(associationRow, GENERATION_CONFIG_REVISION)) + || !Objects.equals( + row.get(INSTANCE_RELEASE_BUNDLE_ID, Long.class), + required(associationRow, RELEASE_BUNDLE_ID)) + || !Objects.equals( + row.get(INSTANCE_PUBLISHED_RELEASE_BUNDLE_REF, String.class), + required(associationRow, PUBLISHED_RELEASE_BUNDLE_REF)) + || !Objects.equals( + row.get(INSTANCE_REMAP_SET_ID, String.class), + associationRow.get(REMAP_SET_ID, String.class)) + || !Objects.equals( + row.get(INSTANCE_VERSION_STATE_EPOCH, Long.class), + versionIdentity.versionStateEvidence().versionStateEpoch())) { + throw new InvalidAssociationEvidenceException( + "Persisted run-owned fixture World row differs from its retained owner association"); + } + } + + private void requireInsertBornFixtureIdentity( + Record row, + long worldInstanceId, + WorldCanonicalInstanceAssociation.CanonicalIdentity identity, + WorldCanonicalInstanceAssociation.WorldPrivateKeys worldPrivateKeys, + PreparedWorldInstanceRequest request, + RunOwnedCanonicalWorldLaunchEvidence evidence, + String fixtureBindingSha256) { + evidence.requireMatches(request); + var gameSession = evidence.gameSessionAssociation(); + if (gameSession == null) { + throw new InvalidAssociationEvidenceException( + "Run-owned World fixture row requires the exact authenticated Game Session association"); + } + var capability = evidence.capability(); + var source = evidence.sourceReceipt().sourceEvidence(); + var descriptor = evidence.launchDescriptor(); + if (row == null + || !evidence.bindingDigest(request, 1L).equals(fixtureBindingSha256) + || !identity.canonicalGameInstanceId().equals(gameSession.gameInstanceUuid()) + || !identity.targetNamespace().equals(gameSession.request().targetNamespace()) + || !identity.canonicalTenantId().equals(gameSession.canonicalTenantId()) + || !identity.worldSlug().equals(source.worldSlug()) + || !identity.playableStateNamespaceId().equals(gameSession.playableStateNamespaceId()) + || !identity.playableStateScope().equals(capability.stateScope()) + || identity.publicProduction() != capability.publicProductionRealm() + || !identity.canonicalRealmId().equals(gameSession.canonicalRealmId()) + || identity.catalogRevision() != gameSession.catalogRevision() + || !identity.controlPlaneRequestId().equals(capability.operationId()) + || !descriptor.targetNamespace().equals(source.targetNamespace()) + || !descriptor.canonicalTenantId().equals(source.canonicalTenantId()) + || !descriptor.worldSlug().equals(source.worldSlug()) + || !descriptor.authoredWorldSourceOperationId().equals(source.operationId()) + || !descriptor.authoredWorldSourceEvidenceDigest().equals(source.evidenceDigest()) + || !evidence + .fixtureProvenanceDigest() + .equals(gameSession.fixturePolicySeal().evidenceDigest()) + || !Objects.equals(row.get(INSTANCE_ID), worldInstanceId) + || !Objects.equals(row.get(INSTANCE_TENANT_ID), worldPrivateKeys.tenantId()) + || !Objects.equals(row.get(INSTANCE_GAME_INSTANCE_ID), worldPrivateKeys.gameInstanceId()) + || !Objects.equals(row.get(INSTANCE_VERSION_ID), worldPrivateKeys.versionId()) + || !Objects.equals(row.get(INSTANCE_GAME_TEMPLATE_ID), capability.gameTemplateId()) + || !Objects.equals( + row.get(INSTANCE_CONTROL_PLANE_REQUEST_ID), identity.controlPlaneRequestId()) + || !Objects.equals(row.get(INSTANCE_LAUNCH_DESCRIPTOR_ID), descriptor.launchDescriptorId()) + || !Objects.equals( + row.get(INSTANCE_SCRIPT_PATCH_VERSION), + descriptor.scriptPatchVersionPresent() ? descriptor.scriptPatchVersion() : null) + || !Objects.equals(row.get(INSTANCE_RUNTIME_FLAGS_JSON), descriptor.runtimeFlagsJson()) + || !Objects.equals( + row.get(INSTANCE_GENERATION_CONFIG_REVISION), descriptor.generationConfigRevision()) + || !Objects.equals(row.get(INSTANCE_RELEASE_BUNDLE_ID), descriptor.releaseBundleId()) + || !Objects.equals( + row.get(INSTANCE_PUBLISHED_RELEASE_BUNDLE_REF), descriptor.publishedReleaseBundleRef()) + || !Objects.equals(row.get(INSTANCE_VERSION_STATE_EPOCH), descriptor.versionStateEpoch()) + || !Objects.equals( + row.get(INSTANCE_REMAP_SET_ID), + descriptor.remapSetIdPresent() ? descriptor.remapSetId() : null) + || !Objects.equals( + row.get(INSTANCE_CANONICAL_GAME_INSTANCE_ID), identity.canonicalGameInstanceId()) + || !Objects.equals(row.get(INSTANCE_CANONICAL_TARGET_NAMESPACE), identity.targetNamespace()) + || !Objects.equals(row.get(INSTANCE_CANONICAL_TENANT_ID), identity.canonicalTenantId()) + || !Objects.equals(row.get(INSTANCE_CANONICAL_WORLD_SLUG), identity.worldSlug()) + || !Objects.equals( + row.get(INSTANCE_PLAYABLE_STATE_NAMESPACE_ID), identity.playableStateNamespaceId()) + || !Objects.equals(row.get(INSTANCE_PLAYABLE_STATE_SCOPE), identity.playableStateScope()) + || !Objects.equals(row.get(INSTANCE_PUBLIC_PRODUCTION), identity.publicProduction()) + || !Objects.equals(row.get(INSTANCE_CANONICAL_REALM_ID), identity.canonicalRealmId()) + || !Objects.equals(row.get(INSTANCE_CATALOG_REVISION), identity.catalogRevision()) + || row.get(INSTANCE_PLAYTEST_LIFECYCLE_ID) != null + || row.get(INSTANCE_PLAYTEST_STATE_GENERATION) != null + || row.get(INSTANCE_LAUNCH_BINDING_OPERATION_ID) != null + || !"RUN_OWNED_FIXTURE".equals(row.get(INSTANCE_CANONICAL_AUTHORITY_KIND)) + || !Objects.equals( + row.get(INSTANCE_FIXTURE_PROVENANCE_DIGEST), evidence.fixtureProvenanceDigest()) + || !Objects.equals( + row.get(INSTANCE_GAME_SESSION_TENANT_ID), gameSession.gameSessionTenantId()) + || !Objects.equals( + row.get(INSTANCE_GAME_SESSION_GAME_INSTANCE_ID), gameSession.gameInstanceId()) + || !Objects.equals(row.get(INSTANCE_GAME_DESIGN_VERSION_ID), descriptor.versionId()) + || !Objects.equals(row.get(INSTANCE_FIXTURE_BINDING_SHA256), fixtureBindingSha256) + || !Objects.equals(row.get(INSTANCE_FIXTURE_PREPARING_EPOCH), 1L) + || !Objects.equals(row.get(INSTANCE_LIFECYCLE_EPOCH), 1L) + || !"PREPARING".equals(row.get(INSTANCE_STATUS))) { + throw new InvalidAssociationEvidenceException( + "World run-owned fixture row differs from the exact authenticated Game Session, source, descriptor, or original preparing identity"); + } + } + + static AuthoredWorldLaunchDescriptorEvidence runOwnedFixtureDescriptor( + WorldCanonicalInstanceAssociation.RunOwnedFixture fixture) { + var policy = fixture.gameSessionAssociation().fixturePolicyRequest(); + var source = policy.sourceEvidence(); + var capability = policy.capability(); + return AuthoredWorldLaunchDescriptorGrpcCodec.fromLaunchDescriptorMessage( + new AuthoredWorldLaunchDescriptorEvidence.Request( + source.targetNamespace(), + capability.operationId(), + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + capability.gameTemplateId(), + false, + null, + false, + null, + false, + null, + false, + null), + policy.launchReadEvidence().launchDescriptor()); + } + + private long nextPositiveSequenceValue(String sequenceName) { + if (!"world_instance_id_seq".equals(sequenceName) + && !"world_canonical_private_game_instance_key_seq".equals(sequenceName)) { + throw new IllegalArgumentException("Unsupported World fixture allocation sequence"); + } + Record sequenceRow = dsl.fetchOne("SELECT nextval('" + sequenceName + "') AS value"); + Long value = sequenceRow == null ? null : sequenceRow.get("value", Long.class); + if (value == null || value <= 0) { + throw new InvalidAssociationEvidenceException( + "World run-owned fixture allocation sequence returned an invalid private key"); + } + return value; + } + + private void requireExactImmutableOwnerEvidence(WorldCanonicalInstanceAssociation.Claim claim) { + var sourceReceipt = claim.completeLaunchBinding().sourceIntakeReceipt(); + var evidence = claim.completeLaunchBinding().evidence(); + var descriptor = evidence.descriptor(); + var release = evidence.releaseAttestation(); + + Record binding = + dsl.selectFrom(COMPLETE_BINDING) + .where(BINDING_OPERATION_ID.eq(claim.launchBindingOperationId())) + .fetchOne(); + if (binding == null + || !Objects.equals( + binding.get(BINDING_TARGET_NAMESPACE, String.class), claim.targetNamespace()) + || !Objects.equals( + binding.get(BINDING_CANONICAL_TENANT_ID, UUID.class), claim.canonicalTenantId()) + || !Objects.equals( + binding.get(BINDING_CANONICAL_VERSION_ID, UUID.class), claim.canonicalVersionId()) + || !Objects.equals(binding.get(BINDING_WORLD_SLUG, String.class), claim.worldSlug()) + || !Objects.equals( + binding.get(BINDING_CONTROL_PLANE_REQUEST_ID, String.class), + claim.controlPlaneRequestId()) + || !Objects.equals( + binding.get(BINDING_INTAKE_OPERATION_ID, UUID.class), sourceReceipt.operationId()) + || !Objects.equals( + binding.get(BINDING_INTAKE_REQUEST_ID, UUID.class), sourceReceipt.intakeRequestId()) + || !Objects.equals( + binding.get(BINDING_LOCAL_TENANT_KEY, Long.class), sourceReceipt.localTenantKey()) + || !Objects.equals( + binding.get(BINDING_SOURCE_OPERATION_ID, UUID.class), sourceReceipt.sourceOperationId()) + || !Objects.equals( + binding.get(BINDING_SOURCE_EVIDENCE_DIGEST, String.class), + sourceReceipt.sourceEvidenceDigest()) + || !Objects.equals( + binding.get(BINDING_INTAKE_RECEIPT_DIGEST, String.class), sourceReceipt.receiptDigest()) + || !Objects.equals( + binding.get(BINDING_DESCRIPTOR_REQUEST_DIGEST, String.class), + descriptor.requestDigest()) + || !Objects.equals( + binding.get(BINDING_DESCRIPTOR_RESULT_DIGEST, String.class), descriptor.resultDigest()) + || !Objects.equals( + binding.get(BINDING_RELEASE_ATTESTATION_DIGEST, String.class), release.evidenceDigest()) + || !Objects.equals( + binding.get(BINDING_DESCRIPTOR_JSON, String.class), writeJson(descriptor)) + || !Objects.equals( + binding.get(BINDING_RELEASE_ATTESTATION_JSON, String.class), writeJson(release))) { + throw new RegistrationConflictException( + "Canonical instance claim differs from exact immutable V26 descriptor/release bytes"); + } + + Record source = + dsl.selectFrom(SOURCE_INTAKE) + .where(SOURCE_OPERATION_ID_KEY.eq(sourceReceipt.operationId())) + .fetchOne(); + requireExactSourceColumns(source, sourceReceipt); + + WorldAuthoredVersionIdentityReceipt identity = claim.versionIdentity(); + AuthoredWorldVersionStateEvidence versionEvidence = identity.versionStateEvidence(); + Record version = + dsl.selectFrom(VERSION_IDENTITY) + .where(VERSION_OPERATION_ID.eq(identity.operationId())) + .fetchOne(); + if (version == null + || !Objects.equals( + version.get(VERSION_TARGET_NAMESPACE, String.class), identity.targetNamespace()) + || !Objects.equals( + version.get(VERSION_CANONICAL_TENANT_ID, UUID.class), identity.canonicalTenantId()) + || !Objects.equals(version.get(VERSION_WORLD_SLUG, String.class), identity.worldSlug()) + || !Objects.equals( + version.get(VERSION_CANONICAL_VERSION_ID, UUID.class), identity.canonicalVersionId()) + || !Objects.equals( + version.get(VERSION_GAME_DESIGN_VERSION_ID, Long.class), identity.gameDesignVersionId()) + || !Objects.equals( + version.get(VERSION_LOCAL_VERSION_KEY, Long.class), identity.localVersionKey()) + || !Objects.equals( + version.get(VERSION_INTAKE_OPERATION_ID, UUID.class), sourceReceipt.operationId()) + || !Objects.equals( + version.get(VERSION_INTAKE_REQUEST_ID, UUID.class), sourceReceipt.intakeRequestId()) + || !Objects.equals( + version.get(VERSION_LOCAL_TENANT_KEY, Long.class), sourceReceipt.localTenantKey()) + || !Objects.equals( + version.get(VERSION_INTAKE_REQUEST_DIGEST, String.class), sourceReceipt.requestDigest()) + || !Objects.equals( + version.get(VERSION_SOURCE_OPERATION_ID, UUID.class), sourceReceipt.sourceOperationId()) + || !Objects.equals( + version.get(VERSION_SOURCE_EVIDENCE_DIGEST, String.class), + sourceReceipt.sourceEvidenceDigest()) + || !Objects.equals( + version.get(VERSION_INTAKE_RECEIPT_DIGEST, String.class), sourceReceipt.receiptDigest()) + || !Objects.equals( + version.get(VERSION_STATE_SCHEMA_VERSION, Short.class), + (short) versionEvidence.request().schemaVersion()) + || !Objects.equals( + version.get(VERSION_STATE_READ_REQUEST_ID, UUID.class), + versionEvidence.request().readRequestId()) + || !Objects.equals( + version.get(VERSION_STATE_STATE, String.class), + versionEvidence.versionState().name().replace("VERSION_LIFECYCLE_STATE_", "")) + || !Objects.equals( + version.get(VERSION_STATE_EVIDENCE_EPOCH, Long.class), + versionEvidence.versionStateEpoch()) + || !Objects.equals( + version.get(VERSION_STATE_EVIDENCE_DIGEST, String.class), + versionEvidence.evidenceDigest()) + || !Objects.equals( + version.get(VERSION_STATE_EVIDENCE_JSON, String.class), writeJson(versionEvidence))) { + throw new RegistrationConflictException( + "Canonical instance claim differs from exact immutable V27 Version/source bytes"); + } + } + + private static void requireExactSourceColumns( + Record row, WorldAuthoredSourceIntakeReceipt receipt) { + if (row == null) { + throw new RegistrationConflictException( + "Canonical instance claim lost its original source intake"); + } + AuthoredWorldSourceEvidence source = receipt.source(); + if (!Objects.equals( + row.get(SOURCE_SCHEMA_VERSION, Short.class), (short) receipt.schemaVersion()) + || !Objects.equals( + row.get(SOURCE_TARGET_NAMESPACE, String.class), receipt.targetNamespace()) + || !Objects.equals(row.get(SOURCE_INTAKE_REQUEST_ID, UUID.class), receipt.intakeRequestId()) + || !Objects.equals(row.get(SOURCE_REQUEST_DIGEST, String.class), receipt.requestDigest()) + || !Objects.equals(row.get(SOURCE_LOCAL_TENANT_KEY, Long.class), receipt.localTenantKey()) + || !Objects.equals( + row.get(SOURCE_EVIDENCE_SCHEMA_VERSION, Short.class), (short) source.schemaVersion()) + || !Objects.equals( + row.get(SOURCE_REGISTRATION_REQUEST_ID, UUID.class), source.registrationRequestId()) + || !Objects.equals(row.get(SOURCE_SOURCE_OPERATION_ID, UUID.class), source.operationId()) + || !Objects.equals( + row.get(SOURCE_SOURCE_REQUEST_DIGEST, String.class), source.requestDigest()) + || !Objects.equals( + row.get(SOURCE_CANONICAL_TENANT_ID, UUID.class), source.canonicalTenantId()) + || !Objects.equals(row.get(SOURCE_TENANT_SLUG, String.class), source.tenantSlug()) + || !Objects.equals(row.get(SOURCE_WORLD_SLUG, String.class), source.worldSlug()) + || !Objects.equals( + row.get(SOURCE_WORLD_DISPLAY_NAME, String.class), source.worldDisplayName()) + || !Objects.equals(row.get(SOURCE_GAME_ROW_ID, Long.class), source.sourceGameRowId()) + || !Objects.equals( + row.get(SOURCE_GAME_TENANT_KEY, String.class), source.sourceGameTenantKey()) + || !Objects.equals(row.get(SOURCE_PROVENANCE_KIND, String.class), source.provenanceKind()) + || !Objects.equals( + row.get(SOURCE_SOURCE_EVIDENCE_DIGEST, String.class), source.evidenceDigest()) + || !Objects.equals(row.get(SOURCE_RECEIPT_DIGEST, String.class), receipt.receiptDigest())) { + throw new RegistrationConflictException( + "Canonical instance claim differs from exact immutable World source intake fields"); + } + } + + private void requireSameStoredClaim( + Record stored, + WorldCanonicalInstanceAssociation.Claim claim, + WorldCanonicalInstanceAssociation.WorldPrepareFields prepareFields) { + requireStoredAssociationColumns( + stored, + claim.identity(), + claim.worldInstanceId(), + claim.completeLaunchBinding(), + claim.versionIdentity(), + prepareFields); + WorldCanonicalInstanceAssociation.WorldPrepareFields actual = + toWorldPrepareFields(readWorldInstance(claim.worldInstanceId())); + if (!actual.equals(prepareFields)) { + throw new InvalidAssociationEvidenceException( + "World canonical association row changed during exact owner retry"); + } + } + + private static void requireStoredAssociationColumns( + Record row, + WorldCanonicalInstanceAssociation.CanonicalIdentity identity, + long worldInstanceId, + WorldCompleteLaunchBindingReceipt completeLaunchBinding, + WorldAuthoredVersionIdentityReceipt versionIdentity, + WorldCanonicalInstanceAssociation.WorldPrepareFields prepareFields) { + var source = completeLaunchBinding.sourceIntakeReceipt(); + var descriptor = completeLaunchBinding.descriptor(); + var release = completeLaunchBinding.evidence().releaseAttestation(); + if (required(row, SCHEMA_VERSION) != 2 + || !Objects.equals( + required(row, CANONICAL_GAME_INSTANCE_ID), identity.canonicalGameInstanceId()) + || !Objects.equals(required(row, CANONICAL_TARGET_NAMESPACE), identity.targetNamespace()) + || !Objects.equals(required(row, CANONICAL_TENANT_ID), identity.canonicalTenantId()) + || !Objects.equals(required(row, CANONICAL_WORLD_SLUG), identity.worldSlug()) + || !Objects.equals( + required(row, PLAYABLE_STATE_NAMESPACE_ID), identity.playableStateNamespaceId()) + || !Objects.equals(required(row, PLAYABLE_STATE_SCOPE), identity.playableStateScope()) + || !Objects.equals(required(row, PUBLIC_PRODUCTION), identity.publicProduction()) + || !Objects.equals(required(row, CANONICAL_REALM_ID), identity.canonicalRealmId()) + || !Objects.equals(required(row, CATALOG_REVISION), identity.catalogRevision()) + || row.get(PLAYTEST_LIFECYCLE_ID) != null + || row.get(PLAYTEST_STATE_GENERATION) != null + || !Objects.equals( + required(row, CONTROL_PLANE_REQUEST_ID), identity.controlPlaneRequestId()) + || !Objects.equals(required(row, WORLD_INSTANCE_ID), worldInstanceId) + || !Objects.equals( + required(row, LAUNCH_BINDING_OPERATION_ID), completeLaunchBinding.operationId()) + || !Objects.equals( + required(row, VERSION_IDENTITY_OPERATION_ID), versionIdentity.operationId()) + || !Objects.equals(required(row, CANONICAL_VERSION_ID), release.canonicalVersionId()) + || !Objects.equals(required(row, LOCAL_TENANT_KEY), prepareFields.privateTenantKey()) + || !Objects.equals( + required(row, PRIVATE_GAME_INSTANCE_KEY), prepareFields.privateGameInstanceKey()) + || !Objects.equals(required(row, GAME_TEMPLATE_ID), prepareFields.gameTemplateId()) + || !Objects.equals(required(row, LAUNCH_DESCRIPTOR_ID), prepareFields.launchDescriptorId()) + || !Objects.equals(required(row, LOCAL_VERSION_KEY), prepareFields.localVersionKey()) + || !Objects.equals(row.get(SCRIPT_PATCH_VERSION), prepareFields.scriptPatchVersion()) + || !Objects.equals(required(row, RUNTIME_FLAGS_JSON), prepareFields.runtimeFlagsJson()) + || !Objects.equals( + required(row, GENERATION_CONFIG_REVISION), prepareFields.generationConfigRevision()) + || !Objects.equals(required(row, RELEASE_BUNDLE_ID), prepareFields.releaseBundleId()) + || !Objects.equals( + required(row, PUBLISHED_RELEASE_BUNDLE_REF), prepareFields.publishedReleaseBundleRef()) + || !Objects.equals(required(row, VERSION_STATE_EPOCH), prepareFields.versionStateEpoch()) + || !Objects.equals(row.get(REMAP_SET_ID), prepareFields.remapSetId()) + || !Objects.equals(required(row, INTAKE_OPERATION_ID), source.operationId()) + || !Objects.equals(required(row, INTAKE_REQUEST_ID), source.intakeRequestId()) + || !Objects.equals(required(row, SOURCE_OPERATION_ID), source.sourceOperationId()) + || !Objects.equals(required(row, SOURCE_EVIDENCE_DIGEST), source.sourceEvidenceDigest()) + || !Objects.equals(required(row, INTAKE_REQUEST_DIGEST), source.requestDigest()) + || !Objects.equals(required(row, INTAKE_RECEIPT_DIGEST), source.receiptDigest()) + || !Objects.equals(required(row, DESCRIPTOR_REQUEST_DIGEST), descriptor.requestDigest()) + || !Objects.equals(required(row, DESCRIPTOR_RESULT_DIGEST), descriptor.resultDigest()) + || !Objects.equals(required(row, RELEASE_ATTESTATION_DIGEST), release.evidenceDigest())) { + throw new RegistrationConflictException( + "Canonical Game Instance, World row, request, source, Version, descriptor, or release binding conflicts"); + } + } + + private void requireInsertBornIdentity( + Record row, WorldCanonicalInstanceAssociation.Claim claim) { + requireInsertBornIdentity(row, claim.identity(), claim.launchBindingOperationId()); + } + + private void requireInsertBornIdentity( + Record row, + WorldCanonicalInstanceAssociation.CanonicalIdentity identity, + UUID launchBindingOperationId) { + if (row == null + || !Objects.equals( + row.get(INSTANCE_CANONICAL_GAME_INSTANCE_ID), identity.canonicalGameInstanceId()) + || !Objects.equals(row.get(INSTANCE_CANONICAL_TARGET_NAMESPACE), identity.targetNamespace()) + || !Objects.equals(row.get(INSTANCE_CANONICAL_TENANT_ID), identity.canonicalTenantId()) + || !Objects.equals(row.get(INSTANCE_CANONICAL_WORLD_SLUG), identity.worldSlug()) + || !Objects.equals( + row.get(INSTANCE_PLAYABLE_STATE_NAMESPACE_ID), identity.playableStateNamespaceId()) + || !Objects.equals(row.get(INSTANCE_PLAYABLE_STATE_SCOPE), identity.playableStateScope()) + || !Objects.equals(row.get(INSTANCE_PUBLIC_PRODUCTION), identity.publicProduction()) + || !Objects.equals(row.get(INSTANCE_CANONICAL_REALM_ID), identity.canonicalRealmId()) + || !Objects.equals(row.get(INSTANCE_CATALOG_REVISION), identity.catalogRevision()) + || row.get(INSTANCE_PLAYTEST_LIFECYCLE_ID) != null + || row.get(INSTANCE_PLAYTEST_STATE_GENERATION) != null + || !Objects.equals( + row.get(INSTANCE_LAUNCH_BINDING_OPERATION_ID), launchBindingOperationId)) { + throw new InvalidAssociationEvidenceException( + "World row has no matching insert-born canonical prepare identity; retained numeric rows cannot be associated"); + } + } + + private Record lockWorldInstance(long worldInstanceId) { + Record row = + dsl.selectFrom(WORLD_INSTANCE) + .where(INSTANCE_ID.eq(worldInstanceId)) + .forUpdate() + .fetchOne(); + if (row == null) { + throw new InvalidAssociationEvidenceException( + "Canonical instance association requires an already-created World instance row"); + } + return row; + } + + private Record readWorldInstance(long worldInstanceId) { + Record row = dsl.selectFrom(WORLD_INSTANCE).where(INSTANCE_ID.eq(worldInstanceId)).fetchOne(); + if (row == null) { + throw new InvalidAssociationEvidenceException( + "Canonical instance association lost its exact World instance row"); + } + return row; + } + + private WorldCanonicalInstanceAssociation.WorldPrepareFields toWorldPrepareFields(Record row) { + if (row == null) { + throw new InvalidAssociationEvidenceException("World instance row is missing"); + } + try { + return new WorldCanonicalInstanceAssociation.WorldPrepareFields( + required(row, INSTANCE_ID), + required(row, INSTANCE_TENANT_ID), + required(row, INSTANCE_GAME_INSTANCE_ID), + required(row, INSTANCE_GAME_TEMPLATE_ID), + required(row, INSTANCE_CONTROL_PLANE_REQUEST_ID), + required(row, INSTANCE_LAUNCH_DESCRIPTOR_ID), + required(row, INSTANCE_VERSION_ID), + row.get(INSTANCE_SCRIPT_PATCH_VERSION), + required(row, INSTANCE_RUNTIME_FLAGS_JSON), + required(row, INSTANCE_GENERATION_CONFIG_REVISION), + required(row, INSTANCE_RELEASE_BUNDLE_ID), + required(row, INSTANCE_PUBLISHED_RELEASE_BUNDLE_REF), + required(row, INSTANCE_VERSION_STATE_EPOCH), + row.get(INSTANCE_REMAP_SET_ID)); + } catch (RuntimeException exception) { + if (exception instanceof InvalidAssociationEvidenceException) { + throw exception; + } + throw new InvalidAssociationEvidenceException( + "World instance prepare fields are incomplete or invalid", exception); + } + } + + private Record findConflict(WorldCanonicalInstanceAssociation.Claim claim) { + Record row = findByCanonicalGameInstance(claim.canonicalGameInstanceId()); + if (row == null) { + row = + dsl.selectFrom(ASSOCIATION) + .where( + CANONICAL_TARGET_NAMESPACE + .eq(claim.targetNamespace()) + .and(CANONICAL_TENANT_ID.eq(claim.canonicalTenantId())) + .and(CONTROL_PLANE_REQUEST_ID.eq(claim.controlPlaneRequestId()))) + .fetchOne(); + } + if (row == null) { + row = + dsl.selectFrom(ASSOCIATION) + .where(WORLD_INSTANCE_ID.eq(claim.worldInstanceId())) + .fetchOne(); + } + if (row == null) { + row = + dsl.selectFrom(ASSOCIATION) + .where(LAUNCH_BINDING_OPERATION_ID.eq(claim.launchBindingOperationId())) + .fetchOne(); + } + return row; + } + + private Record findByCanonicalGameInstance(UUID canonicalGameInstanceId) { + return dsl.selectFrom(ASSOCIATION) + .where(CANONICAL_GAME_INSTANCE_ID.eq(canonicalGameInstanceId)) + .fetchOne(); + } + + private static String writeJson(Object value) { + try { + return CLOSED_JSON.writeValueAsString(value); + } catch (Exception exception) { + throw new InvalidAssociationEvidenceException( + "Immutable World owner evidence could not be encoded for exact comparison", exception); + } + } + + private static T required(Record row, Field field) { + return Objects.requireNonNull(row.get(field), "Persisted " + field.getName() + " is null"); + } + + private static Field field(String name, Class type) { + return DSL.field(DSL.name(name), type); + } + + private static void requireNoActiveTransaction(String label) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException(label + " requires an independent committed owner read"); + } + } + + private void requireReadOnlyRepeatableReadOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World canonical association snapshot read requires a read-only REPEATABLE READ owner transaction"); + } + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + if (!"repeatable read".equals(state.get("isolation", String.class)) + || !"on".equals(state.get("read_only", String.class))) { + throw new IllegalStateException( + "World canonical association snapshot read requires a read-only REPEATABLE READ owner transaction"); + } + } + + private void requireWritableActivationTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World canonical association activation read requires a writable READ COMMITTED owner transaction"); + } + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + if (!"read committed".equals(state.get("isolation", String.class)) + || !"off".equals(state.get("read_only", String.class))) { + throw new IllegalStateException( + "World canonical association activation read requires a writable READ COMMITTED owner transaction"); + } + } + + private static void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World canonical instance association requires an active World owner transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "World canonical instance association requires a writable owner transaction"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation == null || declaredIsolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "World canonical instance association requires READ COMMITTED isolation"); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + public static final class RegistrationConflictException extends IllegalStateException { + public RegistrationConflictException(String message) { + super(message); + } + } + + public static final class InvalidAssociationEvidenceException extends IllegalStateException { + public InvalidAssociationEvidenceException(String message) { + super(message); + } + + public InvalidAssociationEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/world-management-service/src/main/resources/db/migration/V1008__world_canonical_instance_association.sql b/services/world-management-service/src/main/resources/db/migration/V1008__world_canonical_instance_association.sql new file mode 100644 index 0000000000..d3e4459c95 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1008__world_canonical_instance_association.sql @@ -0,0 +1,506 @@ +-- Canonical creation identity is insert-born. Existing numeric lifecycle rows stay unmapped. +ALTER TABLE world_instance + ADD COLUMN canonical_game_instance_id UUID, + ADD COLUMN canonical_target_namespace VARCHAR(63), + ADD COLUMN canonical_tenant_id UUID, + ADD COLUMN canonical_world_slug VARCHAR(120), + ADD COLUMN playable_state_namespace_id UUID, + ADD COLUMN playable_state_scope VARCHAR(16), + ADD COLUMN public_production BOOLEAN, + ADD COLUMN playtest_lifecycle_id UUID, + ADD COLUMN playtest_state_generation BIGINT, + ADD COLUMN canonical_launch_binding_operation_id UUID; + +ALTER TABLE world_instance + ADD CONSTRAINT fk_world_instance_canonical_launch_binding + FOREIGN KEY (canonical_launch_binding_operation_id) + REFERENCES world_complete_launch_binding (binding_operation_id) + ON DELETE RESTRICT, + ADD CONSTRAINT uq_world_instance_canonical_game_instance + UNIQUE (canonical_game_instance_id), + ADD CONSTRAINT uq_world_instance_canonical_binding + UNIQUE (canonical_launch_binding_operation_id), + ADD CONSTRAINT uq_world_instance_canonical_association_fk + UNIQUE ( + id, + canonical_game_instance_id, + canonical_target_namespace, + canonical_tenant_id, + canonical_world_slug, + playable_state_namespace_id, + playable_state_scope, + public_production, + control_plane_request_id, + canonical_launch_binding_operation_id + ), + ADD CONSTRAINT ck_world_instance_canonical_creation_identity CHECK ( + ( + canonical_game_instance_id IS NULL + AND canonical_target_namespace IS NULL + AND canonical_tenant_id IS NULL + AND canonical_world_slug IS NULL + AND playable_state_namespace_id IS NULL + AND playable_state_scope IS NULL + AND public_production IS NULL + AND playtest_lifecycle_id IS NULL + AND playtest_state_generation IS NULL + AND canonical_launch_binding_operation_id IS NULL + ) + OR + ( + canonical_game_instance_id IS NOT NULL + AND canonical_target_namespace IS NOT NULL + AND canonical_tenant_id IS NOT NULL + AND canonical_world_slug IS NOT NULL + AND playable_state_namespace_id IS NOT NULL + AND playable_state_scope IS NOT NULL + AND public_production IS TRUE + AND canonical_launch_binding_operation_id IS NOT NULL + -- The current Game Session owner-read projection does not carry playtest identity. + -- This foundation therefore admits only SHARED, non-playtest creation rows. + AND playtest_lifecycle_id IS NULL + AND playtest_state_generation IS NULL + AND canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND octet_length(canonical_world_slug) BETWEEN 1 AND 120 + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND playable_state_scope = 'SHARED' + AND canonical_launch_binding_operation_id + <> '00000000-0000-0000-0000-000000000000'::UUID + ) + ); + +-- A canonical World version key must remain explicitly tied to its immutable UUID association. +ALTER TABLE world_authored_version_identity + ADD CONSTRAINT uq_world_authored_version_identity_instance_binding + UNIQUE ( + operation_id, + target_namespace, + canonical_tenant_id, + world_slug, + canonical_version_id, + local_tenant_key, + local_version_key + ); + +CREATE TABLE world_canonical_instance_association ( + schema_version SMALLINT NOT NULL, + canonical_game_instance_id UUID NOT NULL, + canonical_target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_world_slug VARCHAR(120) NOT NULL, + playable_state_namespace_id UUID NOT NULL, + playable_state_scope VARCHAR(16) NOT NULL, + public_production BOOLEAN NOT NULL, + playtest_lifecycle_id UUID, + playtest_state_generation BIGINT, + control_plane_request_id VARCHAR(128) NOT NULL, + world_instance_id BIGINT NOT NULL, + canonical_launch_binding_operation_id UUID NOT NULL, + version_identity_operation_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL, + private_game_instance_key BIGINT NOT NULL, + game_template_id BIGINT NOT NULL, + launch_descriptor_id VARCHAR(64) NOT NULL, + local_version_key BIGINT NOT NULL, + script_patch_version VARCHAR(100), + runtime_flags_json TEXT NOT NULL, + generation_config_revision VARCHAR(128) NOT NULL, + release_bundle_id BIGINT NOT NULL, + published_release_bundle_ref VARCHAR(128) NOT NULL, + version_state_epoch BIGINT NOT NULL, + remap_set_id VARCHAR(64), + intake_operation_id UUID NOT NULL, + intake_request_id UUID NOT NULL, + source_operation_id UUID NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL, + intake_request_digest VARCHAR(71) NOT NULL, + intake_receipt_digest VARCHAR(71) NOT NULL, + descriptor_request_digest VARCHAR(71) NOT NULL, + descriptor_result_digest VARCHAR(71) NOT NULL, + release_attestation_digest VARCHAR(71) NOT NULL, + CONSTRAINT pk_world_canonical_instance_association + PRIMARY KEY (canonical_game_instance_id), + CONSTRAINT uq_world_canonical_instance_association_scoped + UNIQUE ( + canonical_target_namespace, + canonical_tenant_id, + canonical_world_slug, + playable_state_namespace_id, + playable_state_scope, + canonical_game_instance_id + ), + CONSTRAINT uq_world_canonical_instance_association_request + UNIQUE (canonical_target_namespace, canonical_tenant_id, control_plane_request_id), + CONSTRAINT uq_world_canonical_instance_association_row UNIQUE (world_instance_id), + CONSTRAINT uq_world_canonical_instance_association_binding + UNIQUE (canonical_launch_binding_operation_id), + CONSTRAINT fk_world_canonical_instance_association_world_row + FOREIGN KEY ( + world_instance_id, + canonical_game_instance_id, + canonical_target_namespace, + canonical_tenant_id, + canonical_world_slug, + playable_state_namespace_id, + playable_state_scope, + public_production, + control_plane_request_id, + canonical_launch_binding_operation_id + ) REFERENCES world_instance ( + id, + canonical_game_instance_id, + canonical_target_namespace, + canonical_tenant_id, + canonical_world_slug, + playable_state_namespace_id, + playable_state_scope, + public_production, + control_plane_request_id, + canonical_launch_binding_operation_id + ) ON DELETE RESTRICT, + CONSTRAINT fk_world_canonical_instance_association_launch_binding + FOREIGN KEY (canonical_launch_binding_operation_id) + REFERENCES world_complete_launch_binding (binding_operation_id) + ON DELETE RESTRICT, + CONSTRAINT fk_world_canonical_instance_association_version_identity + FOREIGN KEY ( + version_identity_operation_id, + canonical_target_namespace, + canonical_tenant_id, + canonical_world_slug, + canonical_version_id, + local_tenant_key, + local_version_key + ) REFERENCES world_authored_version_identity ( + operation_id, + target_namespace, + canonical_tenant_id, + world_slug, + canonical_version_id, + local_tenant_key, + local_version_key + ) ON DELETE RESTRICT, + CONSTRAINT ck_world_canonical_instance_association_schema + CHECK (schema_version = 1), + CONSTRAINT ck_world_canonical_instance_association_ids CHECK ( + canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_launch_binding_operation_id + <> '00000000-0000-0000-0000-000000000000'::UUID + AND version_identity_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT ck_world_canonical_instance_association_scope CHECK ( + canonical_target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + AND canonical_world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND octet_length(canonical_world_slug) BETWEEN 1 AND 120 + AND playable_state_scope = 'SHARED' + AND public_production IS TRUE + AND length(btrim(control_plane_request_id)) BETWEEN 1 AND 128 + AND playtest_lifecycle_id IS NULL + AND playtest_state_generation IS NULL + ), + CONSTRAINT ck_world_canonical_instance_association_owner_keys CHECK ( + world_instance_id > 0 + AND local_tenant_key > 0 + AND private_game_instance_key > 0 + AND game_template_id > 0 + AND local_version_key > 0 + AND release_bundle_id > 0 + AND version_state_epoch > 0 + AND length(btrim(launch_descriptor_id)) BETWEEN 1 AND 64 + AND length(btrim(runtime_flags_json)) > 0 + AND length(btrim(generation_config_revision)) BETWEEN 1 AND 128 + AND length(btrim(published_release_bundle_ref)) BETWEEN 1 AND 128 + AND (script_patch_version IS NULL OR length(btrim(script_patch_version)) BETWEEN 1 AND 100) + AND (remap_set_id IS NULL OR length(btrim(remap_set_id)) BETWEEN 1 AND 64) + ), + CONSTRAINT ck_world_canonical_instance_association_digests CHECK ( + source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND intake_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND intake_receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND descriptor_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND descriptor_result_digest ~ '^sha256:[0-9a-f]{64}$' + AND release_attestation_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +-- [jooq ignore start] +CREATE FUNCTION world_validate_canonical_prepare_identity() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + binding world_complete_launch_binding%ROWTYPE; + version_identity world_authored_version_identity%ROWTYPE; + descriptor JSONB; + release_attestation JSONB; +BEGIN + IF TG_OP = 'DELETE' THEN + IF OLD.canonical_game_instance_id IS NOT NULL THEN + RAISE EXCEPTION 'Canonical World instance creation identity is retained' + USING ERRCODE = '55000'; + END IF; + RETURN OLD; + END IF; + + IF TG_OP = 'UPDATE' THEN + IF OLD.canonical_game_instance_id IS NULL THEN + IF NEW.canonical_game_instance_id IS NOT NULL + OR NEW.canonical_target_namespace IS NOT NULL + OR NEW.canonical_tenant_id IS NOT NULL + OR NEW.canonical_world_slug IS NOT NULL + OR NEW.playable_state_namespace_id IS NOT NULL + OR NEW.playable_state_scope IS NOT NULL + OR NEW.public_production IS NOT NULL + OR NEW.playtest_lifecycle_id IS NOT NULL + OR NEW.playtest_state_generation IS NOT NULL + OR NEW.canonical_launch_binding_operation_id IS NOT NULL THEN + RAISE EXCEPTION 'A retained World instance cannot acquire canonical creation identity' + USING ERRCODE = '55000'; + END IF; + RETURN NEW; + END IF; + + IF OLD.id IS DISTINCT FROM NEW.id + OR OLD.tenant_id IS DISTINCT FROM NEW.tenant_id + OR OLD.game_instance_id IS DISTINCT FROM NEW.game_instance_id + OR OLD.game_template_id IS DISTINCT FROM NEW.game_template_id + OR OLD.control_plane_request_id IS DISTINCT FROM NEW.control_plane_request_id + OR OLD.launch_descriptor_id IS DISTINCT FROM NEW.launch_descriptor_id + OR OLD.version_id IS DISTINCT FROM NEW.version_id + OR OLD.script_patch_version IS DISTINCT FROM NEW.script_patch_version + OR OLD.runtime_flags_json IS DISTINCT FROM NEW.runtime_flags_json + OR OLD.generation_config_revision IS DISTINCT FROM NEW.generation_config_revision + OR OLD.release_bundle_id IS DISTINCT FROM NEW.release_bundle_id + OR OLD.published_release_bundle_ref IS DISTINCT FROM NEW.published_release_bundle_ref + OR OLD.version_state_epoch IS DISTINCT FROM NEW.version_state_epoch + OR OLD.remap_set_id IS DISTINCT FROM NEW.remap_set_id + OR OLD.canonical_game_instance_id IS DISTINCT FROM NEW.canonical_game_instance_id + OR OLD.canonical_target_namespace IS DISTINCT FROM NEW.canonical_target_namespace + OR OLD.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR OLD.canonical_world_slug IS DISTINCT FROM NEW.canonical_world_slug + OR OLD.playable_state_namespace_id IS DISTINCT FROM NEW.playable_state_namespace_id + OR OLD.playable_state_scope IS DISTINCT FROM NEW.playable_state_scope + OR OLD.public_production IS DISTINCT FROM NEW.public_production + OR OLD.playtest_lifecycle_id IS DISTINCT FROM NEW.playtest_lifecycle_id + OR OLD.playtest_state_generation IS DISTINCT FROM NEW.playtest_state_generation + OR OLD.canonical_launch_binding_operation_id + IS DISTINCT FROM NEW.canonical_launch_binding_operation_id THEN + RAISE EXCEPTION 'Canonical World instance creation and prepare inputs are immutable' + USING ERRCODE = '55000'; + END IF; + RETURN NEW; + END IF; + + IF NEW.canonical_game_instance_id IS NULL THEN + RETURN NEW; + END IF; + + SELECT * INTO binding + FROM world_complete_launch_binding + WHERE binding_operation_id = NEW.canonical_launch_binding_operation_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Canonical World instance requires its exact retained launch binding' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO version_identity + FROM world_authored_version_identity + WHERE target_namespace = NEW.canonical_target_namespace + AND canonical_tenant_id = NEW.canonical_tenant_id + AND world_slug = NEW.canonical_world_slug + AND canonical_version_id = binding.canonical_version_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Canonical World instance requires its exact UUID-to-private-Version association' + USING ERRCODE = '23514'; + END IF; + + descriptor := binding.descriptor_json::jsonb; + release_attestation := binding.release_attestation_json::jsonb; + IF binding.target_namespace IS DISTINCT FROM NEW.canonical_target_namespace + OR binding.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR binding.world_slug IS DISTINCT FROM NEW.canonical_world_slug + OR binding.control_plane_request_id IS DISTINCT FROM NEW.control_plane_request_id + OR binding.local_tenant_key IS DISTINCT FROM NEW.tenant_id + OR version_identity.intake_operation_id IS DISTINCT FROM binding.intake_operation_id + OR version_identity.intake_request_id IS DISTINCT FROM binding.intake_request_id + OR version_identity.intake_request_digest IS DISTINCT FROM ( + SELECT request_digest FROM world_authored_source_intake + WHERE operation_id = binding.intake_operation_id + ) + OR version_identity.source_operation_id IS DISTINCT FROM binding.source_operation_id + OR version_identity.source_evidence_digest IS DISTINCT FROM binding.source_evidence_digest + OR version_identity.intake_receipt_digest IS DISTINCT FROM binding.intake_receipt_digest + OR version_identity.local_tenant_key IS DISTINCT FROM NEW.tenant_id + OR version_identity.local_version_key IS DISTINCT FROM NEW.version_id + OR version_identity.canonical_version_id IS DISTINCT FROM binding.canonical_version_id + OR version_identity.game_design_version_id::text IS DISTINCT FROM descriptor->>'versionId' + OR descriptor->>'targetNamespace' IS DISTINCT FROM NEW.canonical_target_namespace + OR descriptor->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::text + OR descriptor->>'worldSlug' IS DISTINCT FROM NEW.canonical_world_slug + OR descriptor->>'controlPlaneRequestId' IS DISTINCT FROM NEW.control_plane_request_id + OR descriptor->>'authoredWorldSourceOperationId' + IS DISTINCT FROM binding.source_operation_id::text + OR descriptor->>'authoredWorldSourceEvidenceDigest' + IS DISTINCT FROM binding.source_evidence_digest + OR descriptor->>'requestDigest' IS DISTINCT FROM binding.descriptor_request_digest + OR descriptor->>'resultDigest' IS DISTINCT FROM binding.descriptor_result_digest + OR descriptor->>'launchDescriptorId' IS DISTINCT FROM NEW.launch_descriptor_id + OR descriptor->>'gameTemplateId' IS DISTINCT FROM NEW.game_template_id::text + OR descriptor->>'runtimeFlagsJson' IS DISTINCT FROM NEW.runtime_flags_json + OR descriptor->>'generationConfigRevision' IS DISTINCT FROM NEW.generation_config_revision + OR descriptor->>'releaseBundleId' IS DISTINCT FROM NEW.release_bundle_id::text + OR descriptor->>'publishedReleaseBundleRef' IS DISTINCT FROM NEW.published_release_bundle_ref + OR descriptor->>'versionStateEpoch' IS DISTINCT FROM NEW.version_state_epoch::text + OR ( + CASE WHEN descriptor->>'scriptPatchVersionPresent' = 'true' + THEN descriptor->>'scriptPatchVersion' + ELSE NULL + END + ) IS DISTINCT FROM NEW.script_patch_version + OR ( + CASE WHEN descriptor->>'remapSetIdPresent' = 'true' + THEN descriptor->>'remapSetId' + ELSE NULL + END + ) IS DISTINCT FROM NEW.remap_set_id + OR release_attestation->>'targetNamespace' IS DISTINCT FROM NEW.canonical_target_namespace + OR release_attestation->>'descriptorResultDigest' + IS DISTINCT FROM binding.descriptor_result_digest + OR release_attestation->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::text + OR release_attestation->>'canonicalVersionId' IS DISTINCT FROM binding.canonical_version_id::text + OR release_attestation->>'worldSlug' IS DISTINCT FROM NEW.canonical_world_slug + OR release_attestation->>'authoredWorldSourceOperationId' + IS DISTINCT FROM binding.source_operation_id::text + OR release_attestation->>'authoredWorldSourceEvidenceDigest' + IS DISTINCT FROM binding.source_evidence_digest + OR release_attestation->>'launchDescriptorId' IS DISTINCT FROM NEW.launch_descriptor_id + OR release_attestation->>'publishedReleaseBundleRef' + IS DISTINCT FROM NEW.published_release_bundle_ref + OR release_attestation->>'versionStateEpoch' IS DISTINCT FROM NEW.version_state_epoch::text + OR release_attestation->>'generationConfigRevision' + IS DISTINCT FROM NEW.generation_config_revision + OR release_attestation->>'evidenceDigest' IS DISTINCT FROM binding.release_attestation_digest THEN + RAISE EXCEPTION 'Canonical World instance prepare fields differ from immutable launch/source history' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_world_instance_canonical_prepare_identity + BEFORE INSERT OR UPDATE OR DELETE ON world_instance + FOR EACH ROW EXECUTE FUNCTION world_validate_canonical_prepare_identity(); + +CREATE FUNCTION world_validate_canonical_instance_association() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + instance world_instance%ROWTYPE; + binding world_complete_launch_binding%ROWTYPE; + version_identity world_authored_version_identity%ROWTYPE; +BEGIN + SELECT * INTO instance FROM world_instance WHERE id = NEW.world_instance_id FOR KEY SHARE; + IF NOT FOUND OR instance.canonical_game_instance_id IS NULL THEN + RAISE EXCEPTION 'Canonical instance association requires an insert-born canonical World row' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO binding + FROM world_complete_launch_binding + WHERE binding_operation_id = NEW.canonical_launch_binding_operation_id; + SELECT * INTO version_identity + FROM world_authored_version_identity + WHERE operation_id = NEW.version_identity_operation_id; + + IF NOT FOUND + OR instance.canonical_game_instance_id IS DISTINCT FROM NEW.canonical_game_instance_id + OR instance.canonical_target_namespace IS DISTINCT FROM NEW.canonical_target_namespace + OR instance.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR instance.canonical_world_slug IS DISTINCT FROM NEW.canonical_world_slug + OR instance.playable_state_namespace_id IS DISTINCT FROM NEW.playable_state_namespace_id + OR instance.playable_state_scope IS DISTINCT FROM NEW.playable_state_scope + OR instance.public_production IS DISTINCT FROM NEW.public_production + OR instance.playtest_lifecycle_id IS DISTINCT FROM NEW.playtest_lifecycle_id + OR instance.playtest_state_generation IS DISTINCT FROM NEW.playtest_state_generation + OR instance.control_plane_request_id IS DISTINCT FROM NEW.control_plane_request_id + OR instance.canonical_launch_binding_operation_id + IS DISTINCT FROM NEW.canonical_launch_binding_operation_id + OR instance.tenant_id IS DISTINCT FROM NEW.local_tenant_key + OR instance.game_instance_id IS DISTINCT FROM NEW.private_game_instance_key + OR instance.game_template_id IS DISTINCT FROM NEW.game_template_id + OR instance.launch_descriptor_id IS DISTINCT FROM NEW.launch_descriptor_id + OR instance.version_id IS DISTINCT FROM NEW.local_version_key + OR instance.script_patch_version IS DISTINCT FROM NEW.script_patch_version + OR instance.runtime_flags_json IS DISTINCT FROM NEW.runtime_flags_json + OR instance.generation_config_revision IS DISTINCT FROM NEW.generation_config_revision + OR instance.release_bundle_id IS DISTINCT FROM NEW.release_bundle_id + OR instance.published_release_bundle_ref IS DISTINCT FROM NEW.published_release_bundle_ref + OR instance.version_state_epoch IS DISTINCT FROM NEW.version_state_epoch + OR instance.remap_set_id IS DISTINCT FROM NEW.remap_set_id + OR binding.target_namespace IS DISTINCT FROM NEW.canonical_target_namespace + OR binding.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR binding.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR binding.world_slug IS DISTINCT FROM NEW.canonical_world_slug + OR binding.control_plane_request_id IS DISTINCT FROM NEW.control_plane_request_id + OR binding.intake_operation_id IS DISTINCT FROM NEW.intake_operation_id + OR binding.intake_request_id IS DISTINCT FROM NEW.intake_request_id + OR binding.local_tenant_key IS DISTINCT FROM NEW.local_tenant_key + OR binding.source_operation_id IS DISTINCT FROM NEW.source_operation_id + OR binding.source_evidence_digest IS DISTINCT FROM NEW.source_evidence_digest + OR binding.intake_receipt_digest IS DISTINCT FROM NEW.intake_receipt_digest + OR binding.descriptor_request_digest IS DISTINCT FROM NEW.descriptor_request_digest + OR binding.descriptor_result_digest IS DISTINCT FROM NEW.descriptor_result_digest + OR binding.release_attestation_digest IS DISTINCT FROM NEW.release_attestation_digest + OR version_identity.target_namespace IS DISTINCT FROM NEW.canonical_target_namespace + OR version_identity.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR version_identity.world_slug IS DISTINCT FROM NEW.canonical_world_slug + OR version_identity.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR version_identity.local_tenant_key IS DISTINCT FROM NEW.local_tenant_key + OR version_identity.local_version_key IS DISTINCT FROM NEW.local_version_key + OR version_identity.intake_operation_id IS DISTINCT FROM binding.intake_operation_id + OR version_identity.intake_request_id IS DISTINCT FROM binding.intake_request_id + OR version_identity.source_operation_id IS DISTINCT FROM binding.source_operation_id + OR version_identity.source_evidence_digest IS DISTINCT FROM binding.source_evidence_digest + OR version_identity.intake_receipt_digest IS DISTINCT FROM binding.intake_receipt_digest THEN + RAISE EXCEPTION 'Canonical instance association differs from exact owner creation, source, Version, or release rows' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_world_canonical_instance_association_exact_insert + BEFORE INSERT ON world_canonical_instance_association + FOR EACH ROW EXECUTE FUNCTION world_validate_canonical_instance_association(); + +CREATE TRIGGER trg_world_canonical_instance_association_immutable + BEFORE UPDATE OR DELETE ON world_canonical_instance_association + FOR EACH ROW EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE TRIGGER trg_world_canonical_instance_association_no_truncate + BEFORE TRUNCATE ON world_canonical_instance_association + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE FUNCTION world_reject_canonical_world_instance_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'World instance creation identity cannot be truncated' + USING ERRCODE = '55000'; +END; +$$; + +CREATE TRIGGER trg_world_instance_canonical_no_truncate + BEFORE TRUNCATE ON world_instance + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_canonical_world_instance_truncate(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1009.1__world_restore_stable_legacy_update_fastpath.sql b/services/world-management-service/src/main/resources/db/migration/V1009.1__world_restore_stable_legacy_update_fastpath.sql new file mode 100644 index 0000000000..857713fa03 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1009.1__world_restore_stable_legacy_update_fastpath.sql @@ -0,0 +1,26 @@ +-- Restore installed V27.2 stable same-tenant legacy UPDATE behavior immediately after V1009. +-- Canonical mutations and DELETE retain their exact guarded branches before this fastpath. +-- [jooq ignore start] +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; + INSERT INTO "${serviceSchema}".world_authored_source_tenant_key_reservation AS reservation$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_claim_legacy_numeric_tenant_key()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,anchor,'')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact V1009 legacy reservation claim anchor'; + END IF; + original := replace(original, anchor, $replacement$ IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; + IF TG_OP = 'UPDATE' AND OLD.tenant_id = NEW.tenant_id + AND EXISTS (SELECT 1 FROM "${serviceSchema}".world_authored_source_tenant_key_reservation retained + WHERE retained.tenant_key = NEW.tenant_id AND retained.claim_kind = 'LEGACY_NUMERIC') THEN + RETURN NEW; + END IF; + INSERT INTO "${serviceSchema}".world_authored_source_tenant_key_reservation AS reservation$replacement$); + EXECUTE original; +END; +$migration$; + +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1009__world_guarded_canonical_instance_preparation.sql b/services/world-management-service/src/main/resources/db/migration/V1009__world_guarded_canonical_instance_preparation.sql new file mode 100644 index 0000000000..dc71fa0d17 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1009__world_guarded_canonical_instance_preparation.sql @@ -0,0 +1,858 @@ +-- Canonical preparation is an insert-born, owner-private materialization boundary. The existing +-- V24 reserved-tenant guard remains closed except for exact single-use rows emitted below. +ALTER TABLE region_instance ADD COLUMN canonical_region_instance_id UUID; +ALTER TABLE zone_instance ADD COLUMN canonical_zone_instance_id UUID; +CREATE UNIQUE INDEX uq_region_instance_canonical_runtime_id + ON region_instance (canonical_region_instance_id) + WHERE canonical_region_instance_id IS NOT NULL; +CREATE UNIQUE INDEX uq_zone_instance_canonical_runtime_id + ON zone_instance (canonical_zone_instance_id) + WHERE canonical_zone_instance_id IS NOT NULL; + +CREATE SEQUENCE world_canonical_private_game_instance_key_seq AS BIGINT MINVALUE 1; +SELECT setval( + 'world_canonical_private_game_instance_key_seq'::REGCLASS, + coalesce(max(game_instance_id), 0) + 1, + FALSE) +FROM world_instance; + +CREATE TABLE world_canonical_instance_preparation_execution_manifest ( + transaction_id BIGINT NOT NULL, + table_name VARCHAR(64) NOT NULL, + row_id BIGINT NOT NULL, + canonical_game_instance_id UUID NOT NULL, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + version_identity_operation_id UUID NOT NULL, + capture_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL, + input_digest VARCHAR(71) NOT NULL, + expected_new JSONB NOT NULL, + PRIMARY KEY (transaction_id, table_name, row_id), + CHECK (table_name IN ( + 'world_instance', 'region_instance', 'zone_instance', 'room_instance', + 'room_instance_exit', 'world_canonical_instance_topology_identity', + 'world_canonical_instance_preparation')), + CHECK (canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (version_identity_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (capture_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (local_tenant_key > 0), + CHECK (input_digest ~ '^sha256:[0-9a-f]{64}$') +); + +CREATE TABLE world_canonical_instance_topology_identity ( + id BIGSERIAL PRIMARY KEY, + world_instance_id BIGINT NOT NULL REFERENCES world_instance(id) ON DELETE RESTRICT, + canonical_game_instance_id UUID NOT NULL, + family VARCHAR(32) NOT NULL CHECK (family IN ('REGION', 'ZONE', 'ROOM', 'ROOM_EXIT')), + template_id UUID NOT NULL CHECK (template_id <> '00000000-0000-0000-0000-000000000000'::UUID), + template_private_row_key BIGINT NOT NULL CHECK (template_private_row_key > 0), + runtime_row_id BIGINT NOT NULL CHECK (runtime_row_id > 0), + runtime_identity UUID, + runtime_room_instance_id BIGINT, + UNIQUE (world_instance_id, family, template_id), + UNIQUE (family, runtime_row_id), + FOREIGN KEY (canonical_game_instance_id) REFERENCES world_instance(canonical_game_instance_id) + ON DELETE RESTRICT, + CHECK ( + (family = 'REGION' AND runtime_identity IS NOT NULL AND runtime_room_instance_id IS NULL) + OR (family = 'ZONE' AND runtime_identity IS NOT NULL AND runtime_room_instance_id IS NULL) + OR (family = 'ROOM' AND runtime_identity IS NULL AND runtime_room_instance_id > 0) + OR (family = 'ROOM_EXIT' AND runtime_identity IS NULL AND runtime_room_instance_id IS NULL) + ) +); +CREATE INDEX idx_world_canonical_instance_topology_world + ON world_canonical_instance_topology_identity(world_instance_id, family, id); + +CREATE TABLE world_canonical_instance_preparation ( + id BIGSERIAL PRIMARY KEY, + canonical_game_instance_id UUID NOT NULL UNIQUE, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + world_slug VARCHAR(120) NOT NULL, + control_plane_request_id VARCHAR(128) NOT NULL, + canonical_version_id UUID NOT NULL, + version_identity_operation_id UUID NOT NULL, + capture_id UUID NOT NULL REFERENCES world_canonical_frozen_topology(capture_id) ON DELETE RESTRICT, + graph_bytes BYTEA NOT NULL CHECK (octet_length(graph_bytes) > 0), + graph_sha256 VARCHAR(64) NOT NULL CHECK (graph_sha256 ~ '^[0-9a-f]{64}$'), + input_digest VARCHAR(71) NOT NULL CHECK (input_digest ~ '^sha256:[0-9a-f]{64}$'), + input_json TEXT NOT NULL CHECK (length(input_json) > 0), + world_instance_id BIGINT NOT NULL UNIQUE REFERENCES world_instance(id) ON DELETE RESTRICT, + private_game_instance_key BIGINT NOT NULL CHECK (private_game_instance_key > 0), + region_count INTEGER NOT NULL CHECK (region_count > 0), + zone_count INTEGER NOT NULL CHECK (zone_count >= 0), + room_count INTEGER NOT NULL CHECK (room_count >= 0), + exit_count INTEGER NOT NULL CHECK (exit_count >= 0), + storage_status VARCHAR(32) NOT NULL CHECK (storage_status = 'MATERIALIZED_UNVERIFIED'), + prepared_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE (target_namespace, canonical_tenant_id, control_plane_request_id), + FOREIGN KEY (version_identity_operation_id) + REFERENCES world_authored_version_identity(operation_id) ON DELETE RESTRICT, + FOREIGN KEY (canonical_game_instance_id) + REFERENCES world_canonical_instance_association(canonical_game_instance_id) + DEFERRABLE INITIALLY DEFERRED +); + +-- [jooq ignore start] +REVOKE ALL ON world_canonical_instance_preparation_execution_manifest FROM PUBLIC; + +CREATE FUNCTION world_consume_canonical_prepare_execution_manifest( + actual_table TEXT, actual_operation TEXT, actual_old JSONB, actual_new JSONB +) RETURNS BOOLEAN +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + consumed BIGINT; +BEGIN + IF actual_operation <> 'INSERT' OR actual_old IS NOT NULL OR actual_new IS NULL THEN + RETURN FALSE; + END IF; + DELETE FROM "${serviceSchema}".world_canonical_instance_preparation_execution_manifest m + USING "${serviceSchema}".world_authored_version_identity v, + "${serviceSchema}".world_canonical_frozen_topology f, + "${serviceSchema}".world_authored_source_tenant_key_reservation r + WHERE m.transaction_id = txid_current() + AND m.table_name = actual_table + AND m.row_id = (actual_new->>'id')::BIGINT + AND m.expected_new = actual_new + AND v.operation_id = m.version_identity_operation_id + AND v.target_namespace = m.target_namespace + AND v.canonical_tenant_id = m.canonical_tenant_id + AND v.canonical_version_id = m.canonical_version_id + AND v.local_tenant_key = m.local_tenant_key + AND f.capture_id = m.capture_id + AND f.version_identity_operation_id = v.operation_id + AND f.capture_status = 'CAPTURED_UNVERIFIED' + AND r.tenant_key = m.local_tenant_key + AND r.claim_kind = 'CANONICAL_AUTHORED_SOURCE' + AND ( + (actual_table = 'world_instance' + AND actual_new->>'canonical_game_instance_id' = m.canonical_game_instance_id::TEXT + AND actual_new->>'canonical_target_namespace' = m.target_namespace + AND actual_new->>'canonical_tenant_id' = m.canonical_tenant_id::TEXT + AND actual_new->>'tenant_id' = m.local_tenant_key::TEXT) + OR (actual_table IN ('region_instance', 'zone_instance', 'room_instance', 'room_instance_exit') + AND actual_new->>'tenant_id' = m.local_tenant_key::TEXT + AND EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_instance wi + WHERE wi.canonical_game_instance_id = m.canonical_game_instance_id + AND wi.tenant_id = m.local_tenant_key + AND wi.game_instance_id = (actual_new->>'game_instance_id')::BIGINT + AND wi.canonical_target_namespace = m.target_namespace + AND wi.canonical_tenant_id = m.canonical_tenant_id)) + OR (actual_table IN ('world_canonical_instance_topology_identity', 'world_canonical_instance_preparation') + AND actual_new->>'canonical_game_instance_id' = m.canonical_game_instance_id::TEXT + AND EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_instance wi + WHERE wi.id = (actual_new->>'world_instance_id')::BIGINT + AND wi.canonical_game_instance_id = m.canonical_game_instance_id + AND wi.tenant_id = m.local_tenant_key + AND wi.canonical_target_namespace = m.target_namespace + AND wi.canonical_tenant_id = m.canonical_tenant_id)) + ) + RETURNING m.row_id INTO consumed; + RETURN consumed IS NOT NULL; +END; +$$; +REVOKE ALL ON FUNCTION world_consume_canonical_prepare_execution_manifest(TEXT, TEXT, JSONB, JSONB) + FROM PUBLIC; + +-- V24's reserved-source denial is preserved. Only V29's existing exact draft manifest and this +-- V35 exact insert manifest may consume a canonical tenant mutation; legacy tenants retain the +-- original numeric reservation behavior. +CREATE OR REPLACE FUNCTION world_claim_legacy_numeric_tenant_key() +RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + claimed_key BIGINT; + old_row JSONB; + new_row JSONB; + canonical_old BOOLEAN := FALSE; + canonical_new BOOLEAN := FALSE; +BEGIN + IF TG_OP <> 'INSERT' THEN + old_row := to_jsonb(OLD); + SELECT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_authored_source_tenant_key_reservation + WHERE tenant_key = OLD.tenant_id AND claim_kind = 'CANONICAL_AUTHORED_SOURCE') + INTO canonical_old; + END IF; + IF TG_OP <> 'DELETE' THEN + new_row := to_jsonb(NEW); + SELECT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_authored_source_tenant_key_reservation + WHERE tenant_key = NEW.tenant_id AND claim_kind = 'CANONICAL_AUTHORED_SOURCE') + INTO canonical_new; + END IF; + IF canonical_old OR canonical_new THEN + IF TG_TABLE_SCHEMA = '${serviceSchema}' + AND "${serviceSchema}".world_consume_region_execution_manifest( + TG_TABLE_NAME, TG_OP, old_row, new_row) THEN + RETURN NEW; + END IF; + IF TG_TABLE_SCHEMA = '${serviceSchema}' + AND "${serviceSchema}".world_consume_canonical_prepare_execution_manifest( + TG_TABLE_NAME, TG_OP, old_row, new_row) THEN + RETURN NEW; + END IF; + RAISE EXCEPTION + 'World tenant key is reserved for a canonical authored source; no exact transaction execution manifest' + USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; + INSERT INTO "${serviceSchema}".world_authored_source_tenant_key_reservation AS reservation + (tenant_key, claim_kind) VALUES (NEW.tenant_id, 'LEGACY_NUMERIC') + ON CONFLICT (tenant_key) DO UPDATE SET tenant_key = EXCLUDED.tenant_key + WHERE reservation.claim_kind = 'LEGACY_NUMERIC' + RETURNING reservation.tenant_key INTO claimed_key; + IF claimed_key IS NULL THEN + RAISE EXCEPTION 'World tenant key % is reserved for a canonical authored source', NEW.tenant_id + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION world_validate_canonical_preparation_row() +RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + consumed BOOLEAN; +BEGIN + IF TG_OP = 'INSERT' THEN + consumed := "${serviceSchema}".world_consume_canonical_prepare_execution_manifest( + TG_TABLE_NAME, TG_OP, NULL, to_jsonb(NEW)); + IF consumed THEN RETURN NEW; END IF; + RAISE EXCEPTION 'Canonical topology/preparation rows require the exact V35 owner operation' + USING ERRCODE = '23514'; + END IF; + RAISE EXCEPTION 'Canonical topology/preparation history is immutable' + USING ERRCODE = '55000'; +END; +$$; +CREATE TRIGGER trg_world_canonical_instance_topology_identity_exact_insert + BEFORE INSERT OR UPDATE OR DELETE ON world_canonical_instance_topology_identity + FOR EACH ROW EXECUTE FUNCTION world_validate_canonical_preparation_row(); +CREATE TRIGGER trg_world_canonical_instance_topology_identity_no_truncate + BEFORE TRUNCATE ON world_canonical_instance_topology_identity + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +CREATE TRIGGER trg_world_canonical_instance_preparation_exact_insert + BEFORE INSERT OR UPDATE OR DELETE ON world_canonical_instance_preparation + FOR EACH ROW EXECUTE FUNCTION world_validate_canonical_preparation_row(); +CREATE TRIGGER trg_world_canonical_instance_preparation_no_truncate + BEFORE TRUNCATE ON world_canonical_instance_preparation + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +-- Exact insert-only materialization. Configured generation and spawn intent are rejected before +-- any sequence allocation or write. All parent and template selectors come from typed, exact +-- UUID-to-private-key mappings committed by V30; no numeric/UUID inference occurs here. +CREATE FUNCTION world_prepare_canonical_instance(p_input_json TEXT, p_input_digest TEXT) +RETURNS TABLE(world_instance_id BIGINT, private_game_instance_key BIGINT) +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + p JSONB; + ident JSONB; + gs_request JSONB; + gs_evidence JSONB; + launch JSONB; + version_input JSONB; + topology JSONB; + source_input JSONB; + source_evidence_input JSONB; + identity_row "${serviceSchema}".world_authored_version_identity%ROWTYPE; + binding_row "${serviceSchema}".world_complete_launch_binding%ROWTYPE; + intake_row "${serviceSchema}".world_authored_source_intake%ROWTYPE; + capture_row "${serviceSchema}".world_canonical_frozen_topology%ROWTYPE; + publication_owner "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + prior "${serviceSchema}".world_canonical_instance_preparation%ROWTYPE; + world_row "${serviceSchema}".world_instance%ROWTYPE; + region_runtime "${serviceSchema}".region_instance%ROWTYPE; + zone_runtime "${serviceSchema}".zone_instance%ROWTYPE; + room_runtime "${serviceSchema}".room_instance%ROWTYPE; + exit_runtime "${serviceSchema}".room_instance_exit%ROWTYPE; + topology_identity "${serviceSchema}".world_canonical_instance_topology_identity%ROWTYPE; + preparation_row "${serviceSchema}".world_canonical_instance_preparation%ROWTYPE; + source_region RECORD; + source_zone RECORD; + source_room RECORD; + source_exit RECORD; + parent_row RECORD; + other_row RECORD; + full_row JSONB; + template_count BIGINT; + region_count BIGINT; + zone_count BIGINT; + room_count BIGINT; + exit_count BIGINT; + generation_count BIGINT; + spawn_count BIGINT; + local_game_instance_key BIGINT; + runtime_id BIGINT; + runtime_uuid UUID; + new_world_instance_id BIGINT; + new_result_id BIGINT; +BEGIN + IF current_setting('transaction_isolation') <> 'read committed' + OR current_setting('transaction_read_only') <> 'off' THEN + RAISE EXCEPTION 'Canonical preparation requires writable READ COMMITTED' + USING ERRCODE = '23514'; + END IF; + IF p_input_json IS NULL OR length(p_input_json) = 0 OR p_input_digest IS NULL + OR p_input_digest !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Canonical preparation input/digest is malformed' USING ERRCODE = '23514'; + END IF; + p := p_input_json::JSONB; + IF p->>'schemaVersion' IS DISTINCT FROM '1' THEN + RAISE EXCEPTION 'Unsupported canonical preparation input schema' USING ERRCODE = '23514'; + END IF; + ident := p->'identity'; + gs_request := p->'gameSessionReadRequest'; + gs_evidence := p->'gameSessionReadEvidence'; + launch := p->'launchBinding'; + version_input := p->'versionIdentity'; + topology := p->'topology'; + source_input := p->'sourceIntake'; + source_evidence_input := source_input->'sourceEvidence'; + IF ident IS NULL OR gs_request IS NULL OR gs_evidence IS NULL + OR launch IS NULL OR version_input IS NULL OR topology IS NULL + OR source_input IS NULL OR jsonb_typeof(source_input) IS DISTINCT FROM 'object' + OR source_evidence_input IS NULL + OR jsonb_typeof(source_evidence_input) IS DISTINCT FROM 'object' + OR ident->>'publicProduction' IS DISTINCT FROM 'true' + OR ident->>'playableStateScope' IS DISTINCT FROM 'SHARED' + OR ident->>'canonicalGameInstanceId' IS DISTINCT FROM gs_request->>'canonicalGameInstanceId' + OR ident->>'canonicalGameInstanceId' IS DISTINCT FROM gs_evidence->>'canonicalGameInstanceId' + OR ident->>'targetNamespace' IS DISTINCT FROM gs_request->>'targetNamespace' + OR ident->>'canonicalTenantId' IS DISTINCT FROM gs_request->>'canonicalTenantId' + OR ident->>'worldSlug' IS DISTINCT FROM gs_request->>'worldSlug' + OR ident->>'controlPlaneRequestId' IS DISTINCT FROM gs_request->>'controlPlaneRequestId' + OR gs_request->>'launchDescriptorId' IS DISTINCT FROM gs_evidence->>'launchDescriptorId' + OR gs_request->>'expectedDescriptorRequestDigest' IS DISTINCT FROM gs_evidence->>'descriptorRequestDigest' + OR gs_request->>'expectedDescriptorResultDigest' IS DISTINCT FROM gs_evidence->>'descriptorResultDigest' + OR gs_request->>'expectedReleaseAttestationEvidenceDigest' + IS DISTINCT FROM gs_evidence->>'releaseAttestationEvidenceDigest' + OR ident->>'playableStateNamespaceId' IS DISTINCT FROM gs_evidence->>'playableStateNamespaceId' + OR ident->>'playableStateScope' IS DISTINCT FROM gs_evidence->>'playableStateScope' + OR ident->>'publicProduction' IS DISTINCT FROM gs_evidence->>'publicProduction' + OR ident->>'targetNamespace' IS DISTINCT FROM launch->>'targetNamespace' + OR ident->>'canonicalTenantId' IS DISTINCT FROM launch->>'canonicalTenantId' + OR ident->>'worldSlug' IS DISTINCT FROM launch->>'worldSlug' + OR ident->>'controlPlaneRequestId' IS DISTINCT FROM launch->>'controlPlaneRequestId' + OR ident->>'controlPlaneRequestId' IS DISTINCT FROM gs_request->>'controlPlaneRequestId' + OR topology->>'captureId' IS NULL + OR topology->>'planDigest' IS NULL + OR topology->>'planDigest' !~ '^sha256:[0-9a-f]{64}$' + OR jsonb_typeof(topology->'regionCount') IS DISTINCT FROM 'number' + OR jsonb_typeof(topology->'zoneCount') IS DISTINCT FROM 'number' + OR jsonb_typeof(topology->'roomCount') IS DISTINCT FROM 'number' + OR jsonb_typeof(topology->'exitCount') IS DISTINCT FROM 'number' + OR jsonb_typeof(topology->'generationRuleCount') IS DISTINCT FROM 'number' + OR jsonb_typeof(topology->'spawnBindingCount') IS DISTINCT FROM 'number' + OR (topology->>'regionCount')::BIGINT < 1 + OR (topology->>'zoneCount')::BIGINT < 0 + OR (topology->>'roomCount')::BIGINT < 0 + OR (topology->>'exitCount')::BIGINT < 0 + OR (topology->>'generationRuleCount')::BIGINT < 0 + OR (topology->>'spawnBindingCount')::BIGINT < 0 THEN + RAISE EXCEPTION 'Canonical preparation identity or exact Game Session echo differs' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO STRICT identity_row + FROM "${serviceSchema}".world_authored_version_identity + WHERE operation_id = (version_input->>'operationId')::UUID; + SELECT * INTO STRICT binding_row + FROM "${serviceSchema}".world_complete_launch_binding + WHERE binding_operation_id = (launch->>'operationId')::UUID; + SELECT * INTO STRICT intake_row + FROM "${serviceSchema}".world_authored_source_intake + WHERE operation_id = binding_row.intake_operation_id; + SELECT * INTO STRICT capture_row + FROM "${serviceSchema}".world_canonical_frozen_topology + WHERE capture_id = (topology->>'captureId')::UUID; + + IF identity_row.operation_id::TEXT IS DISTINCT FROM topology->>'versionIdentityOperationId' + OR identity_row.target_namespace IS DISTINCT FROM ident->>'targetNamespace' + OR identity_row.canonical_tenant_id::TEXT IS DISTINCT FROM ident->>'canonicalTenantId' + OR identity_row.world_slug IS DISTINCT FROM ident->>'worldSlug' + OR identity_row.canonical_version_id::TEXT IS DISTINCT FROM version_input->>'canonicalVersionId' + OR identity_row.canonical_version_id::TEXT IS DISTINCT FROM topology->>'canonicalVersionId' + OR identity_row.local_tenant_key IS DISTINCT FROM (launch->>'localTenantKey')::BIGINT + OR identity_row.local_version_key IS DISTINCT FROM (version_input->>'localVersionKey')::BIGINT + OR identity_row.game_design_version_id IS DISTINCT FROM (version_input->>'gameDesignVersionId')::BIGINT + OR identity_row.intake_operation_id IS DISTINCT FROM (launch->>'intakeOperationId')::UUID + OR identity_row.intake_request_id IS DISTINCT FROM (launch->>'intakeRequestId')::UUID + OR identity_row.source_operation_id IS DISTINCT FROM (launch->>'sourceOperationId')::UUID + OR identity_row.source_evidence_digest IS DISTINCT FROM launch->>'sourceEvidenceDigest' + OR identity_row.intake_request_digest IS DISTINCT FROM launch->>'intakeRequestDigest' + OR identity_row.intake_receipt_digest IS DISTINCT FROM launch->>'intakeReceiptDigest' + OR binding_row.target_namespace IS DISTINCT FROM ident->>'targetNamespace' + OR binding_row.canonical_tenant_id::TEXT IS DISTINCT FROM ident->>'canonicalTenantId' + OR binding_row.world_slug IS DISTINCT FROM ident->>'worldSlug' + OR binding_row.control_plane_request_id IS DISTINCT FROM ident->>'controlPlaneRequestId' + OR binding_row.descriptor_request_digest IS DISTINCT FROM gs_evidence->>'descriptorRequestDigest' + OR binding_row.descriptor_result_digest IS DISTINCT FROM gs_evidence->>'descriptorResultDigest' + OR binding_row.release_attestation_digest IS DISTINCT FROM gs_evidence->>'releaseAttestationEvidenceDigest' + OR binding_row.canonical_version_id::TEXT IS DISTINCT FROM version_input->>'canonicalVersionId' + OR binding_row.canonical_version_id::TEXT IS DISTINCT FROM launch->>'canonicalVersionId' + OR capture_row.request_id IS DISTINCT FROM (topology->>'requestId')::UUID + OR capture_row.commit_id IS DISTINCT FROM (topology->>'commitId')::UUID + OR capture_row.version_identity_operation_id IS DISTINCT FROM identity_row.operation_id + OR capture_row.binding_json IS DISTINCT FROM ( + SELECT binding_json FROM "${serviceSchema}".world_topology_draft_commit + WHERE request_id = capture_row.request_id) + OR capture_row.freeze_request_json::JSONB->>'publicationRequestId' + IS DISTINCT FROM topology->>'freezeRequestId' + OR capture_row.freeze_request_json::JSONB->>'publicationFence' + IS DISTINCT FROM topology->>'publicationFence' + OR capture_row.freeze_request_json::JSONB->>'requestDigest' + IS DISTINCT FROM topology->>'publicationRequestDigest' + OR capture_row.freeze_request_json::JSONB->>'appliedCommitId' + IS DISTINCT FROM topology->>'appliedCommitId' + OR capture_row.graph_sha256 !~ '^[0-9a-f]{64}$' + OR intake_row.source_provenance_kind <> 'NEW_GAME_ROW' + OR source_input->>'schemaVersion' IS DISTINCT FROM intake_row.schema_version::TEXT + OR source_input->>'targetNamespace' IS DISTINCT FROM intake_row.target_namespace + OR source_input->>'intakeRequestId' IS DISTINCT FROM intake_row.intake_request_id::TEXT + OR source_input->>'operationId' IS DISTINCT FROM intake_row.operation_id::TEXT + OR source_input->>'canonicalTenantId' IS DISTINCT FROM intake_row.canonical_tenant_id::TEXT + OR source_input->>'worldSlug' IS DISTINCT FROM intake_row.world_slug + OR source_input->>'sourceOperationId' IS DISTINCT FROM intake_row.source_operation_id::TEXT + OR source_input->>'sourceEvidenceDigest' IS DISTINCT FROM intake_row.source_evidence_digest + OR source_input->>'requestDigest' IS DISTINCT FROM intake_row.request_digest + OR source_input->>'receiptDigest' IS DISTINCT FROM intake_row.receipt_digest + OR source_input->>'localTenantKey' IS DISTINCT FROM intake_row.local_tenant_key::TEXT + OR source_evidence_input->>'schemaVersion' IS DISTINCT FROM intake_row.source_schema_version::TEXT + OR source_evidence_input->>'registrationRequestId' IS DISTINCT FROM intake_row.source_registration_request_id::TEXT + OR source_evidence_input->>'sourceOperationId' IS DISTINCT FROM intake_row.source_operation_id::TEXT + OR source_evidence_input->>'requestDigest' IS DISTINCT FROM intake_row.source_request_digest + OR source_evidence_input->>'canonicalTenantId' IS DISTINCT FROM intake_row.canonical_tenant_id::TEXT + OR source_evidence_input->>'tenantSlug' IS DISTINCT FROM intake_row.tenant_slug + OR source_evidence_input->>'worldSlug' IS DISTINCT FROM intake_row.world_slug + OR source_evidence_input->>'worldDisplayName' IS DISTINCT FROM intake_row.world_display_name + OR source_evidence_input->>'sourceGameRowId' IS DISTINCT FROM intake_row.source_game_row_id::TEXT + OR source_evidence_input->>'sourceGameTenantKey' IS DISTINCT FROM intake_row.source_game_tenant_key + OR source_evidence_input->>'provenanceKind' IS DISTINCT FROM intake_row.source_provenance_kind + OR source_evidence_input->>'evidenceDigest' IS DISTINCT FROM intake_row.source_evidence_digest + OR capture_row.graph_bytes IS NULL OR octet_length(capture_row.graph_bytes) = 0 + OR capture_row.graph_sha256 IS NULL OR capture_row.graph_sha256 !~ '^[0-9a-f]{64}$' + OR NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_authored_source_tenant_key_reservation r + WHERE r.tenant_key = identity_row.local_tenant_key + AND r.claim_kind = 'CANONICAL_AUTHORED_SOURCE') THEN + RAISE EXCEPTION 'Canonical preparation differs from exact V26/V27 source, version, or frozen capture' + USING ERRCODE = '23514'; + END IF; + + SELECT count(*) FILTER (WHERE family = 'REGION'), + count(*) FILTER (WHERE family = 'ZONE'), + count(*) FILTER (WHERE family = 'ROOM'), + count(*) FILTER (WHERE family = 'ROOM_EXIT'), + count(*) FILTER (WHERE family = 'GENERATION_RULE'), + count(*) FILTER (WHERE family = 'WORLD_ENTITY_SPAWN_BINDING'), + count(*) + INTO region_count, zone_count, room_count, exit_count, generation_count, spawn_count, template_count + FROM "${serviceSchema}".world_authored_topology_identity + WHERE request_id = capture_row.request_id AND commit_id = capture_row.commit_id + AND version_identity_operation_id = identity_row.operation_id; + + -- Required intent is a hard pre-allocation rejection; there is no skip/default path. + IF generation_count <> 0 OR spawn_count <> 0 + OR generation_count <> (topology->>'generationRuleCount')::BIGINT + OR spawn_count <> (topology->>'spawnBindingCount')::BIGINT THEN + RAISE EXCEPTION 'Canonical generation-free preparation rejects configured generation/spawn intent' + USING ERRCODE = '23514'; + END IF; + IF region_count <> (topology->>'regionCount')::BIGINT + OR zone_count <> (topology->>'zoneCount')::BIGINT + OR room_count <> (topology->>'roomCount')::BIGINT + OR exit_count <> (topology->>'exitCount')::BIGINT + OR template_count <> region_count + zone_count + room_count + exit_count + OR region_count = 0 THEN + RAISE EXCEPTION 'Canonical preparation plan omits or adds a selected frozen graph row' + USING ERRCODE = '23514'; + END IF; + + -- The capture's V25 version owner is the serialization fence shared with every V29 writer. + -- Hold it through this transaction: a writer that began first completes before this row can be + -- locked (and its phase is then rechecked); a later writer cannot acquire its required UPDATE + -- lock until this exact immutable source graph has been materialized and committed. + SELECT * INTO STRICT publication_owner + FROM "${serviceSchema}".world_design_publication_fence_owner + WHERE local_tenant_key = identity_row.local_tenant_key + AND version_id = identity_row.local_version_key + FOR SHARE; + IF publication_owner.owner_freeze_phase IS DISTINCT FROM 'FROZEN' + OR publication_owner.current_publication_fence IS DISTINCT FROM capture_row.publication_fence THEN + RAISE EXCEPTION 'Canonical preparation requires the exact still-FROZEN V25 source owner' + USING ERRCODE = '23514'; + END IF; + + -- Serialize exact canonical-id and request retries before checking prior identity or allocating + -- any private key/row identifier. These locks are entered only after the external verifier ran. + PERFORM pg_advisory_xact_lock(hashtextextended( + 'canonical-game-instance:' || (ident->>'canonicalGameInstanceId'), 0)); + PERFORM pg_advisory_xact_lock(hashtextextended( + 'canonical-prepare-request:' || (ident->>'targetNamespace') || ':' + || (ident->>'canonicalTenantId') || ':' || (ident->>'controlPlaneRequestId'), 0)); + + SELECT * INTO prior FROM "${serviceSchema}".world_canonical_instance_preparation + WHERE canonical_game_instance_id = (ident->>'canonicalGameInstanceId')::UUID FOR UPDATE; + IF FOUND THEN + IF prior.input_json IS DISTINCT FROM p_input_json + OR prior.input_digest IS DISTINCT FROM p_input_digest + OR prior.capture_id IS DISTINCT FROM capture_row.capture_id + OR prior.graph_bytes IS DISTINCT FROM capture_row.graph_bytes + OR prior.graph_sha256 IS DISTINCT FROM capture_row.graph_sha256 THEN + RAISE EXCEPTION 'Canonical gameInstanceId is already bound to a different preparation' + USING ERRCODE = '23505'; + END IF; + world_instance_id := prior.world_instance_id; + private_game_instance_key := prior.private_game_instance_key; + RETURN NEXT; + RETURN; + END IF; + IF EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_canonical_instance_preparation + WHERE target_namespace = ident->>'targetNamespace' + AND canonical_tenant_id = (ident->>'canonicalTenantId')::UUID + AND control_plane_request_id = ident->>'controlPlaneRequestId') + OR EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_instance + WHERE canonical_game_instance_id = (ident->>'canonicalGameInstanceId')::UUID) + OR EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_instance + WHERE tenant_id = identity_row.local_tenant_key + AND control_plane_request_id = ident->>'controlPlaneRequestId') THEN + RAISE EXCEPTION 'Canonical game instance or request identity is already reserved' + USING ERRCODE = '23505'; + END IF; + + LOOP + local_game_instance_key := nextval('"${serviceSchema}".world_canonical_private_game_instance_key_seq'); + EXIT WHEN NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_instance + WHERE tenant_id = identity_row.local_tenant_key + AND game_instance_id = local_game_instance_key); + END LOOP; + new_world_instance_id := nextval('"${serviceSchema}".world_instance_id_seq'); + world_row := jsonb_populate_record(NULL::"${serviceSchema}".world_instance, + jsonb_build_object( + 'id', new_world_instance_id, + 'tenant_id', identity_row.local_tenant_key, + 'game_instance_id', local_game_instance_key, + 'game_template_id', (binding_row.descriptor_json::JSONB->>'gameTemplateId')::BIGINT, + 'control_plane_request_id', ident->>'controlPlaneRequestId', + 'launch_descriptor_id', binding_row.descriptor_json::JSONB->>'launchDescriptorId', + 'version_id', identity_row.local_version_key, + 'script_patch_version', CASE WHEN binding_row.descriptor_json::JSONB->>'scriptPatchVersionPresent' = 'true' + THEN binding_row.descriptor_json::JSONB->>'scriptPatchVersion' ELSE NULL END, + 'runtime_flags_json', binding_row.descriptor_json::JSONB->>'runtimeFlagsJson', + 'generation_config_revision', binding_row.descriptor_json::JSONB->>'generationConfigRevision', + 'release_bundle_id', (binding_row.descriptor_json::JSONB->>'releaseBundleId')::BIGINT, + 'published_release_bundle_ref', binding_row.descriptor_json::JSONB->>'publishedReleaseBundleRef', + 'version_state_epoch', (binding_row.descriptor_json::JSONB->>'versionStateEpoch')::BIGINT, + 'lifecycle_epoch', 1, + 'status', 'PREPARING', + 'failure_reason', NULL, + 'created_at', CURRENT_TIMESTAMP::TIMESTAMP, + 'updated_at', CURRENT_TIMESTAMP::TIMESTAMP, + 'row_version', 0, + 'termination_request_id', NULL, + 'terminated_at', NULL, + 'remap_set_id', CASE WHEN binding_row.descriptor_json::JSONB->>'remapSetIdPresent' = 'true' + THEN binding_row.descriptor_json::JSONB->>'remapSetId' ELSE NULL END, + 'canonical_game_instance_id', (ident->>'canonicalGameInstanceId')::UUID, + 'canonical_target_namespace', ident->>'targetNamespace', + 'canonical_tenant_id', (ident->>'canonicalTenantId')::UUID, + 'canonical_world_slug', ident->>'worldSlug', + 'playable_state_namespace_id', (ident->>'playableStateNamespaceId')::UUID, + 'playable_state_scope', 'SHARED', + 'public_production', TRUE, + 'playtest_lifecycle_id', NULL, + 'playtest_state_generation', NULL, + 'canonical_launch_binding_operation_id', binding_row.binding_operation_id)); + full_row := to_jsonb(world_row); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'world_instance', new_world_instance_id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".world_instance SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".world_instance, full_row)).*; + + FOR source_region IN + SELECT m.template_id, m.private_row_key, r.shard_id, r.name, r.weather, + r.generation_seed, r.generator_type, r.generator_params, r.spacing_multiplier + FROM "${serviceSchema}".world_authored_topology_identity m + JOIN "${serviceSchema}".region r ON r.id = m.private_row_key + WHERE m.request_id = capture_row.request_id AND m.commit_id = capture_row.commit_id + AND m.version_identity_operation_id = identity_row.operation_id AND m.family = 'REGION' + AND r.tenant_id = identity_row.local_tenant_key AND r.version_id = identity_row.local_version_key + ORDER BY m.template_id + LOOP + runtime_id := nextval('"${serviceSchema}".region_instance_id_seq'); + runtime_uuid := gen_random_uuid(); + region_runtime := jsonb_populate_record(NULL::"${serviceSchema}".region_instance, + jsonb_build_object( + 'id', runtime_id, 'tenant_id', identity_row.local_tenant_key, + 'game_instance_id', local_game_instance_key, 'world_instance_id', new_world_instance_id, + 'shard_id', source_region.shard_id, 'name', source_region.name, + 'weather', source_region.weather, 'generation_seed', source_region.generation_seed, + 'generator_type', source_region.generator_type, + 'generator_params', source_region.generator_params, + 'spacing_multiplier', source_region.spacing_multiplier, 'version', 0, + 'canonical_region_instance_id', runtime_uuid)); + full_row := to_jsonb(region_runtime); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'region_instance', runtime_id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".region_instance SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".region_instance, full_row)).*; + + topology_identity := jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_topology_identity, + jsonb_build_object('id', nextval('"${serviceSchema}".world_canonical_instance_topology_identity_id_seq'), + 'world_instance_id', new_world_instance_id, + 'canonical_game_instance_id', (ident->>'canonicalGameInstanceId')::UUID, + 'family', 'REGION', 'template_id', source_region.template_id, + 'template_private_row_key', source_region.private_row_key, + 'runtime_row_id', runtime_id, 'runtime_identity', runtime_uuid, + 'runtime_room_instance_id', NULL)); + full_row := to_jsonb(topology_identity); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'world_canonical_instance_topology_identity', topology_identity.id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".world_canonical_instance_topology_identity SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".world_canonical_instance_topology_identity, full_row)).*; + END LOOP; + + FOR source_zone IN + SELECT m.template_id, m.private_row_key, z.region_id, z.name + FROM "${serviceSchema}".world_authored_topology_identity m + JOIN "${serviceSchema}".zone z ON z.id = m.private_row_key + WHERE m.request_id = capture_row.request_id AND m.commit_id = capture_row.commit_id + AND m.version_identity_operation_id = identity_row.operation_id AND m.family = 'ZONE' + AND z.tenant_id = identity_row.local_tenant_key AND z.version_id = identity_row.local_version_key + ORDER BY m.template_id + LOOP + SELECT ti.runtime_row_id INTO STRICT parent_row + FROM "${serviceSchema}".world_canonical_instance_topology_identity ti + WHERE ti.world_instance_id = new_world_instance_id AND ti.family = 'REGION' + AND ti.template_private_row_key = source_zone.region_id; + runtime_id := nextval('"${serviceSchema}".zone_instance_id_seq'); + runtime_uuid := gen_random_uuid(); + zone_runtime := jsonb_populate_record(NULL::"${serviceSchema}".zone_instance, + jsonb_build_object( + 'id', runtime_id, 'tenant_id', identity_row.local_tenant_key, + 'game_instance_id', local_game_instance_key, 'zone_instance_id', runtime_id, + 'template_zone_id', source_zone.private_row_key, + 'region_instance_id', parent_row.runtime_row_id, + 'name', source_zone.name, 'version', 0, + 'canonical_zone_instance_id', runtime_uuid)); + full_row := to_jsonb(zone_runtime); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'zone_instance', runtime_id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".zone_instance SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".zone_instance, full_row)).*; + + topology_identity := jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_topology_identity, + jsonb_build_object('id', nextval('"${serviceSchema}".world_canonical_instance_topology_identity_id_seq'), + 'world_instance_id', new_world_instance_id, + 'canonical_game_instance_id', (ident->>'canonicalGameInstanceId')::UUID, + 'family', 'ZONE', 'template_id', source_zone.template_id, + 'template_private_row_key', source_zone.private_row_key, + 'runtime_row_id', runtime_id, 'runtime_identity', runtime_uuid, + 'runtime_room_instance_id', NULL)); + full_row := to_jsonb(topology_identity); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'world_canonical_instance_topology_identity', topology_identity.id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".world_canonical_instance_topology_identity SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".world_canonical_instance_topology_identity, full_row)).*; + END LOOP; + + FOR source_room IN + SELECT m.template_id, m.private_row_key, r.zone_id, r.name, r.description, + r.name_localized_variants_json, r.description_localized_variants_json + FROM "${serviceSchema}".world_authored_topology_identity m + JOIN "${serviceSchema}".room r ON r.id = m.private_row_key + WHERE m.request_id = capture_row.request_id AND m.commit_id = capture_row.commit_id + AND m.version_identity_operation_id = identity_row.operation_id AND m.family = 'ROOM' + AND r.tenant_id = identity_row.local_tenant_key AND r.version_id = identity_row.local_version_key + ORDER BY m.template_id + LOOP + SELECT ti.runtime_row_id INTO STRICT parent_row + FROM "${serviceSchema}".world_canonical_instance_topology_identity ti + WHERE ti.world_instance_id = new_world_instance_id AND ti.family = 'ZONE' + AND ti.template_private_row_key = source_room.zone_id; + SELECT ti.runtime_row_id INTO STRICT other_row + FROM "${serviceSchema}".world_canonical_instance_topology_identity ti + JOIN "${serviceSchema}".zone z ON z.id = source_room.zone_id + WHERE ti.world_instance_id = new_world_instance_id AND ti.family = 'REGION' + AND ti.template_private_row_key = z.region_id; + runtime_id := nextval('"${serviceSchema}".room_instance_id_seq'); + room_runtime := jsonb_populate_record(NULL::"${serviceSchema}".room_instance, + jsonb_build_object( + 'id', runtime_id, 'tenant_id', identity_row.local_tenant_key, + 'game_instance_id', local_game_instance_key, 'room_instance_row_id', runtime_id, + 'template_room_id', source_room.private_row_key, + 'region_instance_id', other_row.runtime_row_id, + 'zone_instance_id', parent_row.runtime_row_id, + 'name', source_room.name, 'description', source_room.description, + 'name_localized_variants_json', source_room.name_localized_variants_json, + 'description_localized_variants_json', source_room.description_localized_variants_json, + 'version', 0)); + full_row := to_jsonb(room_runtime); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'room_instance', runtime_id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".room_instance SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".room_instance, full_row)).*; + + topology_identity := jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_topology_identity, + jsonb_build_object('id', nextval('"${serviceSchema}".world_canonical_instance_topology_identity_id_seq'), + 'world_instance_id', new_world_instance_id, + 'canonical_game_instance_id', (ident->>'canonicalGameInstanceId')::UUID, + 'family', 'ROOM', 'template_id', source_room.template_id, + 'template_private_row_key', source_room.private_row_key, + 'runtime_row_id', runtime_id, 'runtime_identity', NULL, + 'runtime_room_instance_id', runtime_id)); + full_row := to_jsonb(topology_identity); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'world_canonical_instance_topology_identity', topology_identity.id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".world_canonical_instance_topology_identity SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".world_canonical_instance_topology_identity, full_row)).*; + END LOOP; + + FOR source_exit IN + SELECT m.template_id, m.private_row_key, e.from_room_id, e.to_room_id, e.direction, e.cost + FROM "${serviceSchema}".world_authored_topology_identity m + JOIN "${serviceSchema}".room_exit e ON e.id = m.private_row_key + WHERE m.request_id = capture_row.request_id AND m.commit_id = capture_row.commit_id + AND m.version_identity_operation_id = identity_row.operation_id AND m.family = 'ROOM_EXIT' + AND e.tenant_id = identity_row.local_tenant_key AND e.version_id = identity_row.local_version_key + ORDER BY m.template_id + LOOP + SELECT ti.runtime_room_instance_id INTO STRICT parent_row + FROM "${serviceSchema}".world_canonical_instance_topology_identity ti + WHERE ti.world_instance_id = new_world_instance_id AND ti.family = 'ROOM' + AND ti.template_private_row_key = source_exit.from_room_id; + SELECT ti.runtime_room_instance_id INTO STRICT other_row + FROM "${serviceSchema}".world_canonical_instance_topology_identity ti + WHERE ti.world_instance_id = new_world_instance_id AND ti.family = 'ROOM' + AND ti.template_private_row_key = source_exit.to_room_id; + runtime_id := nextval('"${serviceSchema}".room_instance_exit_id_seq'); + exit_runtime := jsonb_populate_record(NULL::"${serviceSchema}".room_instance_exit, + jsonb_build_object( + 'id', runtime_id, 'tenant_id', identity_row.local_tenant_key, + 'game_instance_id', local_game_instance_key, + 'from_room_instance_record_id', parent_row.runtime_room_instance_id, + 'to_room_instance_record_id', other_row.runtime_room_instance_id, + 'direction', source_exit.direction, 'cost', source_exit.cost, 'version', 0)); + full_row := to_jsonb(exit_runtime); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'room_instance_exit', runtime_id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".room_instance_exit SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".room_instance_exit, full_row)).*; + + topology_identity := jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_topology_identity, + jsonb_build_object('id', nextval('"${serviceSchema}".world_canonical_instance_topology_identity_id_seq'), + 'world_instance_id', new_world_instance_id, + 'canonical_game_instance_id', (ident->>'canonicalGameInstanceId')::UUID, + 'family', 'ROOM_EXIT', 'template_id', source_exit.template_id, + 'template_private_row_key', source_exit.private_row_key, + 'runtime_row_id', runtime_id, 'runtime_identity', NULL, + 'runtime_room_instance_id', NULL)); + full_row := to_jsonb(topology_identity); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'world_canonical_instance_topology_identity', topology_identity.id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".world_canonical_instance_topology_identity SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".world_canonical_instance_topology_identity, full_row)).*; + END LOOP; + + IF (SELECT count(*) FROM "${serviceSchema}".world_canonical_instance_preparation_execution_manifest + WHERE transaction_id = txid_current()) <> 0 THEN + RAISE EXCEPTION 'Canonical preparation left an unconsumed exact execution manifest' + USING ERRCODE = '23514'; + END IF; + + new_result_id := nextval('"${serviceSchema}".world_canonical_instance_preparation_id_seq'); + preparation_row := jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_preparation, + jsonb_build_object( + 'id', new_result_id, + 'canonical_game_instance_id', (ident->>'canonicalGameInstanceId')::UUID, + 'target_namespace', ident->>'targetNamespace', + 'canonical_tenant_id', (ident->>'canonicalTenantId')::UUID, + 'world_slug', ident->>'worldSlug', + 'control_plane_request_id', ident->>'controlPlaneRequestId', + 'canonical_version_id', identity_row.canonical_version_id, + 'version_identity_operation_id', identity_row.operation_id, + 'capture_id', capture_row.capture_id, + 'graph_bytes', capture_row.graph_bytes, + 'graph_sha256', capture_row.graph_sha256, + 'input_digest', p_input_digest, + 'input_json', p_input_json, + 'world_instance_id', new_world_instance_id, + 'private_game_instance_key', local_game_instance_key, + 'region_count', region_count, + 'zone_count', zone_count, + 'room_count', room_count, + 'exit_count', exit_count, + 'storage_status', 'MATERIALIZED_UNVERIFIED', + 'prepared_at', CURRENT_TIMESTAMP)); + full_row := to_jsonb(preparation_row); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'world_canonical_instance_preparation', new_result_id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".world_canonical_instance_preparation, full_row)).*; + + IF (SELECT count(*) FROM "${serviceSchema}".world_canonical_instance_preparation_execution_manifest + WHERE transaction_id = txid_current()) <> 0 THEN + RAISE EXCEPTION 'Canonical preparation left an unconsumed result manifest' + USING ERRCODE = '23514'; + END IF; + world_instance_id := new_world_instance_id; + private_game_instance_key := local_game_instance_key; + RETURN NEXT; +END; +$$; +REVOKE ALL ON FUNCTION world_prepare_canonical_instance(TEXT, TEXT) FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1010__world_draft_terminal_outcomes.sql b/services/world-management-service/src/main/resources/db/migration/V1010__world_draft_terminal_outcomes.sql new file mode 100644 index 0000000000..cab3365494 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1010__world_draft_terminal_outcomes.sql @@ -0,0 +1,237 @@ +-- A definitive no-commit result is an immutable, owner-local tombstone. It is not permission, +-- an APPLIED result, or evidence that Account's authorization fence may be released. +CREATE TABLE world_draft_terminal_outcome ( + operation_id UUID PRIMARY KEY, + request_id UUID NOT NULL UNIQUE, + commit_id UUID NOT NULL UNIQUE, + authorization_fence_id UUID NOT NULL UNIQUE, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + version_identity_operation_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL CHECK (local_tenant_key > 0), + local_version_key BIGINT NOT NULL CHECK (local_version_key > 0), + owner_binding_json TEXT NOT NULL, + binding_json TEXT NOT NULL, + binding_digest VARCHAR(71) NOT NULL CHECK (binding_digest ~ '^sha256:[0-9a-f]{64}$'), + account_binding_bytes BYTEA NOT NULL CHECK (octet_length(account_binding_bytes) > 0), + account_binding_digest VARCHAR(71) NOT NULL CHECK (account_binding_digest ~ '^sha256:[0-9a-f]{64}$'), + affected_units_json JSONB NOT NULL CHECK (jsonb_typeof(affected_units_json) = 'array'), + outcome VARCHAR(32) NOT NULL CHECK (outcome = 'DEFINITIVELY_ABORTED'), + outcome_bytes BYTEA NOT NULL CHECK (octet_length(outcome_bytes) > 0), + outcome_digest VARCHAR(71) NOT NULL CHECK (outcome_digest ~ '^sha256:[0-9a-f]{64}$'), + recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT ck_world_draft_terminal_non_nil CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND commit_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND authorization_fence_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT ck_world_draft_terminal_scope CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + ), + CONSTRAINT fk_world_draft_terminal_version_identity FOREIGN KEY ( + version_identity_operation_id, + target_namespace, + canonical_tenant_id, + canonical_version_id, + local_version_key + ) REFERENCES world_authored_version_identity ( + operation_id, + target_namespace, + canonical_tenant_id, + canonical_version_id, + local_version_key + ) +); +CREATE INDEX idx_world_draft_terminal_scope + ON world_draft_terminal_outcome (target_namespace, canonical_tenant_id, canonical_version_id); + +-- [jooq ignore start] +-- Preserve the PostgreSQL binding constraint; jOOQ's H2 DDL simulation cannot render ->>. +ALTER TABLE world_draft_terminal_outcome ADD CONSTRAINT ck_world_draft_terminal_binding CHECK ( + jsonb_typeof(binding_json::jsonb) = 'object' + AND binding_json::jsonb->>'canonicalTenantId' = canonical_tenant_id::TEXT + AND binding_json::jsonb->>'canonicalVersionId' = canonical_version_id::TEXT + AND binding_json::jsonb->>'requestId' = request_id::TEXT + AND binding_json::jsonb->>'commitId' = commit_id::TEXT + AND jsonb_typeof(owner_binding_json::jsonb) = 'object' + AND owner_binding_json::jsonb->>'targetNamespace' = target_namespace + AND owner_binding_json::jsonb->>'canonicalTenantId' = canonical_tenant_id::TEXT + AND owner_binding_json::jsonb->>'canonicalVersionId' = canonical_version_id::TEXT + AND owner_binding_json::jsonb->>'versionIdentityOperationId' = version_identity_operation_id::TEXT +); +REVOKE ALL ON world_draft_terminal_outcome FROM PUBLIC; + +CREATE FUNCTION world_draft_terminal_outcome_guard() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + owner_row "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + unit JSONB; + aggregate_key BIGINT; + observed_epoch BIGINT; + expected_epoch BIGINT; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'World Draft terminal outcomes are immutable and retained' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO owner_row FROM "${serviceSchema}".world_design_publication_fence_owner + WHERE target_namespace = NEW.target_namespace + AND canonical_tenant_id = NEW.canonical_tenant_id + AND local_tenant_key = NEW.local_tenant_key + AND version_id = NEW.local_version_key + FOR UPDATE; + IF NOT FOUND OR owner_row.owner_freeze_phase <> 'OPEN' + OR owner_row.current_publication_fence IS NOT NULL THEN + RAISE EXCEPTION 'First World Draft abort requires the exact OPEN V25 owner row' + USING ERRCODE = '23514'; + END IF; + + IF EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_region_draft_commit c + WHERE c.request_id = NEW.request_id OR c.commit_id = NEW.commit_id + ) OR EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_topology_draft_commit c + WHERE c.request_id = NEW.request_id OR c.commit_id = NEW.commit_id + ) OR EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_authored_topology_identity i + WHERE i.target_namespace = NEW.target_namespace + AND i.canonical_tenant_id = NEW.canonical_tenant_id + AND i.canonical_version_id = NEW.canonical_version_id + AND (i.request_id = NEW.request_id OR i.commit_id = NEW.commit_id) + ) OR EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_design_revision_ledger r + WHERE r.tenant_id = NEW.local_tenant_key + AND r.version_id = NEW.local_version_key + AND r.commit_id = NEW.commit_id::TEXT + ) THEN + RAISE EXCEPTION 'Retained World application history cannot be terminalized as no-commit' + USING ERRCODE = '23514'; + END IF; + + FOR unit IN SELECT value FROM jsonb_array_elements(NEW.affected_units_json) LOOP + IF unit->>'owner' <> 'WORLD_MANAGEMENT' THEN + RAISE EXCEPTION 'World terminal affected-unit vector contains a foreign owner' + USING ERRCODE = '23514'; + END IF; + expected_epoch := (unit->>'expectedEpoch')::BIGINT; + IF unit->>'scopeType' = 'AGGREGATE' THEN + IF unit->>'aggregateId' ~ '^[1-9][0-9]*$' THEN + aggregate_key := (unit->>'aggregateId')::BIGINT; + ELSE + SELECT private_row_key INTO aggregate_key + FROM "${serviceSchema}".world_authored_topology_identity + WHERE target_namespace = NEW.target_namespace + AND canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND family = unit->>'aggregateType' + AND template_id = (unit->>'aggregateId')::UUID; + IF NOT FOUND AND expected_epoch <> 0 THEN + RAISE EXCEPTION 'World topology mapping is absent for a nonzero expected epoch' + USING ERRCODE = '23514'; + END IF; + END IF; + observed_epoch := 0; + IF aggregate_key IS NOT NULL THEN + SELECT draft_revision_epoch INTO observed_epoch + FROM "${serviceSchema}".world_design_aggregate_epoch + WHERE tenant_id = NEW.local_tenant_key + AND version_id = NEW.local_version_key + AND aggregate_type = unit->>'aggregateType' + AND aggregate_id = aggregate_key; + IF NOT FOUND THEN observed_epoch := 0; END IF; + END IF; + IF observed_epoch IS DISTINCT FROM expected_epoch THEN + RAISE EXCEPTION 'Affected World aggregate advanced before definitive abort' + USING ERRCODE = '23514'; + END IF; + ELSE + observed_epoch := 0; + SELECT draft_scope_revision_epoch INTO observed_epoch + FROM "${serviceSchema}".world_design_scope_epoch + WHERE tenant_id = NEW.local_tenant_key + AND version_id = NEW.local_version_key + AND scope_type = unit->>'scopeType' + AND scope_id = unit->>'scopeId'; + IF NOT FOUND THEN observed_epoch := 0; END IF; + IF observed_epoch IS DISTINCT FROM expected_epoch THEN + RAISE EXCEPTION 'Affected World scope advanced before definitive abort' + USING ERRCODE = '23514'; + END IF; + END IF; + aggregate_key := NULL; + END LOOP; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_world_draft_terminal_outcome_guard + BEFORE INSERT OR UPDATE OR DELETE ON world_draft_terminal_outcome + FOR EACH ROW EXECUTE FUNCTION world_draft_terminal_outcome_guard(); +CREATE TRIGGER trg_world_draft_terminal_outcome_no_truncate + BEFORE TRUNCATE ON world_draft_terminal_outcome + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE FUNCTION world_reject_aborted_draft_attempt() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + request_identity UUID; + commit_identity UUID; + target_tenant UUID; + target_version UUID; + target_namespace TEXT; +BEGIN + IF TG_TABLE_NAME = 'world_region_draft_execution_manifest' THEN + request_identity := (NEW.complete_binding->>'requestId')::UUID; + commit_identity := (NEW.complete_binding->>'commitId')::UUID; + target_tenant := (NEW.complete_binding->>'canonicalTenantId')::UUID; + target_version := (NEW.complete_binding->>'canonicalVersionId')::UUID; + target_namespace := NEW.owner_binding->>'targetNamespace'; + ELSE + request_identity := NEW.request_id; + commit_identity := NEW.commit_id; + target_tenant := NEW.canonical_tenant_id; + target_version := NEW.canonical_version_id; + target_namespace := NEW.target_namespace; + END IF; + IF EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_draft_terminal_outcome terminal + WHERE terminal.target_namespace = target_namespace + AND terminal.canonical_tenant_id = target_tenant + AND terminal.canonical_version_id = target_version + AND (terminal.request_id = request_identity OR terminal.commit_id = commit_identity) + ) THEN + RAISE EXCEPTION 'World Draft operation has immutable definitive no-commit evidence' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +-- The guarded writers first lock the same V25 owner row. The region function creates this +-- manifest before any content or epoch change; topology identity insertion is also protected +-- by its existing deferred history FK. These gates exclude a delayed raw SQL call as well as +-- repository retries after an ABORTED result. +CREATE TRIGGER trg_world_region_manifest_aborted_attempt + BEFORE INSERT ON world_region_draft_execution_manifest + FOR EACH ROW EXECUTE FUNCTION world_reject_aborted_draft_attempt(); +CREATE TRIGGER trg_world_region_commit_aborted_attempt + BEFORE INSERT ON world_region_draft_commit + FOR EACH ROW EXECUTE FUNCTION world_reject_aborted_draft_attempt(); +CREATE TRIGGER trg_world_topology_identity_aborted_attempt + BEFORE INSERT ON world_authored_topology_identity + FOR EACH ROW EXECUTE FUNCTION world_reject_aborted_draft_attempt(); +CREATE TRIGGER trg_world_topology_commit_aborted_attempt + BEFORE INSERT ON world_topology_draft_commit + FOR EACH ROW EXECUTE FUNCTION world_reject_aborted_draft_attempt(); + +REVOKE ALL ON FUNCTION world_draft_terminal_outcome_guard() FROM PUBLIC; +REVOKE ALL ON FUNCTION world_reject_aborted_draft_attempt() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1011__world_draft_terminal_guard_namespace.sql b/services/world-management-service/src/main/resources/db/migration/V1011__world_draft_terminal_guard_namespace.sql new file mode 100644 index 0000000000..eae4613a1d --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1011__world_draft_terminal_guard_namespace.sql @@ -0,0 +1,43 @@ +-- V36's terminal guard remains installed for retained rows and trigger bindings. Replace only its +-- trigger function body so the PL/pgSQL variable cannot collide with the terminal table column. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION world_reject_aborted_draft_attempt() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + v_request_identity UUID; + v_commit_identity UUID; + v_target_tenant UUID; + v_target_version UUID; + v_target_namespace TEXT; +BEGIN + IF TG_TABLE_NAME = 'world_region_draft_execution_manifest' THEN + v_request_identity := (NEW.complete_binding->>'requestId')::UUID; + v_commit_identity := (NEW.complete_binding->>'commitId')::UUID; + v_target_tenant := (NEW.complete_binding->>'canonicalTenantId')::UUID; + v_target_version := (NEW.complete_binding->>'canonicalVersionId')::UUID; + v_target_namespace := NEW.owner_binding->>'targetNamespace'; + ELSE + v_request_identity := NEW.request_id; + v_commit_identity := NEW.commit_id; + v_target_tenant := NEW.canonical_tenant_id; + v_target_version := NEW.canonical_version_id; + v_target_namespace := NEW.target_namespace; + END IF; + IF EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_draft_terminal_outcome terminal + WHERE terminal.target_namespace = v_target_namespace + AND terminal.canonical_tenant_id = v_target_tenant + AND terminal.canonical_version_id = v_target_version + AND (terminal.request_id = v_request_identity + OR terminal.commit_id = v_commit_identity) + ) THEN + RAISE EXCEPTION 'World Draft operation has immutable definitive no-commit evidence' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +REVOKE ALL ON FUNCTION world_reject_aborted_draft_attempt() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1012__world_account_bound_graph_application.sql b/services/world-management-service/src/main/resources/db/migration/V1012__world_account_bound_graph_application.sql new file mode 100644 index 0000000000..4a9fb8de4b --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1012__world_account_bound_graph_application.sql @@ -0,0 +1,216 @@ +-- Preserve all V30 histories and bytes. A past unverified row has no application transaction. +ALTER TABLE world_topology_draft_commit ADD COLUMN application_transaction_id BIGINT; + +CREATE TABLE world_draft_graph_application ( + operation_id UUID PRIMARY KEY, + request_id UUID NOT NULL UNIQUE, + commit_id UUID NOT NULL UNIQUE, + authorization_fence_id UUID NOT NULL UNIQUE, + operation_bytes BYTEA NOT NULL CHECK (octet_length(operation_bytes) > 0), + account_binding_bytes BYTEA NOT NULL CHECK (octet_length(account_binding_bytes) > 0), + account_binding_digest VARCHAR(71) NOT NULL CHECK (account_binding_digest ~ '^sha256:[0-9a-f]{64}$'), + result_bytes BYTEA NOT NULL CHECK (octet_length(result_bytes) > 0), + result_digest VARCHAR(71) NOT NULL CHECK (result_digest ~ '^sha256:[0-9a-f]{64}$'), + application_transaction_id BIGINT NOT NULL, + recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (request_id) REFERENCES world_topology_draft_commit(request_id), + FOREIGN KEY (commit_id) REFERENCES world_topology_draft_commit(commit_id), + CHECK (operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND authorization_fence_id <> '00000000-0000-0000-0000-000000000000'::UUID) +); + +-- One immutable identity namespace across positive and no-commit outcomes, including altered +-- target bindings that would otherwise lock different V25 rows. Retained abort bytes are copied +-- exactly; old permission-unverified graphs never receive a positive terminal identity. +CREATE TABLE world_draft_graph_terminal_identity ( + operation_id UUID PRIMARY KEY, + request_id UUID NOT NULL UNIQUE, + commit_id UUID NOT NULL UNIQUE, + authorization_fence_id UUID NOT NULL UNIQUE, + account_binding_bytes BYTEA NOT NULL, + account_binding_digest VARCHAR(71) NOT NULL, + outcome VARCHAR(32) NOT NULL CHECK (outcome IN ('APPLIED', 'DEFINITIVELY_ABORTED')) +); +INSERT INTO world_draft_graph_terminal_identity + (operation_id,request_id,commit_id,authorization_fence_id,account_binding_bytes,account_binding_digest,outcome) + SELECT operation_id,request_id,commit_id,authorization_fence_id,account_binding_bytes,account_binding_digest,outcome + FROM world_draft_terminal_outcome; + +-- [jooq ignore start] +CREATE FUNCTION world_claim_graph_terminal_identity() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + retained "${serviceSchema}".world_draft_graph_terminal_identity%ROWTYPE; + expected_outcome TEXT; + identity_count BIGINT; +BEGIN + expected_outcome := CASE TG_TABLE_NAME WHEN 'world_draft_graph_application' + THEN 'APPLIED' ELSE 'DEFINITIVELY_ABORTED' END; + INSERT INTO "${serviceSchema}".world_draft_graph_terminal_identity + (operation_id,request_id,commit_id,authorization_fence_id,account_binding_bytes,account_binding_digest,outcome) + VALUES (NEW.operation_id,NEW.request_id,NEW.commit_id,NEW.authorization_fence_id, + NEW.account_binding_bytes,NEW.account_binding_digest,expected_outcome) + ON CONFLICT DO NOTHING; + SELECT count(*) INTO identity_count FROM "${serviceSchema}".world_draft_graph_terminal_identity i + WHERE i.operation_id=NEW.operation_id OR i.request_id=NEW.request_id OR i.commit_id=NEW.commit_id + OR i.authorization_fence_id=NEW.authorization_fence_id; + IF identity_count <> 1 THEN + RAISE EXCEPTION 'World terminal identities select conflicting retained original operations' USING ERRCODE='23514'; + END IF; + SELECT * INTO STRICT retained FROM "${serviceSchema}".world_draft_graph_terminal_identity i + WHERE i.operation_id=NEW.operation_id OR i.request_id=NEW.request_id OR i.commit_id=NEW.commit_id + OR i.authorization_fence_id=NEW.authorization_fence_id FOR UPDATE; + IF retained.operation_id IS DISTINCT FROM NEW.operation_id + OR retained.request_id IS DISTINCT FROM NEW.request_id + OR retained.commit_id IS DISTINCT FROM NEW.commit_id + OR retained.authorization_fence_id IS DISTINCT FROM NEW.authorization_fence_id + OR retained.account_binding_bytes IS DISTINCT FROM NEW.account_binding_bytes + OR retained.account_binding_digest IS DISTINCT FROM NEW.account_binding_digest + OR retained.outcome IS DISTINCT FROM expected_outcome THEN + RAISE EXCEPTION 'World original terminal identity cannot be reused or relabeled' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE FUNCTION world_verify_graph_terminal_identity_receipt() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + IF NEW.outcome = 'APPLIED' THEN + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_draft_graph_application a + WHERE a.operation_id=NEW.operation_id AND a.request_id=NEW.request_id AND a.commit_id=NEW.commit_id + AND a.authorization_fence_id=NEW.authorization_fence_id + AND a.account_binding_bytes=NEW.account_binding_bytes AND a.account_binding_digest=NEW.account_binding_digest) THEN + RETURN NEW; + END IF; + ELSE + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_draft_terminal_outcome a + WHERE a.operation_id=NEW.operation_id AND a.request_id=NEW.request_id AND a.commit_id=NEW.commit_id + AND a.authorization_fence_id=NEW.authorization_fence_id + AND a.account_binding_bytes=NEW.account_binding_bytes AND a.account_binding_digest=NEW.account_binding_digest) THEN + RETURN NEW; + END IF; + END IF; + RAISE EXCEPTION 'World terminal identity lacks its exact immutable owner receipt' USING ERRCODE='23514'; +END; +$$; +CREATE TRIGGER trg_world_terminal_identity_immutable BEFORE UPDATE OR DELETE + ON world_draft_graph_terminal_identity FOR EACH ROW EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +CREATE TRIGGER trg_world_terminal_identity_no_truncate BEFORE TRUNCATE + ON world_draft_graph_terminal_identity FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +CREATE CONSTRAINT TRIGGER trg_world_terminal_identity_receipt AFTER INSERT ON world_draft_graph_terminal_identity + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION world_verify_graph_terminal_identity_receipt(); +CREATE TRIGGER trg_world_graph_terminal_identity_claim BEFORE INSERT + ON world_draft_graph_application FOR EACH ROW EXECUTE FUNCTION world_claim_graph_terminal_identity(); +CREATE TRIGGER trg_world_abort_terminal_identity_claim BEFORE INSERT + ON world_draft_terminal_outcome FOR EACH ROW EXECUTE FUNCTION world_claim_graph_terminal_identity(); + +CREATE FUNCTION world_stamp_topology_application_transaction() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + NEW.application_transaction_id := txid_current(); + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_world_topology_application_transaction BEFORE INSERT + ON world_topology_draft_commit FOR EACH ROW + EXECUTE FUNCTION world_stamp_topology_application_transaction(); + +CREATE FUNCTION world_guard_graph_application() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + graph_row "${serviceSchema}".world_topology_draft_commit%ROWTYPE; + owner_row "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + unit JSONB; + current_epoch BIGINT; + mapped_key BIGINT; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'World graph APPLIED results are immutable and retained' USING ERRCODE = '23514'; + END IF; + SELECT * INTO graph_row FROM "${serviceSchema}".world_topology_draft_commit + WHERE request_id = NEW.request_id AND commit_id = NEW.commit_id; + IF NOT FOUND OR graph_row.application_transaction_id IS DISTINCT FROM txid_current() THEN + RAISE EXCEPTION 'APPLIED requires a genuine fresh graph in the same transaction; old history cannot be promoted' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO owner_row FROM "${serviceSchema}".world_design_publication_fence_owner + WHERE target_namespace = graph_row.target_namespace + AND canonical_tenant_id = graph_row.canonical_tenant_id + AND local_tenant_key = graph_row.local_tenant_key + AND version_id = graph_row.local_version_key FOR UPDATE; + IF NOT FOUND OR owner_row.owner_freeze_phase <> 'OPEN' + OR owner_row.current_publication_fence IS NOT NULL THEN + RAISE EXCEPTION 'Fresh graph APPLIED requires exact OPEN V25 owner' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_draft_terminal_outcome t + WHERE t.operation_id = NEW.operation_id OR t.request_id = NEW.request_id + OR t.commit_id = NEW.commit_id OR t.authorization_fence_id = NEW.authorization_fence_id) THEN + RAISE EXCEPTION 'Definitively aborted World operation cannot apply' USING ERRCODE = '23514'; + END IF; + IF (SELECT count(DISTINCT family) FROM "${serviceSchema}".world_authored_topology_identity + WHERE request_id = NEW.request_id AND commit_id = NEW.commit_id) <> 6 THEN + RAISE EXCEPTION 'APPLIED requires all six genuinely mutated World families' USING ERRCODE = '23514'; + END IF; + FOR unit IN SELECT value FROM jsonb_array_elements(graph_row.binding_json::JSONB->'affectedUnits') + WHERE value->>'owner' = 'WORLD_MANAGEMENT' LOOP + IF unit->>'expectedEpoch' <> '0' THEN + RAISE EXCEPTION 'Fresh graph APPLIED requires original zero epochs' USING ERRCODE = '23514'; + END IF; + SELECT private_row_key INTO mapped_key FROM "${serviceSchema}".world_authored_topology_identity + WHERE request_id = NEW.request_id AND commit_id = NEW.commit_id + AND family = unit->>'aggregateType' AND template_id = (unit->>'aggregateId')::UUID; + IF NOT FOUND THEN + RAISE EXCEPTION 'APPLIED affected unit lacks exact fresh mapping' USING ERRCODE = '23514'; + END IF; + IF unit->>'scopeType' = 'AGGREGATE' THEN + SELECT draft_revision_epoch INTO current_epoch FROM "${serviceSchema}".world_design_aggregate_epoch + WHERE tenant_id = graph_row.local_tenant_key AND version_id = graph_row.local_version_key + AND aggregate_type = unit->>'aggregateType' AND aggregate_id = mapped_key; + ELSE + SELECT draft_scope_revision_epoch INTO current_epoch FROM "${serviceSchema}".world_design_scope_epoch + WHERE tenant_id = graph_row.local_tenant_key AND version_id = graph_row.local_version_key + AND scope_type = unit->>'scopeType' AND scope_id = unit->>'scopeId'; + END IF; + IF NOT FOUND OR current_epoch IS DISTINCT FROM 1::BIGINT THEN + RAISE EXCEPTION 'APPLIED lacks complete resulting World epochs' USING ERRCODE = '23514'; + END IF; + END LOOP; + NEW.application_transaction_id := txid_current(); + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_world_graph_application_guard BEFORE INSERT OR UPDATE OR DELETE + ON world_draft_graph_application FOR EACH ROW EXECUTE FUNCTION world_guard_graph_application(); +CREATE TRIGGER trg_world_graph_application_no_truncate BEFORE TRUNCATE + ON world_draft_graph_application FOR EACH STATEMENT + EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +CREATE FUNCTION world_abort_excludes_graph_application() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + PERFORM 1 FROM "${serviceSchema}".world_design_publication_fence_owner + WHERE target_namespace = NEW.target_namespace AND canonical_tenant_id = NEW.canonical_tenant_id + AND local_tenant_key = NEW.local_tenant_key AND version_id = NEW.local_version_key FOR UPDATE; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_draft_graph_application a + WHERE a.operation_id = NEW.operation_id OR a.request_id = NEW.request_id + OR a.commit_id = NEW.commit_id OR a.authorization_fence_id = NEW.authorization_fence_id) THEN + RAISE EXCEPTION 'Committed World graph cannot be relabeled as definitive no-commit' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_world_abort_excludes_graph_application BEFORE INSERT + ON world_draft_terminal_outcome FOR EACH ROW EXECUTE FUNCTION world_abort_excludes_graph_application(); +REVOKE ALL ON world_draft_graph_application FROM PUBLIC; +REVOKE ALL ON world_draft_graph_terminal_identity FROM PUBLIC; +REVOKE ALL ON FUNCTION world_claim_graph_terminal_identity() FROM PUBLIC; +REVOKE ALL ON FUNCTION world_verify_graph_terminal_identity_receipt() FROM PUBLIC; +REVOKE ALL ON FUNCTION world_stamp_topology_application_transaction() FROM PUBLIC; +REVOKE ALL ON FUNCTION world_guard_graph_application() FROM PUBLIC; +REVOKE ALL ON FUNCTION world_abort_excludes_graph_application() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1013__world_preparation_exact_release_graph.sql b/services/world-management-service/src/main/resources/db/migration/V1013__world_preparation_exact_release_graph.sql new file mode 100644 index 0000000000..a58b329d7a --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1013__world_preparation_exact_release_graph.sql @@ -0,0 +1,67 @@ +-- Retain the V35 function identity, access grants and complete original guard body. Add the +-- immutable release/checkpoint join before either retry readback or runtime allocation. +-- [jooq ignore start] +DO $migration$ +DECLARE + preparation_function REGPROCEDURE := + '"${serviceSchema}".world_prepare_canonical_instance(text,text)'::REGPROCEDURE; + original_definition TEXT; + insertion_point TEXT := $anchor$ IF identity_row.operation_id::TEXT IS DISTINCT FROM topology->>'versionIdentityOperationId'$anchor$; + join_guard TEXT := $guard$ IF binding_row.release_attestation_json::JSONB->>'targetNamespace' + IS DISTINCT FROM capture_row.freeze_request_json::JSONB->>'targetNamespace' + OR binding_row.release_attestation_json::JSONB->>'targetNamespace' + IS DISTINCT FROM identity_row.target_namespace + OR binding_row.release_attestation_json::JSONB->>'canonicalTenantId' + IS DISTINCT FROM identity_row.canonical_tenant_id::TEXT + OR binding_row.release_attestation_json::JSONB->>'canonicalTenantId' + IS DISTINCT FROM capture_row.freeze_request_json::JSONB->>'canonicalTenantId' + OR binding_row.release_attestation_json::JSONB->>'canonicalVersionId' + IS DISTINCT FROM identity_row.canonical_version_id::TEXT + OR binding_row.release_attestation_json::JSONB->>'canonicalVersionId' + IS DISTINCT FROM capture_row.freeze_request_json::JSONB->>'canonicalVersionId' + OR binding_row.release_attestation_json::JSONB->>'canonicalVersionId' + IS DISTINCT FROM capture_row.binding_json::JSONB->>'canonicalVersionId' + OR binding_row.release_attestation_json::JSONB->>'canonicalTenantId' + IS DISTINCT FROM capture_row.binding_json::JSONB->>'canonicalTenantId' + OR binding_row.release_attestation_json::JSONB->>'commitId' + IS DISTINCT FROM capture_row.commit_id::TEXT + OR binding_row.release_attestation_json::JSONB->>'commitId' + IS DISTINCT FROM capture_row.binding_json::JSONB->>'commitId' + OR binding_row.release_attestation_json::JSONB->>'commitId' + IS DISTINCT FROM capture_row.freeze_request_json::JSONB->>'appliedCommitId' + OR binding_row.release_attestation_json::JSONB->>'publishWorkflowId' + IS DISTINCT FROM capture_row.freeze_request_json::JSONB->>'publishWorkflowId' + OR (SELECT count(*) FROM jsonb_array_elements( + CASE WHEN jsonb_typeof(binding_row.release_attestation_json::JSONB->'participantDigests') = 'array' + THEN binding_row.release_attestation_json::JSONB->'participantDigests' + ELSE '[]'::JSONB END) participant + WHERE participant->>'participantKey' = 'WORLD_MANAGEMENT') <> 1 + OR NOT EXISTS ( + SELECT 1 FROM jsonb_array_elements( + CASE WHEN jsonb_typeof(binding_row.release_attestation_json::JSONB->'participantDigests') = 'array' + THEN binding_row.release_attestation_json::JSONB->'participantDigests' + ELSE '[]'::JSONB END) participant + WHERE participant->>'participantKey' = 'WORLD_MANAGEMENT' + AND participant->>'scopeValue' = identity_row.game_design_version_id::TEXT + AND participant->>'baseVersionIdPresent' = 'false' + AND participant->'baseVersionId' = 'null'::JSONB + AND participant->>'appliedCommitId' = capture_row.freeze_request_json::JSONB->>'appliedCommitId' + AND participant->>'contentDigest' = capture_row.freeze_request_json::JSONB->>'contentDigest' + AND participant->>'digestSchemaVersion' = capture_row.freeze_request_json::JSONB->>'digestSchemaVersion' + AND participant->>'digestSchemaVersion' = '3' + ) THEN + RAISE EXCEPTION 'Canonical preparation release differs from the exact selected frozen World graph' + USING ERRCODE = '23514'; + END IF; + +$guard$; +BEGIN + SELECT pg_get_functiondef(preparation_function) INTO STRICT original_definition; + IF (length(original_definition) - length(replace(original_definition, insertion_point, ''))) + / length(insertion_point) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V35 canonical preparation release-join insertion point'; + END IF; + EXECUTE replace(original_definition, insertion_point, join_guard || insertion_point); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1014__world_explicit_fresh_graph_start_location.sql b/services/world-management-service/src/main/resources/db/migration/V1014__world_explicit_fresh_graph_start_location.sql new file mode 100644 index 0000000000..543b4b8c84 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1014__world_explicit_fresh_graph_start_location.sql @@ -0,0 +1,292 @@ +CREATE TABLE world_draft_start_location_receipt ( + operation_id UUID PRIMARY KEY, + request_id UUID NOT NULL UNIQUE, + commit_id UUID NOT NULL UNIQUE, + authorization_fence_id UUID NOT NULL UNIQUE, + target_namespace VARCHAR(128) NOT NULL, + account_binding_bytes BYTEA NOT NULL CHECK (octet_length(account_binding_bytes) > 0), + account_binding_digest VARCHAR(71) NOT NULL CHECK (account_binding_digest ~ '^sha256:[0-9a-f]{64}$'), + binding_digest VARCHAR(71) NOT NULL CHECK (binding_digest ~ '^sha256:[0-9a-f]{64}$'), + canonical_tenant_id UUID NOT NULL CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + canonical_version_id UUID NOT NULL CHECK (canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID), + room_template_id UUID NOT NULL CHECK (room_template_id <> '00000000-0000-0000-0000-000000000000'::UUID), + graph_digest VARCHAR(71) NOT NULL CHECK (graph_digest ~ '^sha256:[0-9a-f]{64}$'), + receipt_digest VARCHAR(71) NOT NULL CHECK (receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + receipt_bytes BYTEA NOT NULL CHECK (octet_length(receipt_bytes) > 0), + recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT fk_world_draft_start_location_application + FOREIGN KEY (operation_id) REFERENCES world_draft_graph_application(operation_id) + DEFERRABLE INITIALLY DEFERRED, + CHECK (operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND commit_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND authorization_fence_id <> '00000000-0000-0000-0000-000000000000'::UUID) +); + +-- [jooq ignore start] +CREATE FUNCTION world_reject_draft_start_location_receipt_mutation() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + RAISE EXCEPTION 'World original start-location receipts are immutable and retained' + USING ERRCODE = '23514'; +END; +$$; +CREATE TRIGGER trg_world_start_location_receipt_immutable + BEFORE UPDATE OR DELETE ON world_draft_start_location_receipt + FOR EACH ROW EXECUTE FUNCTION world_reject_draft_start_location_receipt_mutation(); +CREATE TRIGGER trg_world_start_location_receipt_no_truncate + BEFORE TRUNCATE ON world_draft_start_location_receipt + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_draft_start_location_receipt_mutation(); + +CREATE FUNCTION world_guard_draft_start_location_receipt() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + graph_row "${serviceSchema}".world_topology_draft_commit%ROWTYPE; + declaration JSONB; + start_location JSONB; + declaration_count BIGINT; +BEGIN + SELECT * INTO graph_row FROM "${serviceSchema}".world_topology_draft_commit + WHERE request_id = NEW.request_id AND commit_id = NEW.commit_id; + IF NOT FOUND OR graph_row.application_transaction_id IS DISTINCT FROM txid_current() THEN + RAISE EXCEPTION 'World start-location receipt requires its exact fresh graph transaction' + USING ERRCODE = '23514'; + END IF; + SELECT count(*) INTO declaration_count + FROM jsonb_array_elements(graph_row.binding_json::JSONB->'revisions') AS revision(value) + WHERE value->>'owner' = 'WORLD_MANAGEMENT' + AND ((value->>'payload')::JSONB ? 'freshGraphDeclaration'); + IF declaration_count <> 1 THEN + RAISE EXCEPTION 'World start-location receipt requires exactly one original graph declaration' + USING ERRCODE = '23514'; + END IF; + SELECT ((value->>'payload')::JSONB)->'freshGraphDeclaration' INTO declaration + FROM jsonb_array_elements(graph_row.binding_json::JSONB->'revisions') AS revision(value) + WHERE value->>'owner' = 'WORLD_MANAGEMENT' + AND ((value->>'payload')::JSONB ? 'freshGraphDeclaration'); + start_location := declaration->'startLocation'; + IF NEW.operation_id = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.request_id IS DISTINCT FROM graph_row.request_id + OR NEW.commit_id IS DISTINCT FROM graph_row.commit_id + OR NEW.target_namespace IS DISTINCT FROM graph_row.target_namespace + OR NEW.binding_digest IS DISTINCT FROM graph_row.binding_digest + OR NEW.canonical_tenant_id IS DISTINCT FROM graph_row.canonical_tenant_id + OR NEW.canonical_version_id IS DISTINCT FROM graph_row.canonical_version_id + OR declaration->>'tenantId' IS DISTINCT FROM graph_row.canonical_tenant_id::TEXT + OR declaration->>'versionId' IS DISTINCT FROM graph_row.canonical_version_id::TEXT + OR start_location->>'tenantId' IS DISTINCT FROM graph_row.canonical_tenant_id::TEXT + OR start_location->>'versionId' IS DISTINCT FROM graph_row.canonical_version_id::TEXT + OR start_location->>'roomTemplateId' IS NULL + OR start_location->>'roomTemplateId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR NEW.room_template_id = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.room_template_id IS DISTINCT FROM (start_location->>'roomTemplateId')::UUID + OR NEW.graph_digest IS DISTINCT FROM ('sha256:' || graph_row.graph_sha256) + OR NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_authored_topology_identity m + JOIN "${serviceSchema}".room r ON r.id = m.private_row_key + WHERE m.target_namespace = graph_row.target_namespace + AND m.canonical_tenant_id = graph_row.canonical_tenant_id + AND m.canonical_version_id = graph_row.canonical_version_id + AND m.family = 'ROOM' + AND m.template_id = NEW.room_template_id + AND m.request_id = NEW.request_id + AND m.commit_id = NEW.commit_id + AND m.tenant_id = graph_row.local_tenant_key + AND m.version_id = graph_row.local_version_key + AND r.tenant_id = graph_row.local_tenant_key + AND r.version_id = graph_row.local_version_key) + THEN + RAISE EXCEPTION 'World typed start selector differs from exact original graph/Version/ROOM' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_world_start_location_receipt_guard + BEFORE INSERT ON world_draft_start_location_receipt + FOR EACH ROW EXECUTE FUNCTION world_guard_draft_start_location_receipt(); + +-- V39 required six populated families. The Account-bound application now proves all six declared +-- counts, including explicit zero families, against the original binding and exact Version rows. +CREATE OR REPLACE FUNCTION world_guard_graph_application() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + graph_row "${serviceSchema}".world_topology_draft_commit%ROWTYPE; + owner_row "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + receipt "${serviceSchema}".world_draft_start_location_receipt%ROWTYPE; + unit JSONB; + declaration JSONB; + start_location JSONB; + family_entry JSONB; + family_names TEXT[] := ARRAY[ + 'REGION','ZONE','ROOM','ROOM_EXIT','GENERATION_RULE','WORLD_ENTITY_SPAWN_BINDING']; + family_name TEXT; + declared_count BIGINT; + mapping_count BIGINT; + content_count BIGINT; + declaration_count BIGINT; + receipt_count BIGINT; + family_index INTEGER; + mapped_key BIGINT; + current_epoch BIGINT; + result_json JSONB; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'World graph APPLIED results are immutable and retained' USING ERRCODE = '23514'; + END IF; + SELECT * INTO graph_row FROM "${serviceSchema}".world_topology_draft_commit + WHERE request_id = NEW.request_id AND commit_id = NEW.commit_id; + IF NOT FOUND OR graph_row.application_transaction_id IS DISTINCT FROM txid_current() THEN + RAISE EXCEPTION 'APPLIED requires a genuine fresh graph in the same transaction; old history cannot be promoted' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO owner_row FROM "${serviceSchema}".world_design_publication_fence_owner + WHERE target_namespace = graph_row.target_namespace + AND canonical_tenant_id = graph_row.canonical_tenant_id + AND local_tenant_key = graph_row.local_tenant_key + AND version_id = graph_row.local_version_key FOR UPDATE; + IF NOT FOUND OR owner_row.owner_freeze_phase <> 'OPEN' + OR owner_row.current_publication_fence IS NOT NULL THEN + RAISE EXCEPTION 'Fresh graph APPLIED requires exact OPEN V25 owner' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_draft_terminal_outcome t + WHERE t.operation_id = NEW.operation_id OR t.request_id = NEW.request_id + OR t.commit_id = NEW.commit_id OR t.authorization_fence_id = NEW.authorization_fence_id) THEN + RAISE EXCEPTION 'Definitively aborted World operation cannot apply' USING ERRCODE = '23514'; + END IF; + SELECT count(*) INTO declaration_count + FROM jsonb_array_elements(graph_row.binding_json::JSONB->'revisions') AS revision(value) + WHERE value->>'owner' = 'WORLD_MANAGEMENT' + AND ((value->>'payload')::JSONB ? 'freshGraphDeclaration'); + IF declaration_count <> 1 THEN + RAISE EXCEPTION 'Fresh graph APPLIED requires exactly one original complete declaration' + USING ERRCODE = '23514'; + END IF; + SELECT ((value->>'payload')::JSONB)->'freshGraphDeclaration' INTO declaration + FROM jsonb_array_elements(graph_row.binding_json::JSONB->'revisions') AS revision(value) + WHERE value->>'owner' = 'WORLD_MANAGEMENT' + AND ((value->>'payload')::JSONB ? 'freshGraphDeclaration'); + start_location := declaration->'startLocation'; + IF declaration->>'tenantId' IS DISTINCT FROM graph_row.canonical_tenant_id::TEXT + OR declaration->>'versionId' IS DISTINCT FROM graph_row.canonical_version_id::TEXT + OR start_location->>'tenantId' IS DISTINCT FROM graph_row.canonical_tenant_id::TEXT + OR start_location->>'versionId' IS DISTINCT FROM graph_row.canonical_version_id::TEXT + OR jsonb_typeof(declaration->'familyCounts') IS DISTINCT FROM 'array' + OR jsonb_array_length(declaration->'familyCounts') <> 6 THEN + RAISE EXCEPTION 'Fresh graph APPLIED declaration has wrong canonical scope or family vector' + USING ERRCODE = '23514'; + END IF; + FOR family_index IN 1..6 LOOP + family_entry := declaration->'familyCounts'->(family_index - 1); + family_name := family_names[family_index]; + IF family_entry->>'family' IS DISTINCT FROM + ('WORLD_DESIGN_AGGREGATE_TYPE_' || family_name) + OR NOT (family_entry ? 'count') + OR jsonb_typeof(family_entry->'count') IS DISTINCT FROM 'number' + OR (family_entry->>'count') !~ '^(0|[1-9][0-9]*)$' + OR (family_entry->>'count')::NUMERIC > 2147483647 THEN + RAISE EXCEPTION 'Fresh graph APPLIED family declaration is absent, changed or noncanonical' + USING ERRCODE = '23514'; + END IF; + declared_count := (family_entry->>'count')::BIGINT; + SELECT count(*) INTO mapping_count FROM "${serviceSchema}".world_authored_topology_identity + WHERE request_id = NEW.request_id AND commit_id = NEW.commit_id AND family = family_name; + EXECUTE format('SELECT count(*) FROM %I.%I WHERE tenant_id=$1 AND version_id=$2', + '${serviceSchema}', lower(family_name)) + INTO content_count USING graph_row.local_tenant_key, graph_row.local_version_key; + IF mapping_count IS DISTINCT FROM declared_count + OR content_count IS DISTINCT FROM declared_count THEN + RAISE EXCEPTION 'APPLIED requires every declared World family row and explicit empty family for exact Version' + USING ERRCODE = '23514'; + END IF; + END LOOP; + IF start_location->>'roomTemplateId' IS NULL + OR start_location->>'roomTemplateId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (start_location->>'roomTemplateId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_authored_topology_identity m + JOIN "${serviceSchema}".room r ON r.id = m.private_row_key + WHERE m.target_namespace = graph_row.target_namespace + AND m.canonical_tenant_id = graph_row.canonical_tenant_id + AND m.canonical_version_id = graph_row.canonical_version_id + AND m.family = 'ROOM' + AND m.template_id = (start_location->>'roomTemplateId')::UUID + AND m.request_id = NEW.request_id AND m.commit_id = NEW.commit_id + AND m.tenant_id = graph_row.local_tenant_key AND m.version_id = graph_row.local_version_key + AND r.tenant_id = graph_row.local_tenant_key AND r.version_id = graph_row.local_version_key) THEN + RAISE EXCEPTION 'APPLIED start selector must name one exact ROOM row in this graph and Version' + USING ERRCODE = '23514'; + END IF; + SELECT count(*) INTO receipt_count FROM "${serviceSchema}".world_draft_start_location_receipt + WHERE operation_id = NEW.operation_id OR request_id = NEW.request_id + OR commit_id = NEW.commit_id OR authorization_fence_id = NEW.authorization_fence_id; + IF receipt_count <> 1 THEN + RAISE EXCEPTION 'APPLIED requires one exact durable start-location receipt' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT receipt FROM "${serviceSchema}".world_draft_start_location_receipt + WHERE operation_id = NEW.operation_id OR request_id = NEW.request_id + OR commit_id = NEW.commit_id OR authorization_fence_id = NEW.authorization_fence_id; + IF receipt.operation_id IS DISTINCT FROM NEW.operation_id + OR receipt.request_id IS DISTINCT FROM NEW.request_id + OR receipt.commit_id IS DISTINCT FROM NEW.commit_id + OR receipt.authorization_fence_id IS DISTINCT FROM NEW.authorization_fence_id + OR receipt.target_namespace IS DISTINCT FROM graph_row.target_namespace + OR receipt.account_binding_bytes IS DISTINCT FROM NEW.account_binding_bytes + OR receipt.account_binding_digest IS DISTINCT FROM NEW.account_binding_digest + OR receipt.binding_digest IS DISTINCT FROM graph_row.binding_digest + OR receipt.canonical_tenant_id IS DISTINCT FROM graph_row.canonical_tenant_id + OR receipt.canonical_version_id IS DISTINCT FROM graph_row.canonical_version_id + OR receipt.room_template_id IS DISTINCT FROM (start_location->>'roomTemplateId')::UUID + OR receipt.graph_digest IS DISTINCT FROM ('sha256:' || graph_row.graph_sha256) + OR receipt.receipt_digest !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'APPLIED requires exact durable original Account-bound start selector receipt' + USING ERRCODE = '23514'; + END IF; + result_json := convert_from(NEW.result_bytes, 'UTF8')::JSONB; + IF result_json->>'schema' IS DISTINCT FROM 'world-draft-graph-applied/v2' + OR result_json->>'status' IS DISTINCT FROM 'APPLIED' + OR result_json->>'graphDigest' IS DISTINCT FROM ('sha256:' || graph_row.graph_sha256) + OR result_json->>'startLocationReceiptDigest' IS DISTINCT FROM receipt.receipt_digest + OR decode(result_json->>'startLocationReceiptBase64', 'base64') IS DISTINCT FROM receipt.receipt_bytes + OR decode(result_json->>'operationBytesBase64', 'base64') IS DISTINCT FROM NEW.operation_bytes + OR decode(result_json->>'graphBytesBase64', 'base64') IS DISTINCT FROM graph_row.graph_bytes THEN + RAISE EXCEPTION 'APPLIED result does not retain the exact graph, operation and start selector' + USING ERRCODE = '23514'; + END IF; + FOR unit IN SELECT value FROM jsonb_array_elements(graph_row.binding_json::JSONB->'affectedUnits') + WHERE value->>'owner' = 'WORLD_MANAGEMENT' LOOP + IF unit->>'expectedEpoch' <> '0' THEN + RAISE EXCEPTION 'Fresh graph APPLIED requires original zero epochs' USING ERRCODE = '23514'; + END IF; + SELECT private_row_key INTO mapped_key FROM "${serviceSchema}".world_authored_topology_identity + WHERE request_id = NEW.request_id AND commit_id = NEW.commit_id + AND family = unit->>'aggregateType' AND template_id = (unit->>'aggregateId')::UUID; + IF NOT FOUND THEN + RAISE EXCEPTION 'APPLIED affected unit lacks exact fresh mapping' USING ERRCODE = '23514'; + END IF; + IF unit->>'scopeType' = 'AGGREGATE' THEN + SELECT draft_revision_epoch INTO current_epoch FROM "${serviceSchema}".world_design_aggregate_epoch + WHERE tenant_id = graph_row.local_tenant_key AND version_id = graph_row.local_version_key + AND aggregate_type = unit->>'aggregateType' AND aggregate_id = mapped_key; + ELSE + SELECT draft_scope_revision_epoch INTO current_epoch FROM "${serviceSchema}".world_design_scope_epoch + WHERE tenant_id = graph_row.local_tenant_key AND version_id = graph_row.local_version_key + AND scope_type = unit->>'scopeType' AND scope_id = unit->>'scopeId'; + END IF; + IF NOT FOUND OR current_epoch IS DISTINCT FROM 1::BIGINT THEN + RAISE EXCEPTION 'APPLIED lacks complete resulting World epochs' USING ERRCODE = '23514'; + END IF; + END LOOP; + NEW.application_transaction_id := txid_current(); + RETURN NEW; +END; +$$; +REVOKE ALL ON world_draft_start_location_receipt FROM PUBLIC; +REVOKE ALL ON FUNCTION world_reject_draft_start_location_receipt_mutation() FROM PUBLIC; +REVOKE ALL ON FUNCTION world_guard_draft_start_location_receipt() FROM PUBLIC; +REVOKE ALL ON FUNCTION world_guard_graph_application() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1015__world_release_start_location_materialization.sql b/services/world-management-service/src/main/resources/db/migration/V1015__world_release_start_location_materialization.sql new file mode 100644 index 0000000000..108d82c335 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1015__world_release_start_location_materialization.sql @@ -0,0 +1,227 @@ +-- Keep V1 materialization history inert and byte-for-byte retryable. V2 retains the authored +-- ROOM reference separately from its exact World-owned runtime mapping; neither activates it. +CREATE TABLE world_canonical_preparation_start_location ( + canonical_game_instance_id UUID PRIMARY KEY REFERENCES world_canonical_instance_preparation(canonical_game_instance_id) ON DELETE RESTRICT, + world_instance_id BIGINT NOT NULL REFERENCES world_instance(id) ON DELETE RESTRICT, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + room_template_id UUID NOT NULL, + runtime_room_instance_id BIGINT NOT NULL CHECK (runtime_room_instance_id > 0), + receipt_digest VARCHAR(71) NOT NULL CHECK (receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + graph_digest VARCHAR(71) NOT NULL CHECK (graph_digest ~ '^sha256:[0-9a-f]{64}$'), + evidence_bytes BYTEA NOT NULL CHECK (octet_length(evidence_bytes) > 0), + recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +-- [jooq ignore start] +REVOKE ALL ON world_canonical_preparation_start_location FROM PUBLIC; + +-- This independently checks immutable producer evidence before allocation and on every retry. +CREATE FUNCTION world_require_preparation_start_location(input JSONB, binding JSONB, capture UUID) +RETURNS VOID LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + frozen "${serviceSchema}".world_canonical_frozen_topology%ROWTYPE; + receipt "${serviceSchema}".world_draft_start_location_receipt%ROWTYPE; + application "${serviceSchema}".world_draft_graph_application%ROWTYPE; + graph "${serviceSchema}".world_topology_draft_commit%ROWTYPE; + evidence JSONB; + selected JSONB; + publication_request JSONB; + retained JSONB; + retained_version_state_epoch BIGINT; + expected_tuples JSONB; +BEGIN + IF input->>'schemaVersion' = '1' THEN + IF binding->>'schemaVersion' IS DISTINCT FROM '1' + OR binding ? 'worldStartLocationEvidence' OR input ? 'worldStartLocationEvidenceBase64' THEN + RAISE EXCEPTION 'V1 preparation cannot acquire selector evidence' USING ERRCODE = '23514'; + END IF; + RETURN; + END IF; + IF input->>'schemaVersion' IS DISTINCT FROM '2' OR binding->>'schemaVersion' IS DISTINCT FROM '2' + OR input->>'worldStartLocationEvidenceBase64' IS NULL + OR jsonb_typeof(binding->'worldStartLocationEvidence') IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'V2 preparation requires original complete World selector evidence' USING ERRCODE = '23514'; + END IF; + evidence := convert_from(decode(input->>'worldStartLocationEvidenceBase64', 'base64'), 'UTF8')::JSONB; + selected := evidence->'request'; + retained := binding->'worldStartLocationEvidence'; + IF jsonb_typeof(retained->'request') IS DISTINCT FROM 'object' + OR jsonb_typeof(retained->'request'->'versionStateEpoch') IS DISTINCT FROM 'number' + OR retained->'request'->>'versionStateEpoch' !~ '^[1-9][0-9]*$' THEN + RAISE EXCEPTION 'Retained full release selector epoch must be a canonical positive JSON number' + USING ERRCODE = '23514'; + END IF; + retained_version_state_epoch := (retained->'request'->>'versionStateEpoch')::BIGINT; + SELECT * INTO STRICT frozen FROM "${serviceSchema}".world_canonical_frozen_topology WHERE capture_id=capture; + publication_request := frozen.freeze_request_json::JSONB; + SELECT coalesce(jsonb_agg(value ORDER BY value->>'owner',value->>'aggregateType',value->>'aggregateId', + value->>'scopeType',value->>'scopeId',value->>'expectedEpoch'), '[]'::JSONB) + INTO expected_tuples FROM jsonb_array_elements(publication_request->'suppliedOwnedAffectedTuples'); + IF evidence->>'schema' IS DISTINCT FROM 'world-published-start-location-evidence/v1' + OR (SELECT count(*) FROM jsonb_object_keys(evidence)) <> 5 + OR selected IS DISTINCT FROM jsonb_set( + retained->'request', '{versionStateEpoch}', to_jsonb(retained_version_state_epoch::TEXT), FALSE) + OR (SELECT count(*) FROM jsonb_object_keys(selected)) <> 13 + OR selected->>'targetNamespace' IS DISTINCT FROM publication_request->>'targetNamespace' + OR selected->>'canonicalTenantId' IS DISTINCT FROM publication_request->>'canonicalTenantId' + OR selected->>'canonicalVersionId' IS DISTINCT FROM publication_request->>'canonicalVersionId' + OR selected->>'intakeRequestId' IS DISTINCT FROM publication_request->>'intakeRequestId' + OR selected->>'publicationFence' IS DISTINCT FROM publication_request->>'publicationFence' + OR selected->>'publicationRequestId' IS DISTINCT FROM publication_request->>'publicationRequestId' + OR selected->>'requestDigest' IS DISTINCT FROM publication_request->>'requestDigest' + OR selected->>'versionStateEpoch' IS DISTINCT FROM publication_request->>'versionStateEpoch' + OR selected->>'publishWorkflowId' IS DISTINCT FROM publication_request->>'publishWorkflowId' + OR selected->>'appliedCommitId' IS DISTINCT FROM publication_request->>'appliedCommitId' + OR selected->>'contentDigest' IS DISTINCT FROM publication_request->>'contentDigest' + OR selected->>'digestSchemaVersion' IS DISTINCT FROM '3' + OR selected->>'digestSchemaVersion' IS DISTINCT FROM publication_request->>'digestSchemaVersion' + OR selected->'worldAffectedTuples' IS DISTINCT FROM expected_tuples + OR decode(evidence->>'selectorReceiptBytesBase64','base64') IS DISTINCT FROM decode(retained->>'selectorReceiptBytes','base64') + OR decode(evidence->>'originalAccountBindingBytesBase64','base64') IS DISTINCT FROM decode(retained->>'originalAccountBindingBytes','base64') + OR decode(evidence->>'appliedResultBytesBase64','base64') IS DISTINCT FROM decode(retained->>'appliedResultBytes','base64') THEN + RAISE EXCEPTION 'Preparation selector differs from complete frozen request or retained release bytes' USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT receipt FROM "${serviceSchema}".world_draft_start_location_receipt + WHERE request_id=frozen.request_id AND commit_id=frozen.commit_id; + SELECT * INTO STRICT application FROM "${serviceSchema}".world_draft_graph_application + WHERE operation_id=receipt.operation_id AND request_id=receipt.request_id AND commit_id=receipt.commit_id + AND authorization_fence_id=receipt.authorization_fence_id; + SELECT * INTO STRICT graph FROM "${serviceSchema}".world_topology_draft_commit + WHERE request_id=frozen.request_id AND commit_id=frozen.commit_id; + IF receipt.target_namespace IS DISTINCT FROM selected->>'targetNamespace' + OR receipt.canonical_tenant_id::TEXT IS DISTINCT FROM selected->>'canonicalTenantId' + OR receipt.canonical_version_id::TEXT IS DISTINCT FROM selected->>'canonicalVersionId' + OR receipt.binding_digest IS DISTINCT FROM graph.binding_digest + OR receipt.graph_digest IS DISTINCT FROM ('sha256:' || frozen.graph_sha256) + OR graph.graph_bytes IS DISTINCT FROM frozen.graph_bytes + OR graph.binding_json IS DISTINCT FROM frozen.binding_json + OR graph.owner_binding_json IS DISTINCT FROM frozen.owner_binding_json + OR receipt.account_binding_bytes IS DISTINCT FROM application.account_binding_bytes + OR receipt.account_binding_digest IS DISTINCT FROM application.account_binding_digest + OR receipt.receipt_bytes IS DISTINCT FROM decode(evidence->>'selectorReceiptBytesBase64','base64') + OR receipt.account_binding_bytes IS DISTINCT FROM decode(evidence->>'originalAccountBindingBytesBase64','base64') + OR application.result_bytes IS DISTINCT FROM decode(evidence->>'appliedResultBytesBase64','base64') + OR convert_from(application.result_bytes,'UTF8')::JSONB->>'schema' IS DISTINCT FROM 'world-draft-graph-applied/v2' + OR convert_from(application.result_bytes,'UTF8')::JSONB->>'status' IS DISTINCT FROM 'APPLIED' + OR NOT EXISTS (SELECT 1 FROM "${serviceSchema}".world_authored_topology_identity m + JOIN "${serviceSchema}".room r ON r.id=m.private_row_key + WHERE m.request_id=frozen.request_id AND m.commit_id=frozen.commit_id AND m.family='ROOM' + AND m.template_id=receipt.room_template_id AND m.canonical_tenant_id=receipt.canonical_tenant_id + AND m.canonical_version_id=receipt.canonical_version_id AND m.target_namespace=receipt.target_namespace + AND r.tenant_id=graph.local_tenant_key AND r.version_id=graph.local_version_key + AND m.tenant_id=r.tenant_id AND m.version_id=r.version_id) THEN + RAISE EXCEPTION 'Preparation selector lacks exact original Account/APPLIED/graph/ROOM evidence' USING ERRCODE = '23514'; + END IF; +END; +$$; +REVOKE ALL ON FUNCTION world_require_preparation_start_location(JSONB, JSONB, UUID) FROM PUBLIC; + +-- Amend only the input-schema gate and insert additional guards. Preserve the complete existing +-- V35/V40 guard body, grants, ownership, materialization writes and V1 historical input bytes. +DO $migration$ +DECLARE + original TEXT; + schema_anchor TEXT := $anchor$ IF p->>'schemaVersion' IS DISTINCT FROM '1' THEN$anchor$; + join_anchor TEXT := $anchor$ IF identity_row.operation_id::TEXT IS DISTINCT FROM topology->>'versionIdentityOperationId'$anchor$; + retry_anchor TEXT := $anchor$ IF FOUND THEN + IF prior.input_json IS DISTINCT FROM p_input_json$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_prepare_canonical_instance(text,text)'::REGPROCEDURE) INTO STRICT original; + IF (length(original)-length(replace(original,schema_anchor,'')))/length(schema_anchor) <> 1 + OR (length(original)-length(replace(original,join_anchor,'')))/length(join_anchor) <> 1 + OR (length(original)-length(replace(original,retry_anchor,'')))/length(retry_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one original preparation schema/join/retry guard'; + END IF; + original := replace(original,schema_anchor,$replacement$ IF p->>'schemaVersion' IS NULL OR p->>'schemaVersion' NOT IN ('1','2') THEN$replacement$); + original := replace(original,join_anchor,$replacement$ PERFORM "${serviceSchema}".world_require_preparation_start_location(p, binding_row.release_attestation_json::JSONB, capture_row.capture_id); + +$replacement$ || join_anchor); + original := replace(original,retry_anchor,$replacement$ IF FOUND THEN + IF p->>'schemaVersion' = '2' AND NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_canonical_preparation_start_location s + WHERE s.canonical_game_instance_id=prior.canonical_game_instance_id + AND s.world_instance_id=prior.world_instance_id + AND s.evidence_bytes=decode(p->>'worldStartLocationEvidenceBase64','base64')) THEN + RAISE EXCEPTION 'V2 preparation retry lacks original selector readback' USING ERRCODE='23514'; + END IF; + IF prior.input_json IS DISTINCT FROM p_input_json$replacement$); + EXECUTE original; +END; +$migration$; + +CREATE FUNCTION world_retain_preparation_start_location() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,"${serviceSchema}" +AS $$ +DECLARE + receipt "${serviceSchema}".world_draft_start_location_receipt%ROWTYPE; + mapping "${serviceSchema}".world_canonical_instance_topology_identity%ROWTYPE; + frozen "${serviceSchema}".world_canonical_frozen_topology%ROWTYPE; +BEGIN + IF NEW.input_json::JSONB->>'schemaVersion' = '1' THEN RETURN NEW; END IF; + SELECT * INTO STRICT frozen FROM "${serviceSchema}".world_canonical_frozen_topology WHERE capture_id=NEW.capture_id; + SELECT * INTO STRICT receipt FROM "${serviceSchema}".world_draft_start_location_receipt + WHERE request_id=frozen.request_id AND commit_id=frozen.commit_id; + SELECT * INTO STRICT mapping FROM "${serviceSchema}".world_canonical_instance_topology_identity + WHERE world_instance_id=NEW.world_instance_id AND canonical_game_instance_id=NEW.canonical_game_instance_id + AND family='ROOM' AND template_id=receipt.room_template_id; + INSERT INTO "${serviceSchema}".world_canonical_preparation_start_location + (canonical_game_instance_id,world_instance_id,canonical_tenant_id,canonical_version_id,room_template_id, + runtime_room_instance_id,receipt_digest,graph_digest,evidence_bytes) + VALUES (NEW.canonical_game_instance_id,NEW.world_instance_id,receipt.canonical_tenant_id,receipt.canonical_version_id, + receipt.room_template_id,mapping.runtime_room_instance_id,receipt.receipt_digest,receipt.graph_digest, + decode(NEW.input_json::JSONB->>'worldStartLocationEvidenceBase64','base64')); + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_world_preparation_retain_start_location AFTER INSERT ON world_canonical_instance_preparation + FOR EACH ROW EXECUTE FUNCTION world_retain_preparation_start_location(); + +CREATE FUNCTION world_guard_preparation_start_location() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,"${serviceSchema}" +AS $$ +DECLARE + prepared "${serviceSchema}".world_canonical_instance_preparation%ROWTYPE; + binding TEXT; + original JSONB; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Original canonical preparation selector is immutable and retained' USING ERRCODE='23514'; + END IF; + SELECT p.* INTO STRICT prepared FROM "${serviceSchema}".world_canonical_instance_preparation p + WHERE p.canonical_game_instance_id=NEW.canonical_game_instance_id + AND p.xmin::TEXT=(txid_current() % 4294967296)::TEXT; + original := prepared.input_json::JSONB; + SELECT release_attestation_json INTO STRICT binding FROM "${serviceSchema}".world_complete_launch_binding + WHERE binding_operation_id=(original->'launchBinding'->>'operationId')::UUID; + IF original->>'schemaVersion' IS DISTINCT FROM '2' + OR prepared.world_instance_id IS DISTINCT FROM NEW.world_instance_id + OR prepared.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR prepared.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR NEW.evidence_bytes IS DISTINCT FROM decode(original->>'worldStartLocationEvidenceBase64','base64') + OR NOT EXISTS (SELECT 1 FROM "${serviceSchema}".world_draft_start_location_receipt s + JOIN "${serviceSchema}".world_canonical_frozen_topology f ON f.request_id=s.request_id AND f.commit_id=s.commit_id + WHERE f.capture_id=prepared.capture_id AND s.canonical_tenant_id=NEW.canonical_tenant_id + AND s.canonical_version_id=NEW.canonical_version_id AND s.room_template_id=NEW.room_template_id + AND s.receipt_digest=NEW.receipt_digest AND s.graph_digest=NEW.graph_digest) + OR NOT EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_topology_identity m + JOIN "${serviceSchema}".room_instance r ON r.id=m.runtime_row_id + JOIN "${serviceSchema}".world_instance w ON w.id=m.world_instance_id + WHERE m.world_instance_id=prepared.world_instance_id AND m.canonical_game_instance_id=NEW.canonical_game_instance_id + AND m.family='ROOM' AND m.template_id=NEW.room_template_id + AND m.runtime_room_instance_id=NEW.runtime_room_instance_id AND r.room_instance_row_id=NEW.runtime_room_instance_id + AND r.tenant_id=w.tenant_id AND r.game_instance_id=w.game_instance_id) THEN + RAISE EXCEPTION 'Original preparation selector differs from exact authored/runtime ROOM mapping' USING ERRCODE='23514'; + END IF; + PERFORM "${serviceSchema}".world_require_preparation_start_location(original,binding::JSONB,prepared.capture_id); + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_world_preparation_start_location_guard BEFORE INSERT OR UPDATE OR DELETE ON world_canonical_preparation_start_location + FOR EACH ROW EXECUTE FUNCTION world_guard_preparation_start_location(); +CREATE TRIGGER trg_world_preparation_start_location_no_truncate BEFORE TRUNCATE ON world_canonical_preparation_start_location + FOR EACH STATEMENT EXECUTE FUNCTION world_guard_preparation_start_location(); +REVOKE ALL ON FUNCTION world_retain_preparation_start_location() FROM PUBLIC; +REVOKE ALL ON FUNCTION world_guard_preparation_start_location() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1016__canonical_instance_activation_operation.sql b/services/world-management-service/src/main/resources/db/migration/V1016__canonical_instance_activation_operation.sql new file mode 100644 index 0000000000..175c33022a --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1016__canonical_instance_activation_operation.sql @@ -0,0 +1,565 @@ +-- Canonical World activation is one immutable owner operation. A row can become ACTIVE only +-- through the exact PREPARING epoch/row-version CAS retained here. +CREATE TABLE world_canonical_instance_activation_operation ( + activation_request_id UUID PRIMARY KEY, + request_digest VARCHAR(71) NOT NULL CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'), + request_bytes BYTEA NOT NULL CHECK (octet_length(request_bytes) > 0), + preparing_evidence_bytes BYTEA NOT NULL CHECK (octet_length(preparing_evidence_bytes) > 0), + canonical_game_instance_id UUID NOT NULL, + world_instance_id BIGINT NOT NULL, + expected_lifecycle_epoch BIGINT NOT NULL CHECK (expected_lifecycle_epoch > 0), + expected_row_version BIGINT NOT NULL CHECK (expected_row_version >= 0), + outcome VARCHAR(16) NOT NULL CHECK (outcome IN ('COMMITTED', 'ABORTED')), + terminal_code VARCHAR(64), + result_lifecycle_epoch BIGINT NOT NULL CHECK (result_lifecycle_epoch > 0), + result_row_version BIGINT NOT NULL CHECK (result_row_version >= 0), + result_bytes BYTEA NOT NULL CHECK (octet_length(result_bytes) > 0), + result_digest VARCHAR(71) NOT NULL CHECK (result_digest ~ '^sha256:[0-9a-f]{64}$'), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT fk_world_activation_association + FOREIGN KEY (canonical_game_instance_id) + REFERENCES world_canonical_instance_association(canonical_game_instance_id) + ON DELETE RESTRICT, + CONSTRAINT ck_world_activation_outcome_shape CHECK ( + (outcome = 'COMMITTED' AND terminal_code IS NULL + AND result_lifecycle_epoch = expected_lifecycle_epoch + 1 + AND result_row_version = expected_row_version + 1) + OR (outcome = 'ABORTED' AND terminal_code IS NOT NULL + AND length(btrim(terminal_code)) BETWEEN 1 AND 64) + ), + CONSTRAINT ck_world_activation_request_id_non_nil + CHECK (activation_request_id <> '00000000-0000-0000-0000-000000000000'::UUID) +); +CREATE UNIQUE INDEX uq_world_activation_one_commit_per_instance + ON world_canonical_instance_activation_operation(canonical_game_instance_id) + WHERE outcome = 'COMMITTED'; +CREATE INDEX idx_world_activation_world_row + ON world_canonical_instance_activation_operation(world_instance_id, activation_request_id); + +-- Only the validated operation insert may mint this exact, transaction-local UPDATE capability. +CREATE TABLE world_canonical_activation_execution_manifest ( + transaction_id BIGINT NOT NULL, + activation_request_id UUID NOT NULL, + request_digest VARCHAR(71) NOT NULL, + result_digest VARCHAR(71) NOT NULL, + canonical_game_instance_id UUID NOT NULL, + world_instance_id BIGINT NOT NULL, + local_tenant_key BIGINT NOT NULL, + private_game_instance_key BIGINT NOT NULL, + expected_old JSONB NOT NULL, + expected_new JSONB NOT NULL, + PRIMARY KEY (transaction_id, activation_request_id), + UNIQUE (transaction_id, world_instance_id), + FOREIGN KEY (activation_request_id) + REFERENCES world_canonical_instance_activation_operation(activation_request_id) + ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED +); + +-- [jooq ignore start] +REVOKE ALL ON world_canonical_instance_activation_operation FROM PUBLIC; +REVOKE ALL ON world_canonical_activation_execution_manifest FROM PUBLIC; + +CREATE FUNCTION world_validate_canonical_activation_operation() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + association_row "${serviceSchema}".world_canonical_instance_association%ROWTYPE; + instance "${serviceSchema}".world_instance%ROWTYPE; + activated_instance "${serviceSchema}".world_instance%ROWTYPE; + preparing JSONB; + normalized_request JSONB; + result JSONB; + lifecycle JSONB; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Canonical World activation operation evidence is immutable' + USING ERRCODE = '55000'; + END IF; + preparing := convert_from(NEW.preparing_evidence_bytes, 'UTF8')::JSONB; + normalized_request := convert_from(NEW.request_bytes, 'UTF8')::JSONB; + result := convert_from(NEW.result_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(preparing) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(preparing)) <> 11 + OR (SELECT count(*) FROM jsonb_object_keys(preparing->'request')) <> 14 + OR preparing->>'schema' IS DISTINCT FROM 'world-canonical-instance-lifecycle-evidence/v1' + OR preparing->>'lifecycleStatus' IS DISTINCT FROM 'PREPARING' + OR (preparing->'request'->>'canonicalGameInstanceId') IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR (preparing->>'lifecycleEpoch') IS DISTINCT FROM NEW.expected_lifecycle_epoch::TEXT + OR (preparing->>'rowVersion') IS DISTINCT FROM NEW.expected_row_version::TEXT + OR jsonb_typeof(normalized_request) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(normalized_request)) <> 3 + OR (SELECT count(*) FROM jsonb_object_keys(normalized_request->'preparingEvidence')) <> 11 + OR (SELECT count(*) FROM jsonb_object_keys(normalized_request->'preparingEvidence'->'request')) <> 13 + OR normalized_request->>'schema' IS DISTINCT FROM 'world-canonical-instance-activation-request/v1' + OR normalized_request->>'activationRequestId' IS DISTINCT FROM NEW.activation_request_id::TEXT + OR NEW.request_digest IS DISTINCT FROM + ('sha256:' || encode(sha256(NEW.request_bytes), 'hex')) + OR NEW.result_digest IS DISTINCT FROM + ('sha256:' || encode(sha256(NEW.result_bytes), 'hex')) + OR normalized_request->'preparingEvidence' IS DISTINCT FROM + (preparing - 'request' || jsonb_build_object( + 'request', (preparing->'request') - 'readRequestId')) THEN + RAISE EXCEPTION 'Canonical activation request differs from its exact retained PREPARING evidence' + USING ERRCODE = '23514'; + END IF; + IF jsonb_typeof(result) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(result)) <> 8 + OR result->>'schema' IS DISTINCT FROM 'world-canonical-instance-activation-result/v1' + OR result->>'activationRequestId' IS DISTINCT FROM NEW.activation_request_id::TEXT + OR result->>'requestDigest' IS DISTINCT FROM NEW.request_digest + OR result->>'outcome' IS DISTINCT FROM NEW.outcome + OR result->>'terminalCode' IS DISTINCT FROM NEW.terminal_code + OR (NEW.terminal_code IS NULL AND jsonb_typeof(result->'terminalCode') IS DISTINCT FROM 'null') + OR (NEW.terminal_code IS NOT NULL AND jsonb_typeof(result->'terminalCode') IS DISTINCT FROM 'string') + OR decode(result->>'requestBytesBase64', 'base64') IS DISTINCT FROM NEW.request_bytes + OR decode(result->>'preparingEvidenceBytesBase64', 'base64') IS DISTINCT FROM NEW.preparing_evidence_bytes THEN + RAISE EXCEPTION 'Canonical activation result differs from its immutable request outcome' + USING ERRCODE = '23514'; + END IF; + lifecycle := convert_from(decode(result->>'lifecycleEvidenceBytesBase64', 'base64'), 'UTF8')::JSONB; + IF jsonb_typeof(lifecycle) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(lifecycle)) <> 11 + OR (SELECT count(*) FROM jsonb_object_keys(lifecycle->'request')) <> 14 + OR lifecycle->>'schema' IS DISTINCT FROM 'world-canonical-instance-lifecycle-evidence/v1' + OR lifecycle->'request' IS DISTINCT FROM preparing->'request' + OR lifecycle->>'lifecycleEpoch' IS DISTINCT FROM NEW.result_lifecycle_epoch::TEXT + OR lifecycle->>'rowVersion' IS DISTINCT FROM NEW.result_row_version::TEXT + OR (lifecycle - 'lifecycleStatus' - 'lifecycleEpoch' - 'rowVersion') + IS DISTINCT FROM + (preparing - 'lifecycleStatus' - 'lifecycleEpoch' - 'rowVersion') THEN + RAISE EXCEPTION 'Canonical activation result does not retain its exact owner lifecycle snapshot' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO association_row FROM "${serviceSchema}".world_canonical_instance_association + WHERE canonical_game_instance_id = NEW.canonical_game_instance_id; + IF NOT FOUND OR association_row.world_instance_id IS DISTINCT FROM NEW.world_instance_id + OR lifecycle->'request'->>'canonicalGameInstanceId' IS DISTINCT FROM association_row.canonical_game_instance_id::TEXT THEN + RAISE EXCEPTION 'Canonical activation operation does not resolve through its exact World association' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO instance FROM "${serviceSchema}".world_instance WHERE id=association_row.world_instance_id FOR UPDATE; + IF NOT FOUND OR instance.canonical_game_instance_id IS DISTINCT FROM NEW.canonical_game_instance_id THEN + RAISE EXCEPTION 'Canonical activation operation lost its associated World row' + USING ERRCODE = '23514'; + END IF; + IF NOT EXISTS ( + SELECT 1 + FROM "${serviceSchema}".world_canonical_instance_association a + JOIN "${serviceSchema}".world_instance w + ON w.id=a.world_instance_id + JOIN "${serviceSchema}".world_complete_launch_binding b + ON b.binding_operation_id=a.canonical_launch_binding_operation_id + JOIN "${serviceSchema}".world_authored_source_intake s + ON s.operation_id=a.intake_operation_id + JOIN "${serviceSchema}".world_authored_version_identity v + ON v.operation_id=a.version_identity_operation_id + JOIN "${serviceSchema}".world_canonical_instance_preparation p + ON p.canonical_game_instance_id=a.canonical_game_instance_id + JOIN "${serviceSchema}".world_canonical_preparation_start_location start_row + ON start_row.canonical_game_instance_id=a.canonical_game_instance_id + JOIN "${serviceSchema}".world_canonical_instance_topology_identity m + ON m.world_instance_id=a.world_instance_id + AND m.canonical_game_instance_id=a.canonical_game_instance_id + AND m.family='ROOM' AND m.template_id=start_row.room_template_id + JOIN "${serviceSchema}".room_instance r + ON r.id=m.runtime_row_id AND r.room_instance_row_id=start_row.runtime_room_instance_id + JOIN "${serviceSchema}".region_instance runtime_region + ON runtime_region.id=r.region_instance_id AND runtime_region.world_instance_id=a.world_instance_id + WHERE a.canonical_game_instance_id=NEW.canonical_game_instance_id + AND a.world_instance_id=NEW.world_instance_id + AND a.schema_version=1 + AND a.playable_state_scope='SHARED' + AND a.public_production IS TRUE + AND a.playtest_lifecycle_id IS NULL + AND a.playtest_state_generation IS NULL + AND w.canonical_game_instance_id=a.canonical_game_instance_id + AND w.canonical_target_namespace=a.canonical_target_namespace + AND w.canonical_tenant_id=a.canonical_tenant_id + AND w.canonical_world_slug=a.canonical_world_slug + AND w.playable_state_namespace_id=a.playable_state_namespace_id + AND w.playable_state_scope=a.playable_state_scope + AND w.public_production=a.public_production + AND w.control_plane_request_id=a.control_plane_request_id + AND w.canonical_launch_binding_operation_id=a.canonical_launch_binding_operation_id + AND w.tenant_id=a.local_tenant_key + AND w.game_instance_id=a.private_game_instance_key + AND b.target_namespace=a.canonical_target_namespace + AND b.canonical_tenant_id=a.canonical_tenant_id + AND b.canonical_version_id=a.canonical_version_id + AND b.world_slug=a.canonical_world_slug + AND b.control_plane_request_id=a.control_plane_request_id + AND b.intake_operation_id=a.intake_operation_id + AND b.intake_request_id=a.intake_request_id + AND b.local_tenant_key=a.local_tenant_key + AND b.source_operation_id=a.source_operation_id + AND b.source_evidence_digest=a.source_evidence_digest + AND b.intake_receipt_digest=a.intake_receipt_digest + AND b.descriptor_request_digest=a.descriptor_request_digest + AND b.descriptor_result_digest=a.descriptor_result_digest + AND b.release_attestation_digest=a.release_attestation_digest + AND b.descriptor_json::JSONB->>'launchDescriptorId'=a.launch_descriptor_id + AND b.descriptor_json::JSONB->>'versionId'=v.game_design_version_id::TEXT + AND b.descriptor_json::JSONB->>'gameTemplateId'=a.game_template_id::TEXT + AND b.descriptor_json::JSONB->>'targetNamespace'=a.canonical_target_namespace + AND b.descriptor_json::JSONB->>'canonicalTenantId'=a.canonical_tenant_id::TEXT + AND b.descriptor_json::JSONB->>'worldSlug'=a.canonical_world_slug + AND b.descriptor_json::JSONB->>'controlPlaneRequestId'=a.control_plane_request_id + AND b.descriptor_json::JSONB->>'authoredWorldSourceOperationId'=a.source_operation_id::TEXT + AND b.descriptor_json::JSONB->>'authoredWorldSourceEvidenceDigest'=a.source_evidence_digest + AND b.descriptor_json::JSONB->>'requestDigest'=a.descriptor_request_digest + AND b.descriptor_json::JSONB->>'resultDigest'=a.descriptor_result_digest + AND (CASE WHEN b.descriptor_json::JSONB->>'scriptPatchVersionPresent'='true' + THEN b.descriptor_json::JSONB->>'scriptPatchVersion' ELSE NULL END) + IS NOT DISTINCT FROM a.script_patch_version + AND b.descriptor_json::JSONB->>'runtimeFlagsJson' IS NOT DISTINCT FROM a.runtime_flags_json + AND b.descriptor_json::JSONB->>'generationConfigRevision'=a.generation_config_revision + AND b.descriptor_json::JSONB->>'versionStateEpoch'=a.version_state_epoch::TEXT + AND b.descriptor_json::JSONB->>'releaseBundleId'=a.release_bundle_id::TEXT + AND b.descriptor_json::JSONB->>'publishedReleaseBundleRef'=a.published_release_bundle_ref + AND (CASE WHEN b.descriptor_json::JSONB->>'remapSetIdPresent'='true' + THEN b.descriptor_json::JSONB->>'remapSetId' ELSE NULL END) + IS NOT DISTINCT FROM a.remap_set_id + AND b.release_attestation_json::JSONB->>'targetNamespace'=a.canonical_target_namespace + AND b.release_attestation_json::JSONB->>'descriptorResultDigest'=a.descriptor_result_digest + AND b.release_attestation_json::JSONB->>'canonicalTenantId'=a.canonical_tenant_id::TEXT + AND b.release_attestation_json::JSONB->>'canonicalVersionId'=a.canonical_version_id::TEXT + AND b.release_attestation_json::JSONB->>'worldSlug'=a.canonical_world_slug + AND b.release_attestation_json::JSONB->>'authoredWorldSourceOperationId'=a.source_operation_id::TEXT + AND b.release_attestation_json::JSONB->>'authoredWorldSourceEvidenceDigest'=a.source_evidence_digest + AND b.release_attestation_json::JSONB->>'launchDescriptorId'=a.launch_descriptor_id + AND b.release_attestation_json::JSONB->>'publishedReleaseBundleRef'=a.published_release_bundle_ref + AND b.release_attestation_json::JSONB->>'versionStateEpoch'=a.version_state_epoch::TEXT + AND b.release_attestation_json::JSONB->>'generationConfigRevision'=a.generation_config_revision + AND b.release_attestation_json::JSONB->>'evidenceDigest'=a.release_attestation_digest + AND s.target_namespace=a.canonical_target_namespace + AND s.canonical_tenant_id=a.canonical_tenant_id + AND s.world_slug=a.canonical_world_slug + AND s.local_tenant_key=a.local_tenant_key + AND s.intake_request_id=a.intake_request_id + AND s.source_operation_id=a.source_operation_id + AND s.source_evidence_digest=a.source_evidence_digest + AND s.request_digest=a.intake_request_digest + AND s.receipt_digest=a.intake_receipt_digest + AND v.target_namespace=a.canonical_target_namespace + AND v.canonical_tenant_id=a.canonical_tenant_id + AND v.world_slug=a.canonical_world_slug + AND v.canonical_version_id=a.canonical_version_id + AND v.local_tenant_key=a.local_tenant_key + AND v.local_version_key=a.local_version_key + AND v.intake_operation_id=a.intake_operation_id + AND v.intake_request_id=a.intake_request_id + AND v.intake_request_digest=a.intake_request_digest + AND v.source_operation_id=a.source_operation_id + AND v.source_evidence_digest=a.source_evidence_digest + AND v.intake_receipt_digest=a.intake_receipt_digest + AND v.game_design_version_id::TEXT=b.descriptor_json::JSONB->>'versionId' + -- Original version intake and later published launch are distinct captures. + -- Each epoch remains bound to its own retained evidence below and above. + AND p.target_namespace=a.canonical_target_namespace + AND p.canonical_tenant_id=a.canonical_tenant_id + AND p.world_slug=a.canonical_world_slug + AND p.control_plane_request_id=a.control_plane_request_id + AND p.canonical_version_id=a.canonical_version_id + AND p.version_identity_operation_id=a.version_identity_operation_id + AND p.world_instance_id=a.world_instance_id + AND p.private_game_instance_key=a.private_game_instance_key + AND p.capture_id::TEXT=lifecycle->>'captureId' + AND p.graph_sha256=lifecycle->>'graphSha256' + AND p.graph_sha256=encode(sha256(p.graph_bytes),'hex') + AND p.input_digest=lifecycle->>'preparationInputDigest' + AND p.input_digest=('sha256:' || encode(sha256(convert_to(p.input_json,'UTF8')),'hex')) + AND p.input_json::JSONB->>'schemaVersion'='2' + AND p.input_json::JSONB->'identity'->>'canonicalGameInstanceId'=a.canonical_game_instance_id::TEXT + AND p.input_json::JSONB->'identity'->>'targetNamespace'=a.canonical_target_namespace + AND p.input_json::JSONB->'identity'->>'canonicalTenantId'=a.canonical_tenant_id::TEXT + AND p.input_json::JSONB->'identity'->>'worldSlug'=a.canonical_world_slug + AND p.input_json::JSONB->'identity'->>'playableStateNamespaceId'=a.playable_state_namespace_id::TEXT + AND p.input_json::JSONB->'identity'->>'playableStateScope'=a.playable_state_scope + AND p.input_json::JSONB->'identity'->'publicProduction'=to_jsonb(a.public_production) + AND p.input_json::JSONB->'identity'->>'controlPlaneRequestId'=a.control_plane_request_id + AND p.input_json::JSONB->'launchBinding'->>'operationId'=a.canonical_launch_binding_operation_id::TEXT + AND p.input_json::JSONB->'launchBinding'->>'targetNamespace'=b.target_namespace + AND p.input_json::JSONB->'launchBinding'->>'canonicalTenantId'=b.canonical_tenant_id::TEXT + AND p.input_json::JSONB->'launchBinding'->>'worldSlug'=b.world_slug + AND p.input_json::JSONB->'launchBinding'->>'controlPlaneRequestId'=b.control_plane_request_id + AND p.input_json::JSONB->'launchBinding'->>'canonicalVersionId'=b.canonical_version_id::TEXT + AND p.input_json::JSONB->'launchBinding'->>'descriptorRequestDigest'=b.descriptor_request_digest + AND p.input_json::JSONB->'launchBinding'->>'descriptorResultDigest'=b.descriptor_result_digest + AND p.input_json::JSONB->'launchBinding'->>'releaseAttestationDigest'=b.release_attestation_digest + AND p.input_json::JSONB->'launchBinding'->>'localTenantKey'=b.local_tenant_key::TEXT + AND p.input_json::JSONB->'launchBinding'->>'intakeOperationId'=b.intake_operation_id::TEXT + AND p.input_json::JSONB->'launchBinding'->>'intakeRequestId'=b.intake_request_id::TEXT + AND p.input_json::JSONB->'launchBinding'->>'sourceOperationId'=b.source_operation_id::TEXT + AND p.input_json::JSONB->'launchBinding'->>'sourceEvidenceDigest'=b.source_evidence_digest + AND p.input_json::JSONB->'launchBinding'->>'intakeRequestDigest'=s.request_digest + AND p.input_json::JSONB->'launchBinding'->>'intakeReceiptDigest'=s.receipt_digest + AND p.input_json::JSONB->'versionIdentity'->>'operationId'=v.operation_id::TEXT + AND p.input_json::JSONB->'versionIdentity'->>'canonicalVersionId'=v.canonical_version_id::TEXT + AND p.input_json::JSONB->'versionIdentity'->>'localVersionKey'=v.local_version_key::TEXT + AND p.input_json::JSONB->'versionIdentity'->>'gameDesignVersionId'=v.game_design_version_id::TEXT + AND p.input_json::JSONB->'versionIdentity'->>'versionState'= + CASE v.version_state_state + WHEN 'DRAFT' THEN 'VERSION_LIFECYCLE_STATE_DRAFT' + WHEN 'PUBLISHED' THEN 'VERSION_LIFECYCLE_STATE_PUBLISHED' + WHEN 'ACTIVE' THEN 'VERSION_LIFECYCLE_STATE_ACTIVE' + END + AND p.input_json::JSONB->'versionIdentity'->>'versionStateEpoch'=v.version_state_epoch::TEXT + AND p.input_json::JSONB->'versionIdentity'->>'evidenceDigest'=v.version_state_evidence_digest + AND p.input_json::JSONB->'sourceIntake'->>'schemaVersion'=s.schema_version::TEXT + AND p.input_json::JSONB->'sourceIntake'->>'targetNamespace'=s.target_namespace + AND p.input_json::JSONB->'sourceIntake'->>'intakeRequestId'=s.intake_request_id::TEXT + AND p.input_json::JSONB->'sourceIntake'->>'operationId'=s.operation_id::TEXT + AND p.input_json::JSONB->'sourceIntake'->>'canonicalTenantId'=s.canonical_tenant_id::TEXT + AND p.input_json::JSONB->'sourceIntake'->>'worldSlug'=s.world_slug + AND p.input_json::JSONB->'sourceIntake'->>'sourceOperationId'=s.source_operation_id::TEXT + AND p.input_json::JSONB->'sourceIntake'->>'sourceEvidenceDigest'=s.source_evidence_digest + AND p.input_json::JSONB->'sourceIntake'->>'requestDigest'=s.request_digest + AND p.input_json::JSONB->'sourceIntake'->>'receiptDigest'=s.receipt_digest + AND p.input_json::JSONB->'sourceIntake'->>'localTenantKey'=s.local_tenant_key::TEXT + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'schemaVersion'=s.source_schema_version::TEXT + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'registrationRequestId'=s.source_registration_request_id::TEXT + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'sourceOperationId'=s.source_operation_id::TEXT + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'requestDigest'=s.source_request_digest + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'canonicalTenantId'=s.canonical_tenant_id::TEXT + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'tenantSlug'=s.tenant_slug + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'worldSlug'=s.world_slug + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'worldDisplayName'=s.world_display_name + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'sourceGameRowId'=s.source_game_row_id::TEXT + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'sourceGameTenantKey'=s.source_game_tenant_key + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'provenanceKind'=s.source_provenance_kind + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'evidenceDigest'=s.source_evidence_digest + AND p.input_json::JSONB->'topology'->>'captureId'=p.capture_id::TEXT + AND p.input_json::JSONB->'topology'->>'targetNamespace'=a.canonical_target_namespace + AND p.input_json::JSONB->'topology'->>'canonicalTenantId'=a.canonical_tenant_id::TEXT + AND p.input_json::JSONB->'topology'->>'canonicalVersionId'=a.canonical_version_id::TEXT + AND p.input_json::JSONB->'topology'->>'versionIdentityOperationId'=a.version_identity_operation_id::TEXT + AND lifecycle->'request'->>'schemaVersion'='1' + AND lifecycle->'request'->>'targetNamespace'=a.canonical_target_namespace + AND lifecycle->'request'->>'canonicalTenantId'=a.canonical_tenant_id::TEXT + AND lifecycle->'request'->>'worldSlug'=a.canonical_world_slug + AND lifecycle->'request'->>'canonicalGameInstanceId'=a.canonical_game_instance_id::TEXT + AND lifecycle->'request'->>'playableStateNamespaceId'=a.playable_state_namespace_id::TEXT + AND lifecycle->'request'->>'playableStateScope'=a.playable_state_scope + AND lifecycle->'request'->'publicProduction'=to_jsonb(a.public_production) + AND lifecycle->'request'->>'controlPlaneRequestId'=a.control_plane_request_id + AND lifecycle->'request'->>'canonicalVersionId'=a.canonical_version_id::TEXT + AND lifecycle->'request'->>'expectedDescriptorRequestDigest'=a.descriptor_request_digest + AND lifecycle->'request'->>'expectedDescriptorResultDigest'=a.descriptor_result_digest + AND lifecycle->'request'->>'expectedReleaseAttestationDigest'=a.release_attestation_digest + AND decode(preparing->>'launchBindingBytesBase64','base64') IS NOT NULL + AND convert_from(decode(preparing->>'launchBindingBytesBase64','base64'),'UTF8')::JSONB + IS NOT DISTINCT FROM jsonb_build_object( + 'descriptor', b.descriptor_json::JSONB, + 'releaseAttestation', b.release_attestation_json::JSONB) + AND start_row.world_instance_id=a.world_instance_id + AND start_row.canonical_tenant_id=a.canonical_tenant_id + AND start_row.canonical_version_id=a.canonical_version_id + AND lifecycle->'startLocation'->>'tenantId'=start_row.canonical_tenant_id::TEXT + AND lifecycle->'startLocation'->>'versionId'=start_row.canonical_version_id::TEXT + AND lifecycle->'startLocation'->>'roomTemplateId'=start_row.room_template_id::TEXT + AND lifecycle->>'runtimeRoomInstanceId'=start_row.runtime_room_instance_id::TEXT + AND lifecycle->>'captureId'=p.capture_id::TEXT + AND lifecycle->>'graphSha256'=p.graph_sha256 + AND lifecycle->>'preparationInputDigest'=p.input_digest + AND start_row.graph_digest=('sha256:' || p.graph_sha256) + AND start_row.evidence_bytes=decode(p.input_json::JSONB->>'worldStartLocationEvidenceBase64','base64') + AND m.runtime_room_instance_id=start_row.runtime_room_instance_id + AND m.runtime_row_id=r.id + AND r.template_room_id=m.template_private_row_key + AND r.tenant_id=a.local_tenant_key + AND r.game_instance_id=a.private_game_instance_key + AND runtime_region.tenant_id=a.local_tenant_key + AND runtime_region.game_instance_id=a.private_game_instance_key + ) THEN + RAISE EXCEPTION 'Canonical activation proof differs from immutable World association, launch, preparation, or ROOM bindings' + USING ERRCODE = '23514'; + END IF; + IF NEW.outcome = 'COMMITTED' THEN + IF instance.status IS DISTINCT FROM 'PREPARING' + OR instance.lifecycle_epoch IS DISTINCT FROM NEW.expected_lifecycle_epoch + OR instance.row_version IS DISTINCT FROM NEW.expected_row_version + OR lifecycle->>'lifecycleStatus' IS DISTINCT FROM 'ACTIVE' THEN + RAISE EXCEPTION 'Committed canonical activation lacks the exact current PREPARING CAS' + USING ERRCODE = '23514'; + END IF; + activated_instance := instance; + activated_instance.status := 'ACTIVE'; + activated_instance.lifecycle_epoch := NEW.result_lifecycle_epoch; + activated_instance.row_version := NEW.result_row_version; + activated_instance.updated_at := CURRENT_TIMESTAMP; + INSERT INTO "${serviceSchema}".world_canonical_activation_execution_manifest + (transaction_id, activation_request_id, request_digest, result_digest, + canonical_game_instance_id, world_instance_id, local_tenant_key, + private_game_instance_key, expected_old, expected_new) + VALUES (txid_current(), NEW.activation_request_id, NEW.request_digest, NEW.result_digest, + NEW.canonical_game_instance_id, NEW.world_instance_id, association_row.local_tenant_key, + association_row.private_game_instance_key, to_jsonb(instance), to_jsonb(activated_instance)); + ELSIF lifecycle->>'lifecycleStatus' IS DISTINCT FROM instance.status + OR lifecycle->>'lifecycleEpoch' IS DISTINCT FROM instance.lifecycle_epoch::TEXT + OR lifecycle->>'rowVersion' IS DISTINCT FROM instance.row_version::TEXT THEN + RAISE EXCEPTION 'Aborted canonical activation must retain the actual current lifecycle state' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +REVOKE ALL ON FUNCTION world_validate_canonical_activation_operation() FROM PUBLIC; +CREATE TRIGGER trg_world_canonical_activation_operation + BEFORE INSERT OR UPDATE OR DELETE ON world_canonical_instance_activation_operation + FOR EACH ROW EXECUTE FUNCTION world_validate_canonical_activation_operation(); + +CREATE FUNCTION world_reject_canonical_activation_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + RAISE EXCEPTION 'Canonical World activation operation evidence is immutable and retained' + USING ERRCODE = '55000'; + RETURN NULL; +END; +$$; +REVOKE ALL ON FUNCTION world_reject_canonical_activation_truncate() FROM PUBLIC; +CREATE TRIGGER trg_world_canonical_activation_operation_no_truncate + BEFORE TRUNCATE ON world_canonical_instance_activation_operation + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_canonical_activation_truncate(); + +CREATE FUNCTION world_consume_canonical_activation_execution_manifest( + actual_schema TEXT, actual_table TEXT, actual_operation TEXT, + actual_old JSONB, actual_new JSONB +) RETURNS BOOLEAN +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + consumed UUID; +BEGIN + IF actual_schema IS DISTINCT FROM '${serviceSchema}' + OR actual_table IS DISTINCT FROM 'world_instance' + OR actual_operation IS DISTINCT FROM 'UPDATE' + OR actual_old IS NULL OR actual_new IS NULL THEN + RETURN FALSE; + END IF; + DELETE FROM "${serviceSchema}".world_canonical_activation_execution_manifest m + USING "${serviceSchema}".world_canonical_instance_activation_operation o, + "${serviceSchema}".world_canonical_instance_association a + WHERE m.transaction_id = txid_current() + AND m.expected_old = actual_old AND m.expected_new = actual_new + AND m.world_instance_id = (actual_old->>'id')::BIGINT + AND m.world_instance_id = (actual_new->>'id')::BIGINT + AND m.canonical_game_instance_id::TEXT = actual_old->>'canonical_game_instance_id' + AND m.canonical_game_instance_id::TEXT = actual_new->>'canonical_game_instance_id' + AND m.local_tenant_key = (actual_old->>'tenant_id')::BIGINT + AND m.local_tenant_key = (actual_new->>'tenant_id')::BIGINT + AND m.private_game_instance_key = (actual_old->>'game_instance_id')::BIGINT + AND m.private_game_instance_key = (actual_new->>'game_instance_id')::BIGINT + AND o.activation_request_id = m.activation_request_id + AND o.request_digest = m.request_digest AND o.result_digest = m.result_digest + AND o.canonical_game_instance_id = m.canonical_game_instance_id + AND o.world_instance_id = m.world_instance_id AND o.outcome = 'COMMITTED' + AND actual_old->>'status' = 'PREPARING' AND actual_new->>'status' = 'ACTIVE' + AND o.expected_lifecycle_epoch = (actual_old->>'lifecycle_epoch')::BIGINT + AND o.expected_row_version = (actual_old->>'row_version')::BIGINT + AND o.result_lifecycle_epoch = (actual_new->>'lifecycle_epoch')::BIGINT + AND o.result_row_version = (actual_new->>'row_version')::BIGINT + AND convert_from(o.result_bytes, 'UTF8')::JSONB->>'outcome' = 'COMMITTED' + AND convert_from(o.result_bytes, 'UTF8')::JSONB->>'requestDigest' = m.request_digest + AND a.canonical_game_instance_id = m.canonical_game_instance_id + AND a.world_instance_id = m.world_instance_id + AND a.local_tenant_key = m.local_tenant_key + AND a.private_game_instance_key = m.private_game_instance_key + RETURNING m.activation_request_id INTO consumed; + RETURN consumed IS NOT NULL; +END; +$$; +REVOKE ALL ON FUNCTION world_consume_canonical_activation_execution_manifest(TEXT, TEXT, TEXT, JSONB, JSONB) + FROM PUBLIC; + +-- Extend V35's guard at one exact anchor, retaining its region/preparation paths and legacy denial. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ RAISE EXCEPTION + 'World tenant key is reserved for a canonical authored source; no exact transaction execution manifest'$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_claim_legacy_numeric_tenant_key()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,anchor,'')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one reserved-tenant execution denial guard'; + END IF; + original := replace(original,anchor,$replacement$ IF "${serviceSchema}".world_consume_canonical_activation_execution_manifest( + TG_TABLE_SCHEMA, TG_TABLE_NAME, TG_OP, old_row, new_row) THEN + RETURN NEW; + END IF; +$replacement$ || anchor); + EXECUTE original; +END; +$migration$; + +CREATE FUNCTION world_require_committed_activation_at_commit() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + instance "${serviceSchema}".world_instance%ROWTYPE; + result JSONB; +BEGIN + IF NEW.outcome <> 'COMMITTED' THEN RETURN NULL; END IF; + SELECT * INTO instance FROM "${serviceSchema}".world_instance + WHERE id=NEW.world_instance_id AND canonical_game_instance_id=NEW.canonical_game_instance_id; + result := convert_from(NEW.result_bytes, 'UTF8')::JSONB; + IF NOT FOUND + OR instance.status IS DISTINCT FROM 'ACTIVE' + OR instance.lifecycle_epoch IS DISTINCT FROM NEW.result_lifecycle_epoch + OR instance.row_version IS DISTINCT FROM NEW.result_row_version + OR result->>'outcome' IS DISTINCT FROM 'COMMITTED' + OR result->>'requestDigest' IS DISTINCT FROM NEW.request_digest + OR EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_activation_execution_manifest m + WHERE m.transaction_id = txid_current() AND m.activation_request_id = NEW.activation_request_id) + OR convert_from(decode(result->>'lifecycleEvidenceBytesBase64','base64'),'UTF8')::JSONB->>'lifecycleStatus' + IS DISTINCT FROM 'ACTIVE' THEN + RAISE EXCEPTION 'Committed canonical activation must include its exact ACTIVE lifecycle CAS before commit' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; +REVOKE ALL ON FUNCTION world_require_committed_activation_at_commit() FROM PUBLIC; +CREATE CONSTRAINT TRIGGER trg_world_canonical_activation_commit_cas + AFTER INSERT ON world_canonical_instance_activation_operation + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION world_require_committed_activation_at_commit(); + +CREATE FUNCTION world_guard_canonical_activation_transition() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + IF OLD.canonical_game_instance_id IS NOT NULL AND NEW.status = 'ACTIVE' + AND (OLD.status IS DISTINCT FROM NEW.status + OR OLD.lifecycle_epoch IS DISTINCT FROM NEW.lifecycle_epoch + OR OLD.row_version IS DISTINCT FROM NEW.row_version) THEN + IF OLD.status IS DISTINCT FROM 'PREPARING' + OR NEW.lifecycle_epoch IS DISTINCT FROM OLD.lifecycle_epoch + 1 + OR NEW.row_version IS DISTINCT FROM OLD.row_version + 1 + OR NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_canonical_instance_activation_operation o + WHERE o.canonical_game_instance_id = OLD.canonical_game_instance_id + AND o.world_instance_id = OLD.id + AND o.outcome = 'COMMITTED' + AND o.expected_lifecycle_epoch = OLD.lifecycle_epoch + AND o.expected_row_version = OLD.row_version + AND o.result_lifecycle_epoch = NEW.lifecycle_epoch + AND o.result_row_version = NEW.row_version + AND convert_from(o.result_bytes, 'UTF8')::JSONB->>'outcome' = 'COMMITTED') THEN + RAISE EXCEPTION 'Canonical World PREPARING-to-ACTIVE transition requires its exact activation operation' + USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; +REVOKE ALL ON FUNCTION world_guard_canonical_activation_transition() FROM PUBLIC; +CREATE TRIGGER trg_world_canonical_activation_transition + BEFORE UPDATE ON world_instance + FOR EACH ROW EXECUTE FUNCTION world_guard_canonical_activation_transition(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1017__world_publication_terminal_handoff.sql b/services/world-management-service/src/main/resources/db/migration/V1017__world_publication_terminal_handoff.sql new file mode 100644 index 0000000000..9547215d6c --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1017__world_publication_terminal_handoff.sql @@ -0,0 +1,354 @@ +-- Retain the authenticated Game Design terminal result before World leaves FROZEN. The owner +-- transition and immutable receipt are committed atomically; absence or uncertainty never settles. +CREATE TABLE world_design_publication_terminal ( + publication_fence UUID PRIMARY KEY + REFERENCES world_design_publication_fence_attempt(publication_fence) ON DELETE RESTRICT, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + publication_request_id VARCHAR(256) NOT NULL, + request_digest VARCHAR(64) NOT NULL, + publish_workflow_id VARCHAR(537) NOT NULL, + freeze_version_state_epoch BIGINT NOT NULL CHECK (freeze_version_state_epoch > 0), + applied_commit_id VARCHAR(256) NOT NULL, + content_digest VARCHAR(64) NOT NULL, + digest_schema_version INTEGER NOT NULL CHECK (digest_schema_version > 0), + outcome VARCHAR(16) NOT NULL CHECK (outcome IN ('PUBLISHED', 'NO_PUBLICATION')), + publication_version_state_epoch BIGINT, + published_release_bundle_ref VARCHAR(512), + published_release_bundle_digest VARCHAR(71), + operation_bytes BYTEA NOT NULL CHECK (octet_length(operation_bytes) > 0), + terminal_evidence_bytes BYTEA NOT NULL CHECK (octet_length(terminal_evidence_bytes) > 0), + terminal_evidence_digest VARCHAR(64) NOT NULL CHECK (terminal_evidence_digest ~ '^[0-9a-f]{64}$'), + world_evidence_bytes BYTEA NOT NULL CHECK (octet_length(world_evidence_bytes) > 0), + world_request_json TEXT NOT NULL, + selector_receipt_bytes BYTEA NOT NULL CHECK (octet_length(selector_receipt_bytes) > 0), + original_account_binding_bytes BYTEA NOT NULL CHECK (octet_length(original_account_binding_bytes) > 0), + applied_result_bytes BYTEA NOT NULL CHECK (octet_length(applied_result_bytes) > 0), + release_content_bytes BYTEA NOT NULL, + recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT uq_world_publication_terminal_scope_request UNIQUE + (target_namespace, canonical_tenant_id, canonical_version_id, publication_request_id), + CONSTRAINT ck_world_publication_terminal_identity CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND octet_length(publication_request_id) BETWEEN 1 AND 256 + AND position(':' IN publication_request_id) = 0 + AND request_digest ~ '^[0-9a-f]{64}$' + AND publish_workflow_id = 'publish:' || canonical_tenant_id::TEXT + || ':publish-request:' || publication_request_id + AND octet_length(applied_commit_id) BETWEEN 1 AND 256 + AND content_digest ~ '^[0-9a-f]{64}$' + ), + CONSTRAINT ck_world_publication_terminal_outcome_shape CHECK ( + (outcome = 'PUBLISHED' + AND publication_version_state_epoch IS NOT NULL + AND publication_version_state_epoch = freeze_version_state_epoch + 1 + AND published_release_bundle_ref IS NOT NULL + AND octet_length(published_release_bundle_ref) BETWEEN 1 AND 512 + AND published_release_bundle_digest IS NOT NULL + AND published_release_bundle_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(release_content_bytes) > 0) + OR + (outcome = 'NO_PUBLICATION' + AND publication_version_state_epoch IS NULL + AND published_release_bundle_ref IS NULL + AND published_release_bundle_digest IS NULL + AND octet_length(release_content_bytes) = 0) + ) +); + +-- [jooq ignore start] +REVOKE ALL ON world_design_publication_terminal FROM PUBLIC; + +CREATE FUNCTION world_validate_publication_terminal() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + attempt "${serviceSchema}".world_design_publication_fence_attempt%ROWTYPE; + owner_row "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + frozen "${serviceSchema}".world_canonical_frozen_topology%ROWTYPE; + receipt "${serviceSchema}".world_draft_start_location_receipt%ROWTYPE; + application "${serviceSchema}".world_draft_graph_application%ROWTYPE; + graph "${serviceSchema}".world_topology_draft_commit%ROWTYPE; + identity_row "${serviceSchema}".world_authored_version_identity%ROWTYPE; + intake_row "${serviceSchema}".world_authored_source_intake%ROWTYPE; + world_request JSONB; + world_evidence JSONB; + freeze_request JSONB; + expected_tuples JSONB; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'World publication terminal evidence is immutable' USING ERRCODE = '55000'; + END IF; + IF current_setting('transaction_isolation') <> 'read committed' + OR current_setting('transaction_read_only') <> 'off' THEN + RAISE EXCEPTION 'World publication terminal requires writable READ COMMITTED' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT attempt FROM "${serviceSchema}".world_design_publication_fence_attempt + WHERE publication_fence=NEW.publication_fence; + SELECT * INTO STRICT owner_row FROM "${serviceSchema}".world_design_publication_fence_owner + WHERE target_namespace=attempt.target_namespace + AND canonical_tenant_id=attempt.canonical_tenant_id + AND local_tenant_key=attempt.local_tenant_key AND version_id=attempt.version_id + FOR UPDATE; + SELECT * INTO STRICT frozen FROM "${serviceSchema}".world_canonical_frozen_topology + WHERE publication_fence=NEW.publication_fence; + SELECT * INTO STRICT identity_row FROM "${serviceSchema}".world_authored_version_identity + WHERE operation_id=attempt.version_identity_operation_id; + SELECT * INTO STRICT intake_row FROM "${serviceSchema}".world_authored_source_intake + WHERE operation_id=attempt.intake_operation_id; + SELECT * INTO STRICT graph FROM "${serviceSchema}".world_topology_draft_commit + WHERE request_id=frozen.request_id AND commit_id=frozen.commit_id; + SELECT * INTO STRICT receipt FROM "${serviceSchema}".world_draft_start_location_receipt + WHERE request_id=frozen.request_id AND commit_id=frozen.commit_id; + SELECT * INTO STRICT application FROM "${serviceSchema}".world_draft_graph_application + WHERE request_id=frozen.request_id AND commit_id=frozen.commit_id + AND operation_id=receipt.operation_id; + + world_request := NEW.world_request_json::JSONB; + world_evidence := convert_from(NEW.world_evidence_bytes, 'UTF8')::JSONB; + freeze_request := frozen.freeze_request_json::JSONB; + SELECT coalesce(jsonb_agg(value ORDER BY value->>'owner',value->>'aggregateType',value->>'aggregateId', + value->>'scopeType',value->>'scopeId',value->>'expectedEpoch'), '[]'::JSONB) + INTO expected_tuples FROM jsonb_array_elements(freeze_request->'suppliedOwnedAffectedTuples'); + + IF attempt.owner_binding_schema_version IS DISTINCT FROM 1 + OR owner_row.owner_freeze_phase IS DISTINCT FROM 'FROZEN' + OR owner_row.current_publication_fence IS DISTINCT FROM NEW.publication_fence + OR NEW.target_namespace IS DISTINCT FROM attempt.target_namespace + OR NEW.canonical_tenant_id IS DISTINCT FROM attempt.canonical_tenant_id + OR NEW.canonical_version_id IS DISTINCT FROM attempt.canonical_version_id + OR NEW.publication_request_id IS DISTINCT FROM attempt.publication_request_id + OR NEW.request_digest IS DISTINCT FROM attempt.request_digest + OR NEW.publish_workflow_id IS DISTINCT FROM attempt.publish_workflow_id + OR NEW.freeze_version_state_epoch IS DISTINCT FROM attempt.version_state_epoch + OR NEW.applied_commit_id IS DISTINCT FROM attempt.applied_commit_id + OR NEW.content_digest IS DISTINCT FROM attempt.content_digest + OR NEW.digest_schema_version IS DISTINCT FROM attempt.digest_schema_version THEN + RAISE EXCEPTION 'World terminal differs from exact current V25 publication owner' + USING ERRCODE = '23514'; + END IF; + + IF encode(sha256(NEW.terminal_evidence_bytes), 'hex') IS DISTINCT FROM NEW.terminal_evidence_digest + OR jsonb_typeof(world_request) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(world_request)) <> 13 + OR jsonb_typeof(world_evidence) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(world_evidence)) <> 5 + OR world_evidence->>'schema' IS DISTINCT FROM 'world-published-start-location-evidence/v1' + OR world_evidence->'request' IS DISTINCT FROM world_request + OR decode(world_evidence->>'selectorReceiptBytesBase64','base64') IS DISTINCT FROM NEW.selector_receipt_bytes + OR decode(world_evidence->>'originalAccountBindingBytesBase64','base64') IS DISTINCT FROM NEW.original_account_binding_bytes + OR decode(world_evidence->>'appliedResultBytesBase64','base64') IS DISTINCT FROM NEW.applied_result_bytes + OR world_request->>'targetNamespace' IS DISTINCT FROM attempt.target_namespace + OR world_request->>'canonicalTenantId' IS DISTINCT FROM attempt.canonical_tenant_id::TEXT + OR world_request->>'canonicalVersionId' IS DISTINCT FROM attempt.canonical_version_id::TEXT + OR world_request->>'intakeRequestId' IS DISTINCT FROM attempt.intake_request_id::TEXT + OR world_request->>'publicationFence' IS DISTINCT FROM attempt.publication_fence::TEXT + OR world_request->>'publicationRequestId' IS DISTINCT FROM attempt.publication_request_id + OR world_request->>'requestDigest' IS DISTINCT FROM attempt.request_digest + OR world_request->>'versionStateEpoch' IS DISTINCT FROM attempt.version_state_epoch::TEXT + OR world_request->>'publishWorkflowId' IS DISTINCT FROM attempt.publish_workflow_id + OR world_request->>'appliedCommitId' IS DISTINCT FROM attempt.applied_commit_id + OR world_request->>'contentDigest' IS DISTINCT FROM attempt.content_digest + OR world_request->>'digestSchemaVersion' IS DISTINCT FROM attempt.digest_schema_version::TEXT + OR world_request->'worldAffectedTuples' IS DISTINCT FROM expected_tuples + OR freeze_request->>'targetNamespace' IS DISTINCT FROM attempt.target_namespace + OR freeze_request->>'canonicalTenantId' IS DISTINCT FROM attempt.canonical_tenant_id::TEXT + OR freeze_request->>'canonicalVersionId' IS DISTINCT FROM attempt.canonical_version_id::TEXT + OR freeze_request->>'publicationFence' IS DISTINCT FROM attempt.publication_fence::TEXT + OR freeze_request->>'publicationRequestId' IS DISTINCT FROM attempt.publication_request_id + OR freeze_request->>'requestDigest' IS DISTINCT FROM attempt.request_digest + OR freeze_request->>'versionStateEpoch' IS DISTINCT FROM attempt.version_state_epoch::TEXT + OR freeze_request->>'publishWorkflowId' IS DISTINCT FROM attempt.publish_workflow_id + OR freeze_request->>'appliedCommitId' IS DISTINCT FROM attempt.applied_commit_id + OR freeze_request->>'contentDigest' IS DISTINCT FROM attempt.content_digest + OR freeze_request->>'digestSchemaVersion' IS DISTINCT FROM attempt.digest_schema_version::TEXT + OR identity_row.target_namespace IS DISTINCT FROM attempt.target_namespace + OR identity_row.canonical_tenant_id IS DISTINCT FROM attempt.canonical_tenant_id + OR identity_row.canonical_version_id IS DISTINCT FROM attempt.canonical_version_id + OR identity_row.local_tenant_key IS DISTINCT FROM attempt.local_tenant_key + OR identity_row.local_version_key IS DISTINCT FROM attempt.version_id + OR identity_row.intake_operation_id IS DISTINCT FROM attempt.intake_operation_id + OR identity_row.intake_request_id IS DISTINCT FROM attempt.intake_request_id + OR identity_row.source_operation_id IS DISTINCT FROM attempt.source_operation_id + OR identity_row.source_evidence_digest IS DISTINCT FROM attempt.source_evidence_digest + OR identity_row.intake_receipt_digest IS DISTINCT FROM attempt.intake_receipt_digest + OR intake_row.target_namespace IS DISTINCT FROM attempt.target_namespace + OR intake_row.canonical_tenant_id IS DISTINCT FROM attempt.canonical_tenant_id + OR intake_row.local_tenant_key IS DISTINCT FROM attempt.local_tenant_key + OR intake_row.intake_request_id IS DISTINCT FROM attempt.intake_request_id + OR intake_row.source_operation_id IS DISTINCT FROM attempt.source_operation_id + OR intake_row.source_evidence_digest IS DISTINCT FROM attempt.source_evidence_digest + OR intake_row.receipt_digest IS DISTINCT FROM attempt.intake_receipt_digest + OR frozen.request_id IS DISTINCT FROM graph.request_id + OR frozen.commit_id IS DISTINCT FROM graph.commit_id + OR frozen.graph_bytes IS DISTINCT FROM graph.graph_bytes + OR application.account_binding_bytes IS DISTINCT FROM NEW.original_account_binding_bytes + OR receipt.account_binding_bytes IS DISTINCT FROM NEW.original_account_binding_bytes + OR receipt.receipt_bytes IS DISTINCT FROM NEW.selector_receipt_bytes + OR application.result_bytes IS DISTINCT FROM NEW.applied_result_bytes + OR graph.binding_digest IS DISTINCT FROM receipt.binding_digest + OR receipt.graph_digest IS DISTINCT FROM ('sha256:' || frozen.graph_sha256) THEN + RAISE EXCEPTION 'World terminal does not bind the exact immutable source, selector, APPLIED result and freeze checkpoint' + USING ERRCODE = '23514'; + END IF; + IF NEW.outcome='PUBLISHED' + AND (NEW.publication_version_state_epoch IS DISTINCT FROM attempt.version_state_epoch + 1 + OR NEW.published_release_bundle_digest IS DISTINCT FROM + ('sha256:' || encode(sha256(NEW.release_content_bytes), 'hex'))) THEN + RAISE EXCEPTION 'PUBLISHED World terminal lacks the exact next Game Design publication epoch' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_world_publication_terminal_validate + BEFORE INSERT ON world_design_publication_terminal FOR EACH ROW + EXECUTE FUNCTION world_validate_publication_terminal(); +CREATE TRIGGER trg_world_publication_terminal_immutable + BEFORE UPDATE OR DELETE ON world_design_publication_terminal FOR EACH ROW + EXECUTE FUNCTION world_reject_publication_attempt_history_mutation(); +CREATE TRIGGER trg_world_publication_terminal_no_truncate + BEFORE TRUNCATE ON world_design_publication_terminal FOR EACH STATEMENT + EXECUTE FUNCTION world_reject_publication_attempt_history_mutation(); + +-- A valid-looking receipt is not a terminal result until the same transaction commits the +-- matching owner phase. This deferred check observes the post-CAS row at transaction commit. +CREATE FUNCTION world_require_publication_terminal_owner_phase() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + expected_phase TEXT; + actual_phase TEXT; +BEGIN + expected_phase := CASE WHEN NEW.outcome='PUBLISHED' THEN 'PUBLISHED' ELSE 'ABORTED' END; + SELECT o.owner_freeze_phase INTO actual_phase + FROM "${serviceSchema}".world_design_publication_fence_attempt a + JOIN "${serviceSchema}".world_design_publication_fence_owner o + ON o.target_namespace=a.target_namespace + AND o.canonical_tenant_id=a.canonical_tenant_id + AND o.local_tenant_key=a.local_tenant_key AND o.version_id=a.version_id + WHERE a.publication_fence=NEW.publication_fence + AND a.owner_binding_schema_version=1 + AND a.target_namespace=NEW.target_namespace + AND a.canonical_tenant_id=NEW.canonical_tenant_id + AND a.canonical_version_id=NEW.canonical_version_id + AND a.publication_request_id=NEW.publication_request_id + AND a.request_digest=NEW.request_digest + AND a.publish_workflow_id=NEW.publish_workflow_id + AND a.version_state_epoch=NEW.freeze_version_state_epoch + AND a.applied_commit_id=NEW.applied_commit_id + AND a.content_digest=NEW.content_digest + AND a.digest_schema_version=NEW.digest_schema_version + AND o.current_publication_fence=NEW.publication_fence; + IF NOT FOUND OR actual_phase IS DISTINCT FROM expected_phase THEN + RAISE EXCEPTION 'World terminal receipt must commit with its exact owner phase' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER trg_world_publication_terminal_owner_phase_commit + AFTER INSERT ON world_design_publication_terminal + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION world_require_publication_terminal_owner_phase(); + +-- Preserve the original OPEN-to-FROZEN writer while allowing only a just-inserted immutable V44 +-- terminal row to authorize FROZEN-to-PUBLISHED/ABORTED. No reopen or reconciliation transition +-- is introduced by this migration. +CREATE OR REPLACE FUNCTION world_protect_publication_fence_owner() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'World publication-fence owner rows cannot be deleted' USING ERRCODE = '55000'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.owner_freeze_phase = 'OPEN' AND NEW.current_publication_fence IS NULL THEN RETURN NEW; END IF; + RAISE EXCEPTION 'World publication-fence owner rows must be created OPEN without a fence' USING ERRCODE = '55000'; + END IF; + IF OLD.target_namespace IS NOT DISTINCT FROM NEW.target_namespace + AND OLD.canonical_tenant_id IS NOT DISTINCT FROM NEW.canonical_tenant_id + AND OLD.local_tenant_key IS NOT DISTINCT FROM NEW.local_tenant_key + AND OLD.version_id IS NOT DISTINCT FROM NEW.version_id + AND OLD.owner_freeze_phase='OPEN' AND NEW.owner_freeze_phase='FROZEN' + AND OLD.current_publication_fence IS NULL AND NEW.current_publication_fence IS NOT NULL THEN + RETURN NEW; + END IF; + IF OLD.target_namespace IS NOT DISTINCT FROM NEW.target_namespace + AND OLD.canonical_tenant_id IS NOT DISTINCT FROM NEW.canonical_tenant_id + AND OLD.local_tenant_key IS NOT DISTINCT FROM NEW.local_tenant_key + AND OLD.version_id IS NOT DISTINCT FROM NEW.version_id + AND OLD.owner_freeze_phase='FROZEN' + AND OLD.current_publication_fence IS NOT DISTINCT FROM NEW.current_publication_fence + AND NEW.owner_freeze_phase IN ('PUBLISHED','ABORTED') + AND EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_design_publication_terminal t + WHERE t.publication_fence=OLD.current_publication_fence + AND t.target_namespace=OLD.target_namespace + AND t.canonical_tenant_id=OLD.canonical_tenant_id + AND t.canonical_version_id=(SELECT a.canonical_version_id + FROM "${serviceSchema}".world_design_publication_fence_attempt a + WHERE a.publication_fence=OLD.current_publication_fence) + AND ((NEW.owner_freeze_phase='PUBLISHED' AND t.outcome='PUBLISHED') + OR (NEW.owner_freeze_phase='ABORTED' AND t.outcome='NO_PUBLICATION')) + ) THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'World publication-fence owner binding or phase transition is immutable' + USING ERRCODE = '55000'; +END; +$$; + +-- Fresh allocation now requires the completed terminal handoff, not merely the earlier freeze. +-- All other V35/V40 guards, source checks and historical input bytes remain unchanged. +DO $migration$ +DECLARE + original TEXT; + phase_anchor TEXT := $anchor$ IF publication_owner.owner_freeze_phase IS DISTINCT FROM 'FROZEN' + OR publication_owner.current_publication_fence IS DISTINCT FROM capture_row.publication_fence THEN + RAISE EXCEPTION 'Canonical preparation requires the exact still-FROZEN V25 source owner' + USING ERRCODE = '23514'; + END IF;$anchor$; + replacement TEXT := $replacement$ IF publication_owner.owner_freeze_phase IS DISTINCT FROM 'PUBLISHED' + OR publication_owner.current_publication_fence IS DISTINCT FROM capture_row.publication_fence + OR NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_design_publication_terminal t + WHERE t.publication_fence=capture_row.publication_fence + AND t.target_namespace=identity_row.target_namespace + AND t.canonical_tenant_id=identity_row.canonical_tenant_id + AND t.canonical_version_id=identity_row.canonical_version_id + AND t.outcome='PUBLISHED' + AND t.publication_request_id=capture_row.freeze_request_json::JSONB->>'publicationRequestId' + AND t.request_digest=capture_row.freeze_request_json::JSONB->>'requestDigest' + AND t.publish_workflow_id=capture_row.freeze_request_json::JSONB->>'publishWorkflowId' + AND t.applied_commit_id=capture_row.freeze_request_json::JSONB->>'appliedCommitId' + AND t.content_digest=capture_row.freeze_request_json::JSONB->>'contentDigest' + AND t.digest_schema_version=(capture_row.freeze_request_json::JSONB->>'digestSchemaVersion')::INTEGER + AND t.published_release_bundle_ref=binding_row.release_attestation_json::JSONB->>'publishedReleaseBundleRef' + AND t.publication_version_state_epoch<=(binding_row.release_attestation_json::JSONB->>'versionStateEpoch')::BIGINT + AND t.world_request_json::JSONB=jsonb_set( + binding_row.release_attestation_json::JSONB->'worldStartLocationEvidence'->'request', + '{versionStateEpoch}',to_jsonb(t.freeze_version_state_epoch::TEXT),FALSE) + ) THEN + RAISE EXCEPTION 'Canonical preparation requires the exact published V44 terminal for this retained release and frozen World source' + USING ERRCODE = '23514'; + END IF;$replacement$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_prepare_canonical_instance(text,text)'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,phase_anchor,'')))/length(phase_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V35 FROZEN preparation phase guard'; + END IF; + EXECUTE replace(original,phase_anchor,replacement); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1018__world_operational_region_assignment.sql b/services/world-management-service/src/main/resources/db/migration/V1018__world_operational_region_assignment.sql new file mode 100644 index 0000000000..c308d03d0d --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1018__world_operational_region_assignment.sql @@ -0,0 +1,93 @@ +-- World owns the assignment label; Game Session registers it and owns its operational epoch/fence. +-- The assignment is separate from the canonical topology UUID. +-- Historical rows remain unassigned until a separately authorized migration can prove identity. +ALTER TABLE region_instance + ADD COLUMN operational_region_id UUID; + +ALTER TABLE region_instance + ADD CONSTRAINT uq_region_instance_operational_region + UNIQUE (tenant_id, game_instance_id, operational_region_id), + ADD CONSTRAINT ck_region_instance_operational_region_non_nil_and_distinct + CHECK ( + operational_region_id IS NULL + OR (operational_region_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND operational_region_id IS DISTINCT FROM canonical_region_instance_id) + ); + +-- [jooq ignore start] +CREATE FUNCTION reject_region_instance_operational_assignment_tuple_change() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.operational_region_id IS DISTINCT FROM OLD.operational_region_id + OR ( + OLD.operational_region_id IS NOT NULL + AND ( + NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.game_instance_id IS DISTINCT FROM OLD.game_instance_id + OR NEW.world_instance_id IS DISTINCT FROM OLD.world_instance_id + ) + ) THEN + RAISE EXCEPTION 'region_instance operational assignment tuple is immutable' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_region_instance_operational_assignment_tuple_immutable + BEFORE UPDATE ON region_instance + FOR EACH ROW + EXECUTE FUNCTION reject_region_instance_operational_assignment_tuple_change(); + +-- V35 writes region_instance directly, so preserve its manifest and row write while adding an +-- independent operational UUID to the exact composite inserted by that canonical producer. +DO $migration$ +DECLARE + original TEXT; + original_oid OID; + original_acl ACLITEM[]; + declaration_anchor TEXT := $anchor$ runtime_uuid UUID;$anchor$; + declaration_replacement TEXT := $replacement$ runtime_uuid UUID; + operational_runtime_uuid UUID;$replacement$; + allocation_anchor TEXT := $anchor$ runtime_uuid := gen_random_uuid(); + region_runtime := jsonb_populate_record$anchor$; + allocation_replacement TEXT := $replacement$ runtime_uuid := gen_random_uuid(); + operational_runtime_uuid := gen_random_uuid(); + WHILE operational_runtime_uuid = runtime_uuid LOOP + operational_runtime_uuid := gen_random_uuid(); + END LOOP; + region_runtime := jsonb_populate_record$replacement$; + region_anchor TEXT := $anchor$ 'canonical_region_instance_id', runtime_uuid));$anchor$; + region_replacement TEXT := $replacement$ 'canonical_region_instance_id', runtime_uuid, + 'operational_region_id', operational_runtime_uuid));$replacement$; +BEGIN + SELECT p.oid, p.proacl + INTO STRICT original_oid, original_acl + FROM pg_proc p + WHERE p.oid = '"${serviceSchema}".world_prepare_canonical_instance(text,text)'::REGPROCEDURE; + SELECT pg_get_functiondef( + '"${serviceSchema}".world_prepare_canonical_instance(text,text)'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, declaration_anchor, ''))) + / length(declaration_anchor) <> 1 + OR (length(original) - length(replace(original, allocation_anchor, ''))) + / length(allocation_anchor) <> 1 + OR (length(original) - length(replace(original, region_anchor, ''))) + / length(region_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one canonical region materialization insertion site'; + END IF; + original := replace(original, declaration_anchor, declaration_replacement); + original := replace(original, allocation_anchor, allocation_replacement); + original := replace(original, region_anchor, region_replacement); + EXECUTE original; + IF '"${serviceSchema}".world_prepare_canonical_instance(text,text)'::REGPROCEDURE + IS DISTINCT FROM original_oid + OR (SELECT p.proacl FROM pg_proc p WHERE p.oid = original_oid) + IS DISTINCT FROM original_acl THEN + RAISE EXCEPTION 'Canonical preparation replacement changed function identity or grants'; + END IF; +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1019__world_canonical_initial_player_location.sql b/services/world-management-service/src/main/resources/db/migration/V1019__world_canonical_initial_player_location.sql new file mode 100644 index 0000000000..32421ff4cf --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1019__world_canonical_initial_player_location.sql @@ -0,0 +1,458 @@ +-- Fresh canonical actor placement is World-owned and runtime-instance scoped (S3). The target +-- retains its typed V42 authored ROOM selector and mapped runtime room; this migration adds only +-- the actor's first placement and its exact operation result, with no retained-row backfill. +CREATE TABLE world_canonical_initial_player_location_operation ( + canonical_tenant_id UUID NOT NULL, + playable_state_namespace_id UUID NOT NULL, + canonical_game_instance_id UUID NOT NULL, + operation_id UUID NOT NULL, + world_instance_id BIGINT NOT NULL REFERENCES world_instance(id) ON DELETE RESTRICT, + request_digest VARCHAR(71) NOT NULL CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'), + request_bytes BYTEA NOT NULL CHECK (octet_length(request_bytes) > 0), + original_lifecycle_evidence_bytes BYTEA NOT NULL CHECK (octet_length(original_lifecycle_evidence_bytes) > 0), + outcome VARCHAR(16) NOT NULL CHECK (outcome IN ('APPLIED', 'CONFLICT')), + conflict_code VARCHAR(64), + result_bytes BYTEA NOT NULL CHECK (octet_length(result_bytes) > 0), + result_digest VARCHAR(71) NOT NULL CHECK (result_digest ~ '^sha256:[0-9a-f]{64}$'), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (operation_id), + CONSTRAINT fk_world_initial_location_operation_association + FOREIGN KEY (canonical_game_instance_id) + REFERENCES world_canonical_instance_association(canonical_game_instance_id) ON DELETE RESTRICT, + CONSTRAINT ck_world_initial_location_operation_ids CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT ck_world_initial_location_operation_outcome CHECK ( + (outcome = 'APPLIED' AND conflict_code IS NULL) + OR (outcome = 'CONFLICT' AND conflict_code IS NOT NULL + AND conflict_code COLLATE "C" ~ '^[A-Z][A-Z0-9_]{0,63}$' + AND conflict_code COLLATE "C" !~ '[^A-Z0-9_]') + ) +); + +CREATE TABLE character_location ( + canonical_tenant_id UUID NOT NULL, + realm_id UUID NOT NULL, + world_slug VARCHAR(120) NOT NULL, + playable_state_namespace_id UUID NOT NULL, + playable_state_scope VARCHAR(16) NOT NULL CHECK (playable_state_scope IN ('SHARED', 'ISOLATED')), + canonical_game_instance_id UUID NOT NULL, + world_instance_id BIGINT NOT NULL REFERENCES world_instance(id) ON DELETE RESTRICT, + canonical_account_id UUID NOT NULL, + character_id UUID NOT NULL, + entity_assignment_operation_id UUID NOT NULL, + entity_assignment_digest CHAR(64) NOT NULL CHECK (entity_assignment_digest ~ '^[0-9a-f]{64}$'), + canonical_version_id UUID NOT NULL, + active_lifecycle_epoch BIGINT NOT NULL CHECK (active_lifecycle_epoch > 0), + initial_room_template_id UUID NOT NULL, + initial_runtime_room_instance_id BIGINT NOT NULL CHECK (initial_runtime_room_instance_id > 0), + runtime_room_instance_id BIGINT NOT NULL CHECK (runtime_room_instance_id > 0), + initial_admission_hold_id UUID NOT NULL, + initial_admission_hold_fence UUID NOT NULL, + initial_admission_request_id VARCHAR(128) NOT NULL CHECK (btrim(initial_admission_request_id) <> ''), + initial_admission_request_digest CHAR(64) NOT NULL CHECK (initial_admission_request_digest ~ '^[0-9a-f]{64}$'), + catalog_revision BIGINT NOT NULL CHECK (catalog_revision > 0), + initial_admission_owner_proof_id VARCHAR(128) NOT NULL CHECK (btrim(initial_admission_owner_proof_id) <> ''), + initial_admission_owner_proof_digest CHAR(64) NOT NULL CHECK (initial_admission_owner_proof_digest ~ '^[0-9a-f]{64}$'), + pointer_audit_id VARCHAR(128) NOT NULL CHECK (btrim(pointer_audit_id) <> ''), + pointer_version BIGINT NOT NULL CHECK (pointer_version > 0), + initial_location_operation_id UUID NOT NULL, + initial_location_request_digest VARCHAR(71) NOT NULL CHECK (initial_location_request_digest ~ '^sha256:[0-9a-f]{64}$'), + initial_lifecycle_evidence_bytes BYTEA NOT NULL CHECK (octet_length(initial_lifecycle_evidence_bytes) > 0), + initial_lifecycle_evidence_digest VARCHAR(71) NOT NULL CHECK (initial_lifecycle_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + row_version BIGINT NOT NULL DEFAULT 0 CHECK (row_version >= 0), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (canonical_tenant_id, playable_state_namespace_id, canonical_game_instance_id, + character_id), + CONSTRAINT uq_world_character_assignment_operation + UNIQUE (canonical_tenant_id, playable_state_namespace_id, canonical_game_instance_id, + entity_assignment_operation_id), + CONSTRAINT fk_world_character_location_association + FOREIGN KEY (canonical_game_instance_id) + REFERENCES world_canonical_instance_association(canonical_game_instance_id) ON DELETE RESTRICT, + CONSTRAINT fk_world_character_location_operation + FOREIGN KEY (initial_location_operation_id) + REFERENCES world_canonical_initial_player_location_operation(operation_id) ON DELETE RESTRICT, + CONSTRAINT fk_world_character_location_admission_hold + FOREIGN KEY (initial_admission_hold_id) + REFERENCES initial_admission_bind_hold(hold_id) ON DELETE RESTRICT, + CONSTRAINT ck_world_character_location_ids CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND realm_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_account_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND character_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND entity_assignment_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND initial_room_template_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND initial_admission_hold_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND initial_admission_hold_fence <> '00000000-0000-0000-0000-000000000000'::UUID + AND initial_location_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT ck_world_character_location_slug CHECK ( + octet_length(world_slug) BETWEEN 1 AND 120 AND world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ) +); + +CREATE INDEX idx_world_character_location_occupants + ON character_location (canonical_tenant_id, playable_state_namespace_id, + canonical_game_instance_id, runtime_room_instance_id); + +-- [jooq ignore start] +REVOKE ALL ON world_canonical_initial_player_location_operation FROM PUBLIC; +REVOKE ALL ON character_location FROM PUBLIC; + +CREATE FUNCTION world_guard_initial_location_operation() +RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER +SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + request JSONB; + result JSONB; + canonical_result BYTEA; + canonical_room TEXT; + canonical_conflict_code TEXT; + canonical_runtime_room TEXT; + request_base64 TEXT; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'World initial-location operation evidence is immutable' USING ERRCODE = '55000'; + END IF; + IF NEW.request_digest IS DISTINCT FROM ('sha256:' || encode(sha256(NEW.request_bytes), 'hex')) + OR NEW.result_digest IS DISTINCT FROM ('sha256:' || encode(sha256(NEW.result_bytes), 'hex')) THEN + RAISE EXCEPTION 'World initial-location operation digests do not match retained bytes' USING ERRCODE = '23514'; + END IF; + request := convert_from(NEW.request_bytes, 'UTF8')::JSONB; + result := convert_from(NEW.result_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(request) IS DISTINCT FROM 'object' + OR request->>'schema' IS DISTINCT FROM 'world-canonical-initial-player-location-request/v1' + OR request->>'operationId' IS DISTINCT FROM NEW.operation_id::TEXT + OR request->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR request->>'playableStateNamespaceId' IS DISTINCT FROM NEW.playable_state_namespace_id::TEXT + OR request->>'canonicalGameInstanceId' IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR request->>'initialAdmissionOrigin' IS DISTINCT FROM 'NO_PRIOR_POINTER' + OR jsonb_typeof(request->'activeLifecycleEvidence') IS DISTINCT FROM 'object' + OR (convert_from(NEW.original_lifecycle_evidence_bytes, 'UTF8')::JSONB #- '{request,readRequestId}') + IS DISTINCT FROM (request->'activeLifecycleEvidence' #- '{request,readRequestId}') + THEN + RAISE EXCEPTION 'World initial-location operation differs from its canonical request/result' USING ERRCODE = '23514'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_canonical_instance_association a + WHERE a.canonical_game_instance_id = NEW.canonical_game_instance_id + AND a.world_instance_id = NEW.world_instance_id + AND a.canonical_tenant_id = NEW.canonical_tenant_id + AND a.playable_state_namespace_id = NEW.playable_state_namespace_id + ) THEN + RAISE EXCEPTION 'World initial-location operation differs from its canonical association' USING ERRCODE = '23514'; + END IF; + + IF jsonb_typeof(result) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'World initial-location result must be a closed canonical object' USING ERRCODE = '23514'; + END IF; + IF (SELECT count(*) FROM jsonb_object_keys(result)) <> 8 + OR NOT (result ?& ARRAY[ + 'conflictCode', 'operationId', 'outcome', 'requestBytesBase64', + 'requestDigest', 'runtimeRoomInstanceId', 'schema', 'startLocation' + ]) THEN + RAISE EXCEPTION 'World initial-location result must have exactly eight fields' USING ERRCODE = '23514'; + END IF; + IF jsonb_typeof(result->'schema') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'operationId') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'requestDigest') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'requestBytesBase64') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'outcome') IS DISTINCT FROM 'string' + OR result->>'schema' IS DISTINCT FROM 'world-canonical-initial-player-location-result/v1' + OR result->>'operationId' IS DISTINCT FROM NEW.operation_id::TEXT + OR result->>'requestDigest' IS DISTINCT FROM NEW.request_digest + OR result->>'outcome' IS DISTINCT FROM NEW.outcome THEN + RAISE EXCEPTION 'World initial-location operation differs from its canonical result identity' USING ERRCODE = '23514'; + END IF; + + request_base64 := replace(replace(encode(NEW.request_bytes, 'base64'), E'\n', ''), E'\r', ''); + IF result->>'requestBytesBase64' IS DISTINCT FROM request_base64 + OR decode(result->>'requestBytesBase64', 'base64') IS DISTINCT FROM NEW.request_bytes THEN + RAISE EXCEPTION 'World initial-location result request bytes differ from its operation' USING ERRCODE = '23514'; + END IF; + + IF NEW.outcome = 'APPLIED' THEN + IF jsonb_typeof(result->'conflictCode') IS DISTINCT FROM 'null' + OR jsonb_typeof(result->'runtimeRoomInstanceId') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'startLocation') IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'Applied World initial-location result has an invalid field shape' USING ERRCODE = '23514'; + END IF; + IF (SELECT count(*) FROM jsonb_object_keys(result->'startLocation')) <> 3 + OR NOT ((result->'startLocation') ?& ARRAY['roomTemplateId', 'tenantId', 'versionId']) + OR jsonb_typeof(result->'startLocation'->'roomTemplateId') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'startLocation'->'tenantId') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'startLocation'->'versionId') IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Applied World initial-location result room must have exactly three string fields' USING ERRCODE = '23514'; + END IF; + IF (result->'startLocation'->>'roomTemplateId') !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (result->'startLocation'->>'tenantId') !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (result->'startLocation'->>'versionId') !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (result->'startLocation'->>'roomTemplateId') = '00000000-0000-0000-0000-000000000000' + OR (result->'startLocation'->>'tenantId') = '00000000-0000-0000-0000-000000000000' + OR (result->'startLocation'->>'versionId') = '00000000-0000-0000-0000-000000000000' + OR (result->>'runtimeRoomInstanceId') !~ '^[1-9][0-9]*$' THEN + RAISE EXCEPTION 'Applied World initial-location result contains a noncanonical room identity' USING ERRCODE = '23514'; + END IF; + IF (result->>'runtimeRoomInstanceId')::NUMERIC > 9223372036854775807 THEN + RAISE EXCEPTION 'Applied World initial-location runtime room id exceeds signed 64-bit range' USING ERRCODE = '23514'; + END IF; + IF (result->'startLocation') IS DISTINCT FROM + (request->'activeLifecycleEvidence'->'startLocation') + OR result->>'runtimeRoomInstanceId' IS DISTINCT FROM + request->'activeLifecycleEvidence'->>'runtimeRoomInstanceId' THEN + RAISE EXCEPTION 'Applied World initial-location result differs from the exact V2 ROOM mapping' USING ERRCODE = '23514'; + END IF; + canonical_room := + '{"roomTemplateId":' || to_jsonb(result->'startLocation'->>'roomTemplateId')::TEXT + || ',"tenantId":' || to_jsonb(result->'startLocation'->>'tenantId')::TEXT + || ',"versionId":' || to_jsonb(result->'startLocation'->>'versionId')::TEXT || '}'; + canonical_conflict_code := 'null'; + canonical_runtime_room := to_jsonb(result->>'runtimeRoomInstanceId')::TEXT; + ELSE + IF jsonb_typeof(result->'conflictCode') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'runtimeRoomInstanceId') IS DISTINCT FROM 'null' + OR jsonb_typeof(result->'startLocation') IS DISTINCT FROM 'null' + OR result->>'conflictCode' IS DISTINCT FROM NEW.conflict_code THEN + RAISE EXCEPTION 'Conflicting World initial-location result has an invalid field shape' USING ERRCODE = '23514'; + END IF; + IF (result->>'conflictCode') COLLATE "C" !~ '^[A-Z][A-Z0-9_]{0,63}$' + OR (result->>'conflictCode') COLLATE "C" ~ '[^A-Z0-9_]' THEN + RAISE EXCEPTION 'Conflicting World initial-location result has an invalid machine code' USING ERRCODE = '23514'; + END IF; + canonical_room := 'null'; + canonical_conflict_code := to_jsonb(result->>'conflictCode')::TEXT; + canonical_runtime_room := 'null'; + END IF; + + canonical_result := convert_to( + '{"conflictCode":' || canonical_conflict_code + || ',"operationId":' || to_jsonb(NEW.operation_id::TEXT)::TEXT + || ',"outcome":' || to_jsonb(NEW.outcome)::TEXT + || ',"requestBytesBase64":' || to_jsonb(request_base64)::TEXT + || ',"requestDigest":' || to_jsonb(NEW.request_digest)::TEXT + || ',"runtimeRoomInstanceId":' || canonical_runtime_room + || ',"schema":"world-canonical-initial-player-location-result/v1"' + || ',"startLocation":' || canonical_room || '}', + 'UTF8'); + IF NEW.result_bytes IS DISTINCT FROM canonical_result THEN + RAISE EXCEPTION 'World initial-location result bytes are not canonical' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_world_guard_initial_location_operation + BEFORE INSERT OR UPDATE OR DELETE ON world_canonical_initial_player_location_operation + FOR EACH ROW EXECUTE FUNCTION world_guard_initial_location_operation(); +REVOKE ALL ON FUNCTION world_guard_initial_location_operation() FROM PUBLIC; + +CREATE FUNCTION world_guard_initial_character_location() +RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER +SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + operation_row "${serviceSchema}".world_canonical_initial_player_location_operation%ROWTYPE; + request JSONB; + lifecycle JSONB; +BEGIN + IF TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Initial placement is immutable; a separate World movement owner must be implemented' USING ERRCODE = '55000'; + END IF; + IF TG_OP <> 'INSERT' THEN RETURN NEW; END IF; + + SELECT * INTO STRICT operation_row + FROM "${serviceSchema}".world_canonical_initial_player_location_operation + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND playable_state_namespace_id = NEW.playable_state_namespace_id + AND canonical_game_instance_id = NEW.canonical_game_instance_id + AND operation_id = NEW.initial_location_operation_id; + request := convert_from(operation_row.request_bytes, 'UTF8')::JSONB; + lifecycle := convert_from(NEW.initial_lifecycle_evidence_bytes, 'UTF8')::JSONB; + + IF operation_row.outcome IS DISTINCT FROM 'APPLIED' + OR operation_row.request_digest IS DISTINCT FROM NEW.initial_location_request_digest + OR request->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR request->>'playableStateNamespaceId' IS DISTINCT FROM NEW.playable_state_namespace_id::TEXT + OR request->>'canonicalGameInstanceId' IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR request->>'playableStateScope' IS DISTINCT FROM NEW.playable_state_scope + OR request->>'canonicalAccountId' IS DISTINCT FROM NEW.canonical_account_id::TEXT + OR request->>'characterId' IS DISTINCT FROM NEW.character_id::TEXT + OR request->>'entityAssignmentOperationId' IS DISTINCT FROM NEW.entity_assignment_operation_id::TEXT + OR request->>'entityAssignmentDigest' IS DISTINCT FROM NEW.entity_assignment_digest + OR request->>'realmId' IS DISTINCT FROM NEW.realm_id::TEXT + OR request->>'worldSlug' IS DISTINCT FROM NEW.world_slug + OR request->>'initialAdmissionHoldId' IS DISTINCT FROM NEW.initial_admission_hold_id::TEXT + OR request->>'initialAdmissionHoldFence' IS DISTINCT FROM NEW.initial_admission_hold_fence::TEXT + OR request->>'initialAdmissionOrigin' IS DISTINCT FROM 'NO_PRIOR_POINTER' + OR request->>'initialAdmissionRequestId' IS DISTINCT FROM NEW.initial_admission_request_id + OR request->>'initialAdmissionRequestDigest' IS DISTINCT FROM NEW.initial_admission_request_digest + OR request->>'initialAdmissionOwnerProofId' IS DISTINCT FROM NEW.initial_admission_owner_proof_id + OR request->>'initialAdmissionOwnerProofDigest' IS DISTINCT FROM NEW.initial_admission_owner_proof_digest + OR request->>'pointerAuditId' IS DISTINCT FROM NEW.pointer_audit_id + OR request->>'pointerVersion' IS DISTINCT FROM NEW.pointer_version::TEXT + OR request->>'catalogRevision' IS DISTINCT FROM NEW.catalog_revision::TEXT + OR request->'activeLifecycleEvidence' IS NULL + OR (request->'activeLifecycleEvidence' #- '{request,readRequestId}') + IS DISTINCT FROM (lifecycle #- '{request,readRequestId}') + OR NEW.initial_lifecycle_evidence_digest IS DISTINCT FROM ('sha256:' || encode(sha256(NEW.initial_lifecycle_evidence_bytes), 'hex')) + OR lifecycle->>'schema' IS DISTINCT FROM 'world-canonical-instance-lifecycle-evidence/v1' + OR lifecycle->>'lifecycleStatus' IS DISTINCT FROM 'ACTIVE' + OR lifecycle->>'lifecycleEpoch' IS DISTINCT FROM NEW.active_lifecycle_epoch::TEXT + OR lifecycle->'request'->>'canonicalGameInstanceId' IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR lifecycle->'request'->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR lifecycle->'request'->>'playableStateNamespaceId' IS DISTINCT FROM NEW.playable_state_namespace_id::TEXT + OR lifecycle->'request'->>'playableStateScope' IS DISTINCT FROM NEW.playable_state_scope + OR lifecycle->'startLocation'->>'tenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR lifecycle->'startLocation'->>'versionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR lifecycle->'startLocation'->>'roomTemplateId' IS DISTINCT FROM NEW.initial_room_template_id::TEXT + OR lifecycle->>'runtimeRoomInstanceId' IS DISTINCT FROM NEW.initial_runtime_room_instance_id::TEXT + OR NEW.runtime_room_instance_id IS DISTINCT FROM NEW.initial_runtime_room_instance_id THEN + RAISE EXCEPTION 'World initial placement differs from its retained operation or lifecycle proof' USING ERRCODE = '23514'; + END IF; + + IF NOT EXISTS ( + SELECT 1 + FROM "${serviceSchema}".world_canonical_instance_association a + JOIN "${serviceSchema}".world_instance w ON w.id = a.world_instance_id + JOIN "${serviceSchema}".world_canonical_preparation_start_location s + ON s.canonical_game_instance_id = a.canonical_game_instance_id + AND s.world_instance_id = a.world_instance_id + JOIN "${serviceSchema}".world_canonical_instance_topology_identity m + ON m.world_instance_id = a.world_instance_id + AND m.canonical_game_instance_id = a.canonical_game_instance_id + AND m.family = 'ROOM' AND m.template_id = s.room_template_id + AND m.runtime_room_instance_id = s.runtime_room_instance_id + JOIN "${serviceSchema}".room_instance r + ON r.id = m.runtime_row_id AND r.room_instance_row_id = s.runtime_room_instance_id + JOIN "${serviceSchema}".initial_admission_bind_hold h + ON h.hold_id = NEW.initial_admission_hold_id + WHERE a.canonical_game_instance_id = NEW.canonical_game_instance_id + AND a.world_instance_id = NEW.world_instance_id + AND a.canonical_tenant_id = NEW.canonical_tenant_id + AND a.canonical_world_slug = NEW.world_slug + AND a.playable_state_namespace_id = NEW.playable_state_namespace_id + AND a.playable_state_scope = NEW.playable_state_scope + AND a.canonical_version_id = NEW.canonical_version_id + AND w.canonical_game_instance_id = a.canonical_game_instance_id + AND w.canonical_tenant_id = NEW.canonical_tenant_id + AND w.canonical_world_slug = NEW.world_slug + AND w.playable_state_namespace_id = NEW.playable_state_namespace_id + AND w.playable_state_scope = NEW.playable_state_scope + AND w.status = 'ACTIVE' AND w.lifecycle_epoch = NEW.active_lifecycle_epoch + AND s.canonical_tenant_id = NEW.canonical_tenant_id + AND s.canonical_version_id = NEW.canonical_version_id + AND s.room_template_id = NEW.initial_room_template_id + AND s.runtime_room_instance_id = NEW.initial_runtime_room_instance_id + AND r.tenant_id = w.tenant_id AND r.game_instance_id = w.game_instance_id + AND h.tenant_id = w.tenant_id AND h.game_instance_id = w.game_instance_id + AND h.realm_uuid = NEW.realm_id + AND h.playable_state_namespace_uuid = NEW.playable_state_namespace_id + AND h.playable_state_scope = NEW.playable_state_scope + AND h.version_id = w.version_id AND h.active_lifecycle_epoch = w.lifecycle_epoch + AND h.status = 'COMMITTED' AND h.expected_no_prior_pointer IS TRUE + AND h.initial_admission_request_id = NEW.initial_admission_request_id + AND h.request_digest = NEW.initial_admission_request_digest + AND h.expected_catalog_revision = NEW.catalog_revision + AND h.owner_proof_id = NEW.initial_admission_owner_proof_id + AND h.owner_proof_digest = NEW.initial_admission_owner_proof_digest + AND h.owner_pointer_audit_id = NEW.pointer_audit_id + AND h.owner_pointer_version = NEW.pointer_version + AND h.hold_fence = NEW.initial_admission_hold_fence + ) THEN + RAISE EXCEPTION 'World initial location lacks exact current association, V2 ROOM mapping, or committed first-open proof' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_world_guard_initial_character_location + BEFORE INSERT OR UPDATE ON character_location + FOR EACH ROW EXECUTE FUNCTION world_guard_initial_character_location(); +REVOKE ALL ON FUNCTION world_guard_initial_character_location() FROM PUBLIC; + +CREATE FUNCTION world_require_initial_location_operation_result() +RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER +SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + request JSONB; + result JSONB; + lifecycle JSONB; +BEGIN + request := convert_from(NEW.request_bytes, 'UTF8')::JSONB; + result := convert_from(NEW.result_bytes, 'UTF8')::JSONB; + lifecycle := request->'activeLifecycleEvidence'; + IF NEW.outcome = 'APPLIED' AND NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".character_location l + WHERE l.canonical_tenant_id = NEW.canonical_tenant_id + AND l.playable_state_namespace_id = NEW.playable_state_namespace_id + AND l.canonical_game_instance_id = NEW.canonical_game_instance_id + AND l.canonical_account_id = (convert_from(NEW.request_bytes, 'UTF8')::JSONB->>'canonicalAccountId')::UUID + AND l.character_id = (convert_from(NEW.request_bytes, 'UTF8')::JSONB->>'characterId')::UUID + AND l.entity_assignment_operation_id = (convert_from(NEW.request_bytes, 'UTF8')::JSONB->>'entityAssignmentOperationId')::UUID + AND l.entity_assignment_digest = convert_from(NEW.request_bytes, 'UTF8')::JSONB->>'entityAssignmentDigest' + AND l.canonical_tenant_id = (result->'startLocation'->>'tenantId')::UUID + AND l.canonical_version_id = (result->'startLocation'->>'versionId')::UUID + AND l.initial_room_template_id = (result->'startLocation'->>'roomTemplateId')::UUID + AND l.initial_runtime_room_instance_id = (result->>'runtimeRoomInstanceId')::BIGINT + AND result->'startLocation' IS NOT DISTINCT FROM lifecycle->'startLocation' + AND result->>'runtimeRoomInstanceId' IS NOT DISTINCT FROM lifecycle->>'runtimeRoomInstanceId' + AND l.canonical_account_id = (request->>'canonicalAccountId')::UUID + AND l.initial_admission_hold_id = (request->>'initialAdmissionHoldId')::UUID + AND l.initial_admission_hold_fence = (request->>'initialAdmissionHoldFence')::UUID + AND l.realm_id = (request->>'realmId')::UUID + AND l.world_slug = request->>'worldSlug' + AND l.playable_state_scope = request->>'playableStateScope' + AND l.canonical_version_id = (lifecycle->'request'->>'canonicalVersionId')::UUID + AND l.active_lifecycle_epoch = (lifecycle->>'lifecycleEpoch')::BIGINT + AND l.initial_admission_request_id = request->>'initialAdmissionRequestId' + AND l.initial_admission_request_digest = request->>'initialAdmissionRequestDigest' + AND l.catalog_revision = (request->>'catalogRevision')::BIGINT + AND l.initial_admission_owner_proof_id = request->>'initialAdmissionOwnerProofId' + AND l.initial_admission_owner_proof_digest = request->>'initialAdmissionOwnerProofDigest' + AND l.pointer_audit_id = request->>'pointerAuditId' + AND l.pointer_version = (request->>'pointerVersion')::BIGINT + ) THEN + RAISE EXCEPTION 'Applied World initial-location operation has no atomic location row' USING ERRCODE = '23514'; + END IF; + IF NEW.outcome = 'CONFLICT' AND EXISTS ( + SELECT 1 FROM "${serviceSchema}".character_location l + WHERE l.canonical_tenant_id = NEW.canonical_tenant_id + AND l.playable_state_namespace_id = NEW.playable_state_namespace_id + AND l.canonical_game_instance_id = NEW.canonical_game_instance_id + AND l.initial_location_operation_id = NEW.operation_id + ) THEN + RAISE EXCEPTION 'Conflicting World initial-location operation cannot own a location row' USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER trg_world_require_initial_location_operation_result + AFTER INSERT ON world_canonical_initial_player_location_operation + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION world_require_initial_location_operation_result(); +REVOKE ALL ON FUNCTION world_require_initial_location_operation_result() FROM PUBLIC; + +CREATE FUNCTION world_reject_initial_location_operation_truncate() +RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER +SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + RAISE EXCEPTION 'World initial-location operation evidence cannot be truncated' USING ERRCODE = '55000'; +END; +$$; + +CREATE TRIGGER trg_world_reject_initial_location_operation_truncate + BEFORE TRUNCATE ON world_canonical_initial_player_location_operation + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_initial_location_operation_truncate(); +REVOKE ALL ON FUNCTION world_reject_initial_location_operation_truncate() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1020__canonical_initial_admission_hold_binding.sql b/services/world-management-service/src/main/resources/db/migration/V1020__canonical_initial_admission_hold_binding.sql new file mode 100644 index 0000000000..c14e117748 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1020__canonical_initial_admission_hold_binding.sql @@ -0,0 +1,255 @@ +-- Canonical first-open holds retain their complete owner request alongside the legacy numeric +-- termination-blocking record. Retained V23 rows intentionally remain unmapped. +-- PostgreSQL auto-names V23's CHECK; H2 metadata simulator has a different name. +-- [jooq ignore start] +ALTER TABLE initial_admission_bind_hold + DROP CONSTRAINT initial_admission_bind_hold_expected_no_prior_pointer_check; +-- [jooq ignore stop] + +ALTER TABLE initial_admission_bind_hold + ADD COLUMN canonical_target_namespace VARCHAR(63), + ADD COLUMN canonical_tenant_id UUID, + ADD COLUMN canonical_world_slug VARCHAR(120), + ADD COLUMN canonical_game_instance_id UUID, + ADD COLUMN canonical_version_id UUID, + ADD COLUMN initial_admission_origin VARCHAR(32), + ADD COLUMN expected_prior_pointer_version BIGINT, + ADD COLUMN canonical_request_bytes BYTEA, + ADD COLUMN hold_binding_digest VARCHAR(71), + ADD CONSTRAINT fk_initial_admission_bind_canonical_association + FOREIGN KEY ( + canonical_target_namespace, + canonical_tenant_id, + canonical_world_slug, + playable_state_namespace_uuid, + playable_state_scope, + canonical_game_instance_id + ) REFERENCES world_canonical_instance_association ( + canonical_target_namespace, + canonical_tenant_id, + canonical_world_slug, + playable_state_namespace_id, + playable_state_scope, + canonical_game_instance_id + ) ON DELETE RESTRICT, + ADD CONSTRAINT ck_initial_admission_bind_canonical_metadata CHECK ( + ( + canonical_target_namespace IS NULL + AND canonical_tenant_id IS NULL + AND canonical_world_slug IS NULL + AND canonical_game_instance_id IS NULL + AND canonical_version_id IS NULL + AND initial_admission_origin IS NULL + AND expected_prior_pointer_version IS NULL + AND canonical_request_bytes IS NULL + AND hold_binding_digest IS NULL + AND expected_no_prior_pointer IS TRUE + ) + OR + ( + canonical_target_namespace IS NOT NULL + AND canonical_tenant_id IS NOT NULL + AND canonical_world_slug IS NOT NULL + AND canonical_game_instance_id IS NOT NULL + AND canonical_version_id IS NOT NULL + AND initial_admission_origin IS NOT NULL + AND canonical_request_bytes IS NOT NULL + AND hold_binding_digest IS NOT NULL + AND canonical_target_namespace COLLATE "C" ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_world_slug COLLATE "C" ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND octet_length(canonical_world_slug) BETWEEN 1 AND 120 + AND canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND octet_length(canonical_request_bytes) > 0 + AND hold_binding_digest COLLATE "C" ~ '^sha256:[0-9a-f]{64}$' + AND ( + (initial_admission_origin = 'NO_PRIOR_POINTER' + AND expected_no_prior_pointer IS TRUE + AND expected_prior_pointer_version IS NULL) + OR + (initial_admission_origin = 'EXPECT_CLOSED' + AND expected_no_prior_pointer IS FALSE + AND expected_prior_pointer_version IS NOT NULL + AND expected_prior_pointer_version > 0) + ) + ) + ); + +-- [jooq ignore start] +REVOKE ALL ON initial_admission_bind_hold FROM PUBLIC; + +CREATE FUNCTION world_guard_canonical_initial_admission_hold() +RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER +SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + instance_row "${serviceSchema}".world_instance%ROWTYPE; + association_row "${serviceSchema}".world_canonical_instance_association%ROWTYPE; + stored_request JSONB; + expected_request JSONB; +BEGIN + IF TG_OP = 'DELETE' THEN + IF OLD.canonical_request_bytes IS NOT NULL THEN + RAISE EXCEPTION 'Canonical initial-admission hold identity cannot be deleted' + USING ERRCODE = '55000'; + END IF; + RETURN OLD; + END IF; + + IF TG_OP = 'UPDATE' THEN + IF OLD.hold_id IS DISTINCT FROM NEW.hold_id + OR OLD.hold_fence IS DISTINCT FROM NEW.hold_fence + OR OLD.tenant_id IS DISTINCT FROM NEW.tenant_id + OR OLD.realm_uuid IS DISTINCT FROM NEW.realm_uuid + OR OLD.playable_state_namespace_uuid IS DISTINCT FROM NEW.playable_state_namespace_uuid + OR OLD.playable_state_scope IS DISTINCT FROM NEW.playable_state_scope + OR OLD.game_instance_id IS DISTINCT FROM NEW.game_instance_id + OR OLD.version_id IS DISTINCT FROM NEW.version_id + OR OLD.active_lifecycle_epoch IS DISTINCT FROM NEW.active_lifecycle_epoch + OR OLD.initial_admission_request_id IS DISTINCT FROM NEW.initial_admission_request_id + OR OLD.request_digest IS DISTINCT FROM NEW.request_digest + OR OLD.expected_no_prior_pointer IS DISTINCT FROM NEW.expected_no_prior_pointer + OR OLD.expected_catalog_revision IS DISTINCT FROM NEW.expected_catalog_revision + OR OLD.diagnostic_expires_at IS DISTINCT FROM NEW.diagnostic_expires_at + OR OLD.created_at IS DISTINCT FROM NEW.created_at + OR OLD.canonical_target_namespace IS DISTINCT FROM NEW.canonical_target_namespace + OR OLD.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR OLD.canonical_world_slug IS DISTINCT FROM NEW.canonical_world_slug + OR OLD.canonical_game_instance_id IS DISTINCT FROM NEW.canonical_game_instance_id + OR OLD.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR OLD.initial_admission_origin IS DISTINCT FROM NEW.initial_admission_origin + OR OLD.expected_prior_pointer_version IS DISTINCT FROM NEW.expected_prior_pointer_version + OR OLD.canonical_request_bytes IS DISTINCT FROM NEW.canonical_request_bytes + OR OLD.hold_binding_digest IS DISTINCT FROM NEW.hold_binding_digest THEN + RAISE EXCEPTION 'Initial-admission hold acquisition identity is immutable' + USING ERRCODE = '55000'; + END IF; + IF OLD.canonical_request_bytes IS NOT NULL + AND (OLD.status IS DISTINCT FROM NEW.status + OR OLD.owner_proof_id IS DISTINCT FROM NEW.owner_proof_id + OR OLD.owner_proof_digest IS DISTINCT FROM NEW.owner_proof_digest + OR OLD.owner_pointer_audit_id IS DISTINCT FROM NEW.owner_pointer_audit_id + OR OLD.owner_pointer_version IS DISTINCT FROM NEW.owner_pointer_version + OR OLD.terminal_at IS DISTINCT FROM NEW.terminal_at) THEN + RAISE EXCEPTION 'Canonical initial-admission hold requires its deferred typed owner outcome' + USING ERRCODE = '55000'; + END IF; + IF OLD.canonical_request_bytes IS NOT NULL THEN + RAISE EXCEPTION 'Canonical initial-admission hold lifecycle updates are not enabled' + USING ERRCODE = '55000'; + END IF; + RETURN NEW; + END IF; + + -- A retained V23 numeric hold can never be promoted to canonical evidence. New untyped + -- acquisitions are rejected when their actual private World row already has an association. + IF NEW.canonical_request_bytes IS NULL THEN + SELECT wi.* INTO instance_row + FROM "${serviceSchema}".world_instance wi + WHERE wi.tenant_id = NEW.tenant_id + AND wi.game_instance_id = NEW.game_instance_id + FOR UPDATE; + IF FOUND AND EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_canonical_instance_association a + WHERE a.world_instance_id = instance_row.id + ) THEN + RAISE EXCEPTION 'Canonical World instances require a typed initial-admission hold' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + -- Resolve private numeric keys only through the actual association row and its World row. + SELECT a.* INTO association_row + FROM "${serviceSchema}".world_canonical_instance_association a + JOIN "${serviceSchema}".world_instance wi ON wi.id = a.world_instance_id + WHERE wi.tenant_id = NEW.tenant_id + AND wi.game_instance_id = NEW.game_instance_id + AND wi.version_id = NEW.version_id + FOR UPDATE OF wi; + IF NOT FOUND THEN + RAISE EXCEPTION 'Canonical initial-admission hold lacks its actual World association' + USING ERRCODE = '23514'; + END IF; + + SELECT wi.* INTO instance_row + FROM "${serviceSchema}".world_instance wi + WHERE wi.id = association_row.world_instance_id; + IF NOT FOUND + OR association_row.canonical_target_namespace IS DISTINCT FROM NEW.canonical_target_namespace + OR association_row.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR association_row.canonical_world_slug IS DISTINCT FROM NEW.canonical_world_slug + OR association_row.playable_state_namespace_id IS DISTINCT FROM NEW.playable_state_namespace_uuid + OR association_row.playable_state_scope IS DISTINCT FROM NEW.playable_state_scope + OR association_row.canonical_game_instance_id IS DISTINCT FROM NEW.canonical_game_instance_id + OR association_row.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR association_row.local_tenant_key IS DISTINCT FROM NEW.tenant_id + OR association_row.private_game_instance_key IS DISTINCT FROM NEW.game_instance_id + OR association_row.local_version_key IS DISTINCT FROM NEW.version_id + OR instance_row.canonical_game_instance_id IS DISTINCT FROM association_row.canonical_game_instance_id + OR instance_row.canonical_target_namespace IS DISTINCT FROM association_row.canonical_target_namespace + OR instance_row.canonical_tenant_id IS DISTINCT FROM association_row.canonical_tenant_id + OR instance_row.canonical_world_slug IS DISTINCT FROM association_row.canonical_world_slug + OR instance_row.playable_state_namespace_id IS DISTINCT FROM association_row.playable_state_namespace_id + OR instance_row.playable_state_scope IS DISTINCT FROM association_row.playable_state_scope + OR instance_row.version_id IS DISTINCT FROM association_row.local_version_key + OR instance_row.status IS DISTINCT FROM 'ACTIVE' + OR instance_row.lifecycle_epoch IS DISTINCT FROM NEW.active_lifecycle_epoch THEN + RAISE EXCEPTION 'Canonical initial-admission hold differs from its actual World association' + USING ERRCODE = '23514'; + END IF; + + IF NEW.hold_binding_digest IS DISTINCT FROM + ('sha256:' || encode(sha256(NEW.canonical_request_bytes), 'hex')) THEN + RAISE EXCEPTION 'Canonical initial-admission hold digest differs from its request bytes' + USING ERRCODE = '23514'; + END IF; + + stored_request := convert_from(NEW.canonical_request_bytes, 'UTF8')::JSONB; + expected_request := jsonb_build_object( + 'schema', 'world-canonical-initial-admission-hold-request/v1', + 'request', jsonb_build_object( + 'targetNamespace', NEW.canonical_target_namespace, + 'canonicalTenantId', NEW.canonical_tenant_id::TEXT, + 'worldSlug', NEW.canonical_world_slug, + 'realmId', NEW.realm_uuid::TEXT, + 'playableStateNamespaceId', NEW.playable_state_namespace_uuid::TEXT, + 'playableStateScope', NEW.playable_state_scope, + 'canonicalGameInstanceId', NEW.canonical_game_instance_id::TEXT, + 'canonicalVersionId', NEW.canonical_version_id::TEXT, + 'activeLifecycleEpoch', NEW.active_lifecycle_epoch::TEXT, + 'initialAdmissionRequestId', NEW.initial_admission_request_id, + 'initialAdmissionRequestDigest', NEW.request_digest::TEXT, + 'initialAdmissionOrigin', NEW.initial_admission_origin, + 'expectedCatalogRevision', NEW.expected_catalog_revision::TEXT, + 'expectedPriorPointerVersion', CASE + WHEN NEW.expected_prior_pointer_version IS NULL THEN NULL + ELSE NEW.expected_prior_pointer_version::TEXT + END + ) + ); + IF jsonb_typeof(stored_request) IS DISTINCT FROM 'object' + OR stored_request IS DISTINCT FROM expected_request THEN + RAISE EXCEPTION 'Canonical initial-admission request bytes differ from hold columns' + USING ERRCODE = '23514'; + END IF; + + IF NEW.status <> 'PENDING' + OR NEW.owner_proof_id IS NOT NULL + OR NEW.owner_proof_digest IS NOT NULL + OR NEW.owner_pointer_audit_id IS NOT NULL + OR NEW.owner_pointer_version IS NOT NULL + OR NEW.terminal_at IS NOT NULL THEN + RAISE EXCEPTION 'Canonical initial-admission acquisition must begin PENDING' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_world_guard_canonical_initial_admission_hold + BEFORE INSERT OR UPDATE OR DELETE ON initial_admission_bind_hold + FOR EACH ROW EXECUTE FUNCTION world_guard_canonical_initial_admission_hold(); +REVOKE ALL ON FUNCTION world_guard_canonical_initial_admission_hold() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1021__canonical_initial_admission_hold_terminal.sql b/services/world-management-service/src/main/resources/db/migration/V1021__canonical_initial_admission_hold_terminal.sql new file mode 100644 index 0000000000..7623c17fe2 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1021__canonical_initial_admission_hold_terminal.sql @@ -0,0 +1,334 @@ +-- Typed terminal outcomes retain the complete authenticated Game Session proof separately from +-- the legacy bare digest columns. Retained V23 rows stay untyped and receive no inferred proof. +ALTER TABLE initial_admission_bind_hold + ADD COLUMN canonical_owner_proof_bytes BYTEA, + ADD COLUMN canonical_owner_proof_digest VARCHAR(71), + ADD CONSTRAINT ck_initial_admission_bind_canonical_owner_proof CHECK ( + ( + canonical_request_bytes IS NULL + AND canonical_owner_proof_bytes IS NULL + AND canonical_owner_proof_digest IS NULL + ) + OR + ( + canonical_request_bytes IS NOT NULL + AND ( + ( + status = 'PENDING' + AND canonical_owner_proof_bytes IS NULL + AND canonical_owner_proof_digest IS NULL + ) + OR + ( + status IN ('COMMITTED', 'ABORTED') + AND canonical_owner_proof_bytes IS NOT NULL + AND octet_length(canonical_owner_proof_bytes) > 0 + AND canonical_owner_proof_digest IS NOT NULL + AND canonical_owner_proof_digest COLLATE "C" ~ '^sha256:[0-9a-f]{64}$' + ) + ) + ) + ); + +-- This transaction-local, exact-row manifest is not owner proof and is never public storage. +CREATE TABLE world_canonical_initial_admission_hold_finalization_manifest ( + transaction_id BIGINT NOT NULL, + hold_id UUID NOT NULL, + hold_fence UUID NOT NULL, + expected_old JSONB NOT NULL, + expected_new JSONB NOT NULL, + PRIMARY KEY (transaction_id, hold_id) +); + +-- [jooq ignore start] +REVOKE ALL ON world_canonical_initial_admission_hold_finalization_manifest FROM PUBLIC; + +CREATE FUNCTION world_consume_canonical_initial_admission_hold_finalization_manifest( + actual_operation TEXT, + actual_old JSONB, + actual_new JSONB +) RETURNS BOOLEAN +LANGUAGE plpgsql SECURITY DEFINER +SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + consumed UUID; +BEGIN + IF actual_operation IS DISTINCT FROM 'UPDATE' + OR actual_old IS NULL + OR actual_new IS NULL + OR actual_old->>'status' IS DISTINCT FROM 'PENDING' + OR (actual_new->>'status' IS DISTINCT FROM 'COMMITTED' + AND actual_new->>'status' IS DISTINCT FROM 'ABORTED') THEN + RETURN FALSE; + END IF; + + DELETE FROM "${serviceSchema}".world_canonical_initial_admission_hold_finalization_manifest m + WHERE m.transaction_id = txid_current() + AND m.hold_id::TEXT = actual_old->>'hold_id' + AND m.hold_id::TEXT = actual_new->>'hold_id' + AND m.hold_fence::TEXT = actual_old->>'hold_fence' + AND m.hold_fence::TEXT = actual_new->>'hold_fence' + AND m.expected_old = actual_old + AND m.expected_new = actual_new + AND actual_old->>'canonical_request_bytes' IS NOT NULL + AND actual_new->>'canonical_request_bytes' = actual_old->>'canonical_request_bytes' + AND actual_new->>'hold_binding_digest' = actual_old->>'hold_binding_digest' + AND actual_new->>'canonical_owner_proof_bytes' IS NOT NULL + AND actual_new->>'canonical_owner_proof_digest' IS NOT NULL + RETURNING m.hold_id INTO consumed; + RETURN consumed IS NOT NULL; +END; +$$; +REVOKE ALL ON FUNCTION + world_consume_canonical_initial_admission_hold_finalization_manifest(TEXT, JSONB, JSONB) + FROM PUBLIC; + +CREATE FUNCTION world_finalize_canonical_initial_admission_hold( + p_hold_id UUID, + p_hold_fence UUID, + p_status TEXT, + p_owner_proof_id TEXT, + p_owner_proof_digest TEXT, + p_owner_pointer_audit_id TEXT, + p_owner_pointer_version BIGINT, + p_terminal_at TIMESTAMPTZ, + p_positive_durable_abort BOOLEAN, + p_canonical_owner_proof_bytes BYTEA, + p_canonical_owner_proof_digest TEXT +) RETURNS VOID +LANGUAGE plpgsql SECURITY DEFINER +SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + candidate "${serviceSchema}".initial_admission_bind_hold%ROWTYPE; + held "${serviceSchema}".initial_admission_bind_hold%ROWTYPE; + next_held "${serviceSchema}".initial_admission_bind_hold%ROWTYPE; + association_row "${serviceSchema}".world_canonical_instance_association%ROWTYPE; + instance_row "${serviceSchema}".world_instance%ROWTYPE; + updated_count INTEGER; +BEGIN + IF p_status NOT IN ('COMMITTED', 'ABORTED') + OR p_terminal_at IS NULL + OR p_canonical_owner_proof_bytes IS NULL + OR octet_length(p_canonical_owner_proof_bytes) = 0 + OR p_canonical_owner_proof_digest !~ '^sha256:[0-9a-f]{64}$' + OR p_canonical_owner_proof_digest IS DISTINCT FROM + ('sha256:' || encode(sha256(p_canonical_owner_proof_bytes), 'hex')) THEN + RAISE EXCEPTION 'Canonical initial-admission terminal proof is incomplete or has an invalid digest' + USING ERRCODE = '23514'; + END IF; + + -- Read the immutable selector without locking, then preserve acquisition order by locking + -- the actual World lifecycle row before the hold itself. + SELECT h.* INTO candidate + FROM "${serviceSchema}".initial_admission_bind_hold h + WHERE h.hold_id = p_hold_id; + IF NOT FOUND + OR candidate.hold_fence IS DISTINCT FROM p_hold_fence + OR candidate.canonical_request_bytes IS NULL THEN + RAISE EXCEPTION 'Canonical initial-admission hold identity is missing or untyped' + USING ERRCODE = '55000'; + END IF; + + SELECT a.* INTO association_row + FROM "${serviceSchema}".world_canonical_instance_association a + JOIN "${serviceSchema}".world_instance wi ON wi.id = a.world_instance_id + WHERE wi.tenant_id = candidate.tenant_id + AND wi.game_instance_id = candidate.game_instance_id + AND wi.version_id = candidate.version_id + AND a.local_tenant_key = candidate.tenant_id + AND a.private_game_instance_key = candidate.game_instance_id + AND a.local_version_key = candidate.version_id + AND a.canonical_target_namespace = candidate.canonical_target_namespace + AND a.canonical_tenant_id = candidate.canonical_tenant_id + AND a.canonical_world_slug = candidate.canonical_world_slug + AND a.canonical_game_instance_id = candidate.canonical_game_instance_id + AND a.canonical_version_id = candidate.canonical_version_id + AND a.playable_state_namespace_id = candidate.playable_state_namespace_uuid + AND a.playable_state_scope = candidate.playable_state_scope + FOR UPDATE OF wi; + IF NOT FOUND THEN + RAISE EXCEPTION 'Canonical initial-admission terminalization lacks its exact World association' + USING ERRCODE = '23514'; + END IF; + + -- Keep each composite result in one ROWTYPE target. The preceding query already holds + -- this actual lifecycle row; the second read retains that lock and its exact binding. + SELECT wi.* INTO instance_row + FROM "${serviceSchema}".world_instance wi + WHERE wi.id = association_row.world_instance_id + FOR UPDATE; + IF NOT FOUND + OR instance_row.canonical_game_instance_id IS DISTINCT FROM association_row.canonical_game_instance_id + OR instance_row.canonical_target_namespace IS DISTINCT FROM association_row.canonical_target_namespace + OR instance_row.canonical_tenant_id IS DISTINCT FROM association_row.canonical_tenant_id + OR instance_row.canonical_world_slug IS DISTINCT FROM association_row.canonical_world_slug + OR instance_row.playable_state_namespace_id IS DISTINCT FROM association_row.playable_state_namespace_id + OR instance_row.playable_state_scope IS DISTINCT FROM association_row.playable_state_scope + OR instance_row.status IS DISTINCT FROM 'ACTIVE' + OR instance_row.lifecycle_epoch IS DISTINCT FROM candidate.active_lifecycle_epoch THEN + RAISE EXCEPTION 'Canonical initial-admission terminalization lacks its exact ACTIVE World association epoch' + USING ERRCODE = '23514'; + END IF; + + SELECT h.* INTO held + FROM "${serviceSchema}".initial_admission_bind_hold h + WHERE h.hold_id = p_hold_id + FOR UPDATE; + IF NOT FOUND + OR held.hold_fence IS DISTINCT FROM candidate.hold_fence + OR held.tenant_id IS DISTINCT FROM candidate.tenant_id + OR held.realm_uuid IS DISTINCT FROM candidate.realm_uuid + OR held.playable_state_namespace_uuid IS DISTINCT FROM candidate.playable_state_namespace_uuid + OR held.playable_state_scope IS DISTINCT FROM candidate.playable_state_scope + OR held.game_instance_id IS DISTINCT FROM candidate.game_instance_id + OR held.version_id IS DISTINCT FROM candidate.version_id + OR held.active_lifecycle_epoch IS DISTINCT FROM candidate.active_lifecycle_epoch + OR held.initial_admission_request_id IS DISTINCT FROM candidate.initial_admission_request_id + OR held.request_digest IS DISTINCT FROM candidate.request_digest + OR held.expected_no_prior_pointer IS DISTINCT FROM candidate.expected_no_prior_pointer + OR held.expected_catalog_revision IS DISTINCT FROM candidate.expected_catalog_revision + OR held.canonical_target_namespace IS DISTINCT FROM candidate.canonical_target_namespace + OR held.canonical_tenant_id IS DISTINCT FROM candidate.canonical_tenant_id + OR held.canonical_world_slug IS DISTINCT FROM candidate.canonical_world_slug + OR held.canonical_game_instance_id IS DISTINCT FROM candidate.canonical_game_instance_id + OR held.canonical_version_id IS DISTINCT FROM candidate.canonical_version_id + OR held.initial_admission_origin IS DISTINCT FROM candidate.initial_admission_origin + OR held.expected_prior_pointer_version IS DISTINCT FROM candidate.expected_prior_pointer_version + OR held.canonical_request_bytes IS DISTINCT FROM candidate.canonical_request_bytes + OR held.hold_binding_digest IS DISTINCT FROM candidate.hold_binding_digest + OR held.status IS DISTINCT FROM 'PENDING' + OR held.canonical_owner_proof_bytes IS NOT NULL + OR held.canonical_owner_proof_digest IS NOT NULL + OR held.owner_proof_id IS NOT NULL + OR held.owner_proof_digest IS NOT NULL + OR held.owner_pointer_audit_id IS NOT NULL + OR held.owner_pointer_version IS NOT NULL + OR held.terminal_at IS NOT NULL + OR held.row_version = 9223372036854775807 THEN + RAISE EXCEPTION 'Canonical initial-admission hold is not the exact terminalizable PENDING row' + USING ERRCODE = '55000'; + END IF; + + IF p_owner_proof_id IS DISTINCT FROM held.initial_admission_request_id + OR p_owner_proof_digest !~ '^[0-9a-f]{64}$' + OR p_owner_proof_digest IS NULL THEN + RAISE EXCEPTION 'Canonical initial-admission owner proof differs from its original request identity' + USING ERRCODE = '23514'; + END IF; + + IF p_status = 'COMMITTED' THEN + IF p_positive_durable_abort IS DISTINCT FROM FALSE + OR p_owner_pointer_version IS NULL + OR p_owner_pointer_version <= 0 + OR p_owner_pointer_audit_id IS NULL + OR p_owner_pointer_audit_id !~ '^[1-9][0-9]*$' + OR p_owner_pointer_audit_id::NUMERIC > 9223372036854775807 THEN + RAISE EXCEPTION 'Committed canonical initial-admission proof has invalid pointer or audit evidence' + USING ERRCODE = '23514'; + END IF; + IF held.initial_admission_origin = 'NO_PRIOR_POINTER' THEN + IF p_owner_pointer_version IS DISTINCT FROM 1 THEN + RAISE EXCEPTION 'First canonical initial-admission pointer version must be one' + USING ERRCODE = '23514'; + END IF; + ELSIF held.initial_admission_origin = 'EXPECT_CLOSED' THEN + IF held.expected_prior_pointer_version = 9223372036854775807 + OR p_owner_pointer_version IS DISTINCT FROM held.expected_prior_pointer_version + 1 THEN + RAISE EXCEPTION 'Committed canonical initial-admission pointer is not the exact next version' + USING ERRCODE = '23514'; + END IF; + ELSE + RAISE EXCEPTION 'Canonical initial-admission origin is unsupported' + USING ERRCODE = '23514'; + END IF; + ELSE + IF p_positive_durable_abort IS DISTINCT FROM TRUE + OR p_owner_pointer_audit_id IS NOT NULL + OR p_owner_pointer_version IS NOT NULL THEN + RAISE EXCEPTION 'Aborted canonical initial-admission proof lacks positive durable fencing' + USING ERRCODE = '23514'; + END IF; + END IF; + + next_held := held; + next_held.status := p_status; + next_held.owner_proof_id := p_owner_proof_id; + next_held.owner_proof_digest := p_owner_proof_digest; + next_held.owner_pointer_audit_id := p_owner_pointer_audit_id; + next_held.owner_pointer_version := p_owner_pointer_version; + next_held.terminal_at := p_terminal_at AT TIME ZONE 'UTC'; + next_held.canonical_owner_proof_bytes := p_canonical_owner_proof_bytes; + next_held.canonical_owner_proof_digest := p_canonical_owner_proof_digest; + next_held.updated_at := CURRENT_TIMESTAMP; + next_held.row_version := held.row_version + 1; + + INSERT INTO "${serviceSchema}".world_canonical_initial_admission_hold_finalization_manifest + (transaction_id, hold_id, hold_fence, expected_old, expected_new) + VALUES (txid_current(), held.hold_id, held.hold_fence, to_jsonb(held), to_jsonb(next_held)); + + UPDATE "${serviceSchema}".initial_admission_bind_hold h + SET status = next_held.status, + owner_proof_id = next_held.owner_proof_id, + owner_proof_digest = next_held.owner_proof_digest, + owner_pointer_audit_id = next_held.owner_pointer_audit_id, + owner_pointer_version = next_held.owner_pointer_version, + terminal_at = next_held.terminal_at, + canonical_owner_proof_bytes = next_held.canonical_owner_proof_bytes, + canonical_owner_proof_digest = next_held.canonical_owner_proof_digest, + updated_at = next_held.updated_at, + row_version = next_held.row_version + WHERE h.hold_id = held.hold_id + AND h.hold_fence = held.hold_fence + AND h.status = 'PENDING' + AND h.row_version = held.row_version; + GET DIAGNOSTICS updated_count = ROW_COUNT; + IF updated_count <> 1 THEN + RAISE EXCEPTION 'Canonical initial-admission hold terminal compare-and-set did not update one row' + USING ERRCODE = '40001'; + END IF; +END; +$$; +REVOKE ALL ON FUNCTION world_finalize_canonical_initial_admission_hold( + UUID, UUID, TEXT, TEXT, TEXT, TEXT, BIGINT, TIMESTAMPTZ, BOOLEAN, BYTEA, TEXT +) FROM PUBLIC; + +-- Replace only V47's typed-update denial branch. Immutable acquisition checks and legacy +-- lifecycle behavior remain in the original trigger function definition. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ IF OLD.canonical_request_bytes IS NOT NULL + AND (OLD.status IS DISTINCT FROM NEW.status + OR OLD.owner_proof_id IS DISTINCT FROM NEW.owner_proof_id + OR OLD.owner_proof_digest IS DISTINCT FROM NEW.owner_proof_digest + OR OLD.owner_pointer_audit_id IS DISTINCT FROM NEW.owner_pointer_audit_id + OR OLD.owner_pointer_version IS DISTINCT FROM NEW.owner_pointer_version + OR OLD.terminal_at IS DISTINCT FROM NEW.terminal_at) THEN + RAISE EXCEPTION 'Canonical initial-admission hold requires its deferred typed owner outcome' + USING ERRCODE = '55000'; + END IF; + IF OLD.canonical_request_bytes IS NOT NULL THEN + RAISE EXCEPTION 'Canonical initial-admission hold lifecycle updates are not enabled' + USING ERRCODE = '55000'; + END IF;$anchor$; + replacement TEXT := $replacement$ IF OLD.canonical_request_bytes IS NOT NULL THEN + IF "${serviceSchema}".world_consume_canonical_initial_admission_hold_finalization_manifest( + TG_OP, to_jsonb(OLD), to_jsonb(NEW)) THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'Canonical initial-admission hold update lacks its exact one-use owner manifest' + USING ERRCODE = '55000'; + END IF;$replacement$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_guard_canonical_initial_admission_hold()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one canonical initial-admission typed update denial'; + END IF; + EXECUTE replace(original, anchor, replacement); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1022__canonical_initial_player_location_typed_hold.sql b/services/world-management-service/src/main/resources/db/migration/V1022__canonical_initial_player_location_typed_hold.sql new file mode 100644 index 0000000000..ea91a79df5 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1022__canonical_initial_player_location_typed_hold.sql @@ -0,0 +1,146 @@ +-- Forward alignment of the existing location guard to complete typed first-open outcomes. +-- Retained legacy holds are not promoted or accepted as canonical placement proof. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION world_guard_initial_character_location() +RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER +SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + operation_row "${serviceSchema}".world_canonical_initial_player_location_operation%ROWTYPE; + request JSONB; + lifecycle JSONB; +BEGIN + IF TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Initial placement is immutable; a separate World movement owner must be implemented' USING ERRCODE = '55000'; + END IF; + IF TG_OP <> 'INSERT' THEN RETURN NEW; END IF; + + SELECT * INTO STRICT operation_row + FROM "${serviceSchema}".world_canonical_initial_player_location_operation + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND playable_state_namespace_id = NEW.playable_state_namespace_id + AND canonical_game_instance_id = NEW.canonical_game_instance_id + AND operation_id = NEW.initial_location_operation_id; + request := convert_from(operation_row.request_bytes, 'UTF8')::JSONB; + lifecycle := convert_from(NEW.initial_lifecycle_evidence_bytes, 'UTF8')::JSONB; + + IF operation_row.outcome IS DISTINCT FROM 'APPLIED' + OR operation_row.request_digest IS DISTINCT FROM NEW.initial_location_request_digest + OR request->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR request->>'playableStateNamespaceId' IS DISTINCT FROM NEW.playable_state_namespace_id::TEXT + OR request->>'canonicalGameInstanceId' IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR request->>'playableStateScope' IS DISTINCT FROM NEW.playable_state_scope + OR request->>'canonicalAccountId' IS DISTINCT FROM NEW.canonical_account_id::TEXT + OR request->>'characterId' IS DISTINCT FROM NEW.character_id::TEXT + OR request->>'entityAssignmentOperationId' IS DISTINCT FROM NEW.entity_assignment_operation_id::TEXT + OR request->>'entityAssignmentDigest' IS DISTINCT FROM NEW.entity_assignment_digest + OR request->>'realmId' IS DISTINCT FROM NEW.realm_id::TEXT + OR request->>'worldSlug' IS DISTINCT FROM NEW.world_slug + OR request->>'initialAdmissionHoldId' IS DISTINCT FROM NEW.initial_admission_hold_id::TEXT + OR request->>'initialAdmissionHoldFence' IS DISTINCT FROM NEW.initial_admission_hold_fence::TEXT + OR request->>'initialAdmissionOrigin' IS NULL + OR request->>'initialAdmissionOrigin' NOT IN ('NO_PRIOR_POINTER', 'EXPECT_CLOSED') + OR request->>'initialAdmissionRequestId' IS DISTINCT FROM NEW.initial_admission_request_id + OR request->>'initialAdmissionRequestDigest' IS DISTINCT FROM NEW.initial_admission_request_digest + OR request->>'initialAdmissionOwnerProofId' IS DISTINCT FROM NEW.initial_admission_owner_proof_id + OR request->>'initialAdmissionOwnerProofDigest' IS DISTINCT FROM NEW.initial_admission_owner_proof_digest + OR request->>'pointerAuditId' IS DISTINCT FROM NEW.pointer_audit_id + OR request->>'pointerVersion' IS DISTINCT FROM NEW.pointer_version::TEXT + OR request->>'catalogRevision' IS DISTINCT FROM NEW.catalog_revision::TEXT + OR request->'activeLifecycleEvidence' IS NULL + OR (request->'activeLifecycleEvidence' #- '{request,readRequestId}') + IS DISTINCT FROM (lifecycle #- '{request,readRequestId}') + OR NEW.initial_lifecycle_evidence_digest IS DISTINCT FROM ('sha256:' || encode(sha256(NEW.initial_lifecycle_evidence_bytes), 'hex')) + OR lifecycle->>'schema' IS DISTINCT FROM 'world-canonical-instance-lifecycle-evidence/v1' + OR lifecycle->>'lifecycleStatus' IS DISTINCT FROM 'ACTIVE' + OR lifecycle->>'lifecycleEpoch' IS DISTINCT FROM NEW.active_lifecycle_epoch::TEXT + OR lifecycle->'request'->>'canonicalGameInstanceId' IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR lifecycle->'request'->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR lifecycle->'request'->>'playableStateNamespaceId' IS DISTINCT FROM NEW.playable_state_namespace_id::TEXT + OR lifecycle->'request'->>'playableStateScope' IS DISTINCT FROM NEW.playable_state_scope + OR lifecycle->'startLocation'->>'tenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR lifecycle->'startLocation'->>'versionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR lifecycle->'startLocation'->>'roomTemplateId' IS DISTINCT FROM NEW.initial_room_template_id::TEXT + OR lifecycle->>'runtimeRoomInstanceId' IS DISTINCT FROM NEW.initial_runtime_room_instance_id::TEXT + OR NEW.runtime_room_instance_id IS DISTINCT FROM NEW.initial_runtime_room_instance_id THEN + RAISE EXCEPTION 'World initial placement differs from its retained operation or lifecycle proof' USING ERRCODE = '23514'; + END IF; + + IF NOT EXISTS ( + SELECT 1 + FROM "${serviceSchema}".world_canonical_instance_association a + JOIN "${serviceSchema}".world_instance w ON w.id = a.world_instance_id + JOIN "${serviceSchema}".world_canonical_preparation_start_location s + ON s.canonical_game_instance_id = a.canonical_game_instance_id + AND s.world_instance_id = a.world_instance_id + JOIN "${serviceSchema}".world_canonical_instance_topology_identity m + ON m.world_instance_id = a.world_instance_id + AND m.canonical_game_instance_id = a.canonical_game_instance_id + AND m.family = 'ROOM' AND m.template_id = s.room_template_id + AND m.runtime_room_instance_id = s.runtime_room_instance_id + JOIN "${serviceSchema}".room_instance r + ON r.id = m.runtime_row_id AND r.room_instance_row_id = s.runtime_room_instance_id + JOIN "${serviceSchema}".initial_admission_bind_hold h + ON h.hold_id = NEW.initial_admission_hold_id + WHERE a.canonical_game_instance_id = NEW.canonical_game_instance_id + AND a.world_instance_id = NEW.world_instance_id + AND a.canonical_tenant_id = NEW.canonical_tenant_id + AND a.canonical_world_slug = NEW.world_slug + AND a.playable_state_namespace_id = NEW.playable_state_namespace_id + AND a.playable_state_scope = NEW.playable_state_scope + AND a.canonical_version_id = NEW.canonical_version_id + AND w.canonical_game_instance_id = a.canonical_game_instance_id + AND w.canonical_tenant_id = NEW.canonical_tenant_id + AND w.canonical_world_slug = NEW.world_slug + AND w.playable_state_namespace_id = NEW.playable_state_namespace_id + AND w.playable_state_scope = NEW.playable_state_scope + AND w.status = 'ACTIVE' AND w.lifecycle_epoch = NEW.active_lifecycle_epoch + AND s.canonical_tenant_id = NEW.canonical_tenant_id + AND s.canonical_version_id = NEW.canonical_version_id + AND s.room_template_id = NEW.initial_room_template_id + AND s.runtime_room_instance_id = NEW.initial_runtime_room_instance_id + AND r.tenant_id = w.tenant_id AND r.game_instance_id = w.game_instance_id + AND h.tenant_id = w.tenant_id AND h.game_instance_id = w.game_instance_id + AND h.realm_uuid = NEW.realm_id + AND h.playable_state_namespace_uuid = NEW.playable_state_namespace_id + AND h.playable_state_scope = NEW.playable_state_scope + AND h.version_id = w.version_id AND h.active_lifecycle_epoch = w.lifecycle_epoch + AND h.status = 'COMMITTED' + AND h.canonical_target_namespace = a.canonical_target_namespace + AND h.canonical_tenant_id = NEW.canonical_tenant_id + AND h.canonical_world_slug = NEW.world_slug + AND h.canonical_game_instance_id = NEW.canonical_game_instance_id + AND h.canonical_version_id = NEW.canonical_version_id + AND h.canonical_request_bytes IS NOT NULL + AND h.hold_binding_digest = ('sha256:' || encode(sha256(h.canonical_request_bytes), 'hex')) + AND h.canonical_owner_proof_bytes IS NOT NULL + AND h.canonical_owner_proof_digest = ('sha256:' || encode(sha256(h.canonical_owner_proof_bytes), 'hex')) + AND h.initial_admission_origin = request->>'initialAdmissionOrigin' + AND ( + (h.initial_admission_origin = 'NO_PRIOR_POINTER' + AND h.expected_no_prior_pointer IS TRUE + AND h.expected_prior_pointer_version IS NULL + AND h.owner_pointer_version = 1) + OR + (h.initial_admission_origin = 'EXPECT_CLOSED' + AND h.expected_no_prior_pointer IS FALSE + AND h.expected_prior_pointer_version IS NOT NULL + AND h.expected_prior_pointer_version < 9223372036854775807 + AND h.owner_pointer_version = h.expected_prior_pointer_version + 1) + ) + AND h.initial_admission_request_id = NEW.initial_admission_request_id + AND h.request_digest = NEW.initial_admission_request_digest + AND h.expected_catalog_revision = NEW.catalog_revision + AND h.owner_proof_id = NEW.initial_admission_owner_proof_id + AND h.owner_proof_digest = NEW.initial_admission_owner_proof_digest + AND h.owner_pointer_audit_id = NEW.pointer_audit_id + AND h.owner_pointer_version = NEW.pointer_version + AND h.hold_fence = NEW.initial_admission_hold_fence + ) THEN + RAISE EXCEPTION 'World initial location lacks exact current association, V2 ROOM mapping, or committed first-open proof' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +REVOKE ALL ON FUNCTION world_guard_initial_character_location() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1023__canonical_initial_location_operation_origins.sql b/services/world-management-service/src/main/resources/db/migration/V1023__canonical_initial_location_operation_origins.sql new file mode 100644 index 0000000000..c3c8d0bfb7 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1023__canonical_initial_location_operation_origins.sql @@ -0,0 +1,148 @@ +-- Forward-align the placement operation guard with the two tagged first-open origins. +-- V46 and V49 remain unchanged; the typed hold and owner-proof checks stay in the V49 location guard. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION world_guard_initial_location_operation() +RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER +SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + request JSONB; + result JSONB; + canonical_result BYTEA; + canonical_room TEXT; + canonical_conflict_code TEXT; + canonical_runtime_room TEXT; + request_base64 TEXT; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'World initial-location operation evidence is immutable' USING ERRCODE = '55000'; + END IF; + IF NEW.request_digest IS DISTINCT FROM ('sha256:' || encode(sha256(NEW.request_bytes), 'hex')) + OR NEW.result_digest IS DISTINCT FROM ('sha256:' || encode(sha256(NEW.result_bytes), 'hex')) THEN + RAISE EXCEPTION 'World initial-location operation digests do not match retained bytes' USING ERRCODE = '23514'; + END IF; + request := convert_from(NEW.request_bytes, 'UTF8')::JSONB; + result := convert_from(NEW.result_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(request) IS DISTINCT FROM 'object' + OR request->>'schema' IS DISTINCT FROM 'world-canonical-initial-player-location-request/v1' + OR request->>'operationId' IS DISTINCT FROM NEW.operation_id::TEXT + OR request->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR request->>'playableStateNamespaceId' IS DISTINCT FROM NEW.playable_state_namespace_id::TEXT + OR request->>'canonicalGameInstanceId' IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR request->>'initialAdmissionOrigin' IS NULL + OR request->>'initialAdmissionOrigin' NOT IN ('NO_PRIOR_POINTER', 'EXPECT_CLOSED') + OR jsonb_typeof(request->'activeLifecycleEvidence') IS DISTINCT FROM 'object' + OR (convert_from(NEW.original_lifecycle_evidence_bytes, 'UTF8')::JSONB #- '{request,readRequestId}') + IS DISTINCT FROM (request->'activeLifecycleEvidence' #- '{request,readRequestId}') + THEN + RAISE EXCEPTION 'World initial-location operation differs from its canonical request/result' USING ERRCODE = '23514'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_canonical_instance_association a + WHERE a.canonical_game_instance_id = NEW.canonical_game_instance_id + AND a.world_instance_id = NEW.world_instance_id + AND a.canonical_tenant_id = NEW.canonical_tenant_id + AND a.playable_state_namespace_id = NEW.playable_state_namespace_id + ) THEN + RAISE EXCEPTION 'World initial-location operation differs from its canonical association' USING ERRCODE = '23514'; + END IF; + + IF jsonb_typeof(result) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'World initial-location result must be a closed canonical object' USING ERRCODE = '23514'; + END IF; + IF (SELECT count(*) FROM jsonb_object_keys(result)) <> 8 + OR NOT (result ?& ARRAY[ + 'conflictCode', 'operationId', 'outcome', 'requestBytesBase64', + 'requestDigest', 'runtimeRoomInstanceId', 'schema', 'startLocation' + ]) THEN + RAISE EXCEPTION 'World initial-location result must have exactly eight fields' USING ERRCODE = '23514'; + END IF; + IF jsonb_typeof(result->'schema') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'operationId') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'requestDigest') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'requestBytesBase64') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'outcome') IS DISTINCT FROM 'string' + OR result->>'schema' IS DISTINCT FROM 'world-canonical-initial-player-location-result/v1' + OR result->>'operationId' IS DISTINCT FROM NEW.operation_id::TEXT + OR result->>'requestDigest' IS DISTINCT FROM NEW.request_digest + OR result->>'outcome' IS DISTINCT FROM NEW.outcome THEN + RAISE EXCEPTION 'World initial-location operation differs from its canonical result identity' USING ERRCODE = '23514'; + END IF; + + request_base64 := replace(replace(encode(NEW.request_bytes, 'base64'), E'\n', ''), E'\r', ''); + IF result->>'requestBytesBase64' IS DISTINCT FROM request_base64 + OR decode(result->>'requestBytesBase64', 'base64') IS DISTINCT FROM NEW.request_bytes THEN + RAISE EXCEPTION 'World initial-location result request bytes differ from its operation' USING ERRCODE = '23514'; + END IF; + + IF NEW.outcome = 'APPLIED' THEN + IF jsonb_typeof(result->'conflictCode') IS DISTINCT FROM 'null' + OR jsonb_typeof(result->'runtimeRoomInstanceId') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'startLocation') IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'Applied World initial-location result has an invalid field shape' USING ERRCODE = '23514'; + END IF; + IF (SELECT count(*) FROM jsonb_object_keys(result->'startLocation')) <> 3 + OR NOT ((result->'startLocation') ?& ARRAY['roomTemplateId', 'tenantId', 'versionId']) + OR jsonb_typeof(result->'startLocation'->'roomTemplateId') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'startLocation'->'tenantId') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'startLocation'->'versionId') IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Applied World initial-location result room must have exactly three string fields' USING ERRCODE = '23514'; + END IF; + IF (result->'startLocation'->>'roomTemplateId') !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (result->'startLocation'->>'tenantId') !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (result->'startLocation'->>'versionId') !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (result->'startLocation'->>'roomTemplateId') = '00000000-0000-0000-0000-000000000000' + OR (result->'startLocation'->>'tenantId') = '00000000-0000-0000-0000-000000000000' + OR (result->'startLocation'->>'versionId') = '00000000-0000-0000-0000-000000000000' + OR (result->>'runtimeRoomInstanceId') !~ '^[1-9][0-9]*$' THEN + RAISE EXCEPTION 'Applied World initial-location result contains a noncanonical room identity' USING ERRCODE = '23514'; + END IF; + IF (result->>'runtimeRoomInstanceId')::NUMERIC > 9223372036854775807 THEN + RAISE EXCEPTION 'Applied World initial-location runtime room id exceeds signed 64-bit range' USING ERRCODE = '23514'; + END IF; + IF (result->'startLocation') IS DISTINCT FROM + (request->'activeLifecycleEvidence'->'startLocation') + OR result->>'runtimeRoomInstanceId' IS DISTINCT FROM + request->'activeLifecycleEvidence'->>'runtimeRoomInstanceId' THEN + RAISE EXCEPTION 'Applied World initial-location result differs from the exact V2 ROOM mapping' USING ERRCODE = '23514'; + END IF; + canonical_room := + '{"roomTemplateId":' || to_jsonb(result->'startLocation'->>'roomTemplateId')::TEXT + || ',"tenantId":' || to_jsonb(result->'startLocation'->>'tenantId')::TEXT + || ',"versionId":' || to_jsonb(result->'startLocation'->>'versionId')::TEXT || '}'; + canonical_conflict_code := 'null'; + canonical_runtime_room := to_jsonb(result->>'runtimeRoomInstanceId')::TEXT; + ELSE + IF jsonb_typeof(result->'conflictCode') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'runtimeRoomInstanceId') IS DISTINCT FROM 'null' + OR jsonb_typeof(result->'startLocation') IS DISTINCT FROM 'null' + OR result->>'conflictCode' IS DISTINCT FROM NEW.conflict_code THEN + RAISE EXCEPTION 'Conflicting World initial-location result has an invalid field shape' USING ERRCODE = '23514'; + END IF; + IF (result->>'conflictCode') COLLATE "C" !~ '^[A-Z][A-Z0-9_]{0,63}$' + OR (result->>'conflictCode') COLLATE "C" ~ '[^A-Z0-9_]' THEN + RAISE EXCEPTION 'Conflicting World initial-location result has an invalid machine code' USING ERRCODE = '23514'; + END IF; + canonical_room := 'null'; + canonical_conflict_code := to_jsonb(result->>'conflictCode')::TEXT; + canonical_runtime_room := 'null'; + END IF; + + canonical_result := convert_to( + '{"conflictCode":' || canonical_conflict_code + || ',"operationId":' || to_jsonb(NEW.operation_id::TEXT)::TEXT + || ',"outcome":' || to_jsonb(NEW.outcome)::TEXT + || ',"requestBytesBase64":' || to_jsonb(request_base64)::TEXT + || ',"requestDigest":' || to_jsonb(NEW.request_digest)::TEXT + || ',"runtimeRoomInstanceId":' || canonical_runtime_room + || ',"schema":"world-canonical-initial-player-location-result/v1"' + || ',"startLocation":' || canonical_room || '}', + 'UTF8'); + IF NEW.result_bytes IS DISTINCT FROM canonical_result THEN + RAISE EXCEPTION 'World initial-location result bytes are not canonical' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +REVOKE ALL ON FUNCTION world_guard_initial_location_operation() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1024__world_canonical_player_admission_hold.sql b/services/world-management-service/src/main/resources/db/migration/V1024__world_canonical_player_admission_hold.sql new file mode 100644 index 0000000000..515121ac2a --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1024__world_canonical_player_admission_hold.sql @@ -0,0 +1,241 @@ +-- Player admission is distinct from initial-pointer opening. No release producer exists yet: +-- every retained row stays HELD, even after its diagnostic lease deadline. +CREATE TABLE world_canonical_player_admission_hold ( + hold_id UUID PRIMARY KEY, + hold_fence UUID NOT NULL UNIQUE, + lease_id UUID NOT NULL UNIQUE, + attempt_id UUID NOT NULL UNIQUE, + lease_sha256 VARCHAR(64) NOT NULL CHECK (lease_sha256 ~ '^[0-9a-f]{64}$'), + lease_bytes BYTEA NOT NULL CHECK (octet_length(lease_bytes) BETWEEN 1 AND 65536), + canonical_game_instance_id UUID NOT NULL + REFERENCES world_canonical_instance_association(canonical_game_instance_id) ON DELETE RESTRICT, + world_instance_id BIGINT NOT NULL REFERENCES world_instance(id) ON DELETE RESTRICT, + active_lifecycle_epoch BIGINT NOT NULL CHECK (active_lifecycle_epoch > 0), + active_row_version BIGINT NOT NULL CHECK (active_row_version >= 0), + world_evidence_bytes BYTEA NOT NULL CHECK (octet_length(world_evidence_bytes) > 0), + diagnostic_expires_at_millis BIGINT NOT NULL CHECK (diagnostic_expires_at_millis > 0), + hold_state VARCHAR(16) NOT NULL DEFAULT 'HELD' CHECK (hold_state = 'HELD'), + -- Future terminalization must retain both exact independently authenticated owner results. + -- NULL means missing proof, never definitive absence. This migration authorizes neither. + account_terminal_evidence_bytes BYTEA CHECK (account_terminal_evidence_bytes IS NULL), + game_session_completion_evidence_bytes BYTEA CHECK (game_session_completion_evidence_bytes IS NULL), + acquisition_transaction_id BIGINT NOT NULL DEFAULT txid_current(), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); +CREATE INDEX idx_world_player_admission_hold_lifecycle + ON world_canonical_player_admission_hold(world_instance_id, hold_state); + +-- [jooq ignore start] +REVOKE ALL ON world_canonical_player_admission_hold FROM PUBLIC; + +CREATE FUNCTION world_validate_player_admission_hold() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + instance "${serviceSchema}".world_instance%ROWTYPE; + association "${serviceSchema}".world_canonical_instance_association%ROWTYPE; + preparation "${serviceSchema}".world_canonical_instance_preparation%ROWTYPE; + lease JSONB; + scope JSONB; + evidence JSONB; + selector JSONB; + evaluated BIGINT; + deadline BIGINT; + now_millis BIGINT; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'World player-admission hold is retained; authenticated dual-owner release is unavailable' + USING ERRCODE = '55000'; + END IF; + IF current_setting('transaction_isolation') <> 'read committed' + OR current_setting('transaction_read_only') <> 'off' + OR NEW.acquisition_transaction_id IS DISTINCT FROM txid_current() THEN + RAISE EXCEPTION 'World player-admission hold requires its writable READ COMMITTED owner transaction' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO instance FROM "${serviceSchema}".world_instance + WHERE id = NEW.world_instance_id FOR UPDATE; + IF NOT FOUND OR instance.status IS DISTINCT FROM 'ACTIVE' + OR instance.canonical_game_instance_id IS DISTINCT FROM NEW.canonical_game_instance_id + OR instance.lifecycle_epoch IS DISTINCT FROM NEW.active_lifecycle_epoch + OR instance.row_version IS DISTINCT FROM NEW.active_row_version THEN + RAISE EXCEPTION 'World player-admission hold requires the exact current ACTIVE lifecycle tuple' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO association FROM "${serviceSchema}".world_canonical_instance_association + WHERE canonical_game_instance_id = NEW.canonical_game_instance_id; + IF NOT FOUND OR association.world_instance_id IS DISTINCT FROM instance.id + OR association.local_tenant_key IS DISTINCT FROM instance.tenant_id + OR association.private_game_instance_key IS DISTINCT FROM instance.game_instance_id + OR association.canonical_tenant_id IS DISTINCT FROM instance.canonical_tenant_id + OR association.canonical_target_namespace IS DISTINCT FROM instance.canonical_target_namespace + OR association.canonical_world_slug IS DISTINCT FROM instance.canonical_world_slug + OR association.playable_state_namespace_id IS DISTINCT FROM instance.playable_state_namespace_id + OR association.playable_state_scope IS DISTINCT FROM instance.playable_state_scope + OR association.public_production IS DISTINCT FROM TRUE THEN + RAISE EXCEPTION 'World player-admission hold has no exact canonical owner association' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO preparation FROM "${serviceSchema}".world_canonical_instance_preparation + WHERE canonical_game_instance_id = NEW.canonical_game_instance_id; + IF NOT FOUND OR preparation.world_instance_id IS DISTINCT FROM instance.id + OR preparation.storage_status IS DISTINCT FROM 'MATERIALIZED_UNVERIFIED' + OR preparation.graph_sha256 IS DISTINCT FROM encode(sha256(preparation.graph_bytes), 'hex') + OR preparation.input_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(convert_to(preparation.input_json,'UTF8')), 'hex') THEN + RAISE EXCEPTION 'World player-admission hold requires retained canonical materialization' + USING ERRCODE = '23514'; + END IF; + lease := convert_from(NEW.lease_bytes, 'UTF8')::JSONB; + scope := lease->'bindingScope'; + evidence := convert_from(NEW.world_evidence_bytes, 'UTF8')::JSONB; + selector := evidence->'request'; + evaluated := (lease->>'evaluatedAt')::BIGINT; + deadline := (lease->>'expiresAt')::BIGINT; + now_millis := floor(extract(epoch FROM clock_timestamp()) * 1000)::BIGINT; + IF lease->>'schema' IS DISTINCT FROM 'account-gameplay-admission-lease-evidence/v1' + OR lease->>'schemaVersion' IS DISTINCT FROM '1' + OR lease->>'mode' IS DISTINCT FROM 'PUBLIC_PRODUCTION' + OR lease->>'targetNamespace' IS DISTINCT FROM association.canonical_target_namespace + OR lease->>'callerWorkload' IS DISTINCT FROM + 'spiffe://firemud/ns/' || association.canonical_target_namespace || '/sa/game-session-service' + OR lease->>'leaseId' IS DISTINCT FROM NEW.lease_id::TEXT + OR lease->>'requestId' IS DISTINCT FROM NEW.attempt_id::TEXT + OR NEW.lease_sha256 IS DISTINCT FROM encode(sha256(NEW.lease_bytes), 'hex') + OR lease->'membershipBaseline'->>'membershipLifecycleState' IS DISTINCT FROM 'ACTIVE' + OR evaluated IS NULL OR deadline IS NULL OR evaluated <= 0 + OR evaluated > now_millis OR deadline <= now_millis + OR deadline <= evaluated OR deadline - evaluated > 15000 + OR NEW.diagnostic_expires_at_millis IS DISTINCT FROM deadline + OR scope->>'tenantId' IS DISTINCT FROM association.canonical_tenant_id::TEXT + OR scope->>'worldSlug' IS DISTINCT FROM association.canonical_world_slug + OR scope->>'gameInstanceId' IS DISTINCT FROM association.canonical_game_instance_id::TEXT + OR scope->>'playableStateNamespaceId' IS DISTINCT FROM association.playable_state_namespace_id::TEXT + OR scope->>'playableStateScope' IS DISTINCT FROM association.playable_state_scope + OR evidence->>'schema' IS DISTINCT FROM 'world-canonical-instance-lifecycle-evidence/v1' + OR evidence->>'lifecycleStatus' IS DISTINCT FROM 'ACTIVE' + OR evidence->>'lifecycleEpoch' IS DISTINCT FROM instance.lifecycle_epoch::TEXT + OR evidence->>'rowVersion' IS DISTINCT FROM instance.row_version::TEXT + OR evidence->>'captureId' IS DISTINCT FROM preparation.capture_id::TEXT + OR evidence->>'graphSha256' IS DISTINCT FROM preparation.graph_sha256 + OR evidence->>'preparationInputDigest' IS DISTINCT FROM preparation.input_digest + OR selector->>'schemaVersion' IS DISTINCT FROM '1' + OR selector->>'readRequestId' IS DISTINCT FROM NEW.attempt_id::TEXT + OR selector->>'targetNamespace' IS DISTINCT FROM association.canonical_target_namespace + OR selector->>'canonicalTenantId' IS DISTINCT FROM association.canonical_tenant_id::TEXT + OR selector->>'worldSlug' IS DISTINCT FROM association.canonical_world_slug + OR selector->>'canonicalGameInstanceId' IS DISTINCT FROM association.canonical_game_instance_id::TEXT + OR selector->>'playableStateNamespaceId' IS DISTINCT FROM association.playable_state_namespace_id::TEXT + OR selector->>'playableStateScope' IS DISTINCT FROM association.playable_state_scope + OR selector->'publicProduction' IS DISTINCT FROM 'true'::JSONB + OR selector->>'controlPlaneRequestId' IS DISTINCT FROM association.control_plane_request_id + OR selector->>'canonicalVersionId' IS DISTINCT FROM association.canonical_version_id::TEXT + OR selector->>'expectedDescriptorRequestDigest' IS DISTINCT FROM association.descriptor_request_digest + OR selector->>'expectedDescriptorResultDigest' IS DISTINCT FROM association.descriptor_result_digest + OR selector->>'expectedReleaseAttestationDigest' IS DISTINCT FROM association.release_attestation_digest THEN + RAISE EXCEPTION 'World player-admission hold differs from the original lease or exact owner evidence' + USING ERRCODE = '23514'; + END IF; + IF NEW.hold_id::TEXT !~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + OR NEW.hold_fence::TEXT !~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' THEN + RAISE EXCEPTION 'World player-admission hold requires opaque identities' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +REVOKE ALL ON FUNCTION world_validate_player_admission_hold() FROM PUBLIC; +CREATE TRIGGER trg_world_player_admission_hold_retained + BEFORE INSERT OR UPDATE OR DELETE ON world_canonical_player_admission_hold + FOR EACH ROW EXECUTE FUNCTION world_validate_player_admission_hold(); + +CREATE FUNCTION world_reject_player_admission_hold_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + RAISE EXCEPTION 'World player-admission holds and original evidence are retained' USING ERRCODE='55000'; +END; +$$; +REVOKE ALL ON FUNCTION world_reject_player_admission_hold_truncate() FROM PUBLIC; +CREATE TRIGGER trg_world_player_admission_hold_no_truncate + BEFORE TRUNCATE ON world_canonical_player_admission_hold + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_player_admission_hold_truncate(); + +-- Preserve V35 and all subsequent exact execution-manifest extensions. The one exception is an +-- exact same-value World row UPDATE in the transaction that inserted this bound ACTIVE hold. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ RAISE EXCEPTION + 'World tenant key is reserved for a canonical authored source; no exact transaction execution manifest'$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_claim_legacy_numeric_tenant_key()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,anchor,'')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one reserved-tenant execution denial guard'; + END IF; + original := replace(original,anchor,$replacement$ IF TG_TABLE_SCHEMA = '${serviceSchema}' AND TG_TABLE_NAME = 'world_instance' + AND TG_OP = 'UPDATE' AND old_row = new_row + AND old_row->>'status' = 'ACTIVE' + AND EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_player_admission_hold h + WHERE h.world_instance_id = (old_row->>'id')::BIGINT + AND h.canonical_game_instance_id::TEXT = old_row->>'canonical_game_instance_id' + AND h.active_lifecycle_epoch = (old_row->>'lifecycle_epoch')::BIGINT + AND h.active_row_version = (old_row->>'row_version')::BIGINT + AND h.hold_state = 'HELD' AND h.acquisition_transaction_id = txid_current()) THEN + RETURN NEW; + END IF; +$replacement$ || anchor); + EXECUTE original; +END; +$migration$; + +CREATE FUNCTION world_version_player_admission_lifecycle_tuple() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + -- FOR UPDATE alone cannot refresh an older REPEATABLE READ/SERIALIZABLE snapshot. This exact + -- no-op UPDATE makes its later lifecycle UPDATE fail serialization rather than miss the hold. + UPDATE "${serviceSchema}".world_instance SET row_version = row_version + WHERE id = NEW.world_instance_id AND canonical_game_instance_id = NEW.canonical_game_instance_id + AND status = 'ACTIVE' AND lifecycle_epoch = NEW.active_lifecycle_epoch + AND row_version = NEW.active_row_version; + IF NOT FOUND THEN + RAISE EXCEPTION 'World player-admission hold lost its exact ACTIVE tuple' USING ERRCODE='23514'; + END IF; + RETURN NULL; +END; +$$; +REVOKE ALL ON FUNCTION world_version_player_admission_lifecycle_tuple() FROM PUBLIC; +CREATE TRIGGER trg_world_player_admission_hold_tuple_version + AFTER INSERT ON world_canonical_player_admission_hold + FOR EACH ROW EXECUTE FUNCTION world_version_player_admission_lifecycle_tuple(); + +CREATE FUNCTION world_guard_player_admission_lifecycle() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + -- UPDATE/DELETE owns the same tuple lock used by hold creation. For old MVCC snapshots the + -- hold's tuple UPDATE supplies PostgreSQL's serialization error before a stale change commits. + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_player_admission_hold h + WHERE h.world_instance_id = OLD.id AND h.hold_state = 'HELD') THEN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'World lifecycle is fenced by a retained player-admission hold' USING ERRCODE='23514'; + END IF; + IF to_jsonb(OLD) IS DISTINCT FROM to_jsonb(NEW) THEN + RAISE EXCEPTION 'World lifecycle is fenced by a retained player-admission hold' USING ERRCODE='23514'; + END IF; + END IF; + IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; + RETURN NEW; +END; +$$; +REVOKE ALL ON FUNCTION world_guard_player_admission_lifecycle() FROM PUBLIC; +CREATE TRIGGER aaa_world_player_admission_lifecycle + BEFORE UPDATE OR DELETE ON world_instance + FOR EACH ROW EXECUTE FUNCTION world_guard_player_admission_lifecycle(); +-- Existing V34's unconditional World instance TRUNCATE guard remains in force. +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1025__canonical_activation_complete_region_evidence.sql b/services/world-management-service/src/main/resources/db/migration/V1025__canonical_activation_complete_region_evidence.sql new file mode 100644 index 0000000000..1b93267ce6 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1025__canonical_activation_complete_region_evidence.sql @@ -0,0 +1,108 @@ +-- Extend V43's canonical activation proof to retain and validate the complete operational REGION +-- assignment map added to WorldCanonicalInstanceLifecycleEvidence. +-- [jooq ignore start] +DO $migration$ +DECLARE + definition TEXT; + original_oid OID; + original_acl ACLITEM[]; + old_fragment TEXT; + new_fragment TEXT; + anchor TEXT; + replacement TEXT; +BEGIN + SELECT p.oid, p.proacl + INTO STRICT original_oid, original_acl + FROM pg_proc p + WHERE p.oid = '"${serviceSchema}".world_validate_canonical_activation_operation()'::REGPROCEDURE; + SELECT pg_get_functiondef( + '"${serviceSchema}".world_validate_canonical_activation_operation()'::REGPROCEDURE) + INTO STRICT definition; + + old_fragment := '(SELECT count(*) FROM jsonb_object_keys(preparing)) <> 11'; + new_fragment := '(SELECT count(*) FROM jsonb_object_keys(preparing)) <> 12'; + IF (length(definition)-length(replace(definition, old_fragment, '')))/length(old_fragment) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one closed PREPARING lifecycle object count in V43 activation guard'; + END IF; + definition := replace(definition, old_fragment, new_fragment); + + old_fragment := '(SELECT count(*) FROM jsonb_object_keys(normalized_request->''preparingEvidence'')) <> 11'; + new_fragment := '(SELECT count(*) FROM jsonb_object_keys(normalized_request->''preparingEvidence'')) <> 12'; + IF (length(definition)-length(replace(definition, old_fragment, '')))/length(old_fragment) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one closed normalized PREPARING lifecycle object count in V43 activation guard'; + END IF; + definition := replace(definition, old_fragment, new_fragment); + + old_fragment := '(SELECT count(*) FROM jsonb_object_keys(lifecycle)) <> 11'; + new_fragment := '(SELECT count(*) FROM jsonb_object_keys(lifecycle)) <> 12'; + IF (length(definition)-length(replace(definition, old_fragment, '')))/length(old_fragment) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one closed result lifecycle object count in V43 activation guard'; + END IF; + definition := replace(definition, old_fragment, new_fragment); + + anchor := $$ IF jsonb_typeof(result) IS DISTINCT FROM 'object'$$; + IF (length(definition)-length(replace(definition, anchor, '')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one result-evidence validation anchor in V43 activation guard'; + END IF; + replacement := $replacement$ IF NOT EXISTS ( + SELECT 1 + FROM "${serviceSchema}".world_canonical_instance_association a + JOIN "${serviceSchema}".world_canonical_instance_preparation p + ON p.canonical_game_instance_id=a.canonical_game_instance_id + CROSS JOIN LATERAL ( + SELECT count(*) AS row_count, + count(*) FILTER (WHERE m.id IS NULL OR ri.id IS NULL + OR m.world_instance_id IS DISTINCT FROM a.world_instance_id + OR m.canonical_game_instance_id IS DISTINCT FROM a.canonical_game_instance_id + OR m.family IS DISTINCT FROM 'REGION' + OR m.runtime_row_id IS DISTINCT FROM ri.id + OR ri.world_instance_id IS DISTINCT FROM a.world_instance_id + OR ri.tenant_id IS DISTINCT FROM a.local_tenant_key + OR ri.game_instance_id IS DISTINCT FROM a.private_game_instance_key + OR m.runtime_identity IS NULL + OR m.runtime_identity = '00000000-0000-0000-0000-000000000000'::UUID + OR ri.canonical_region_instance_id IS DISTINCT FROM m.runtime_identity + OR ri.operational_region_id IS NULL + OR ri.operational_region_id = '00000000-0000-0000-0000-000000000000'::UUID + OR ri.operational_region_id = m.runtime_identity) AS invalid_count, + count(DISTINCT m.runtime_identity) AS canonical_identity_count, + count(DISTINCT ri.operational_region_id) AS operational_identity_count, + jsonb_object_agg(m.runtime_identity::TEXT, ri.operational_region_id::TEXT) + FILTER (WHERE m.runtime_identity IS NOT NULL AND ri.operational_region_id IS NOT NULL) + AS assignment_map + FROM "${serviceSchema}".world_canonical_instance_topology_identity m + FULL OUTER JOIN "${serviceSchema}".region_instance ri + ON m.family='REGION' AND m.runtime_row_id=ri.id + WHERE (m.world_instance_id=a.world_instance_id AND m.family='REGION') + OR ri.world_instance_id=a.world_instance_id + OR (ri.tenant_id=a.local_tenant_key AND ri.game_instance_id=a.private_game_instance_key) + ) scoped_regions + WHERE a.canonical_game_instance_id=NEW.canonical_game_instance_id + AND a.world_instance_id=NEW.world_instance_id + AND p.region_count > 0 + AND p.region_count=scoped_regions.row_count + AND scoped_regions.row_count=scoped_regions.canonical_identity_count + AND scoped_regions.row_count=scoped_regions.operational_identity_count + AND scoped_regions.invalid_count=0 + AND jsonb_typeof(preparing->'operationalRegionAssignments')='object' + AND CASE WHEN jsonb_typeof(preparing->'operationalRegionAssignments')='object' + THEN (SELECT count(*) FROM jsonb_object_keys(preparing->'operationalRegionAssignments')) + ELSE -1 END = p.region_count + AND scoped_regions.assignment_map=preparing->'operationalRegionAssignments' + ) THEN + RAISE EXCEPTION 'Canonical activation lifecycle evidence lacks the exact complete operational REGION assignment map' + USING ERRCODE = '23514'; + END IF; + IF jsonb_typeof(result) IS DISTINCT FROM 'object'$replacement$; + definition := replace(definition, anchor, replacement); + + EXECUTE definition; + IF '"${serviceSchema}".world_validate_canonical_activation_operation()'::REGPROCEDURE + IS DISTINCT FROM original_oid + OR (SELECT p.proacl FROM pg_proc p WHERE p.oid = original_oid) + IS DISTINCT FROM original_acl THEN + RAISE EXCEPTION 'Canonical activation guard replacement changed function identity or grants'; + END IF; +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1026__world_selected_publication_account_binding.sql b/services/world-management-service/src/main/resources/db/migration/V1026__world_selected_publication_account_binding.sql new file mode 100644 index 0000000000..7651fc48f1 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1026__world_selected_publication_account_binding.sql @@ -0,0 +1,86 @@ +-- Preserve the distinct original Account publication order beside only a newly created World +-- freeze attempt. Historical attempts remain unqualified; their Account order is not inferred. +CREATE TABLE world_design_publication_account_binding ( + publication_fence UUID NOT NULL PRIMARY KEY + REFERENCES world_design_publication_fence_attempt(publication_fence) ON DELETE RESTRICT, + account_operation_id UUID NOT NULL, + account_fence_id UUID NOT NULL, + account_binding_bytes BYTEA NOT NULL CHECK (octet_length(account_binding_bytes) > 0), + account_binding_digest VARCHAR(71) NOT NULL + CHECK (account_binding_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT uq_world_publication_account_operation UNIQUE (account_operation_id), + CONSTRAINT uq_world_publication_account_fence UNIQUE (account_fence_id), + CONSTRAINT ck_world_publication_account_binding_ids CHECK ( + account_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND account_fence_id <> '00000000-0000-0000-0000-000000000000'::UUID + ) +); + +-- A canonical binding may qualify only an attempt inserted by this same transaction. This makes +-- late attachment to an older unqualified FROZEN attempt impossible even for direct SQL writers. +-- The repository additionally decodes and exact-compares the complete Account binding. +-- [jooq ignore start] +-- Existing attempts retain NULL; only attempts inserted after this forward-only stamp receive +-- their full transaction identity. Do not backfill historical rows from their wrapping xmin. +ALTER TABLE world_design_publication_fence_attempt + ADD COLUMN attempt_created_full_xid xid8; +ALTER TABLE world_design_publication_fence_attempt + ALTER COLUMN attempt_created_full_xid SET DEFAULT pg_current_xact_id(); + +REVOKE ALL ON world_design_publication_account_binding FROM PUBLIC; + +CREATE FUNCTION world_validate_selected_publication_account_binding() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + attempt "${serviceSchema}".world_design_publication_fence_attempt%ROWTYPE; + owner_row "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'World selected-publication Account binding is immutable' + USING ERRCODE = '55000'; + END IF; + IF current_setting('transaction_isolation') <> 'read committed' + OR current_setting('transaction_read_only') <> 'off' THEN + RAISE EXCEPTION 'World selected-publication Account binding requires writable READ COMMITTED' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO STRICT attempt + FROM "${serviceSchema}".world_design_publication_fence_attempt a + WHERE a.publication_fence = NEW.publication_fence + AND a.attempt_created_full_xid = pg_current_xact_id() + AND a.xmin::TEXT = (txid_current() % 4294967296)::TEXT; + SELECT * INTO STRICT owner_row + FROM "${serviceSchema}".world_design_publication_fence_owner o + WHERE o.target_namespace = attempt.target_namespace + AND o.canonical_tenant_id = attempt.canonical_tenant_id + AND o.local_tenant_key = attempt.local_tenant_key + AND o.version_id = attempt.version_id + FOR UPDATE; + + IF attempt.owner_binding_schema_version IS DISTINCT FROM 1 + OR owner_row.owner_freeze_phase IS DISTINCT FROM 'FROZEN' + OR owner_row.current_publication_fence IS DISTINCT FROM NEW.publication_fence + OR encode(sha256(NEW.account_binding_bytes), 'hex') + IS DISTINCT FROM substring(NEW.account_binding_digest FROM 8) + OR NEW.account_operation_id = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.account_fence_id = '00000000-0000-0000-0000-000000000000'::UUID THEN + RAISE EXCEPTION 'World Account binding differs from a newly committed qualified freeze' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_world_publication_account_binding_validate + BEFORE INSERT ON world_design_publication_account_binding FOR EACH ROW + EXECUTE FUNCTION world_validate_selected_publication_account_binding(); +CREATE TRIGGER trg_world_publication_account_binding_immutable + BEFORE UPDATE OR DELETE ON world_design_publication_account_binding FOR EACH ROW + EXECUTE FUNCTION world_reject_publication_attempt_history_mutation(); +CREATE TRIGGER trg_world_publication_account_binding_no_truncate + BEFORE TRUNCATE ON world_design_publication_account_binding FOR EACH STATEMENT + EXECUTE FUNCTION world_reject_publication_attempt_history_mutation(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1027__world_publication_terminal_account_binding.sql b/services/world-management-service/src/main/resources/db/migration/V1027__world_publication_terminal_account_binding.sql new file mode 100644 index 0000000000..cec14bd1e5 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1027__world_publication_terminal_account_binding.sql @@ -0,0 +1,115 @@ +-- Keep Game Design's complete original Account publication order bound to the exact World +-- terminal operation, rather than substituting the older Account Draft authorization receipt. +-- [jooq ignore start] +CREATE FUNCTION world_publication_operation_frame(operation_bytes BYTEA, frame_offset INTEGER) +RETURNS BYTEA +LANGUAGE plpgsql IMMUTABLE STRICT +AS $$ +DECLARE + frame_length BIGINT; + remaining_bytes BIGINT; +BEGIN + IF frame_offset < 0 OR frame_offset > octet_length(operation_bytes) - 4 THEN + RAISE EXCEPTION 'World publication operation contains a truncated frame header' + USING ERRCODE = '23514'; + END IF; + + frame_length := + get_byte(operation_bytes, frame_offset)::BIGINT * 16777216 + + get_byte(operation_bytes, frame_offset + 1)::BIGINT * 65536 + + get_byte(operation_bytes, frame_offset + 2)::BIGINT * 256 + + get_byte(operation_bytes, frame_offset + 3)::BIGINT; + remaining_bytes := octet_length(operation_bytes)::BIGINT - frame_offset::BIGINT - 4; + IF frame_length > 4194304 OR frame_length > remaining_bytes THEN + RAISE EXCEPTION 'World publication operation contains a negative or oversized frame' + USING ERRCODE = '23514'; + END IF; + RETURN substring(operation_bytes FROM frame_offset + 5 FOR frame_length::INTEGER); +END; +$$; +REVOKE ALL ON FUNCTION world_publication_operation_frame(BYTEA, INTEGER) FROM PUBLIC; + +CREATE FUNCTION world_require_publication_operation_account_binding( + p_operation_bytes BYTEA, + p_publication_fence UUID, + p_world_evidence_bytes BYTEA +) +RETURNS BOOLEAN +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + frame_offset INTEGER := 0; + schema_bytes BYTEA; + account_binding_bytes BYTEA; + framed_world_evidence BYTEA; + retained_account_binding BYTEA; + retained_account_digest VARCHAR(71); +BEGIN + IF p_operation_bytes IS NULL + OR octet_length(p_operation_bytes) > 4194304 + OR octet_length(p_operation_bytes) < 4 THEN + RAISE EXCEPTION 'World publication operation is empty or oversized' + USING ERRCODE = '23514'; + END IF; + + schema_bytes := world_publication_operation_frame(p_operation_bytes, frame_offset); + IF schema_bytes IS DISTINCT FROM convert_to('game-design-publication-operation/v1', 'UTF8') THEN + RAISE EXCEPTION 'World publication operation has an unsupported schema frame' + USING ERRCODE = '23514'; + END IF; + frame_offset := frame_offset + 4 + octet_length(schema_bytes); + + account_binding_bytes := world_publication_operation_frame(p_operation_bytes, frame_offset); + frame_offset := frame_offset + 4 + octet_length(account_binding_bytes); + + framed_world_evidence := world_publication_operation_frame(p_operation_bytes, frame_offset); + frame_offset := frame_offset + 4 + octet_length(framed_world_evidence); + IF frame_offset <> octet_length(p_operation_bytes) THEN + RAISE EXCEPTION 'World publication operation contains trailing frames or bytes' + USING ERRCODE = '23514'; + END IF; + IF framed_world_evidence IS DISTINCT FROM p_world_evidence_bytes THEN + RAISE EXCEPTION 'World publication operation differs from its exact World evidence' + USING ERRCODE = '23514'; + END IF; + + SELECT q.account_binding_bytes, q.account_binding_digest + INTO STRICT retained_account_binding, retained_account_digest + FROM "${serviceSchema}".world_design_publication_account_binding q + WHERE q.publication_fence = p_publication_fence; + IF encode(sha256(retained_account_binding), 'hex') + IS DISTINCT FROM substring(retained_account_digest FROM 8) THEN + RAISE EXCEPTION 'World publication Account qualification has a corrupt binding digest' + USING ERRCODE = '23514'; + END IF; + + RETURN account_binding_bytes IS NOT DISTINCT FROM retained_account_binding; +END; +$$; +REVOKE ALL ON FUNCTION world_require_publication_operation_account_binding(BYTEA, UUID, BYTEA) + FROM PUBLIC; + +-- Add only the exact original-order guard to V44's terminal validator. The original body remains +-- the source of every existing owner, APPLIED, selector, digest, release and outcome check. +DO $migration$ +DECLARE + original TEXT; + operation_anchor TEXT := $anchor$ world_evidence := convert_from(NEW.world_evidence_bytes, 'UTF8')::JSONB;$anchor$; + operation_guard TEXT := $replacement$ IF NOT world_require_publication_operation_account_binding( + NEW.operation_bytes, NEW.publication_fence, NEW.world_evidence_bytes) THEN + RAISE EXCEPTION 'World terminal operation differs from the exact qualified Account publication binding' + USING ERRCODE = '23514'; + END IF; + world_evidence := convert_from(NEW.world_evidence_bytes, 'UTF8')::JSONB;$replacement$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_validate_publication_terminal()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, operation_anchor, ''))) + / length(operation_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V44 World terminal evidence decode anchor'; + END IF; + EXECUTE replace(original, operation_anchor, operation_guard); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1028__selected_publication_artifact_inventory.sql b/services/world-management-service/src/main/resources/db/migration/V1028__selected_publication_artifact_inventory.sql new file mode 100644 index 0000000000..21f2f442bb --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1028__selected_publication_artifact_inventory.sql @@ -0,0 +1,112 @@ +CREATE TABLE world_selected_publication_artifact_inventory ( + publication_fence UUID NOT NULL PRIMARY KEY + REFERENCES world_design_publication_fence_attempt(publication_fence) ON DELETE RESTRICT, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL, + local_version_key BIGINT NOT NULL, + applied_commit_id VARCHAR(256) NOT NULL, + account_operation_id UUID NOT NULL, + account_fence_id UUID NOT NULL, + inventory_schema_version SMALLINT NOT NULL CHECK (inventory_schema_version = 1), + inventory_bytes BYTEA NOT NULL CHECK (octet_length(inventory_bytes) > 0), + inventory_digest VARCHAR(71) NOT NULL + CHECK (inventory_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT fk_world_selected_publication_inventory_account + FOREIGN KEY (publication_fence) + REFERENCES world_design_publication_account_binding(publication_fence) + ON DELETE RESTRICT, + CONSTRAINT uq_world_selected_publication_inventory_account_operation + UNIQUE (account_operation_id), + CONSTRAINT uq_world_selected_publication_inventory_account_fence + UNIQUE (account_fence_id), + CONSTRAINT ck_world_selected_publication_inventory_scope + CHECK (local_tenant_key > 0 AND local_version_key > 0), + CONSTRAINT ck_world_selected_publication_inventory_ids + CHECK ( + publication_fence <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND account_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND account_fence_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT ck_world_selected_publication_inventory_namespace + CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + ), + CONSTRAINT ck_world_selected_publication_inventory_commit + CHECK (octet_length(applied_commit_id) BETWEEN 1 AND 256) +); + +-- [jooq ignore start] +REVOKE ALL ON world_selected_publication_artifact_inventory FROM PUBLIC; + +CREATE FUNCTION world_validate_selected_publication_artifact_inventory() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + attempt "${serviceSchema}".world_design_publication_fence_attempt%ROWTYPE; + owner_row "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + account_binding "${serviceSchema}".world_design_publication_account_binding%ROWTYPE; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'World selected-publication artifact inventory is immutable' + USING ERRCODE = '55000'; + END IF; + IF current_setting('transaction_isolation') <> 'read committed' + OR current_setting('transaction_read_only') <> 'off' THEN + RAISE EXCEPTION 'World selected-publication artifact inventory requires writable READ COMMITTED' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO STRICT attempt + FROM "${serviceSchema}".world_design_publication_fence_attempt a + WHERE a.publication_fence = NEW.publication_fence + AND a.attempt_created_full_xid = pg_current_xact_id() + AND a.xmin::TEXT = (txid_current() % 4294967296)::TEXT; + SELECT * INTO STRICT owner_row + FROM "${serviceSchema}".world_design_publication_fence_owner o + WHERE o.target_namespace = attempt.target_namespace + AND o.canonical_tenant_id = attempt.canonical_tenant_id + AND o.local_tenant_key = attempt.local_tenant_key + AND o.version_id = attempt.version_id + FOR UPDATE; + SELECT * INTO STRICT account_binding + FROM "${serviceSchema}".world_design_publication_account_binding b + WHERE b.publication_fence = NEW.publication_fence; + + IF attempt.owner_binding_schema_version IS DISTINCT FROM 1 + OR attempt.target_namespace IS DISTINCT FROM NEW.target_namespace + OR attempt.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR attempt.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR attempt.version_id IS DISTINCT FROM NEW.local_version_key + OR attempt.local_tenant_key IS DISTINCT FROM NEW.local_tenant_key + OR attempt.applied_commit_id IS DISTINCT FROM NEW.applied_commit_id + OR account_binding.account_operation_id IS DISTINCT FROM NEW.account_operation_id + OR account_binding.account_fence_id IS DISTINCT FROM NEW.account_fence_id + OR encode(sha256(account_binding.account_binding_bytes), 'hex') + IS DISTINCT FROM substring(account_binding.account_binding_digest FROM 8) + OR encode(sha256(NEW.inventory_bytes), 'hex') + IS DISTINCT FROM substring(NEW.inventory_digest FROM 8) + OR owner_row.owner_freeze_phase IS DISTINCT FROM 'FROZEN' + OR owner_row.current_publication_fence IS DISTINCT FROM NEW.publication_fence THEN + RAISE EXCEPTION 'World artifact inventory differs from the newly qualified selected freeze' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_world_selected_publication_artifact_inventory_validate + BEFORE INSERT ON world_selected_publication_artifact_inventory FOR EACH ROW + EXECUTE FUNCTION world_validate_selected_publication_artifact_inventory(); +CREATE TRIGGER trg_world_selected_publication_artifact_inventory_immutable + BEFORE UPDATE OR DELETE ON world_selected_publication_artifact_inventory FOR EACH ROW + EXECUTE FUNCTION world_reject_publication_attempt_history_mutation(); +CREATE TRIGGER trg_world_selected_publication_artifact_inventory_no_truncate + BEFORE TRUNCATE ON world_selected_publication_artifact_inventory FOR EACH STATEMENT + EXECUTE FUNCTION world_reject_publication_attempt_history_mutation(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1029__publication_operation_inventory_v2.sql b/services/world-management-service/src/main/resources/db/migration/V1029__publication_operation_inventory_v2.sql new file mode 100644 index 0000000000..2e09511e43 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1029__publication_operation_inventory_v2.sql @@ -0,0 +1,192 @@ +-- Mandatory v2 public evidence, derived from unchanged private retained inventory. +-- [jooq ignore start] +CREATE FUNCTION selected_inventory_operation_frame(operation_bytes BYTEA, frame_offset INTEGER) RETURNS BYTEA AS $$ +DECLARE length_bytes BIGINT; +BEGIN + IF frame_offset < 0 OR frame_offset > octet_length(operation_bytes) - 4 THEN + RAISE EXCEPTION 'Truncated publication inventory frame' USING ERRCODE = '23514'; END IF; + length_bytes := get_byte(operation_bytes, frame_offset)::BIGINT * 16777216 + + get_byte(operation_bytes, frame_offset + 1)::BIGINT * 65536 + + get_byte(operation_bytes, frame_offset + 2)::BIGINT * 256 + + get_byte(operation_bytes, frame_offset + 3)::BIGINT; + IF length_bytes > 4194304 OR length_bytes > octet_length(operation_bytes) - frame_offset - 4 THEN + RAISE EXCEPTION 'Oversized publication inventory frame' USING ERRCODE = '23514'; END IF; + RETURN substring(operation_bytes FROM frame_offset + 5 FOR length_bytes::INTEGER); +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; +CREATE FUNCTION selected_inventory_operation_nth(operation_bytes BYTEA, frame_index INTEGER) RETURNS BYTEA AS $$ +DECLARE offset_bytes INTEGER := 0; value BYTEA; i INTEGER; +BEGIN + IF frame_index < 0 THEN RAISE EXCEPTION 'Negative frame index' USING ERRCODE = '23514'; END IF; + FOR i IN 0..frame_index LOOP + value := selected_inventory_operation_frame(operation_bytes, offset_bytes); + offset_bytes := offset_bytes + 4 + octet_length(value); + END LOOP; + RETURN value; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; +CREATE FUNCTION require_selected_inventory_operation_v2(operation_bytes BYTEA) RETURNS VOID AS $$ +DECLARE frames BYTEA[] := ARRAY[]::BYTEA[]; value BYTEA; offset_bytes INTEGER := 0; + account_bytes BYTEA; input_bytes BYTEA; selector JSONB; inventory JSONB; selected JSONB; + applied JSONB; applied_bytes BYTEA; applied_operation BYTEA; original_account BYTEA; + owner JSONB; application JSONB; account_order JSONB; frozen JSONB; checkpoint JSONB; + model JSONB; expected_epochs JSONB; i INTEGER; +BEGIN + IF operation_bytes IS NULL OR octet_length(operation_bytes) NOT BETWEEN 1 AND 4194304 THEN + RAISE EXCEPTION 'Complete bounded v2 publication operation required' USING ERRCODE = '23514'; END IF; + FOR i IN 0..4 LOOP + value := selected_inventory_operation_frame(operation_bytes, offset_bytes); + offset_bytes := offset_bytes + 4 + octet_length(value); + frames := array_append(frames, value); + END LOOP; + IF offset_bytes <> octet_length(operation_bytes) OR frames[1] <> convert_to('game-design-publication-operation/v2', 'UTF8') + OR frames[5] IS DISTINCT FROM convert_to('sha256:' || encode(sha256(frames[4]), 'hex'), 'UTF8') THEN + RAISE EXCEPTION 'Publication v2 schema, exact frame count or inventory digest invalid' USING ERRCODE = '23514'; END IF; + account_bytes := frames[2]; + input_bytes := selected_inventory_operation_nth(account_bytes, 3); + selected := convert_from(selected_inventory_operation_nth(input_bytes, 2), 'UTF8')::JSONB; + selector := convert_from(frames[3], 'UTF8')::JSONB; + inventory := convert_from(frames[4], 'UTF8')::JSONB; + applied_bytes := decode(selector->>'appliedResultBytesBase64', 'base64'); + applied := convert_from(applied_bytes, 'UTF8')::JSONB; + applied_operation := decode(applied->>'operationBytesBase64', 'base64'); + original_account := decode(selector->>'originalAccountBindingBytesBase64', 'base64'); + owner := inventory->'ownerScope'; application := inventory->'selectedApplication'; + account_order := inventory->'accountOrder'; frozen := inventory->'freeze'; + checkpoint := inventory->'checkpoint'; model := inventory->'sourceModel'; + SELECT coalesce(jsonb_agg((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT) + ORDER BY unit->>'aggregateType', unit->>'aggregateId', unit->>'scopeType', unit->>'scopeId'), '[]'::JSONB) + INTO expected_epochs FROM jsonb_array_elements((selected->>'selectedCommitBindingJson')::JSONB->'affectedUnits') unit + WHERE unit->>'owner' = 'WORLD_MANAGEMENT'; + IF inventory->>'schema' IS DISTINCT FROM 'world-selected-publication-artifact-inventory/v1' + OR inventory->'schemaVersion' IS DISTINCT FROM '1'::JSONB OR inventory->>'completeness' IS DISTINCT FROM 'COMPLETE' + OR (SELECT count(*) FROM jsonb_object_keys(inventory)) <> 10 + OR owner->>'targetNamespace' IS DISTINCT FROM selector->'request'->>'targetNamespace' + OR owner->>'canonicalTenantId' IS DISTINCT FROM selector->'request'->>'canonicalTenantId' + OR owner->>'canonicalVersionId' IS DISTINCT FROM selector->'request'->>'canonicalVersionId' + OR owner->>'intakeRequestId' IS DISTINCT FROM selector->'request'->>'intakeRequestId' + OR application->>'applicationOperationId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(applied_operation, 1), 'UTF8') + OR application->>'applicationOperationId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(original_account, 1), 'UTF8') + OR application->>'applicationRequestId' IS DISTINCT FROM selected->'intent'->>'selectedCommitRequestId' + OR application->>'appliedCommitId' IS DISTINCT FROM selector->'request'->>'appliedCommitId' + OR application->>'bindingDigest' IS DISTINCT FROM selected->'intent'->>'selectedCommitDigest' + OR application->>'appliedResultDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(applied_bytes), 'hex') + OR account_order->>'operationId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(account_bytes, 1), 'UTF8') + OR account_order->>'fenceId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(account_bytes, 2), 'UTF8') + OR account_order->>'actorAccountId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(input_bytes, 1), 'UTF8') + OR account_order->>'publicationRequestId' IS DISTINCT FROM selected->'intent'->>'publishRequestId' + OR account_order->>'selectionDigest' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(input_bytes, 3), 'UTF8') + OR account_order->>'selectedCommitId' IS DISTINCT FROM selected->'intent'->>'selectedCommitId' + OR account_order->>'bindingDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(account_bytes), 'hex') + OR frozen->>'publicationFence' IS DISTINCT FROM selector->'request'->>'publicationFence' + OR frozen->>'publicationRequestId' IS DISTINCT FROM selector->'request'->>'publicationRequestId' + OR frozen->>'requestDigest' IS DISTINCT FROM selector->'request'->>'requestDigest' + OR frozen->>'versionStateEpoch' IS DISTINCT FROM selector->'request'->>'versionStateEpoch' + OR frozen->>'publishWorkflowId' IS DISTINCT FROM selector->'request'->>'publishWorkflowId' + OR checkpoint->>'appliedCommitId' IS DISTINCT FROM selector->'request'->>'appliedCommitId' + OR checkpoint->>'contentDigest' IS DISTINCT FROM selector->'request'->>'contentDigest' + OR checkpoint->'digestSchemaVersion' IS DISTINCT FROM selector->'request'->'digestSchemaVersion' + OR model->>'graphDigest' IS DISTINCT FROM applied->>'graphDigest' + OR model->'appliedEpochs' IS DISTINCT FROM expected_epochs OR expected_epochs = '[]'::JSONB + OR model->>'modelId' IS DISTINCT FROM 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1' + OR model->'graphSchemaVersion' IS DISTINCT FROM '2'::JSONB + OR model->'generationRuleInputCount' IS DISTINCT FROM '0'::JSONB + OR inventory->'artifactDecisions' IS DISTINCT FROM + '[{"artifactKind":"NAVMESH","state":"NOT_REQUIRED","rule":"ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"},{"artifactKind":"PATH_GRAPH","state":"NOT_REQUIRED","rule":"AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"}]'::JSONB THEN + RAISE EXCEPTION 'Inventory differs from exact original selected Account, APPLIED graph or freeze' USING ERRCODE = '23514'; END IF; +END; +$$ LANGUAGE plpgsql; +CREATE OR REPLACE FUNCTION world_require_publication_operation_account_binding( + p_operation_bytes BYTEA, + p_publication_fence UUID, + p_world_evidence_bytes BYTEA +) +RETURNS BOOLEAN +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + frame_offset INTEGER := 0; + schema_bytes BYTEA; + account_binding_bytes BYTEA; + framed_world_evidence BYTEA; + retained_account_binding BYTEA; + retained_account_digest VARCHAR(71); + public_inventory BYTEA; public_digest BYTEA; private_inventory JSONB; expected_public JSONB; model JSONB; +BEGIN + IF p_operation_bytes IS NULL + OR octet_length(p_operation_bytes) > 4194304 + OR octet_length(p_operation_bytes) < 4 THEN + RAISE EXCEPTION 'World publication operation is empty or oversized' + USING ERRCODE = '23514'; + END IF; + + schema_bytes := world_publication_operation_frame(p_operation_bytes, frame_offset); + IF schema_bytes IS DISTINCT FROM convert_to('game-design-publication-operation/v2', 'UTF8') THEN + RAISE EXCEPTION 'World publication operation has an unsupported schema frame' + USING ERRCODE = '23514'; + END IF; + frame_offset := frame_offset + 4 + octet_length(schema_bytes); + + account_binding_bytes := world_publication_operation_frame(p_operation_bytes, frame_offset); + frame_offset := frame_offset + 4 + octet_length(account_binding_bytes); + + PERFORM require_selected_inventory_operation_v2(p_operation_bytes); + framed_world_evidence := world_publication_operation_frame(p_operation_bytes, frame_offset); + frame_offset := frame_offset + 4 + octet_length(framed_world_evidence); + public_inventory := world_publication_operation_frame(p_operation_bytes, frame_offset); + frame_offset := frame_offset + 4 + octet_length(public_inventory); + public_digest := world_publication_operation_frame(p_operation_bytes, frame_offset); + frame_offset := frame_offset + 4 + octet_length(public_digest); + IF frame_offset <> octet_length(p_operation_bytes) THEN + RAISE EXCEPTION 'World publication operation contains trailing frames or bytes' + USING ERRCODE = '23514'; + END IF; + IF framed_world_evidence IS DISTINCT FROM p_world_evidence_bytes THEN + RAISE EXCEPTION 'World publication operation differs from its exact World evidence' + USING ERRCODE = '23514'; + END IF; + + SELECT q.account_binding_bytes, q.account_binding_digest + INTO STRICT retained_account_binding, retained_account_digest + FROM "${serviceSchema}".world_design_publication_account_binding q + WHERE q.publication_fence = p_publication_fence; + IF encode(sha256(retained_account_binding), 'hex') + IS DISTINCT FROM substring(retained_account_digest FROM 8) THEN + RAISE EXCEPTION 'World publication Account qualification has a corrupt binding digest' + USING ERRCODE = '23514'; + END IF; + + SELECT convert_from(i.inventory_bytes, 'UTF8')::JSONB INTO STRICT private_inventory + FROM "${serviceSchema}".world_selected_publication_artifact_inventory i + WHERE i.publication_fence = p_publication_fence + AND i.inventory_digest = 'sha256:' || encode(sha256(i.inventory_bytes), 'hex'); + model := private_inventory->'sourceModel'; + model := jsonb_set(model, '{regionGeneratorInputs}', + coalesce((SELECT jsonb_agg(x ORDER BY x->>'regionTemplateId') FROM jsonb_array_elements(model->'regionGeneratorInputs') x), '[]'::JSONB)); + model := jsonb_set(model, '{spawnBindingInputs}', + coalesce((SELECT jsonb_agg(x ORDER BY x->>'bindingTemplateId') FROM jsonb_array_elements(model->'spawnBindingInputs') x), '[]'::JSONB)); + expected_public := jsonb_build_object( + 'schema', private_inventory->'schema', 'schemaVersion', private_inventory->'schemaVersion', + 'completeness', private_inventory->'completeness', + 'ownerScope', private_inventory->'ownerScope' - ARRAY['localTenantKey', 'localVersionKey', 'gameDesignVersionId'], + 'selectedApplication', private_inventory->'selectedApplication', + 'accountOrder', private_inventory->'accountOrder' - ARRAY['canonicalBindingBytes'], + 'freeze', private_inventory->'freeze', 'checkpoint', private_inventory->'checkpoint', + 'sourceModel', model, 'artifactDecisions', private_inventory->'artifactDecisions'); + IF jsonb_typeof(private_inventory) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(private_inventory)) <> 11 + OR NOT (private_inventory ?& ARRAY['schema', 'schemaVersion', 'completeness', 'ownerScope', + 'sourceIntake', 'selectedApplication', 'accountOrder', 'freeze', 'checkpoint', + 'sourceModel', 'artifactDecisions']) + OR jsonb_typeof(private_inventory->'sourceIntake') IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(private_inventory->'sourceIntake')) <> 4 + OR NOT (private_inventory->'sourceIntake' ?& ARRAY['worldSlug', 'sourceGameRowId', + 'sourceGameTenantKey', 'sourceProvenanceKind']) + OR NOT (convert_from(public_inventory, 'UTF8') IS JSON OBJECT WITH UNIQUE KEYS) + OR convert_from(public_inventory, 'UTF8')::JSONB IS DISTINCT FROM expected_public + OR public_digest IS DISTINCT FROM convert_to('sha256:' || encode(sha256(public_inventory), 'hex'), 'UTF8') THEN + RAISE EXCEPTION 'World terminal inventory differs from complete retained public projection' USING ERRCODE = '23514'; END IF; + RETURN account_binding_bytes IS NOT DISTINCT FROM retained_account_binding; +END; +$$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1030__world_publication_inventory_projection_precedence.sql b/services/world-management-service/src/main/resources/db/migration/V1030__world_publication_inventory_projection_precedence.sql new file mode 100644 index 0000000000..21fdd21f8a --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1030__world_publication_inventory_projection_precedence.sql @@ -0,0 +1,19 @@ +-- Preserve the V56 public inventory projection while making JSONB extraction bind before `-`. +-- [jooq ignore start] +DO $migration$ +DECLARE + original TEXT; + projection_anchor TEXT := $anchor$ 'ownerScope', private_inventory->'ownerScope' - ARRAY['localTenantKey', 'localVersionKey', 'gameDesignVersionId'],$anchor$; + corrected_projection TEXT := $replacement$ 'ownerScope', (private_inventory->'ownerScope') - ARRAY['localTenantKey', 'localVersionKey', 'gameDesignVersionId'],$replacement$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_require_publication_operation_account_binding(BYTEA, UUID, BYTEA)'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, projection_anchor, ''))) + / length(projection_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V56 World ownerScope projection expression'; + END IF; + EXECUTE replace(original, projection_anchor, corrected_projection); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1031__publication_account_order_projection.sql b/services/world-management-service/src/main/resources/db/migration/V1031__publication_account_order_projection.sql new file mode 100644 index 0000000000..45a28e585b --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1031__publication_account_order_projection.sql @@ -0,0 +1,19 @@ +-- Preserve the complete Account-order projection while binding JSONB extraction before `-`. +-- [jooq ignore start] +DO $migration$ +DECLARE + original TEXT; + projection_anchor TEXT := $anchor$ 'accountOrder', private_inventory->'accountOrder' - ARRAY['canonicalBindingBytes'],$anchor$; + corrected_projection TEXT := $replacement$ 'accountOrder', (private_inventory->'accountOrder') - ARRAY['canonicalBindingBytes'],$replacement$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_require_publication_operation_account_binding(BYTEA, UUID, BYTEA)'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, projection_anchor, ''))) + / length(projection_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V56 World accountOrder projection expression'; + END IF; + EXECUTE replace(original, projection_anchor, corrected_projection); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1032__world_selected_inbound_closure_declaration.sql b/services/world-management-service/src/main/resources/db/migration/V1032__world_selected_inbound_closure_declaration.sql new file mode 100644 index 0000000000..c0fac99d26 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1032__world_selected_inbound_closure_declaration.sql @@ -0,0 +1,115 @@ +-- Additive guard for the versioned selected-inbound source declaration. Existing V24/V30/V35 +-- canonical-key, mapped-identity and execution-manifest guards remain authoritative; this guard +-- binds the explicit empty-only closure to the exact original graph written under the OPEN owner. +-- [jooq ignore start] +CREATE FUNCTION world_guard_selected_inbound_closure() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + graph_row "${serviceSchema}".world_topology_draft_commit%ROWTYPE; + owner_row "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + declaration JSONB; + closure JSONB; + graph_json JSONB; + family_entry JSONB; + family_names TEXT[] := ARRAY[ + 'WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT', + 'WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT', + 'WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION', + 'WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING', + 'WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK', + 'WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE', + 'WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING']; + declaration_count BIGINT; + mapping_count BIGINT; + family_index INTEGER; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'World selected-inbound APPLIED evidence is immutable and retained' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO graph_row FROM "${serviceSchema}".world_topology_draft_commit + WHERE request_id = NEW.request_id AND commit_id = NEW.commit_id; + IF NOT FOUND OR graph_row.application_transaction_id IS DISTINCT FROM txid_current() THEN + RAISE EXCEPTION 'Selected-inbound closure requires a genuinely fresh graph in this transaction' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO owner_row FROM "${serviceSchema}".world_design_publication_fence_owner + WHERE target_namespace = graph_row.target_namespace + AND canonical_tenant_id = graph_row.canonical_tenant_id + AND local_tenant_key = graph_row.local_tenant_key + AND version_id = graph_row.local_version_key FOR UPDATE; + IF NOT FOUND OR owner_row.owner_freeze_phase <> 'OPEN' + OR owner_row.current_publication_fence IS NOT NULL THEN + RAISE EXCEPTION 'Selected-inbound closure requires the exact OPEN World owner lock' + USING ERRCODE = '23514'; + END IF; + + SELECT count(*) INTO declaration_count + FROM jsonb_array_elements(graph_row.binding_json::JSONB->'revisions') AS revision(value) + WHERE value->>'owner' = 'WORLD_MANAGEMENT' + AND (((value->>'payload')::JSONB)->'freshGraphDeclaration') IS NOT NULL; + IF declaration_count <> 1 THEN + RAISE EXCEPTION 'Selected-inbound closure requires one exact original World declaration' + USING ERRCODE = '23514'; + END IF; + SELECT ((value->>'payload')::JSONB)->'freshGraphDeclaration' INTO declaration + FROM jsonb_array_elements(graph_row.binding_json::JSONB->'revisions') AS revision(value) + WHERE value->>'owner' = 'WORLD_MANAGEMENT' + AND (((value->>'payload')::JSONB)->'freshGraphDeclaration') ? 'inboundSourceClosure'; + closure := declaration->'inboundSourceClosure'; + IF jsonb_typeof(closure) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys( + CASE WHEN jsonb_typeof(closure) = 'object' THEN closure ELSE '{}'::JSONB END)) <> 2 + OR NOT (closure ? 'schemaVersion') + OR jsonb_typeof(closure->'schemaVersion') IS DISTINCT FROM 'number' + OR closure->>'schemaVersion' IS DISTINCT FROM '1' + OR jsonb_typeof(closure->'familyCounts') IS DISTINCT FROM 'array' + OR jsonb_array_length(closure->'familyCounts') <> array_length(family_names, 1) THEN + RAISE EXCEPTION 'Selected-inbound source closure is unknown, incomplete or unversioned' + USING ERRCODE = '23514'; + END IF; + + graph_json := convert_from(graph_row.graph_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(graph_json) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys( + CASE WHEN jsonb_typeof(graph_json) = 'object' THEN graph_json ELSE '{}'::JSONB END)) <> 5 + OR graph_json->>'schemaVersion' IS DISTINCT FROM '3' + OR graph_json->>'canonicalTenantId' IS DISTINCT FROM graph_row.canonical_tenant_id::TEXT + OR graph_json->>'canonicalVersionId' IS DISTINCT FROM graph_row.canonical_version_id::TEXT + OR graph_json->'inboundSourceClosure' IS DISTINCT FROM closure + OR jsonb_typeof(graph_json->'rows') IS DISTINCT FROM 'array' + OR jsonb_array_length(graph_json->'rows') < 1 THEN + RAISE EXCEPTION 'Canonical graph does not retain the exact original inbound closure' + USING ERRCODE = '23514'; + END IF; + SELECT count(*) INTO mapping_count + FROM "${serviceSchema}".world_authored_topology_identity + WHERE request_id = NEW.request_id AND commit_id = NEW.commit_id + AND tenant_id = graph_row.local_tenant_key AND version_id = graph_row.local_version_key; + IF mapping_count <> jsonb_array_length(graph_json->'rows') THEN + RAISE EXCEPTION 'Selected-inbound closure lacks complete same-scope fresh mapped World rows' + USING ERRCODE = '23514'; + END IF; + + FOR family_index IN 1..array_length(family_names, 1) LOOP + family_entry := closure->'familyCounts'->(family_index - 1); + IF jsonb_typeof(family_entry) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys( + CASE WHEN jsonb_typeof(family_entry) = 'object' THEN family_entry ELSE '{}'::JSONB END)) <> 2 + OR family_entry->>'family' IS DISTINCT FROM family_names[family_index] + OR NOT (family_entry ? 'count') + OR jsonb_typeof(family_entry->'count') IS DISTINCT FROM 'number' + OR family_entry->>'count' IS DISTINCT FROM '0' THEN + RAISE EXCEPTION 'Selected-inbound family vector is noncanonical or outside the empty-only subset' + USING ERRCODE = '23514'; + END IF; + END LOOP; + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_world_graph_inbound_closure_guard BEFORE INSERT + ON world_draft_graph_application FOR EACH ROW + EXECUTE FUNCTION world_guard_selected_inbound_closure(); +REVOKE ALL ON FUNCTION world_guard_selected_inbound_closure() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1033__world_selected_publication_inventory_schema_v2.sql b/services/world-management-service/src/main/resources/db/migration/V1033__world_selected_publication_inventory_schema_v2.sql new file mode 100644 index 0000000000..890be52f65 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1033__world_selected_publication_inventory_schema_v2.sql @@ -0,0 +1,63 @@ +-- Preserve exact schema-1 inventory rows and permit only the additive closure inventory profile. +-- [jooq ignore start] +DO $migration$ +DECLARE + target_schema TEXT := '${serviceSchema}'; + target_table TEXT := 'world_selected_publication_artifact_inventory'; + target_relation OID; + target_column SMALLINT; + matching_guard_count BIGINT; + guard_names TEXT[]; + guard_name TEXT; + guard_is_expected BOOLEAN; + replacement_guard TEXT := 'ck_world_selected_pub_inv_schema_v2'; +BEGIN + SELECT c.oid INTO target_relation + FROM pg_catalog.pg_class c + JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = target_schema + AND c.relname = target_table + AND c.relkind = 'r'; + IF target_relation IS NULL THEN + RAISE EXCEPTION 'Expected exact World selected inventory owner table %.%', + target_schema, target_table; + END IF; + + SELECT a.attnum INTO target_column + FROM pg_catalog.pg_attribute a + WHERE a.attrelid = target_relation + AND a.attname = 'inventory_schema_version' + AND NOT a.attisdropped; + IF target_column IS NULL THEN + RAISE EXCEPTION 'Expected inventory_schema_version on exact World inventory owner table'; + END IF; + + SELECT count(*), array_agg(c.conname::TEXT), bool_and( + c.conislocal + AND c.convalidated + AND c.conkey = ARRAY[target_column]::SMALLINT[] + AND pg_catalog.regexp_replace( + pg_catalog.lower(pg_catalog.pg_get_expr(c.conbin, c.conrelid)), + '[[:space:]()]', '', 'g') = 'inventory_schema_version=1') + INTO matching_guard_count, guard_names, guard_is_expected + FROM pg_catalog.pg_constraint c + WHERE c.conrelid = target_relation + AND c.contype = 'c' + AND target_column = ANY(c.conkey); + + IF matching_guard_count <> 1 OR guard_is_expected IS DISTINCT FROM TRUE THEN + RAISE EXCEPTION + 'Expected exactly one single-column inventory_schema_version = 1 check on %.%', + target_schema, target_table; + END IF; + guard_name := guard_names[1]; + + EXECUTE pg_catalog.format( + 'ALTER TABLE %I.%I DROP CONSTRAINT %s', + target_schema, target_table, pg_catalog.quote_ident(guard_name)); + EXECUTE pg_catalog.format( + 'ALTER TABLE %I.%I ADD CONSTRAINT %s CHECK (inventory_schema_version IN (1, 2))', + target_schema, target_table, pg_catalog.quote_ident(replacement_guard)); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1034__world_selected_closure_schema4_guards.sql b/services/world-management-service/src/main/resources/db/migration/V1034__world_selected_closure_schema4_guards.sql new file mode 100644 index 0000000000..512155f3f0 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1034__world_selected_closure_schema4_guards.sql @@ -0,0 +1,267 @@ +-- A selected World digest/4 is valid only for a newly applied graph/3 carrying the exact original +-- seven-family empty declaration. Historical schema-2/3 rows and V27 bytes are not rewritten. +-- [jooq ignore start] +DROP TRIGGER trg_world_canonical_frozen_00_schema3 ON world_canonical_frozen_topology; + +CREATE FUNCTION world_require_new_selected_digest_capture() RETURNS TRIGGER +LANGUAGE plpgsql SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + request JSONB; + attempt "${serviceSchema}".world_design_publication_fence_attempt%ROWTYPE; + owner_row "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + commit_row "${serviceSchema}".world_topology_draft_commit%ROWTYPE; + graph_json JSONB; + closure JSONB; + declaration_count BIGINT; + matching_declaration_count BIGINT; + mapping_count BIGINT; + applied_count BIGINT; +BEGIN + IF current_setting('transaction_isolation') <> 'read committed' + OR current_setting('transaction_read_only') <> 'off' THEN + RAISE EXCEPTION 'Canonical frozen capture requires writable READ COMMITTED' + USING ERRCODE = '23514'; + END IF; + + request := NEW.freeze_request_json::JSONB; + IF request->>'digestSchemaVersion' IS DISTINCT FROM '4' THEN + RAISE EXCEPTION 'New canonical graph capture requires selected closure schema 4' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO STRICT commit_row + FROM "${serviceSchema}".world_topology_draft_commit c + WHERE c.request_id = NEW.request_id AND c.commit_id = NEW.commit_id; + SELECT * INTO STRICT attempt + FROM "${serviceSchema}".world_design_publication_fence_attempt a + WHERE a.publication_fence = NEW.publication_fence; + SELECT * INTO STRICT owner_row + FROM "${serviceSchema}".world_design_publication_fence_owner o + WHERE o.target_namespace = commit_row.target_namespace + AND o.canonical_tenant_id = commit_row.canonical_tenant_id + AND o.local_tenant_key = commit_row.local_tenant_key + AND o.version_id = commit_row.local_version_key + FOR UPDATE; + + IF owner_row.owner_freeze_phase IS DISTINCT FROM 'FROZEN' + OR owner_row.current_publication_fence IS DISTINCT FROM NEW.publication_fence + OR attempt.owner_binding_schema_version IS DISTINCT FROM 1 + OR attempt.publication_fence IS DISTINCT FROM NEW.publication_fence + OR attempt.target_namespace IS DISTINCT FROM request->>'targetNamespace' + OR attempt.canonical_tenant_id::TEXT IS DISTINCT FROM request->>'canonicalTenantId' + OR attempt.canonical_version_id::TEXT IS DISTINCT FROM request->>'canonicalVersionId' + OR attempt.applied_commit_id IS DISTINCT FROM request->>'appliedCommitId' + OR attempt.content_digest IS DISTINCT FROM request->>'contentDigest' + OR attempt.digest_schema_version IS DISTINCT FROM 4 + OR commit_row.target_namespace IS DISTINCT FROM request->>'targetNamespace' + OR commit_row.canonical_tenant_id::TEXT IS DISTINCT FROM request->>'canonicalTenantId' + OR commit_row.canonical_version_id::TEXT IS DISTINCT FROM request->>'canonicalVersionId' + OR commit_row.graph_bytes IS DISTINCT FROM NEW.graph_bytes + OR commit_row.result_bytes IS DISTINCT FROM NEW.storage_result_bytes THEN + RAISE EXCEPTION 'Selected graph/4 capture differs from exact FROZEN source and checkpoint' + USING ERRCODE = '23514'; + END IF; + + closure := '{"schemaVersion":1,"familyCounts":[{"family":"WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING","count":0}]}'::JSONB; + graph_json := convert_from(commit_row.graph_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(graph_json) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys( + CASE WHEN jsonb_typeof(graph_json) = 'object' THEN graph_json ELSE '{}'::JSONB END)) <> 5 + OR graph_json->>'schemaVersion' IS DISTINCT FROM '3' + OR graph_json->>'canonicalTenantId' IS DISTINCT FROM commit_row.canonical_tenant_id::TEXT + OR graph_json->>'canonicalVersionId' IS DISTINCT FROM commit_row.canonical_version_id::TEXT + OR graph_json->'inboundSourceClosure' IS DISTINCT FROM closure + OR jsonb_typeof(graph_json->'rows') IS DISTINCT FROM 'array' + OR jsonb_array_length(graph_json->'rows') < 1 THEN + RAISE EXCEPTION 'Selected digest/4 requires the exact original graph/3 closure declaration' + USING ERRCODE = '23514'; + END IF; + + SELECT count(*) INTO declaration_count + FROM jsonb_array_elements(commit_row.binding_json::JSONB->'revisions') AS revision(value) + WHERE revision.value->>'owner' = 'WORLD_MANAGEMENT' + AND (((revision.value->>'payload')::JSONB)->'freshGraphDeclaration') IS NOT NULL; + SELECT count(*) INTO matching_declaration_count + FROM jsonb_array_elements(commit_row.binding_json::JSONB->'revisions') AS revision(value) + WHERE revision.value->>'owner' = 'WORLD_MANAGEMENT' + AND (((revision.value->>'payload')::JSONB)->'freshGraphDeclaration'->'inboundSourceClosure') + IS NOT DISTINCT FROM closure; + IF declaration_count <> 1 OR matching_declaration_count <> 1 THEN + RAISE EXCEPTION 'Selected digest/4 requires one exact original authored closure declaration' + USING ERRCODE = '23514'; + END IF; + + SELECT count(*) INTO mapping_count + FROM "${serviceSchema}".world_authored_topology_identity m + WHERE m.request_id = commit_row.request_id AND m.commit_id = commit_row.commit_id + AND m.tenant_id = commit_row.local_tenant_key + AND m.version_id = commit_row.local_version_key; + SELECT count(*) INTO applied_count + FROM "${serviceSchema}".world_draft_graph_application a + WHERE a.request_id = commit_row.request_id AND a.commit_id = commit_row.commit_id + AND a.application_transaction_id = commit_row.application_transaction_id + AND a.result_digest = 'sha256:' || encode(sha256(a.result_bytes), 'hex') + AND convert_from(a.result_bytes, 'UTF8')::JSONB->>'status' = 'APPLIED' + AND convert_from(a.result_bytes, 'UTF8')::JSONB->>'graphDigest' + = 'sha256:' || encode(sha256(commit_row.graph_bytes), 'hex'); + IF mapping_count <> jsonb_array_length(graph_json->'rows') OR mapping_count = 0 + OR applied_count <> 1 THEN + RAISE EXCEPTION 'Selected digest/4 requires complete same-scope fresh mappings and exact APPLIED result' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_world_canonical_frozen_00_selected_digest + BEFORE INSERT ON world_canonical_frozen_topology + FOR EACH ROW EXECUTE FUNCTION world_require_new_selected_digest_capture(); +REVOKE ALL ON FUNCTION world_require_new_selected_digest_capture() FROM PUBLIC; + +-- Advance the release join without changing its v1/v2 evidence or preparation behavior. Selected +-- attestation/2 remains World/3; only attestation/3 may carry World/4 and its exact selector. +DO $migration$ +DECLARE + preparation_function REGPROCEDURE := + '"${serviceSchema}".world_prepare_canonical_instance(text,text)'::REGPROCEDURE; + original_definition TEXT; + anchor TEXT := $anchor$ AND participant->>'digestSchemaVersion' = '3'$anchor$; + replacement TEXT := $replacement$ AND binding_row.release_attestation_json::JSONB->>'schemaVersion' IN ('2', '3') + AND participant->>'digestSchemaVersion' = CASE + binding_row.release_attestation_json::JSONB->>'schemaVersion' + WHEN '2' THEN '3' WHEN '3' THEN '4' ELSE NULL END + AND binding_row.release_attestation_json::JSONB->'worldStartLocationEvidence'->'request'->>'digestSchemaVersion' + = capture_row.freeze_request_json::JSONB->>'digestSchemaVersion'$replacement$; +BEGIN + SELECT pg_get_functiondef(preparation_function) INTO STRICT original_definition; + IF (length(original_definition) - length(replace(original_definition, anchor, ''))) + / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V40 World digest-3 participant guard'; + END IF; + EXECUTE replace(original_definition, anchor, replacement); +END; +$migration$; + +-- Keep preparation input schema 2 and all V1 retries exact. Its release selector pair is either +-- the retained attestation/2 + World/3 pair or new attestation/3 + World/4 pair. +DO $migration$ +DECLARE + selector_function REGPROCEDURE := + '"${serviceSchema}".world_require_preparation_start_location(jsonb,jsonb,uuid)'::REGPROCEDURE; + original_definition TEXT; + schema_anchor TEXT := $anchor$ IF input->>'schemaVersion' IS DISTINCT FROM '2' OR binding->>'schemaVersion' IS DISTINCT FROM '2' + OR input->>'worldStartLocationEvidenceBase64' IS NULL$anchor$; + schema_replacement TEXT := $replacement$ IF input->>'schemaVersion' IS DISTINCT FROM '2' + OR binding->>'schemaVersion' IS NULL + OR binding->>'schemaVersion' NOT IN ('2', '3') + OR input->>'worldStartLocationEvidenceBase64' IS NULL$replacement$; + digest_anchor TEXT := $anchor$ OR selected->>'digestSchemaVersion' IS DISTINCT FROM '3'$anchor$; + -- Parentheses keep the CASE's THEN tokens inside the SQL expression rather than terminating + -- PL/pgSQL's outer IF condition while the rewritten function is compiled. + digest_replacement TEXT := $replacement$ OR selected->>'digestSchemaVersion' IS DISTINCT FROM (CASE binding->>'schemaVersion' + WHEN '2' THEN '3' WHEN '3' THEN '4' ELSE NULL END)$replacement$; +BEGIN + SELECT pg_get_functiondef(selector_function) INTO STRICT original_definition; + IF (length(original_definition) - length(replace(original_definition, schema_anchor, ''))) + / length(schema_anchor) <> 1 + OR (length(original_definition) - length(replace(original_definition, digest_anchor, ''))) + / length(digest_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact V42 selected World schema-3 selector guards'; + END IF; + original_definition := replace(original_definition, schema_anchor, schema_replacement); + original_definition := replace(original_definition, digest_anchor, digest_replacement); +EXECUTE original_definition; +END; +$migration$; + +-- The immutable operation/public projection accepts only legacy inventory/1 + World/3 or the +-- explicit closure inventory/2 + World/4 pair. It never promotes an absent declaration. +DO $migration$ +DECLARE + inventory_function REGPROCEDURE := + '"${serviceSchema}".require_selected_inventory_operation_v2(bytea)'::REGPROCEDURE; + original_definition TEXT; + anchor TEXT := $anchor$ IF inventory->>'schema' IS DISTINCT FROM 'world-selected-publication-artifact-inventory/v1' + OR inventory->'schemaVersion' IS DISTINCT FROM '1'::JSONB OR inventory->>'completeness' IS DISTINCT FROM 'COMPLETE'$anchor$; + replacement TEXT := $replacement$ IF (( + (inventory->>'schema' = 'world-selected-publication-artifact-inventory/v1' + AND inventory->'schemaVersion' = '1'::JSONB + AND model->>'modelId' = 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1' + AND model->'graphSchemaVersion' = '2'::JSONB + AND checkpoint->'digestSchemaVersion' = '3'::JSONB + AND selector->'request'->'digestSchemaVersion' = '3'::JSONB + AND NOT (model ? 'inboundSourceClosure') + AND (SELECT count(*) FROM jsonb_object_keys( + CASE WHEN jsonb_typeof(model) = 'object' THEN model ELSE '{}'::JSONB END)) = 16) + OR + (inventory->>'schema' = 'world-selected-publication-artifact-inventory/v2' + AND inventory->'schemaVersion' = '2'::JSONB + AND model->>'modelId' = 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_INBOUND_EMPTY_V1' + AND model->'graphSchemaVersion' = '3'::JSONB + AND checkpoint->'digestSchemaVersion' = '4'::JSONB + AND selector->'request'->'digestSchemaVersion' = '4'::JSONB + AND (SELECT count(*) FROM jsonb_object_keys( + CASE WHEN jsonb_typeof(model) = 'object' THEN model ELSE '{}'::JSONB END)) = 17 + AND model ?& ARRAY['modelId', 'graphSchemaVersion', 'graphDigest', + 'topologyResultDigest', 'familyCounts', 'regionGeneratorInputs', + 'generationRuleFields', 'regionFields', 'zoneFields', 'roomFields', + 'roomExitFields', 'spawnBindingFields', 'spawnBindingInputs', + 'generationRuleInputCount', 'spawnBindingCount', 'appliedEpochs', + 'inboundSourceClosure'] + AND model->'inboundSourceClosure' IS NOT DISTINCT FROM + '{"schemaVersion":1,"familyCounts":[{"family":"WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING","count":0}]}'::JSONB) + ) IS NOT TRUE) OR inventory->>'completeness' IS DISTINCT FROM 'COMPLETE'$replacement$; + legacy_model_anchor TEXT := $anchor$ OR model->>'modelId' IS DISTINCT FROM 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1' + OR model->'graphSchemaVersion' IS DISTINCT FROM '2'::JSONB$anchor$; + legacy_model_replacement TEXT := ''; +BEGIN + SELECT pg_get_functiondef(inventory_function) INTO STRICT original_definition; + IF (length(original_definition) - length(replace(original_definition, anchor, ''))) + / length(anchor) <> 1 + OR (length(original_definition) - length(replace(original_definition, legacy_model_anchor, ''))) + / length(legacy_model_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V56 selected inventory schema-1 profile guard'; + END IF; + original_definition := replace(original_definition, anchor, replacement); + -- Model id and graph version are validated as exact paired profiles above; retain the + -- generation-rule and artifact-decision restrictions below for both profiles. + original_definition := replace(original_definition, legacy_model_anchor, legacy_model_replacement); + EXECUTE original_definition; +END; +$migration$; + +-- Correlate the additive database discriminator with immutable bytes on the SQL owner path too. +DO $migration$ +DECLARE + operation_function REGPROCEDURE := + '"${serviceSchema}".world_require_publication_operation_account_binding(bytea,uuid,bytea)'::REGPROCEDURE; + original_definition TEXT; + declaration_anchor TEXT := $anchor$ public_inventory BYTEA; public_digest BYTEA; private_inventory JSONB; expected_public JSONB; model JSONB;$anchor$; + declaration_replacement TEXT := $replacement$ public_inventory BYTEA; public_digest BYTEA; private_inventory JSONB; expected_public JSONB; model JSONB; + inventory_schema_version SMALLINT;$replacement$; + select_anchor TEXT := $anchor$ SELECT convert_from(i.inventory_bytes, 'UTF8')::JSONB INTO STRICT private_inventory + FROM "${serviceSchema}".world_selected_publication_artifact_inventory i$anchor$; + select_replacement TEXT := $replacement$ SELECT i.inventory_schema_version, convert_from(i.inventory_bytes, 'UTF8')::JSONB + INTO STRICT inventory_schema_version, private_inventory + FROM "${serviceSchema}".world_selected_publication_artifact_inventory i$replacement$; + projection_anchor TEXT := $anchor$ IF jsonb_typeof(private_inventory) IS DISTINCT FROM 'object'$anchor$; + projection_replacement TEXT := $replacement$ IF private_inventory->'schemaVersion' IS DISTINCT FROM to_jsonb(inventory_schema_version) + OR jsonb_typeof(private_inventory) IS DISTINCT FROM 'object'$replacement$; +BEGIN + SELECT pg_get_functiondef(operation_function) INTO STRICT original_definition; + IF (length(original_definition) - length(replace(original_definition, declaration_anchor, ''))) + / length(declaration_anchor) <> 1 + OR (length(original_definition) - length(replace(original_definition, select_anchor, ''))) + / length(select_anchor) <> 1 + OR (length(original_definition) - length(replace(original_definition, projection_anchor, ''))) + / length(projection_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact V56 World inventory discriminator/readback guards'; + END IF; + original_definition := replace(original_definition, declaration_anchor, declaration_replacement); + original_definition := replace(original_definition, select_anchor, select_replacement); + original_definition := replace(original_definition, projection_anchor, projection_replacement); + EXECUTE original_definition; +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1035__world_start_session_execution_terminal_fence.sql b/services/world-management-service/src/main/resources/db/migration/V1035__world_start_session_execution_terminal_fence.sql new file mode 100644 index 0000000000..63a1e4bf82 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1035__world_start_session_execution_terminal_fence.sql @@ -0,0 +1,817 @@ +-- A World preparation operation is retained before its execution transaction so that a later +-- serialized abort can name the exact original tuple and source binding without re-reading remote +-- sources. EXECUTING is visible only inside the one materialization transaction and may never +-- commit; COMMITTED includes both the V35 rows and V34 association, while ABORTED fences retries. +-- Historical V35/V34 rows are deliberately not backfilled into this operation ledger. +CREATE SEQUENCE world_canonical_instance_execution_fence_seq AS BIGINT MINVALUE 1; + +CREATE TABLE world_canonical_instance_execution ( + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + control_plane_request_id VARCHAR(128) NOT NULL, + canonical_game_instance_id UUID NOT NULL, + canonical_world_slug VARCHAR(120) NOT NULL, + game_template_id BIGINT NOT NULL, + original_post_authorization_tuple BYTEA NOT NULL + CHECK (octet_length(original_post_authorization_tuple) BETWEEN 1 AND 262144), + original_post_authorization_tuple_sha256 VARCHAR(64) NOT NULL + CHECK (original_post_authorization_tuple_sha256 ~ '^[0-9a-f]{64}$'), + account_world_participation_id UUID NOT NULL, + account_world_participation_fence BIGINT NOT NULL CHECK (account_world_participation_fence > 0), + game_session_owner_attempt_id UUID NOT NULL, + game_session_owner_fence BIGINT NOT NULL CHECK (game_session_owner_fence > 0), + preparation_input_digest VARCHAR(71) NOT NULL + CHECK (preparation_input_digest ~ '^sha256:[0-9a-f]{64}$'), + preparation_input_json TEXT NOT NULL CHECK (length(preparation_input_json) > 0), + world_execution_fence BIGINT NOT NULL UNIQUE CHECK (world_execution_fence > 0), + operation_state VARCHAR(16) NOT NULL + CHECK (operation_state IN ('PENDING', 'EXECUTING', 'COMMITTED', 'ABORTED')), + execution_claimed BOOLEAN NOT NULL DEFAULT FALSE, + active_transaction_id BIGINT, + world_instance_id BIGINT REFERENCES world_instance(id) ON DELETE RESTRICT + DEFERRABLE INITIALLY DEFERRED, + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + terminal_at TIMESTAMPTZ, + PRIMARY KEY (target_namespace, canonical_tenant_id, control_plane_request_id), + UNIQUE (canonical_game_instance_id), + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (account_world_participation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (game_session_owner_attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (game_template_id > 0), + CHECK ( + (operation_state = 'PENDING' AND active_transaction_id IS NULL + AND world_instance_id IS NULL AND terminal_at IS NULL) + OR (operation_state = 'EXECUTING' AND execution_claimed IS TRUE + AND active_transaction_id > 0 + AND world_instance_id IS NULL AND terminal_at IS NULL) + OR (operation_state = 'COMMITTED' AND execution_claimed IS TRUE + AND active_transaction_id IS NULL + AND world_instance_id > 0 AND terminal_at IS NOT NULL) + OR (operation_state = 'ABORTED' AND active_transaction_id IS NULL + AND world_instance_id IS NULL AND terminal_at IS NOT NULL) + ) +); +-- [jooq ignore start] +REVOKE ALL ON world_canonical_instance_execution FROM PUBLIC; +REVOKE ALL ON SEQUENCE world_canonical_instance_execution_fence_seq FROM PUBLIC; + +CREATE FUNCTION world_validate_canonical_instance_execution_input( + p_input_json TEXT, + p_input_digest TEXT, + p_original_tuple BYTEA, + p_account_participation_id UUID, + p_account_participation_fence BIGINT, + p_game_session_attempt_id UUID, + p_game_session_fence BIGINT, + p_canonical_game_instance_id UUID +) RETURNS VOID +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + input JSONB; + tuple_value JSONB; + original JSONB; + descriptor JSONB; + action_scope JSONB; + target JSONB; + target_owner JSONB; +BEGIN + IF p_input_json IS NULL OR length(p_input_json) = 0 + OR p_input_digest IS NULL OR p_input_digest !~ '^sha256:[0-9a-f]{64}$' + OR p_input_digest IS DISTINCT FROM 'sha256:' || encode(sha256(convert_to(p_input_json, 'UTF8')), 'hex') + OR p_original_tuple IS NULL OR octet_length(p_original_tuple) NOT BETWEEN 1 AND 262144 + OR p_account_participation_id IS NULL + OR p_account_participation_id = '00000000-0000-0000-0000-000000000000'::UUID + OR p_account_participation_fence IS NULL OR p_account_participation_fence <= 0 + OR p_game_session_attempt_id IS NULL + OR p_game_session_attempt_id = '00000000-0000-0000-0000-000000000000'::UUID + OR p_game_session_fence IS NULL OR p_game_session_fence <= 0 + OR p_canonical_game_instance_id IS NULL + OR p_canonical_game_instance_id = '00000000-0000-0000-0000-000000000000'::UUID THEN + RAISE EXCEPTION 'World execution identity or preparation input is malformed' + USING ERRCODE = '23514'; + END IF; + + input := p_input_json::JSONB; + tuple_value := convert_from(p_original_tuple, 'UTF8')::JSONB; + original := tuple_value->'preAuthorizationReservationTuple'; + action_scope := tuple_value->'scope'; + target := tuple_value->'target'; + target_owner := tuple_value->'targetOwner'; + descriptor := (input->'gameSessionReadEvidence'->>'descriptorJson')::JSONB; + IF tuple_value->>'tupleSchemaId' IS DISTINCT FROM 'postAuthorizationExecutionTuple' + OR tuple_value->>'tupleSchemaVersion' IS DISTINCT FROM '1' + OR tuple_value->>'issuanceKind' IS DISTINCT FROM 'human_operator' + OR tuple_value->>'controlPlaneRequestId' IS DISTINCT FROM original->'actionFamilyRequestIdentity'->>'requestId' + OR action_scope->>'targetNamespace' IS DISTINCT FROM input->'identity'->>'targetNamespace' + OR action_scope->>'tenantId' IS DISTINCT FROM input->'identity'->>'canonicalTenantId' + OR tuple_value->>'controlPlaneRequestId' IS DISTINCT FROM input->'identity'->>'controlPlaneRequestId' + OR target_owner->>'ownerService' IS DISTINCT FROM 'game-session-service' + OR original->>'actionFamily' IS DISTINCT FROM 'StartSession' + OR (target->>'gameTemplateId')::BIGINT IS DISTINCT FROM (descriptor->>'gameTemplateId')::BIGINT + OR input->'identity'->>'canonicalGameInstanceId' IS DISTINCT FROM p_canonical_game_instance_id::TEXT + OR input->'gameSessionReadEvidence'->>'canonicalGameInstanceId' IS DISTINCT FROM p_canonical_game_instance_id::TEXT + OR input->'gameSessionReadRequest'->>'canonicalGameInstanceId' IS DISTINCT FROM p_canonical_game_instance_id::TEXT + OR input->'identity'->>'targetNamespace' IS DISTINCT FROM input->'gameSessionReadEvidence'->>'targetNamespace' + OR input->'identity'->>'canonicalTenantId' IS DISTINCT FROM input->'gameSessionReadEvidence'->>'canonicalTenantId' + OR input->'identity'->>'worldSlug' IS DISTINCT FROM input->'gameSessionReadEvidence'->>'worldSlug' + OR input->'identity'->>'controlPlaneRequestId' IS DISTINCT FROM input->'gameSessionReadEvidence'->>'controlPlaneRequestId' + OR tuple_value->'authorityEvidenceBundle'->'accountProjectionEvidence'->>'expiresAt' IS NULL THEN + RAISE EXCEPTION 'World execution identity differs from the exact StartSession tuple or World target' + USING ERRCODE = '23514'; + END IF; +END; +$$; +REVOKE ALL ON FUNCTION world_validate_canonical_instance_execution_input(TEXT, TEXT, BYTEA, UUID, BIGINT, UUID, BIGINT, UUID) FROM PUBLIC; + +CREATE FUNCTION world_lock_canonical_instance_execution( + p_target_namespace TEXT, p_canonical_tenant_id UUID, + p_control_plane_request_id TEXT, p_canonical_game_instance_id UUID +) RETURNS VOID +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + -- The request lock comes first so a substituted canonical target cannot race the original + -- request. The target lock then serializes different requests aimed at the same World target. + PERFORM pg_advisory_xact_lock(hashtextextended( + 'world-canonical-execution-request:' || p_target_namespace || ':' + || p_canonical_tenant_id::TEXT || ':' || p_control_plane_request_id, 0)); + PERFORM pg_advisory_xact_lock(hashtextextended( + 'world-canonical-execution-target:' || p_canonical_game_instance_id::TEXT, 0)); +END; +$$; +REVOKE ALL ON FUNCTION world_lock_canonical_instance_execution(TEXT, UUID, TEXT, UUID) FROM PUBLIC; + +CREATE FUNCTION world_persist_canonical_instance_execution_intent( + p_input_json TEXT, p_input_digest TEXT, p_original_tuple BYTEA, + p_account_participation_id UUID, p_account_participation_fence BIGINT, + p_game_session_attempt_id UUID, p_game_session_fence BIGINT, + p_canonical_game_instance_id UUID +) RETURNS BIGINT +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + input JSONB; + tuple_value JSONB; + projection_expiry TIMESTAMPTZ; + v_target_namespace TEXT; + v_canonical_tenant_id UUID; + v_request_id TEXT; + v_world_slug TEXT; + v_game_template_id BIGINT; + prior "${serviceSchema}".world_canonical_instance_execution%ROWTYPE; +BEGIN + PERFORM "${serviceSchema}".world_validate_canonical_instance_execution_input( + p_input_json, p_input_digest, p_original_tuple, + p_account_participation_id, p_account_participation_fence, + p_game_session_attempt_id, p_game_session_fence, p_canonical_game_instance_id); + input := p_input_json::JSONB; + tuple_value := convert_from(p_original_tuple, 'UTF8')::JSONB; + v_target_namespace := input->'identity'->>'targetNamespace'; + v_canonical_tenant_id := (input->'identity'->>'canonicalTenantId')::UUID; + v_request_id := input->'identity'->>'controlPlaneRequestId'; + v_world_slug := input->'identity'->>'worldSlug'; + v_game_template_id := (((input->'gameSessionReadEvidence'->>'descriptorJson')::JSONB)->>'gameTemplateId')::BIGINT; + projection_expiry := (tuple_value->'authorityEvidenceBundle'->'accountProjectionEvidence'->>'expiresAt')::TIMESTAMPTZ; + + PERFORM "${serviceSchema}".world_lock_canonical_instance_execution( + v_target_namespace, v_canonical_tenant_id, v_request_id, p_canonical_game_instance_id); + -- Use the database wall clock after both shared identity locks; transaction-start timestamps + -- would admit a transaction that waited past the original Account bound. + IF projection_expiry <= clock_timestamp() THEN + RAISE EXCEPTION 'Original StartSession authorization expired before World intent retention' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO prior FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.target_namespace = v_target_namespace + AND e.canonical_tenant_id = v_canonical_tenant_id + AND e.control_plane_request_id = v_request_id + FOR UPDATE; + IF FOUND THEN + IF prior.canonical_game_instance_id IS DISTINCT FROM p_canonical_game_instance_id + OR prior.canonical_world_slug IS DISTINCT FROM v_world_slug + OR prior.game_template_id IS DISTINCT FROM v_game_template_id + OR prior.original_post_authorization_tuple IS DISTINCT FROM p_original_tuple + OR prior.account_world_participation_id IS DISTINCT FROM p_account_participation_id + OR prior.account_world_participation_fence IS DISTINCT FROM p_account_participation_fence + OR prior.game_session_owner_attempt_id IS DISTINCT FROM p_game_session_attempt_id + OR prior.game_session_owner_fence IS DISTINCT FROM p_game_session_fence + OR prior.preparation_input_digest IS DISTINCT FROM p_input_digest + OR prior.preparation_input_json IS DISTINCT FROM p_input_json THEN + RAISE EXCEPTION 'World execution request is already bound to a different full identity' + USING ERRCODE = '23505'; + END IF; + -- A previously retained intent is never automatically restarted. The caller performs an + -- exact terminal read; PENDING requires the shared-lock durable-abort path. + RETURN 0; + END IF; + + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_preparation p + WHERE p.canonical_game_instance_id = p_canonical_game_instance_id + OR (p.target_namespace = v_target_namespace + AND p.canonical_tenant_id = v_canonical_tenant_id + AND p.control_plane_request_id = v_request_id)) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_association a + WHERE a.canonical_game_instance_id = p_canonical_game_instance_id + OR (a.canonical_target_namespace = v_target_namespace + AND a.canonical_tenant_id = v_canonical_tenant_id + AND a.control_plane_request_id = v_request_id)) THEN + RAISE EXCEPTION 'Historical World materialization has no exact execution identity' + USING ERRCODE = '23514'; + END IF; + + INSERT INTO "${serviceSchema}".world_canonical_instance_execution ( + target_namespace, canonical_tenant_id, control_plane_request_id, + canonical_game_instance_id, canonical_world_slug, game_template_id, + original_post_authorization_tuple, original_post_authorization_tuple_sha256, + account_world_participation_id, account_world_participation_fence, + game_session_owner_attempt_id, game_session_owner_fence, + preparation_input_digest, preparation_input_json, world_execution_fence, + operation_state) + VALUES ( + v_target_namespace, v_canonical_tenant_id, v_request_id, + p_canonical_game_instance_id, v_world_slug, v_game_template_id, + p_original_tuple, encode(sha256(p_original_tuple), 'hex'), + p_account_participation_id, p_account_participation_fence, + p_game_session_attempt_id, p_game_session_fence, + p_input_digest, p_input_json, + nextval('"${serviceSchema}".world_canonical_instance_execution_fence_seq'), + 'PENDING') + RETURNING world_execution_fence INTO prior.world_execution_fence; + RETURN prior.world_execution_fence; +END; +$$; +REVOKE ALL ON FUNCTION world_persist_canonical_instance_execution_intent(TEXT, TEXT, BYTEA, UUID, BIGINT, UUID, BIGINT, UUID) FROM PUBLIC; + +CREATE FUNCTION world_claim_canonical_instance_execution( + p_input_json TEXT, p_input_digest TEXT, p_original_tuple BYTEA, + p_account_participation_id UUID, p_account_participation_fence BIGINT, + p_game_session_attempt_id UUID, p_game_session_fence BIGINT, + p_canonical_game_instance_id UUID +) RETURNS BIGINT +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + input JSONB; + tuple_value JSONB; + operation "${serviceSchema}".world_canonical_instance_execution%ROWTYPE; + v_target_namespace TEXT; + v_canonical_tenant_id UUID; + v_request_id TEXT; + original_expiry TIMESTAMPTZ; +BEGIN + PERFORM "${serviceSchema}".world_validate_canonical_instance_execution_input( + p_input_json, p_input_digest, p_original_tuple, + p_account_participation_id, p_account_participation_fence, + p_game_session_attempt_id, p_game_session_fence, p_canonical_game_instance_id); + input := p_input_json::JSONB; + tuple_value := convert_from(p_original_tuple, 'UTF8')::JSONB; + v_target_namespace := input->'identity'->>'targetNamespace'; + v_canonical_tenant_id := (input->'identity'->>'canonicalTenantId')::UUID; + v_request_id := input->'identity'->>'controlPlaneRequestId'; + PERFORM "${serviceSchema}".world_lock_canonical_instance_execution( + v_target_namespace, v_canonical_tenant_id, v_request_id, p_canonical_game_instance_id); + original_expiry := (tuple_value->'authorityEvidenceBundle'->'accountProjectionEvidence'->>'expiresAt')::TIMESTAMPTZ; + IF original_expiry <= clock_timestamp() THEN + RAISE EXCEPTION 'Original StartSession authorization expired before World execution claim' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO operation FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.target_namespace = v_target_namespace + AND e.canonical_tenant_id = v_canonical_tenant_id + AND e.control_plane_request_id = v_request_id + FOR UPDATE; + IF NOT FOUND + OR operation.canonical_game_instance_id IS DISTINCT FROM p_canonical_game_instance_id + OR operation.original_post_authorization_tuple IS DISTINCT FROM p_original_tuple + OR operation.account_world_participation_id IS DISTINCT FROM p_account_participation_id + OR operation.account_world_participation_fence IS DISTINCT FROM p_account_participation_fence + OR operation.game_session_owner_attempt_id IS DISTINCT FROM p_game_session_attempt_id + OR operation.game_session_owner_fence IS DISTINCT FROM p_game_session_fence + OR operation.preparation_input_digest IS DISTINCT FROM p_input_digest + OR operation.preparation_input_json IS DISTINCT FROM p_input_json THEN + RAISE EXCEPTION 'World execution claim differs from the exact original full identity' + USING ERRCODE = '23514'; + END IF; + IF operation.operation_state = 'COMMITTED' THEN + RETURN 0; + END IF; + IF operation.operation_state <> 'PENDING' OR operation.execution_claimed THEN + RETURN 0; + END IF; + PERFORM set_config('world.canonical_claim_namespace', operation.target_namespace, TRUE); + PERFORM set_config('world.canonical_claim_tenant', operation.canonical_tenant_id::TEXT, TRUE); + PERFORM set_config('world.canonical_claim_request', operation.control_plane_request_id, TRUE); + PERFORM set_config('world.canonical_claim_target', operation.canonical_game_instance_id::TEXT, TRUE); + PERFORM set_config('world.canonical_claim_fence', operation.world_execution_fence::TEXT, TRUE); + UPDATE "${serviceSchema}".world_canonical_instance_execution e + SET execution_claimed = TRUE + WHERE e.target_namespace = operation.target_namespace + AND e.canonical_tenant_id = operation.canonical_tenant_id + AND e.control_plane_request_id = operation.control_plane_request_id; + RETURN operation.world_execution_fence; +END; +$$; +REVOKE ALL ON FUNCTION world_claim_canonical_instance_execution(TEXT, TEXT, BYTEA, UUID, BIGINT, UUID, BIGINT, UUID) FROM PUBLIC; + +CREATE FUNCTION world_begin_canonical_instance_execution( + p_input_json TEXT, p_input_digest TEXT, p_original_tuple BYTEA, + p_account_participation_id UUID, p_account_participation_fence BIGINT, + p_game_session_attempt_id UUID, p_game_session_fence BIGINT, + p_canonical_game_instance_id UUID, p_world_execution_fence BIGINT +) RETURNS BIGINT +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + input JSONB; + v_target_namespace TEXT; + v_canonical_tenant_id UUID; + v_request_id TEXT; + operation "${serviceSchema}".world_canonical_instance_execution%ROWTYPE; +BEGIN + PERFORM "${serviceSchema}".world_validate_canonical_instance_execution_input( + p_input_json, p_input_digest, p_original_tuple, + p_account_participation_id, p_account_participation_fence, + p_game_session_attempt_id, p_game_session_fence, p_canonical_game_instance_id); + input := p_input_json::JSONB; + v_target_namespace := input->'identity'->>'targetNamespace'; + v_canonical_tenant_id := (input->'identity'->>'canonicalTenantId')::UUID; + v_request_id := input->'identity'->>'controlPlaneRequestId'; + PERFORM "${serviceSchema}".world_lock_canonical_instance_execution( + v_target_namespace, v_canonical_tenant_id, v_request_id, p_canonical_game_instance_id); + + SELECT * INTO operation FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.target_namespace = v_target_namespace + AND e.canonical_tenant_id = v_canonical_tenant_id + AND e.control_plane_request_id = v_request_id + FOR UPDATE; + IF NOT FOUND + OR operation.canonical_game_instance_id IS DISTINCT FROM p_canonical_game_instance_id + OR operation.original_post_authorization_tuple IS DISTINCT FROM p_original_tuple + OR operation.account_world_participation_id IS DISTINCT FROM p_account_participation_id + OR operation.account_world_participation_fence IS DISTINCT FROM p_account_participation_fence + OR operation.game_session_owner_attempt_id IS DISTINCT FROM p_game_session_attempt_id + OR operation.game_session_owner_fence IS DISTINCT FROM p_game_session_fence + OR operation.preparation_input_digest IS DISTINCT FROM p_input_digest + OR operation.preparation_input_json IS DISTINCT FROM p_input_json + OR operation.world_execution_fence IS DISTINCT FROM p_world_execution_fence THEN + RAISE EXCEPTION 'World execution intent does not match the exact original full identity' + USING ERRCODE = '23514'; + END IF; + IF operation.operation_state = 'COMMITTED' THEN + -- The caller must perform a separate read-only exact terminal readback. No V35 call or + -- operation update occurs on this branch. + RETURN 0; + END IF; + IF operation.operation_state <> 'PENDING' OR NOT operation.execution_claimed THEN + RAISE EXCEPTION 'World execution intent is terminal or already in flight' + USING ERRCODE = '23514'; + END IF; + + PERFORM set_config('world.canonical_execution_namespace', operation.target_namespace, TRUE); + PERFORM set_config('world.canonical_execution_tenant', operation.canonical_tenant_id::TEXT, TRUE); + PERFORM set_config('world.canonical_execution_request', operation.control_plane_request_id, TRUE); + PERFORM set_config('world.canonical_execution_target', operation.canonical_game_instance_id::TEXT, TRUE); + PERFORM set_config('world.canonical_execution_fence', operation.world_execution_fence::TEXT, TRUE); + PERFORM set_config('world.canonical_execution_input_digest', operation.preparation_input_digest, TRUE); + UPDATE "${serviceSchema}".world_canonical_instance_execution e + SET operation_state = 'EXECUTING', active_transaction_id = txid_current() + WHERE e.target_namespace = operation.target_namespace + AND e.canonical_tenant_id = operation.canonical_tenant_id + AND e.control_plane_request_id = operation.control_plane_request_id; + RETURN operation.world_execution_fence; +END; +$$; +REVOKE ALL ON FUNCTION world_begin_canonical_instance_execution(TEXT, TEXT, BYTEA, UUID, BIGINT, UUID, BIGINT, UUID, BIGINT) FROM PUBLIC; + +CREATE FUNCTION world_require_active_canonical_instance_execution( + p_input_json TEXT, p_input_digest TEXT +) RETURNS VOID +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + operation "${serviceSchema}".world_canonical_instance_execution%ROWTYPE; + original_tuple JSONB; + original_expiry TIMESTAMPTZ; +BEGIN + SELECT * INTO operation FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.target_namespace = current_setting('world.canonical_execution_namespace', TRUE) + AND e.canonical_tenant_id::TEXT = current_setting('world.canonical_execution_tenant', TRUE) + AND e.control_plane_request_id = current_setting('world.canonical_execution_request', TRUE) + AND e.canonical_game_instance_id::TEXT = current_setting('world.canonical_execution_target', TRUE) + AND e.world_execution_fence::TEXT = current_setting('world.canonical_execution_fence', TRUE) + AND e.preparation_input_digest = p_input_digest + AND e.preparation_input_json = p_input_json + AND e.operation_state = 'EXECUTING' + AND e.active_transaction_id = txid_current(); + IF NOT FOUND THEN + RAISE EXCEPTION 'V35 requires the exact current World execution identity and fence' + USING ERRCODE = '23514'; + END IF; + original_tuple := convert_from(operation.original_post_authorization_tuple, 'UTF8')::JSONB; + original_expiry := (original_tuple->'authorityEvidenceBundle'->'accountProjectionEvidence'->>'expiresAt')::TIMESTAMPTZ; + -- This hook is inserted after V35's publication-owner, canonical-target, and request locks. + IF original_expiry <= clock_timestamp() THEN + RAISE EXCEPTION 'Original StartSession authorization expired before World execution admission' + USING ERRCODE = '23514'; + END IF; +END; +$$; +REVOKE ALL ON FUNCTION world_require_active_canonical_instance_execution(TEXT, TEXT) FROM PUBLIC; + +-- Preserve the reviewed V35/V40/V42/V61 source guards as an owner-private inner implementation. +ALTER FUNCTION world_prepare_canonical_instance(TEXT, TEXT) + RENAME TO world_prepare_canonical_instance_v61_impl; + +CREATE FUNCTION world_prepare_canonical_instance(p_input_json TEXT, p_input_digest TEXT) +RETURNS TABLE(world_instance_id BIGINT, private_game_instance_key BIGINT) +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + RETURN QUERY SELECT * + FROM "${serviceSchema}".world_prepare_canonical_instance_v61_impl(p_input_json, p_input_digest); +END; +$$; +REVOKE ALL ON FUNCTION world_prepare_canonical_instance(TEXT, TEXT) FROM PUBLIC; +REVOKE ALL ON FUNCTION world_prepare_canonical_instance_v61_impl(TEXT, TEXT) FROM PUBLIC; + +-- The ordinary application call path enters the operation lock before the V35 owner/publication +-- locks; the expiry hook above rechecks only after V35 has acquired all of its own locks. +DO $migration$ +DECLARE + preparation_function REGPROCEDURE := + '"${serviceSchema}".world_prepare_canonical_instance_v61_impl(text,text)'::REGPROCEDURE; + original_definition TEXT; + lock_anchor TEXT := $anchor$ SELECT * INTO prior FROM "${serviceSchema}".world_canonical_instance_preparation$anchor$; + lock_replacement TEXT := $replacement$ PERFORM "${serviceSchema}".world_require_active_canonical_instance_execution( + p_input_json, p_input_digest); + + SELECT * INTO prior FROM "${serviceSchema}".world_canonical_instance_preparation$replacement$; +BEGIN + SELECT pg_get_functiondef(preparation_function) INTO STRICT original_definition; + IF (length(original_definition) - length(replace(original_definition, lock_anchor, ''))) + / length(lock_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected one post-V61 canonical preparation prior-row lookup'; + END IF; + EXECUTE replace(original_definition, lock_anchor, lock_replacement); +END; +$migration$; + +CREATE FUNCTION world_execution_has_exact_materialized_result( + p_operation "${serviceSchema}".world_canonical_instance_execution, + p_world_instance_id BIGINT +) RETURNS BOOLEAN +LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ + SELECT p_world_instance_id IS NOT NULL AND p_world_instance_id > 0 AND EXISTS ( + SELECT 1 + FROM world_canonical_instance_preparation p + JOIN world_canonical_instance_association a + ON a.canonical_game_instance_id = p.canonical_game_instance_id + AND a.world_instance_id = p.world_instance_id + WHERE p.canonical_game_instance_id = (p_operation).canonical_game_instance_id + AND p.target_namespace = (p_operation).target_namespace + AND p.canonical_tenant_id = (p_operation).canonical_tenant_id + AND p.control_plane_request_id = (p_operation).control_plane_request_id + AND p.input_digest = (p_operation).preparation_input_digest + AND p.input_json = (p_operation).preparation_input_json + AND p.world_instance_id = p_world_instance_id + AND a.canonical_target_namespace = (p_operation).target_namespace + AND a.canonical_tenant_id = (p_operation).canonical_tenant_id + AND a.control_plane_request_id = (p_operation).control_plane_request_id + AND a.game_template_id = (p_operation).game_template_id) +$$; +REVOKE ALL ON FUNCTION world_execution_has_exact_materialized_result("${serviceSchema}".world_canonical_instance_execution, BIGINT) FROM PUBLIC; + +CREATE FUNCTION world_commit_canonical_instance_execution(p_world_instance_id BIGINT) +RETURNS VOID +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + operation "${serviceSchema}".world_canonical_instance_execution%ROWTYPE; +BEGIN + SELECT * INTO operation FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.target_namespace = current_setting('world.canonical_execution_namespace', TRUE) + AND e.canonical_tenant_id::TEXT = current_setting('world.canonical_execution_tenant', TRUE) + AND e.control_plane_request_id = current_setting('world.canonical_execution_request', TRUE) + AND e.canonical_game_instance_id::TEXT = current_setting('world.canonical_execution_target', TRUE) + AND e.world_execution_fence::TEXT = current_setting('world.canonical_execution_fence', TRUE) + AND e.preparation_input_digest = current_setting('world.canonical_execution_input_digest', TRUE) + AND e.operation_state = 'EXECUTING' + AND e.active_transaction_id = txid_current() + FOR UPDATE; + IF NOT FOUND OR p_world_instance_id IS NULL OR p_world_instance_id <= 0 + OR NOT "${serviceSchema}".world_execution_has_exact_materialized_result( + operation, p_world_instance_id) THEN + RAISE EXCEPTION 'World execution cannot commit without its exact V35 preparation and V34 association' + USING ERRCODE = '23514'; + END IF; + UPDATE "${serviceSchema}".world_canonical_instance_execution e + SET operation_state = 'COMMITTED', active_transaction_id = NULL, + world_instance_id = p_world_instance_id, terminal_at = clock_timestamp() + WHERE e.target_namespace = operation.target_namespace + AND e.canonical_tenant_id = operation.canonical_tenant_id + AND e.control_plane_request_id = operation.control_plane_request_id; +END; +$$; +REVOKE ALL ON FUNCTION world_commit_canonical_instance_execution(BIGINT) FROM PUBLIC; + +CREATE FUNCTION world_abort_canonical_instance_execution( + p_target_namespace TEXT, p_canonical_tenant_id UUID, p_control_plane_request_id TEXT, + p_canonical_game_instance_id UUID, p_preparation_input_json TEXT, p_preparation_input_digest TEXT, + p_original_tuple BYTEA, p_account_participation_id UUID, p_account_participation_fence BIGINT, + p_game_session_attempt_id UUID, p_game_session_fence BIGINT +) RETURNS TABLE(operation_state TEXT, world_execution_fence BIGINT, world_instance_id BIGINT) +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + operation "${serviceSchema}".world_canonical_instance_execution%ROWTYPE; + tuple_value JSONB; +BEGIN + PERFORM "${serviceSchema}".world_validate_canonical_instance_execution_input( + p_preparation_input_json, p_preparation_input_digest, p_original_tuple, + p_account_participation_id, p_account_participation_fence, + p_game_session_attempt_id, p_game_session_fence, p_canonical_game_instance_id); + IF p_original_tuple IS NULL OR p_preparation_input_digest !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Exact original identity is required for World abort' + USING ERRCODE = '23514'; + END IF; + tuple_value := convert_from(p_original_tuple, 'UTF8')::JSONB; + IF tuple_value->>'controlPlaneRequestId' IS DISTINCT FROM p_control_plane_request_id + OR tuple_value->'scope'->>'targetNamespace' IS DISTINCT FROM p_target_namespace + OR tuple_value->'scope'->>'tenantId' IS DISTINCT FROM p_canonical_tenant_id::TEXT THEN + RAISE EXCEPTION 'World abort identity differs from the original scoped StartSession tuple' + USING ERRCODE = '23514'; + END IF; + PERFORM "${serviceSchema}".world_lock_canonical_instance_execution( + p_target_namespace, p_canonical_tenant_id, p_control_plane_request_id, + p_canonical_game_instance_id); + PERFORM set_config('world.canonical_abort_namespace', p_target_namespace, TRUE); + PERFORM set_config('world.canonical_abort_tenant', p_canonical_tenant_id::TEXT, TRUE); + PERFORM set_config('world.canonical_abort_request', p_control_plane_request_id, TRUE); + PERFORM set_config('world.canonical_abort_target', p_canonical_game_instance_id::TEXT, TRUE); + SELECT * INTO operation FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.target_namespace = p_target_namespace + AND e.canonical_tenant_id = p_canonical_tenant_id + AND e.control_plane_request_id = p_control_plane_request_id + FOR UPDATE; + IF NOT FOUND THEN + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.canonical_game_instance_id = p_canonical_game_instance_id) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_preparation p + WHERE p.canonical_game_instance_id = p_canonical_game_instance_id + OR (p.target_namespace = p_target_namespace + AND p.canonical_tenant_id = p_canonical_tenant_id + AND p.control_plane_request_id = p_control_plane_request_id)) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_association a + WHERE a.canonical_game_instance_id = p_canonical_game_instance_id + OR (a.canonical_target_namespace = p_target_namespace + AND a.canonical_tenant_id = p_canonical_tenant_id + AND a.control_plane_request_id = p_control_plane_request_id)) THEN + RAISE EXCEPTION 'Historical or conflicting World rows make missing-operation abort unresolved' + USING ERRCODE = '23514'; + END IF; + INSERT INTO "${serviceSchema}".world_canonical_instance_execution ( + target_namespace, canonical_tenant_id, control_plane_request_id, + canonical_game_instance_id, canonical_world_slug, game_template_id, + original_post_authorization_tuple, original_post_authorization_tuple_sha256, + account_world_participation_id, account_world_participation_fence, + game_session_owner_attempt_id, game_session_owner_fence, + preparation_input_digest, preparation_input_json, world_execution_fence, + operation_state, terminal_at) + VALUES ( + p_target_namespace, p_canonical_tenant_id, p_control_plane_request_id, + p_canonical_game_instance_id, + (p_preparation_input_json::JSONB->'identity'->>'worldSlug'), + (((p_preparation_input_json::JSONB->'gameSessionReadEvidence'->>'descriptorJson')::JSONB)->>'gameTemplateId')::BIGINT, + p_original_tuple, encode(sha256(p_original_tuple), 'hex'), + p_account_participation_id, p_account_participation_fence, + p_game_session_attempt_id, p_game_session_fence, + p_preparation_input_digest, p_preparation_input_json, + nextval('"${serviceSchema}".world_canonical_instance_execution_fence_seq'), + 'ABORTED', clock_timestamp()) + RETURNING * INTO operation; + END IF; + IF operation.canonical_game_instance_id IS DISTINCT FROM p_canonical_game_instance_id + OR operation.canonical_world_slug IS DISTINCT FROM p_preparation_input_json::JSONB->'identity'->>'worldSlug' + OR operation.game_template_id IS DISTINCT FROM (((p_preparation_input_json::JSONB->'gameSessionReadEvidence'->>'descriptorJson')::JSONB)->>'gameTemplateId')::BIGINT + OR operation.preparation_input_digest IS DISTINCT FROM p_preparation_input_digest + OR operation.preparation_input_json IS DISTINCT FROM p_preparation_input_json + OR operation.original_post_authorization_tuple IS DISTINCT FROM p_original_tuple + OR operation.account_world_participation_id IS DISTINCT FROM p_account_participation_id + OR operation.account_world_participation_fence IS DISTINCT FROM p_account_participation_fence + OR operation.game_session_owner_attempt_id IS DISTINCT FROM p_game_session_attempt_id + OR operation.game_session_owner_fence IS DISTINCT FROM p_game_session_fence THEN + RAISE EXCEPTION 'World abort differs from the exact original full execution identity' + USING ERRCODE = '23514'; + END IF; + IF operation.operation_state = 'PENDING' THEN + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_preparation p + WHERE p.canonical_game_instance_id = operation.canonical_game_instance_id + OR (p.target_namespace = operation.target_namespace + AND p.canonical_tenant_id = operation.canonical_tenant_id + AND p.control_plane_request_id = operation.control_plane_request_id)) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_association a + WHERE a.canonical_game_instance_id = operation.canonical_game_instance_id + OR (a.canonical_target_namespace = operation.target_namespace + AND a.canonical_tenant_id = operation.canonical_tenant_id + AND a.control_plane_request_id = operation.control_plane_request_id)) THEN + RAISE EXCEPTION 'World has unbound materialization rows; operation remains unresolved' + USING ERRCODE = '23514'; + END IF; + UPDATE "${serviceSchema}".world_canonical_instance_execution e + SET operation_state = 'ABORTED', terminal_at = clock_timestamp() + WHERE e.target_namespace = operation.target_namespace + AND e.canonical_tenant_id = operation.canonical_tenant_id + AND e.control_plane_request_id = operation.control_plane_request_id; + operation.operation_state := 'ABORTED'; + ELSIF operation.operation_state NOT IN ('COMMITTED', 'ABORTED') THEN + RAISE EXCEPTION 'World execution is not in a durable terminal state' + USING ERRCODE = '23514'; + END IF; + operation_state := operation.operation_state; + world_execution_fence := operation.world_execution_fence; + world_instance_id := operation.world_instance_id; + RETURN NEXT; +END; +$$; +REVOKE ALL ON FUNCTION world_abort_canonical_instance_execution(TEXT, UUID, TEXT, UUID, TEXT, TEXT, BYTEA, UUID, BIGINT, UUID, BIGINT) FROM PUBLIC; + +CREATE FUNCTION world_enforce_canonical_instance_execution_transition() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + IF TG_OP = 'UPDATE' THEN + IF NEW.target_namespace IS DISTINCT FROM OLD.target_namespace + OR NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id + OR NEW.control_plane_request_id IS DISTINCT FROM OLD.control_plane_request_id + OR NEW.canonical_game_instance_id IS DISTINCT FROM OLD.canonical_game_instance_id + OR NEW.canonical_world_slug IS DISTINCT FROM OLD.canonical_world_slug + OR NEW.game_template_id IS DISTINCT FROM OLD.game_template_id + OR NEW.original_post_authorization_tuple IS DISTINCT FROM OLD.original_post_authorization_tuple + OR NEW.original_post_authorization_tuple_sha256 IS DISTINCT FROM OLD.original_post_authorization_tuple_sha256 + OR NEW.account_world_participation_id IS DISTINCT FROM OLD.account_world_participation_id + OR NEW.account_world_participation_fence IS DISTINCT FROM OLD.account_world_participation_fence + OR NEW.game_session_owner_attempt_id IS DISTINCT FROM OLD.game_session_owner_attempt_id + OR NEW.game_session_owner_fence IS DISTINCT FROM OLD.game_session_owner_fence + OR NEW.preparation_input_digest IS DISTINCT FROM OLD.preparation_input_digest + OR NEW.preparation_input_json IS DISTINCT FROM OLD.preparation_input_json + OR NEW.world_execution_fence IS DISTINCT FROM OLD.world_execution_fence + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'World execution identity is immutable and terminal states cannot be reopened' + USING ERRCODE = '23514'; + END IF; + IF OLD.operation_state = 'PENDING' AND NEW.operation_state = 'PENDING' THEN + IF OLD.execution_claimed OR NOT NEW.execution_claimed + OR OLD.active_transaction_id IS DISTINCT FROM NEW.active_transaction_id + OR OLD.world_instance_id IS DISTINCT FROM NEW.world_instance_id + OR OLD.terminal_at IS DISTINCT FROM NEW.terminal_at + OR current_setting('world.canonical_claim_namespace', TRUE) IS DISTINCT FROM NEW.target_namespace + OR current_setting('world.canonical_claim_tenant', TRUE) IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR current_setting('world.canonical_claim_request', TRUE) IS DISTINCT FROM NEW.control_plane_request_id + OR current_setting('world.canonical_claim_target', TRUE) IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR current_setting('world.canonical_claim_fence', TRUE) IS DISTINCT FROM NEW.world_execution_fence::TEXT THEN + RAISE EXCEPTION 'World execution intent may be claimed only once by its exact serialization fence' + USING ERRCODE = '23514'; + END IF; + ELSIF OLD.operation_state = 'PENDING' AND NEW.operation_state = 'EXECUTING' THEN + IF NOT OLD.execution_claimed OR NOT NEW.execution_claimed + OR NEW.active_transaction_id IS DISTINCT FROM txid_current() + OR NEW.world_instance_id IS NOT NULL OR NEW.terminal_at IS NOT NULL + OR current_setting('world.canonical_execution_namespace', TRUE) IS DISTINCT FROM NEW.target_namespace + OR current_setting('world.canonical_execution_tenant', TRUE) IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR current_setting('world.canonical_execution_request', TRUE) IS DISTINCT FROM NEW.control_plane_request_id + OR current_setting('world.canonical_execution_target', TRUE) IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR current_setting('world.canonical_execution_fence', TRUE) IS DISTINCT FROM NEW.world_execution_fence::TEXT + OR current_setting('world.canonical_execution_input_digest', TRUE) IS DISTINCT FROM NEW.preparation_input_digest THEN + RAISE EXCEPTION 'World EXECUTING state requires its exact current transaction and execution fence' + USING ERRCODE = '23514'; + END IF; + ELSIF OLD.operation_state = 'PENDING' AND NEW.operation_state = 'ABORTED' THEN + IF NEW.execution_claimed IS DISTINCT FROM OLD.execution_claimed + OR NEW.active_transaction_id IS NOT NULL OR NEW.world_instance_id IS NOT NULL + OR NEW.terminal_at IS NULL + OR current_setting('world.canonical_abort_namespace', TRUE) IS DISTINCT FROM NEW.target_namespace + OR current_setting('world.canonical_abort_tenant', TRUE) IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR current_setting('world.canonical_abort_request', TRUE) IS DISTINCT FROM NEW.control_plane_request_id + OR current_setting('world.canonical_abort_target', TRUE) IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT THEN + RAISE EXCEPTION 'World ABORTED state requires its exact serialized terminal fence' + USING ERRCODE = '23514'; + END IF; + ELSIF OLD.operation_state = 'EXECUTING' AND NEW.operation_state = 'COMMITTED' THEN + IF OLD.active_transaction_id IS DISTINCT FROM txid_current() + OR NEW.execution_claimed IS DISTINCT FROM TRUE + OR NEW.active_transaction_id IS NOT NULL + OR NEW.terminal_at IS NULL + OR current_setting('world.canonical_execution_namespace', TRUE) IS DISTINCT FROM NEW.target_namespace + OR current_setting('world.canonical_execution_tenant', TRUE) IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR current_setting('world.canonical_execution_request', TRUE) IS DISTINCT FROM NEW.control_plane_request_id + OR current_setting('world.canonical_execution_target', TRUE) IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR current_setting('world.canonical_execution_fence', TRUE) IS DISTINCT FROM NEW.world_execution_fence::TEXT + OR current_setting('world.canonical_execution_input_digest', TRUE) IS DISTINCT FROM NEW.preparation_input_digest + OR NOT "${serviceSchema}".world_execution_has_exact_materialized_result(NEW, NEW.world_instance_id) THEN + RAISE EXCEPTION 'World COMMITTED state requires the current exact V35 preparation and V34 association' + USING ERRCODE = '23514'; + END IF; + ELSE + RAISE EXCEPTION 'World execution state transition is not permitted' + USING ERRCODE = '23514'; + END IF; + ELSIF NEW.operation_state = 'PENDING' THEN + IF NEW.execution_claimed OR NEW.active_transaction_id IS NOT NULL + OR NEW.world_instance_id IS NOT NULL OR NEW.terminal_at IS NOT NULL THEN + RAISE EXCEPTION 'World execution intent must be born unclaimed and PENDING' + USING ERRCODE = '23514'; + END IF; + ELSIF NEW.operation_state = 'ABORTED' THEN + IF NEW.execution_claimed OR NEW.active_transaction_id IS NOT NULL + OR NEW.world_instance_id IS NOT NULL OR NEW.terminal_at IS NULL + OR current_setting('world.canonical_abort_namespace', TRUE) IS DISTINCT FROM NEW.target_namespace + OR current_setting('world.canonical_abort_tenant', TRUE) IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR current_setting('world.canonical_abort_request', TRUE) IS DISTINCT FROM NEW.control_plane_request_id + OR current_setting('world.canonical_abort_target', TRUE) IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT THEN + RAISE EXCEPTION 'A born-ABORTED World operation requires its exact serialized abort fence' + USING ERRCODE = '23514'; + END IF; + ELSE + RAISE EXCEPTION 'World execution rows must be born PENDING or terminally ABORTED' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_world_canonical_instance_execution_transition + BEFORE INSERT OR UPDATE ON world_canonical_instance_execution + FOR EACH ROW EXECUTE FUNCTION world_enforce_canonical_instance_execution_transition(); +REVOKE ALL ON FUNCTION world_enforce_canonical_instance_execution_transition() FROM PUBLIC; + +CREATE FUNCTION world_require_canonical_instance_execution_terminal() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + final_state TEXT; +BEGIN + SELECT operation_state INTO final_state + FROM world_canonical_instance_execution + WHERE target_namespace = NEW.target_namespace + AND canonical_tenant_id = NEW.canonical_tenant_id + AND control_plane_request_id = NEW.control_plane_request_id; + IF final_state IS NULL OR final_state = 'EXECUTING' THEN + RAISE EXCEPTION 'World EXECUTING state cannot commit without exact terminal settlement' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER trg_world_canonical_instance_execution_no_inflight_commit + AFTER INSERT OR UPDATE ON world_canonical_instance_execution + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION world_require_canonical_instance_execution_terminal(); +REVOKE ALL ON FUNCTION world_require_canonical_instance_execution_terminal() FROM PUBLIC; + +CREATE FUNCTION world_guard_canonical_instance_association_execution() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + operation "${serviceSchema}".world_canonical_instance_execution%ROWTYPE; +BEGIN + SELECT * INTO operation FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.target_namespace = current_setting('world.canonical_execution_namespace', TRUE) + AND e.canonical_tenant_id::TEXT = current_setting('world.canonical_execution_tenant', TRUE) + AND e.control_plane_request_id = current_setting('world.canonical_execution_request', TRUE) + AND e.canonical_game_instance_id::TEXT = current_setting('world.canonical_execution_target', TRUE) + AND e.world_execution_fence::TEXT = current_setting('world.canonical_execution_fence', TRUE) + AND e.operation_state = 'EXECUTING' + AND e.active_transaction_id = txid_current() + FOR KEY SHARE; + IF NOT FOUND OR NEW.canonical_game_instance_id IS DISTINCT FROM operation.canonical_game_instance_id + OR NEW.canonical_target_namespace IS DISTINCT FROM operation.target_namespace + OR NEW.canonical_tenant_id IS DISTINCT FROM operation.canonical_tenant_id + OR NEW.control_plane_request_id IS DISTINCT FROM operation.control_plane_request_id + OR NEW.game_template_id IS DISTINCT FROM operation.game_template_id + OR NEW.world_instance_id IS NULL + OR NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_canonical_instance_preparation p + WHERE p.canonical_game_instance_id = operation.canonical_game_instance_id + AND p.target_namespace = operation.target_namespace + AND p.canonical_tenant_id = operation.canonical_tenant_id + AND p.control_plane_request_id = operation.control_plane_request_id + AND p.input_digest = operation.preparation_input_digest + AND p.input_json = operation.preparation_input_json + AND p.world_instance_id = NEW.world_instance_id) THEN + RAISE EXCEPTION 'V34 association requires the exact active World execution identity and fence' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_world_canonical_instance_association_00_execution + BEFORE INSERT ON world_canonical_instance_association + FOR EACH ROW EXECUTE FUNCTION world_guard_canonical_instance_association_execution(); +REVOKE ALL ON FUNCTION world_guard_canonical_instance_association_execution() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1036__world_original_start_session_attempt_admission.sql b/services/world-management-service/src/main/resources/db/migration/V1036__world_original_start_session_attempt_admission.sql new file mode 100644 index 0000000000..47deee4306 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1036__world_original_start_session_attempt_admission.sql @@ -0,0 +1,583 @@ +-- Fresh World execution intents retain Account's exact first original-attempt observation. +-- Existing V62 rows remain untouched and nullable; missing evidence never becomes migration data. +ALTER TABLE world_canonical_instance_execution + ADD COLUMN game_session_owner_mutation_id UUID, + ADD COLUMN original_attempt_read_request_id UUID, + ADD COLUMN original_game_session_lease_expires_at TIMESTAMPTZ, + ADD COLUMN original_attempt_evidence_bytes BYTEA, + ADD COLUMN original_attempt_evidence_sha256 VARCHAR(71); + +ALTER TABLE world_canonical_instance_execution + ADD CONSTRAINT ck_world_execution_original_attempt_witness + CHECK ( + (game_session_owner_mutation_id IS NULL + AND original_attempt_read_request_id IS NULL + AND original_game_session_lease_expires_at IS NULL + AND original_attempt_evidence_bytes IS NULL + AND original_attempt_evidence_sha256 IS NULL) + OR (game_session_owner_mutation_id IS NOT NULL + AND game_session_owner_mutation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND original_attempt_read_request_id IS NOT NULL + AND original_attempt_read_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND original_game_session_lease_expires_at IS NOT NULL + AND original_attempt_evidence_bytes IS NOT NULL + AND octet_length(original_attempt_evidence_bytes) BETWEEN 1 AND 525824 + AND original_attempt_evidence_sha256 IS NOT NULL + AND original_attempt_evidence_sha256 ~ '^sha256:[0-9a-f]{64}$' + AND original_attempt_evidence_sha256 = 'sha256:' || encode(sha256(original_attempt_evidence_bytes), 'hex')) + ); + +-- [jooq ignore start] +REVOKE ALL ON world_canonical_instance_execution FROM PUBLIC; + +-- Fresh operations use this function so the Account-returned exact observation is born with the +-- World-local identity and execution fence. A V62 row with absent witness fields is never upgraded. +CREATE FUNCTION world_persist_canonical_instance_execution_intent_with_original_attempt( + p_input_json TEXT, p_input_digest TEXT, p_original_tuple BYTEA, + p_account_participation_id UUID, p_account_participation_fence BIGINT, + p_game_session_attempt_id UUID, p_game_session_fence BIGINT, + p_canonical_game_instance_id UUID, + p_game_session_mutation_id UUID, p_attempt_read_request_id UUID, + p_original_game_session_lease_expires_at TIMESTAMPTZ, + p_original_attempt_evidence_bytes BYTEA, p_original_attempt_evidence_sha256 TEXT +) RETURNS BIGINT +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + input JSONB; + tuple_value JSONB; + projection_expiry TIMESTAMPTZ; + v_target_namespace TEXT; + v_canonical_tenant_id UUID; + v_request_id TEXT; + v_world_slug TEXT; + v_game_template_id BIGINT; + prior "${serviceSchema}".world_canonical_instance_execution%ROWTYPE; +BEGIN + PERFORM "${serviceSchema}".world_validate_canonical_instance_execution_input( + p_input_json, p_input_digest, p_original_tuple, + p_account_participation_id, p_account_participation_fence, + p_game_session_attempt_id, p_game_session_fence, p_canonical_game_instance_id); + IF p_game_session_mutation_id IS NULL + OR p_game_session_mutation_id = '00000000-0000-0000-0000-000000000000'::UUID + OR p_attempt_read_request_id IS NULL + OR p_attempt_read_request_id = '00000000-0000-0000-0000-000000000000'::UUID + OR p_original_game_session_lease_expires_at IS NULL + OR p_original_attempt_evidence_bytes IS NULL + OR octet_length(p_original_attempt_evidence_bytes) NOT BETWEEN 1 AND 525824 + OR p_original_attempt_evidence_sha256 IS DISTINCT FROM + 'sha256:' || encode(sha256(p_original_attempt_evidence_bytes), 'hex') THEN + RAISE EXCEPTION 'Exact Account original Game Session attempt observation is required' + USING ERRCODE = '23514'; + END IF; + + input := p_input_json::JSONB; + tuple_value := convert_from(p_original_tuple, 'UTF8')::JSONB; + v_target_namespace := input->'identity'->>'targetNamespace'; + v_canonical_tenant_id := (input->'identity'->>'canonicalTenantId')::UUID; + v_request_id := input->'identity'->>'controlPlaneRequestId'; + v_world_slug := input->'identity'->>'worldSlug'; + v_game_template_id := (((input->'gameSessionReadEvidence'->>'descriptorJson')::JSONB)->>'gameTemplateId')::BIGINT; + projection_expiry := (tuple_value->'authorityEvidenceBundle'->'accountProjectionEvidence'->>'expiresAt')::TIMESTAMPTZ; + + PERFORM "${serviceSchema}".world_lock_canonical_instance_execution( + v_target_namespace, v_canonical_tenant_id, v_request_id, p_canonical_game_instance_id); + -- Preliminary checks bound the retained intent. Actual admission repeats both expiries only + -- after all V35 owner locks, so a lock wait cannot admit a stale lease. + IF projection_expiry <= clock_timestamp() + OR p_original_game_session_lease_expires_at <= clock_timestamp() THEN + RAISE EXCEPTION 'Original StartSession authorization or Game Session lease expired before World intent retention' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO prior FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.target_namespace = v_target_namespace + AND e.canonical_tenant_id = v_canonical_tenant_id + AND e.control_plane_request_id = v_request_id + FOR UPDATE; + IF FOUND THEN + IF prior.canonical_game_instance_id IS DISTINCT FROM p_canonical_game_instance_id + OR prior.canonical_world_slug IS DISTINCT FROM v_world_slug + OR prior.game_template_id IS DISTINCT FROM v_game_template_id + OR prior.original_post_authorization_tuple IS DISTINCT FROM p_original_tuple + OR prior.account_world_participation_id IS DISTINCT FROM p_account_participation_id + OR prior.account_world_participation_fence IS DISTINCT FROM p_account_participation_fence + OR prior.game_session_owner_attempt_id IS DISTINCT FROM p_game_session_attempt_id + OR prior.game_session_owner_fence IS DISTINCT FROM p_game_session_fence + OR prior.game_session_owner_mutation_id IS DISTINCT FROM p_game_session_mutation_id + OR prior.original_attempt_read_request_id IS DISTINCT FROM p_attempt_read_request_id + OR prior.original_game_session_lease_expires_at IS DISTINCT FROM p_original_game_session_lease_expires_at + OR prior.original_attempt_evidence_bytes IS DISTINCT FROM p_original_attempt_evidence_bytes + OR prior.original_attempt_evidence_sha256 IS DISTINCT FROM p_original_attempt_evidence_sha256 + OR prior.preparation_input_digest IS DISTINCT FROM p_input_digest + OR prior.preparation_input_json IS DISTINCT FROM p_input_json THEN + RAISE EXCEPTION 'World execution request is already bound to a different or incomplete original owner observation' + USING ERRCODE = '23505'; + END IF; + RETURN 0; + END IF; + + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_preparation p + WHERE p.canonical_game_instance_id = p_canonical_game_instance_id + OR (p.target_namespace = v_target_namespace + AND p.canonical_tenant_id = v_canonical_tenant_id + AND p.control_plane_request_id = v_request_id)) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_association a + WHERE a.canonical_game_instance_id = p_canonical_game_instance_id + OR (a.canonical_target_namespace = v_target_namespace + AND a.canonical_tenant_id = v_canonical_tenant_id + AND a.control_plane_request_id = v_request_id)) THEN + RAISE EXCEPTION 'Historical World materialization has no exact execution identity' + USING ERRCODE = '23514'; + END IF; + + INSERT INTO "${serviceSchema}".world_canonical_instance_execution ( + target_namespace, canonical_tenant_id, control_plane_request_id, + canonical_game_instance_id, canonical_world_slug, game_template_id, + original_post_authorization_tuple, original_post_authorization_tuple_sha256, + account_world_participation_id, account_world_participation_fence, + game_session_owner_attempt_id, game_session_owner_fence, + game_session_owner_mutation_id, original_attempt_read_request_id, + original_game_session_lease_expires_at, original_attempt_evidence_bytes, + original_attempt_evidence_sha256, + preparation_input_digest, preparation_input_json, world_execution_fence, + operation_state) + VALUES ( + v_target_namespace, v_canonical_tenant_id, v_request_id, + p_canonical_game_instance_id, v_world_slug, v_game_template_id, + p_original_tuple, encode(sha256(p_original_tuple), 'hex'), + p_account_participation_id, p_account_participation_fence, + p_game_session_attempt_id, p_game_session_fence, + p_game_session_mutation_id, p_attempt_read_request_id, + p_original_game_session_lease_expires_at, p_original_attempt_evidence_bytes, + p_original_attempt_evidence_sha256, + p_input_digest, p_input_json, + nextval('"${serviceSchema}".world_canonical_instance_execution_fence_seq'), + 'PENDING') + RETURNING world_execution_fence INTO prior.world_execution_fence; + RETURN prior.world_execution_fence; +END; +$$; +REVOKE ALL ON FUNCTION world_persist_canonical_instance_execution_intent_with_original_attempt( + TEXT, TEXT, BYTEA, UUID, BIGINT, UUID, BIGINT, UUID, UUID, UUID, TIMESTAMPTZ, BYTEA, TEXT) FROM PUBLIC; + +-- Fresh claims and execution admission compare the full Account observation, not just the older +-- V62 tuple/participation/attempt projection. +CREATE FUNCTION world_claim_canonical_instance_execution_with_original_attempt( + p_input_json TEXT, p_input_digest TEXT, p_original_tuple BYTEA, + p_account_participation_id UUID, p_account_participation_fence BIGINT, + p_game_session_attempt_id UUID, p_game_session_fence BIGINT, + p_canonical_game_instance_id UUID, + p_game_session_mutation_id UUID, p_attempt_read_request_id UUID, + p_original_game_session_lease_expires_at TIMESTAMPTZ, + p_original_attempt_evidence_bytes BYTEA, p_original_attempt_evidence_sha256 TEXT +) RETURNS BIGINT +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + result_fence BIGINT; + identity JSONB := p_input_json::JSONB->'identity'; + operation "${serviceSchema}".world_canonical_instance_execution%ROWTYPE; +BEGIN + result_fence := "${serviceSchema}".world_claim_canonical_instance_execution( + p_input_json, p_input_digest, p_original_tuple, + p_account_participation_id, p_account_participation_fence, + p_game_session_attempt_id, p_game_session_fence, p_canonical_game_instance_id); + SELECT * INTO operation FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.target_namespace = identity->>'targetNamespace' + AND e.canonical_tenant_id = (identity->>'canonicalTenantId')::UUID + AND e.control_plane_request_id = identity->>'controlPlaneRequestId' + FOR UPDATE; + IF NOT FOUND + OR operation.game_session_owner_mutation_id IS DISTINCT FROM p_game_session_mutation_id + OR operation.original_attempt_read_request_id IS DISTINCT FROM p_attempt_read_request_id + OR operation.original_game_session_lease_expires_at IS DISTINCT FROM p_original_game_session_lease_expires_at + OR operation.original_attempt_evidence_bytes IS DISTINCT FROM p_original_attempt_evidence_bytes + OR operation.original_attempt_evidence_sha256 IS DISTINCT FROM p_original_attempt_evidence_sha256 THEN + RAISE EXCEPTION 'World execution claim differs from the exact Account owner observation' + USING ERRCODE = '23514'; + END IF; + RETURN result_fence; +END; +$$; +REVOKE ALL ON FUNCTION world_claim_canonical_instance_execution_with_original_attempt( + TEXT, TEXT, BYTEA, UUID, BIGINT, UUID, BIGINT, UUID, UUID, UUID, TIMESTAMPTZ, BYTEA, TEXT) FROM PUBLIC; + +CREATE FUNCTION world_begin_canonical_instance_execution_with_original_attempt( + p_input_json TEXT, p_input_digest TEXT, p_original_tuple BYTEA, + p_account_participation_id UUID, p_account_participation_fence BIGINT, + p_game_session_attempt_id UUID, p_game_session_fence BIGINT, + p_canonical_game_instance_id UUID, p_world_execution_fence BIGINT, + p_game_session_mutation_id UUID, p_attempt_read_request_id UUID, + p_original_game_session_lease_expires_at TIMESTAMPTZ, + p_original_attempt_evidence_bytes BYTEA, p_original_attempt_evidence_sha256 TEXT +) RETURNS BIGINT +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + result_fence BIGINT; + identity JSONB := p_input_json::JSONB->'identity'; + operation "${serviceSchema}".world_canonical_instance_execution%ROWTYPE; +BEGIN + result_fence := "${serviceSchema}".world_begin_canonical_instance_execution( + p_input_json, p_input_digest, p_original_tuple, + p_account_participation_id, p_account_participation_fence, + p_game_session_attempt_id, p_game_session_fence, + p_canonical_game_instance_id, p_world_execution_fence); + SELECT * INTO operation FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.target_namespace = identity->>'targetNamespace' + AND e.canonical_tenant_id = (identity->>'canonicalTenantId')::UUID + AND e.control_plane_request_id = identity->>'controlPlaneRequestId' + FOR UPDATE; + IF NOT FOUND + OR operation.game_session_owner_mutation_id IS DISTINCT FROM p_game_session_mutation_id + OR operation.original_attempt_read_request_id IS DISTINCT FROM p_attempt_read_request_id + OR operation.original_game_session_lease_expires_at IS DISTINCT FROM p_original_game_session_lease_expires_at + OR operation.original_attempt_evidence_bytes IS DISTINCT FROM p_original_attempt_evidence_bytes + OR operation.original_attempt_evidence_sha256 IS DISTINCT FROM p_original_attempt_evidence_sha256 THEN + RAISE EXCEPTION 'World execution admission differs from the exact Account owner observation' + USING ERRCODE = '23514'; + END IF; + RETURN result_fence; +END; +$$; +REVOKE ALL ON FUNCTION world_begin_canonical_instance_execution_with_original_attempt( + TEXT, TEXT, BYTEA, UUID, BIGINT, UUID, BIGINT, UUID, BIGINT, UUID, UUID, TIMESTAMPTZ, BYTEA, TEXT) FROM PUBLIC; + +-- Exact durable abort uses the same request/target serialization and binds the Account-returned +-- owner observation when it must create the terminal row. It never settles/releases Account itself. +CREATE FUNCTION world_abort_canonical_instance_execution_with_original_attempt( + p_target_namespace TEXT, p_canonical_tenant_id UUID, p_control_plane_request_id TEXT, + p_canonical_game_instance_id UUID, p_preparation_input_json TEXT, + p_preparation_input_digest TEXT, p_original_tuple BYTEA, + p_account_participation_id UUID, p_account_participation_fence BIGINT, + p_game_session_attempt_id UUID, p_game_session_fence BIGINT, + p_game_session_mutation_id UUID, p_attempt_read_request_id UUID, + p_original_game_session_lease_expires_at TIMESTAMPTZ, + p_original_attempt_evidence_bytes BYTEA, p_original_attempt_evidence_sha256 TEXT +) RETURNS TABLE(operation_state TEXT, world_execution_fence BIGINT, world_instance_id BIGINT) +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + operation "${serviceSchema}".world_canonical_instance_execution%ROWTYPE; + tuple_value JSONB; +BEGIN + PERFORM "${serviceSchema}".world_validate_canonical_instance_execution_input( + p_preparation_input_json, p_preparation_input_digest, p_original_tuple, + p_account_participation_id, p_account_participation_fence, + p_game_session_attempt_id, p_game_session_fence, p_canonical_game_instance_id); + IF p_game_session_mutation_id IS NULL + OR p_game_session_mutation_id = '00000000-0000-0000-0000-000000000000'::UUID + OR p_attempt_read_request_id IS NULL + OR p_attempt_read_request_id = '00000000-0000-0000-0000-000000000000'::UUID + OR p_original_game_session_lease_expires_at IS NULL + OR p_original_attempt_evidence_bytes IS NULL + OR octet_length(p_original_attempt_evidence_bytes) NOT BETWEEN 1 AND 525824 + OR p_original_attempt_evidence_sha256 IS DISTINCT FROM + 'sha256:' || encode(sha256(p_original_attempt_evidence_bytes), 'hex') THEN + RAISE EXCEPTION 'Exact Account original Game Session attempt observation is required for World abort' + USING ERRCODE = '23514'; + END IF; + tuple_value := convert_from(p_original_tuple, 'UTF8')::JSONB; + IF tuple_value->>'controlPlaneRequestId' IS DISTINCT FROM p_control_plane_request_id + OR tuple_value->'scope'->>'targetNamespace' IS DISTINCT FROM p_target_namespace + OR tuple_value->'scope'->>'tenantId' IS DISTINCT FROM p_canonical_tenant_id::TEXT THEN + RAISE EXCEPTION 'World abort identity differs from the original scoped StartSession tuple' + USING ERRCODE = '23514'; + END IF; + PERFORM "${serviceSchema}".world_lock_canonical_instance_execution( + p_target_namespace, p_canonical_tenant_id, p_control_plane_request_id, + p_canonical_game_instance_id); + PERFORM set_config('world.canonical_abort_namespace', p_target_namespace, TRUE); + PERFORM set_config('world.canonical_abort_tenant', p_canonical_tenant_id::TEXT, TRUE); + PERFORM set_config('world.canonical_abort_request', p_control_plane_request_id, TRUE); + PERFORM set_config('world.canonical_abort_target', p_canonical_game_instance_id::TEXT, TRUE); + PERFORM set_config('world.canonical_abort_mutation', p_game_session_mutation_id::TEXT, TRUE); + PERFORM set_config('world.canonical_abort_attempt_read', p_attempt_read_request_id::TEXT, TRUE); + PERFORM set_config( + 'world.canonical_abort_lease_expiry', + p_original_game_session_lease_expires_at::TEXT, + TRUE); + PERFORM set_config( + 'world.canonical_abort_observation_digest', + p_original_attempt_evidence_sha256, + TRUE); + SELECT * INTO operation FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.target_namespace = p_target_namespace + AND e.canonical_tenant_id = p_canonical_tenant_id + AND e.control_plane_request_id = p_control_plane_request_id + FOR UPDATE; + IF NOT FOUND THEN + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.canonical_game_instance_id = p_canonical_game_instance_id) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_preparation p + WHERE p.canonical_game_instance_id = p_canonical_game_instance_id + OR (p.target_namespace = p_target_namespace + AND p.canonical_tenant_id = p_canonical_tenant_id + AND p.control_plane_request_id = p_control_plane_request_id)) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_association a + WHERE a.canonical_game_instance_id = p_canonical_game_instance_id + OR (a.canonical_target_namespace = p_target_namespace + AND a.canonical_tenant_id = p_canonical_tenant_id + AND a.control_plane_request_id = p_control_plane_request_id)) THEN + RAISE EXCEPTION 'Historical or conflicting World rows make missing-operation abort unresolved' + USING ERRCODE = '23514'; + END IF; + INSERT INTO "${serviceSchema}".world_canonical_instance_execution ( + target_namespace, canonical_tenant_id, control_plane_request_id, + canonical_game_instance_id, canonical_world_slug, game_template_id, + original_post_authorization_tuple, original_post_authorization_tuple_sha256, + account_world_participation_id, account_world_participation_fence, + game_session_owner_attempt_id, game_session_owner_fence, + game_session_owner_mutation_id, original_attempt_read_request_id, + original_game_session_lease_expires_at, original_attempt_evidence_bytes, + original_attempt_evidence_sha256, + preparation_input_digest, preparation_input_json, world_execution_fence, + operation_state, terminal_at) + VALUES ( + p_target_namespace, p_canonical_tenant_id, p_control_plane_request_id, + p_canonical_game_instance_id, + (p_preparation_input_json::JSONB->'identity'->>'worldSlug'), + (((p_preparation_input_json::JSONB->'gameSessionReadEvidence'->>'descriptorJson')::JSONB)->>'gameTemplateId')::BIGINT, + p_original_tuple, encode(sha256(p_original_tuple), 'hex'), + p_account_participation_id, p_account_participation_fence, + p_game_session_attempt_id, p_game_session_fence, + p_game_session_mutation_id, p_attempt_read_request_id, + p_original_game_session_lease_expires_at, p_original_attempt_evidence_bytes, + p_original_attempt_evidence_sha256, + p_preparation_input_digest, p_preparation_input_json, + nextval('"${serviceSchema}".world_canonical_instance_execution_fence_seq'), + 'ABORTED', clock_timestamp()) + RETURNING * INTO operation; + END IF; + IF operation.canonical_game_instance_id IS DISTINCT FROM p_canonical_game_instance_id + OR operation.canonical_world_slug IS DISTINCT FROM p_preparation_input_json::JSONB->'identity'->>'worldSlug' + OR operation.game_template_id IS DISTINCT FROM (((p_preparation_input_json::JSONB->'gameSessionReadEvidence'->>'descriptorJson')::JSONB)->>'gameTemplateId')::BIGINT + OR operation.preparation_input_digest IS DISTINCT FROM p_preparation_input_digest + OR operation.preparation_input_json IS DISTINCT FROM p_preparation_input_json + OR operation.original_post_authorization_tuple IS DISTINCT FROM p_original_tuple + OR operation.account_world_participation_id IS DISTINCT FROM p_account_participation_id + OR operation.account_world_participation_fence IS DISTINCT FROM p_account_participation_fence + OR operation.game_session_owner_attempt_id IS DISTINCT FROM p_game_session_attempt_id + OR operation.game_session_owner_fence IS DISTINCT FROM p_game_session_fence + OR operation.game_session_owner_mutation_id IS DISTINCT FROM p_game_session_mutation_id + OR operation.original_attempt_read_request_id IS DISTINCT FROM p_attempt_read_request_id + OR operation.original_game_session_lease_expires_at IS DISTINCT FROM p_original_game_session_lease_expires_at + OR operation.original_attempt_evidence_bytes IS DISTINCT FROM p_original_attempt_evidence_bytes + OR operation.original_attempt_evidence_sha256 IS DISTINCT FROM p_original_attempt_evidence_sha256 THEN + RAISE EXCEPTION 'World abort differs from the exact original full owner-observation identity' + USING ERRCODE = '23514'; + END IF; + IF operation.operation_state = 'PENDING' THEN + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_preparation p + WHERE p.canonical_game_instance_id = operation.canonical_game_instance_id + OR (p.target_namespace = operation.target_namespace + AND p.canonical_tenant_id = operation.canonical_tenant_id + AND p.control_plane_request_id = operation.control_plane_request_id)) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_association a + WHERE a.canonical_game_instance_id = operation.canonical_game_instance_id + OR (a.canonical_target_namespace = operation.target_namespace + AND a.canonical_tenant_id = operation.canonical_tenant_id + AND a.control_plane_request_id = operation.control_plane_request_id)) THEN + RAISE EXCEPTION 'World has unbound materialization rows; operation remains unresolved' + USING ERRCODE = '23514'; + END IF; + UPDATE "${serviceSchema}".world_canonical_instance_execution e + SET operation_state = 'ABORTED', terminal_at = clock_timestamp() + WHERE e.target_namespace = operation.target_namespace + AND e.canonical_tenant_id = operation.canonical_tenant_id + AND e.control_plane_request_id = operation.control_plane_request_id; + operation.operation_state := 'ABORTED'; + ELSIF operation.operation_state NOT IN ('COMMITTED', 'ABORTED') THEN + RAISE EXCEPTION 'World execution is not in a durable terminal state' + USING ERRCODE = '23514'; + END IF; + operation_state := operation.operation_state; + world_execution_fence := operation.world_execution_fence; + world_instance_id := operation.world_instance_id; + RETURN NEXT; +END; +$$; +REVOKE ALL ON FUNCTION world_abort_canonical_instance_execution_with_original_attempt( + TEXT, UUID, TEXT, UUID, TEXT, TEXT, BYTEA, UUID, BIGINT, UUID, BIGINT, + UUID, UUID, TIMESTAMPTZ, BYTEA, TEXT) FROM PUBLIC; + +-- V35 calls this hook only after its publication, target and request locks. The original Account +-- authorization and unchanged Game Session lease must both still be valid at that local admission. +CREATE OR REPLACE FUNCTION world_require_active_canonical_instance_execution( + p_input_json TEXT, p_input_digest TEXT +) RETURNS VOID +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + operation "${serviceSchema}".world_canonical_instance_execution%ROWTYPE; + original_tuple JSONB; + original_expiry TIMESTAMPTZ; +BEGIN + SELECT * INTO operation FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.target_namespace = current_setting('world.canonical_execution_namespace', TRUE) + AND e.canonical_tenant_id::TEXT = current_setting('world.canonical_execution_tenant', TRUE) + AND e.control_plane_request_id = current_setting('world.canonical_execution_request', TRUE) + AND e.canonical_game_instance_id::TEXT = current_setting('world.canonical_execution_target', TRUE) + AND e.world_execution_fence::TEXT = current_setting('world.canonical_execution_fence', TRUE) + AND e.preparation_input_digest = p_input_digest + AND e.preparation_input_json = p_input_json + AND e.operation_state = 'EXECUTING' + AND e.active_transaction_id = txid_current(); + IF NOT FOUND + OR operation.game_session_owner_mutation_id IS NULL + OR operation.original_attempt_read_request_id IS NULL + OR operation.original_game_session_lease_expires_at IS NULL + OR operation.original_attempt_evidence_bytes IS NULL + OR operation.original_attempt_evidence_sha256 IS DISTINCT FROM + 'sha256:' || encode(sha256(operation.original_attempt_evidence_bytes), 'hex') THEN + RAISE EXCEPTION 'V35 requires the exact current World and Account owner-observation identity' + USING ERRCODE = '23514'; + END IF; + original_tuple := convert_from(operation.original_post_authorization_tuple, 'UTF8')::JSONB; + original_expiry := (original_tuple->'authorityEvidenceBundle'->'accountProjectionEvidence'->>'expiresAt')::TIMESTAMPTZ; + IF original_expiry <= clock_timestamp() + OR operation.original_game_session_lease_expires_at <= clock_timestamp() THEN + RAISE EXCEPTION 'Original StartSession authorization or Game Session lease expired before World execution admission' + USING ERRCODE = '23514'; + END IF; +END; +$$; +REVOKE ALL ON FUNCTION world_require_active_canonical_instance_execution(TEXT, TEXT) FROM PUBLIC; + +-- V62's transition guard already serializes each state with its World fence. Replace only the +-- owner-private guard body to make the returned Account witness immutable and require it for every +-- new PENDING intent/claim/admission. Existing rows keep their original null witness values. +CREATE OR REPLACE FUNCTION world_enforce_canonical_instance_execution_transition() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + IF TG_OP = 'UPDATE' THEN + IF NEW.target_namespace IS DISTINCT FROM OLD.target_namespace + OR NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id + OR NEW.control_plane_request_id IS DISTINCT FROM OLD.control_plane_request_id + OR NEW.canonical_game_instance_id IS DISTINCT FROM OLD.canonical_game_instance_id + OR NEW.canonical_world_slug IS DISTINCT FROM OLD.canonical_world_slug + OR NEW.game_template_id IS DISTINCT FROM OLD.game_template_id + OR NEW.original_post_authorization_tuple IS DISTINCT FROM OLD.original_post_authorization_tuple + OR NEW.original_post_authorization_tuple_sha256 IS DISTINCT FROM OLD.original_post_authorization_tuple_sha256 + OR NEW.account_world_participation_id IS DISTINCT FROM OLD.account_world_participation_id + OR NEW.account_world_participation_fence IS DISTINCT FROM OLD.account_world_participation_fence + OR NEW.game_session_owner_attempt_id IS DISTINCT FROM OLD.game_session_owner_attempt_id + OR NEW.game_session_owner_fence IS DISTINCT FROM OLD.game_session_owner_fence + OR NEW.game_session_owner_mutation_id IS DISTINCT FROM OLD.game_session_owner_mutation_id + OR NEW.original_attempt_read_request_id IS DISTINCT FROM OLD.original_attempt_read_request_id + OR NEW.original_game_session_lease_expires_at IS DISTINCT FROM OLD.original_game_session_lease_expires_at + OR NEW.original_attempt_evidence_bytes IS DISTINCT FROM OLD.original_attempt_evidence_bytes + OR NEW.original_attempt_evidence_sha256 IS DISTINCT FROM OLD.original_attempt_evidence_sha256 + OR NEW.preparation_input_digest IS DISTINCT FROM OLD.preparation_input_digest + OR NEW.preparation_input_json IS DISTINCT FROM OLD.preparation_input_json + OR NEW.world_execution_fence IS DISTINCT FROM OLD.world_execution_fence + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'World execution identity and Account owner witness are immutable' + USING ERRCODE = '23514'; + END IF; + IF OLD.operation_state = 'PENDING' AND NEW.operation_state = 'PENDING' THEN + IF OLD.execution_claimed OR NOT NEW.execution_claimed + OR OLD.active_transaction_id IS DISTINCT FROM NEW.active_transaction_id + OR OLD.world_instance_id IS DISTINCT FROM NEW.world_instance_id + OR OLD.terminal_at IS DISTINCT FROM NEW.terminal_at + OR NEW.game_session_owner_mutation_id IS NULL + OR NEW.original_attempt_read_request_id IS NULL + OR NEW.original_game_session_lease_expires_at IS NULL + OR NEW.original_attempt_evidence_bytes IS NULL + OR current_setting('world.canonical_claim_namespace', TRUE) IS DISTINCT FROM NEW.target_namespace + OR current_setting('world.canonical_claim_tenant', TRUE) IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR current_setting('world.canonical_claim_request', TRUE) IS DISTINCT FROM NEW.control_plane_request_id + OR current_setting('world.canonical_claim_target', TRUE) IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR current_setting('world.canonical_claim_fence', TRUE) IS DISTINCT FROM NEW.world_execution_fence::TEXT THEN + RAISE EXCEPTION 'World execution intent may be claimed only once by its exact complete owner observation and serialization fence' + USING ERRCODE = '23514'; + END IF; + ELSIF OLD.operation_state = 'PENDING' AND NEW.operation_state = 'EXECUTING' THEN + IF NOT OLD.execution_claimed OR NOT NEW.execution_claimed + OR NEW.active_transaction_id IS DISTINCT FROM txid_current() + OR NEW.world_instance_id IS NOT NULL OR NEW.terminal_at IS NOT NULL + OR NEW.game_session_owner_mutation_id IS NULL + OR NEW.original_attempt_read_request_id IS NULL + OR NEW.original_game_session_lease_expires_at IS NULL + OR NEW.original_attempt_evidence_bytes IS NULL + OR current_setting('world.canonical_execution_namespace', TRUE) IS DISTINCT FROM NEW.target_namespace + OR current_setting('world.canonical_execution_tenant', TRUE) IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR current_setting('world.canonical_execution_request', TRUE) IS DISTINCT FROM NEW.control_plane_request_id + OR current_setting('world.canonical_execution_target', TRUE) IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR current_setting('world.canonical_execution_fence', TRUE) IS DISTINCT FROM NEW.world_execution_fence::TEXT + OR current_setting('world.canonical_execution_input_digest', TRUE) IS DISTINCT FROM NEW.preparation_input_digest THEN + RAISE EXCEPTION 'World EXECUTING state requires its exact current transaction, complete owner observation and execution fence' + USING ERRCODE = '23514'; + END IF; + ELSIF OLD.operation_state = 'PENDING' AND NEW.operation_state = 'ABORTED' THEN + IF NEW.execution_claimed IS DISTINCT FROM OLD.execution_claimed + OR NEW.active_transaction_id IS NOT NULL OR NEW.world_instance_id IS NOT NULL + OR NEW.terminal_at IS NULL + OR current_setting('world.canonical_abort_namespace', TRUE) IS DISTINCT FROM NEW.target_namespace + OR current_setting('world.canonical_abort_tenant', TRUE) IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR current_setting('world.canonical_abort_request', TRUE) IS DISTINCT FROM NEW.control_plane_request_id + OR current_setting('world.canonical_abort_target', TRUE) IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR (OLD.game_session_owner_mutation_id IS NOT NULL AND ( + current_setting('world.canonical_abort_mutation', TRUE) IS DISTINCT FROM OLD.game_session_owner_mutation_id::TEXT + OR current_setting('world.canonical_abort_attempt_read', TRUE) IS DISTINCT FROM OLD.original_attempt_read_request_id::TEXT + OR current_setting('world.canonical_abort_lease_expiry', TRUE) IS DISTINCT FROM OLD.original_game_session_lease_expires_at::TEXT + OR current_setting('world.canonical_abort_observation_digest', TRUE) IS DISTINCT FROM OLD.original_attempt_evidence_sha256)) THEN + RAISE EXCEPTION 'World ABORTED state requires its exact serialized terminal fence' + USING ERRCODE = '23514'; + END IF; + ELSIF OLD.operation_state = 'EXECUTING' AND NEW.operation_state = 'COMMITTED' THEN + IF OLD.active_transaction_id IS DISTINCT FROM txid_current() + OR NEW.execution_claimed IS DISTINCT FROM TRUE + OR NEW.active_transaction_id IS NOT NULL + OR NEW.terminal_at IS NULL + OR current_setting('world.canonical_execution_namespace', TRUE) IS DISTINCT FROM NEW.target_namespace + OR current_setting('world.canonical_execution_tenant', TRUE) IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR current_setting('world.canonical_execution_request', TRUE) IS DISTINCT FROM NEW.control_plane_request_id + OR current_setting('world.canonical_execution_target', TRUE) IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR current_setting('world.canonical_execution_fence', TRUE) IS DISTINCT FROM NEW.world_execution_fence::TEXT + OR current_setting('world.canonical_execution_input_digest', TRUE) IS DISTINCT FROM NEW.preparation_input_digest + OR NOT "${serviceSchema}".world_execution_has_exact_materialized_result(NEW, NEW.world_instance_id) THEN + RAISE EXCEPTION 'World COMMITTED state requires the current exact V35 preparation and V34 association' + USING ERRCODE = '23514'; + END IF; + ELSE + RAISE EXCEPTION 'World execution state transition is not permitted' + USING ERRCODE = '23514'; + END IF; + ELSIF NEW.operation_state = 'PENDING' THEN + IF NEW.execution_claimed OR NEW.active_transaction_id IS NOT NULL + OR NEW.world_instance_id IS NOT NULL OR NEW.terminal_at IS NOT NULL + OR NEW.game_session_owner_mutation_id IS NULL + OR NEW.original_attempt_read_request_id IS NULL + OR NEW.original_game_session_lease_expires_at IS NULL + OR NEW.original_attempt_evidence_bytes IS NULL THEN + RAISE EXCEPTION 'A fresh World execution intent requires its exact Account owner observation' + USING ERRCODE = '23514'; + END IF; + ELSIF NEW.operation_state = 'ABORTED' THEN + IF NEW.execution_claimed OR NEW.active_transaction_id IS NOT NULL + OR NEW.world_instance_id IS NOT NULL OR NEW.terminal_at IS NULL + OR current_setting('world.canonical_abort_namespace', TRUE) IS DISTINCT FROM NEW.target_namespace + OR current_setting('world.canonical_abort_tenant', TRUE) IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR current_setting('world.canonical_abort_request', TRUE) IS DISTINCT FROM NEW.control_plane_request_id + OR current_setting('world.canonical_abort_target', TRUE) IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR (NEW.game_session_owner_mutation_id IS NOT NULL AND ( + current_setting('world.canonical_abort_mutation', TRUE) IS DISTINCT FROM NEW.game_session_owner_mutation_id::TEXT + OR current_setting('world.canonical_abort_attempt_read', TRUE) IS DISTINCT FROM NEW.original_attempt_read_request_id::TEXT + OR current_setting('world.canonical_abort_lease_expiry', TRUE) IS DISTINCT FROM NEW.original_game_session_lease_expires_at::TEXT + OR current_setting('world.canonical_abort_observation_digest', TRUE) IS DISTINCT FROM NEW.original_attempt_evidence_sha256)) THEN + RAISE EXCEPTION 'A born-ABORTED World operation requires its exact serialized abort fence' + USING ERRCODE = '23514'; + END IF; + ELSE + RAISE EXCEPTION 'World execution rows must be born PENDING or terminally ABORTED' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +REVOKE ALL ON FUNCTION world_enforce_canonical_instance_execution_transition() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1037__world_launch_captured_catalog_identity.sql b/services/world-management-service/src/main/resources/db/migration/V1037__world_launch_captured_catalog_identity.sql new file mode 100644 index 0000000000..2d88138426 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1037__world_launch_captured_catalog_identity.sql @@ -0,0 +1,280 @@ +-- Retain the exact Game Session launch-captured realm/catalog tuple. Historical World rows and +-- original preparation bytes remain unchanged; only new canonical associations/preparations can +-- carry this complete identity. +ALTER TABLE world_instance + ADD COLUMN canonical_realm_id UUID, + ADD COLUMN catalog_revision BIGINT, + ADD CONSTRAINT ck_world_instance_launch_catalog_identity CHECK ( + (canonical_realm_id IS NULL AND catalog_revision IS NULL) + OR (canonical_realm_id IS NOT NULL + AND canonical_realm_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND catalog_revision IS NOT NULL + AND catalog_revision > 0) + ); + +ALTER TABLE world_instance + ADD CONSTRAINT uq_world_instance_canonical_catalog_association_fk + UNIQUE ( + id, + canonical_game_instance_id, + canonical_target_namespace, + canonical_tenant_id, + canonical_world_slug, + playable_state_namespace_id, + playable_state_scope, + public_production, + control_plane_request_id, + canonical_launch_binding_operation_id, + canonical_realm_id, + catalog_revision + ); + +ALTER TABLE world_canonical_instance_association + ADD COLUMN canonical_realm_id UUID, + ADD COLUMN catalog_revision BIGINT; + +ALTER TABLE world_canonical_instance_association + DROP CONSTRAINT ck_world_canonical_instance_association_schema; + +ALTER TABLE world_canonical_instance_association + ADD CONSTRAINT ck_world_canonical_instance_association_schema CHECK ( + (schema_version = 1 AND canonical_realm_id IS NULL AND catalog_revision IS NULL) + OR (schema_version = 2 + AND canonical_realm_id IS NOT NULL + AND canonical_realm_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND catalog_revision IS NOT NULL + AND catalog_revision > 0) + ); + +ALTER TABLE world_canonical_instance_association + ADD CONSTRAINT fk_world_canonical_instance_association_catalog_world_row + FOREIGN KEY ( + world_instance_id, + canonical_game_instance_id, + canonical_target_namespace, + canonical_tenant_id, + canonical_world_slug, + playable_state_namespace_id, + playable_state_scope, + public_production, + control_plane_request_id, + canonical_launch_binding_operation_id, + canonical_realm_id, + catalog_revision + ) REFERENCES world_instance ( + id, + canonical_game_instance_id, + canonical_target_namespace, + canonical_tenant_id, + canonical_world_slug, + playable_state_namespace_id, + playable_state_scope, + public_production, + control_plane_request_id, + canonical_launch_binding_operation_id, + canonical_realm_id, + catalog_revision + ) ON DELETE RESTRICT; + +-- Keep V34 insert-born immutability, while allowing old retained rows to stay NULL and requiring +-- the complete captured pair on every new canonical World instance insert. +-- [jooq ignore start] +DO $migration$ +DECLARE + original TEXT; + null_identity_anchor TEXT := $anchor$ OR NEW.canonical_launch_binding_operation_id IS NOT NULL THEN$anchor$; + immutable_anchor TEXT := $anchor$ OR OLD.canonical_launch_binding_operation_id + IS DISTINCT FROM NEW.canonical_launch_binding_operation_id THEN$anchor$; + insert_anchor TEXT := $anchor$ IF NEW.canonical_game_instance_id IS NULL THEN + RETURN NEW; + END IF;$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_validate_canonical_prepare_identity()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,null_identity_anchor,'')))/length(null_identity_anchor) <> 1 + OR (length(original)-length(replace(original,immutable_anchor,'')))/length(immutable_anchor) <> 1 + OR (length(original)-length(replace(original,insert_anchor,'')))/length(insert_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V34 canonical World identity trigger anchor'; + END IF; + original := replace(original, + null_identity_anchor, + $replacement$ OR NEW.canonical_launch_binding_operation_id IS NOT NULL + OR NEW.canonical_realm_id IS NOT NULL + OR NEW.catalog_revision IS NOT NULL THEN$replacement$); + original := replace(original, + immutable_anchor, + $replacement$ OR OLD.canonical_launch_binding_operation_id + IS DISTINCT FROM NEW.canonical_launch_binding_operation_id + OR OLD.canonical_realm_id IS DISTINCT FROM NEW.canonical_realm_id + OR OLD.catalog_revision IS DISTINCT FROM NEW.catalog_revision THEN$replacement$); + original := replace(original, + insert_anchor, + $replacement$ IF NEW.canonical_game_instance_id IS NULL THEN + RETURN NEW; + END IF; + IF NEW.canonical_realm_id IS NULL + OR NEW.canonical_realm_id = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.catalog_revision IS NULL + OR NEW.catalog_revision <= 0 THEN + RAISE EXCEPTION 'New canonical World instance requires launch-captured realm and catalog revision' + USING ERRCODE = '23514'; + END IF;$replacement$); + EXECUTE original; +END; +$migration$; + +-- Association schema 1 remains historical and incomplete; all new association inserts use schema 2 +-- and must exactly match the catalog identity on their insert-born World row. +DO $migration$ +DECLARE + original TEXT; + begin_anchor TEXT := $anchor$BEGIN + SELECT * INTO instance FROM world_instance WHERE id = NEW.world_instance_id FOR KEY SHARE;$anchor$; + equality_anchor TEXT := $anchor$ OR instance.public_production IS DISTINCT FROM NEW.public_production$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_validate_canonical_instance_association()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,begin_anchor,'')))/length(begin_anchor) <> 1 + OR (length(original)-length(replace(original,equality_anchor,'')))/length(equality_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V34 canonical association trigger anchor'; + END IF; + original := replace(original, + begin_anchor, + $replacement$BEGIN + IF NEW.schema_version IS DISTINCT FROM 2 + OR NEW.canonical_realm_id IS NULL + OR NEW.canonical_realm_id = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.catalog_revision IS NULL + OR NEW.catalog_revision <= 0 THEN + RAISE EXCEPTION 'New canonical World association requires complete launch-captured catalog identity' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO instance FROM world_instance WHERE id = NEW.world_instance_id FOR KEY SHARE;$replacement$); + original := replace(original, + equality_anchor, + $replacement$ OR instance.public_production IS DISTINCT FROM NEW.public_production + OR instance.canonical_realm_id IS DISTINCT FROM NEW.canonical_realm_id + OR instance.catalog_revision IS DISTINCT FROM NEW.catalog_revision$replacement$); + EXECUTE original; +END; +$migration$; + +-- Keep V62's protected execution wrapper intact. Widen only its private V61 implementation, which +-- retains the V35/V40/V42/V61 owner guards, plus the selector verifier they call. +DO $migration$ +DECLARE + original TEXT; + schema_anchor TEXT := $anchor$ IF p->>'schemaVersion' IS NULL OR p->>'schemaVersion' NOT IN ('1','2') THEN$anchor$; + identity_anchor TEXT := $anchor$ OR ident->>'publicProduction' IS DISTINCT FROM gs_evidence->>'publicProduction'$anchor$; + row_anchor TEXT := $anchor$ 'canonical_launch_binding_operation_id', binding_row.binding_operation_id));$anchor$; + retry_anchor TEXT := $anchor$ IF p->>'schemaVersion' = '2' AND NOT EXISTS ($anchor$; + release_profile_anchor TEXT := $anchor$ AND binding_row.release_attestation_json::JSONB->>'schemaVersion' IN ('2', '3') + AND participant->>'digestSchemaVersion' = CASE + binding_row.release_attestation_json::JSONB->>'schemaVersion' + WHEN '2' THEN '3' WHEN '3' THEN '4' ELSE NULL END + AND binding_row.release_attestation_json::JSONB->'worldStartLocationEvidence'->'request'->>'digestSchemaVersion' + = capture_row.freeze_request_json::JSONB->>'digestSchemaVersion'$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_prepare_canonical_instance_v61_impl(text,text)'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,schema_anchor,'')))/length(schema_anchor) <> 1 + OR (length(original)-length(replace(original,identity_anchor,'')))/length(identity_anchor) <> 1 + OR (length(original)-length(replace(original,row_anchor,'')))/length(row_anchor) <> 1 + OR (length(original)-length(replace(original,retry_anchor,'')))/length(retry_anchor) <> 1 + OR (length(original)-length(replace(original,release_profile_anchor,'')))/length(release_profile_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V61 implementation preparation guard anchor'; + END IF; + original := replace(original,schema_anchor, + $replacement$ IF p->>'schemaVersion' IS NULL OR p->>'schemaVersion' NOT IN ('3','4') THEN$replacement$); + original := replace(original,identity_anchor, + $replacement$ OR ident->>'publicProduction' IS DISTINCT FROM gs_evidence->>'publicProduction' + OR ident->>'canonicalRealmId' IS NULL + OR ident->>'canonicalRealmId' IS DISTINCT FROM gs_evidence->>'canonicalRealmId' + OR (ident->>'canonicalRealmId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR ident->>'canonicalRealmId' IS DISTINCT FROM (ident->>'canonicalRealmId')::UUID::TEXT + OR jsonb_typeof(ident->'catalogRevision') IS DISTINCT FROM 'number' + OR ident->>'catalogRevision' !~ '^[1-9][0-9]*$' + OR ident->>'catalogRevision' IS DISTINCT FROM gs_evidence->>'catalogRevision'$replacement$); + original := replace(original,row_anchor, + $replacement$ 'canonical_launch_binding_operation_id', binding_row.binding_operation_id, + 'canonical_realm_id', (ident->>'canonicalRealmId')::UUID, + 'catalog_revision', (ident->>'catalogRevision')::BIGINT));$replacement$); + original := replace(original,retry_anchor, + $replacement$ IF p->>'schemaVersion' = '4' AND NOT EXISTS ($replacement$); + original := replace(original,release_profile_anchor, + $replacement$ AND binding_row.release_attestation_json::JSONB->>'schemaVersion' IN ('2', '3', '4') + AND participant->>'digestSchemaVersion' = CASE + binding_row.release_attestation_json::JSONB->>'schemaVersion' + WHEN '2' THEN '3' WHEN '3' THEN '4' WHEN '4' THEN '4' ELSE NULL END + AND binding_row.release_attestation_json::JSONB->'worldStartLocationEvidence'->'request'->>'digestSchemaVersion' + = capture_row.freeze_request_json::JSONB->>'digestSchemaVersion'$replacement$); + EXECUTE original; +END; +$migration$; + +-- Preserve the V61 retained schema-2/3 selector semantics and add the accepted selected-full +-- schema-4 attestation with its exact World/4 selector. Historical preparation v1/v2 remain inert. +DO $migration$ +DECLARE + original TEXT; + no_location_anchor TEXT := $anchor$ IF input->>'schemaVersion' = '1' THEN$anchor$; + with_location_anchor TEXT := $anchor$ IF input->>'schemaVersion' IS DISTINCT FROM '2' + OR binding->>'schemaVersion' IS NULL + OR binding->>'schemaVersion' NOT IN ('2', '3') + OR input->>'worldStartLocationEvidenceBase64' IS NULL$anchor$; + selector_digest_anchor TEXT := $anchor$ OR selected->>'digestSchemaVersion' IS DISTINCT FROM (CASE binding->>'schemaVersion' + WHEN '2' THEN '3' WHEN '3' THEN '4' ELSE NULL END)$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_require_preparation_start_location(jsonb,jsonb,uuid)'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,no_location_anchor,'')))/length(no_location_anchor) <> 1 + OR (length(original)-length(replace(original,with_location_anchor,'')))/length(with_location_anchor) <> 1 + OR (length(original)-length(replace(original,selector_digest_anchor,'')))/length(selector_digest_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V42 preparation selector schema anchor'; + END IF; + original := replace(original,no_location_anchor, + $replacement$ IF input->>'schemaVersion' = '3' THEN$replacement$); + original := replace(original, + with_location_anchor, + $replacement$ IF input->>'schemaVersion' IS DISTINCT FROM '4' + OR binding->>'schemaVersion' IS NULL + OR binding->>'schemaVersion' NOT IN ('2', '3', '4') + OR input->>'worldStartLocationEvidenceBase64' IS NULL$replacement$); + original := replace(original,selector_digest_anchor, + $replacement$ OR selected->>'digestSchemaVersion' IS DISTINCT FROM (CASE binding->>'schemaVersion' + WHEN '2' THEN '3' WHEN '3' THEN '4' WHEN '4' THEN '4' ELSE NULL END)$replacement$); + EXECUTE original; +END; +$migration$; + +-- Keep the V42 start-location retention/readback trigger scoped to schema 4 only. +DO $migration$ +DECLARE + original TEXT; + retain_anchor TEXT := $anchor$ IF NEW.input_json::JSONB->>'schemaVersion' = '1' THEN RETURN NEW; END IF;$anchor$; + guard_anchor TEXT := $anchor$ IF original->>'schemaVersion' IS DISTINCT FROM '2'$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_retain_preparation_start_location()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,retain_anchor,'')))/length(retain_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V42 start-location retention anchor'; + END IF; + original := replace(original,retain_anchor, + $replacement$ IF NEW.input_json::JSONB->>'schemaVersion' = '3' THEN RETURN NEW; END IF;$replacement$); + EXECUTE original; + + SELECT pg_get_functiondef('"${serviceSchema}".world_guard_preparation_start_location()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,guard_anchor,'')))/length(guard_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V42 start-location guard anchor'; + END IF; + original := replace(original,guard_anchor, + $replacement$ IF original->>'schemaVersion' IS DISTINCT FROM '4'$replacement$); + EXECUTE original; +END; +$migration$; + +REVOKE ALL ON FUNCTION world_validate_canonical_prepare_identity() FROM PUBLIC; +REVOKE ALL ON FUNCTION world_validate_canonical_instance_association() FROM PUBLIC; +REVOKE ALL ON FUNCTION world_prepare_canonical_instance(TEXT,TEXT) FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1038__original_start_session_protected_activation.sql b/services/world-management-service/src/main/resources/db/migration/V1038__original_start_session_protected_activation.sql new file mode 100644 index 0000000000..e254d4ea91 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1038__original_start_session_protected_activation.sql @@ -0,0 +1,367 @@ +-- World activation intent is bound to the distinct Account StartSession protection receipt before +-- the PREPARING-to-ACTIVE lifecycle CAS. Historical V43 operation rows remain untouched. +CREATE SEQUENCE world_canonical_instance_activation_fence_seq AS BIGINT MINVALUE 1; + +CREATE TABLE world_canonical_instance_activation_fence ( + activation_request_id UUID PRIMARY KEY, + protection_operation_digest VARCHAR(71) NOT NULL + CHECK (protection_operation_digest ~ '^sha256:[0-9a-f]{64}$'), + account_protection_id UUID NOT NULL + CHECK (account_protection_id <> '00000000-0000-0000-0000-000000000000'::UUID), + account_protection_fence BIGINT NOT NULL CHECK (account_protection_fence > 0), + account_protection_evidence_bytes BYTEA NOT NULL + CHECK (octet_length(account_protection_evidence_bytes) BETWEEN 1 AND 209715200), + account_protection_evidence_digest VARCHAR(71) NOT NULL + CHECK (account_protection_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND account_protection_evidence_digest = + 'sha256:' || encode(sha256(account_protection_evidence_bytes), 'hex')), + source_capture_reference_digest VARCHAR(64) NOT NULL + CHECK (source_capture_reference_digest ~ '^[0-9a-f]{64}$'), + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + control_plane_request_id VARCHAR(128) NOT NULL, + canonical_world_slug VARCHAR(120) NOT NULL, + canonical_game_instance_id UUID NOT NULL UNIQUE + CHECK (canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID), + original_post_authorization_tuple BYTEA NOT NULL + CHECK (octet_length(original_post_authorization_tuple) BETWEEN 1 AND 262144), + account_world_participation_id UUID NOT NULL + CHECK (account_world_participation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + account_world_participation_fence BIGINT NOT NULL CHECK (account_world_participation_fence > 0), + game_session_owner_mutation_id UUID NOT NULL + CHECK (game_session_owner_mutation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_owner_attempt_id UUID NOT NULL + CHECK (game_session_owner_attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_owner_fence BIGINT NOT NULL CHECK (game_session_owner_fence > 0), + original_game_session_lease_expires_at TIMESTAMPTZ NOT NULL, + canonical_realm_id UUID NOT NULL + CHECK (canonical_realm_id <> '00000000-0000-0000-0000-000000000000'::UUID), + catalog_revision BIGINT NOT NULL CHECK (catalog_revision > 0), + expected_lifecycle_epoch BIGINT NOT NULL CHECK (expected_lifecycle_epoch > 0), + expected_row_version BIGINT NOT NULL CHECK (expected_row_version >= 0), + preparing_evidence_bytes BYTEA NOT NULL + CHECK (octet_length(preparing_evidence_bytes) BETWEEN 1 AND 67108864), + world_execution_fence BIGINT NOT NULL UNIQUE CHECK (world_execution_fence > 0), + world_instance_id BIGINT NOT NULL REFERENCES world_instance(id) ON DELETE RESTRICT, + world_activation_fence BIGINT NOT NULL UNIQUE CHECK (world_activation_fence > 0), + operation_state VARCHAR(16) NOT NULL CHECK (operation_state IN ('PENDING', 'COMMITTED', 'ABORTED')), + terminal_result_bytes BYTEA, + terminal_result_digest VARCHAR(71), + terminal_evidence_bytes BYTEA, + terminal_evidence_digest VARCHAR(71), + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + terminal_at TIMESTAMPTZ, + CONSTRAINT ck_world_activation_fence_request_id_non_nil + CHECK (activation_request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_world_activation_fence_terminal_shape CHECK ( + (operation_state = 'PENDING' + AND terminal_result_bytes IS NULL AND terminal_result_digest IS NULL + AND terminal_evidence_bytes IS NULL AND terminal_evidence_digest IS NULL + AND terminal_at IS NULL) + OR (operation_state IN ('COMMITTED', 'ABORTED') + AND terminal_result_bytes IS NOT NULL + AND octet_length(terminal_result_bytes) BETWEEN 1 AND 402653184 + AND terminal_result_digest IS NOT NULL + AND terminal_result_digest ~ '^sha256:[0-9a-f]{64}$' + AND terminal_result_digest = 'sha256:' || encode(sha256(terminal_result_bytes), 'hex') + AND terminal_evidence_bytes IS NOT NULL + AND octet_length(terminal_evidence_bytes) BETWEEN 1 AND 805306368 + AND terminal_evidence_digest IS NOT NULL + AND terminal_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND terminal_evidence_digest = 'sha256:' || encode(sha256(terminal_evidence_bytes), 'hex') + AND terminal_at IS NOT NULL) + ) +); + +CREATE INDEX idx_world_activation_fence_terminal + ON world_canonical_instance_activation_fence(operation_state, world_instance_id); + +-- [jooq ignore start] +REVOKE ALL ON world_canonical_instance_activation_fence FROM PUBLIC; +REVOKE ALL ON SEQUENCE world_canonical_instance_activation_fence_seq FROM PUBLIC; + +-- V43 deliberately rejected the V64 schema-2 association because it lacked the launch-captured +-- realm/catalog pair. Widen only its old schema discriminator and preserve schema-1 history exactly. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ AND a.schema_version=1$anchor$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_validate_canonical_activation_operation()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,anchor,'')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V43 schema-1 activation guard'; + END IF; + original := replace(original, anchor, $replacement$ AND a.schema_version IN (1,2) + AND (a.schema_version=1 OR ( + a.canonical_realm_id IS NOT NULL + AND a.catalog_revision IS NOT NULL + AND w.canonical_realm_id=a.canonical_realm_id + AND w.catalog_revision=a.catalog_revision + AND p.input_json::JSONB->'identity'->>'canonicalRealmId'=a.canonical_realm_id::TEXT + AND p.input_json::JSONB->'identity'->>'catalogRevision'=a.catalog_revision::TEXT))$replacement$); + EXECUTE original; +END; +$migration$; + +CREATE FUNCTION world_validate_original_start_session_activation_fence() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + account_evidence JSONB; + account_request JSONB; + preparing JSONB; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'World original StartSession activation fences are immutable and retained' + USING ERRCODE = '55000'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.operation_state IS DISTINCT FROM 'PENDING' + OR NEW.terminal_result_bytes IS NOT NULL OR NEW.terminal_result_digest IS NOT NULL + OR NEW.terminal_evidence_bytes IS NOT NULL OR NEW.terminal_evidence_digest IS NOT NULL + OR NEW.terminal_at IS NOT NULL THEN + RAISE EXCEPTION 'World activation fence must be retained as PENDING before its exact terminal' + USING ERRCODE = '23514'; + END IF; + account_evidence := convert_from(NEW.account_protection_evidence_bytes, 'UTF8')::JSONB; + preparing := convert_from(NEW.preparing_evidence_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(account_evidence) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(account_evidence)) <> 8 + OR account_evidence->>'schema' IS DISTINCT FROM 'account-start-session-activation-protection-evidence/v1' + OR account_evidence->>'accountProtectionId' IS DISTINCT FROM NEW.account_protection_id::TEXT + OR account_evidence->>'accountProtectionFence' IS DISTINCT FROM NEW.account_protection_fence::TEXT + OR account_evidence->>'originalSourceCaptureReferenceSha256' + IS DISTINCT FROM NEW.source_capture_reference_digest + OR NEW.source_capture_reference_digest IS DISTINCT FROM + encode(sha256(decode(account_evidence->>'originalSourceCaptureReferenceBytesBase64','base64')), 'hex') + OR jsonb_typeof(account_evidence->'sourceEvidenceVector') IS DISTINCT FROM 'array' + OR jsonb_array_length(account_evidence->'sourceEvidenceVector') < 1 THEN + RAISE EXCEPTION 'World activation fence does not retain a complete exact Account protection receipt' + USING ERRCODE = '23514'; + END IF; + account_request := convert_from( + decode(account_evidence->>'requestBytesBase64', 'base64'), 'UTF8')::JSONB; + IF jsonb_typeof(account_request) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(account_request)) <> 12 + OR account_request->>'schema' IS DISTINCT FROM 'account-start-session-activation-protection-request/v1' + OR decode(account_request->>'originalPostAuthorizationTupleBytesBase64', 'base64') + IS DISTINCT FROM NEW.original_post_authorization_tuple + OR account_request->>'gameSessionOwnerMutationId' IS DISTINCT FROM NEW.game_session_owner_mutation_id::TEXT + OR account_request->>'gameSessionOwnerAttemptId' IS DISTINCT FROM NEW.game_session_owner_attempt_id::TEXT + OR account_request->>'gameSessionOwnerFence' IS DISTINCT FROM NEW.game_session_owner_fence::TEXT + OR (account_request->>'originalLeaseExpiresAt')::TIMESTAMPTZ + IS DISTINCT FROM NEW.original_game_session_lease_expires_at + OR account_request->>'accountWorldParticipationId' IS DISTINCT FROM NEW.account_world_participation_id::TEXT + OR account_request->>'accountWorldParticipationFence' IS DISTINCT FROM NEW.account_world_participation_fence::TEXT + OR account_request->>'worldActivationRequestId' IS DISTINCT FROM NEW.activation_request_id::TEXT + OR decode(account_request->>'preparingEvidenceBytesBase64', 'base64') + IS DISTINCT FROM NEW.preparing_evidence_bytes + OR preparing->>'schema' IS DISTINCT FROM 'world-canonical-instance-lifecycle-evidence/v1' + OR preparing->>'lifecycleStatus' IS DISTINCT FROM 'PREPARING' + OR preparing->>'lifecycleEpoch' IS DISTINCT FROM NEW.expected_lifecycle_epoch::TEXT + OR preparing->>'rowVersion' IS DISTINCT FROM NEW.expected_row_version::TEXT + OR preparing->'request'->>'targetNamespace' IS DISTINCT FROM NEW.target_namespace + OR preparing->'request'->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR preparing->'request'->>'worldSlug' IS DISTINCT FROM NEW.canonical_world_slug + OR preparing->'request'->>'controlPlaneRequestId' IS DISTINCT FROM NEW.control_plane_request_id + OR preparing->'request'->>'canonicalGameInstanceId' IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT THEN + RAISE EXCEPTION 'World activation fence identity differs from the complete Account original request' + USING ERRCODE = '23514'; + END IF; + IF NOT EXISTS ( + SELECT 1 + FROM world_canonical_instance_execution e + JOIN world_canonical_instance_association a + ON a.canonical_game_instance_id=e.canonical_game_instance_id + JOIN world_instance w ON w.id=a.world_instance_id + JOIN world_canonical_instance_preparation p + ON p.canonical_game_instance_id=a.canonical_game_instance_id + WHERE e.target_namespace=NEW.target_namespace + AND e.canonical_tenant_id=NEW.canonical_tenant_id + AND e.control_plane_request_id=NEW.control_plane_request_id + AND e.canonical_world_slug=NEW.canonical_world_slug + AND e.canonical_game_instance_id=NEW.canonical_game_instance_id + AND e.original_post_authorization_tuple=NEW.original_post_authorization_tuple + AND e.account_world_participation_id=NEW.account_world_participation_id + AND e.account_world_participation_fence=NEW.account_world_participation_fence + AND e.game_session_owner_mutation_id=NEW.game_session_owner_mutation_id + AND e.game_session_owner_attempt_id=NEW.game_session_owner_attempt_id + AND e.game_session_owner_fence=NEW.game_session_owner_fence + AND e.original_game_session_lease_expires_at=NEW.original_game_session_lease_expires_at + AND e.operation_state='COMMITTED' + AND e.world_execution_fence=NEW.world_execution_fence + AND e.world_instance_id=NEW.world_instance_id + AND a.world_instance_id=NEW.world_instance_id + AND a.schema_version=2 + AND a.canonical_realm_id=NEW.canonical_realm_id + AND a.catalog_revision=NEW.catalog_revision + AND w.canonical_game_instance_id=a.canonical_game_instance_id + AND w.canonical_realm_id=a.canonical_realm_id + AND w.catalog_revision=a.catalog_revision + AND p.input_digest=e.preparation_input_digest + AND p.input_digest=preparing->>'preparationInputDigest' + AND p.input_json::JSONB->'identity'->>'canonicalRealmId'=a.canonical_realm_id::TEXT + AND p.input_json::JSONB->'identity'->>'catalogRevision'=a.catalog_revision::TEXT + AND p.input_json::JSONB->>'schemaVersion'='4' + ) THEN + RAISE EXCEPTION 'World activation fence differs from the committed original execution, schema-2 realm/catalog, or exact preparation' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF OLD.operation_state IS DISTINCT FROM 'PENDING' + OR NEW.operation_state NOT IN ('COMMITTED', 'ABORTED') + OR (to_jsonb(NEW) - ARRAY['operation_state','terminal_result_bytes','terminal_result_digest', + 'terminal_evidence_bytes','terminal_evidence_digest','terminal_at']) + IS DISTINCT FROM + (to_jsonb(OLD) - ARRAY['operation_state','terminal_result_bytes','terminal_result_digest', + 'terminal_evidence_bytes','terminal_evidence_digest','terminal_at']) + OR NEW.terminal_result_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(NEW.terminal_result_bytes), 'hex') + OR NEW.terminal_evidence_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(NEW.terminal_evidence_bytes), 'hex') + OR NEW.terminal_at IS NULL THEN + RAISE EXCEPTION 'World activation intent permits one immutable PENDING-to-terminal transition only' + USING ERRCODE = '55000'; + END IF; + IF NEW.terminal_result_bytes IS NULL OR NEW.terminal_evidence_bytes IS NULL + OR NEW.terminal_result_digest IS NULL OR NEW.terminal_evidence_digest IS NULL THEN + RAISE EXCEPTION 'World activation terminal fence requires complete immutable result and evidence bytes' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +REVOKE ALL ON FUNCTION world_validate_original_start_session_activation_fence() FROM PUBLIC; +CREATE TRIGGER trg_world_original_start_session_activation_fence + BEFORE INSERT OR UPDATE OR DELETE ON world_canonical_instance_activation_fence + FOR EACH ROW EXECUTE FUNCTION world_validate_original_start_session_activation_fence(); + +CREATE FUNCTION world_reject_original_start_session_activation_fence_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + RAISE EXCEPTION 'World original StartSession activation fences are immutable and retained' + USING ERRCODE = '55000'; + RETURN NULL; +END; +$$; +REVOKE ALL ON FUNCTION world_reject_original_start_session_activation_fence_truncate() FROM PUBLIC; +CREATE TRIGGER trg_world_original_start_session_activation_fence_no_truncate + BEFORE TRUNCATE ON world_canonical_instance_activation_fence + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_original_start_session_activation_fence_truncate(); + +-- Every new V43 result, including a direct SQL insert, must belong to the exact pending protected +-- operation. The pre-existing operation rows are not rewritten or revalidated. +CREATE FUNCTION world_require_protected_canonical_activation_operation() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + fence "${serviceSchema}".world_canonical_instance_activation_fence%ROWTYPE; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'World canonical activation operation evidence is immutable' + USING ERRCODE = '55000'; + END IF; + SELECT * INTO fence FROM "${serviceSchema}".world_canonical_instance_activation_fence + WHERE activation_request_id=NEW.activation_request_id FOR UPDATE; + IF NOT FOUND + OR fence.operation_state IS DISTINCT FROM 'PENDING' + OR fence.canonical_game_instance_id IS DISTINCT FROM NEW.canonical_game_instance_id + OR fence.world_instance_id IS DISTINCT FROM NEW.world_instance_id + OR fence.expected_lifecycle_epoch IS DISTINCT FROM NEW.expected_lifecycle_epoch + OR fence.expected_row_version IS DISTINCT FROM NEW.expected_row_version + OR fence.preparing_evidence_bytes IS DISTINCT FROM NEW.preparing_evidence_bytes + OR NEW.request_bytes IS DISTINCT FROM + decode(convert_from(NEW.result_bytes, 'UTF8')::JSONB->>'requestBytesBase64','base64') + OR convert_from(NEW.result_bytes, 'UTF8')::JSONB->>'requestDigest' IS DISTINCT FROM NEW.request_digest THEN + RAISE EXCEPTION 'New World activation result lacks its exact pending Account-protected operation fence' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +REVOKE ALL ON FUNCTION world_require_protected_canonical_activation_operation() FROM PUBLIC; +CREATE TRIGGER trg_world_require_protected_canonical_activation_operation + BEFORE INSERT ON world_canonical_instance_activation_operation + FOR EACH ROW EXECUTE FUNCTION world_require_protected_canonical_activation_operation(); + +CREATE FUNCTION world_require_original_start_session_activation_terminal() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + result JSONB; + terminal JSONB; +BEGIN + IF NEW.operation_state='PENDING' THEN RETURN NULL; END IF; + result := convert_from(NEW.terminal_result_bytes, 'UTF8')::JSONB; + terminal := convert_from(NEW.terminal_evidence_bytes, 'UTF8')::JSONB; + IF NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_canonical_instance_activation_operation o + WHERE o.activation_request_id=NEW.activation_request_id + AND o.canonical_game_instance_id=NEW.canonical_game_instance_id + AND o.world_instance_id=NEW.world_instance_id + AND o.outcome=NEW.operation_state + AND o.result_bytes=NEW.terminal_result_bytes + AND o.result_digest=NEW.terminal_result_digest + AND o.request_bytes=decode(result->>'requestBytesBase64','base64') + AND o.preparing_evidence_bytes=NEW.preparing_evidence_bytes + ) OR jsonb_typeof(terminal) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(terminal)) <> 8 + OR terminal->>'schema' IS DISTINCT FROM 'world-original-start-session-activation-terminal-evidence/v1' + OR terminal->>'activationRequestId' IS DISTINCT FROM NEW.activation_request_id::TEXT + OR terminal->>'accountProtectionId' IS DISTINCT FROM NEW.account_protection_id::TEXT + OR terminal->>'accountProtectionFence' IS DISTINCT FROM NEW.account_protection_fence::TEXT + OR terminal->>'worldActivationFence' IS DISTINCT FROM NEW.world_activation_fence::TEXT + OR decode(terminal->>'accountProtectionEvidenceBytesBase64','base64') + IS DISTINCT FROM NEW.account_protection_evidence_bytes + OR decode(terminal->>'activationResultBytesBase64','base64') + IS DISTINCT FROM NEW.terminal_result_bytes + OR terminal->>'activationResultSha256' IS DISTINCT FROM NEW.terminal_result_digest + OR result->>'activationRequestId' IS DISTINCT FROM NEW.activation_request_id::TEXT + OR result->>'outcome' IS DISTINCT FROM NEW.operation_state THEN + RAISE EXCEPTION 'World terminal receipt is not the exact Account protection and committed lifecycle operation' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; +REVOKE ALL ON FUNCTION world_require_original_start_session_activation_terminal() FROM PUBLIC; +CREATE CONSTRAINT TRIGGER trg_world_original_start_session_activation_terminal + AFTER INSERT OR UPDATE ON world_canonical_instance_activation_fence + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION world_require_original_start_session_activation_terminal(); + +CREATE FUNCTION world_require_protected_activation_fence_for_operation() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + fence "${serviceSchema}".world_canonical_instance_activation_fence%ROWTYPE; +BEGIN + SELECT * INTO fence FROM "${serviceSchema}".world_canonical_instance_activation_fence + WHERE activation_request_id=NEW.activation_request_id; + IF NOT FOUND + OR fence.canonical_game_instance_id IS DISTINCT FROM NEW.canonical_game_instance_id + OR fence.world_instance_id IS DISTINCT FROM NEW.world_instance_id + OR fence.operation_state IS DISTINCT FROM NEW.outcome THEN + RAISE EXCEPTION 'World activation lifecycle result cannot commit without its exact protected terminal fence' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; +REVOKE ALL ON FUNCTION world_require_protected_activation_fence_for_operation() FROM PUBLIC; +CREATE CONSTRAINT TRIGGER trg_world_protected_activation_operation_terminal + AFTER INSERT ON world_canonical_instance_activation_operation + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION world_require_protected_activation_fence_for_operation(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1039__canonical_activation_preparation_schema.sql b/services/world-management-service/src/main/resources/db/migration/V1039__canonical_activation_preparation_schema.sql new file mode 100644 index 0000000000..3f2b392775 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1039__canonical_activation_preparation_schema.sql @@ -0,0 +1,38 @@ +-- Keep canonical activation's preparation schema correlated with the retained association schema. +-- V43 required schema-1 association/schema-2 preparation. V65 admits the schema-2 association and +-- its captured realm/catalog identity, whose selector-bearing preparation input is schema four. +-- [jooq ignore start] +DO $migration$ +DECLARE + definition TEXT; + original_oid OID; + original_acl ACLITEM[]; + old_fragment TEXT := $$AND p.input_json::JSONB->>'schemaVersion'='2'$$; + new_fragment TEXT := $replacement$AND ( + (a.schema_version=1 AND p.input_json::JSONB->>'schemaVersion'='2') + OR (a.schema_version=2 AND p.input_json::JSONB->>'schemaVersion'='4') + )$replacement$; +BEGIN + SELECT p.oid, p.proacl + INTO STRICT original_oid, original_acl + FROM pg_proc p + WHERE p.oid = '"${serviceSchema}".world_validate_canonical_activation_operation()'::REGPROCEDURE; + SELECT pg_get_functiondef( + '"${serviceSchema}".world_validate_canonical_activation_operation()'::REGPROCEDURE) + INTO STRICT definition; + + IF (length(definition)-length(replace(definition, old_fragment, '')))/length(old_fragment) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V65 canonical activation preparation schema discriminator'; + END IF; + definition := replace(definition, old_fragment, new_fragment); + + EXECUTE definition; + IF '"${serviceSchema}".world_validate_canonical_activation_operation()'::REGPROCEDURE + IS DISTINCT FROM original_oid + OR (SELECT p.proacl FROM pg_proc p WHERE p.oid = original_oid) + IS DISTINCT FROM original_acl THEN + RAISE EXCEPTION 'Canonical activation guard replacement changed function identity or grants'; + END IF; +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1040__world_run_owned_fixture_canonical_association.sql b/services/world-management-service/src/main/resources/db/migration/V1040__world_run_owned_fixture_canonical_association.sql new file mode 100644 index 0000000000..81383e1ae3 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1040__world_run_owned_fixture_canonical_association.sql @@ -0,0 +1,665 @@ +-- Retain run-owned fixture provenance on the existing canonical World row and association. +-- Human initial-admission hold owners remain unchanged; fixture holds remain unsupported. +ALTER TABLE world_instance + ADD COLUMN canonical_authority_kind VARCHAR(32); + +ALTER TABLE world_instance + ADD COLUMN fixture_provenance_digest VARCHAR(71); + +ALTER TABLE world_instance + ADD COLUMN game_session_tenant_id BIGINT; + +ALTER TABLE world_instance + ADD COLUMN game_session_game_instance_id BIGINT; + +ALTER TABLE world_instance + ADD COLUMN game_design_version_id BIGINT; + +ALTER TABLE world_instance + DROP CONSTRAINT ck_world_instance_canonical_creation_identity; + +ALTER TABLE world_instance + ADD CONSTRAINT ck_world_instance_canonical_creation_identity CHECK ( + ( + canonical_game_instance_id IS NULL + AND canonical_target_namespace IS NULL + AND canonical_tenant_id IS NULL + AND canonical_world_slug IS NULL + AND playable_state_namespace_id IS NULL + AND playable_state_scope IS NULL + AND public_production IS NULL + AND playtest_lifecycle_id IS NULL + AND playtest_state_generation IS NULL + AND canonical_launch_binding_operation_id IS NULL + AND canonical_authority_kind IS NULL + AND fixture_provenance_digest IS NULL + AND game_session_tenant_id IS NULL + AND game_session_game_instance_id IS NULL + AND game_design_version_id IS NULL + ) + OR + ( + canonical_game_instance_id IS NOT NULL + AND canonical_target_namespace IS NOT NULL + AND canonical_tenant_id IS NOT NULL + AND canonical_world_slug IS NOT NULL + AND playable_state_namespace_id IS NOT NULL + AND playable_state_scope IS NOT NULL + AND playable_state_scope = 'SHARED' + AND public_production IS TRUE + AND playtest_lifecycle_id IS NULL + AND playtest_state_generation IS NULL + AND canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_target_namespace COLLATE "C" ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_world_slug COLLATE "C" ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND octet_length(canonical_world_slug) BETWEEN 1 AND 120 + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND ( + ( + (canonical_authority_kind IS NULL OR canonical_authority_kind = 'HUMAN') + AND canonical_launch_binding_operation_id IS NOT NULL + AND canonical_launch_binding_operation_id + <> '00000000-0000-0000-0000-000000000000'::UUID + AND fixture_provenance_digest IS NULL + AND game_session_tenant_id IS NULL + AND game_session_game_instance_id IS NULL + AND game_design_version_id IS NULL + ) + OR + ( + canonical_authority_kind IS NOT NULL + AND canonical_authority_kind = 'RUN_OWNED_FIXTURE' + AND canonical_launch_binding_operation_id IS NULL + AND fixture_provenance_digest IS NOT NULL + AND fixture_provenance_digest COLLATE "C" ~ '^sha256:[0-9a-f]{64}$' + AND canonical_realm_id IS NOT NULL + AND canonical_realm_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND catalog_revision IS NOT NULL + AND catalog_revision > 0 + AND game_session_tenant_id IS NOT NULL + AND game_session_tenant_id > 0 + AND game_session_game_instance_id IS NOT NULL + AND game_session_game_instance_id > 0 + AND game_design_version_id IS NOT NULL + AND game_design_version_id > 0 + AND run_owned_fixture_binding_sha256 IS NOT NULL + AND run_owned_fixture_preparing_lifecycle_epoch IS NOT NULL + AND run_owned_fixture_preparing_lifecycle_epoch > 0 + ) + ) + ) + ); + +ALTER TABLE world_instance + ADD CONSTRAINT ck_world_instance_fixture_gs_allocation CHECK ( + (canonical_authority_kind IS NOT NULL + AND canonical_authority_kind = 'RUN_OWNED_FIXTURE' + AND game_session_tenant_id > 0 + AND game_session_game_instance_id > 0 + AND game_design_version_id > 0) + OR + (canonical_authority_kind IS DISTINCT FROM 'RUN_OWNED_FIXTURE' + AND game_session_tenant_id IS NULL + AND game_session_game_instance_id IS NULL + AND game_design_version_id IS NULL) + ); + +ALTER TABLE world_canonical_instance_association + ALTER COLUMN canonical_launch_binding_operation_id DROP NOT NULL; + +ALTER TABLE world_canonical_instance_association + ALTER COLUMN release_attestation_digest DROP NOT NULL; + +ALTER TABLE world_canonical_instance_association + ADD COLUMN canonical_authority_kind VARCHAR(32); + +ALTER TABLE world_canonical_instance_association + ADD COLUMN fixture_provenance_digest VARCHAR(71); + +ALTER TABLE world_canonical_instance_association + ADD COLUMN game_session_tenant_id BIGINT; + +ALTER TABLE world_canonical_instance_association + ADD COLUMN game_session_game_instance_id BIGINT; + +ALTER TABLE world_canonical_instance_association + ADD COLUMN game_design_version_id BIGINT; + +ALTER TABLE world_canonical_instance_association + ADD COLUMN preparation_input_digest VARCHAR(71); + +ALTER TABLE world_canonical_instance_association + ADD COLUMN preparing_lifecycle_epoch BIGINT; + +ALTER TABLE world_canonical_instance_association + ADD COLUMN game_session_association_response_bytes BYTEA; + +ALTER TABLE world_canonical_instance_association + DROP CONSTRAINT ck_world_canonical_instance_association_schema; + +ALTER TABLE world_canonical_instance_association + DROP CONSTRAINT ck_world_canonical_instance_association_ids; + +ALTER TABLE world_canonical_instance_association + DROP CONSTRAINT ck_world_canonical_instance_association_owner_keys; + +ALTER TABLE world_canonical_instance_association + DROP CONSTRAINT ck_world_canonical_instance_association_digests; + +ALTER TABLE world_canonical_instance_association + ADD CONSTRAINT ck_world_canonical_instance_association_schema CHECK ( + (schema_version = 1 + AND (canonical_authority_kind IS NULL OR canonical_authority_kind = 'HUMAN') + AND canonical_realm_id IS NULL + AND catalog_revision IS NULL) + OR + (schema_version = 2 + AND (canonical_authority_kind IS NULL OR canonical_authority_kind = 'HUMAN') + AND canonical_realm_id IS NOT NULL + AND canonical_realm_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND catalog_revision > 0) + OR + (schema_version = 3 + AND canonical_authority_kind IS NOT NULL + AND canonical_authority_kind = 'RUN_OWNED_FIXTURE' + AND canonical_realm_id IS NOT NULL + AND canonical_realm_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND catalog_revision > 0 + AND canonical_launch_binding_operation_id IS NULL + AND release_attestation_digest IS NULL + AND fixture_provenance_digest IS NOT NULL + AND fixture_provenance_digest COLLATE "C" ~ '^sha256:[0-9a-f]{64}$' + AND game_session_tenant_id IS NOT NULL + AND game_session_tenant_id > 0 + AND game_session_game_instance_id IS NOT NULL + AND game_session_game_instance_id > 0 + AND game_design_version_id IS NOT NULL + AND game_design_version_id > 0 + AND preparation_input_digest IS NOT NULL + AND preparation_input_digest COLLATE "C" ~ '^sha256:[0-9a-f]{64}$' + AND preparing_lifecycle_epoch IS NOT NULL + AND preparing_lifecycle_epoch > 0 + AND game_session_association_response_bytes IS NOT NULL + AND octet_length(game_session_association_response_bytes) > 0) + ); + +ALTER TABLE world_canonical_instance_association + ADD CONSTRAINT ck_world_canonical_instance_association_ids CHECK ( + canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND version_identity_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND (canonical_launch_binding_operation_id IS NULL + OR canonical_launch_binding_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID) + ); + +ALTER TABLE world_canonical_instance_association + ADD CONSTRAINT ck_world_canonical_instance_association_owner_keys CHECK ( + world_instance_id > 0 + AND local_tenant_key > 0 + AND private_game_instance_key > 0 + AND game_template_id > 0 + AND local_version_key > 0 + AND release_bundle_id > 0 + AND version_state_epoch > 0 + AND length(btrim(launch_descriptor_id)) BETWEEN 1 AND 64 + AND length(btrim(runtime_flags_json)) > 0 + AND length(btrim(generation_config_revision)) BETWEEN 1 AND 128 + AND length(btrim(published_release_bundle_ref)) BETWEEN 1 AND 128 + AND (script_patch_version IS NULL OR length(btrim(script_patch_version)) BETWEEN 1 AND 100) + AND (remap_set_id IS NULL OR length(btrim(remap_set_id)) BETWEEN 1 AND 64) + ); + +ALTER TABLE world_canonical_instance_association + ADD CONSTRAINT ck_world_canonical_instance_association_digests CHECK ( + source_evidence_digest COLLATE "C" ~ '^sha256:[0-9a-f]{64}$' + AND intake_request_digest COLLATE "C" ~ '^sha256:[0-9a-f]{64}$' + AND intake_receipt_digest COLLATE "C" ~ '^sha256:[0-9a-f]{64}$' + AND descriptor_request_digest COLLATE "C" ~ '^sha256:[0-9a-f]{64}$' + AND descriptor_result_digest COLLATE "C" ~ '^sha256:[0-9a-f]{64}$' + AND ( + (schema_version IN (1, 2) + AND release_attestation_digest COLLATE "C" ~ '^sha256:[0-9a-f]{64}$') + OR (schema_version = 3 AND release_attestation_digest IS NULL) + ) + ); + +ALTER TABLE world_canonical_instance_association + ADD CONSTRAINT ck_world_canonical_instance_association_fixture_metadata CHECK ( + (schema_version = 3 + AND fixture_provenance_digest IS NOT NULL + AND fixture_provenance_digest COLLATE "C" ~ '^sha256:[0-9a-f]{64}$' + AND game_session_tenant_id IS NOT NULL + AND game_session_tenant_id > 0 + AND game_session_game_instance_id IS NOT NULL + AND game_session_game_instance_id > 0 + AND game_design_version_id IS NOT NULL + AND game_design_version_id > 0 + AND preparation_input_digest IS NOT NULL + AND preparation_input_digest COLLATE "C" ~ '^sha256:[0-9a-f]{64}$' + AND preparing_lifecycle_epoch IS NOT NULL + AND preparing_lifecycle_epoch > 0 + AND game_session_association_response_bytes IS NOT NULL + AND octet_length(game_session_association_response_bytes) > 0) + OR + (schema_version IN (1, 2) + AND fixture_provenance_digest IS NULL + AND game_session_tenant_id IS NULL + AND game_session_game_instance_id IS NULL + AND game_design_version_id IS NULL + AND preparation_input_digest IS NULL + AND preparing_lifecycle_epoch IS NULL + AND game_session_association_response_bytes IS NULL) + ); + +ALTER TABLE world_canonical_instance_association + ADD CONSTRAINT uq_world_canonical_instance_association_fixture_owner_fk + UNIQUE (canonical_authority_kind, fixture_provenance_digest, + canonical_game_instance_id, canonical_target_namespace, canonical_tenant_id, + canonical_world_slug); + +ALTER TABLE world_canonical_instance_association + ADD CONSTRAINT fk_world_canonical_instance_association_fixture_world_row + FOREIGN KEY (world_instance_id) + REFERENCES world_instance (id) + ON DELETE RESTRICT; + +CREATE UNIQUE INDEX uq_world_canonical_instance_association_fixture_operation + ON world_canonical_instance_association (control_plane_request_id) + WHERE canonical_authority_kind = 'RUN_OWNED_FIXTURE'; + +-- Run-owned fixture lifecycle inserts use the same retained World row owner but a closed typed +-- branch. Preserve the existing Human validation below the fixture fast path. +-- [jooq ignore start] +DO $migration$ +DECLARE + original TEXT; + insert_anchor TEXT := $anchor$ IF NEW.canonical_game_instance_id IS NULL THEN + RETURN NEW; + END IF; + IF NEW.canonical_realm_id IS NULL$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_validate_canonical_prepare_identity()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,insert_anchor,'')))/length(insert_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V64 canonical World identity insert anchor'; + END IF; + original := replace(original, insert_anchor, + $replacement$ IF NEW.run_owned_fixture_binding_sha256 IS NOT NULL + AND (NEW.status IS DISTINCT FROM 'PREPARING' + OR NEW.run_owned_fixture_preparing_lifecycle_epoch IS DISTINCT FROM 1 + OR NEW.lifecycle_epoch IS DISTINCT FROM NEW.run_owned_fixture_preparing_lifecycle_epoch) THEN + RAISE EXCEPTION 'New World rows carrying fixture binding evidence must begin PREPARING at epoch 1' + USING ERRCODE = '23514'; + END IF; + IF NEW.canonical_game_instance_id IS NULL THEN + RETURN NEW; + END IF; + IF NEW.canonical_authority_kind = 'RUN_OWNED_FIXTURE' THEN + SELECT * INTO version_identity + FROM world_authored_version_identity vi + WHERE vi.target_namespace = NEW.canonical_target_namespace + AND vi.canonical_tenant_id = NEW.canonical_tenant_id + AND vi.world_slug = NEW.canonical_world_slug + AND vi.game_design_version_id = NEW.game_design_version_id; + IF NEW.canonical_launch_binding_operation_id IS NOT NULL + OR NEW.fixture_provenance_digest IS NULL + OR NEW.fixture_provenance_digest COLLATE "C" !~ '^sha256:[0-9a-f]{64}$' + OR NEW.game_session_tenant_id IS NULL + OR NEW.game_session_tenant_id <= 0 + OR NEW.game_session_game_instance_id IS NULL + OR NEW.game_session_game_instance_id <= 0 + OR NEW.game_design_version_id IS NULL + OR NEW.game_design_version_id <= 0 + OR NEW.run_owned_fixture_binding_sha256 COLLATE "C" !~ '^[0-9a-f]{64}$' + OR NEW.run_owned_fixture_preparing_lifecycle_epoch IS NULL + OR NEW.run_owned_fixture_preparing_lifecycle_epoch <= 0 + OR NEW.status IS DISTINCT FROM 'PREPARING' + OR NEW.lifecycle_epoch IS DISTINCT FROM NEW.run_owned_fixture_preparing_lifecycle_epoch + OR version_identity.operation_id IS NULL + OR NEW.tenant_id IS DISTINCT FROM version_identity.local_tenant_key + OR NEW.version_id IS DISTINCT FROM version_identity.local_version_key + OR NOT EXISTS ( + SELECT 1 + FROM world_authored_source_intake si + WHERE si.operation_id = version_identity.intake_operation_id + AND si.intake_request_id = version_identity.intake_request_id + AND si.local_tenant_key = NEW.tenant_id + AND si.source_provenance_kind = 'NEW_GAME_ROW' + ) THEN + RAISE EXCEPTION 'Run-owned fixture World row differs from actual World source and Version owners' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF NEW.canonical_authority_kind IS NOT NULL + AND NEW.canonical_authority_kind IS DISTINCT FROM 'HUMAN' THEN + RAISE EXCEPTION 'New canonical World row requires an explicit authority variant' + USING ERRCODE = '23514'; + END IF; + IF NEW.canonical_realm_id IS NULL$replacement$); + EXECUTE original; +END; +$migration$; + +DO $migration$ +DECLARE + original TEXT; + authority_anchor TEXT := $anchor$ IF NEW.schema_version IS DISTINCT FROM 2 + OR NEW.canonical_realm_id IS NULL + OR NEW.canonical_realm_id = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.catalog_revision IS NULL + OR NEW.catalog_revision <= 0 THEN$anchor$; + begin_anchor TEXT := $anchor$ SELECT * INTO instance FROM world_instance WHERE id = NEW.world_instance_id FOR KEY SHARE;$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_validate_canonical_instance_association()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,authority_anchor,'')))/length(authority_anchor) <> 1 + OR (length(original)-length(replace(original,begin_anchor,'')))/length(begin_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V64 canonical association authority guard anchor'; + END IF; + original := replace(original, begin_anchor, + $replacement$ SELECT * INTO instance FROM world_instance WHERE id = NEW.world_instance_id FOR KEY SHARE; + IF NEW.schema_version = 3 AND NEW.canonical_authority_kind = 'RUN_OWNED_FIXTURE' THEN + IF instance.id IS NULL THEN + RAISE EXCEPTION 'Run-owned fixture association requires its allocated World row' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO version_identity + FROM world_authored_version_identity + WHERE operation_id = NEW.version_identity_operation_id; + IF NOT FOUND + OR instance.id IS NULL + OR instance.canonical_authority_kind IS DISTINCT FROM 'RUN_OWNED_FIXTURE' + OR instance.canonical_game_instance_id IS DISTINCT FROM NEW.canonical_game_instance_id + OR instance.canonical_target_namespace IS DISTINCT FROM NEW.canonical_target_namespace + OR instance.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR instance.canonical_world_slug IS DISTINCT FROM NEW.canonical_world_slug + OR instance.playable_state_namespace_id IS DISTINCT FROM NEW.playable_state_namespace_id + OR instance.playable_state_scope IS DISTINCT FROM NEW.playable_state_scope + OR instance.public_production IS DISTINCT FROM NEW.public_production + OR instance.control_plane_request_id IS DISTINCT FROM NEW.control_plane_request_id + OR instance.canonical_launch_binding_operation_id IS NOT NULL + OR instance.fixture_provenance_digest IS DISTINCT FROM NEW.fixture_provenance_digest + OR instance.game_session_tenant_id IS DISTINCT FROM NEW.game_session_tenant_id + OR instance.game_session_game_instance_id IS DISTINCT FROM NEW.game_session_game_instance_id + OR instance.game_design_version_id IS DISTINCT FROM NEW.game_design_version_id + OR instance.tenant_id IS DISTINCT FROM NEW.local_tenant_key + OR instance.game_instance_id IS DISTINCT FROM NEW.private_game_instance_key + OR instance.version_id IS DISTINCT FROM NEW.local_version_key + OR instance.game_template_id IS DISTINCT FROM NEW.game_template_id + OR instance.launch_descriptor_id IS DISTINCT FROM NEW.launch_descriptor_id + OR instance.version_state_epoch IS DISTINCT FROM NEW.version_state_epoch + OR instance.run_owned_fixture_preparing_lifecycle_epoch IS DISTINCT FROM NEW.preparing_lifecycle_epoch + OR NEW.preparation_input_digest IS DISTINCT FROM + ('sha256:' || instance.run_owned_fixture_binding_sha256) + OR NEW.fixture_provenance_digest IS NULL + OR NEW.fixture_provenance_digest COLLATE "C" !~ '^sha256:[0-9a-f]{64}$' + OR octet_length(NEW.game_session_association_response_bytes) <= 0 + OR NEW.canonical_launch_binding_operation_id IS NOT NULL + OR NEW.release_attestation_digest IS NOT NULL + OR version_identity.target_namespace IS DISTINCT FROM NEW.canonical_target_namespace + OR version_identity.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR version_identity.world_slug IS DISTINCT FROM NEW.canonical_world_slug + OR version_identity.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR version_identity.local_tenant_key IS DISTINCT FROM NEW.local_tenant_key + OR version_identity.local_version_key IS DISTINCT FROM NEW.local_version_key + OR version_identity.game_design_version_id IS DISTINCT FROM NEW.game_design_version_id + OR version_identity.source_operation_id IS DISTINCT FROM NEW.source_operation_id + OR version_identity.source_evidence_digest IS DISTINCT FROM NEW.source_evidence_digest + OR version_identity.intake_operation_id IS DISTINCT FROM NEW.intake_operation_id + OR version_identity.intake_request_id IS DISTINCT FROM NEW.intake_request_id + OR version_identity.intake_request_digest IS DISTINCT FROM NEW.intake_request_digest + OR version_identity.intake_receipt_digest IS DISTINCT FROM NEW.intake_receipt_digest + OR version_identity.intake_operation_id IS DISTINCT FROM ( + SELECT si.operation_id FROM world_authored_source_intake si + WHERE si.operation_id = NEW.intake_operation_id + AND si.intake_request_id = NEW.intake_request_id + AND si.local_tenant_key = NEW.local_tenant_key + AND si.source_operation_id = NEW.source_operation_id + AND si.source_evidence_digest = NEW.source_evidence_digest + AND si.receipt_digest = NEW.intake_receipt_digest + ) THEN + RAISE EXCEPTION 'Run-owned fixture association differs from its exact World, source, Version, or GS owner readback' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + $replacement$); + original := replace(original, authority_anchor, + $replacement$ IF NOT ( + (NEW.schema_version IS NOT DISTINCT FROM 2 + AND (NEW.canonical_authority_kind IS NULL + OR NEW.canonical_authority_kind IS NOT DISTINCT FROM 'HUMAN')) + OR (NEW.schema_version IS NOT DISTINCT FROM 3 + AND NEW.canonical_authority_kind IS NOT DISTINCT FROM 'RUN_OWNED_FIXTURE')) + OR NEW.canonical_realm_id IS NULL + OR NEW.canonical_realm_id = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.catalog_revision IS NULL + OR NEW.catalog_revision <= 0 THEN$replacement$); + EXECUTE original; +END; +$migration$; + +DO $migration$ +DECLARE + original TEXT; + immutable_anchor TEXT := $anchor$ OR OLD.canonical_launch_binding_operation_id + IS DISTINCT FROM NEW.canonical_launch_binding_operation_id + OR OLD.canonical_realm_id IS DISTINCT FROM NEW.canonical_realm_id + OR OLD.catalog_revision IS DISTINCT FROM NEW.catalog_revision THEN$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_validate_canonical_prepare_identity()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,immutable_anchor,'')))/length(immutable_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V64 canonical World identity immutability anchor'; + END IF; + original := replace(original, immutable_anchor, + $replacement$ OR OLD.canonical_launch_binding_operation_id + IS DISTINCT FROM NEW.canonical_launch_binding_operation_id + OR OLD.canonical_realm_id IS DISTINCT FROM NEW.canonical_realm_id + OR OLD.catalog_revision IS DISTINCT FROM NEW.catalog_revision + OR OLD.canonical_authority_kind IS DISTINCT FROM NEW.canonical_authority_kind + OR OLD.fixture_provenance_digest IS DISTINCT FROM NEW.fixture_provenance_digest + OR OLD.game_session_tenant_id IS DISTINCT FROM NEW.game_session_tenant_id + OR OLD.game_session_game_instance_id IS DISTINCT FROM NEW.game_session_game_instance_id + OR OLD.game_design_version_id IS DISTINCT FROM NEW.game_design_version_id THEN$replacement$); + EXECUTE original; +END; +$migration$; +-- [jooq ignore stop] + + +-- Existing World activation and first-admission owners remain Human-only. Fixture lifecycle +-- activation is closed at the World row trigger before any lifecycle or owner write. +-- [jooq ignore start] +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$BEGIN + IF OLD.canonical_game_instance_id IS NOT NULL AND NEW.status = 'ACTIVE'$anchor$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_guard_canonical_activation_transition()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,anchor,'')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact current canonical activation-transition guard anchor'; + END IF; + original := replace(original, anchor, $replacement$BEGIN + IF OLD.canonical_authority_kind = 'RUN_OWNED_FIXTURE' + OR NEW.canonical_authority_kind = 'RUN_OWNED_FIXTURE' THEN + RAISE EXCEPTION 'Run-owned fixture World lifecycle transitions are disabled' + USING ERRCODE = '23514'; + END IF; + IF (OLD.run_owned_fixture_binding_sha256 IS NOT NULL + OR NEW.run_owned_fixture_binding_sha256 IS NOT NULL) + AND (OLD.status IS DISTINCT FROM NEW.status + OR OLD.lifecycle_epoch IS DISTINCT FROM NEW.lifecycle_epoch) THEN + RAISE EXCEPTION 'World lifecycle transitions are disabled for rows carrying fixture binding evidence' + USING ERRCODE = '23514'; + END IF; + IF OLD.canonical_game_instance_id IS NOT NULL AND NEW.status = 'ACTIVE'$replacement$); + EXECUTE original; +END; +$migration$; + +-- A fixture association cannot acquire a hold through either the typed owner or a legacy +-- numeric request. Human and legacy acquisitions continue through their existing validation. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$BEGIN + IF TG_OP = 'DELETE' THEN$anchor$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_guard_canonical_initial_admission_hold()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,anchor,'')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact current initial-admission hold guard anchor'; + END IF; + original := replace(original, anchor, $replacement$BEGIN + IF TG_OP = 'INSERT' AND EXISTS ( + SELECT 1 + FROM "${serviceSchema}".world_canonical_instance_association a + JOIN "${serviceSchema}".world_instance wi ON wi.id = a.world_instance_id + WHERE a.schema_version = 3 + AND a.canonical_authority_kind = 'RUN_OWNED_FIXTURE' + AND (a.canonical_game_instance_id = NEW.canonical_game_instance_id + OR (wi.tenant_id = NEW.tenant_id + AND wi.game_instance_id = NEW.game_instance_id + AND wi.version_id = NEW.version_id))) THEN + RAISE EXCEPTION 'Run-owned fixture initial-admission holds are disabled' + USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'DELETE' THEN$replacement$); + EXECUTE original; +END; +$migration$; + +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ RAISE EXCEPTION 'Canonical initial-admission hold identity is missing or untyped' + USING ERRCODE = '55000'; + END IF; + + SELECT a.* INTO association_row$anchor$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_finalize_canonical_initial_admission_hold(uuid,uuid,text,text,text,text,bigint,timestamptz,boolean,bytea,text)'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,anchor,'')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact current initial-admission finalizer candidate anchor'; + END IF; + original := replace(original, anchor, $replacement$ RAISE EXCEPTION 'Canonical initial-admission hold identity is missing or untyped' + USING ERRCODE = '55000'; + END IF; + IF EXISTS ( + SELECT 1 + FROM "${serviceSchema}".world_canonical_instance_association a + JOIN "${serviceSchema}".world_instance wi ON wi.id = a.world_instance_id + WHERE a.schema_version = 3 + AND a.canonical_authority_kind = 'RUN_OWNED_FIXTURE' + AND (a.canonical_game_instance_id = candidate.canonical_game_instance_id + OR (wi.tenant_id = candidate.tenant_id + AND wi.game_instance_id = candidate.game_instance_id + AND wi.version_id = candidate.version_id))) THEN + RAISE EXCEPTION 'Run-owned fixture initial-admission hold finalization is disabled' + USING ERRCODE = '23514'; + END IF; + + SELECT a.* INTO association_row$replacement$); + EXECUTE original; +END; +$migration$; +-- [jooq ignore stop] + +-- Placement and World-side player-admission hold owners stay closed for the fixture variant. +-- These exact owners reject direct SQL inserts before claiming or changing lifecycle rows. +-- [jooq ignore start] +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$BEGIN + IF TG_OP <> 'INSERT' THEN$anchor$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_guard_initial_location_operation()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,anchor,'')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact current initial-location operation owner anchor'; + END IF; + original := replace(original, anchor, $replacement$BEGIN + IF TG_OP = 'INSERT' AND EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_canonical_instance_association a + WHERE (a.world_instance_id = NEW.world_instance_id + OR a.canonical_game_instance_id = NEW.canonical_game_instance_id) + AND a.schema_version = 3 + AND a.canonical_authority_kind = 'RUN_OWNED_FIXTURE') THEN + RAISE EXCEPTION 'Run-owned fixture initial-location placement is disabled' + USING ERRCODE = '23514'; + END IF; + IF TG_OP <> 'INSERT' THEN$replacement$); + EXECUTE original; +END; +$migration$; + +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$BEGIN + IF TG_OP = 'UPDATE' THEN$anchor$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_guard_initial_character_location()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,anchor,'')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact current initial-character location owner anchor'; + END IF; + original := replace(original, anchor, $replacement$BEGIN + IF TG_OP = 'INSERT' AND EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_canonical_instance_association a + WHERE (a.world_instance_id = NEW.world_instance_id + OR a.canonical_game_instance_id = NEW.canonical_game_instance_id) + AND a.schema_version = 3 + AND a.canonical_authority_kind = 'RUN_OWNED_FIXTURE') THEN + RAISE EXCEPTION 'Run-owned fixture initial-character placement is disabled' + USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'UPDATE' THEN$replacement$); + EXECUTE original; +END; +$migration$; + +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$BEGIN + IF TG_OP <> 'INSERT' THEN$anchor$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_validate_player_admission_hold()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,anchor,'')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact current World player-admission hold owner anchor'; + END IF; + original := replace(original, anchor, $replacement$BEGIN + IF TG_OP = 'INSERT' AND EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_canonical_instance_association a + WHERE (a.world_instance_id = NEW.world_instance_id + OR a.canonical_game_instance_id = NEW.canonical_game_instance_id) + AND a.schema_version = 3 + AND a.canonical_authority_kind = 'RUN_OWNED_FIXTURE') THEN + RAISE EXCEPTION 'Run-owned fixture World player-admission holds are disabled' + USING ERRCODE = '23514'; + END IF; + IF TG_OP <> 'INSERT' THEN$replacement$); + EXECUTE original; +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1041__world_run_owned_fixed_preset_preparation.sql b/services/world-management-service/src/main/resources/db/migration/V1041__world_run_owned_fixed_preset_preparation.sql new file mode 100644 index 0000000000..cce486f081 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1041__world_run_owned_fixed_preset_preparation.sql @@ -0,0 +1,1842 @@ +-- The run-owned local fixture is a separate V67 composition. Human frozen-capture preparation +-- retains its original capture identity, graph, and execution path without a preset exception. +ALTER TABLE world_canonical_instance_preparation + ALTER COLUMN capture_id DROP NOT NULL; + +ALTER TABLE world_canonical_instance_preparation + ADD COLUMN fixed_preset_id VARCHAR(96); + +ALTER TABLE world_canonical_instance_preparation + ADD COLUMN fixed_preset_content_digest VARCHAR(71); + +ALTER TABLE world_canonical_instance_preparation + ADD COLUMN fixed_preset_binding_digest VARCHAR(71); + +ALTER TABLE world_canonical_instance_preparation + ADD CONSTRAINT ck_world_canonical_preparation_one_authority CHECK ( + (capture_id IS NOT NULL AND fixed_preset_id IS NULL + AND fixed_preset_content_digest IS NULL AND fixed_preset_binding_digest IS NULL) + OR (capture_id IS NULL AND fixed_preset_id IS NOT NULL + AND fixed_preset_content_digest IS NOT NULL AND fixed_preset_binding_digest IS NOT NULL + AND fixed_preset_id = 'firemud-demo-topology-v1' + AND fixed_preset_content_digest = + 'sha256:f817af2770072bab0384c30c19b8cd30fce7a5a33f7587faed0024aa7c0909bc' + AND fixed_preset_binding_digest = input_digest + AND fixed_preset_binding_digest ~ '^sha256:[0-9a-f]{64}$') + ); + +-- A fixture owner is the actual immutable V67 association, never an authored Draft commit. +ALTER TABLE world_canonical_instance_association + ADD CONSTRAINT uq_world_fixed_preset_fixture_owner UNIQUE ( + canonical_authority_kind, fixture_provenance_digest, world_instance_id, + control_plane_request_id); + +-- Historical Human identities and the original Human row producer retain nullable metadata. +-- The closed Human arm still requires every original Draft identity and its existing FK. +ALTER TABLE world_authored_topology_identity + ADD COLUMN preparation_authority_kind VARCHAR(32); + +ALTER TABLE world_authored_topology_identity + ADD COLUMN fixture_provenance_digest VARCHAR(71); + +ALTER TABLE world_authored_topology_identity + ADD COLUMN fixture_world_instance_id BIGINT; + +ALTER TABLE world_authored_topology_identity + ADD COLUMN fixture_operation_id VARCHAR(128); + +ALTER TABLE world_authored_topology_identity + ADD CONSTRAINT fk_topology_fixed_preset_fixture_owner FOREIGN KEY ( + preparation_authority_kind, fixture_provenance_digest, fixture_world_instance_id, + fixture_operation_id) + REFERENCES world_canonical_instance_association ( + canonical_authority_kind, fixture_provenance_digest, world_instance_id, + control_plane_request_id) ON DELETE RESTRICT; + +ALTER TABLE world_authored_topology_identity + ALTER COLUMN request_id DROP NOT NULL; + +ALTER TABLE world_authored_topology_identity + ALTER COLUMN commit_id DROP NOT NULL; + +ALTER TABLE world_authored_topology_identity + ALTER COLUMN revision_id DROP NOT NULL; + +ALTER TABLE world_authored_topology_identity + ALTER COLUMN revision_order DROP NOT NULL; + +ALTER TABLE world_authored_topology_identity + ADD CONSTRAINT ck_topology_fixed_preset_authority CHECK ( + ((preparation_authority_kind IS NULL OR preparation_authority_kind = 'HUMAN') + AND request_id IS NOT NULL AND commit_id IS NOT NULL + AND revision_id IS NOT NULL AND revision_order IS NOT NULL AND fixture_provenance_digest IS NULL + AND fixture_world_instance_id IS NULL AND fixture_operation_id IS NULL) + OR (preparation_authority_kind IS NOT NULL + AND preparation_authority_kind = 'RUN_OWNED_FIXTURE' AND request_id IS NULL AND commit_id IS NULL + AND revision_id IS NULL AND revision_order IS NULL + AND family IN ('REGION','ZONE','ROOM','ROOM_EXIT') + AND fixture_provenance_digest IS NOT NULL + AND fixture_provenance_digest ~ '^sha256:[0-9a-f]{64}$' + AND fixture_world_instance_id IS NOT NULL AND fixture_world_instance_id > 0 + AND fixture_operation_id IS NOT NULL) + ); + +ALTER TABLE world_region_draft_execution_manifest + ADD COLUMN preparation_authority_kind VARCHAR(32) NOT NULL DEFAULT 'HUMAN'; + +ALTER TABLE world_region_draft_execution_manifest + ADD COLUMN fixture_provenance_digest VARCHAR(71); + +ALTER TABLE world_region_draft_execution_manifest + ADD COLUMN fixture_world_instance_id BIGINT; + +ALTER TABLE world_region_draft_execution_manifest + ADD COLUMN fixture_operation_id VARCHAR(128); + +ALTER TABLE world_region_draft_execution_manifest + ADD CONSTRAINT fk_region_manifest_fixed_preset_fixture_owner FOREIGN KEY ( + preparation_authority_kind, fixture_provenance_digest, fixture_world_instance_id, + fixture_operation_id) + REFERENCES world_canonical_instance_association ( + canonical_authority_kind, fixture_provenance_digest, world_instance_id, + control_plane_request_id) ON DELETE RESTRICT; + +ALTER TABLE world_region_draft_execution_manifest + ADD CONSTRAINT ck_region_manifest_fixed_preset_authority CHECK ( + (preparation_authority_kind = 'HUMAN' AND fixture_provenance_digest IS NULL + AND fixture_world_instance_id IS NULL AND fixture_operation_id IS NULL) + OR (preparation_authority_kind = 'RUN_OWNED_FIXTURE' AND row_operation = 'INSERT' AND expected_old IS NULL + AND table_name IN ('region','zone','room','room_exit','world_authored_topology_identity') AND fixture_provenance_digest IS NOT NULL + AND fixture_provenance_digest ~ '^sha256:[0-9a-f]{64}$' + AND fixture_world_instance_id IS NOT NULL AND fixture_world_instance_id > 0 + AND fixture_operation_id IS NOT NULL) + ); + +ALTER TABLE world_canonical_instance_preparation_execution_manifest + ADD COLUMN preparation_authority_kind VARCHAR(32) NOT NULL DEFAULT 'HUMAN'; + +ALTER TABLE world_canonical_instance_preparation_execution_manifest + ADD COLUMN fixture_provenance_digest VARCHAR(71); + +ALTER TABLE world_canonical_instance_preparation_execution_manifest + ADD COLUMN fixture_world_instance_id BIGINT; + +ALTER TABLE world_canonical_instance_preparation_execution_manifest + ADD COLUMN fixture_operation_id VARCHAR(128); + +ALTER TABLE world_canonical_instance_preparation_execution_manifest + ADD CONSTRAINT fk_prepare_manifest_fixed_preset_fixture_owner FOREIGN KEY ( + preparation_authority_kind, fixture_provenance_digest, fixture_world_instance_id, + fixture_operation_id) + REFERENCES world_canonical_instance_association ( + canonical_authority_kind, fixture_provenance_digest, world_instance_id, + control_plane_request_id) ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE; + +ALTER TABLE world_canonical_instance_preparation_execution_manifest + ALTER COLUMN capture_id DROP NOT NULL; + +ALTER TABLE world_canonical_instance_preparation_execution_manifest + ADD COLUMN fixture_plan JSONB; + +-- PostgreSQL JSON evidence predicates are independently exercised by native owner proof. +-- [jooq ignore start] +-- Replace only the original anonymous table-name CHECK, located by its expression rather +-- than a PostgreSQL/H2 generated name. Human authority keeps its original closed row families. +DO $migration$ +DECLARE + original_name TEXT; +BEGIN + SELECT c.conname INTO STRICT original_name FROM pg_constraint c + WHERE c.conrelid = '"${serviceSchema}".world_canonical_instance_preparation_execution_manifest'::REGCLASS + AND c.contype = 'c' AND pg_get_constraintdef(c.oid) LIKE '%table_name%' + AND pg_get_constraintdef(c.oid) NOT LIKE '%preparation_authority_kind%'; + EXECUTE format('ALTER TABLE "${serviceSchema}".world_canonical_instance_preparation_execution_manifest DROP CONSTRAINT %I', original_name); +END; +$migration$; +ALTER TABLE world_canonical_instance_preparation_execution_manifest + ADD CONSTRAINT ck_prepare_manifest_table_name CHECK ( + table_name IN ('world_instance','region_instance','zone_instance','room_instance', + 'room_instance_exit','world_canonical_instance_topology_identity', + 'world_canonical_instance_preparation') + OR (table_name = 'world_canonical_instance_association' + AND preparation_authority_kind = 'RUN_OWNED_FIXTURE')); + +ALTER TABLE world_canonical_instance_preparation_execution_manifest + ADD CONSTRAINT ck_prepare_manifest_fixed_preset_authority CHECK ( + (preparation_authority_kind = 'HUMAN' AND capture_id IS NOT NULL + AND table_name <> 'world_canonical_instance_association' + AND (table_name <> 'world_canonical_instance_preparation' OR ( + expected_new->>'capture_id' = capture_id::TEXT + AND expected_new->>'fixed_preset_id' IS NULL + AND expected_new->>'fixed_preset_content_digest' IS NULL + AND expected_new->>'fixed_preset_binding_digest' IS NULL)) + AND fixture_plan IS NULL AND fixture_provenance_digest IS NULL + AND fixture_world_instance_id IS NULL AND fixture_operation_id IS NULL) + OR (preparation_authority_kind = 'RUN_OWNED_FIXTURE' AND capture_id IS NULL AND fixture_plan IS NOT NULL + AND jsonb_typeof(fixture_plan) = 'object' + AND table_name IN ('world_instance','world_canonical_instance_association', + 'region_instance','zone_instance','room_instance','room_instance_exit', + 'world_canonical_instance_topology_identity','world_canonical_instance_preparation') + AND fixture_provenance_digest IS NOT NULL + AND fixture_provenance_digest ~ '^sha256:[0-9a-f]{64}$' + AND fixture_world_instance_id IS NOT NULL AND fixture_world_instance_id > 0 + AND fixture_operation_id IS NOT NULL) + ); + +-- [jooq ignore stop] + +-- [jooq ignore start] +-- This owner emits two exact allocation manifests, consuming the first through the unchanged +-- tenant guard and the second through the closed fixture association execution arm. Exceptions roll back the whole SQL statement. +CREATE FUNCTION world_allocate_run_owned_fixture_instance(p_world JSONB, p_association JSONB) +RETURNS BIGINT +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + world_row "${serviceSchema}".world_instance%ROWTYPE; + association_row "${serviceSchema}".world_canonical_instance_association%ROWTYPE; + stored_world JSONB; + stored_association JSONB; + allocation_plan JSONB; +BEGIN + IF current_setting('transaction_isolation') <> 'read committed' + OR current_setting('transaction_read_only') <> 'off' + OR jsonb_typeof(p_world) IS DISTINCT FROM 'object' + OR jsonb_typeof(p_association) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'Fixture allocation requires its writable READ COMMITTED owner transaction'; + END IF; + world_row := jsonb_populate_record(NULL::"${serviceSchema}".world_instance, + p_world || jsonb_build_object('created_at', CURRENT_TIMESTAMP::TIMESTAMP, + 'updated_at', CURRENT_TIMESTAMP::TIMESTAMP, 'row_version', 0)); + association_row := jsonb_populate_record( + NULL::"${serviceSchema}".world_canonical_instance_association, p_association); + IF p_world IS DISTINCT FROM to_jsonb(world_row) - ARRAY[ + 'created_at','updated_at','row_version','failure_reason', + 'termination_request_id','terminated_at'] + OR p_association IS DISTINCT FROM to_jsonb(association_row) + OR world_row.id IS NULL OR world_row.id <= 0 THEN + RAISE EXCEPTION 'Fixture allocation requires complete exact owner row values'; + END IF; + PERFORM 1 FROM "${serviceSchema}".world_authored_source_intake + WHERE operation_id = association_row.intake_operation_id FOR UPDATE; + IF NOT FOUND THEN RAISE EXCEPTION 'Fixture allocation source owner is missing'; END IF; + PERFORM 1 FROM "${serviceSchema}".world_authored_version_identity + WHERE operation_id = association_row.version_identity_operation_id FOR UPDATE; + IF NOT FOUND THEN RAISE EXCEPTION 'Fixture allocation Version owner is missing'; END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_preparation_execution_manifest + WHERE transaction_id = txid_current()) THEN + RAISE EXCEPTION 'Fixture allocation cannot adopt pending preparation manifests'; + END IF; + allocation_plan := jsonb_build_object( + 'schema', 'firemud.run-owned-world-allocation.v1', + 'association', to_jsonb(association_row), + 'world', to_jsonb(world_row), + 'gameSessionResponseBytesDigest', 'sha256:' || + encode(sha256(association_row.game_session_association_response_bytes), 'hex')); + -- Only this existing manifest-owner FK is deferred for the first-row statement. No + -- association-to-World constraint or trigger is deferred; resources stay association-bound. + SET CONSTRAINTS fk_prepare_manifest_fixed_preset_fixture_owner DEFERRED; + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest ( + transaction_id, table_name, row_id, canonical_game_instance_id, target_namespace, + canonical_tenant_id, canonical_version_id, version_identity_operation_id, capture_id, + local_tenant_key, input_digest, expected_new, preparation_authority_kind, + fixture_provenance_digest, fixture_world_instance_id, fixture_operation_id, fixture_plan) + VALUES (txid_current(), 'world_instance', world_row.id, + association_row.canonical_game_instance_id, association_row.canonical_target_namespace, + association_row.canonical_tenant_id, association_row.canonical_version_id, + association_row.version_identity_operation_id, NULL, association_row.local_tenant_key, + association_row.preparation_input_digest, to_jsonb(world_row), 'RUN_OWNED_FIXTURE', + association_row.fixture_provenance_digest, association_row.world_instance_id, + association_row.control_plane_request_id, allocation_plan); + INSERT INTO "${serviceSchema}".world_instance SELECT (world_row).*; + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest ( + transaction_id, table_name, row_id, canonical_game_instance_id, target_namespace, + canonical_tenant_id, canonical_version_id, version_identity_operation_id, capture_id, + local_tenant_key, input_digest, expected_new, preparation_authority_kind, + fixture_provenance_digest, fixture_world_instance_id, fixture_operation_id, fixture_plan) + VALUES (txid_current(), 'world_canonical_instance_association', world_row.id, + association_row.canonical_game_instance_id, association_row.canonical_target_namespace, + association_row.canonical_tenant_id, association_row.canonical_version_id, + association_row.version_identity_operation_id, NULL, association_row.local_tenant_key, + association_row.preparation_input_digest, to_jsonb(association_row), 'RUN_OWNED_FIXTURE', + association_row.fixture_provenance_digest, association_row.world_instance_id, + association_row.control_plane_request_id, allocation_plan); + INSERT INTO "${serviceSchema}".world_canonical_instance_association SELECT (association_row).*; + SELECT to_jsonb(w) INTO STRICT stored_world FROM "${serviceSchema}".world_instance w + WHERE id = world_row.id FOR UPDATE; + SELECT to_jsonb(a) INTO STRICT stored_association + FROM "${serviceSchema}".world_canonical_instance_association a + WHERE canonical_game_instance_id = association_row.canonical_game_instance_id; + IF stored_world IS DISTINCT FROM to_jsonb(world_row) + OR stored_association IS DISTINCT FROM to_jsonb(association_row) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_preparation_execution_manifest + WHERE transaction_id = txid_current()) THEN + RAISE EXCEPTION 'Fixture allocation changed its exact rows or left an unconsumed manifest'; + END IF; + SET CONSTRAINTS fk_prepare_manifest_fixed_preset_fixture_owner IMMEDIATE; + RETURN world_row.id; +END; +$$; +REVOKE ALL ON FUNCTION world_allocate_run_owned_fixture_instance(JSONB, JSONB) FROM PUBLIC; + +CREATE FUNCTION world_verify_run_owned_fixed_preset_plan( + p JSONB, p_expected_content_digest TEXT, p_world_instance_id BIGINT, + p_private_game_instance_key BIGINT +) RETURNS VOID +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + association "${serviceSchema}".world_canonical_instance_association%ROWTYPE; + instance "${serviceSchema}".world_instance%ROWTYPE; + version_identity "${serviceSchema}".world_authored_version_identity%ROWTYPE; + source_intake "${serviceSchema}".world_authored_source_intake%ROWTYPE; + publication_owner "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + actual_keys TEXT[]; + seal_bytes BYTEA := ''::BYTEA; + seal_value TEXT; +BEGIN + IF p IS NULL OR jsonb_typeof(p) IS DISTINCT FROM 'object' + OR p_expected_content_digest IS DISTINCT FROM + 'sha256:f817af2770072bab0384c30c19b8cd30fce7a5a33f7587faed0024aa7c0909bc' + OR p->>'expectedContentDigest' IS DISTINCT FROM p_expected_content_digest + OR p->>'schemaVersion' IS DISTINCT FROM '1' + OR p->>'presetId' IS DISTINCT FROM 'firemud-demo-topology-v1' + OR p->>'presetSealDigest' !~ '^sha256:[0-9a-f]{64}$' + OR p->>'lifecycleBindingDigest' !~ '^sha256:[0-9a-f]{64}$' + OR p->>'gameSessionResponseBytesDigest' !~ '^sha256:[0-9a-f]{64}$' + OR p->>'fixturePolicyBytesDigest' !~ '^sha256:[0-9a-f]{64}$' + OR p->>'fixturePolicyRequestDigest' !~ '^sha256:[0-9a-f]{64}$' + OR p->>'fixturePolicyEvidenceDigest' !~ '^sha256:[0-9a-f]{64}$' + OR p->>'claimDigest' !~ '^[0-9a-f]{64}$' + OR p->>'playableStateScope' IS DISTINCT FROM 'SHARED' + OR jsonb_typeof(p->'topology') IS DISTINCT FROM 'array' + OR p->'topology' IS DISTINCT FROM jsonb_build_array( + jsonb_build_object('family','REGION', + 'templateId','9affa11b-02f5-3cc9-a50e-6760083c71e9', + 'name','Demo Region','spacingMultiplier',1.0,'generationSeed',0), + jsonb_build_object('family','ZONE', + 'templateId','936c4d65-c460-3b73-9f4e-6ee6295bca24', + 'parentRegionTemplateId','9affa11b-02f5-3cc9-a50e-6760083c71e9', + 'name','Demo Zone'), + jsonb_build_object('family','ROOM', + 'templateId','c6058518-f9e0-3f26-9b05-2bc786095089', + 'parentZoneTemplateId','936c4d65-c460-3b73-9f4e-6ee6295bca24', + 'name','Candle-lit Antechamber', + 'description','Stalactites drip along the northern wall while a faint draft carries the smell of damp earth from the lower tunnels. Torches flicker in alcoves, casting motion into the shadowy archway to the north.'), + jsonb_build_object('family','ROOM', + 'templateId','e74cca03-3b53-3edc-84f5-890651f5fea8', + 'parentZoneTemplateId','936c4d65-c460-3b73-9f4e-6ee6295bca24', + 'name','Smith''s Annex', + 'description','An anvil, banked coals, and orderly tool racks mark this alcove as a working annex off the starter chamber.'), + jsonb_build_object('family','ROOM_EXIT', + 'templateId','18c4b7a2-6498-3865-a464-814b56e4d4c2', + 'fromRoomTemplateId','c6058518-f9e0-3f26-9b05-2bc786095089', + 'toRoomTemplateId','e74cca03-3b53-3edc-84f5-890651f5fea8', + 'direction','NORTH','cost',1), + jsonb_build_object('family','ROOM_EXIT', + 'templateId','ab46ef8f-e74f-3197-be62-9785ef63242e', + 'fromRoomTemplateId','e74cca03-3b53-3edc-84f5-890651f5fea8', + 'toRoomTemplateId','c6058518-f9e0-3f26-9b05-2bc786095089', + 'direction','SOUTH','cost',1)) THEN + RAISE EXCEPTION 'RUN_OWNED_WORLD_FIXED_PRESET_PLAN_INVALID: plan is not the closed canonical preset' + USING ERRCODE = '23514'; + END IF; + + SELECT array_agg(k ORDER BY k) INTO actual_keys FROM jsonb_object_keys(p) AS keys(k); + IF actual_keys IS DISTINCT FROM ARRAY[ + 'canonicalRealmId','canonicalTenantId','canonicalVersionId','catalogRevision', + 'claimDigest','descriptorRequestDigest','descriptorResultDigest','descriptorRuntimeFlagsJson','expectedContentDigest', + 'fixtureOperationId','fixturePolicyBytesDigest','fixturePolicyEvidenceDigest', + 'fixturePolicyRequestDigest','gameDesignVersionId','gameSessionCanonicalTenantId', + 'gameSessionCanonicalVersionId','gameSessionGameInstanceId','gameSessionGameInstanceUuid', + 'gameSessionResponseBytesDigest','gameSessionTenantId','gameTemplateId', + 'generationConfigRevision','launchDescriptorId','launchGameDesignVersionId', + 'lifecycleBindingDigest','manifestHash','playableStateNamespaceId','playableStateScope', + 'presetId','presetSealDigest','publicProduction','publishedReleaseBundleRef','releaseBundleId', + 'schemaVersion','sourceEvidenceDigest','sourceOperationId','sourceReceiptDigest', + 'targetNamespace','topology','versionEvidenceDigest','versionStateEpoch','worldLocalTenantKey', + 'worldLocalVersionKey','worldSlug','worldSourceIntakeOperationId', + 'worldVersionIdentityOperationId' + ]::TEXT[] THEN + RAISE EXCEPTION 'RUN_OWNED_WORLD_FIXED_PRESET_PLAN_INVALID: unknown or missing plan field' + USING ERRCODE = '23514'; + END IF; + -- Match RunOwnedWorldFixedPresetResources.add: big-endian int32 UTF-8 byte length, + -- followed by the exact value bytes, in the Java binding-domain order. + FOREACH seal_value IN ARRAY ARRAY[ + 'firemud-world-run-owned-fixed-preset-binding/v1', + p->>'presetId', + p->>'expectedContentDigest', + p->>'targetNamespace', + p->>'fixtureOperationId', + p->>'claimDigest', + p->>'fixturePolicyRequestDigest', + p->>'fixturePolicyEvidenceDigest', + p->>'fixturePolicyBytesDigest', + p->>'lifecycleBindingDigest', + p->>'gameSessionResponseBytesDigest', + (p->>'canonicalTenantId')::UUID::TEXT, + p->>'worldSlug', + (p->>'worldSourceIntakeOperationId')::UUID::TEXT, + (p->>'sourceOperationId')::UUID::TEXT, + p->>'sourceEvidenceDigest', + p->>'sourceReceiptDigest', + (p->>'worldLocalTenantKey')::BIGINT::TEXT, + (p->>'worldVersionIdentityOperationId')::UUID::TEXT, + (p->>'canonicalVersionId')::UUID::TEXT, + (p->>'gameDesignVersionId')::BIGINT::TEXT, + p->>'versionEvidenceDigest', + (p->>'worldLocalVersionKey')::BIGINT::TEXT, + p->>'launchDescriptorId', + p->>'descriptorRequestDigest', + p->>'descriptorResultDigest', + p->>'descriptorRuntimeFlagsJson', + (p->>'launchGameDesignVersionId')::BIGINT::TEXT, + (p->>'releaseBundleId')::BIGINT::TEXT, + p->>'publishedReleaseBundleRef', + p->>'manifestHash', + p->>'generationConfigRevision', + (p->>'versionStateEpoch')::BIGINT::TEXT, + (p->>'gameSessionTenantId')::BIGINT::TEXT, + (p->>'gameSessionGameInstanceId')::BIGINT::TEXT, + (p->>'gameSessionGameInstanceUuid')::UUID::TEXT, + (p->>'gameSessionCanonicalTenantId')::UUID::TEXT, + (p->>'gameSessionCanonicalVersionId')::UUID::TEXT, + (p->>'playableStateNamespaceId')::UUID::TEXT, + (p->>'canonicalRealmId')::UUID::TEXT, + p->>'playableStateScope', + (p->>'publicProduction')::BOOLEAN::TEXT, + (p->>'catalogRevision')::BIGINT::TEXT, + (p->>'gameTemplateId')::BIGINT::TEXT + ]::TEXT[] LOOP + IF seal_value IS NULL THEN + RAISE EXCEPTION 'RUN_OWNED_WORLD_FIXED_PRESET_PLAN_INVALID: missing seal value' + USING ERRCODE = '23514'; + END IF; + seal_bytes := seal_bytes || int4send(octet_length(convert_to(seal_value, 'UTF8'))) + || convert_to(seal_value, 'UTF8'); + END LOOP; + IF p->>'presetSealDigest' IS DISTINCT FROM + 'sha256:' || encode(sha256(seal_bytes), 'hex') THEN + RAISE EXCEPTION 'RUN_OWNED_WORLD_FIXED_PRESET_PLAN_INVALID: preset seal differs' + USING ERRCODE = '23514'; + END IF; + + IF p_world_instance_id <= 0 OR p_private_game_instance_key <= 0 THEN + RAISE EXCEPTION 'RUN_OWNED_WORLD_FIXED_PRESET_ALLOCATION_INVALID' USING ERRCODE = '23514'; + END IF; + + SELECT * INTO STRICT association + FROM "${serviceSchema}".world_canonical_instance_association + WHERE world_instance_id = p_world_instance_id + AND canonical_game_instance_id = (p->>'gameSessionGameInstanceUuid')::UUID; + SELECT * INTO STRICT instance + FROM "${serviceSchema}".world_instance + WHERE id = association.world_instance_id; + SELECT * INTO STRICT version_identity + FROM "${serviceSchema}".world_authored_version_identity + WHERE operation_id = association.version_identity_operation_id; + SELECT * INTO STRICT source_intake + FROM "${serviceSchema}".world_authored_source_intake + WHERE operation_id = association.intake_operation_id; + SELECT * INTO STRICT publication_owner + FROM "${serviceSchema}".world_design_publication_fence_owner + WHERE target_namespace = version_identity.target_namespace + AND canonical_tenant_id = version_identity.canonical_tenant_id + AND local_tenant_key = version_identity.local_tenant_key + AND version_id = version_identity.local_version_key; + + IF association.canonical_authority_kind IS DISTINCT FROM 'RUN_OWNED_FIXTURE' + OR association.control_plane_request_id IS DISTINCT FROM p->>'fixtureOperationId' + OR association.canonical_game_instance_id IS DISTINCT FROM (p->>'gameSessionGameInstanceUuid')::UUID + OR association.canonical_target_namespace IS DISTINCT FROM p->>'targetNamespace' + OR association.canonical_tenant_id IS DISTINCT FROM (p->>'canonicalTenantId')::UUID + OR association.canonical_world_slug IS DISTINCT FROM p->>'worldSlug' + OR association.playable_state_namespace_id IS DISTINCT FROM (p->>'playableStateNamespaceId')::UUID + OR association.playable_state_scope IS DISTINCT FROM p->>'playableStateScope' + OR association.public_production IS DISTINCT FROM (p->>'publicProduction')::BOOLEAN + OR association.canonical_realm_id IS DISTINCT FROM (p->>'canonicalRealmId')::UUID + OR association.catalog_revision IS DISTINCT FROM (p->>'catalogRevision')::BIGINT + OR association.fixture_provenance_digest IS DISTINCT FROM p->>'fixturePolicyEvidenceDigest' + OR association.preparation_input_digest IS DISTINCT FROM p->>'lifecycleBindingDigest' + OR association.game_session_tenant_id IS DISTINCT FROM (p->>'gameSessionTenantId')::BIGINT + OR association.game_session_game_instance_id IS DISTINCT FROM (p->>'gameSessionGameInstanceId')::BIGINT + OR association.game_design_version_id IS DISTINCT FROM (p->>'gameDesignVersionId')::BIGINT + OR association.version_identity_operation_id IS DISTINCT FROM (p->>'worldVersionIdentityOperationId')::UUID + OR association.canonical_version_id IS DISTINCT FROM (p->>'canonicalVersionId')::UUID + OR association.local_tenant_key IS DISTINCT FROM (p->>'worldLocalTenantKey')::BIGINT + OR association.private_game_instance_key IS DISTINCT FROM p_private_game_instance_key + OR association.local_version_key IS DISTINCT FROM (p->>'worldLocalVersionKey')::BIGINT + OR association.game_template_id IS DISTINCT FROM (p->>'gameTemplateId')::BIGINT + OR association.launch_descriptor_id IS DISTINCT FROM p->>'launchDescriptorId' + OR association.script_patch_version IS NOT NULL + OR association.runtime_flags_json IS DISTINCT FROM p->>'descriptorRuntimeFlagsJson' + OR association.descriptor_request_digest IS DISTINCT FROM p->>'descriptorRequestDigest' + OR association.descriptor_result_digest IS DISTINCT FROM p->>'descriptorResultDigest' + OR association.release_bundle_id IS DISTINCT FROM (p->>'releaseBundleId')::BIGINT + OR association.published_release_bundle_ref IS DISTINCT FROM p->>'publishedReleaseBundleRef' + OR association.generation_config_revision IS DISTINCT FROM p->>'generationConfigRevision' + OR association.version_state_epoch IS DISTINCT FROM (p->>'versionStateEpoch')::BIGINT + OR association.remap_set_id IS NOT NULL + OR association.intake_operation_id IS DISTINCT FROM (p->>'worldSourceIntakeOperationId')::UUID + OR association.intake_request_id IS DISTINCT FROM source_intake.intake_request_id + OR association.source_operation_id IS DISTINCT FROM (p->>'sourceOperationId')::UUID + OR association.source_evidence_digest IS DISTINCT FROM p->>'sourceEvidenceDigest' + OR association.intake_request_digest IS DISTINCT FROM source_intake.request_digest + OR association.intake_receipt_digest IS DISTINCT FROM p->>'sourceReceiptDigest' + OR association.game_session_association_response_bytes IS NULL + OR 'sha256:' || encode(sha256(association.game_session_association_response_bytes), 'hex') + IS DISTINCT FROM p->>'gameSessionResponseBytesDigest' + OR instance.canonical_authority_kind IS DISTINCT FROM 'RUN_OWNED_FIXTURE' + OR instance.fixture_provenance_digest IS DISTINCT FROM association.fixture_provenance_digest + OR instance.game_session_tenant_id IS DISTINCT FROM association.game_session_tenant_id + OR instance.game_session_game_instance_id IS DISTINCT FROM association.game_session_game_instance_id + OR instance.game_design_version_id IS DISTINCT FROM association.game_design_version_id + OR (p->>'gameSessionCanonicalTenantId')::UUID IS DISTINCT FROM association.canonical_tenant_id + OR (p->>'gameSessionCanonicalVersionId')::UUID IS DISTINCT FROM association.canonical_version_id + OR (p->>'launchGameDesignVersionId')::BIGINT IS DISTINCT FROM association.game_design_version_id + OR instance.tenant_id IS DISTINCT FROM association.local_tenant_key + OR instance.game_instance_id IS DISTINCT FROM p_private_game_instance_key + OR instance.version_id IS DISTINCT FROM association.local_version_key + OR instance.game_template_id IS DISTINCT FROM (p->>'gameTemplateId')::BIGINT + OR instance.control_plane_request_id IS DISTINCT FROM p->>'fixtureOperationId' + OR instance.launch_descriptor_id IS DISTINCT FROM p->>'launchDescriptorId' + OR instance.script_patch_version IS NOT NULL + OR instance.runtime_flags_json IS DISTINCT FROM p->>'descriptorRuntimeFlagsJson' + OR instance.generation_config_revision IS DISTINCT FROM p->>'generationConfigRevision' + OR instance.release_bundle_id IS DISTINCT FROM (p->>'releaseBundleId')::BIGINT + OR instance.published_release_bundle_ref IS DISTINCT FROM p->>'publishedReleaseBundleRef' + OR instance.version_state_epoch IS DISTINCT FROM (p->>'versionStateEpoch')::BIGINT + OR instance.remap_set_id IS NOT NULL + OR instance.canonical_game_instance_id IS DISTINCT FROM association.canonical_game_instance_id + OR instance.canonical_target_namespace IS DISTINCT FROM association.canonical_target_namespace + OR instance.canonical_tenant_id IS DISTINCT FROM association.canonical_tenant_id + OR instance.canonical_world_slug IS DISTINCT FROM association.canonical_world_slug + OR instance.playable_state_namespace_id IS DISTINCT FROM association.playable_state_namespace_id + OR instance.playable_state_scope IS DISTINCT FROM association.playable_state_scope + OR instance.public_production IS DISTINCT FROM association.public_production + OR instance.canonical_realm_id IS DISTINCT FROM association.canonical_realm_id + OR instance.catalog_revision IS DISTINCT FROM association.catalog_revision + OR instance.status IS DISTINCT FROM 'PREPARING' + OR instance.lifecycle_epoch IS DISTINCT FROM association.preparing_lifecycle_epoch + OR instance.run_owned_fixture_preparing_lifecycle_epoch IS DISTINCT FROM association.preparing_lifecycle_epoch + OR 'sha256:' || instance.run_owned_fixture_binding_sha256 IS DISTINCT FROM association.preparation_input_digest + OR version_identity.target_namespace IS DISTINCT FROM p->>'targetNamespace' + OR version_identity.canonical_tenant_id IS DISTINCT FROM (p->>'canonicalTenantId')::UUID + OR version_identity.world_slug IS DISTINCT FROM p->>'worldSlug' + OR version_identity.canonical_version_id IS DISTINCT FROM (p->>'canonicalVersionId')::UUID + OR version_identity.game_design_version_id IS DISTINCT FROM (p->>'gameDesignVersionId')::BIGINT + OR version_identity.local_tenant_key IS DISTINCT FROM (p->>'worldLocalTenantKey')::BIGINT + OR version_identity.local_version_key IS DISTINCT FROM (p->>'worldLocalVersionKey')::BIGINT + OR version_identity.intake_operation_id IS DISTINCT FROM source_intake.operation_id + OR version_identity.intake_request_id IS DISTINCT FROM source_intake.intake_request_id + OR version_identity.intake_request_digest IS DISTINCT FROM source_intake.request_digest + OR version_identity.version_state_evidence_digest IS DISTINCT FROM p->>'versionEvidenceDigest' + OR version_identity.version_state_state NOT IN ('PUBLISHED','ACTIVE') + OR version_identity.source_operation_id IS DISTINCT FROM (p->>'sourceOperationId')::UUID + OR version_identity.source_evidence_digest IS DISTINCT FROM p->>'sourceEvidenceDigest' + OR version_identity.intake_receipt_digest IS DISTINCT FROM p->>'sourceReceiptDigest' + OR source_intake.target_namespace IS DISTINCT FROM p->>'targetNamespace' + OR source_intake.operation_id IS DISTINCT FROM (p->>'worldSourceIntakeOperationId')::UUID + OR source_intake.canonical_tenant_id IS DISTINCT FROM (p->>'canonicalTenantId')::UUID + OR source_intake.world_slug IS DISTINCT FROM p->>'worldSlug' + OR source_intake.local_tenant_key IS DISTINCT FROM (p->>'worldLocalTenantKey')::BIGINT + OR association.intake_request_digest IS DISTINCT FROM source_intake.request_digest + OR source_intake.source_operation_id IS DISTINCT FROM (p->>'sourceOperationId')::UUID + OR source_intake.source_evidence_digest IS DISTINCT FROM p->>'sourceEvidenceDigest' + OR source_intake.receipt_digest IS DISTINCT FROM p->>'sourceReceiptDigest' + OR source_intake.source_provenance_kind IS DISTINCT FROM 'NEW_GAME_ROW' + OR publication_owner.owner_freeze_phase IS DISTINCT FROM 'OPEN' + OR publication_owner.current_publication_fence IS NOT NULL + OR NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_authored_source_tenant_key_reservation reservation + WHERE reservation.tenant_key = association.local_tenant_key + AND reservation.claim_kind = 'CANONICAL_AUTHORED_SOURCE') THEN + RAISE EXCEPTION 'RUN_OWNED_WORLD_FIXED_PRESET_ASSOCIATION_MISMATCH: retained owners or allocation differ' + USING ERRCODE = '23514'; + END IF; +END; +$$; +REVOKE ALL ON FUNCTION world_verify_run_owned_fixed_preset_plan(JSONB, TEXT, BIGINT, BIGINT) + FROM PUBLIC; + +-- Fixture preparation retains no Human selected-start witness. Extend only the retainer's +-- fixture arm; the current Human schema/receipt/capture/mapping body remains unchanged. +DO $migration$ +DECLARE + original TEXT; + declaration_anchor TEXT := $anchor$ frozen "${serviceSchema}".world_canonical_frozen_topology%ROWTYPE;$anchor$; + begin_anchor TEXT := $anchor$BEGIN + IF NEW.input_json::JSONB->>'schemaVersion' = '3' THEN RETURN NEW; END IF;$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_retain_preparation_start_location()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,declaration_anchor,'')))/length(declaration_anchor) <> 1 + OR (length(original)-length(replace(original,begin_anchor,'')))/length(begin_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact current Human preparation start-location retainer anchors'; + END IF; + original := replace(original, declaration_anchor, $replacement$ frozen "${serviceSchema}".world_canonical_frozen_topology%ROWTYPE; + fixture_owner "${serviceSchema}".world_canonical_instance_association%ROWTYPE; + fixture_plan JSONB;$replacement$); + original := replace(original, begin_anchor, $replacement$BEGIN + IF TG_OP = 'INSERT' AND NEW.fixed_preset_id IS NOT NULL THEN + SELECT a.* INTO STRICT fixture_owner + FROM "${serviceSchema}".world_canonical_instance_association a + WHERE a.world_instance_id = NEW.world_instance_id + AND a.canonical_game_instance_id = NEW.canonical_game_instance_id; + fixture_plan := NEW.input_json::JSONB; + IF fixture_owner.schema_version IS DISTINCT FROM 3 + OR fixture_owner.canonical_authority_kind IS DISTINCT FROM 'RUN_OWNED_FIXTURE' + OR NEW.capture_id IS NOT NULL + OR fixture_owner.canonical_launch_binding_operation_id IS NOT NULL + OR fixture_owner.release_attestation_digest IS NOT NULL + OR fixture_plan ?| ARRAY['worldStartLocationEvidenceBase64','worldStartLocationEvidence', + 'launchBinding','captureId','frozenTopology'] + OR NEW.fixed_preset_id IS DISTINCT FROM 'firemud-demo-topology-v1' + OR NEW.fixed_preset_content_digest IS DISTINCT FROM + 'sha256:f817af2770072bab0384c30c19b8cd30fce7a5a33f7587faed0024aa7c0909bc' + OR NEW.fixed_preset_binding_digest IS DISTINCT FROM fixture_plan->>'presetSealDigest' + OR NEW.input_digest IS DISTINCT FROM fixture_plan->>'presetSealDigest' + OR NEW.target_namespace IS DISTINCT FROM fixture_owner.canonical_target_namespace + OR NEW.canonical_tenant_id IS DISTINCT FROM fixture_owner.canonical_tenant_id + OR NEW.world_slug IS DISTINCT FROM fixture_owner.canonical_world_slug + OR NEW.control_plane_request_id IS DISTINCT FROM fixture_owner.control_plane_request_id + OR NEW.canonical_version_id IS DISTINCT FROM fixture_owner.canonical_version_id + OR NEW.version_identity_operation_id IS DISTINCT FROM fixture_owner.version_identity_operation_id + OR NEW.private_game_instance_key IS DISTINCT FROM fixture_owner.private_game_instance_key + OR NEW.graph_bytes IS DISTINCT FROM convert_to(NEW.input_json, 'UTF8') + OR NEW.graph_sha256 IS DISTINCT FROM encode(sha256(convert_to(NEW.input_json, 'UTF8')), 'hex') + OR NEW.storage_status IS DISTINCT FROM 'MATERIALIZED_UNVERIFIED' + OR NEW.region_count IS DISTINCT FROM 1 OR NEW.zone_count IS DISTINCT FROM 1 + OR NEW.room_count IS DISTINCT FROM 2 OR NEW.exit_count IS DISTINCT FROM 2 + OR EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_preparation_start_location selected + WHERE selected.world_instance_id = NEW.world_instance_id + OR selected.canonical_game_instance_id = NEW.canonical_game_instance_id) + OR NOT EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_preparation retained + WHERE retained.id = NEW.id AND to_jsonb(retained) = to_jsonb(NEW) + AND retained.xmin::TEXT = (txid_current() % 4294967296)::TEXT) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_preparation_execution_manifest pending + WHERE pending.transaction_id = txid_current() + AND pending.table_name = 'world_canonical_instance_preparation' + AND pending.row_id = NEW.id) THEN + RAISE EXCEPTION 'Fixture preparation differs from its exact manifest-owned result or carries Human start-location authority' + USING ERRCODE = '23514'; + END IF; + -- The BEFORE preparation guard has already consumed this row's exact manifest. This + -- AFTER retainer independently rechecks the actual fixture/source/Version owners and + -- the original GS bytes, plan seal and complete preset before omitting Human metadata. + PERFORM "${serviceSchema}".world_verify_run_owned_fixed_preset_plan( + fixture_plan, + 'sha256:f817af2770072bab0384c30c19b8cd30fce7a5a33f7587faed0024aa7c0909bc', + NEW.world_instance_id, NEW.private_game_instance_key); + RETURN NEW; + END IF; + IF NEW.input_json::JSONB->>'schemaVersion' = '3' THEN RETURN NEW; END IF;$replacement$); + EXECUTE original; +END; +$migration$; + + +-- V29's original Human owner/fence checks remain the first consumed-once branch. +-- The fixture branch rechecks the exact plan against V67 plus actual source/version evidence. +CREATE OR REPLACE FUNCTION world_consume_region_execution_manifest( + actual_table TEXT, actual_operation TEXT, actual_old JSONB, actual_new JSONB +) RETURNS BOOLEAN +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + consumed BIGINT; + fixture_manifest "${serviceSchema}".world_region_draft_execution_manifest%ROWTYPE; + association "${serviceSchema}".world_canonical_instance_association%ROWTYPE; +BEGIN + IF actual_operation NOT IN ('INSERT', 'UPDATE') OR actual_new IS NULL THEN + RETURN FALSE; + END IF; + DELETE FROM "${serviceSchema}".world_region_draft_execution_manifest m + USING "${serviceSchema}".world_authored_version_identity v, + "${serviceSchema}".world_design_publication_fence_owner o + WHERE m.preparation_authority_kind = 'HUMAN' + AND (actual_table <> 'world_authored_topology_identity' + OR actual_new->>'preparation_authority_kind' IS NULL + OR actual_new->>'preparation_authority_kind' = 'HUMAN') + AND m.transaction_id = txid_current() + AND m.table_name = actual_table AND m.row_operation = actual_operation + AND m.row_id = (actual_new->>'id')::BIGINT + AND m.expected_old IS NOT DISTINCT FROM actual_old + AND m.expected_new = actual_new + AND m.local_tenant_key = (actual_new->>'tenant_id')::BIGINT + AND m.local_version_key = (actual_new->>'version_id')::BIGINT + AND v.operation_id = m.version_identity_operation_id + AND v.local_tenant_key = m.local_tenant_key + AND v.local_version_key = m.local_version_key + AND v.operation_id::TEXT = m.owner_binding->>'versionIdentityOperationId' + AND v.target_namespace = m.owner_binding->>'targetNamespace' + AND v.canonical_tenant_id::TEXT = m.owner_binding->>'canonicalTenantId' + AND v.canonical_version_id::TEXT = m.owner_binding->>'canonicalVersionId' + AND v.intake_operation_id::TEXT = m.owner_binding->>'intakeOperationId' + AND v.intake_request_id::TEXT = m.owner_binding->>'intakeRequestId' + AND v.intake_request_digest = m.owner_binding->>'intakeRequestDigest' + AND v.source_operation_id::TEXT = m.owner_binding->>'sourceOperationId' + AND v.source_evidence_digest = m.owner_binding->>'sourceEvidenceDigest' + AND v.intake_receipt_digest = m.owner_binding->>'intakeReceiptDigest' + AND v.game_design_version_id = (m.owner_binding->>'gameDesignVersionId')::BIGINT + AND v.canonical_tenant_id::TEXT = m.complete_binding->>'canonicalTenantId' + AND v.canonical_version_id::TEXT = m.complete_binding->>'canonicalVersionId' + AND m.operation_id::TEXT = m.complete_binding->>'commitId' + AND o.target_namespace = v.target_namespace + AND o.canonical_tenant_id = v.canonical_tenant_id + AND o.local_tenant_key = v.local_tenant_key AND o.version_id = v.local_version_key + AND o.owner_freeze_phase = 'OPEN' AND o.current_publication_fence IS NULL + RETURNING m.row_id INTO consumed; + IF consumed IS NOT NULL THEN RETURN TRUE; END IF; + IF actual_operation <> 'INSERT' OR actual_old IS NOT NULL THEN RETURN FALSE; END IF; + SELECT * INTO fixture_manifest + FROM "${serviceSchema}".world_region_draft_execution_manifest m + WHERE m.transaction_id = txid_current() + AND m.preparation_authority_kind = 'RUN_OWNED_FIXTURE' + AND m.table_name = actual_table AND m.row_operation = actual_operation + AND m.row_id = (actual_new->>'id')::BIGINT + AND m.expected_old IS NULL AND m.expected_new = actual_new; + IF NOT FOUND THEN RETURN FALSE; END IF; + SELECT * INTO STRICT association + FROM "${serviceSchema}".world_canonical_instance_association + WHERE world_instance_id = fixture_manifest.fixture_world_instance_id; + PERFORM "${serviceSchema}".world_verify_run_owned_fixed_preset_plan( + fixture_manifest.complete_binding, + 'sha256:f817af2770072bab0384c30c19b8cd30fce7a5a33f7587faed0024aa7c0909bc', + association.world_instance_id, association.private_game_instance_key); + DELETE FROM "${serviceSchema}".world_region_draft_execution_manifest m + USING "${serviceSchema}".world_authored_version_identity v, + "${serviceSchema}".world_instance wi + WHERE m.transaction_id = txid_current() + AND m.preparation_authority_kind = 'RUN_OWNED_FIXTURE' + AND m.table_name = actual_table AND m.row_operation = 'INSERT' + AND m.row_id = (actual_new->>'id')::BIGINT + AND m.expected_old IS NULL AND m.expected_new = actual_new + AND m.fixture_world_instance_id = association.world_instance_id + AND m.fixture_operation_id = association.control_plane_request_id + AND m.operation_id::TEXT = association.control_plane_request_id + AND m.fixture_provenance_digest = association.fixture_provenance_digest + AND association.canonical_authority_kind = 'RUN_OWNED_FIXTURE' + AND m.complete_binding = fixture_manifest.complete_binding + AND v.operation_id = m.version_identity_operation_id + AND v.operation_id = association.version_identity_operation_id + AND m.local_tenant_key = association.local_tenant_key + AND m.local_version_key = association.local_version_key + AND m.local_tenant_key = (actual_new->>'tenant_id')::BIGINT + AND m.local_version_key = (actual_new->>'version_id')::BIGINT + AND m.owner_binding = jsonb_build_object( + 'targetNamespace',v.target_namespace,'canonicalTenantId',v.canonical_tenant_id, + 'canonicalVersionId',v.canonical_version_id,'versionIdentityOperationId',v.operation_id, + 'gameDesignVersionId',v.game_design_version_id,'intakeRequestId',v.intake_request_id, + 'intakeOperationId',v.intake_operation_id,'intakeRequestDigest',v.intake_request_digest, + 'sourceOperationId',v.source_operation_id,'sourceEvidenceDigest',v.source_evidence_digest, + 'intakeReceiptDigest',v.intake_receipt_digest) + AND wi.id = association.world_instance_id + AND wi.status = 'PREPARING' AND wi.lifecycle_epoch = association.preparing_lifecycle_epoch + AND (actual_table <> 'world_authored_topology_identity' OR ( + actual_new->>'preparation_authority_kind' = 'RUN_OWNED_FIXTURE' + AND actual_new->>'fixture_world_instance_id' = association.world_instance_id::TEXT + AND actual_new->>'fixture_operation_id' = association.control_plane_request_id + AND actual_new->>'fixture_provenance_digest' = association.fixture_provenance_digest + AND actual_new->>'target_namespace' = association.canonical_target_namespace + AND actual_new->>'canonical_tenant_id' = association.canonical_tenant_id::TEXT + AND actual_new->>'canonical_version_id' = association.canonical_version_id::TEXT + AND actual_new->>'version_identity_operation_id' = association.version_identity_operation_id::TEXT + AND actual_new->>'request_id' IS NULL AND actual_new->>'commit_id' IS NULL + AND actual_new->>'revision_id' IS NULL AND actual_new->>'revision_order' IS NULL)) + RETURNING m.row_id INTO consumed; + RETURN consumed IS NOT NULL; +END; +$$; +REVOKE ALL ON FUNCTION world_consume_region_execution_manifest(TEXT, TEXT, JSONB, JSONB) FROM PUBLIC; + +-- Keep the original Human frozen-capture consumer byte-for-byte in its first DELETE. The second +-- one-use fixture branch accepts the atomic allocation image before its association, then +-- accepts runtime/preparation rows only against the retained V67 owner and lifecycle commitment. +CREATE OR REPLACE FUNCTION world_consume_canonical_prepare_execution_manifest( + actual_table TEXT, actual_operation TEXT, actual_old JSONB, actual_new JSONB +) RETURNS BOOLEAN +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + consumed BIGINT; + allocation_world JSONB; + fixture_manifest "${serviceSchema}".world_canonical_instance_preparation_execution_manifest%ROWTYPE; + fixture_association "${serviceSchema}".world_canonical_instance_association%ROWTYPE; +BEGIN + IF actual_operation = 'UPDATE' THEN + RETURN FALSE; + END IF; + IF actual_operation <> 'INSERT' OR actual_old IS NOT NULL OR actual_new IS NULL THEN + RETURN FALSE; + END IF; + DELETE FROM "${serviceSchema}".world_canonical_instance_preparation_execution_manifest m + USING "${serviceSchema}".world_authored_version_identity v, + "${serviceSchema}".world_canonical_frozen_topology f, + "${serviceSchema}".world_authored_source_tenant_key_reservation r + WHERE m.transaction_id = txid_current() + AND m.table_name = actual_table + AND m.row_id = (actual_new->>'id')::BIGINT + AND m.expected_new = actual_new + AND v.operation_id = m.version_identity_operation_id + AND v.target_namespace = m.target_namespace + AND v.canonical_tenant_id = m.canonical_tenant_id + AND v.canonical_version_id = m.canonical_version_id + AND v.local_tenant_key = m.local_tenant_key + AND f.capture_id = m.capture_id + AND f.version_identity_operation_id = v.operation_id + AND f.capture_status = 'CAPTURED_UNVERIFIED' + AND r.tenant_key = m.local_tenant_key + AND r.claim_kind = 'CANONICAL_AUTHORED_SOURCE' + AND ( + (actual_table = 'world_instance' + AND actual_new->>'canonical_game_instance_id' = m.canonical_game_instance_id::TEXT + AND actual_new->>'canonical_target_namespace' = m.target_namespace + AND actual_new->>'canonical_tenant_id' = m.canonical_tenant_id::TEXT + AND actual_new->>'tenant_id' = m.local_tenant_key::TEXT) + OR (actual_table IN ('region_instance', 'zone_instance', 'room_instance', 'room_instance_exit') + AND actual_new->>'tenant_id' = m.local_tenant_key::TEXT + AND EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_instance wi + WHERE wi.canonical_game_instance_id = m.canonical_game_instance_id + AND wi.tenant_id = m.local_tenant_key + AND wi.game_instance_id = (actual_new->>'game_instance_id')::BIGINT + AND wi.canonical_target_namespace = m.target_namespace + AND wi.canonical_tenant_id = m.canonical_tenant_id)) + OR (actual_table IN ('world_canonical_instance_topology_identity', 'world_canonical_instance_preparation') + AND actual_new->>'canonical_game_instance_id' = m.canonical_game_instance_id::TEXT + AND EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_instance wi + WHERE wi.id = (actual_new->>'world_instance_id')::BIGINT + AND wi.canonical_game_instance_id = m.canonical_game_instance_id + AND wi.tenant_id = m.local_tenant_key + AND wi.canonical_target_namespace = m.target_namespace + AND wi.canonical_tenant_id = m.canonical_tenant_id)) + ) + RETURNING m.row_id INTO consumed; + IF consumed IS NOT NULL THEN RETURN TRUE; END IF; + + SELECT * INTO fixture_manifest + FROM "${serviceSchema}".world_canonical_instance_preparation_execution_manifest m + WHERE m.transaction_id = txid_current() + AND m.preparation_authority_kind = 'RUN_OWNED_FIXTURE' + AND m.table_name = actual_table AND m.row_id = CASE + WHEN actual_table = 'world_canonical_instance_association' + THEN (actual_new->>'world_instance_id')::BIGINT + ELSE (actual_new->>'id')::BIGINT END + AND m.expected_new = actual_new; + IF NOT FOUND THEN RETURN FALSE; END IF; + -- The two allocation statements share one complete row/owner image and original GS bytes. + -- The second consumes its own manifest only against the independently stored first row. + IF actual_table IN ('world_instance','world_canonical_instance_association') THEN + IF fixture_manifest.fixture_plan->>'schema' IS DISTINCT FROM + 'firemud.run-owned-world-allocation.v1' + OR (SELECT array_agg(k ORDER BY k) FROM jsonb_object_keys(fixture_manifest.fixture_plan) k) + IS DISTINCT FROM ARRAY['association','gameSessionResponseBytesDigest','schema','world']::TEXT[] THEN + RETURN FALSE; + END IF; + fixture_association := jsonb_populate_record( + NULL::"${serviceSchema}".world_canonical_instance_association, + fixture_manifest.fixture_plan->'association'); + IF actual_table = 'world_instance' THEN + allocation_world := actual_new; + ELSE + SELECT to_jsonb(w) INTO allocation_world FROM "${serviceSchema}".world_instance w + WHERE w.id = fixture_association.world_instance_id FOR KEY SHARE; + IF NOT FOUND OR actual_new IS DISTINCT FROM to_jsonb(fixture_association) THEN + RETURN FALSE; + END IF; + END IF; + IF allocation_world IS DISTINCT FROM fixture_manifest.fixture_plan->'world' + OR to_jsonb(fixture_association) IS DISTINCT FROM fixture_manifest.fixture_plan->'association' + OR fixture_association.schema_version IS DISTINCT FROM 3 + OR fixture_association.canonical_authority_kind IS DISTINCT FROM 'RUN_OWNED_FIXTURE' + OR fixture_association.world_instance_id IS DISTINCT FROM fixture_manifest.row_id + OR fixture_association.preparing_lifecycle_epoch IS DISTINCT FROM 1 + OR fixture_association.canonical_launch_binding_operation_id IS NOT NULL + OR fixture_association.release_attestation_digest IS NOT NULL + OR fixture_association.playtest_lifecycle_id IS NOT NULL + OR fixture_association.playtest_state_generation IS NOT NULL + OR fixture_association.playable_state_scope IS DISTINCT FROM 'SHARED' + OR fixture_manifest.fixture_plan->>'gameSessionResponseBytesDigest' IS DISTINCT FROM + 'sha256:' || encode(sha256(fixture_association.game_session_association_response_bytes), 'hex') + OR octet_length(fixture_association.game_session_association_response_bytes) IS NULL + OR octet_length(fixture_association.game_session_association_response_bytes) = 0 + OR EXISTS ( + SELECT 1 FROM jsonb_each(to_jsonb(fixture_association)) e + WHERE allocation_world ? e.key AND allocation_world->e.key IS DISTINCT FROM e.value) + OR allocation_world->>'id' IS DISTINCT FROM fixture_association.world_instance_id::TEXT + OR allocation_world->>'tenant_id' IS DISTINCT FROM fixture_association.local_tenant_key::TEXT + OR allocation_world->>'game_instance_id' IS DISTINCT FROM fixture_association.private_game_instance_key::TEXT + OR allocation_world->>'version_id' IS DISTINCT FROM fixture_association.local_version_key::TEXT + OR allocation_world->>'status' IS DISTINCT FROM 'PREPARING' + OR allocation_world->>'lifecycle_epoch' IS DISTINCT FROM '1' + OR allocation_world->>'row_version' IS DISTINCT FROM '0' + OR allocation_world->>'failure_reason' IS NOT NULL + OR allocation_world->>'termination_request_id' IS NOT NULL + OR allocation_world->>'terminated_at' IS NOT NULL + OR allocation_world->>'run_owned_fixture_preparing_lifecycle_epoch' IS DISTINCT FROM '1' + OR 'sha256:' || (allocation_world->>'run_owned_fixture_binding_sha256') IS DISTINCT FROM + fixture_association.preparation_input_digest THEN + RETURN FALSE; + END IF; + DELETE FROM "${serviceSchema}".world_canonical_instance_preparation_execution_manifest m + USING "${serviceSchema}".world_authored_version_identity v, + "${serviceSchema}".world_authored_source_intake si, + "${serviceSchema}".world_authored_source_tenant_key_reservation r + WHERE m.transaction_id = txid_current() + AND m.table_name = actual_table AND m.row_id = fixture_association.world_instance_id + AND m.expected_new = actual_new AND m.fixture_plan = fixture_manifest.fixture_plan + AND m.preparation_authority_kind = 'RUN_OWNED_FIXTURE' AND m.capture_id IS NULL + AND m.fixture_world_instance_id = fixture_association.world_instance_id + AND m.fixture_operation_id = fixture_association.control_plane_request_id + AND m.fixture_provenance_digest = fixture_association.fixture_provenance_digest + AND m.input_digest = fixture_association.preparation_input_digest + AND m.canonical_game_instance_id = fixture_association.canonical_game_instance_id + AND m.target_namespace = fixture_association.canonical_target_namespace + AND m.canonical_tenant_id = fixture_association.canonical_tenant_id + AND m.canonical_version_id = fixture_association.canonical_version_id + AND m.version_identity_operation_id = fixture_association.version_identity_operation_id + AND m.local_tenant_key = fixture_association.local_tenant_key + AND v.operation_id = fixture_association.version_identity_operation_id + AND v.target_namespace = fixture_association.canonical_target_namespace + AND v.canonical_tenant_id = fixture_association.canonical_tenant_id + AND v.world_slug = fixture_association.canonical_world_slug + AND v.canonical_version_id = fixture_association.canonical_version_id + AND v.local_tenant_key = fixture_association.local_tenant_key + AND v.local_version_key = fixture_association.local_version_key + AND v.game_design_version_id = fixture_association.game_design_version_id + AND v.source_operation_id = fixture_association.source_operation_id + AND v.source_evidence_digest = fixture_association.source_evidence_digest + AND v.intake_operation_id = fixture_association.intake_operation_id + AND v.intake_request_id = fixture_association.intake_request_id + AND v.intake_request_digest = fixture_association.intake_request_digest + AND v.intake_receipt_digest = fixture_association.intake_receipt_digest + AND si.operation_id = v.intake_operation_id AND si.intake_request_id = v.intake_request_id + AND si.local_tenant_key = v.local_tenant_key AND si.source_provenance_kind = 'NEW_GAME_ROW' + AND si.source_operation_id = v.source_operation_id + AND si.source_evidence_digest = v.source_evidence_digest + AND si.request_digest = v.intake_request_digest AND si.receipt_digest = v.intake_receipt_digest + AND r.tenant_key = v.local_tenant_key AND r.claim_kind = 'CANONICAL_AUTHORED_SOURCE' + RETURNING m.row_id INTO consumed; + RETURN consumed IS NOT NULL; + END IF; + SELECT * INTO STRICT fixture_association + FROM "${serviceSchema}".world_canonical_instance_association + WHERE world_instance_id = fixture_manifest.fixture_world_instance_id; + PERFORM "${serviceSchema}".world_verify_run_owned_fixed_preset_plan( + fixture_manifest.fixture_plan, + 'sha256:f817af2770072bab0384c30c19b8cd30fce7a5a33f7587faed0024aa7c0909bc', + fixture_association.world_instance_id, fixture_association.private_game_instance_key); + + DELETE FROM "${serviceSchema}".world_canonical_instance_preparation_execution_manifest m + USING "${serviceSchema}".world_authored_version_identity v, + "${serviceSchema}".world_canonical_instance_association a, + "${serviceSchema}".world_instance wi, + "${serviceSchema}".world_authored_source_tenant_key_reservation r + WHERE m.transaction_id = txid_current() + AND m.table_name = actual_table + AND m.row_id = (actual_new->>'id')::BIGINT + AND m.expected_new = actual_new + AND m.preparation_authority_kind = 'RUN_OWNED_FIXTURE' + AND m.capture_id IS NULL + AND m.fixture_world_instance_id = a.world_instance_id + AND m.fixture_operation_id = a.control_plane_request_id + AND m.fixture_provenance_digest = a.fixture_provenance_digest + AND m.fixture_plan = fixture_manifest.fixture_plan + AND a.world_instance_id = fixture_association.world_instance_id + AND m.input_digest = a.preparation_input_digest + AND m.canonical_game_instance_id = a.canonical_game_instance_id + AND m.target_namespace = a.canonical_target_namespace + AND m.canonical_tenant_id = a.canonical_tenant_id + AND m.canonical_version_id = a.canonical_version_id + AND m.version_identity_operation_id = a.version_identity_operation_id + AND m.local_tenant_key = a.local_tenant_key + AND a.canonical_authority_kind = 'RUN_OWNED_FIXTURE' + AND a.world_instance_id = wi.id + AND wi.canonical_game_instance_id = a.canonical_game_instance_id + AND wi.tenant_id = a.local_tenant_key + AND wi.game_instance_id = a.private_game_instance_key + AND wi.version_id = a.local_version_key + AND wi.status = 'PREPARING' + AND wi.lifecycle_epoch = a.preparing_lifecycle_epoch + AND wi.run_owned_fixture_preparing_lifecycle_epoch = a.preparing_lifecycle_epoch + AND 'sha256:' || wi.run_owned_fixture_binding_sha256 = a.preparation_input_digest + AND v.operation_id = a.version_identity_operation_id + AND v.target_namespace = a.canonical_target_namespace + AND v.canonical_tenant_id = a.canonical_tenant_id + AND v.canonical_version_id = a.canonical_version_id + AND v.local_tenant_key = a.local_tenant_key + AND v.local_version_key = a.local_version_key + AND r.tenant_key = a.local_tenant_key + AND r.claim_kind = 'CANONICAL_AUTHORED_SOURCE' + AND (actual_table <> 'world_canonical_instance_preparation' + OR actual_new->>'capture_id' IS NULL + AND actual_new->>'fixed_preset_id' = 'firemud-demo-topology-v1' + AND actual_new->>'fixed_preset_content_digest' = + 'sha256:f817af2770072bab0384c30c19b8cd30fce7a5a33f7587faed0024aa7c0909bc' + AND actual_new->>'fixed_preset_binding_digest' = actual_new->>'input_digest' + AND actual_new->>'input_digest' = fixture_manifest.fixture_plan->>'presetSealDigest' + AND (actual_new->>'input_json')::JSONB = fixture_manifest.fixture_plan + AND actual_new->>'control_plane_request_id' = a.control_plane_request_id) + AND ( + (actual_table IN ('region_instance','zone_instance','room_instance','room_instance_exit') + AND actual_new->>'tenant_id' = a.local_tenant_key::TEXT + AND actual_new->>'game_instance_id' = a.private_game_instance_key::TEXT) + OR (actual_table IN ('world_canonical_instance_topology_identity','world_canonical_instance_preparation') + AND actual_new->>'canonical_game_instance_id' = a.canonical_game_instance_id::TEXT + AND actual_new->>'world_instance_id' = a.world_instance_id::TEXT) + ) + RETURNING m.row_id INTO consumed; + RETURN consumed IS NOT NULL; +END; +$$; +REVOKE ALL ON FUNCTION world_consume_canonical_prepare_execution_manifest(TEXT, TEXT, JSONB, JSONB) + FROM PUBLIC; + +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$BEGIN + SELECT * INTO operation FROM "${serviceSchema}".world_canonical_instance_execution e$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_guard_canonical_instance_association_execution()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,anchor,'')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one original canonical association execution guard anchor'; + END IF; + original := replace(original, anchor, $replacement$BEGIN + IF TG_OP = 'INSERT' AND NEW.schema_version = 3 + AND NEW.canonical_authority_kind = 'RUN_OWNED_FIXTURE' THEN + IF NOT "${serviceSchema}".world_consume_canonical_prepare_execution_manifest( + 'world_canonical_instance_association', 'INSERT', NULL, to_jsonb(NEW)) THEN + RAISE EXCEPTION 'Fixture association requires its exact one-use transaction execution manifest' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + SELECT * INTO operation FROM "${serviceSchema}".world_canonical_instance_execution e$replacement$); + EXECUTE original; +END; +$migration$; + + + + +CREATE FUNCTION world_read_run_owned_fixed_preset( + p_plan_json TEXT, p_expected_content_digest TEXT, p_world_instance_id BIGINT, + p_private_game_instance_key BIGINT +) RETURNS TABLE( + world_instance_id BIGINT, tenant_id BIGINT, private_game_instance_key BIGINT, + version_id BIGINT, preset_id TEXT, preset_content_digest TEXT, + preset_binding_digest TEXT, graph_sha256 TEXT, region_count INTEGER, + zone_count INTEGER, room_count INTEGER, exit_count INTEGER +) +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + p JSONB; + retained "${serviceSchema}".world_canonical_instance_preparation%ROWTYPE; + association "${serviceSchema}".world_canonical_instance_association%ROWTYPE; + template_count BIGINT; + region_runtime_count BIGINT; + zone_runtime_count BIGINT; + room_runtime_count BIGINT; + exit_runtime_count BIGINT; + topology_identity_count BIGINT; +BEGIN + IF current_setting('transaction_read_only') <> 'on' + AND current_setting('transaction_isolation') NOT IN ('read committed','repeatable read','serializable') THEN + RAISE EXCEPTION 'Run-owned fixed-preset readback requires an owner read transaction' + USING ERRCODE = '23514'; + END IF; + IF p_plan_json IS NULL OR length(p_plan_json) = 0 THEN + RAISE EXCEPTION 'RUN_OWNED_WORLD_FIXED_PRESET_PLAN_INVALID' USING ERRCODE = '23514'; + END IF; + p := p_plan_json::JSONB; + PERFORM "${serviceSchema}".world_verify_run_owned_fixed_preset_plan( + p, p_expected_content_digest, p_world_instance_id, p_private_game_instance_key); + SELECT owner.* INTO STRICT association + FROM "${serviceSchema}".world_canonical_instance_association owner + WHERE owner.world_instance_id = p_world_instance_id + AND owner.canonical_game_instance_id = (p->>'gameSessionGameInstanceUuid')::UUID; + SELECT prepared.* INTO STRICT retained + FROM "${serviceSchema}".world_canonical_instance_preparation prepared + WHERE prepared.canonical_game_instance_id = association.canonical_game_instance_id; + IF retained.world_instance_id IS DISTINCT FROM p_world_instance_id + OR retained.private_game_instance_key IS DISTINCT FROM p_private_game_instance_key + OR retained.capture_id IS NOT NULL + OR retained.fixed_preset_id IS DISTINCT FROM 'firemud-demo-topology-v1' + OR retained.fixed_preset_content_digest IS DISTINCT FROM p_expected_content_digest + OR retained.fixed_preset_binding_digest IS DISTINCT FROM p->>'presetSealDigest' + OR retained.input_digest IS DISTINCT FROM p->>'presetSealDigest' + OR retained.input_json IS DISTINCT FROM p_plan_json + OR retained.graph_bytes IS DISTINCT FROM convert_to(p_plan_json, 'UTF8') + OR retained.graph_sha256 IS DISTINCT FROM + encode(sha256(convert_to(p_plan_json, 'UTF8')), 'hex') + OR retained.target_namespace IS DISTINCT FROM p->>'targetNamespace' + OR retained.canonical_tenant_id IS DISTINCT FROM (p->>'canonicalTenantId')::UUID + OR retained.world_slug IS DISTINCT FROM p->>'worldSlug' + OR retained.control_plane_request_id IS DISTINCT FROM p->>'fixtureOperationId' + OR retained.canonical_version_id IS DISTINCT FROM (p->>'canonicalVersionId')::UUID + OR retained.version_identity_operation_id IS DISTINCT FROM + (p->>'worldVersionIdentityOperationId')::UUID THEN + RAISE EXCEPTION 'RUN_OWNED_WORLD_FIXED_PRESET_RESULT_MISMATCH: retained preparation differs' + USING ERRCODE = '23514'; + END IF; + + SELECT count(*) INTO template_count + FROM "${serviceSchema}".world_authored_topology_identity mapping + WHERE mapping.target_namespace = association.canonical_target_namespace + AND mapping.canonical_tenant_id = association.canonical_tenant_id + AND mapping.canonical_version_id = association.canonical_version_id + AND mapping.preparation_authority_kind = 'RUN_OWNED_FIXTURE' + AND mapping.fixture_world_instance_id = association.world_instance_id + AND mapping.fixture_operation_id = association.control_plane_request_id + AND mapping.fixture_provenance_digest = association.fixture_provenance_digest; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_authored_topology_identity m + WHERE m.target_namespace = association.canonical_target_namespace + AND m.canonical_tenant_id = association.canonical_tenant_id + AND m.canonical_version_id = association.canonical_version_id + AND (m.preparation_authority_kind IS DISTINCT FROM 'RUN_OWNED_FIXTURE' + OR m.fixture_world_instance_id IS DISTINCT FROM association.world_instance_id + OR m.fixture_operation_id IS DISTINCT FROM association.control_plane_request_id + OR m.fixture_provenance_digest IS DISTINCT FROM association.fixture_provenance_digest)) THEN + RAISE EXCEPTION 'RUN_OWNED_WORLD_FIXED_PRESET_TOPOLOGY_MISMATCH: mapping owner differs' + USING ERRCODE = '23514'; + END IF; + SELECT count(*) INTO region_runtime_count + FROM "${serviceSchema}".region_instance region_runtime + WHERE region_runtime.world_instance_id = p_world_instance_id + AND region_runtime.tenant_id = association.local_tenant_key + AND region_runtime.game_instance_id = p_private_game_instance_key; + SELECT count(*) INTO zone_runtime_count + FROM "${serviceSchema}".zone_instance z + JOIN "${serviceSchema}".region_instance r ON r.id = z.region_instance_id + WHERE r.world_instance_id = p_world_instance_id + AND z.tenant_id = association.local_tenant_key + AND z.game_instance_id = p_private_game_instance_key; + SELECT count(*) INTO room_runtime_count + FROM "${serviceSchema}".room_instance r + JOIN "${serviceSchema}".region_instance ri ON ri.id = r.region_instance_id + WHERE ri.world_instance_id = p_world_instance_id + AND r.tenant_id = association.local_tenant_key + AND r.game_instance_id = p_private_game_instance_key; + SELECT count(*) INTO exit_runtime_count + FROM "${serviceSchema}".room_instance_exit e + WHERE e.tenant_id = association.local_tenant_key + AND e.game_instance_id = p_private_game_instance_key; + SELECT count(*) INTO topology_identity_count + FROM "${serviceSchema}".world_canonical_instance_topology_identity topology + WHERE topology.world_instance_id = p_world_instance_id + AND topology.canonical_game_instance_id = association.canonical_game_instance_id; + IF template_count <> 6 OR region_runtime_count <> 1 OR zone_runtime_count <> 1 + OR room_runtime_count <> 2 OR exit_runtime_count <> 2 OR topology_identity_count <> 6 + OR retained.region_count <> 1 OR retained.zone_count <> 1 + OR retained.room_count <> 2 OR retained.exit_count <> 2 THEN + RAISE EXCEPTION 'RUN_OWNED_WORLD_FIXED_PRESET_TOPOLOGY_MISMATCH: missing or extra rows' + USING ERRCODE = '23514'; + END IF; + + IF NOT EXISTS ( + SELECT 1 + FROM "${serviceSchema}".world_authored_topology_identity m + JOIN "${serviceSchema}".region r ON r.id = m.private_row_key + WHERE m.target_namespace = association.canonical_target_namespace + AND m.canonical_tenant_id = association.canonical_tenant_id + AND m.canonical_version_id = association.canonical_version_id + AND m.version_identity_operation_id = association.version_identity_operation_id + AND m.family = 'REGION' + AND m.template_id = '9affa11b-02f5-3cc9-a50e-6760083c71e9'::UUID + AND r.tenant_id = association.local_tenant_key + AND r.version_id = association.local_version_key + AND r.name = 'Demo Region' AND r.shard_id = 0 + AND r.generation_seed = 0 AND r.spacing_multiplier = 1.0 + AND EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_canonical_instance_topology_identity ti + JOIN "${serviceSchema}".region_instance ri ON ri.id = ti.runtime_row_id + WHERE ti.world_instance_id = p_world_instance_id + AND ti.family = 'REGION' AND ti.template_id = m.template_id + AND ti.template_private_row_key = m.private_row_key + AND ri.world_instance_id = p_world_instance_id + AND ri.tenant_id = association.local_tenant_key + AND ri.game_instance_id = p_private_game_instance_key + AND ri.name = r.name AND ri.shard_id = r.shard_id + AND ri.generation_seed = r.generation_seed + AND ri.spacing_multiplier = r.spacing_multiplier)) + OR NOT EXISTS ( + SELECT 1 + FROM "${serviceSchema}".world_authored_topology_identity zm + JOIN "${serviceSchema}".zone z ON z.id = zm.private_row_key + JOIN "${serviceSchema}".world_authored_topology_identity rm + ON rm.family = 'REGION' AND rm.target_namespace = zm.target_namespace + AND rm.canonical_tenant_id = zm.canonical_tenant_id + AND rm.canonical_version_id = zm.canonical_version_id + AND rm.template_id = '9affa11b-02f5-3cc9-a50e-6760083c71e9'::UUID + WHERE zm.target_namespace = association.canonical_target_namespace + AND zm.canonical_tenant_id = association.canonical_tenant_id + AND zm.canonical_version_id = association.canonical_version_id + AND zm.version_identity_operation_id = association.version_identity_operation_id + AND zm.family = 'ZONE' + AND zm.template_id = '936c4d65-c460-3b73-9f4e-6ee6295bca24'::UUID + AND z.tenant_id = association.local_tenant_key + AND z.version_id = association.local_version_key + AND z.region_id = rm.private_row_key AND z.name = 'Demo Zone' + AND EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_canonical_instance_topology_identity ti + JOIN "${serviceSchema}".zone_instance zi ON zi.id = ti.runtime_row_id + JOIN "${serviceSchema}".world_canonical_instance_topology_identity ri + ON ri.world_instance_id = p_world_instance_id + AND ri.family = 'REGION' + AND ri.template_id = rm.template_id + WHERE ti.world_instance_id = p_world_instance_id + AND ti.family = 'ZONE' AND ti.template_id = zm.template_id + AND ti.template_private_row_key = zm.private_row_key + AND zi.tenant_id = association.local_tenant_key + AND zi.game_instance_id = p_private_game_instance_key + AND zi.template_zone_id = z.id AND zi.name = z.name + AND zi.region_instance_id = ri.runtime_row_id)) + OR NOT EXISTS ( + SELECT 1 + FROM "${serviceSchema}".world_authored_topology_identity m + JOIN "${serviceSchema}".room r ON r.id = m.private_row_key + JOIN "${serviceSchema}".world_authored_topology_identity zm + ON zm.target_namespace = m.target_namespace + AND zm.canonical_tenant_id = m.canonical_tenant_id + AND zm.canonical_version_id = m.canonical_version_id + AND zm.family = 'ZONE' + AND zm.template_id = '936c4d65-c460-3b73-9f4e-6ee6295bca24'::UUID + WHERE m.target_namespace = association.canonical_target_namespace + AND m.canonical_tenant_id = association.canonical_tenant_id + AND m.canonical_version_id = association.canonical_version_id + AND m.version_identity_operation_id = association.version_identity_operation_id + AND m.family = 'ROOM' + AND ((m.template_id = 'c6058518-f9e0-3f26-9b05-2bc786095089'::UUID + AND r.name = 'Candle-lit Antechamber' + AND r.description = 'Stalactites drip along the northern wall while a faint draft carries the smell of damp earth from the lower tunnels. Torches flicker in alcoves, casting motion into the shadowy archway to the north.') + OR (m.template_id = 'e74cca03-3b53-3edc-84f5-890651f5fea8'::UUID + AND r.name = 'Smith''s Annex' + AND r.description = 'An anvil, banked coals, and orderly tool racks mark this alcove as a working annex off the starter chamber.')) + AND r.tenant_id = association.local_tenant_key + AND r.version_id = association.local_version_key + AND r.zone_id = zm.private_row_key + AND EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_canonical_instance_topology_identity ti + JOIN "${serviceSchema}".room_instance ri ON ri.id = ti.runtime_row_id + JOIN "${serviceSchema}".world_canonical_instance_topology_identity zi + ON zi.world_instance_id = p_world_instance_id + AND zi.family = 'ZONE' + AND zi.template_id = '936c4d65-c460-3b73-9f4e-6ee6295bca24'::UUID + WHERE ti.world_instance_id = p_world_instance_id + AND ti.family = 'ROOM' AND ti.template_id = m.template_id + AND ti.template_private_row_key = m.private_row_key + AND ti.runtime_room_instance_id = ri.room_instance_row_id + AND ri.tenant_id = association.local_tenant_key + AND ri.game_instance_id = p_private_game_instance_key + AND ri.template_room_id = r.id + AND ri.name = r.name AND ri.description IS NOT DISTINCT FROM r.description + AND ri.zone_instance_id = zi.runtime_row_id)) + OR (SELECT count(*) FROM "${serviceSchema}".world_authored_topology_identity m + JOIN "${serviceSchema}".room_exit e ON e.id = m.private_row_key + WHERE m.target_namespace = association.canonical_target_namespace + AND m.canonical_tenant_id = association.canonical_tenant_id + AND m.canonical_version_id = association.canonical_version_id + AND m.version_identity_operation_id = association.version_identity_operation_id + AND m.family = 'ROOM_EXIT' + AND e.tenant_id = association.local_tenant_key + AND e.version_id = association.local_version_key + AND e.cost = 1 + AND ((m.template_id = '18c4b7a2-6498-3865-a464-814b56e4d4c2'::UUID + AND e.direction = 'NORTH') + OR (m.template_id = 'ab46ef8f-e74f-3197-be62-9785ef63242e'::UUID + AND e.direction = 'SOUTH')) + AND EXISTS (SELECT 1 FROM "${serviceSchema}".world_authored_topology_identity f + WHERE f.target_namespace = m.target_namespace + AND f.canonical_tenant_id = m.canonical_tenant_id + AND f.canonical_version_id = m.canonical_version_id + AND f.family = 'ROOM' + AND f.template_id = CASE m.template_id + WHEN '18c4b7a2-6498-3865-a464-814b56e4d4c2'::UUID + THEN 'c6058518-f9e0-3f26-9b05-2bc786095089'::UUID + ELSE 'e74cca03-3b53-3edc-84f5-890651f5fea8'::UUID END + AND f.private_row_key = e.from_room_id) + AND EXISTS (SELECT 1 FROM "${serviceSchema}".world_authored_topology_identity t + WHERE t.target_namespace = m.target_namespace + AND t.canonical_tenant_id = m.canonical_tenant_id + AND t.canonical_version_id = m.canonical_version_id + AND t.family = 'ROOM' + AND t.template_id = CASE m.template_id + WHEN '18c4b7a2-6498-3865-a464-814b56e4d4c2'::UUID + THEN 'e74cca03-3b53-3edc-84f5-890651f5fea8'::UUID + ELSE 'c6058518-f9e0-3f26-9b05-2bc786095089'::UUID END + AND t.private_row_key = e.to_room_id)) <> 2 + OR EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_authored_topology_identity m + WHERE m.target_namespace = association.canonical_target_namespace + AND m.canonical_tenant_id = association.canonical_tenant_id + AND m.canonical_version_id = association.canonical_version_id + AND (m.family,m.template_id) NOT IN ( + ('REGION','9affa11b-02f5-3cc9-a50e-6760083c71e9'::UUID), + ('ZONE','936c4d65-c460-3b73-9f4e-6ee6295bca24'::UUID), + ('ROOM','c6058518-f9e0-3f26-9b05-2bc786095089'::UUID), + ('ROOM','e74cca03-3b53-3edc-84f5-890651f5fea8'::UUID), + ('ROOM_EXIT','18c4b7a2-6498-3865-a464-814b56e4d4c2'::UUID), + ('ROOM_EXIT','ab46ef8f-e74f-3197-be62-9785ef63242e'::UUID))) THEN + RAISE EXCEPTION 'RUN_OWNED_WORLD_FIXED_PRESET_TOPOLOGY_MISMATCH: template graph or runtime readback differs' + USING ERRCODE = '23514'; + END IF; + + IF (SELECT count(*) FROM "${serviceSchema}".room_instance_exit e + JOIN "${serviceSchema}".world_canonical_instance_topology_identity xi + ON xi.world_instance_id = p_world_instance_id AND xi.family = 'ROOM_EXIT' + AND xi.runtime_row_id = e.id + JOIN "${serviceSchema}".world_canonical_instance_topology_identity fi + ON fi.world_instance_id = p_world_instance_id AND fi.family = 'ROOM' + AND fi.template_id = CASE xi.template_id + WHEN '18c4b7a2-6498-3865-a464-814b56e4d4c2'::UUID + THEN 'c6058518-f9e0-3f26-9b05-2bc786095089'::UUID + ELSE 'e74cca03-3b53-3edc-84f5-890651f5fea8'::UUID END + JOIN "${serviceSchema}".world_canonical_instance_topology_identity ti + ON ti.world_instance_id = p_world_instance_id AND ti.family = 'ROOM' + AND ti.template_id = CASE xi.template_id + WHEN '18c4b7a2-6498-3865-a464-814b56e4d4c2'::UUID + THEN 'e74cca03-3b53-3edc-84f5-890651f5fea8'::UUID + ELSE 'c6058518-f9e0-3f26-9b05-2bc786095089'::UUID END + WHERE e.tenant_id = association.local_tenant_key + AND e.game_instance_id = p_private_game_instance_key + AND e.from_room_instance_record_id = fi.runtime_room_instance_id + AND e.to_room_instance_record_id = ti.runtime_room_instance_id + AND e.cost = 1 + AND e.direction = CASE xi.template_id + WHEN '18c4b7a2-6498-3865-a464-814b56e4d4c2'::UUID THEN 'NORTH' + ELSE 'SOUTH' END) <> 2 THEN + RAISE EXCEPTION 'RUN_OWNED_WORLD_FIXED_PRESET_CONNECTIVITY_MISMATCH: reciprocal exits differ' + USING ERRCODE = '23514'; + END IF; + + world_instance_id := retained.world_instance_id; + tenant_id := association.local_tenant_key; + private_game_instance_key := retained.private_game_instance_key; + version_id := association.local_version_key; + preset_id := retained.fixed_preset_id; + preset_content_digest := retained.fixed_preset_content_digest; + preset_binding_digest := retained.fixed_preset_binding_digest; + graph_sha256 := retained.graph_sha256; + region_count := retained.region_count; + zone_count := retained.zone_count; + room_count := retained.room_count; + exit_count := retained.exit_count; + RETURN NEXT; +END; +$$; +REVOKE ALL ON FUNCTION world_read_run_owned_fixed_preset(TEXT, TEXT, BIGINT, BIGINT) FROM PUBLIC; + +-- Fixture lifecycle transitions and admission remain closed by the existing World owners. +-- The PREPARING-only API writes resources and a retained result; it never updates world_instance. + +CREATE FUNCTION world_materialize_run_owned_fixed_preset( + p_plan_json TEXT, p_expected_content_digest TEXT, p_world_instance_id BIGINT, + p_private_game_instance_key BIGINT +) RETURNS TABLE( + world_instance_id BIGINT, tenant_id BIGINT, private_game_instance_key BIGINT, + version_id BIGINT, preset_id TEXT, preset_content_digest TEXT, + preset_binding_digest TEXT, graph_sha256 TEXT, region_count INTEGER, + zone_count INTEGER, room_count INTEGER, exit_count INTEGER +) +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + p JSONB; + a "${serviceSchema}".world_canonical_instance_association%ROWTYPE; + wi "${serviceSchema}".world_instance%ROWTYPE; + v "${serviceSchema}".world_authored_version_identity%ROWTYPE; + intake "${serviceSchema}".world_authored_source_intake%ROWTYPE; + publication_owner "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + owner_binding JSONB; + complete_binding JSONB; + operation UUID; + result_id BIGINT; + template_region_id BIGINT; + template_zone_id BIGINT; + template_room_one_id BIGINT; + template_room_two_id BIGINT; + template_exit_north_id BIGINT; + template_exit_south_id BIGINT; + runtime_region_id BIGINT; + runtime_region_uuid UUID; + runtime_zone_id BIGINT; + runtime_zone_uuid UUID; + runtime_room_one_id BIGINT; + runtime_room_two_id BIGINT; + runtime_exit_north_id BIGINT; + runtime_exit_south_id BIGINT; + row_json JSONB; + region_template "${serviceSchema}".region%ROWTYPE; + zone_template "${serviceSchema}".zone%ROWTYPE; + room_template "${serviceSchema}".room%ROWTYPE; + exit_template "${serviceSchema}".room_exit%ROWTYPE; + runtime_region "${serviceSchema}".region_instance%ROWTYPE; + runtime_zone "${serviceSchema}".zone_instance%ROWTYPE; + runtime_room "${serviceSchema}".room_instance%ROWTYPE; + runtime_exit "${serviceSchema}".room_instance_exit%ROWTYPE; + topology_identity "${serviceSchema}".world_canonical_instance_topology_identity%ROWTYPE; + preparation "${serviceSchema}".world_canonical_instance_preparation%ROWTYPE; + mapping_input RECORD; + mapping_row "${serviceSchema}".world_authored_topology_identity%ROWTYPE; + topology_identity_json JSONB; + graph_digest TEXT; +BEGIN + IF current_setting('transaction_isolation') <> 'read committed' + OR current_setting('transaction_read_only') <> 'off' THEN + RAISE EXCEPTION 'Run-owned fixed-preset materialization requires writable READ COMMITTED' + USING ERRCODE = '23514'; + END IF; + IF p_plan_json IS NULL OR length(p_plan_json) = 0 THEN + RAISE EXCEPTION 'RUN_OWNED_WORLD_FIXED_PRESET_PLAN_INVALID' USING ERRCODE = '23514'; + END IF; + p := p_plan_json::JSONB; + PERFORM "${serviceSchema}".world_verify_run_owned_fixed_preset_plan( + p, p_expected_content_digest, p_world_instance_id, p_private_game_instance_key); + SELECT association.* INTO STRICT a FROM "${serviceSchema}".world_canonical_instance_association association + WHERE association.world_instance_id = p_world_instance_id + AND association.canonical_game_instance_id = (p->>'gameSessionGameInstanceUuid')::UUID FOR UPDATE; + SELECT instance.* INTO STRICT wi FROM "${serviceSchema}".world_instance instance + WHERE instance.id = p_world_instance_id FOR UPDATE; + SELECT version_owner.* INTO STRICT v FROM "${serviceSchema}".world_authored_version_identity version_owner + WHERE version_owner.operation_id = a.version_identity_operation_id FOR SHARE; + SELECT source_owner.* INTO STRICT intake FROM "${serviceSchema}".world_authored_source_intake source_owner + WHERE source_owner.operation_id = a.intake_operation_id FOR SHARE; + SELECT fence_owner.* INTO STRICT publication_owner + FROM "${serviceSchema}".world_design_publication_fence_owner fence_owner + WHERE fence_owner.target_namespace = v.target_namespace + AND fence_owner.canonical_tenant_id = v.canonical_tenant_id + AND fence_owner.local_tenant_key = v.local_tenant_key AND fence_owner.version_id = v.local_version_key + FOR UPDATE; + PERFORM "${serviceSchema}".world_verify_run_owned_fixed_preset_plan( + p, p_expected_content_digest, p_world_instance_id, p_private_game_instance_key); + operation := (p->>'fixtureOperationId')::UUID; + graph_digest := encode(sha256(convert_to(p_plan_json, 'UTF8')), 'hex'); + + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_preparation prepared + WHERE prepared.canonical_game_instance_id = a.canonical_game_instance_id) THEN + RETURN QUERY SELECT * FROM "${serviceSchema}".world_read_run_owned_fixed_preset( + p_plan_json, p_expected_content_digest, p_world_instance_id, + p_private_game_instance_key); + RETURN; + END IF; + + IF EXISTS (SELECT 1 FROM "${serviceSchema}".region region_template_owner + WHERE region_template_owner.tenant_id = a.local_tenant_key AND region_template_owner.version_id = a.local_version_key) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".zone zone_template_owner + WHERE zone_template_owner.tenant_id = a.local_tenant_key AND zone_template_owner.version_id = a.local_version_key) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".room room_template_owner + WHERE room_template_owner.tenant_id = a.local_tenant_key AND room_template_owner.version_id = a.local_version_key) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".room_exit exit_template_owner + WHERE exit_template_owner.tenant_id = a.local_tenant_key AND exit_template_owner.version_id = a.local_version_key) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".generation_rule generation_owner + WHERE generation_owner.tenant_id = a.local_tenant_key AND generation_owner.version_id = a.local_version_key) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".world_entity_spawn_binding spawn_owner + WHERE spawn_owner.tenant_id = a.local_tenant_key AND spawn_owner.version_id = a.local_version_key) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".world_authored_topology_identity mapping + WHERE mapping.target_namespace = a.canonical_target_namespace + AND mapping.canonical_tenant_id = a.canonical_tenant_id + AND mapping.canonical_version_id = a.canonical_version_id) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".region_instance region_runtime + WHERE region_runtime.world_instance_id = p_world_instance_id + OR (region_runtime.tenant_id = a.local_tenant_key AND region_runtime.game_instance_id = p_private_game_instance_key)) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_topology_identity topology + WHERE topology.world_instance_id = p_world_instance_id) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".zone_instance zone_runtime + WHERE zone_runtime.tenant_id = a.local_tenant_key AND zone_runtime.game_instance_id = p_private_game_instance_key) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".room_instance room_runtime + WHERE room_runtime.tenant_id = a.local_tenant_key AND room_runtime.game_instance_id = p_private_game_instance_key) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".room_instance_exit exit_runtime + WHERE exit_runtime.tenant_id = a.local_tenant_key AND exit_runtime.game_instance_id = p_private_game_instance_key) THEN + RAISE EXCEPTION 'RUN_OWNED_WORLD_FIXED_PRESET_PREEXISTING_RESOURCES: refusing unowned or partial topology' + USING ERRCODE = '23514'; + END IF; + + owner_binding := jsonb_build_object( + 'targetNamespace', v.target_namespace, + 'canonicalTenantId', v.canonical_tenant_id, + 'canonicalVersionId', v.canonical_version_id, + 'versionIdentityOperationId', v.operation_id, + 'gameDesignVersionId', v.game_design_version_id, + 'intakeRequestId', v.intake_request_id, + 'intakeOperationId', v.intake_operation_id, + 'intakeRequestDigest', v.intake_request_digest, + 'sourceOperationId', v.source_operation_id, + 'sourceEvidenceDigest', v.source_evidence_digest, + 'intakeReceiptDigest', v.intake_receipt_digest); + complete_binding := p; + + IF wi.status IS DISTINCT FROM 'PREPARING' + OR wi.lifecycle_epoch IS DISTINCT FROM a.preparing_lifecycle_epoch THEN + RAISE EXCEPTION 'RUN_OWNED_WORLD_FIXED_PRESET_ALLOCATION_INVALID: no fresh active materialization' + USING ERRCODE = '23514'; + END IF; + + template_region_id := nextval('"${serviceSchema}".region_id_seq'); + region_template := jsonb_populate_record(NULL::"${serviceSchema}".region, + jsonb_build_object('id',template_region_id,'name','Demo Region', + 'tenant_id',a.local_tenant_key,'shard_id',0,'weather',NULL, + 'generation_seed',0,'generator_type',NULL,'generator_params',NULL, + 'spacing_multiplier',1.0,'version',0,'version_id',a.local_version_key)); + row_json := to_jsonb(region_template); + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(),operation,'region',template_region_id,'INSERT',v.operation_id, + v.local_tenant_key,v.local_version_key,owner_binding,complete_binding,NULL,row_json, + 'RUN_OWNED_FIXTURE',a.fixture_provenance_digest,a.world_instance_id,a.control_plane_request_id); + INSERT INTO "${serviceSchema}".region SELECT + (jsonb_populate_record(NULL::"${serviceSchema}".region,row_json)).*; + + template_zone_id := nextval('"${serviceSchema}".zone_id_seq'); + zone_template := jsonb_populate_record(NULL::"${serviceSchema}".zone, + jsonb_build_object('id',template_zone_id,'region_id',template_region_id, + 'name','Demo Zone','tenant_id',a.local_tenant_key, + 'version_id',a.local_version_key,'version',0)); + row_json := to_jsonb(zone_template); + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(),operation,'zone',template_zone_id,'INSERT',v.operation_id, + v.local_tenant_key,v.local_version_key,owner_binding,complete_binding,NULL,row_json, + 'RUN_OWNED_FIXTURE',a.fixture_provenance_digest,a.world_instance_id,a.control_plane_request_id); + INSERT INTO "${serviceSchema}".zone SELECT + (jsonb_populate_record(NULL::"${serviceSchema}".zone,row_json)).*; + + template_room_one_id := nextval('"${serviceSchema}".room_id_seq'); + room_template := jsonb_populate_record(NULL::"${serviceSchema}".room, + jsonb_build_object('id',template_room_one_id,'zone_id',template_zone_id, + 'name','Candle-lit Antechamber', + 'description','Stalactites drip along the northern wall while a faint draft carries the smell of damp earth from the lower tunnels. Torches flicker in alcoves, casting motion into the shadowy archway to the north.', + 'tenant_id',a.local_tenant_key,'version_id',a.local_version_key, + 'version',0,'name_localized_variants_json',NULL, + 'description_localized_variants_json',NULL)); + row_json := to_jsonb(room_template); + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(),operation,'room',template_room_one_id,'INSERT',v.operation_id, + v.local_tenant_key,v.local_version_key,owner_binding,complete_binding,NULL,row_json, + 'RUN_OWNED_FIXTURE',a.fixture_provenance_digest,a.world_instance_id,a.control_plane_request_id); + INSERT INTO "${serviceSchema}".room SELECT + (jsonb_populate_record(NULL::"${serviceSchema}".room,row_json)).*; + + template_room_two_id := nextval('"${serviceSchema}".room_id_seq'); + room_template := jsonb_populate_record(NULL::"${serviceSchema}".room, + jsonb_build_object('id',template_room_two_id,'zone_id',template_zone_id, + 'name','Smith''s Annex', + 'description','An anvil, banked coals, and orderly tool racks mark this alcove as a working annex off the starter chamber.', + 'tenant_id',a.local_tenant_key,'version_id',a.local_version_key, + 'version',0,'name_localized_variants_json',NULL, + 'description_localized_variants_json',NULL)); + row_json := to_jsonb(room_template); + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(),operation,'room',template_room_two_id,'INSERT',v.operation_id, + v.local_tenant_key,v.local_version_key,owner_binding,complete_binding,NULL,row_json, + 'RUN_OWNED_FIXTURE',a.fixture_provenance_digest,a.world_instance_id,a.control_plane_request_id); + INSERT INTO "${serviceSchema}".room SELECT + (jsonb_populate_record(NULL::"${serviceSchema}".room,row_json)).*; + + template_exit_north_id := nextval('"${serviceSchema}".room_exit_id_seq'); + exit_template := jsonb_populate_record(NULL::"${serviceSchema}".room_exit, + jsonb_build_object('id',template_exit_north_id,'tenant_id',a.local_tenant_key, + 'version_id',a.local_version_key,'from_room_id',template_room_one_id, + 'to_room_id',template_room_two_id,'direction','NORTH','cost',1,'version',0)); + row_json := to_jsonb(exit_template); + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(),operation,'room_exit',template_exit_north_id,'INSERT',v.operation_id, + v.local_tenant_key,v.local_version_key,owner_binding,complete_binding,NULL,row_json, + 'RUN_OWNED_FIXTURE',a.fixture_provenance_digest,a.world_instance_id,a.control_plane_request_id); + INSERT INTO "${serviceSchema}".room_exit SELECT + (jsonb_populate_record(NULL::"${serviceSchema}".room_exit,row_json)).*; + + template_exit_south_id := nextval('"${serviceSchema}".room_exit_id_seq'); + exit_template := jsonb_populate_record(NULL::"${serviceSchema}".room_exit, + jsonb_build_object('id',template_exit_south_id,'tenant_id',a.local_tenant_key, + 'version_id',a.local_version_key,'from_room_id',template_room_two_id, + 'to_room_id',template_room_one_id,'direction','SOUTH','cost',1,'version',0)); + row_json := to_jsonb(exit_template); + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(),operation,'room_exit',template_exit_south_id,'INSERT',v.operation_id, + v.local_tenant_key,v.local_version_key,owner_binding,complete_binding,NULL,row_json, + 'RUN_OWNED_FIXTURE',a.fixture_provenance_digest,a.world_instance_id,a.control_plane_request_id); + INSERT INTO "${serviceSchema}".room_exit SELECT + (jsonb_populate_record(NULL::"${serviceSchema}".room_exit,row_json)).*; + + FOR mapping_input IN + SELECT * FROM (VALUES + ('REGION','9affa11b-02f5-3cc9-a50e-6760083c71e9'::UUID,template_region_id), + ('ZONE','936c4d65-c460-3b73-9f4e-6ee6295bca24'::UUID,template_zone_id), + ('ROOM','c6058518-f9e0-3f26-9b05-2bc786095089'::UUID,template_room_one_id), + ('ROOM','e74cca03-3b53-3edc-84f5-890651f5fea8'::UUID,template_room_two_id), + ('ROOM_EXIT','18c4b7a2-6498-3865-a464-814b56e4d4c2'::UUID,template_exit_north_id), + ('ROOM_EXIT','ab46ef8f-e74f-3197-be62-9785ef63242e'::UUID,template_exit_south_id) + ) AS fixed(family,template_id,private_row_key) + LOOP + mapping_row := jsonb_populate_record(NULL::"${serviceSchema}".world_authored_topology_identity, + jsonb_build_object('id',nextval('"${serviceSchema}".world_authored_topology_identity_id_seq'), + 'target_namespace',v.target_namespace,'canonical_tenant_id',v.canonical_tenant_id, + 'canonical_version_id',v.canonical_version_id,'family',mapping_input.family, + 'template_id',mapping_input.template_id, + 'private_row_key',mapping_input.private_row_key,'tenant_id',v.local_tenant_key, + 'version_id',v.local_version_key,'version_identity_operation_id',v.operation_id, + 'preparation_authority_kind','RUN_OWNED_FIXTURE', + 'fixture_provenance_digest',a.fixture_provenance_digest, + 'fixture_world_instance_id',a.world_instance_id, + 'fixture_operation_id',a.control_plane_request_id)); + row_json := to_jsonb(mapping_row); + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(),operation,'world_authored_topology_identity',mapping_row.id,'INSERT', + v.operation_id,v.local_tenant_key,v.local_version_key,owner_binding, + complete_binding,NULL,row_json, + 'RUN_OWNED_FIXTURE',a.fixture_provenance_digest,a.world_instance_id,a.control_plane_request_id); + INSERT INTO "${serviceSchema}".world_authored_topology_identity SELECT + (jsonb_populate_record(NULL::"${serviceSchema}".world_authored_topology_identity,row_json)).*; + END LOOP; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_region_draft_execution_manifest template_manifest + WHERE template_manifest.transaction_id = txid_current()) THEN + RAISE EXCEPTION 'RUN_OWNED_WORLD_FIXED_PRESET_TEMPLATE_MANIFEST_REMAINS' + USING ERRCODE = '23514'; + END IF; + + runtime_region_id := nextval('"${serviceSchema}".region_instance_id_seq'); + runtime_region_uuid := gen_random_uuid(); + runtime_region := jsonb_populate_record(NULL::"${serviceSchema}".region_instance, + jsonb_build_object('id',runtime_region_id,'tenant_id',a.local_tenant_key, + 'game_instance_id',p_private_game_instance_key,'world_instance_id',p_world_instance_id, + 'shard_id',0,'name','Demo Region','weather',NULL,'generation_seed',0, + 'generator_type',NULL,'generator_params',NULL,'spacing_multiplier',1.0, + 'version',0,'canonical_region_instance_id',runtime_region_uuid)); + row_json := to_jsonb(runtime_region); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(),'region_instance',runtime_region_id,a.canonical_game_instance_id, + a.canonical_target_namespace,a.canonical_tenant_id,a.canonical_version_id, + a.version_identity_operation_id,NULL,a.local_tenant_key,a.preparation_input_digest,row_json, + 'RUN_OWNED_FIXTURE',a.fixture_provenance_digest,a.world_instance_id,a.control_plane_request_id,p); + INSERT INTO "${serviceSchema}".region_instance SELECT + (jsonb_populate_record(NULL::"${serviceSchema}".region_instance,row_json)).*; + topology_identity := jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_topology_identity, + jsonb_build_object('id',nextval('"${serviceSchema}".world_canonical_instance_topology_identity_id_seq'), + 'world_instance_id',p_world_instance_id,'canonical_game_instance_id',a.canonical_game_instance_id, + 'family','REGION','template_id','9affa11b-02f5-3cc9-a50e-6760083c71e9'::UUID, + 'template_private_row_key',template_region_id,'runtime_row_id',runtime_region_id, + 'runtime_identity',runtime_region_uuid,'runtime_room_instance_id',NULL)); + topology_identity_json := to_jsonb(topology_identity); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(),'world_canonical_instance_topology_identity',topology_identity.id, + a.canonical_game_instance_id,a.canonical_target_namespace,a.canonical_tenant_id, + a.canonical_version_id,a.version_identity_operation_id,NULL,a.local_tenant_key, + a.preparation_input_digest,topology_identity_json, + 'RUN_OWNED_FIXTURE',a.fixture_provenance_digest,a.world_instance_id,a.control_plane_request_id,p); + INSERT INTO "${serviceSchema}".world_canonical_instance_topology_identity SELECT + (jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_topology_identity, + topology_identity_json)).*; + + runtime_zone_id := nextval('"${serviceSchema}".zone_instance_id_seq'); + runtime_zone_uuid := gen_random_uuid(); + runtime_zone := jsonb_populate_record(NULL::"${serviceSchema}".zone_instance, + jsonb_build_object('id',runtime_zone_id,'tenant_id',a.local_tenant_key, + 'game_instance_id',p_private_game_instance_key,'zone_instance_id',runtime_zone_id, + 'template_zone_id',template_zone_id,'region_instance_id',runtime_region_id, + 'name','Demo Zone','version',0,'canonical_zone_instance_id',runtime_zone_uuid)); + row_json := to_jsonb(runtime_zone); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(),'zone_instance',runtime_zone_id,a.canonical_game_instance_id, + a.canonical_target_namespace,a.canonical_tenant_id,a.canonical_version_id, + a.version_identity_operation_id,NULL,a.local_tenant_key,a.preparation_input_digest,row_json, + 'RUN_OWNED_FIXTURE',a.fixture_provenance_digest,a.world_instance_id,a.control_plane_request_id,p); + INSERT INTO "${serviceSchema}".zone_instance SELECT + (jsonb_populate_record(NULL::"${serviceSchema}".zone_instance,row_json)).*; + topology_identity := jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_topology_identity, + jsonb_build_object('id',nextval('"${serviceSchema}".world_canonical_instance_topology_identity_id_seq'), + 'world_instance_id',p_world_instance_id,'canonical_game_instance_id',a.canonical_game_instance_id, + 'family','ZONE','template_id','936c4d65-c460-3b73-9f4e-6ee6295bca24'::UUID, + 'template_private_row_key',template_zone_id,'runtime_row_id',runtime_zone_id, + 'runtime_identity',runtime_zone_uuid,'runtime_room_instance_id',NULL)); + topology_identity_json := to_jsonb(topology_identity); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(),'world_canonical_instance_topology_identity',topology_identity.id, + a.canonical_game_instance_id,a.canonical_target_namespace,a.canonical_tenant_id, + a.canonical_version_id,a.version_identity_operation_id,NULL,a.local_tenant_key, + a.preparation_input_digest,topology_identity_json, + 'RUN_OWNED_FIXTURE',a.fixture_provenance_digest,a.world_instance_id,a.control_plane_request_id,p); + INSERT INTO "${serviceSchema}".world_canonical_instance_topology_identity SELECT + (jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_topology_identity, + topology_identity_json)).*; + + runtime_room_one_id := nextval('"${serviceSchema}".room_instance_id_seq'); + runtime_room := jsonb_populate_record(NULL::"${serviceSchema}".room_instance, + jsonb_build_object('id',runtime_room_one_id,'tenant_id',a.local_tenant_key, + 'game_instance_id',p_private_game_instance_key,'room_instance_row_id',runtime_room_one_id, + 'template_room_id',template_room_one_id,'region_instance_id',runtime_region_id, + 'zone_instance_id',runtime_zone_id,'name','Candle-lit Antechamber', + 'description','Stalactites drip along the northern wall while a faint draft carries the smell of damp earth from the lower tunnels. Torches flicker in alcoves, casting motion into the shadowy archway to the north.', + 'name_localized_variants_json',NULL,'description_localized_variants_json',NULL,'version',0)); + row_json := to_jsonb(runtime_room); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(),'room_instance',runtime_room_one_id,a.canonical_game_instance_id, + a.canonical_target_namespace,a.canonical_tenant_id,a.canonical_version_id, + a.version_identity_operation_id,NULL,a.local_tenant_key,a.preparation_input_digest,row_json, + 'RUN_OWNED_FIXTURE',a.fixture_provenance_digest,a.world_instance_id,a.control_plane_request_id,p); + INSERT INTO "${serviceSchema}".room_instance SELECT + (jsonb_populate_record(NULL::"${serviceSchema}".room_instance,row_json)).*; + topology_identity := jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_topology_identity, + jsonb_build_object('id',nextval('"${serviceSchema}".world_canonical_instance_topology_identity_id_seq'), + 'world_instance_id',p_world_instance_id,'canonical_game_instance_id',a.canonical_game_instance_id, + 'family','ROOM','template_id','c6058518-f9e0-3f26-9b05-2bc786095089'::UUID, + 'template_private_row_key',template_room_one_id,'runtime_row_id',runtime_room_one_id, + 'runtime_identity',NULL,'runtime_room_instance_id',runtime_room_one_id)); + topology_identity_json := to_jsonb(topology_identity); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(),'world_canonical_instance_topology_identity',topology_identity.id, + a.canonical_game_instance_id,a.canonical_target_namespace,a.canonical_tenant_id, + a.canonical_version_id,a.version_identity_operation_id,NULL,a.local_tenant_key, + a.preparation_input_digest,topology_identity_json, + 'RUN_OWNED_FIXTURE',a.fixture_provenance_digest,a.world_instance_id,a.control_plane_request_id,p); + INSERT INTO "${serviceSchema}".world_canonical_instance_topology_identity SELECT + (jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_topology_identity, + topology_identity_json)).*; + + runtime_room_two_id := nextval('"${serviceSchema}".room_instance_id_seq'); + runtime_room := jsonb_populate_record(NULL::"${serviceSchema}".room_instance, + jsonb_build_object('id',runtime_room_two_id,'tenant_id',a.local_tenant_key, + 'game_instance_id',p_private_game_instance_key,'room_instance_row_id',runtime_room_two_id, + 'template_room_id',template_room_two_id,'region_instance_id',runtime_region_id, + 'zone_instance_id',runtime_zone_id,'name','Smith''s Annex', + 'description','An anvil, banked coals, and orderly tool racks mark this alcove as a working annex off the starter chamber.', + 'name_localized_variants_json',NULL,'description_localized_variants_json',NULL,'version',0)); + row_json := to_jsonb(runtime_room); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(),'room_instance',runtime_room_two_id,a.canonical_game_instance_id, + a.canonical_target_namespace,a.canonical_tenant_id,a.canonical_version_id, + a.version_identity_operation_id,NULL,a.local_tenant_key,a.preparation_input_digest,row_json, + 'RUN_OWNED_FIXTURE',a.fixture_provenance_digest,a.world_instance_id,a.control_plane_request_id,p); + INSERT INTO "${serviceSchema}".room_instance SELECT + (jsonb_populate_record(NULL::"${serviceSchema}".room_instance,row_json)).*; + topology_identity := jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_topology_identity, + jsonb_build_object('id',nextval('"${serviceSchema}".world_canonical_instance_topology_identity_id_seq'), + 'world_instance_id',p_world_instance_id,'canonical_game_instance_id',a.canonical_game_instance_id, + 'family','ROOM','template_id','e74cca03-3b53-3edc-84f5-890651f5fea8'::UUID, + 'template_private_row_key',template_room_two_id,'runtime_row_id',runtime_room_two_id, + 'runtime_identity',NULL,'runtime_room_instance_id',runtime_room_two_id)); + topology_identity_json := to_jsonb(topology_identity); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(),'world_canonical_instance_topology_identity',topology_identity.id, + a.canonical_game_instance_id,a.canonical_target_namespace,a.canonical_tenant_id, + a.canonical_version_id,a.version_identity_operation_id,NULL,a.local_tenant_key, + a.preparation_input_digest,topology_identity_json, + 'RUN_OWNED_FIXTURE',a.fixture_provenance_digest,a.world_instance_id,a.control_plane_request_id,p); + INSERT INTO "${serviceSchema}".world_canonical_instance_topology_identity SELECT + (jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_topology_identity, + topology_identity_json)).*; + + runtime_exit_north_id := nextval('"${serviceSchema}".room_instance_exit_id_seq'); + runtime_exit := jsonb_populate_record(NULL::"${serviceSchema}".room_instance_exit, + jsonb_build_object('id',runtime_exit_north_id,'tenant_id',a.local_tenant_key, + 'game_instance_id',p_private_game_instance_key, + 'from_room_instance_record_id',runtime_room_one_id, + 'to_room_instance_record_id',runtime_room_two_id,'direction','NORTH','cost',1,'version',0)); + row_json := to_jsonb(runtime_exit); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(),'room_instance_exit',runtime_exit_north_id,a.canonical_game_instance_id, + a.canonical_target_namespace,a.canonical_tenant_id,a.canonical_version_id, + a.version_identity_operation_id,NULL,a.local_tenant_key,a.preparation_input_digest,row_json, + 'RUN_OWNED_FIXTURE',a.fixture_provenance_digest,a.world_instance_id,a.control_plane_request_id,p); + INSERT INTO "${serviceSchema}".room_instance_exit SELECT + (jsonb_populate_record(NULL::"${serviceSchema}".room_instance_exit,row_json)).*; + topology_identity := jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_topology_identity, + jsonb_build_object('id',nextval('"${serviceSchema}".world_canonical_instance_topology_identity_id_seq'), + 'world_instance_id',p_world_instance_id,'canonical_game_instance_id',a.canonical_game_instance_id, + 'family','ROOM_EXIT','template_id','18c4b7a2-6498-3865-a464-814b56e4d4c2'::UUID, + 'template_private_row_key',template_exit_north_id,'runtime_row_id',runtime_exit_north_id, + 'runtime_identity',NULL,'runtime_room_instance_id',NULL)); + topology_identity_json := to_jsonb(topology_identity); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(),'world_canonical_instance_topology_identity',topology_identity.id, + a.canonical_game_instance_id,a.canonical_target_namespace,a.canonical_tenant_id, + a.canonical_version_id,a.version_identity_operation_id,NULL,a.local_tenant_key, + a.preparation_input_digest,topology_identity_json, + 'RUN_OWNED_FIXTURE',a.fixture_provenance_digest,a.world_instance_id,a.control_plane_request_id,p); + INSERT INTO "${serviceSchema}".world_canonical_instance_topology_identity SELECT + (jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_topology_identity, + topology_identity_json)).*; + + runtime_exit_south_id := nextval('"${serviceSchema}".room_instance_exit_id_seq'); + runtime_exit := jsonb_populate_record(NULL::"${serviceSchema}".room_instance_exit, + jsonb_build_object('id',runtime_exit_south_id,'tenant_id',a.local_tenant_key, + 'game_instance_id',p_private_game_instance_key, + 'from_room_instance_record_id',runtime_room_two_id, + 'to_room_instance_record_id',runtime_room_one_id,'direction','SOUTH','cost',1,'version',0)); + row_json := to_jsonb(runtime_exit); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(),'room_instance_exit',runtime_exit_south_id,a.canonical_game_instance_id, + a.canonical_target_namespace,a.canonical_tenant_id,a.canonical_version_id, + a.version_identity_operation_id,NULL,a.local_tenant_key,a.preparation_input_digest,row_json, + 'RUN_OWNED_FIXTURE',a.fixture_provenance_digest,a.world_instance_id,a.control_plane_request_id,p); + INSERT INTO "${serviceSchema}".room_instance_exit SELECT + (jsonb_populate_record(NULL::"${serviceSchema}".room_instance_exit,row_json)).*; + topology_identity := jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_topology_identity, + jsonb_build_object('id',nextval('"${serviceSchema}".world_canonical_instance_topology_identity_id_seq'), + 'world_instance_id',p_world_instance_id,'canonical_game_instance_id',a.canonical_game_instance_id, + 'family','ROOM_EXIT','template_id','ab46ef8f-e74f-3197-be62-9785ef63242e'::UUID, + 'template_private_row_key',template_exit_south_id,'runtime_row_id',runtime_exit_south_id, + 'runtime_identity',NULL,'runtime_room_instance_id',NULL)); + topology_identity_json := to_jsonb(topology_identity); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(),'world_canonical_instance_topology_identity',topology_identity.id, + a.canonical_game_instance_id,a.canonical_target_namespace,a.canonical_tenant_id, + a.canonical_version_id,a.version_identity_operation_id,NULL,a.local_tenant_key, + a.preparation_input_digest,topology_identity_json, + 'RUN_OWNED_FIXTURE',a.fixture_provenance_digest,a.world_instance_id,a.control_plane_request_id,p); + INSERT INTO "${serviceSchema}".world_canonical_instance_topology_identity SELECT + (jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_topology_identity, + topology_identity_json)).*; + + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_preparation_execution_manifest prepare_manifest + WHERE prepare_manifest.transaction_id = txid_current()) THEN + RAISE EXCEPTION 'RUN_OWNED_WORLD_FIXED_PRESET_RUNTIME_MANIFEST_REMAINS' + USING ERRCODE = '23514'; + END IF; + result_id := nextval('"${serviceSchema}".world_canonical_instance_preparation_id_seq'); + preparation := jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_preparation, + jsonb_build_object('id',result_id, + 'canonical_game_instance_id',a.canonical_game_instance_id, + 'target_namespace',a.canonical_target_namespace, + 'canonical_tenant_id',a.canonical_tenant_id, + 'world_slug',a.canonical_world_slug, + 'control_plane_request_id',a.control_plane_request_id, + 'canonical_version_id',a.canonical_version_id, + 'version_identity_operation_id',a.version_identity_operation_id, + 'capture_id',NULL,'fixed_preset_id','firemud-demo-topology-v1', + 'fixed_preset_content_digest',p_expected_content_digest, + 'fixed_preset_binding_digest',p->>'presetSealDigest', + 'graph_bytes',convert_to(p_plan_json,'UTF8'),'graph_sha256',graph_digest, + 'input_digest',p->>'presetSealDigest','input_json',p_plan_json, + 'world_instance_id',p_world_instance_id, + 'private_game_instance_key',p_private_game_instance_key, + 'region_count',1,'zone_count',1,'room_count',2,'exit_count',2, + 'storage_status','MATERIALIZED_UNVERIFIED','prepared_at',CURRENT_TIMESTAMP)); + row_json := to_jsonb(preparation); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(),'world_canonical_instance_preparation',result_id, + a.canonical_game_instance_id,a.canonical_target_namespace,a.canonical_tenant_id, + a.canonical_version_id,a.version_identity_operation_id,NULL,a.local_tenant_key, + a.preparation_input_digest,row_json, + 'RUN_OWNED_FIXTURE',a.fixture_provenance_digest,a.world_instance_id,a.control_plane_request_id,p); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation SELECT + (jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_preparation,row_json)).*; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_preparation_execution_manifest prepare_manifest + WHERE prepare_manifest.transaction_id = txid_current()) THEN + RAISE EXCEPTION 'RUN_OWNED_WORLD_FIXED_PRESET_RESULT_MANIFEST_REMAINS' + USING ERRCODE = '23514'; + END IF; + RETURN QUERY SELECT * FROM "${serviceSchema}".world_read_run_owned_fixed_preset( + p_plan_json,p_expected_content_digest,p_world_instance_id,p_private_game_instance_key); +END; +$$; +REVOKE ALL ON FUNCTION world_materialize_run_owned_fixed_preset(TEXT, TEXT, BIGINT, BIGINT) + FROM PUBLIC; + +-- Stable same-tenant legacy UPDATE behavior is preserved by the earlier own V1007.1 and +-- V1009.1 repairs; later manifest/activation/hold extensions retain that function body. + +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1042.10__world_initial_location_retention_guards.sql b/services/world-management-service/src/main/resources/db/migration/V1042.10__world_initial_location_retention_guards.sql new file mode 100644 index 0000000000..e8d0c943b9 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1042.10__world_initial_location_retention_guards.sql @@ -0,0 +1,9 @@ +-- [jooq ignore start] +CREATE TRIGGER trg_world_reject_character_location_delete + BEFORE DELETE ON character_location + FOR EACH ROW EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE TRIGGER trg_world_reject_character_location_truncate + BEFORE TRUNCATE ON character_location + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1042.11__world_preparation_full_transaction_stamp.sql b/services/world-management-service/src/main/resources/db/migration/V1042.11__world_preparation_full_transaction_stamp.sql new file mode 100644 index 0000000000..1e9f118594 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1042.11__world_preparation_full_transaction_stamp.sql @@ -0,0 +1,88 @@ +-- Preserve the exact V35 manifest row image before adding a server-owned top-level full-XID +-- stamp. The later BEFORE INSERT trigger runs after the existing exact-row validator. +-- PostgreSQL xid8 has no corresponding H2 DDL-interpreter domain; native PostgreSQL tests +-- qualify this internal stamp together with the trigger and selector guard. +-- [jooq ignore start] +ALTER TABLE world_canonical_instance_preparation + ADD COLUMN preparation_inserted_full_xid xid8; + +CREATE FUNCTION world_stamp_preparation_insert_full_xid() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + NEW.preparation_inserted_full_xid := pg_current_xact_id(); + RETURN NEW; +END; +$$; +REVOKE ALL ON FUNCTION world_stamp_preparation_insert_full_xid() FROM PUBLIC; + +CREATE TRIGGER trg_world_preparation_full_xid_stamp + BEFORE INSERT ON world_canonical_instance_preparation + FOR EACH ROW EXECUTE FUNCTION world_stamp_preparation_insert_full_xid(); + +-- Fail closed if the exact manifest validator is absent, disabled, has changed shape, or could +-- run after the stamp. Also reject any additional BEFORE INSERT row trigger on this table. +DO $migration$ +DECLARE + preparation_table REGCLASS := '"${serviceSchema}".world_canonical_instance_preparation'::REGCLASS; + validator_trigger RECORD; + stamp_trigger RECORD; + before_insert_row_trigger_count BIGINT; +BEGIN + SELECT t.* INTO STRICT validator_trigger + FROM pg_catalog.pg_trigger t + WHERE t.tgrelid = preparation_table + AND t.tgname = 'trg_world_canonical_instance_preparation_exact_insert'; + IF validator_trigger.tgisinternal + OR validator_trigger.tgenabled NOT IN ('O', 'A') + OR (validator_trigger.tgtype & 7) <> 7 + OR validator_trigger.tgfoid <> + '"${serviceSchema}".world_validate_canonical_preparation_row()'::REGPROCEDURE::OID THEN + RAISE EXCEPTION 'Canonical preparation exact-row validator must remain enabled BEFORE INSERT FOR EACH ROW'; + END IF; + + SELECT t.* INTO STRICT stamp_trigger + FROM pg_catalog.pg_trigger t + WHERE t.tgrelid = preparation_table + AND t.tgname = 'trg_world_preparation_full_xid_stamp'; + IF stamp_trigger.tgisinternal + OR stamp_trigger.tgenabled NOT IN ('O', 'A') + OR (stamp_trigger.tgtype & 7) <> 7 + OR stamp_trigger.tgfoid <> + '"${serviceSchema}".world_stamp_preparation_insert_full_xid()'::REGPROCEDURE::OID THEN + RAISE EXCEPTION 'Preparation full-XID stamp must remain enabled BEFORE INSERT FOR EACH ROW'; + END IF; + + SELECT count(*) INTO before_insert_row_trigger_count + FROM pg_catalog.pg_trigger t + WHERE t.tgrelid = preparation_table + AND (t.tgtype & 7) = 7; + IF before_insert_row_trigger_count <> 2 THEN + RAISE EXCEPTION 'Unexpected BEFORE INSERT row trigger changes canonical preparation ordering'; + END IF; + + IF NOT (validator_trigger.tgname COLLATE "C" < stamp_trigger.tgname COLLATE "C") THEN + RAISE EXCEPTION 'Canonical preparation exact-row validator must run before the full-XID stamp'; + END IF; +END; +$migration$; + +-- Replace only the legacy tuple-xmin qualification. Keep the original guard function identity, +-- security attributes, grants, and all other predicates intact; NULL historical stamps fail closed. +DO $migration$ +DECLARE + original TEXT; + xmin_anchor TEXT := $anchor$ AND p.xmin::TEXT=(txid_current() % 4294967296)::TEXT$anchor$; + full_xid_predicate TEXT := $replacement$ AND p.preparation_inserted_full_xid=pg_current_xact_id()$replacement$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_guard_preparation_start_location()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,xmin_anchor,'')))/length(xmin_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one preparation start-location xmin guard'; + END IF; + EXECUTE replace(original, xmin_anchor, full_xid_predicate); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1042.12__world_graph_application_receipt_byte_digests.sql b/services/world-management-service/src/main/resources/db/migration/V1042.12__world_graph_application_receipt_byte_digests.sql new file mode 100644 index 0000000000..c8ef508170 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1042.12__world_graph_application_receipt_byte_digests.sql @@ -0,0 +1,46 @@ +-- Bind the original Account, receipt, and APPLIED digest fields to their retained bytes. +-- Preserve both live trigger-function identities, grants, security settings, and all other guards. +-- [jooq ignore start] +DO $migration$ +DECLARE + original TEXT; + receipt_anchor TEXT := $anchor$ OR NEW.graph_digest IS DISTINCT FROM ('sha256:' || graph_row.graph_sha256) + OR NOT EXISTS ($anchor$; + receipt_replacement TEXT := $replacement$ OR NEW.graph_digest IS DISTINCT FROM ('sha256:' || graph_row.graph_sha256) + OR NEW.account_binding_digest IS DISTINCT FROM + ('sha256:' || encode(sha256(NEW.account_binding_bytes), 'hex')) + OR NEW.receipt_digest IS DISTINCT FROM + ('sha256:' || encode(sha256(NEW.receipt_bytes), 'hex')) + OR NOT EXISTS ($replacement$; + application_anchor TEXT := $anchor$ OR receipt.graph_digest IS DISTINCT FROM ('sha256:' || graph_row.graph_sha256) + OR receipt.receipt_digest !~ '^sha256:[0-9a-f]{64}$' THEN$anchor$; + application_replacement TEXT := $replacement$ OR receipt.graph_digest IS DISTINCT FROM ('sha256:' || graph_row.graph_sha256) + OR NEW.account_binding_digest IS DISTINCT FROM + ('sha256:' || encode(sha256(NEW.account_binding_bytes), 'hex')) + OR NEW.result_digest IS DISTINCT FROM + ('sha256:' || encode(sha256(NEW.result_bytes), 'hex')) + OR receipt.account_binding_digest IS DISTINCT FROM + ('sha256:' || encode(sha256(receipt.account_binding_bytes), 'hex')) + OR receipt.receipt_digest IS DISTINCT FROM + ('sha256:' || encode(sha256(receipt.receipt_bytes), 'hex')) THEN$replacement$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_guard_draft_start_location_receipt()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, receipt_anchor, ''))) + / length(receipt_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one World start-location receipt digest anchor'; + END IF; + EXECUTE replace(original, receipt_anchor, receipt_replacement); + + SELECT pg_get_functiondef( + '"${serviceSchema}".world_guard_graph_application()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, application_anchor, ''))) + / length(application_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one World graph-application digest anchor'; + END IF; + EXECUTE replace(original, application_anchor, application_replacement); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1042.13__world_start_location_semantic_receipt_digest.sql b/services/world-management-service/src/main/resources/db/migration/V1042.13__world_start_location_semantic_receipt_digest.sql new file mode 100644 index 0000000000..21feef9502 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1042.13__world_start_location_semantic_receipt_digest.sql @@ -0,0 +1,145 @@ +-- Validate the original framed selector digest and its exact canonical receipt bytes. +-- Preserve both installed guard identities, grants, security settings, and all other predicates. +-- [jooq ignore start] +CREATE FUNCTION world_start_location_receipt_matches( + p_target_namespace TEXT, + p_operation_id UUID, + p_request_id UUID, + p_commit_id UUID, + p_authorization_fence_id UUID, + p_account_binding_digest TEXT, + p_binding_digest TEXT, + p_canonical_tenant_id UUID, + p_canonical_version_id UUID, + p_room_template_id UUID, + p_graph_digest TEXT, + p_receipt_digest TEXT, + p_receipt_bytes BYTEA +) RETURNS BOOLEAN +LANGUAGE plpgsql IMMUTABLE SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + segment TEXT; + segment_bytes BYTEA; + digest_input BYTEA := ''::BYTEA; + expected_receipt_digest TEXT; + expected_receipt_bytes BYTEA; +BEGIN + IF p_target_namespace IS NULL + OR p_operation_id IS NULL + OR p_request_id IS NULL + OR p_commit_id IS NULL + OR p_authorization_fence_id IS NULL + OR p_account_binding_digest IS NULL + OR p_binding_digest IS NULL + OR p_canonical_tenant_id IS NULL + OR p_canonical_version_id IS NULL + OR p_room_template_id IS NULL + OR p_graph_digest IS NULL + OR p_receipt_digest IS NULL + OR p_receipt_bytes IS NULL THEN + RETURN FALSE; + END IF; + + FOREACH segment IN ARRAY ARRAY[ + 'world-draft-start-location-receipt/v1', + p_target_namespace, + p_operation_id::TEXT, + p_request_id::TEXT, + p_commit_id::TEXT, + p_authorization_fence_id::TEXT, + p_account_binding_digest, + p_binding_digest, + p_canonical_tenant_id::TEXT, + p_canonical_version_id::TEXT, + p_room_template_id::TEXT, + p_graph_digest + ] LOOP + segment_bytes := convert_to(segment, 'UTF8'); + digest_input := digest_input || int4send(octet_length(segment_bytes)) || segment_bytes; + END LOOP; + + expected_receipt_digest := 'sha256:' || encode(sha256(digest_input), 'hex'); + expected_receipt_bytes := convert_to( + '{"accountBindingDigest":"' || p_account_binding_digest + || '","authorizationFenceId":"' || p_authorization_fence_id::TEXT + || '","bindingDigest":"' || p_binding_digest + || '","commitId":"' || p_commit_id::TEXT + || '","graphDigest":"' || p_graph_digest + || '","operationId":"' || p_operation_id::TEXT + || '","receiptDigest":"' || expected_receipt_digest + || '","requestId":"' || p_request_id::TEXT + || '","schema":"world-draft-start-location-receipt/v1","startLocation":{"roomTemplateId":"' + || p_room_template_id::TEXT + || '","tenantId":"' || p_canonical_tenant_id::TEXT + || '","versionId":"' || p_canonical_version_id::TEXT + || '"},"targetNamespace":"' || p_target_namespace || '"}', + 'UTF8'); + + RETURN p_receipt_digest IS NOT DISTINCT FROM expected_receipt_digest + AND p_receipt_bytes IS NOT DISTINCT FROM expected_receipt_bytes; +END; +$$; +REVOKE ALL ON FUNCTION world_start_location_receipt_matches( + TEXT, UUID, UUID, UUID, UUID, TEXT, TEXT, UUID, UUID, UUID, TEXT, TEXT, BYTEA) FROM PUBLIC; +DO $permissions$ +DECLARE + function_owner TEXT; +BEGIN + FOR function_owner IN + SELECT DISTINCT pg_get_userbyid(p.proowner) + FROM pg_catalog.pg_proc p + JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace + WHERE n.nspname = '${serviceSchema}' + AND p.proname IN ( + 'world_guard_draft_start_location_receipt', + 'world_guard_graph_application') + LOOP + EXECUTE format( + 'GRANT EXECUTE ON FUNCTION %I.world_start_location_receipt_matches' + || '(text,uuid,uuid,uuid,uuid,text,text,uuid,uuid,uuid,text,text,bytea) TO %I', + '${serviceSchema}', function_owner); + END LOOP; +END; +$permissions$; + +DO $migration$ +DECLARE + original TEXT; + receipt_anchor TEXT := $anchor$ OR NEW.receipt_digest IS DISTINCT FROM + ('sha256:' || encode(sha256(NEW.receipt_bytes), 'hex')) + OR NOT EXISTS ($anchor$; + receipt_replacement TEXT := $replacement$ OR NOT world_start_location_receipt_matches( + NEW.target_namespace, NEW.operation_id, NEW.request_id, NEW.commit_id, + NEW.authorization_fence_id, NEW.account_binding_digest, NEW.binding_digest, + NEW.canonical_tenant_id, NEW.canonical_version_id, NEW.room_template_id, + NEW.graph_digest, NEW.receipt_digest, NEW.receipt_bytes) + OR NOT EXISTS ($replacement$; + application_anchor TEXT := $anchor$ OR receipt.receipt_digest IS DISTINCT FROM + ('sha256:' || encode(sha256(receipt.receipt_bytes), 'hex')) THEN$anchor$; + application_replacement TEXT := $replacement$ OR NOT world_start_location_receipt_matches( + receipt.target_namespace, receipt.operation_id, receipt.request_id, receipt.commit_id, + receipt.authorization_fence_id, receipt.account_binding_digest, receipt.binding_digest, + receipt.canonical_tenant_id, receipt.canonical_version_id, receipt.room_template_id, + receipt.graph_digest, receipt.receipt_digest, receipt.receipt_bytes) THEN$replacement$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_guard_draft_start_location_receipt()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, receipt_anchor, ''))) + / length(receipt_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one World start-location receipt byte-digest predicate'; + END IF; + EXECUTE replace(original, receipt_anchor, receipt_replacement); + + SELECT pg_get_functiondef( + '"${serviceSchema}".world_guard_graph_application()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, application_anchor, ''))) + / length(application_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one World APPLIED receipt byte-digest predicate'; + END IF; + EXECUTE replace(original, application_anchor, application_replacement); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1042.1__world_execution_terminal_service_schema.sql b/services/world-management-service/src/main/resources/db/migration/V1042.1__world_execution_terminal_service_schema.sql new file mode 100644 index 0000000000..b52ee450dc --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1042.1__world_execution_terminal_service_schema.sql @@ -0,0 +1,26 @@ +-- Preserve the V1035 deferred settlement contract when a caller omits the World schema from +-- search_path. CREATE OR REPLACE keeps the original function identity and grants; this remains an +-- invoker trigger and performs no data rewrite. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION world_require_canonical_instance_execution_terminal() +RETURNS TRIGGER +LANGUAGE plpgsql +SECURITY INVOKER +SET search_path = pg_catalog +AS $$ +DECLARE + final_state TEXT; +BEGIN + SELECT operation_state INTO final_state + FROM "${serviceSchema}".world_canonical_instance_execution + WHERE target_namespace = NEW.target_namespace + AND canonical_tenant_id = NEW.canonical_tenant_id + AND control_plane_request_id = NEW.control_plane_request_id; + IF final_state IS NULL OR final_state = 'EXECUTING' THEN + RAISE EXCEPTION 'World EXECUTING state cannot commit without exact terminal settlement' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1042.2__world_fixed_preset_read_transaction.sql b/services/world-management-service/src/main/resources/db/migration/V1042.2__world_fixed_preset_read_transaction.sql new file mode 100644 index 0000000000..ae8e25bb62 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1042.2__world_fixed_preset_read_transaction.sql @@ -0,0 +1,34 @@ +-- Keep committed fixed-preset readback valid inside its writable materialization transaction and +-- in its supported independent read transactions. Preserve the V1041 function identity, grants, +-- security mode and all other body logic by replacing only the exact isolation guard. +-- [jooq ignore start] +DO $migration$ +DECLARE + read_function REGPROCEDURE := + '"${serviceSchema}".world_read_run_owned_fixed_preset(text,text,bigint,bigint)'::REGPROCEDURE; + original_definition TEXT; + isolation_guard_anchor TEXT := $anchor$ IF current_setting('transaction_read_only') <> 'on' + AND current_setting('transaction_isolation') NOT IN ('read committed','repeatable read','serializable') THEN + RAISE EXCEPTION 'Run-owned fixed-preset readback requires an owner read transaction' + USING ERRCODE = '23514'; + END IF;$anchor$; + isolation_guard_replacement TEXT := $replacement$ IF NOT ( + (current_setting('transaction_read_only') = 'on' + AND current_setting('transaction_isolation') IN ('repeatable read','serializable')) + OR (current_setting('transaction_read_only') = 'off' + AND current_setting('transaction_isolation') = 'read committed') + ) THEN + RAISE EXCEPTION 'Run-owned fixed-preset readback requires an owner read transaction' + USING ERRCODE = '23514'; + END IF;$replacement$; +BEGIN + SELECT pg_get_functiondef(read_function) INTO STRICT original_definition; + IF (length(original_definition) + - length(replace(original_definition, isolation_guard_anchor, ''))) + / length(isolation_guard_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V1041 fixed-preset read transaction guard'; + END IF; + EXECUTE replace(original_definition, isolation_guard_anchor, isolation_guard_replacement); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1042.3__world_fixture_row_mutation_diagnostic.sql b/services/world-management-service/src/main/resources/db/migration/V1042.3__world_fixture_row_mutation_diagnostic.sql new file mode 100644 index 0000000000..93bb92aaec --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1042.3__world_fixture_row_mutation_diagnostic.sql @@ -0,0 +1,29 @@ +-- V1040 already closes every World-row update for the run-owned fixture authority. Correct the +-- diagnostic to describe that full storage boundary without replacing the function or changing +-- its security, grants, identity, or predicates. The separate retained-binding lifecycle guard +-- keeps its narrower and accurate lifecycle diagnostic. +-- [jooq ignore start] +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$IF OLD.canonical_authority_kind = 'RUN_OWNED_FIXTURE' + OR NEW.canonical_authority_kind = 'RUN_OWNED_FIXTURE' THEN + RAISE EXCEPTION 'Run-owned fixture World lifecycle transitions are disabled' + USING ERRCODE = '23514'; + END IF;$anchor$; + replacement TEXT := $replacement$IF OLD.canonical_authority_kind = 'RUN_OWNED_FIXTURE' + OR NEW.canonical_authority_kind = 'RUN_OWNED_FIXTURE' THEN + RAISE EXCEPTION 'Run-owned fixture World row mutations are disabled' + USING ERRCODE = '23514'; + END IF;$replacement$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_guard_canonical_activation_transition()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,anchor,'')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one run-owned fixture World row-mutation diagnostic anchor'; + END IF; + EXECUTE replace(original, anchor, replacement); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1042.4__world_fixture_association_owner_copy_checks.sql b/services/world-management-service/src/main/resources/db/migration/V1042.4__world_fixture_association_owner_copy_checks.sql new file mode 100644 index 0000000000..3cb8293259 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1042.4__world_fixture_association_owner_copy_checks.sql @@ -0,0 +1,28 @@ +-- Keep every copied canonical and fixed-preset field bound to its retained World row for fixtures. +-- [jooq ignore start] +DO $migration$ +DECLARE + original TEXT; + copy_anchor TEXT := $anchor$ OR instance.game_design_version_id IS DISTINCT FROM NEW.game_design_version_id$anchor$; + replacement TEXT := $replacement$ OR instance.game_design_version_id IS DISTINCT FROM NEW.game_design_version_id + OR instance.canonical_realm_id IS DISTINCT FROM NEW.canonical_realm_id + OR instance.catalog_revision IS DISTINCT FROM NEW.catalog_revision + OR instance.playtest_lifecycle_id IS DISTINCT FROM NEW.playtest_lifecycle_id + OR instance.playtest_state_generation IS DISTINCT FROM NEW.playtest_state_generation + OR instance.script_patch_version IS DISTINCT FROM NEW.script_patch_version + OR instance.runtime_flags_json IS DISTINCT FROM NEW.runtime_flags_json + OR instance.generation_config_revision IS DISTINCT FROM NEW.generation_config_revision + OR instance.release_bundle_id IS DISTINCT FROM NEW.release_bundle_id + OR instance.published_release_bundle_ref IS DISTINCT FROM NEW.published_release_bundle_ref + OR instance.remap_set_id IS DISTINCT FROM NEW.remap_set_id$replacement$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_validate_canonical_instance_association()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,copy_anchor,'')))/length(copy_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one run-owned fixture association World-copy check anchor'; + END IF; + EXECUTE replace(original, copy_anchor, replacement); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1042.5__world_fixed_preset_complete_room_readback.sql b/services/world-management-service/src/main/resources/db/migration/V1042.5__world_fixed_preset_complete_room_readback.sql new file mode 100644 index 0000000000..1b854937fc --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1042.5__world_fixed_preset_complete_room_readback.sql @@ -0,0 +1,35 @@ +-- Require both authored room rows and their runtime mappings in fixed-preset readback. +-- [jooq ignore start] +DO $migration$ +DECLARE + original TEXT; + room_match_start TEXT := $anchor$OR NOT EXISTS ( + SELECT 1 + FROM "${serviceSchema}".world_authored_topology_identity m + JOIN "${serviceSchema}".room r ON r.id = m.private_row_key$anchor$; + room_match_start_replacement TEXT := $replacement$OR (SELECT count(*) + FROM "${serviceSchema}".world_authored_topology_identity m + JOIN "${serviceSchema}".room r ON r.id = m.private_row_key$replacement$; + room_match_end TEXT := $anchor$AND ri.zone_instance_id = zi.runtime_row_id)) + OR (SELECT count(*) FROM "${serviceSchema}".world_authored_topology_identity m + JOIN "${serviceSchema}".room_exit e$anchor$; + room_match_end_replacement TEXT := $replacement$AND ri.zone_instance_id = zi.runtime_row_id)) <> 2 + OR (SELECT count(*) FROM "${serviceSchema}".world_authored_topology_identity m + JOIN "${serviceSchema}".room_exit e$replacement$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_read_run_owned_fixed_preset(text,text,bigint,bigint)'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,room_match_start,'')))/length(room_match_start) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one fixed-preset any-room readback predicate start'; + END IF; + IF (length(original)-length(replace(original,room_match_end,'')))/length(room_match_end) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one fixed-preset room readback predicate end'; + END IF; + EXECUTE replace( + replace(original, room_match_start, room_match_start_replacement), + room_match_end, + room_match_end_replacement); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1042.6__world_terminal_binding_and_location_operation_checks.sql b/services/world-management-service/src/main/resources/db/migration/V1042.6__world_terminal_binding_and_location_operation_checks.sql new file mode 100644 index 0000000000..0a8a1f1e71 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1042.6__world_terminal_binding_and_location_operation_checks.sql @@ -0,0 +1,36 @@ +-- Keep terminal binding evidence complete and APPLIED placement bound to its own operation. +-- Published V1010/V1019 bytes and all other guards remain unchanged. +-- [jooq ignore start] +ALTER TABLE world_draft_terminal_outcome DROP CONSTRAINT ck_world_draft_terminal_binding; +ALTER TABLE world_draft_terminal_outcome ADD CONSTRAINT ck_world_draft_terminal_binding CHECK (( + jsonb_typeof(binding_json::jsonb) = 'object' + AND binding_json::jsonb->>'canonicalTenantId' = canonical_tenant_id::TEXT + AND binding_json::jsonb->>'canonicalVersionId' = canonical_version_id::TEXT + AND binding_json::jsonb->>'requestId' = request_id::TEXT + AND binding_json::jsonb->>'commitId' = commit_id::TEXT + AND jsonb_typeof(owner_binding_json::jsonb) = 'object' + AND owner_binding_json::jsonb->>'targetNamespace' = target_namespace + AND owner_binding_json::jsonb->>'canonicalTenantId' = canonical_tenant_id::TEXT + AND owner_binding_json::jsonb->>'canonicalVersionId' = canonical_version_id::TEXT + AND owner_binding_json::jsonb->>'versionIdentityOperationId' = version_identity_operation_id::TEXT +) IS TRUE); + +DO $migration$ +DECLARE + original TEXT; + location_anchor TEXT := $anchor$AND l.canonical_game_instance_id = NEW.canonical_game_instance_id + AND l.canonical_account_id = (convert_from(NEW.request_bytes, 'UTF8')::JSONB->>'canonicalAccountId')::UUID$anchor$; + location_replacement TEXT := $replacement$AND l.canonical_game_instance_id = NEW.canonical_game_instance_id + AND l.initial_location_operation_id = NEW.operation_id + AND l.canonical_account_id = (convert_from(NEW.request_bytes, 'UTF8')::JSONB->>'canonicalAccountId')::UUID$replacement$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_require_initial_location_operation_result()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,location_anchor,'')))/length(location_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one initial-location APPLIED operation binding anchor'; + END IF; + EXECUTE replace(original, location_anchor, location_replacement); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1042.7__world_predecessor_fixture_lifecycle_staging.sql b/services/world-management-service/src/main/resources/db/migration/V1042.7__world_predecessor_fixture_lifecycle_staging.sql new file mode 100644 index 0000000000..0525c24908 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1042.7__world_predecessor_fixture_lifecycle_staging.sql @@ -0,0 +1,138 @@ +-- Restore only PREPARING->ACTIVE, PREPARING->FAILED_PRE_ACTIVATION, ACTIVE->TERMINATING and +-- TERMINATING->TERMINATED for the existing source-first lifecycle. Canonical fixture activation +-- and all Human activation-operation requirements stay closed. The authenticated +-- predecessor owner remains responsible for receipt verification, locking, expected-epoch checks, +-- hold refusal and termination coordination; this row shape is not authority. +-- Retire this staging exception forward only after old writers are drained and cleanup is settled. +-- [jooq ignore start] +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$IF (OLD.run_owned_fixture_binding_sha256 IS NOT NULL + OR NEW.run_owned_fixture_binding_sha256 IS NOT NULL) + AND (OLD.status IS DISTINCT FROM NEW.status + OR OLD.lifecycle_epoch IS DISTINCT FROM NEW.lifecycle_epoch) THEN + RAISE EXCEPTION 'World lifecycle transitions are disabled for rows carrying fixture binding evidence' + USING ERRCODE = '23514'; + END IF;$anchor$; + replacement TEXT := $replacement$IF (OLD.run_owned_fixture_binding_sha256 IS NOT NULL + OR NEW.run_owned_fixture_binding_sha256 IS NOT NULL) + AND NOT (( + OLD.run_owned_fixture_binding_sha256 IS NOT NULL + AND NEW.run_owned_fixture_binding_sha256 IS NOT DISTINCT FROM OLD.run_owned_fixture_binding_sha256 + AND OLD.run_owned_fixture_binding_sha256 COLLATE "C" ~ '^[0-9a-f]{64}$' + AND OLD.run_owned_fixture_preparing_lifecycle_epoch = 1 + AND NEW.run_owned_fixture_preparing_lifecycle_epoch = OLD.run_owned_fixture_preparing_lifecycle_epoch + AND OLD.row_version >= 0 + AND NEW.row_version = OLD.row_version + 1 + AND ROW( + OLD.id, OLD.tenant_id, OLD.game_instance_id, OLD.game_template_id, + OLD.control_plane_request_id, OLD.launch_descriptor_id, OLD.version_id, + OLD.script_patch_version, OLD.runtime_flags_json, OLD.generation_config_revision, + OLD.release_bundle_id, OLD.published_release_bundle_ref, OLD.version_state_epoch, + OLD.remap_set_id, OLD.created_at, OLD.updated_at + ) IS NOT DISTINCT FROM ROW( + NEW.id, NEW.tenant_id, NEW.game_instance_id, NEW.game_template_id, + NEW.control_plane_request_id, NEW.launch_descriptor_id, NEW.version_id, + NEW.script_patch_version, NEW.runtime_flags_json, NEW.generation_config_revision, + NEW.release_bundle_id, NEW.published_release_bundle_ref, NEW.version_state_epoch, + NEW.remap_set_id, NEW.created_at, NEW.updated_at + ) + AND OLD.canonical_game_instance_id IS NULL + AND OLD.canonical_target_namespace IS NULL + AND OLD.canonical_tenant_id IS NULL + AND OLD.canonical_world_slug IS NULL + AND OLD.playable_state_namespace_id IS NULL + AND OLD.playable_state_scope IS NULL + AND OLD.public_production IS NULL + AND OLD.playtest_lifecycle_id IS NULL + AND OLD.playtest_state_generation IS NULL + AND OLD.canonical_launch_binding_operation_id IS NULL + AND OLD.canonical_authority_kind IS NULL + AND OLD.fixture_provenance_digest IS NULL + AND OLD.canonical_realm_id IS NULL + AND OLD.catalog_revision IS NULL + AND OLD.game_session_tenant_id IS NULL + AND OLD.game_session_game_instance_id IS NULL + AND OLD.game_design_version_id IS NULL + AND NEW.canonical_game_instance_id IS NULL + AND NEW.canonical_target_namespace IS NULL + AND NEW.canonical_tenant_id IS NULL + AND NEW.canonical_world_slug IS NULL + AND NEW.playable_state_namespace_id IS NULL + AND NEW.playable_state_scope IS NULL + AND NEW.public_production IS NULL + AND NEW.playtest_lifecycle_id IS NULL + AND NEW.playtest_state_generation IS NULL + AND NEW.canonical_launch_binding_operation_id IS NULL + AND NEW.canonical_authority_kind IS NULL + AND NEW.fixture_provenance_digest IS NULL + AND NEW.canonical_realm_id IS NULL + AND NEW.catalog_revision IS NULL + AND NEW.game_session_tenant_id IS NULL + AND NEW.game_session_game_instance_id IS NULL + AND NEW.game_design_version_id IS NULL + AND ( + ( + OLD.status = 'PREPARING' + AND OLD.lifecycle_epoch = OLD.run_owned_fixture_preparing_lifecycle_epoch + AND NEW.status = 'ACTIVE' + AND NEW.lifecycle_epoch = OLD.lifecycle_epoch + 1 + AND OLD.failure_reason IS NULL + AND NEW.failure_reason IS NULL + AND OLD.termination_request_id IS NULL + AND NEW.termination_request_id IS NULL + AND OLD.terminated_at IS NULL + AND NEW.terminated_at IS NULL + ) + OR ( + OLD.status = 'PREPARING' + AND OLD.lifecycle_epoch = OLD.run_owned_fixture_preparing_lifecycle_epoch + AND NEW.status = 'FAILED_PRE_ACTIVATION' + AND NEW.lifecycle_epoch = OLD.lifecycle_epoch + 1 + AND OLD.failure_reason IS NULL + AND OLD.termination_request_id IS NULL + AND NEW.termination_request_id IS NULL + AND OLD.terminated_at IS NULL + AND NEW.terminated_at IS NULL + ) + OR ( + OLD.status = 'ACTIVE' + AND OLD.lifecycle_epoch = OLD.run_owned_fixture_preparing_lifecycle_epoch + 1 + AND NEW.status = 'TERMINATING' + AND NEW.lifecycle_epoch = OLD.lifecycle_epoch + 1 + AND OLD.failure_reason IS NULL + AND OLD.termination_request_id IS NULL + AND NEW.termination_request_id IS NOT NULL + AND btrim(NEW.termination_request_id) <> '' + AND OLD.terminated_at IS NULL + AND NEW.terminated_at IS NULL + ) + OR ( + OLD.status = 'TERMINATING' + AND OLD.lifecycle_epoch = OLD.run_owned_fixture_preparing_lifecycle_epoch + 2 + AND NEW.status = 'TERMINATED' + AND NEW.lifecycle_epoch = OLD.lifecycle_epoch + 1 + AND OLD.failure_reason IS NOT DISTINCT FROM NEW.failure_reason + AND OLD.termination_request_id IS NOT NULL + AND btrim(OLD.termination_request_id) <> '' + AND NEW.termination_request_id IS NOT DISTINCT FROM OLD.termination_request_id + AND OLD.terminated_at IS NULL + AND NEW.terminated_at IS NOT NULL + ) + ) + ) IS TRUE) THEN + RAISE EXCEPTION 'World lifecycle transitions are disabled for rows carrying fixture binding evidence' + USING ERRCODE = '23514'; + END IF;$replacement$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_guard_canonical_activation_transition()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,anchor,'')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one current fixture-binding lifecycle guard anchor'; + END IF; + EXECUTE replace(original, anchor, replacement); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1042.8__world_terminal_affected_unit_validation.sql b/services/world-management-service/src/main/resources/db/migration/V1042.8__world_terminal_affected_unit_validation.sql new file mode 100644 index 0000000000..c559a8b8f3 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1042.8__world_terminal_affected_unit_validation.sql @@ -0,0 +1,45 @@ +-- Fail closed on malformed World terminal affected-unit evidence without rewriting retained rows. +-- V1010 remains immutable; preserve the installed trigger function identity and security settings. +-- Validate expectedEpoch through ->> so numeric JSON counters and canonical decimal strings both remain valid. +-- [jooq ignore start] +DO $migration$ +DECLARE + original TEXT; + affected_unit_anchor TEXT := $anchor$ FOR unit IN SELECT value FROM jsonb_array_elements(NEW.affected_units_json) LOOP + IF unit->>'owner' <> 'WORLD_MANAGEMENT' THEN + RAISE EXCEPTION 'World terminal affected-unit vector contains a foreign owner' + USING ERRCODE = '23514'; + END IF; + expected_epoch := (unit->>'expectedEpoch')::BIGINT;$anchor$; + affected_unit_replacement TEXT := $replacement$ FOR unit IN SELECT value FROM jsonb_array_elements(NEW.affected_units_json) LOOP + IF unit->>'owner' IS DISTINCT FROM 'WORLD_MANAGEMENT' THEN + RAISE EXCEPTION 'World terminal affected-unit vector contains a foreign owner' + USING ERRCODE = '23514'; + END IF; + IF unit->>'scopeType' IS NULL + OR unit->>'scopeType' NOT IN ( + 'AGGREGATE', 'REGION_SUBTREE', 'ZONE_SUBTREE', 'NEW_EMPTY_REGION' + ) THEN + RAISE EXCEPTION 'World terminal affected-unit vector contains an unknown scope type' + USING ERRCODE = '23514'; + END IF; + IF unit->>'expectedEpoch' IS NULL + OR unit->>'expectedEpoch' !~ '^(0|[1-9][0-9]*)$' + OR length(unit->>'expectedEpoch') > 19 + OR (length(unit->>'expectedEpoch') = 19 + AND (unit->>'expectedEpoch') COLLATE "C" > '9223372036854775807' COLLATE "C") THEN + RAISE EXCEPTION 'World terminal affected-unit epoch must be a canonical nonnegative BIGINT' + USING ERRCODE = '23514'; + END IF; + expected_epoch := (unit->>'expectedEpoch')::BIGINT;$replacement$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_draft_terminal_outcome_guard()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,affected_unit_anchor,'')))/length(affected_unit_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one World terminal affected-unit validation anchor'; + END IF; + EXECUTE replace(original, affected_unit_anchor, affected_unit_replacement); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1042.9__world_same_transaction_guard_subtransactions.sql b/services/world-management-service/src/main/resources/db/migration/V1042.9__world_same_transaction_guard_subtransactions.sql new file mode 100644 index 0000000000..5475e2e554 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1042.9__world_same_transaction_guard_subtransactions.sql @@ -0,0 +1,70 @@ +-- Treat a child transaction's tuple xmin as belonging to its top-level transaction when +-- qualifying publication and fixture rows. Keep the full-XID anti-late-attachment check, but +-- make its stamp server-owned so callers cannot supply a forged value. +-- [jooq ignore start] +ALTER TABLE world_design_publication_fence_attempt + ADD COLUMN attempt_inserted_full_xid xid8; + +CREATE FUNCTION world_stamp_publication_attempt_full_xid() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + server_full_xid xid8 := pg_current_xact_id(); +BEGIN + NEW.attempt_created_full_xid := server_full_xid; + NEW.attempt_inserted_full_xid := server_full_xid; + RETURN NEW; +END; +$$; +REVOKE ALL ON FUNCTION world_stamp_publication_attempt_full_xid() FROM PUBLIC; + +CREATE TRIGGER trg_world_publication_attempt_full_xid_stamp + BEFORE INSERT ON world_design_publication_fence_attempt + FOR EACH ROW EXECUTE FUNCTION world_stamp_publication_attempt_full_xid(); + +DO $migration$ +DECLARE + original TEXT; + xmin_anchor TEXT := $anchor$ + AND a.xmin::TEXT = (txid_current() % 4294967296)::TEXT$anchor$; + inserted_xid_predicate TEXT := $replacement$ + AND a.attempt_inserted_full_xid = pg_current_xact_id()$replacement$; + created_xid_anchor TEXT := $anchor$ AND a.attempt_created_full_xid = pg_current_xact_id()$anchor$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_validate_selected_publication_account_binding()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,xmin_anchor,'')))/length(xmin_anchor) <> 1 + OR (length(original)-length(replace(original,created_xid_anchor,'')))/length(created_xid_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one selected-publication Account xmin guard'; + END IF; + EXECUTE replace(original, xmin_anchor, inserted_xid_predicate); + + SELECT pg_get_functiondef( + '"${serviceSchema}".world_validate_selected_publication_artifact_inventory()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,xmin_anchor,'')))/length(xmin_anchor) <> 1 + OR (length(original)-length(replace(original,created_xid_anchor,'')))/length(created_xid_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one selected-publication inventory xmin guard'; + END IF; + EXECUTE replace(original, xmin_anchor, inserted_xid_predicate); +END; +$migration$; + +DO $migration$ +DECLARE + original TEXT; + xmin_anchor TEXT := $anchor$ + AND retained.xmin::TEXT = (txid_current() % 4294967296)::TEXT$anchor$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_retain_preparation_start_location()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,xmin_anchor,'')))/length(xmin_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one fixture preparation retainer xmin guard'; + END IF; + EXECUTE replace(original, xmin_anchor, ''); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V1042__world_canonical_association_required_field_checks.sql b/services/world-management-service/src/main/resources/db/migration/V1042__world_canonical_association_required_field_checks.sql new file mode 100644 index 0000000000..6c9364202d --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1042__world_canonical_association_required_field_checks.sql @@ -0,0 +1,65 @@ +-- Close CHECK UNKNOWN holes without changing the retained schema-1 Human row shape. +-- Schema 1 keeps NULL realm/catalog values; Human schemas 1/2 require their binding and release +-- digest, while schemas 2/3 require a present positive catalog revision. Fixture schema 3 keeps +-- its existing no-Human-binding/no-release-digest shape. +ALTER TABLE world_canonical_instance_association + DROP CONSTRAINT ck_world_canonical_instance_association_schema; + +ALTER TABLE world_canonical_instance_association + ADD CONSTRAINT ck_world_canonical_instance_association_schema CHECK ( + (schema_version = 1 + AND (canonical_authority_kind IS NULL OR canonical_authority_kind = 'HUMAN') + AND canonical_launch_binding_operation_id IS NOT NULL + AND canonical_realm_id IS NULL + AND catalog_revision IS NULL) + OR + (schema_version = 2 + AND (canonical_authority_kind IS NULL OR canonical_authority_kind = 'HUMAN') + AND canonical_launch_binding_operation_id IS NOT NULL + AND canonical_realm_id IS NOT NULL + AND canonical_realm_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND catalog_revision IS NOT NULL + AND catalog_revision > 0) + OR + (schema_version = 3 + AND canonical_authority_kind IS NOT NULL + AND canonical_authority_kind = 'RUN_OWNED_FIXTURE' + AND canonical_realm_id IS NOT NULL + AND canonical_realm_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND catalog_revision IS NOT NULL + AND catalog_revision > 0 + AND canonical_launch_binding_operation_id IS NULL + AND release_attestation_digest IS NULL + AND fixture_provenance_digest IS NOT NULL + AND fixture_provenance_digest COLLATE "C" ~ '^sha256:[0-9a-f]{64}$' + AND game_session_tenant_id IS NOT NULL + AND game_session_tenant_id > 0 + AND game_session_game_instance_id IS NOT NULL + AND game_session_game_instance_id > 0 + AND game_design_version_id IS NOT NULL + AND game_design_version_id > 0 + AND preparation_input_digest IS NOT NULL + AND preparation_input_digest COLLATE "C" ~ '^sha256:[0-9a-f]{64}$' + AND preparing_lifecycle_epoch IS NOT NULL + AND preparing_lifecycle_epoch > 0 + AND game_session_association_response_bytes IS NOT NULL + AND octet_length(game_session_association_response_bytes) > 0) + ); + +ALTER TABLE world_canonical_instance_association + DROP CONSTRAINT ck_world_canonical_instance_association_digests; + +ALTER TABLE world_canonical_instance_association + ADD CONSTRAINT ck_world_canonical_instance_association_digests CHECK ( + source_evidence_digest COLLATE "C" ~ '^sha256:[0-9a-f]{64}$' + AND intake_request_digest COLLATE "C" ~ '^sha256:[0-9a-f]{64}$' + AND intake_receipt_digest COLLATE "C" ~ '^sha256:[0-9a-f]{64}$' + AND descriptor_request_digest COLLATE "C" ~ '^sha256:[0-9a-f]{64}$' + AND descriptor_result_digest COLLATE "C" ~ '^sha256:[0-9a-f]{64}$' + AND ( + (schema_version IN (1, 2) + AND release_attestation_digest IS NOT NULL + AND release_attestation_digest COLLATE "C" ~ '^sha256:[0-9a-f]{64}$') + OR (schema_version = 3 AND release_attestation_digest IS NULL) + ) + ); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java index 42762880a4..b778c3d673 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -60,6 +61,7 @@ import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.entitymanagement.v1.CleanupRuntimeInstanceResponse; import net.firedevops.firemud.gamedesign.v1.ArtifactState; import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; @@ -84,7 +86,9 @@ import net.firedevops.firemud.worldmanagement.repository.ZoneInstanceRepository; import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; import net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceRequest; +import net.firedevops.firemud.worldmanagement.v1.FailPreparedWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceRequest; +import net.firedevops.firemud.worldmanagement.v1.TerminateWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus; import net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc; import org.junit.jupiter.api.AfterEach; @@ -111,6 +115,15 @@ class RunOwnedWorldLaunchEvidenceMtlsIntegrationTest { private static final String STORE_PASSWORD = "test-only-world-mtls-password"; private static final String TEST_JWT_SECRET = "testsecretkeytestsecretkeytest1234"; private static final JwtUtil WORLD_JWT_UTIL = new JwtUtil(TEST_JWT_SECRET, 3_600_000L); + private static final RuntimeIdentity GAME_SESSION_RUNTIME_IDENTITY = + new RuntimeIdentity( + "game-session-service", + "world-mtls-fixture-test-gs", + "localhost", + Instant.parse("2026-10-11T00:00:00Z"), + "test", + "test", + "local"); private static final RuntimeIdentity WORLD_RUNTIME_IDENTITY = new RuntimeIdentity( "world-management-service", @@ -195,14 +208,15 @@ public > T customize(T stub) { RunOwnedWorldLaunchEvidenceProvider evidenceProvider = fixture.provider(gameDesignClient); AtomicReference storedWorld = new AtomicReference<>(); AtomicInteger worldSaves = new AtomicInteger(); + AtomicInteger entityCleanupCalls = new AtomicInteger(); WorldInstanceRepository worldRepository = mockWorldRepository(storedWorld, worldSaves); WorldLifecycleCommandServiceImpl commandService = - newCommandService(worldRepository, evidenceProvider, gameDesignClient); + newCommandService( + worldRepository, evidenceProvider, gameDesignClient, entityCleanupCalls); WorldInstanceActivationServiceImpl activationService = new WorldInstanceActivationServiceImpl( commandService, java.util.Optional.empty(), evidenceProvider, worldRepository); AtomicReference gameSessionAtWorld = new AtomicReference<>(); - AtomicBoolean injectPlayerContext = new AtomicBoolean(); WorldManagementGrpcService grpcService = new WorldManagementGrpcService( null, @@ -233,42 +247,82 @@ public void activatePreparedWorldInstance( .ActivatePreparedWorldInstanceResponse> responseObserver) { gameSessionAtWorld.set(GrpcPeerIdentity.current()); - if (injectPlayerContext.get()) { - SessionContext.setContext("42", List.of("tenantAdmin"), java.util.Map.of()); - } - try { - super.activatePreparedWorldInstance(request, responseObserver); - } finally { - SessionContext.clear(); - } + super.activatePreparedWorldInstance(request, responseObserver); + } + + @Override + public void failPreparedWorldInstance( + FailPreparedWorldInstanceRequest request, + StreamObserver< + net.firedevops.firemud.worldmanagement.v1.FailPreparedWorldInstanceResponse> + responseObserver) { + gameSessionAtWorld.set(GrpcPeerIdentity.current()); + super.failPreparedWorldInstance(request, responseObserver); + } + + @Override + public void terminateWorldInstance( + TerminateWorldInstanceRequest request, + StreamObserver< + net.firedevops.firemud.worldmanagement.v1.TerminateWorldInstanceResponse> + responseObserver) { + gameSessionAtWorld.set(GrpcPeerIdentity.current()); + super.terminateWorldInstance(request, responseObserver); } }; worldServer = startWorldServer(grpcService); gameSessionChannel = channel("localhost", worldServer.getPort(), pki.gameSessionClient()); WorldManagementServiceGrpc.WorldManagementServiceBlockingStub gameSession = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel); - - var prepare = - gameSession.prepareWorldInstance( - PrepareWorldInstanceRequest.newBuilder() - .setTenantId("42") - .setGameInstanceId("101") - .setGameTemplateId("17") - .setControlPlaneRequestId(fixture.operationId()) - .setLaunchDescriptorId("launch-descriptor-fixture-11") - .setVersionId("11") - .setRuntimeFlagsJson("{}") - .setGenerationConfigRevision("genrev-11") - .setReleaseBundleId("77") - .setPublishedReleaseBundleRef(RELEASE_REF) - .setVersionStateEpoch(77L) - .build()); + authenticatedGameSessionStub(); + + PrepareWorldInstanceRequest prepareRequest = + PrepareWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setGameTemplateId("17") + .setControlPlaneRequestId(fixture.operationId()) + .setLaunchDescriptorId("launch-descriptor-fixture-11") + .setVersionId("11") + .setRuntimeFlagsJson("{}") + .setGenerationConfigRevision("genrev-11") + .setReleaseBundleId("77") + .setPublishedReleaseBundleRef(RELEASE_REF) + .setVersionStateEpoch(77L) + .build(); + var missingJwtStub = WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel); + assertThatThrownBy(() -> missingJwtStub.prepareWorldInstance(prepareRequest)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(worldSaves).hasValue(0); + assertThat(descriptorReads).hasValue(0); + assertThat(entityCleanupCalls).hasValue(0); + + var prepare = gameSession.prepareWorldInstance(prepareRequest); assertThat(prepare.hasError()).isFalse(); assertThat(prepare.getWorldInstance().getStatus()) .isEqualTo(WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING); assertThat(storedWorld.get().getRunOwnedFixtureBindingSha256()).matches("[0-9a-f]{64}"); assertThat(storedWorld.get().getRunOwnedFixturePreparingLifecycleEpoch()).isEqualTo(1L); int writesAfterPrepare = worldSaves.get(); + int readsAfterPrepare = descriptorReads.get(); + SessionContext.setContext("42", List.of("tenantAdmin"), java.util.Map.of()); + var playerContextFailure = + authenticatedPlayerGameSessionStub() + .failPreparedWorldInstance( + FailPreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .setReason("denied player context") + .build()); + SessionContext.clear(); + assertThat(playerContextFailure.hasError()).isTrue(); + assertThat(playerContextFailure.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(worldSaves).hasValue(writesAfterPrepare); + assertThat(descriptorReads).hasValue(readsAfterPrepare); + var wrongReference = gameSession.prepareWorldInstance( PrepareWorldInstanceRequest.newBuilder() @@ -338,16 +392,18 @@ public void activatePreparedWorldInstance( .extracting(GrpcPeerIdentity::uri) .isEqualTo(GS_URI); - injectPlayerContext.set(true); + SessionContext.setContext("42", List.of("tenantAdmin"), java.util.Map.of()); var ordinaryCaller = - gameSession.activatePreparedWorldInstance( - ActivatePreparedWorldInstanceRequest.newBuilder() - .setTenantId("42") - .setGameInstanceId("101") - .setExpectedLifecycleEpoch(1L) - .build()); - injectPlayerContext.set(false); + authenticatedPlayerGameSessionStub() + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + SessionContext.clear(); assertThat(ordinaryCaller.hasError()).isTrue(); + assertThat(ordinaryCaller.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); assertThat(worldSaves).hasValue(writesAfterActivation); assertThat(descriptorReads).hasValue(4); @@ -356,7 +412,7 @@ public void activatePreparedWorldInstance( gameSessionChannel = channelWithoutClientIdentity("localhost", worldServer.getPort()); assertThatThrownBy( () -> - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + authenticatedGameSessionStub() .activatePreparedWorldInstance( ActivatePreparedWorldInstanceRequest.newBuilder() .setTenantId("42") @@ -372,7 +428,7 @@ public void activatePreparedWorldInstance( gameSessionChannel = channel("localhost", worldServer.getPort(), pki.wrongNamespaceGameSessionClient()); var wrongPeer = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + authenticatedGameSessionStub() .activatePreparedWorldInstance( ActivatePreparedWorldInstanceRequest.newBuilder() .setTenantId("42") @@ -388,7 +444,7 @@ public void activatePreparedWorldInstance( gameSessionChannel = channel("localhost", worldServer.getPort(), pki.wrongGameSessionLeafClient()); var wrongLeaf = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + authenticatedGameSessionStub() .activatePreparedWorldInstance( ActivatePreparedWorldInstanceRequest.newBuilder() .setTenantId("42") @@ -405,7 +461,7 @@ public void activatePreparedWorldInstance( channel("localhost", worldServer.getPort(), pki.wrongCaGameSessionClient()); assertThatThrownBy( () -> - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + authenticatedGameSessionStub() .activatePreparedWorldInstance( ActivatePreparedWorldInstanceRequest.newBuilder() .setTenantId("42") @@ -422,7 +478,7 @@ public void activatePreparedWorldInstance( fixture.reset(); Fixture.writeFieldMismatch(fixture, "caCertificateSha256", "f".repeat(64)); var wrongCa = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + authenticatedGameSessionStub() .activatePreparedWorldInstance( ActivatePreparedWorldInstanceRequest.newBuilder() .setTenantId("42") @@ -436,7 +492,7 @@ public void activatePreparedWorldInstance( fixture.reset(); Fixture.writeFieldMismatch(fixture, "worldManagementLeafSha256", "e".repeat(64)); var wrongWorldRecipient = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + authenticatedGameSessionStub() .activatePreparedWorldInstance( ActivatePreparedWorldInstanceRequest.newBuilder() .setTenantId("42") @@ -451,7 +507,7 @@ public void activatePreparedWorldInstance( Fixture.writeFieldMismatch( fixture, "worldManagementUriSan", "spiffe://firemud/ns/dev/sa/other-world-service"); var wrongWorldUri = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + authenticatedGameSessionStub() .activatePreparedWorldInstance( ActivatePreparedWorldInstanceRequest.newBuilder() .setTenantId("42") @@ -464,7 +520,7 @@ public void activatePreparedWorldInstance( fixture.reset(); var unknownInstance = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + authenticatedGameSessionStub() .activatePreparedWorldInstance( ActivatePreparedWorldInstanceRequest.newBuilder() .setTenantId("42") @@ -476,7 +532,7 @@ public void activatePreparedWorldInstance( assertThat(descriptorReads).hasValue(4); var duplicateOperation = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + authenticatedGameSessionStub() .prepareWorldInstance( PrepareWorldInstanceRequest.newBuilder() .setTenantId("42") @@ -496,7 +552,7 @@ public void activatePreparedWorldInstance( assertThat(descriptorReads).hasValue(5); var staleAttempt = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + authenticatedGameSessionStub() .activatePreparedWorldInstance( ActivatePreparedWorldInstanceRequest.newBuilder() .setTenantId("42") @@ -510,7 +566,7 @@ public void activatePreparedWorldInstance( fixture.reset(); Fixture.writeReceiptFieldMismatch(fixture, "sourceGameTenantKey", "43"); var changedSource = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + authenticatedGameSessionStub() .activatePreparedWorldInstance( ActivatePreparedWorldInstanceRequest.newBuilder() .setTenantId("42") @@ -524,7 +580,7 @@ public void activatePreparedWorldInstance( fixture.reset(); Fixture.writeFieldMismatch(fixture, "runId", "changed-run"); var changedRun = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + authenticatedGameSessionStub() .activatePreparedWorldInstance( ActivatePreparedWorldInstanceRequest.newBuilder() .setTenantId("42") @@ -538,7 +594,7 @@ public void activatePreparedWorldInstance( fixture.reset(); Fixture.writeFieldMismatch(fixture, "composeProjectName", "different-project"); var changedProject = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + authenticatedGameSessionStub() .activatePreparedWorldInstance( ActivatePreparedWorldInstanceRequest.newBuilder() .setTenantId("42") @@ -553,7 +609,7 @@ public void activatePreparedWorldInstance( Fixture.writeReceiptFieldMismatch( fixture, "fixtureOperationId", "11111111-1111-4111-8111-111111111111"); var changedReceipt = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + authenticatedGameSessionStub() .activatePreparedWorldInstance( ActivatePreparedWorldInstanceRequest.newBuilder() .setTenantId("42") @@ -567,7 +623,7 @@ public void activatePreparedWorldInstance( fixture.reset(); Fixture.writeReceiptFieldMismatch(fixture, "launchDescriptorBase64", "AAAA"); var changedReceiptDescriptor = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + authenticatedGameSessionStub() .activatePreparedWorldInstance( ActivatePreparedWorldInstanceRequest.newBuilder() .setTenantId("42") @@ -581,7 +637,7 @@ public void activatePreparedWorldInstance( fixture.reset(); returnChangedDescriptor.set(true); var changedOwnerDescriptor = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + authenticatedGameSessionStub() .activatePreparedWorldInstance( ActivatePreparedWorldInstanceRequest.newBuilder() .setTenantId("42") @@ -592,6 +648,85 @@ public void activatePreparedWorldInstance( assertThat(changedOwnerDescriptor.hasError()).isTrue(); assertThat(worldSaves).hasValue(writesAfterActivation); assertThat(descriptorReads).hasValue(7); + + fixture.reset(); + TerminateWorldInstanceRequest terminationRequest = + TerminateWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(2L) + .setTerminationRequestId("term-mtls-fixture-11") + .setReason("stop") + .build(); + int writesBeforeTermination = worldSaves.get(); + int readsBeforeDeniedTermination = descriptorReads.get(); + + SessionContext.setContext("42", List.of("tenantAdmin"), java.util.Map.of()); + var playerContextTermination = + authenticatedPlayerGameSessionStub().terminateWorldInstance(terminationRequest); + SessionContext.clear(); + assertThat(playerContextTermination.hasError()).isTrue(); + assertThat(playerContextTermination.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(worldSaves).hasValue(writesBeforeTermination); + assertThat(entityCleanupCalls).hasValue(0); + assertThat(descriptorReads).hasValue(readsBeforeDeniedTermination); + + gameSessionChannel.shutdownNow(); + assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + gameSessionChannel = + channel("localhost", worldServer.getPort(), pki.wrongNamespaceGameSessionClient()); + var wrongPeerTermination = + authenticatedGameSessionStub().terminateWorldInstance(terminationRequest); + assertThat(wrongPeerTermination.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesBeforeTermination); + assertThat(entityCleanupCalls).hasValue(0); + assertThat(descriptorReads).hasValue(readsBeforeDeniedTermination); + + gameSessionChannel.shutdownNow(); + assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + gameSessionChannel = + channel("localhost", worldServer.getPort(), pki.wrongGameSessionLeafClient()); + var wrongLeafTermination = + authenticatedGameSessionStub().terminateWorldInstance(terminationRequest); + assertThat(wrongLeafTermination.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesBeforeTermination); + assertThat(entityCleanupCalls).hasValue(0); + assertThat(descriptorReads).hasValue(readsBeforeDeniedTermination); + + gameSessionChannel.shutdownNow(); + assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + gameSessionChannel = channelWithoutClientIdentity("localhost", worldServer.getPort()); + assertThatThrownBy( + () -> authenticatedGameSessionStub().terminateWorldInstance(terminationRequest)) + .isInstanceOf(StatusRuntimeException.class); + assertThat(worldSaves).hasValue(writesBeforeTermination); + assertThat(entityCleanupCalls).hasValue(0); + + gameSessionChannel.shutdownNow(); + assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + gameSessionChannel = channel("localhost", worldServer.getPort(), pki.gameSessionClient()); + var terminated = authenticatedGameSessionStub().terminateWorldInstance(terminationRequest); + assertThat(terminated.hasError()).isFalse(); + assertThat(terminated.getWorldInstance().getStatus()) + .isEqualTo(WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_TERMINATED); + assertThat(terminated.getWorldInstance().getLifecycleEpoch()).isEqualTo(4L); + assertThat(worldSaves).hasValue(writesBeforeTermination + 2); + assertThat(entityCleanupCalls).hasValue(1); + + var terminalReplay = + authenticatedGameSessionStub().terminateWorldInstance(terminationRequest); + assertThat(terminalReplay.hasError()).isFalse(); + assertThat(terminalReplay.getWorldInstance()).isEqualTo(terminated.getWorldInstance()); + assertThat(worldSaves).hasValue(writesBeforeTermination + 2); + assertThat(entityCleanupCalls).hasValue(1); + + var changedTerminalRequest = + authenticatedGameSessionStub() + .terminateWorldInstance( + terminationRequest.toBuilder().setTerminationRequestId("term-other").build()); + assertThat(changedTerminalRequest.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesBeforeTermination + 2); + assertThat(entityCleanupCalls).hasValue(1); } finally { if (previousReload == null) { System.clearProperty("firemud.grpc.tls-reload.enabled"); @@ -729,11 +864,32 @@ private Server startWorldServer(WorldManagementGrpcService service) throws Excep .trustManager(pki.caCertificateValue()) .clientAuth(ClientAuth.REQUIRE) .build()) - .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .addService( + ServerInterceptors.intercept( + service, + new GrpcPeerIdentityInterceptor(), + new AuthTokenInterceptor( + WORLD_JWT_UTIL, Set.of("world_management.v1.WorldManagementService/Ping")))) .build() .start(); } + private WorldManagementServiceGrpc.WorldManagementServiceBlockingStub + authenticatedGameSessionStub() { + return GrpcClientAuth.attachInternal( + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel), + WORLD_JWT_UTIL, + GAME_SESSION_RUNTIME_IDENTITY); + } + + private WorldManagementServiceGrpc.WorldManagementServiceBlockingStub + authenticatedPlayerGameSessionStub() { + return GrpcClientAuth.attach( + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel), + WORLD_JWT_UTIL, + GAME_SESSION_RUNTIME_IDENTITY); + } + private ManagedChannel channel(String host, int port, TestIdentity identity) throws Exception { return NettyChannelBuilder.forAddress(host, port) .overrideAuthority("localhost") @@ -827,7 +983,8 @@ private WorldInstanceRepository mockWorldRepository( private WorldLifecycleCommandServiceImpl newCommandService( WorldInstanceRepository worldRepository, RunOwnedWorldLaunchEvidenceProvider evidenceProvider, - GameDesignClient client) { + GameDesignClient client, + AtomicInteger entityCleanupCalls) { RegionInstanceRepository regionRepository = mock(RegionInstanceRepository.class); ZoneRepository zoneRepository = mock(ZoneRepository.class); ZoneInstanceRepository zoneInstanceRepository = mock(ZoneInstanceRepository.class); @@ -846,6 +1003,13 @@ private WorldLifecycleCommandServiceImpl newCommandService( when(roomInstanceRepository.save(any())).thenAnswer(invocation -> invocation.getArgument(0)); when(roomInstanceExitRepository.save(any())) .thenAnswer(invocation -> invocation.getArgument(0)); + EntityManagementClient entityManagementClient = mock(EntityManagementClient.class); + when(entityManagementClient.cleanupRuntimeInstance(anyLong(), anyLong(), anyString())) + .thenAnswer( + invocation -> { + entityCleanupCalls.incrementAndGet(); + return CleanupRuntimeInstanceResponse.newBuilder().build(); + }); WorldProperties properties = new WorldProperties(); properties.setLocalShardId(7); WorldLifecycleCommandServiceImpl commandService = @@ -861,7 +1025,7 @@ private WorldLifecycleCommandServiceImpl newCommandService( mock(WorldEventRepository.class), properties, client, - mock(EntityManagementClient.class), + entityManagementClient, new SimpleMeterRegistry(), new PlatformTransactionManager() { @Override diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java index bbc0dd999e..0abe780565 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -17,6 +18,16 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.entitymanagement.v1.CleanupRuntimeInstanceResponse; +import net.firedevops.firemud.gamedesign.v1.ArtifactState; +import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; +import net.firedevops.firemud.gamedesign.v1.GetVersionAssetArtifactStateResponse; +import net.firedevops.firemud.gamedesign.v1.GetVersionStateResponse; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; @@ -211,10 +222,59 @@ void prepareActivationReplayRestartChangedReceiptAndDuplicateOperationUseDurable gameInstanceId)) .isInstanceOf(RuntimeException.class); - WorldInstance staleCopy = + WorldInstance fixtureBeforeMetadataMutation = repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); - WorldInstance winningCopy = + WorldInstance rejectedFixtureMutation = + repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); + rejectedFixtureMutation.setFailureReason("fixture metadata mutation"); + assertThatThrownBy(() -> repository.save(rejectedFixtureMutation)) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("World lifecycle transitions are disabled"); + WorldInstance fixtureAfterMetadataMutation = repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); + assertThat(fixtureAfterMetadataMutation.getStatus()).isEqualTo("ACTIVE"); + assertThat(fixtureAfterMetadataMutation.getFailureReason()).isNull(); + assertThat(fixtureAfterMetadataMutation.getLifecycleEpoch()) + .isEqualTo(fixtureBeforeMetadataMutation.getLifecycleEpoch()); + assertThat(fixtureAfterMetadataMutation.getRowVersion()) + .isEqualTo(fixtureBeforeMetadataMutation.getRowVersion()); + assertThat(fixtureAfterMetadataMutation.getRunOwnedFixtureBindingSha256()).isEqualTo(binding); + + long ordinaryTenantId = 8_810_007L; + long ordinaryGameInstanceId = uniqueId(); + when(fixtureProvider.isEnabled()).thenReturn(false); + configureOrdinaryLaunchInputs(ordinaryTenantId); + var ordinaryPrepared = + lifecycleService.prepareWorldInstance( + request(ordinaryTenantId, ordinaryGameInstanceId, operationId())); + assertThat(ordinaryPrepared.status()).isEqualTo("PREPARING"); + WorldInstance ordinaryWorld = + repository + .findByTenantIdAndGameInstanceId(ordinaryTenantId, ordinaryGameInstanceId) + .orElseThrow(); + assertThat(ordinaryWorld.getRunOwnedFixtureBindingSha256()).isNull(); + assertThat(ordinaryWorld.getRunOwnedFixturePreparingLifecycleEpoch()).isNull(); + var ordinaryCanonicalFields = + dsl.fetchOne( + "SELECT canonical_game_instance_id, canonical_target_namespace, canonical_tenant_id, " + + "canonical_world_slug, playable_state_namespace_id, playable_state_scope, " + + "public_production, playtest_lifecycle_id, playtest_state_generation, " + + "canonical_launch_binding_operation_id, canonical_authority_kind, " + + "fixture_provenance_digest, canonical_realm_id, catalog_revision, " + + "game_session_tenant_id, game_session_game_instance_id, game_design_version_id " + + "FROM world_instance WHERE tenant_id = ? AND game_instance_id = ?", + ordinaryTenantId, + ordinaryGameInstanceId); + assertThat(ordinaryCanonicalFields.intoMap().values()).containsOnlyNulls(); + + WorldInstance staleCopy = + repository + .findByTenantIdAndGameInstanceId(ordinaryTenantId, ordinaryGameInstanceId) + .orElseThrow(); + WorldInstance winningCopy = + repository + .findByTenantIdAndGameInstanceId(ordinaryTenantId, ordinaryGameInstanceId) + .orElseThrow(); winningCopy.setFailureReason("CAS winner"); WorldInstance savedWinningCopy = repository.save(winningCopy); staleCopy.setFailureReason("stale loser"); @@ -222,7 +282,9 @@ void prepareActivationReplayRestartChangedReceiptAndDuplicateOperationUseDurable .isInstanceOf(IllegalStateException.class) .hasMessage("Failed to update world_instance id=" + staleCopy.getId()); WorldInstance durableWinner = - repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); + repository + .findByTenantIdAndGameInstanceId(ordinaryTenantId, ordinaryGameInstanceId) + .orElseThrow(); assertThat(durableWinner.getFailureReason()).isEqualTo("CAS winner"); assertThat(durableWinner.getRowVersion()).isEqualTo(savedWinningCopy.getRowVersion()); @@ -248,6 +310,7 @@ void prepareActivationReplayRestartChangedReceiptAndDuplicateOperationUseDurable assertThatThrownBy(() -> repository.save(duplicate)).isInstanceOf(RuntimeException.class); } finally { dsl.execute("DELETE FROM world_instance WHERE tenant_id = ?", tenantId); + dsl.execute("DELETE FROM world_instance WHERE tenant_id = ?", 8_810_007L); } } @@ -288,6 +351,195 @@ void operationAdvisoryLockSerializesConcurrentRetriesOnPostgres() throws Excepti } } + @Test + void fixtureFailureRequiresExactOwnerAndPersistsTheLockedPredecessorTransition() { + long tenantId = 8_810_004L; + long gameInstanceId = uniqueId(); + PreparedWorldInstanceRequest request = request(tenantId, gameInstanceId, operationId()); + String binding = "c".repeat(64); + configureEvidence(binding); + try { + var prepared = lifecycleService.prepareWorldInstance(request); + assertThat(prepared.status()).isEqualTo("PREPARING"); + WorldInstance beforeFailure = + repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); + assertThat(beforeFailure.getLifecycleEpoch()).isEqualTo(1L); + assertThat(beforeFailure.getRowVersion()).isZero(); + + when(fixtureEvidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn("d".repeat(64)); + assertThatThrownBy( + () -> + lifecycleService.failPreparedWorldInstance( + tenantId, gameInstanceId, 1L, "failed")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageStartingWith("RUN_OWNED_WORLD_LAUNCH_EVIDENCE_MISMATCH:"); + WorldInstance unchanged = + repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); + assertThat(unchanged.getStatus()).isEqualTo("PREPARING"); + assertThat(unchanged.getLifecycleEpoch()).isEqualTo(1L); + assertThat(unchanged.getRowVersion()).isZero(); + + when(fixtureEvidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn(binding); + var failed = + lifecycleService.failPreparedWorldInstance(tenantId, gameInstanceId, 1L, "failed"); + WorldInstance durable = + repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); + assertThat(failed.status()).isEqualTo("FAILED_PRE_ACTIVATION"); + assertThat(failed.lifecycleEpoch()).isEqualTo(2L); + assertThat(durable.getStatus()).isEqualTo("FAILED_PRE_ACTIVATION"); + assertThat(durable.getLifecycleEpoch()).isEqualTo(2L); + assertThat(durable.getRowVersion()).isEqualTo(1L); + assertThat(durable.getRunOwnedFixtureBindingSha256()).isEqualTo(binding); + assertThat(durable.getRunOwnedFixturePreparingLifecycleEpoch()).isEqualTo(1L); + } finally { + dsl.execute("DELETE FROM world_instance WHERE tenant_id = ?", tenantId); + } + } + + @Test + void fixtureTerminationHonorsPhysicalHoldAndRetainsEntityCleanupFailureForExactReplay() { + long tenantId = 8_810_005L; + long gameInstanceId = uniqueId(); + PreparedWorldInstanceRequest request = request(tenantId, gameInstanceId, operationId()); + String binding = "e".repeat(64); + UUID holdId = UUID.randomUUID(); + configureEvidence(binding); + AtomicBoolean failEntityCleanup = new AtomicBoolean(true); + when(entityManagementClient.cleanupRuntimeInstance(anyLong(), anyLong(), anyString())) + .thenAnswer( + invocation -> { + if (failEntityCleanup.getAndSet(false)) { + throw new IllegalStateException("Entity cleanup unavailable"); + } + return CleanupRuntimeInstanceResponse.newBuilder().build(); + }); + try { + lifecycleService.prepareWorldInstance(request); + var active = lifecycleService.activatePreparedWorldInstance(tenantId, gameInstanceId, 1L); + assertThat(active.status()).isEqualTo("ACTIVE"); + WorldInstance activeRow = + repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); + assertThat(activeRow.getLifecycleEpoch()).isEqualTo(2L); + assertThat(activeRow.getRowVersion()).isEqualTo(1L); + + dsl.execute( + "INSERT INTO initial_admission_bind_hold (" + + "hold_id, hold_fence, tenant_id, realm_uuid, playable_state_namespace_uuid, " + + "playable_state_scope, game_instance_id, version_id, active_lifecycle_epoch, " + + "initial_admission_request_id, request_digest, expected_no_prior_pointer, " + + "expected_catalog_revision, status, diagnostic_expires_at) " + + "VALUES (?, ?, ?, ?, ?, 'ISOLATED', ?, 11, 2, ?, ?, TRUE, 1, 'PENDING', " + + "CURRENT_TIMESTAMP + INTERVAL '1 hour')", + holdId, + UUID.randomUUID(), + tenantId, + UUID.randomUUID(), + UUID.randomUUID(), + gameInstanceId, + operationId(), + "a".repeat(64)); + + assertThatThrownBy( + () -> + lifecycleService.terminateWorldInstance( + tenantId, gameInstanceId, 2L, "term-fixture", "stop")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageStartingWith("INITIAL_ADMISSION_BIND_HOLD_ACTIVE:"); + WorldInstance held = + repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); + assertThat(held.getStatus()).isEqualTo("ACTIVE"); + assertThat(held.getLifecycleEpoch()).isEqualTo(2L); + assertThat(held.getRowVersion()).isEqualTo(1L); + verify(entityManagementClient, never()) + .cleanupRuntimeInstance(tenantId, gameInstanceId, "term-fixture"); + dsl.execute("DELETE FROM initial_admission_bind_hold WHERE hold_id = ?", holdId); + + assertThatThrownBy( + () -> + lifecycleService.terminateWorldInstance( + tenantId, gameInstanceId, 2L, "term-fixture", "stop")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Entity cleanup unavailable"); + WorldInstance terminating = + repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); + assertThat(terminating.getStatus()).isEqualTo("TERMINATING"); + assertThat(terminating.getLifecycleEpoch()).isEqualTo(3L); + assertThat(terminating.getTerminationRequestId()).isEqualTo("term-fixture"); + assertThat(terminating.getRowVersion()).isEqualTo(2L); + assertThat(terminating.getRunOwnedFixtureBindingSha256()).isEqualTo(binding); + + var terminated = + lifecycleService.terminateWorldInstance( + tenantId, gameInstanceId, 3L, "term-fixture", "stop"); + assertThat(terminated.status()).isEqualTo("TERMINATED"); + assertThat(terminated.lifecycleEpoch()).isEqualTo(4L); + WorldInstance terminalRow = + repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); + assertThat(terminalRow.getRowVersion()).isEqualTo(3L); + assertThat(terminalRow.getTerminationRequestId()).isEqualTo("term-fixture"); + + var replay = + lifecycleService.terminateWorldInstance( + tenantId, gameInstanceId, 2L, "term-fixture", "stop"); + assertThat(replay).isEqualTo(terminated); + assertThat( + repository + .findByTenantIdAndGameInstanceId(tenantId, gameInstanceId) + .orElseThrow() + .getRowVersion()) + .isEqualTo(3L); + assertThatThrownBy( + () -> + lifecycleService.terminateWorldInstance( + tenantId, gameInstanceId, 2L, "term-other", "stop")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("terminated under a different request id"); + verify(entityManagementClient, org.mockito.Mockito.times(2)) + .cleanupRuntimeInstance(tenantId, gameInstanceId, "term-fixture"); + } finally { + dsl.execute("DELETE FROM initial_admission_bind_hold WHERE hold_id = ?", holdId); + dsl.execute("DELETE FROM world_instance WHERE tenant_id = ?", tenantId); + } + } + + @Test + void ordinaryFailureJoinsAndRollsBackWithItsCallerTransaction() { + long tenantId = 8_810_006L; + long gameInstanceId = uniqueId(); + when(fixtureProvider.isEnabled()).thenReturn(false); + configureOrdinaryLaunchInputs(tenantId); + try { + var prepared = + lifecycleService.prepareWorldInstance(request(tenantId, gameInstanceId, operationId())); + assertThat(prepared.status()).isEqualTo("PREPARING"); + + TransactionTemplate callerTransaction = new TransactionTemplate(transactionManager); + assertThatThrownBy( + () -> + callerTransaction.executeWithoutResult( + status -> { + var failed = + lifecycleService.failPreparedWorldInstance( + tenantId, gameInstanceId, 1L, "caller will roll back"); + assertThat(failed.status()).isEqualTo("FAILED_PRE_ACTIVATION"); + assertThat(failed.lifecycleEpoch()).isEqualTo(2L); + throw new IllegalStateException("rollback ordinary caller"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("rollback ordinary caller"); + + WorldInstance afterRollback = + repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); + assertThat(afterRollback.getStatus()).isEqualTo("PREPARING"); + assertThat(afterRollback.getLifecycleEpoch()).isEqualTo(1L); + assertThat(afterRollback.getRowVersion()).isZero(); + } finally { + dsl.execute("DELETE FROM world_instance WHERE tenant_id = ?", tenantId); + } + } + @Test void concurrentPrepareRetriesCreateOneFixtureBoundWorldInstance() throws Exception { long tenantId = 8_810_003L; @@ -336,6 +588,47 @@ private void configureEvidence(String binding) { .thenReturn(binding); } + private void configureOrdinaryLaunchInputs(long tenantId) { + when(gameDesignClient.getPublishedReleaseBundle(tenantId, 11L)) + .thenReturn( + GetPublishedReleaseBundleResponse.newBuilder() + .setBundle( + PublishedReleaseBundle.newBuilder() + .setId(77L) + .setVersionId(11L) + .setAttestationSchemaVersion("v1") + .setManifestHash("manifest-11") + .addRequiredManifestAssetKeys("manifest.json") + .setGenerationConfigRevision("genrev-11") + .setPublishedReleaseBundleRef(RELEASE_REF) + .build()) + .build()); + when(gameDesignClient.getVersionAssetArtifactState(tenantId, 11L)) + .thenReturn( + GetVersionAssetArtifactStateResponse.newBuilder() + .setArtifactState( + VersionAssetArtifactState.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setVersionId(11L) + .setArtifactState(ArtifactState.ARTIFACT_STATE_PUBLISHED) + .setStateEpoch(3L) + .setManifestHash("manifest-11") + .addExportedManifestAssetKeys("manifest.json") + .build()) + .build()); + when(gameDesignClient.getVersionState(tenantId, 11L)) + .thenReturn( + GetVersionStateResponse.newBuilder() + .setVersionState( + VersionStateSnapshot.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setVersionId(11L) + .setVersionState(VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED) + .setVersionStateEpoch(77L) + .build()) + .build()); + } + private WorldLifecycleCommandServiceImpl restartedLifecycleService( WorldInstanceRepository restartedRepository, RunOwnedWorldLaunchEvidenceProvider provider) { WorldProperties properties = new WorldProperties(); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPostgresMigrationTestSupport.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPostgresMigrationTestSupport.java new file mode 100644 index 0000000000..5eb35710df --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPostgresMigrationTestSupport.java @@ -0,0 +1,163 @@ +package net.firedevops.firemud.worldmanagement; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.springframework.jdbc.datasource.DriverManagerDataSource; + +/** Shared migration fixtures for World Management native PostgreSQL tests. */ +public final class WorldPostgresMigrationTestSupport { + public static final String HISTORY = "flyway_schema_history_world_management_service"; + + // Exact SHA-256 bytes at d7c8f84fa947644a651304205803c3919c81684e: 31 World and 3 Saga. + public static final Map PARENT_MIGRATIONS = + Map.ofEntries( + Map.entry( + "V1000__create_saga_schema.sql", + "13f58ab66bd9c12483e113c8758ef9907ab3d14d47f61a298dd18f929d5aa537"), + Map.entry( + "V1001__saga_instance_table.sql", + "ebc4bbfd1a10314850e19ca6017d654a98c2ee4f5b95d1cce2ee078d990eb2bf"), + Map.entry( + "V1002__saga_step_table.sql", + "d9d98a2e51d53d78d17d27b15fe696e8b1e161af7c6de142680ec7b8a0dc7c31"), + Map.entry( + "V10__room_exit_direction.sql", + "9b174b153af563916b409abdad3da24f2d88f8a547de6d2b1f1085da3f06264e"), + Map.entry( + "V11__room_localized_text_variants.sql", + "cded77589b64b740689276c96e346ffff97226294b72ef184ab9ae5eaeea7b65"), + Map.entry( + "V12__world_instance_activation.sql", + "3fb5eecc00edb542dd45dd8dd11a632732f47277f96cae4bfc26ebf0f905fa62"), + Map.entry( + "V13__world_instance_termination.sql", + "894f7002fe67c6c65ab04018be7802c78b505666a0d16e2d2794eac4fccd54d4"), + Map.entry( + "V14__room_instance_topology.sql", + "4134d648bb29fd22e4e9d0b0df38454a698f1ab9449c1118c027a4e256658bc4"), + Map.entry( + "V15__zone_instance_topology.sql", + "413445894f5f39eb726e5824566c7bacab8ab81e7c51aadfe3d5917544395677"), + Map.entry( + "V16__runtime_world_event_scope.sql", + "905ac02e6a65308ab70fc5e986608131043c7eec7a2ebd1615f13652d36a4ffb"), + Map.entry( + "V17__world_instance_remap_set.sql", + "286a77a1110a9f3b8d7f88a6a829edb5551dbef73f02de1cdbf184c5947181d8"), + Map.entry( + "V18__version_scoped_world_templates.sql", + "02b07237b04c64d9f4215c42b4cefe31bdc05bd066c6f0823f14733a9772819b"), + Map.entry( + "V19__world_design_mutation_ledger.sql", + "fbbec4b460ce5aa9d4ea9dce70b156840c4cb8d99a0a1589771bad7a220d2f59"), + Map.entry( + "V1__init.sql", "7c65f75f6d2e32f7c07e24ea0260768e5660987a54a9148cef3422f5352bee64"), + Map.entry( + "V20__world_entity_spawn_binding.sql", + "ac5c8c2c326f47c4782c5595d7bbde478320ebb05bcde14f8e02a3bee158afd7"), + Map.entry( + "V21__scoped_generation_rules.sql", + "9e358fe5dd4a41f92a5b16681ad2adc7d24b969e5f476152228b2462974e68dd"), + Map.entry( + "V22__room_instance_internal_record_naming.sql", + "f56fce69e28c9dd9457dc508b016657480abd78d2a3190e782b8e2c0e3c4f340"), + Map.entry( + "V23.0.1__world_run_owned_fixture_launch_binding.sql", + "f014485e67b32b6404bb5cd40dc5568c2d1d9bc1993bafe826660c5b438ceecc"), + Map.entry( + "V23.1__world_authored_source_intake.sql", + "a7ac30d48da1911eb3395716e827ac0f0ec612970d4f40b5a27530d634430445"), + Map.entry( + "V23__initial_admission_bind_hold.sql", + "5e6f6070a02fbf09836dcc663ee3c12390dcb0dbea33a9e15ddd021a913ca1f1"), + Map.entry( + "V24__world_canonical_tenant_mutation_guard.sql", + "6ad0933008cea2d0fe28c8e247277950f789ac1f6cc061f1204b23cb044e82ea"), + Map.entry( + "V25__world_design_publication_fence.sql", + "c852a2e24232df5aec8628c1046570b49edb465a416bbdf942b60fe80ae17f94"), + Map.entry( + "V26__world_complete_launch_binding.sql", + "171595e883d8d459bfd05b8331cc2ace6faf41406b26a743cdc6d133cba33f7e"), + Map.entry( + "V27.1__world_publication_owner_binding.sql", + "93def8666763a08b1db34fd3db88cfa9eea0d5bc7bf836cffe9ff8766d0468f1"), + Map.entry( + "V27.2__world_legacy_tenant_claim_concurrency.sql", + "5a0c8de956baf2dce47e45bff6b3e022dd24d6a4c7c0ebeb4d55fdafb757f9bc"), + Map.entry( + "V27__world_authored_version_identity.sql", + "e9ff823152776361f2ac79d08b6dddce72105892fce0706041e8956994d8db0d"), + Map.entry( + "V2__add_tenant_and_expiration.sql", + "180a5c49ce5dc144daeb442c833921a410c51828f8196d1bbb4e6fe2d1955838"), + Map.entry( + "V3__world_events.sql", + "b6aaa18a6f01c7270e062a9cf8d2b13e0a57a092e7f418b87eaa382e3c9f3f3d"), + Map.entry( + "V4__room_exits.sql", + "02fbaee1e529649fa6dbe803795ac78cc40f5121735399131592b32bd23cb23a"), + Map.entry( + "V5__generation_rules.sql", + "27ba4f1827c6eafa14ccd6a4b85c9eb5c3de312ee85cdcae2da846ee1d8817a4"), + Map.entry( + "V6__region_shard.sql", + "a8bca5bad73f02936a8971cc9c34c19921d02bee55f860cad08d2c73932025cb"), + Map.entry( + "V7__optimistic_locking_and_indexes.sql", + "40d428bf21b99351068ee6cf11778ab3171f720f00ad2d8c9230b245093f9261"), + Map.entry( + "V8__region_generation_metadata.sql", + "a3bc7811eff6743f771346188f811b14d882356f67ccdbf6213bb2cc87695570"), + Map.entry( + "V9__region_spacing_multiplier.sql", + "5a5e2279d78b88cfad19802bbdf37416df714ee864265b08472b61fb234b6c32")); + + private WorldPostgresMigrationTestSupport() {} + + public static Path repositoryRoot() { + Path candidate = Path.of("").toAbsolutePath(); + while (candidate != null) { + if (Files.exists(candidate.resolve("settings.gradle.kts"))) return candidate; + candidate = candidate.getParent(); + } + throw new IllegalStateException("Unable to locate repository filesystem migrations"); + } + + public static String worldMigrations(Path root) { + return "filesystem:" + + root.resolve("services/world-management-service/src/main/resources/db/migration"); + } + + public static String sagaMigrations(Path root) { + return "filesystem:" + + root.resolve("services/common-saga/src/main/resources/db/migration/saga"); + } + + public static Flyway migration(DriverManagerDataSource source, String schema, String target) { + Path root = repositoryRoot(); + return flyway( + source, + schema, + target == null ? null : MigrationVersion.fromVersion(target), + worldMigrations(root), + sagaMigrations(root)); + } + + public static Flyway flyway( + DriverManagerDataSource source, String schema, MigrationVersion target, String... locations) { + var configuration = + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .table(HISTORY) + .placeholders(Map.of("serviceSchema", schema)) + .locations(locations); + if (target != null) configuration.target(target); + return configuration.load(); + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPreparationStartLocationSubtransactionPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPreparationStartLocationSubtransactionPostgresIntegrationTest.java new file mode 100644 index 0000000000..b5b76184c2 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPreparationStartLocationSubtransactionPostgresIntegrationTest.java @@ -0,0 +1,591 @@ +package net.firedevops.firemud.worldmanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; +import net.firedevops.firemud.worldmanagement.client.GameDesignClient; +import net.firedevops.firemud.worldmanagement.client.GameSessionClient; +import net.firedevops.firemud.worldmanagement.client.GrpcGameSessionInitialAdmissionBindProofClient; +import org.jooq.DSLContext; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.postgresql.util.PSQLException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; + +/** + * Exercises the installed schema-4 preparation selector against isolated copies of its installed + * table shapes and function bodies. The controlled rows establish SQL predicate behavior only; they + * do not establish Account authorization or a genuine production owner handoff. + */ +@Testcontainers(disabledWithoutDocker = true) +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +@SuppressWarnings("resource") +class WorldPreparationStartLocationSubtransactionPostgresIntegrationTest { + private static final String FORGED_FULL_XID = "9223372036854775807"; + private static final long WORLD_ID = 71001; + private static final long TENANT_KEY = 71002; + private static final long GAME_INSTANCE_KEY = 71003; + private static final long TEMPLATE_ROOM_KEY = 71004; + private static final long RUNTIME_ROOM_KEY = 71005; + + private static final List PROBE_TABLES = + List.of( + "world_instance", + "room", + "room_instance", + "world_complete_launch_binding", + "world_draft_start_location_receipt", + "world_canonical_frozen_topology", + "world_draft_graph_application", + "world_topology_draft_commit", + "world_authored_topology_identity", + "world_canonical_instance_association", + "world_canonical_instance_topology_identity", + "world_canonical_instance_preparation", + "world_canonical_preparation_start_location"); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "world_management_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private DSLContext dsl; + @Autowired private PlatformTransactionManager transactionManager; + @Autowired private ObjectMapper objectMapper; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @Test + void installedSchema4GuardAcceptsStampedSavepointPreparationAndRejectsLateOrHistoricalRows() + throws Exception { + String installedSchema = dsl.fetchSingle("SELECT current_schema()").get(0, String.class); + String probeSchema = "world_preparation_guard_" + UUID.randomUUID().toString().replace("-", ""); + Fixture fixture = fixture(); + try { + dsl.execute("CREATE SCHEMA " + DSL.name(probeSchema)); + cloneProbeTables(installedSchema, probeSchema); + seedSelectorEvidence(probeSchema, fixture); + seedHistoricalPreparation(probeSchema, fixture); + copyInstalledFunctions(installedSchema, probeSchema); + installProbeTriggers(probeSchema); + + var outer = new TransactionTemplate(transactionManager); + outer.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var savepoint = new TransactionTemplate(transactionManager); + savepoint.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); + savepoint.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + XidObservation observation = + outer.execute( + status -> { + savepoint.executeWithoutResult( + nested -> + insertPreparation(probeSchema, fixture, 2, fixture.freshInstanceId())); + var row = + dsl.fetchSingle( + "SELECT preparation_inserted_full_xid::text, xmin::text, " + + "pg_current_xact_id()::text, " + + "(txid_current() % 4294967296)::text " + + "FROM " + + DSL.name(probeSchema, "world_canonical_instance_preparation") + + " WHERE canonical_game_instance_id = ?", + fixture.freshInstanceId()); + return new XidObservation( + row.get(0, String.class), + row.get(1, String.class), + row.get(2, String.class), + row.get(3, String.class)); + }); + + assertThat(observation).isNotNull(); + assertThat(observation.serverStamp()) + .as("a caller-supplied full XID is overwritten by the server stamp") + .isNotEqualTo(FORGED_FULL_XID) + .isEqualTo(observation.topLevelFullXid()); + assertThat(observation.childXmin()) + .as("the row inserted under the savepoint has a child xmin distinct from the top XID") + .isNotEqualTo(observation.topLevelXid32()); + assertThat( + scalarLong( + "SELECT count(*) FROM " + + DSL.name(probeSchema, "world_canonical_preparation_start_location"))) + .as("the installed retainer reaches the installed schema-4 selector guard") + .isEqualTo(1L); + + assertSqlState( + () -> insertStartLocation(probeSchema, fixture, fixture.freshInstanceId()), "P0002"); + assertSqlState( + () -> insertStartLocation(probeSchema, fixture, fixture.historicalInstanceId()), "P0002"); + assertThat( + scalarText( + "SELECT preparation_inserted_full_xid::text FROM " + + DSL.name(probeSchema, "world_canonical_instance_preparation") + + " WHERE canonical_game_instance_id = ?", + fixture.historicalInstanceId())) + .as("the controlled old preparation models a pre-migration NULL stamp") + .isNull(); + } finally { + dsl.execute("DROP SCHEMA IF EXISTS " + DSL.name(probeSchema) + " CASCADE"); + } + } + + private void cloneProbeTables(String installedSchema, String probeSchema) { + for (String table : PROBE_TABLES) + dsl.execute( + "CREATE TABLE " + + DSL.name(probeSchema, table) + + " AS TABLE " + + DSL.name(installedSchema, table) + + " WITH NO DATA"); + } + + private void copyInstalledFunctions(String installedSchema, String probeSchema) { + for (String signature : + List.of( + "world_require_preparation_start_location(jsonb,jsonb,uuid)", + "world_guard_preparation_start_location()", + "world_retain_preparation_start_location()", + "world_stamp_preparation_insert_full_xid()")) { + String definition = + scalarText( + "SELECT pg_get_functiondef(to_regprocedure(?))", installedSchema + "." + signature); + definition = + definition + .replace("\"" + installedSchema + "\"", "\"" + probeSchema + "\"") + .replace(installedSchema + ".", probeSchema + ".") + .replace("'" + installedSchema + "'", "'" + probeSchema + "'"); + dsl.execute(definition); + } + } + + private void installProbeTriggers(String probeSchema) { + dsl.execute( + "CREATE TRIGGER trg_world_preparation_full_xid_stamp BEFORE INSERT ON " + + DSL.name(probeSchema, "world_canonical_instance_preparation") + + " FOR EACH ROW EXECUTE FUNCTION " + + DSL.name(probeSchema, "world_stamp_preparation_insert_full_xid") + + "()"); + dsl.execute( + "CREATE TRIGGER trg_world_preparation_retain_start_location AFTER INSERT ON " + + DSL.name(probeSchema, "world_canonical_instance_preparation") + + " FOR EACH ROW EXECUTE FUNCTION " + + DSL.name(probeSchema, "world_retain_preparation_start_location") + + "()"); + dsl.execute( + "CREATE TRIGGER trg_world_preparation_start_location_guard " + + "BEFORE INSERT OR UPDATE OR DELETE ON " + + DSL.name(probeSchema, "world_canonical_preparation_start_location") + + " FOR EACH ROW EXECUTE FUNCTION " + + DSL.name(probeSchema, "world_guard_preparation_start_location") + + "()"); + dsl.execute( + "CREATE TRIGGER trg_world_preparation_start_location_no_truncate " + + "BEFORE TRUNCATE ON " + + DSL.name(probeSchema, "world_canonical_preparation_start_location") + + " FOR EACH STATEMENT EXECUTE FUNCTION " + + DSL.name(probeSchema, "world_guard_preparation_start_location") + + "()"); + } + + private void seedHistoricalPreparation(String schema, Fixture fixture) throws Exception { + insertPreparation(schema, fixture, 1, fixture.historicalInstanceId(), null); + } + + private void insertPreparation(String schema, Fixture fixture, long rowId, UUID gameInstanceId) { + insertPreparation(schema, fixture, rowId, gameInstanceId, FORGED_FULL_XID); + } + + private void insertPreparation( + String schema, Fixture fixture, long rowId, UUID gameInstanceId, String callerStamp) { + dsl.execute( + "INSERT INTO " + + DSL.name(schema, "world_canonical_instance_preparation") + + " (id, canonical_game_instance_id, target_namespace, canonical_tenant_id, " + + "world_slug, control_plane_request_id, canonical_version_id, " + + "version_identity_operation_id, capture_id, graph_bytes, graph_sha256, input_digest, " + + "input_json, world_instance_id, private_game_instance_key, region_count, zone_count, " + + "room_count, exit_count, storage_status, preparation_inserted_full_xid) " + + "VALUES (?, ?, 'dev', ?, 'probe-world', 'probe-op', ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "1, 0, 1, 0, 'MATERIALIZED_UNVERIFIED', ?::xid8)", + rowId, + gameInstanceId, + fixture.tenantId(), + fixture.versionId(), + fixture.versionIdentityOperationId(), + fixture.captureId(), + fixture.graphBytes(), + fixture.graphSha256(), + fixture.inputDigest(), + fixture.inputJson(), + WORLD_ID, + GAME_INSTANCE_KEY, + callerStamp); + } + + private void seedSelectorEvidence(String schema, Fixture fixture) throws Exception { + var names = fixture.names(); + var source = DSL.name(schema, "world_instance"); + dsl.execute( + "INSERT INTO " + source + " (id, tenant_id, game_instance_id) VALUES (?, ?, ?)", + WORLD_ID, + TENANT_KEY, + GAME_INSTANCE_KEY); + dsl.execute( + "INSERT INTO " + DSL.name(schema, "room") + " (id, tenant_id, version_id) VALUES (?, ?, ?)", + TEMPLATE_ROOM_KEY, + TENANT_KEY, + fixture.localVersionKey()); + dsl.execute( + "INSERT INTO " + + DSL.name(schema, "room_instance") + + " (id, tenant_id, game_instance_id, room_instance_row_id) VALUES (?, ?, ?, ?)", + RUNTIME_ROOM_KEY, + TENANT_KEY, + GAME_INSTANCE_KEY, + RUNTIME_ROOM_KEY); + dsl.execute( + "INSERT INTO " + + DSL.name(schema, "world_canonical_instance_topology_identity") + + " (world_instance_id, canonical_game_instance_id, family, template_id, " + + "template_private_row_key, runtime_row_id, runtime_room_instance_id) " + + "VALUES (?, ?, 'ROOM', ?, ?, ?, ?)", + WORLD_ID, + fixture.freshInstanceId(), + fixture.roomTemplateId(), + TEMPLATE_ROOM_KEY, + RUNTIME_ROOM_KEY, + RUNTIME_ROOM_KEY); + + dsl.execute( + "INSERT INTO " + + DSL.name(schema, "world_complete_launch_binding") + + " (binding_operation_id, release_attestation_json) VALUES (?, ?)", + fixture.bindingOperationId(), + names.releaseAttestationJson()); + dsl.execute( + "INSERT INTO " + + DSL.name(schema, "world_topology_draft_commit") + + " (request_id, commit_id, target_namespace, canonical_tenant_id, " + + "canonical_version_id, local_tenant_key, local_version_key, binding_json, " + + "owner_binding_json, binding_digest, graph_bytes, graph_sha256, result_bytes, " + + "storage_status) VALUES (?, ?, 'dev', ?, ?, ?, ?, '{}', '{}', ?, ?, ?, ?, " + + "'STORED_PERMISSION_UNVERIFIED')", + fixture.requestId(), + fixture.commitId(), + fixture.tenantId(), + fixture.versionId(), + TENANT_KEY, + fixture.localVersionKey(), + fixture.bindingDigest(), + fixture.graphBytes(), + fixture.graphSha256(), + fixture.appliedResultBytes()); + dsl.execute( + "INSERT INTO " + + DSL.name(schema, "world_canonical_frozen_topology") + + " (capture_id, publication_fence, request_id, commit_id, " + + "version_identity_operation_id, freeze_request_json, owner_binding_json, " + + "binding_json, binding_digest, identity_json, intake_json, graph_bytes, " + + "graph_sha256, storage_result_bytes, result_bytes, capture_status) " + + "VALUES (?, ?, ?, ?, ?, ?, '{}', '{}', ?, '{}', '{}', ?, ?, ?, ?, " + + "'CAPTURED_UNVERIFIED')", + fixture.captureId(), + fixture.publicationFence(), + fixture.requestId(), + fixture.commitId(), + fixture.versionIdentityOperationId(), + names.freezeRequestJson(), + fixture.bindingDigest(), + fixture.graphBytes(), + fixture.graphSha256(), + fixture.appliedResultBytes(), + fixture.appliedResultBytes()); + dsl.execute( + "INSERT INTO " + + DSL.name(schema, "world_draft_graph_application") + + " (operation_id, request_id, commit_id, authorization_fence_id, operation_bytes, " + + "account_binding_bytes, account_binding_digest, result_bytes, result_digest, " + + "application_transaction_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 41)", + fixture.applicationOperationId(), + fixture.requestId(), + fixture.commitId(), + fixture.publicationFence(), + fixture.appliedResultBytes(), + fixture.accountBindingBytes(), + fixture.accountBindingDigest(), + fixture.appliedResultBytes(), + fixture.resultDigest()); + dsl.execute( + "INSERT INTO " + + DSL.name(schema, "world_draft_start_location_receipt") + + " (operation_id, request_id, commit_id, authorization_fence_id, target_namespace, " + + "account_binding_bytes, account_binding_digest, binding_digest, canonical_tenant_id, " + + "canonical_version_id, room_template_id, graph_digest, receipt_digest, receipt_bytes) " + + "VALUES (?, ?, ?, ?, 'dev', ?, ?, ?, ?, ?, ?, ?, ?, ?)", + fixture.applicationOperationId(), + fixture.requestId(), + fixture.commitId(), + fixture.publicationFence(), + fixture.accountBindingBytes(), + fixture.accountBindingDigest(), + fixture.bindingDigest(), + fixture.tenantId(), + fixture.versionId(), + fixture.roomTemplateId(), + fixture.graphDigest(), + fixture.receiptDigest(), + fixture.selectorReceiptBytes()); + dsl.execute( + "INSERT INTO " + + DSL.name(schema, "world_authored_topology_identity") + + " (target_namespace, canonical_tenant_id, canonical_version_id, family, template_id, " + + "private_row_key, tenant_id, version_id, version_identity_operation_id, request_id, " + + "commit_id, revision_id, revision_order) VALUES ('dev', ?, ?, 'ROOM', ?, ?, ?, ?, ?, ?, ?, ?, '0')", + fixture.tenantId(), + fixture.versionId(), + fixture.roomTemplateId(), + TEMPLATE_ROOM_KEY, + TENANT_KEY, + fixture.localVersionKey(), + fixture.versionIdentityOperationId(), + fixture.requestId(), + fixture.commitId(), + UUID.randomUUID()); + } + + private void insertStartLocation(String schema, Fixture fixture, UUID gameInstanceId) { + dsl.execute( + "INSERT INTO " + + DSL.name(schema, "world_canonical_preparation_start_location") + + " (canonical_game_instance_id, world_instance_id, canonical_tenant_id, " + + "canonical_version_id, room_template_id, runtime_room_instance_id, receipt_digest, " + + "graph_digest, evidence_bytes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + gameInstanceId, + WORLD_ID, + fixture.tenantId(), + fixture.versionId(), + fixture.roomTemplateId(), + RUNTIME_ROOM_KEY, + fixture.receiptDigest(), + fixture.graphDigest(), + fixture.evidenceBytes()); + } + + private Fixture fixture() throws Exception { + UUID tenantId = UUID.randomUUID(); + UUID versionId = UUID.randomUUID(); + UUID versionIdentityOperationId = UUID.randomUUID(); + UUID applicationOperationId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID commitId = UUID.randomUUID(); + UUID publicationFence = UUID.randomUUID(); + UUID captureId = UUID.randomUUID(); + UUID roomTemplateId = UUID.randomUUID(); + UUID bindingOperationId = UUID.randomUUID(); + byte[] graphBytes = + "{\"schemaVersion\":3,\"rows\":[{\"family\":\"ROOM\"}]}".getBytes(StandardCharsets.UTF_8); + String graphSha256 = digestHex(graphBytes); + String graphDigest = "sha256:" + graphSha256; + String bindingDigest = "sha256:" + "b".repeat(64); + byte[] accountBindingBytes = + "{\"accountBinding\":\"controlled\"}".getBytes(StandardCharsets.UTF_8); + String accountBindingDigest = "sha256:" + digestHex(accountBindingBytes); + byte[] selectorReceiptBytes = "{\"receipt\":\"controlled\"}".getBytes(StandardCharsets.UTF_8); + byte[] appliedResultBytes = + ("{\"schema\":\"world-draft-graph-applied/v2\",\"status\":\"APPLIED\"," + + "\"graphDigest\":\"" + + graphDigest + + "\"}") + .getBytes(StandardCharsets.UTF_8); + String resultDigest = "sha256:" + digestHex(appliedResultBytes); + + Map selectedRequest = new LinkedHashMap<>(); + selectedRequest.put("targetNamespace", "dev"); + selectedRequest.put("canonicalTenantId", tenantId.toString()); + selectedRequest.put("canonicalVersionId", versionId.toString()); + selectedRequest.put("intakeRequestId", UUID.randomUUID().toString()); + selectedRequest.put("publicationFence", publicationFence.toString()); + selectedRequest.put("publicationRequestId", "controlled-publication"); + selectedRequest.put("requestDigest", "c".repeat(64)); + selectedRequest.put("versionStateEpoch", "7"); + selectedRequest.put("publishWorkflowId", "controlled-workflow"); + selectedRequest.put("appliedCommitId", "controlled-commit"); + selectedRequest.put("contentDigest", "sha256:" + "d".repeat(64)); + selectedRequest.put("digestSchemaVersion", "4"); + selectedRequest.put("worldAffectedTuples", List.of()); + Map retainedRequest = new LinkedHashMap<>(selectedRequest); + retainedRequest.put("versionStateEpoch", 7L); + + Map freezeRequest = new LinkedHashMap<>(); + selectedRequest.forEach( + (key, value) -> { + if (!key.equals("worldAffectedTuples")) freezeRequest.put(key, value); + }); + freezeRequest.remove("versionStateEpoch"); + freezeRequest.put("versionStateEpoch", 7L); + freezeRequest.put("suppliedOwnedAffectedTuples", List.of()); + + String receiptBytes64 = Base64.getEncoder().encodeToString(selectorReceiptBytes); + String accountBytes64 = Base64.getEncoder().encodeToString(accountBindingBytes); + String resultBytes64 = Base64.getEncoder().encodeToString(appliedResultBytes); + Map evidence = + Map.of( + "schema", "world-published-start-location-evidence/v1", + "request", selectedRequest, + "selectorReceiptBytesBase64", receiptBytes64, + "originalAccountBindingBytesBase64", accountBytes64, + "appliedResultBytesBase64", resultBytes64); + byte[] evidenceBytes = json(evidence).getBytes(StandardCharsets.UTF_8); + Map retainedEvidence = + Map.of( + "request", retainedRequest, + "selectorReceiptBytes", receiptBytes64, + "originalAccountBindingBytes", accountBytes64, + "appliedResultBytes", resultBytes64); + String releaseAttestationJson = + json(Map.of("schemaVersion", 4, "worldStartLocationEvidence", retainedEvidence)); + Map input = + Map.of( + "schemaVersion", 4, + "launchBinding", Map.of("operationId", bindingOperationId.toString()), + "worldStartLocationEvidenceBase64", Base64.getEncoder().encodeToString(evidenceBytes)); + + return new Fixture( + tenantId, + versionId, + versionIdentityOperationId, + applicationOperationId, + requestId, + commitId, + publicationFence, + captureId, + roomTemplateId, + bindingOperationId, + UUID.randomUUID(), + UUID.randomUUID(), + WORLD_ID, + TENANT_KEY, + GAME_INSTANCE_KEY, + graphBytes, + graphSha256, + graphDigest, + "sha256:" + digestHex(selectorReceiptBytes), + bindingDigest, + accountBindingBytes, + accountBindingDigest, + selectorReceiptBytes, + appliedResultBytes, + resultDigest, + evidenceBytes, + "sha256:" + "e".repeat(64), + json(input), + TENANT_KEY + 20, + new FixtureNames(json(freezeRequest), releaseAttestationJson)); + } + + private String json(Object value) throws Exception { + return objectMapper.writeValueAsString(value); + } + + private static String digestHex(byte[] value) throws Exception { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } + + private long scalarLong(String sql, Object... bindings) { + return dsl.fetchSingle(sql, bindings).get(0, Long.class); + } + + private String scalarText(String sql, Object... bindings) { + return dsl.fetchSingle(sql, bindings).get(0, String.class); + } + + private static void assertSqlState( + org.assertj.core.api.ThrowableAssert.ThrowingCallable action, String state) { + assertThatThrownBy(action) + .satisfies( + failure -> { + Throwable cause = failure; + while (cause.getCause() != null) cause = cause.getCause(); + assertThat(cause).isInstanceOf(PSQLException.class); + assertThat(((PSQLException) cause).getSQLState()).isEqualTo(state); + }); + } + + private record XidObservation( + String serverStamp, String childXmin, String topLevelFullXid, String topLevelXid32) {} + + private record FixtureNames(String freezeRequestJson, String releaseAttestationJson) {} + + private record Fixture( + UUID tenantId, + UUID versionId, + UUID versionIdentityOperationId, + UUID applicationOperationId, + UUID requestId, + UUID commitId, + UUID publicationFence, + UUID captureId, + UUID roomTemplateId, + UUID bindingOperationId, + UUID freshInstanceId, + UUID historicalInstanceId, + long worldId, + long tenantKey, + long privateGameInstanceKey, + byte[] graphBytes, + String graphSha256, + String graphDigest, + String receiptDigest, + String bindingDigest, + byte[] accountBindingBytes, + String accountBindingDigest, + byte[] selectorReceiptBytes, + byte[] appliedResultBytes, + String resultDigest, + byte[] evidenceBytes, + String inputDigest, + String inputJson, + long localVersionKey, + FixtureNames names) {} +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldSameTransactionGuardSubtransactionPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldSameTransactionGuardSubtransactionPostgresIntegrationTest.java new file mode 100644 index 0000000000..9f69264606 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldSameTransactionGuardSubtransactionPostgresIntegrationTest.java @@ -0,0 +1,442 @@ +package net.firedevops.firemud.worldmanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; +import net.firedevops.firemud.worldmanagement.client.GameDesignClient; +import net.firedevops.firemud.worldmanagement.client.GameSessionClient; +import net.firedevops.firemud.worldmanagement.client.GrpcGameSessionInitialAdmissionBindProofClient; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.postgresql.util.PSQLException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Native PostgreSQL proof for same-top-level-transaction guards across savepoints. + * + *

Source/version evidence is stipulated through the existing owner repositories. This test + * proves the SQL boundary and does not claim authenticated Account or Game Design producers. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldSameTransactionGuardSubtransactionPostgresIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final String REQUEST_DIGEST = "f".repeat(64); + private static final String FUTURE_FULL_XID = "9223372036854775807"; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "world_management_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private DSLContext dsl; + @Autowired private PlatformTransactionManager transactionManager; + @Autowired private WorldAuthoredSourceIntakeRepository intakeRepository; + @Autowired private WorldDesignPublicationFenceRepository fenceRepository; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @Test + void childSubtransactionAttemptAcceptsTopLevelAccountBindingAndInventory() { + WorldAuthoredSourceIntakeReceipt receipt = intake(UUID.randomUUID(), "savepoint-world"); + WorldAuthoredVersionIdentityReceipt identity = identity(receipt, 9_000_000_042L); + WorldDesignPublicationFenceEvidence request = + evidence(receipt, identity, "savepoint-publication"); + var childTransaction = new TransactionTemplate(transactionManager); + childTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); + childTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + + UUID publicationFence = + ownerTransaction() + .execute( + status -> { + var frozen = + childTransaction.execute( + nestedStatus -> + fenceRepository.claimFreeze( + request, + () -> + new WorldDesignPublicationFenceEvidence.Checkpoint( + "savepoint-commit", "c".repeat(64), 3))); + assertThat(frozen).isNotNull(); + var insertedAttempt = + dsl.fetchSingle( + "SELECT attempt_created_full_xid::text AS created_full_xid, " + + "attempt_inserted_full_xid::text AS inserted_full_xid, " + + "xmin::text AS tuple_xid, " + + "(attempt_created_full_xid = pg_current_xact_id()) AS top_created_stamp, " + + "(attempt_inserted_full_xid = pg_current_xact_id()) AS top_inserted_stamp, " + + "(xmin::text = (txid_current() % 4294967296)::text) AS top_xmin " + + "FROM world_design_publication_fence_attempt WHERE publication_fence = ?", + frozen.publicationFence()); + assertThat(insertedAttempt.get("top_created_stamp", Boolean.class)).isTrue(); + assertThat(insertedAttempt.get("top_inserted_stamp", Boolean.class)).isTrue(); + assertThat(insertedAttempt.get("top_xmin", Boolean.class)) + .as("the tuple was inserted by the committed child transaction") + .isFalse(); + + UUID accountOperationId = UUID.randomUUID(); + UUID accountFenceId = UUID.randomUUID(); + byte[] accountBytes = + "controlled account binding".getBytes(StandardCharsets.UTF_8); + dsl.execute( + "INSERT INTO world_design_publication_account_binding " + + "(publication_fence, account_operation_id, account_fence_id, " + + "account_binding_bytes, account_binding_digest) VALUES (?, ?, ?, ?, ?)", + frozen.publicationFence(), + accountOperationId, + accountFenceId, + accountBytes, + "sha256:" + sha256(accountBytes)); + + byte[] inventoryBytes = + "controlled selected inventory".getBytes(StandardCharsets.UTF_8); + dsl.execute( + "INSERT INTO world_selected_publication_artifact_inventory " + + "(publication_fence, target_namespace, canonical_tenant_id, canonical_version_id, " + + "local_tenant_key, local_version_key, applied_commit_id, account_operation_id, " + + "account_fence_id, inventory_schema_version, inventory_bytes, inventory_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?)", + frozen.publicationFence(), + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + receipt.localTenantKey(), + identity.localVersionKey(), + frozen.checkpoint().appliedCommitId(), + accountOperationId, + accountFenceId, + inventoryBytes, + "sha256:" + sha256(inventoryBytes)); + return frozen.publicationFence(); + }); + + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM world_design_publication_account_binding WHERE publication_fence = ?", + publicationFence) + .get(0, Long.class)) + .isEqualTo(1L); + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM world_selected_publication_artifact_inventory WHERE publication_fence = ?", + publicationFence) + .get(0, Long.class)) + .isEqualTo(1L); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM world_design_publication_fence_attempt WHERE publication_fence = ?", + publicationFence)) + .hasMessageContaining("World publication-fence attempt history is immutable"); + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM world_design_publication_fence_attempt WHERE publication_fence = ?", + publicationFence) + .get(0, Long.class)) + .isEqualTo(1L); + } + + @Test + void callerSuppliedFutureStampIsOverwrittenAndCommittedAttemptCannotBeAttachedLater() { + WorldAuthoredSourceIntakeReceipt receipt = intake(UUID.randomUUID(), "stamp-world"); + WorldAuthoredVersionIdentityReceipt identity = identity(receipt, 9_000_000_043L); + WorldDesignPublicationFenceEvidence request = evidence(receipt, identity, "future-stamp-probe"); + UUID publicationFence = UUID.randomUUID(); + ownerTransaction() + .executeWithoutResult(status -> fenceRepository.lockOpen(request.ownerBinding())); + + ownerTransaction() + .executeWithoutResult( + status -> { + dsl.execute( + "INSERT INTO world_design_publication_fence_attempt " + + "(publication_fence, target_namespace, canonical_tenant_id, local_tenant_key, " + + "version_id, intake_operation_id, intake_request_id, source_operation_id, " + + "source_evidence_digest, intake_receipt_digest, publication_request_id, " + + "request_digest, version_state_epoch, publish_workflow_id, applied_commit_id, " + + "content_digest, digest_schema_version, owner_binding_schema_version, " + + "canonical_version_id, version_identity_operation_id, game_design_version_id, " + + "intake_request_digest, attempt_created_full_xid, attempt_inserted_full_xid) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 3, 1, ?, ?, ?, ?, ?::xid8, ?::xid8)", + publicationFence, + request.targetNamespace(), + request.canonicalTenantId(), + receipt.localTenantKey(), + identity.localVersionKey(), + receipt.operationId(), + receipt.intakeRequestId(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.receiptDigest(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + "caller-stamp-probe", + "d".repeat(64), + request.canonicalVersionId(), + request.versionIdentityOperationId(), + request.gameDesignVersionId(), + receipt.requestDigest(), + FUTURE_FULL_XID, + FUTURE_FULL_XID); + assertThat( + dsl.execute( + "UPDATE world_design_publication_fence_owner " + + "SET owner_freeze_phase = 'FROZEN', current_publication_fence = ? " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? " + + "AND local_tenant_key = ? AND version_id = ?", + publicationFence, + request.targetNamespace(), + request.canonicalTenantId(), + receipt.localTenantKey(), + identity.localVersionKey())) + .isEqualTo(1); + var stored = + dsl.fetchSingle( + "SELECT attempt_created_full_xid::text AS created_full_xid, " + + "attempt_inserted_full_xid::text AS inserted_full_xid, " + + "pg_current_xact_id()::text AS current_full_xid " + + "FROM world_design_publication_fence_attempt WHERE publication_fence = ?", + publicationFence); + assertThat(stored.get("created_full_xid", String.class)) + .isEqualTo(stored.get("current_full_xid", String.class)) + .isNotEqualTo(FUTURE_FULL_XID); + assertThat(stored.get("inserted_full_xid", String.class)) + .isEqualTo(stored.get("current_full_xid", String.class)) + .isNotEqualTo(FUTURE_FULL_XID); + }); + + var ownerBeforeLateAttachment = + dsl.fetchSingle( + "SELECT owner_freeze_phase, current_publication_fence " + + "FROM world_design_publication_fence_owner WHERE target_namespace = ? " + + "AND canonical_tenant_id = ? AND local_tenant_key = ? AND version_id = ?", + request.targetNamespace(), + request.canonicalTenantId(), + receipt.localTenantKey(), + identity.localVersionKey()); + byte[] accountBytes = "late account binding".getBytes(StandardCharsets.UTF_8); + assertSqlState( + () -> + ownerTransaction() + .executeWithoutResult( + status -> + dsl.execute( + "INSERT INTO world_design_publication_account_binding " + + "(publication_fence, account_operation_id, account_fence_id, " + + "account_binding_bytes, account_binding_digest) VALUES (?, ?, ?, ?, ?)", + publicationFence, + UUID.randomUUID(), + UUID.randomUUID(), + accountBytes, + "sha256:" + sha256(accountBytes))), + "P0002", + "query returned no rows"); + assertThat( + dsl.fetchSingle( + "SELECT owner_freeze_phase, current_publication_fence " + + "FROM world_design_publication_fence_owner WHERE target_namespace = ? " + + "AND canonical_tenant_id = ? AND local_tenant_key = ? AND version_id = ?", + request.targetNamespace(), + request.canonicalTenantId(), + receipt.localTenantKey(), + identity.localVersionKey())) + .as("a late binding fails at the installed SELECT INTO STRICT attempt lookup") + .isEqualTo(ownerBeforeLateAttachment); + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM world_design_publication_fence_attempt WHERE publication_fence = ?", + publicationFence) + .get(0, Long.class)) + .isEqualTo(1L); + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM world_design_publication_account_binding WHERE publication_fence = ?", + publicationFence) + .get(0, Long.class)) + .isZero(); + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM world_selected_publication_artifact_inventory WHERE publication_fence = ?", + publicationFence) + .get(0, Long.class)) + .isZero(); + } + + private WorldAuthoredSourceIntakeReceipt intake(UUID tenantId, String worldSlug) { + String tenantSlug = "tenant-" + tenantId.toString().replace("-", ""); + UUID registrationRequestId = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + long sourceRowId = (UUID.randomUUID().getMostSignificantBits() & 0x7fffffffL) + 1L; + String displayName = "Stipulated subtransaction proof world"; + String sourceTenantKey = "gd-row-" + sourceRowId; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequestId, tenantId, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceRowId, + sourceTenantKey, + "NEW_GAME_ROW"); + var source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceRowId, + sourceTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + return ownerTransaction() + .execute(status -> intakeRepository.acceptFresh(NAMESPACE, UUID.randomUUID(), source)); + } + + private WorldAuthoredVersionIdentityReceipt identity( + WorldAuthoredSourceIntakeReceipt receipt, long gameDesignVersionId) { + UUID canonicalVersionId = UUID.randomUUID(); + var stateRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + gameDesignVersionId); + var state = + AuthoredWorldVersionStateEvidence.create( + stateRequest, + receipt.source(), + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1L); + return ownerTransaction() + .execute( + status -> new WorldAuthoredVersionIdentityRepository(dsl).acceptFresh(receipt, state)); + } + + private static WorldDesignPublicationFenceEvidence evidence( + WorldAuthoredSourceIntakeReceipt receipt, + WorldAuthoredVersionIdentityReceipt identity, + String publicationRequestId) { + var binding = + PublicationDigestRequestBinding.full( + receipt.canonicalTenantId().toString(), + Long.toString(identity.gameDesignVersionId()), + publicationRequestId); + return new WorldDesignPublicationFenceEvidence( + NAMESPACE, + receipt.canonicalTenantId(), + identity.canonicalVersionId(), + identity.operationId(), + identity.gameDesignVersionId(), + receipt.intakeRequestId(), + receipt.operationId(), + receipt.requestDigest(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.receiptDigest(), + publicationRequestId, + REQUEST_DIGEST, + 1L, + binding.derivedWorkflowIdentity()); + } + + private TransactionTemplate ownerTransaction() { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + return transaction; + } + + private static void assertSqlState( + org.assertj.core.api.ThrowableAssert.ThrowingCallable action, String state, String message) { + assertThatThrownBy(action) + .satisfies( + failure -> { + Throwable cause = failure; + while (cause.getCause() != null) cause = cause.getCause(); + assertThat(cause).isInstanceOf(PSQLException.class); + PSQLException postgresFailure = (PSQLException) cause; + assertThat(postgresFailure.getSQLState()).isEqualTo(state); + assertThat(postgresFailure.getMessage()).contains(message); + }); + } + + private static String sha256(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new AssertionError(impossible); + } + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java new file mode 100644 index 0000000000..ca69804373 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java @@ -0,0 +1,3685 @@ +package net.firedevops.firemud.worldmanagement.data; + +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.HISTORY; +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.PARENT_MIGRATIONS; +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.migration; +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.repositoryRoot; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.worldmanagement.WorldManagementServiceApplication; +import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; +import net.firedevops.firemud.worldmanagement.client.GameDesignClient; +import net.firedevops.firemud.worldmanagement.client.GameSessionClient; +import net.firedevops.firemud.worldmanagement.client.GrpcGameSessionInitialAdmissionBindProofClient; +import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; +import net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto; +import net.firedevops.firemud.worldmanagement.service.impl.RunOwnedWorldFixtureLifecycleTestFactory; +import net.firedevops.firemud.worldmanagement.service.impl.WorldLifecycleCommandServiceImpl; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociation; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCompleteLaunchBindingRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.postgresql.util.PSQLException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; + +/** + * Native PostgreSQL PREPARING-only World owner proof with controlled upstream wire inputs. + * + *

GDS/GS values and certificate commitments are stipulated constructor data. This proves actual + * World owner allocation, materialization and readback, not authenticated producers or TLS. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest { + private record LifecycleGuardProbeCase( + int key, + String label, + String oldMutation, + String activationMutation, + String expectedDiagnostic) {} + + private record LifecycleTransitionGuardProbeCase( + int key, + String label, + String startingMutation, + String transitionMutation, + String expectedDiagnostic) {} + + private static final String CONTENT_DIGEST = + "sha256:f817af2770072bab0384c30c19b8cd30fce7a5a33f7587faed0024aa7c0909bc"; + private static final String VALID_DIGEST = "sha256:" + "a".repeat(64); + + private static final Map PROTECTED_ARTIFACTS = + Map.ofEntries( + Map.entry( + "V1003__world_authored_graph_snapshot.sql", + "83e4353e13c648e7a4041d9db2e455a677c49cbe1232843a7bc011ae7d07dd18"), + Map.entry( + "V1004__world_guarded_region_draft_commits.sql", + "4d702e93bcd3f1cc42b24829a9b2083e62b36a89dac35eed974180ddfbc98c35"), + Map.entry( + "V1005__world_guarded_uuid_topology_commits.sql", + "7bf03448938d3d335367fecdd4481250d8235339aa39465b439e651aac539a89"), + Map.entry( + "V1006__world_canonical_frozen_topology.sql", + "766d33d8cc81693fa57c20fdf962a299ed4b35730a8914c407d1200ab3fba5f3"), + Map.entry( + "V1007__world_digest_schema3_capture.sql", + "1a4d1a986793b7947abecb88b97a6faaf4caf95209e49a5de6e5b1c768cd5178"), + Map.entry( + "V1008__world_canonical_instance_association.sql", + "6bece257d5aa97ac0d2073744da650c51366c4076ac72c055f1589123b7f40b9"), + Map.entry( + "V1009__world_guarded_canonical_instance_preparation.sql", + "6c68bcd4086b8ccf0ea188a10a4e95473ad66ebb18a3d6152197dbd7afd68ed1"), + Map.entry( + "V1010__world_draft_terminal_outcomes.sql", + "7d70fb9c89c92ae4eb97998645ff9b818c63d23681166088553384a9a8b5f8a7"), + Map.entry( + "V1011__world_draft_terminal_guard_namespace.sql", + "8e8df60368e92646b70730089ef39fdcf8a53cd248fa931a537f80fc405b80a7"), + Map.entry( + "V1012__world_account_bound_graph_application.sql", + "1ebfaa3513be9438a1840bbe8ccdbdd4b9c9f2f939b25a2498a24a75da1ae125"), + Map.entry( + "V1013__world_preparation_exact_release_graph.sql", + "46c280c1c42fd532df0e0a8efb9a89a0f3dd84695e887fe9102910f6d58db0ee"), + Map.entry( + "V1014__world_explicit_fresh_graph_start_location.sql", + "a7369c0426c854c4e44c34dc1a58fd86952e04c7e2c142cd0b0535bf326480a1"), + Map.entry( + "V1015__world_release_start_location_materialization.sql", + "493e19c4fd37b1ed97f9e8821eff1ba4cd99ac1dc0aea9217d64690371afa56e"), + Map.entry( + "V1016__canonical_instance_activation_operation.sql", + "b251f8d2c0c172bbff71dbb8c33cfb599a6201c9f57cc1c978624ce78f33cf52"), + Map.entry( + "V1017__world_publication_terminal_handoff.sql", + "0dbee29bf9a746fd28cceca950dc383c3c2a1f0f2ea89d0363c973e6debd2d0b"), + Map.entry( + "V1018__world_operational_region_assignment.sql", + "e91713eeba68dab0731d3bc8a69fabbfb828e70d194e73425615fbead050f784"), + Map.entry( + "V1019__world_canonical_initial_player_location.sql", + "b04f1abe5f9ea8a27def3ebe04305abcb8a846f7356dd547f4da0b16973d40ea"), + Map.entry( + "V1020__canonical_initial_admission_hold_binding.sql", + "2baac1fccf9fe87dc2986c6119b8f68ec4c8d078db994f41db2ae880bc25e319"), + Map.entry( + "V1021__canonical_initial_admission_hold_terminal.sql", + "7f5016a8a72367aee9516805d1cacf8410167823fec625add9eeee091dd5cee1"), + Map.entry( + "V1022__canonical_initial_player_location_typed_hold.sql", + "8529548fee59f76acad5a3703ac778bf71785c51f1d3bc1a62c0fa6109cc57ff"), + Map.entry( + "V1023__canonical_initial_location_operation_origins.sql", + "ac780a590828a37bb153dbf6e7340ff028bd8657907917fdfcc5fda4323c14fb"), + Map.entry( + "V1024__world_canonical_player_admission_hold.sql", + "49c31f8ddc677e609491265c6fc35fbeb8c8d60b7ab9cda7dfee934a64b5ff62"), + Map.entry( + "V1025__canonical_activation_complete_region_evidence.sql", + "b4e3b6332f31464be44311d903ce0bdb1a90e17274fa657b98cb0c6503b13988"), + Map.entry( + "V1026__world_selected_publication_account_binding.sql", + "42b3010f6e7b68626f9a68f7dc79f65a8aec499e360ba5d48038ef6981aaffae"), + Map.entry( + "V1027__world_publication_terminal_account_binding.sql", + "8d0dc990b18cffc3eb19eff3784e5ec42179bb5ec37cb70ff9a8a5949e3dfd6b"), + Map.entry( + "V1028__selected_publication_artifact_inventory.sql", + "8b978acbb65eac2870e47f3c39d0a4af132a06ed7acfedc1d663a5451e6a01aa"), + Map.entry( + "V1029__publication_operation_inventory_v2.sql", + "339ceba9b01c7215ca73a39851e4c1da2a6c0b32f86e6dc539dad83731a1c353"), + Map.entry( + "V1030__world_publication_inventory_projection_precedence.sql", + "d42e3c8959793d0908386068bf52806ef9fefd07068d296b6ffe00dd9079b36a"), + Map.entry( + "V1031__publication_account_order_projection.sql", + "c5fcd5dbca23e5f427d0ad04e6d1484f88784c81c9bcbf8432f269430bd2c993"), + Map.entry( + "V1032__world_selected_inbound_closure_declaration.sql", + "011b926c50748670bbf3f4e113ea56c1cdd514252557c08ea6632eb96e9378df"), + Map.entry( + "V1033__world_selected_publication_inventory_schema_v2.sql", + "cceacb2d57a4875efff197a4bf2c89920cc11a7c606d878478270239ad748654"), + Map.entry( + "V1034__world_selected_closure_schema4_guards.sql", + "fe07f9a870094d8cb3b748095bc0a0cb4be6d7d3958a59a653af1b5a737a4b40"), + Map.entry( + "V1035__world_start_session_execution_terminal_fence.sql", + "a7931633a6e1c5ab03e12cc4026b543c8e64fa4c894f5d5f5fbe343c3c5a24be"), + Map.entry( + "V1036__world_original_start_session_attempt_admission.sql", + "c627a2ffbb7cac690de6abbb07d75911db3aba50abdf4d9924c81b4fa95b7d7c"), + Map.entry( + "V1037__world_launch_captured_catalog_identity.sql", + "c714e5b4c6a01a3d5d713a399d4dc33e2cf4daae4f0abf52015a42a3669e39d5"), + Map.entry( + "V1038__original_start_session_protected_activation.sql", + "030e9990884f08c8e83e133bc4eb315c114e662bbb81a96f9f310563bcfd3a50"), + Map.entry( + "V1039__canonical_activation_preparation_schema.sql", + "b744728b0cda73934bcb69fb6cd4c07c1cb50e516bf11cbd4e218e396017b875"), + Map.entry( + "V1040__world_run_owned_fixture_canonical_association.sql", + "5707339f2f028df888a181b34864acfc87a4a06bc76a5d4c74200a0fa47d2a60"), + Map.entry( + "V1041__world_run_owned_fixed_preset_preparation.sql", + "c702cbb04c60f07fdf319c05a3f14f155c01ae8b0f1c9f5830ca152d5be5fbc4"), + Map.entry( + "V1042__world_canonical_association_required_field_checks.sql", + "670e8c82e4a736a5e645ce3ebb3ee2fb5692d996080b473ec5055885c4d73ebb"), + Map.entry( + "V1042.1__world_execution_terminal_service_schema.sql", + "d64c9ad97a4af81d6fddc4c44da7dc4e9afd87b27e905764094f1f37c7c7bd70"), + Map.entry( + "V1042.2__world_fixed_preset_read_transaction.sql", + "4edc9508e967a7fd0c367e00abab4d9694c5dfbc6c5474aaeda9b1eb561c70aa"), + Map.entry( + "V1042.3__world_fixture_row_mutation_diagnostic.sql", + "7e8e2d531c693d5856ee808c26f7c910d1117fbddf8a9044784b10d4372280f5"), + Map.entry( + "V1042.4__world_fixture_association_owner_copy_checks.sql", + "47d443cd8cf2aa74566476575a96faf7a69466daac2324deb2be4f88095b1c60"), + Map.entry( + "V1042.5__world_fixed_preset_complete_room_readback.sql", + "b32bf71e51132168f385ef6b5042c70d99587ab26ab73927234bda03a66464b8"), + Map.entry( + "V1042.6__world_terminal_binding_and_location_operation_checks.sql", + "87b0c67affa696bda5f2bfafdf533405b90cea01b0c2a5a7de8f79f4ff8eca80"), + Map.entry( + "V1007.1__world_restore_stable_legacy_update_fastpath.sql", + "56efb5521ba235ce413caa8ed6ce54dad2c169064f9478e1d31bf1dd869743ed"), + Map.entry( + "V1009.1__world_restore_stable_legacy_update_fastpath.sql", + "f69c64e8ed47714ccf2ac5548562152f5ee5f64a8b1f0ffaf68c6c5d49f20dad")); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "world_management_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private DSLContext dsl; + @Autowired private PlatformTransactionManager transactionManager; + @Autowired private ObjectMapper objectMapper; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + private Context controlledPeerContext; + private Context previousPeerContext; + + @BeforeEach + void attachControlledGsContext() { + // Stipulated certificate/principal data is not an actual TLS handshake or producer proof. + GrpcPeerCertificateEvidence certificate = mock(GrpcPeerCertificateEvidence.class); + when(certificate.leafSha256()).thenReturn("a".repeat(64)); + controlledPeerContext = + Context.ROOT + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/dev/sa/game-session-service", + "dev", + "game-session-service")) + .withValue(GrpcPeerCertificateEvidence.CONTEXT_KEY, certificate); + previousPeerContext = controlledPeerContext.attach(); + } + + @AfterEach + void detachControlledGsContext() { + controlledPeerContext.detach(previousPeerContext); + } + + @Test + void freshDefaultHistoryRetainsLiteralProtectedArtifactsAndNumericFrontier() throws Exception { + Path root = repositoryRoot(); + Path world = root.resolve("services/world-management-service/src/main/resources/db/migration"); + Path saga = root.resolve("services/common-saga/src/main/resources/db/migration/saga"); + for (var artifacts : List.of(PARENT_MIGRATIONS, PROTECTED_ARTIFACTS)) + for (var artifact : artifacts.entrySet()) { + Path file = world.resolve(artifact.getKey()); + if (!Files.exists(file)) file = saga.resolve(artifact.getKey()); + assertThat( + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(file)))) + .as("literal migration %s", artifact.getKey()) + .isEqualTo(artifact.getValue()); + } + var configured = + migration(dataSource("world_management_service"), "world_management_service", null); + assertThat(configured.getConfiguration().isOutOfOrder()).isFalse(); + configured.validate(); + int resolvedVersionedCount = resolvedVersionedMigrationCount(configured); + assertThat(versions(dsl)).hasSize(resolvedVersionedCount); + assertThat(versions(dsl).subList(34, 40)) + .containsExactly("1003", "1004", "1005", "1006", "1007", "1007.1"); + assertThat(versions(dsl).subList(40, resolvedVersionedCount)) + .containsExactlyElementsOf(remainingVersions()); + } + + @Test + void packageOwnerRejectsMissingWrongNamespaceServiceAndLeafBeforeUpstreamOrSqlEffects() { + var evidence = controlledEvidence(); + var upstreamReads = new AtomicInteger(); + var owner = nativeService(evidence, upstreamReads); + var original = allRows(dsl); + List denied = new ArrayList<>(); + denied.add(Context.ROOT); + for (var selector : + List.of( + List.of( + "spiffe://firemud/ns/dev/sa/entity-management-service", + "dev", + "entity-management-service", + "a".repeat(64)), + List.of( + "spiffe://firemud/ns/other/sa/game-session-service", + "other", + "game-session-service", + "a".repeat(64)), + List.of( + "spiffe://firemud/ns/dev/sa/game-session-service", + "dev", + "game-session-service", + "d".repeat(64)))) { + var certificate = mock(GrpcPeerCertificateEvidence.class); + when(certificate.leafSha256()).thenReturn(selector.get(3)); + denied.add( + Context.ROOT + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity(selector.get(0), selector.get(1), selector.get(2))) + .withValue(GrpcPeerCertificateEvidence.CONTEXT_KEY, certificate)); + } + for (Context context : denied) { + var previous = context.attach(); + try { + assertThatThrownBy(() -> RunOwnedWorldFixtureLifecycleTestFactory.prepare(owner, evidence)) + .isInstanceOf(SecurityException.class); + } finally { + context.detach(previous); + } + } + assertThat(upstreamReads.get()).isZero(); + assertThat(allRows(dsl)).isEqualTo(original); + } + + @Test + void packageOwnerPreparationRestartAndFreshObservationRetainAllRowsAndXmin() { + var evidence = controlledEvidence(); + var prepared = + RunOwnedWorldFixtureLifecycleTestFactory.prepare(nativeService(evidence), evidence); + assertThat(prepared.status()).isEqualTo("PREPARING"); + assertThat(prepared.lifecycleEpoch()).isEqualTo(1L); + var gameSession = evidence.gameSessionAssociation(); + var association = + associationRepository() + .readRunOwnedFixtureAssociation( + evidence, RunOwnedWorldFixtureEvidenceTestFixtures.request(evidence)); + var worldPrivateKeys = association.worldPrivateKeys(); + assertThat(prepared.tenantId()).isEqualTo(gameSession.gameSessionTenantId()); + assertThat(prepared.gameInstanceId()).isEqualTo(gameSession.gameInstanceId()); + assertThat(prepared.versionId()).isEqualTo(evidence.launchDescriptor().versionId()); + assertThat(prepared.tenantId()).isNotEqualTo(worldPrivateKeys.tenantId()); + assertThat(prepared.gameInstanceId()).isNotEqualTo(worldPrivateKeys.gameInstanceId()); + assertThat(prepared.versionId()).isNotEqualTo(worldPrivateKeys.versionId()); + var storedWorldKeys = + dsl.fetchSingle( + "SELECT tenant_id, game_instance_id, version_id FROM world_instance WHERE id = ?", + association.worldInstanceId()); + assertThat(storedWorldKeys.get("tenant_id", Long.class)).isEqualTo(worldPrivateKeys.tenantId()); + assertThat(storedWorldKeys.get("game_instance_id", Long.class)) + .isEqualTo(worldPrivateKeys.gameInstanceId()); + assertThat(storedWorldKeys.get("version_id", Long.class)) + .isEqualTo(worldPrivateKeys.versionId()); + assertThat( + scalarLong( + "SELECT row_version FROM world_instance WHERE id = ?", + association.worldInstanceId())) + .isZero(); + assertPresetContent(association); + var original = allRows(dsl); + var fresh = RunOwnedWorldFixtureEvidenceTestFixtures.freshObservation(evidence); + var replay = RunOwnedWorldFixtureLifecycleTestFactory.prepare(nativeService(fresh), fresh); + assertThat(replay).isEqualTo(prepared); + assertThat(replay.tenantId()).isEqualTo(gameSession.gameSessionTenantId()); + assertThat(replay.gameInstanceId()).isEqualTo(gameSession.gameInstanceId()); + assertThat(replay.versionId()).isEqualTo(evidence.launchDescriptor().versionId()); + assertThat( + dsl.fetchSingle( + "SELECT tenant_id, game_instance_id, version_id FROM world_instance WHERE id = ?", + association.worldInstanceId()) + .intoMap()) + .containsEntry("tenant_id", worldPrivateKeys.tenantId()) + .containsEntry("game_instance_id", worldPrivateKeys.gameInstanceId()) + .containsEntry("version_id", worldPrivateKeys.versionId()); + assertThat(allRows(dsl)).isEqualTo(original); + var changed = RunOwnedWorldFixtureEvidenceTestFixtures.changedReceiptBytes(evidence); + assertThatThrownBy( + () -> RunOwnedWorldFixtureLifecycleTestFactory.prepare(nativeService(changed), changed)) + .isInstanceOf( + WorldCanonicalInstanceAssociationRepository.RegistrationConflictException.class); + var second = RunOwnedWorldFixtureEvidenceTestFixtures.secondAssignment(evidence); + assertThatThrownBy( + () -> RunOwnedWorldFixtureLifecycleTestFactory.prepare(nativeService(second), second)) + .isInstanceOf( + WorldCanonicalInstanceAssociationRepository.RegistrationConflictException.class); + assertThat(allRows(dsl)).isEqualTo(original); + assertNoPendingManifests(association.worldInstanceId()); + } + + @Test + void fixtureAssociationRejectsEveryWorldCopyMismatchThroughTheOwnerTransaction() { + var retainedEvidence = controlledEvidence(); + RunOwnedWorldFixtureLifecycleTestFactory.prepare( + nativeService(retainedEvidence), retainedEvidence); + + var evidence = controlledEvidence(); + var sourceRepository = new WorldAuthoredSourceIntakeRepository(dsl); + var versionRepository = new WorldAuthoredVersionIdentityRepository(dsl); + var source = + Objects.requireNonNull( + ownerTransaction() + .execute( + status -> + sourceRepository.acceptFresh( + "dev", UUID.randomUUID(), evidence.sourceReceipt().sourceEvidence()))); + var state = + AuthoredWorldVersionStateEvidence.create( + new AuthoredWorldVersionStateEvidence.Request( + 1, + "dev", + UUID.randomUUID(), + source.canonicalTenantId(), + source.worldSlug(), + source.sourceOperationId(), + source.sourceEvidenceDigest(), + evidence.launchDescriptor().versionId()), + source.source(), + evidence.gameSessionAssociation().canonicalVersionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + evidence.launchDescriptor().versionStateEpoch()); + var version = + Objects.requireNonNull( + ownerTransaction().execute(status -> versionRepository.acceptFresh(source, state))); + var gs = evidence.gameSessionAssociation(); + var descriptor = evidence.launchDescriptor(); + var request = + new PreparedWorldInstanceRequest( + gs.gameSessionTenantId(), + gs.gameInstanceId(), + descriptor.gameTemplateId(), + evidence.capability().operationId(), + descriptor.launchDescriptorId(), + descriptor.versionId(), + null, + descriptor.runtimeFlagsJson(), + descriptor.generationConfigRevision(), + descriptor.releaseBundleId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + null); + var associationRepository = associationRepository(); + var fenceRepository = new WorldDesignPublicationFenceRepository(dsl, sourceRepository); + + String schema = dsl.fetchSingle("SELECT current_schema()").get(0, String.class); + String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 8); + String functionName = "world_test_fixture_copy_mutation_" + suffix; + String triggerName = "trg_world_canonical_instance_association_01_test_copy_" + suffix; + String function = DSL.name(schema, functionName).toString(); + String associationTable = DSL.name(schema, "world_canonical_instance_association").toString(); + String createFunction = + """ + CREATE FUNCTION __test_function__() RETURNS TRIGGER + LANGUAGE plpgsql + AS $test$ + DECLARE + mismatch_field TEXT := current_setting('world.fixture_copy_mismatch_field', TRUE); + BEGIN + IF TG_OP = 'INSERT' AND NEW.schema_version = 3 + AND NEW.canonical_authority_kind = 'RUN_OWNED_FIXTURE' + AND mismatch_field IS NOT NULL THEN + CASE mismatch_field + WHEN 'canonical_realm_id' THEN NEW.canonical_realm_id := pg_catalog.gen_random_uuid(); + WHEN 'catalog_revision' THEN NEW.catalog_revision := NEW.catalog_revision + 1; + WHEN 'playtest_lifecycle_id' THEN NEW.playtest_lifecycle_id := pg_catalog.gen_random_uuid(); + WHEN 'playtest_state_generation' THEN NEW.playtest_state_generation := COALESCE(NEW.playtest_state_generation, 0) + 1; + WHEN 'script_patch_version' THEN NEW.script_patch_version := COALESCE(NEW.script_patch_version, 'fixture-copy-mismatch') || '-mutated'; + WHEN 'runtime_flags_json' THEN NEW.runtime_flags_json := NEW.runtime_flags_json || ' '; + WHEN 'generation_config_revision' THEN NEW.generation_config_revision := NEW.generation_config_revision || '-mutated'; + WHEN 'release_bundle_id' THEN NEW.release_bundle_id := NEW.release_bundle_id + 1; + WHEN 'published_release_bundle_ref' THEN NEW.published_release_bundle_ref := NEW.published_release_bundle_ref || '-mutated'; + WHEN 'remap_set_id' THEN NEW.remap_set_id := COALESCE(NEW.remap_set_id, 'fixture-copy-mismatch') || '-mutated'; + ELSE RAISE EXCEPTION 'Unknown fixture copy mutation field'; + END CASE; + END IF; + RETURN NEW; + END; + $test$ + """ + .replace("__test_function__", function); + String trigger = + "CREATE TRIGGER " + + DSL.name(triggerName) + + " BEFORE INSERT ON " + + associationTable + + " FOR EACH ROW EXECUTE FUNCTION " + + function + + "()"; + + try { + dsl.execute(createFunction); + dsl.execute(trigger); + var beforeInsertTriggers = + dsl.fetch( + "SELECT tgname FROM pg_trigger WHERE tgrelid = ?::REGCLASS " + + "AND NOT tgisinternal AND (tgtype & 7) = 7 ORDER BY tgname", + associationTable) + .getValues(0, String.class); + String executionGuard = "trg_world_canonical_instance_association_00_execution"; + String ownerCopyValidator = "trg_world_canonical_instance_association_exact_insert"; + assertThat(beforeInsertTriggers) + .as("real manifest guard, injected row mutation, then owner-copy validator") + .contains(executionGuard, triggerName, ownerCopyValidator); + assertThat(beforeInsertTriggers.indexOf(executionGuard)) + .isLessThan(beforeInsertTriggers.indexOf(triggerName)); + assertThat(beforeInsertTriggers.indexOf(triggerName)) + .isLessThan(beforeInsertTriggers.indexOf(ownerCopyValidator)); + + var originalRows = allRows(dsl); + for (String field : + List.of( + "canonical_realm_id", + "catalog_revision", + "playtest_lifecycle_id", + "playtest_state_generation", + "script_patch_version", + "runtime_flags_json", + "generation_config_revision", + "release_bundle_id", + "published_release_bundle_ref", + "remap_set_id")) { + assertSqlState( + () -> + ownerTransaction() + .executeWithoutResult( + status -> { + dsl.fetchOne( + "SELECT set_config('world.fixture_copy_mismatch_field', ?, TRUE)", + field); + fenceRepository.lockOpen(binding(source, version)); + associationRepository.allocateRunOwnedFixtureInOwnerTransaction( + evidence, request, source, version); + }), + "23514", + "Run-owned fixture association differs from its exact World, source, Version, or GS owner readback"); + assertThat(allRows(dsl)) + .as("original rows and xmin after %s owner-copy mismatch", field) + .isEqualTo(originalRows); + } + } finally { + dsl.execute("DROP TRIGGER IF EXISTS " + DSL.name(triggerName) + " ON " + associationTable); + dsl.execute("DROP FUNCTION IF EXISTS " + function + "()"); + } + } + + @Test + void racingActualPackageOwnersConvergeOneOriginalAllocation() throws Exception { + var evidence = controlledEvidence(); + var firstOwner = nativeService(evidence); + var secondOwner = nativeService(evidence); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch release = new CountDownLatch(1); + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = + executor.submit( + () -> + withControlledPeer( + () -> { + ready.countDown(); + await(release); + return RunOwnedWorldFixtureLifecycleTestFactory.prepare( + firstOwner, evidence); + })); + Future second = + executor.submit( + () -> + withControlledPeer( + () -> { + ready.countDown(); + await(release); + return RunOwnedWorldFixtureLifecycleTestFactory.prepare( + secondOwner, evidence); + })); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + release.countDown(); + assertThat(first.get(30, TimeUnit.SECONDS)).isEqualTo(second.get(30, TimeUnit.SECONDS)); + } finally { + release.countDown(); + } + assertThat( + scalarLong( + "SELECT count(*) FROM world_canonical_instance_association WHERE control_plane_request_id = ?", + evidence.capability().operationId())) + .isEqualTo(1L); + var association = + associationRepository() + .readRunOwnedFixtureAssociation( + evidence, RunOwnedWorldFixtureEvidenceTestFixtures.request(evidence)); + assertPresetContent(association); + assertNoPendingManifests(association.worldInstanceId()); + } + + @Test + void actualOwnerRollbackLeavesNoAllocationTopologyResultOrManifest() { + var evidence = controlledEvidence(); + var sourceOwner = new WorldAuthoredSourceIntakeRepository(dsl); + var versionOwner = new WorldAuthoredVersionIdentityRepository(dsl); + var intake = + ownerTransaction() + .execute( + status -> + sourceOwner.acceptFresh( + "dev", UUID.randomUUID(), evidence.sourceReceipt().sourceEvidence())); + var state = + AuthoredWorldVersionStateEvidence.create( + new AuthoredWorldVersionStateEvidence.Request( + 1, + "dev", + UUID.randomUUID(), + intake.canonicalTenantId(), + intake.worldSlug(), + intake.sourceOperationId(), + intake.sourceEvidenceDigest(), + evidence.launchDescriptor().versionId()), + intake.source(), + evidence.gameSessionAssociation().canonicalVersionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + evidence.launchDescriptor().versionStateEpoch()); + var version = ownerTransaction().execute(status -> versionOwner.acceptFresh(intake, state)); + var original = allRows(dsl); + assertThatThrownBy( + () -> + ownerTransaction() + .executeWithoutResult( + status -> { + new WorldDesignPublicationFenceRepository(dsl, sourceOwner) + .lockOpen(binding(intake, version)); + var allocated = + associationRepository() + .allocateRunOwnedFixtureInOwnerTransaction( + evidence, + RunOwnedWorldFixtureEvidenceTestFixtures.request(evidence), + intake, + version); + RunOwnedWorldFixedPresetResources.materialize( + dsl, + evidence, + RunOwnedWorldFixedPresetResources.plan(allocated, intake, version), + allocated.worldInstanceId(), + allocated.worldPrivateKeys().gameInstanceId()); + throw new IllegalStateException( + "controlled failure after actual topology writes"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("controlled failure after actual topology writes"); + assertThat(allRows(dsl)).isEqualTo(original); + // PostgreSQL sequences are nontransactional; this compares all rows/xmin and manifests. + } + + @Test + void actualFixtureMaterializationRetainsUnderOwnerSavepoint() { + var evidence = controlledEvidence(); + var sourceOwner = new WorldAuthoredSourceIntakeRepository(dsl); + var versionOwner = new WorldAuthoredVersionIdentityRepository(dsl); + var intake = + ownerTransaction() + .execute( + status -> + sourceOwner.acceptFresh( + "dev", UUID.randomUUID(), evidence.sourceReceipt().sourceEvidence())); + var state = + AuthoredWorldVersionStateEvidence.create( + new AuthoredWorldVersionStateEvidence.Request( + 1, + "dev", + UUID.randomUUID(), + intake.canonicalTenantId(), + intake.worldSlug(), + intake.sourceOperationId(), + intake.sourceEvidenceDigest(), + evidence.launchDescriptor().versionId()), + intake.source(), + evidence.gameSessionAssociation().canonicalVersionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + evidence.launchDescriptor().versionStateEpoch()); + var version = ownerTransaction().execute(status -> versionOwner.acceptFresh(intake, state)); + var fixtureAssociations = + new WorldCanonicalInstanceAssociationRepository( + dsl, new WorldCompleteLaunchBindingRepository(dsl), sourceOwner, versionOwner); + var fixtureFence = new WorldDesignPublicationFenceRepository(dsl, sourceOwner); + var fixtureRequest = RunOwnedWorldFixtureEvidenceTestFixtures.request(evidence); + var allocatedFixture = + ownerTransaction() + .execute( + status -> { + fixtureFence.lockOpen(binding(intake, version)); + return fixtureAssociations.allocateRunOwnedFixtureInOwnerTransaction( + evidence, fixtureRequest, intake, version); + }); + var fixtureAssociation = + fixtureAssociations.readRunOwnedFixtureAssociation(evidence, fixtureRequest); + var fixturePlan = RunOwnedWorldFixedPresetResources.plan(fixtureAssociation, intake, version); + var savepoint = new TransactionTemplate(transactionManager); + savepoint.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); + savepoint.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + + var materialized = + ownerTransaction() + .execute( + status -> { + var result = + savepoint.execute( + nestedStatus -> + RunOwnedWorldFixedPresetResources.materialize( + dsl, + evidence, + fixturePlan, + allocatedFixture.worldInstanceId(), + allocatedFixture.worldPrivateKeys().gameInstanceId())); + var preparationStamp = + dsl.fetchSingle( + "SELECT p.preparation_inserted_full_xid::text, p.xmin::text, " + + "pg_current_xact_id()::text, " + + "(txid_current() % 4294967296)::text " + + "FROM world_canonical_instance_preparation p " + + "WHERE p.world_instance_id = ?", + allocatedFixture.worldInstanceId()); + assertThat(preparationStamp.get(0, String.class)) + .as("the BEFORE INSERT server stamp records the top-level full XID") + .isEqualTo(preparationStamp.get(2, String.class)); + assertThat(preparationStamp.get(1, String.class)) + .as("the row inserted beneath the owner savepoint keeps its child xmin") + .isNotEqualTo(preparationStamp.get(3, String.class)); + return result; + }); + assertThat(materialized).isNotNull(); + assertThat(materialized.regionCount()).isEqualTo(1); + assertThat(materialized.zoneCount()).isEqualTo(1); + assertThat(materialized.roomCount()).isEqualTo(2); + assertThat(materialized.exitCount()).isEqualTo(2); + assertThat( + scalarLong( + "SELECT count(*) FROM world_canonical_instance_preparation " + + "WHERE world_instance_id = ?", + allocatedFixture.worldInstanceId())) + .isEqualTo(1L); + assertThat( + scalarLong( + "SELECT count(*) FROM world_canonical_instance_preparation_execution_manifest " + + "WHERE fixture_world_instance_id = ?", + allocatedFixture.worldInstanceId())) + .isZero(); + assertNoPendingManifests(allocatedFixture.worldInstanceId()); + } + + @Test + void fixturePreparingCannotActivateAcquireHoldsPlaceActorsOrReuseConsumedManifests() + throws Exception { + var evidence = controlledEvidence(); + RunOwnedWorldFixtureLifecycleTestFactory.prepare(nativeService(evidence), evidence); + var association = + associationRepository() + .readRunOwnedFixtureAssociation( + evidence, RunOwnedWorldFixtureEvidenceTestFixtures.request(evidence)); + long id = association.worldInstanceId(); + var original = allRows(dsl); + for (String status : List.of("ACTIVE", "FAILED_PRE_ACTIVATION", "TERMINATING")) + assertSqlState( + () -> + dsl.execute( + "UPDATE world_instance SET status = ?, lifecycle_epoch = 2, row_version = 1 WHERE id = ?", + status, + id), + "23514"); + assertSqlState( + () -> + dsl.execute( + "INSERT INTO world_instance SELECT (jsonb_populate_record(NULL::world_instance, to_jsonb(w) || jsonb_build_object('id', ?, 'status', 'ACTIVE'))).* FROM world_instance w WHERE id = ?", + positiveLong(), + id), + "23514"); + assertThatThrownBy( + () -> + associationRepository() + .activateRunOwnedFixtureInOwnerTransaction(association, 1L, 0L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageStartingWith("RUN_OWNED_WORLD_ACTIVATION_UNAVAILABLE:"); + assertThat( + dsl.fetchSingle( + "SELECT to_regprocedure(?)", + dsl.fetchSingle("SELECT current_schema()").get(0, String.class) + + ".world_activate_run_owned_fixture_instance(bigint,bigint,bigint)") + .get(0)) + .isNull(); + assertThat( + ownerTransaction() + .execute( + status -> + dsl.fetchSingle( + "SELECT world_consume_canonical_prepare_execution_manifest('world_instance','INSERT',NULL,to_jsonb(w)) FROM world_instance w WHERE id = ?", + id) + .get(0, Boolean.class))) + .isFalse(); + assertThat( + ownerTransaction() + .execute( + status -> + dsl.fetchSingle( + "SELECT world_consume_region_execution_manifest('region','INSERT',NULL,to_jsonb(r)) FROM region r WHERE tenant_id = ? AND version_id = ?", + association.worldPrivateKeys().tenantId(), + association.worldPrivateKeys().versionId()) + .get(0, Boolean.class))) + .isFalse(); + for (String table : + List.of( + "world_canonical_initial_player_location_operation", + "character_location", + "world_canonical_player_admission_hold")) + for (boolean omitCanonical : List.of(false, true)) { + Map selectors = new LinkedHashMap<>(); + selectors.put("world_instance_id", omitCanonical ? id : null); + selectors.put( + "canonical_game_instance_id", + omitCanonical ? null : association.identity().canonicalGameInstanceId().toString()); + assertSqlState( + () -> + dsl.execute( + "INSERT INTO " + + DSL.name(table) + + " SELECT (jsonb_populate_record(NULL::" + + DSL.name(table) + + ", ?::jsonb)).*", + json(selectors)), + "23514", + "disabled"); + } + for (boolean omitCanonical : List.of(false, true)) { + Map selectors = new LinkedHashMap<>(); + selectors.put( + "canonical_game_instance_id", + omitCanonical ? null : association.identity().canonicalGameInstanceId().toString()); + selectors.put("tenant_id", omitCanonical ? association.worldPrivateKeys().tenantId() : null); + selectors.put( + "game_instance_id", + omitCanonical ? association.worldPrivateKeys().gameInstanceId() : null); + selectors.put( + "version_id", omitCanonical ? association.worldPrivateKeys().versionId() : null); + assertSqlState( + () -> + dsl.execute( + "INSERT INTO initial_admission_bind_hold SELECT (jsonb_populate_record(NULL::initial_admission_bind_hold, ?::jsonb)).*", + json(selectors)), + "23514", + "disabled"); + } + assertSqlState( + () -> + ownerTransaction() + .executeWithoutResult( + status -> + dsl.fetch( + "SELECT world_finalize_canonical_initial_admission_hold(NULL::uuid,NULL::uuid,'COMMITTED',NULL::text,NULL::text,NULL::text,NULL::bigint,NULL::timestamptz,false,NULL::bytea,NULL::text)")), + "23514", + "terminal proof is incomplete"); + // Invalid controlled bytes with a correct byte digest only pass the preliminary digest + // check. They are not owner proof or permission to create a fixture hold; NULL selectors + // must then fail before any candidate, World row or hold can be locked or changed. + byte[] invalidControlledProbe = "{}".getBytes(StandardCharsets.UTF_8); + String invalidControlledProbeDigest = + "sha256:" + + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(invalidControlledProbe)); + assertSqlState( + () -> + ownerTransaction() + .executeWithoutResult( + status -> + dsl.fetch( + "SELECT world_finalize_canonical_initial_admission_hold(NULL::uuid,NULL::uuid,'COMMITTED',NULL::text,NULL::text,NULL::text,NULL::bigint,TIMESTAMPTZ '2026-10-14T00:00:00Z',false,?::bytea,?::text)", + invalidControlledProbe, + invalidControlledProbeDigest)), + "55000", + "hold identity is missing or untyped"); + assertThat(allRows(dsl)).isEqualTo(original); + assertNoPendingManifests(id); + // First OPEN is GS-owned; no manufactured World table, hold or terminal is introduced. + } + + @Test + void installed34ThroughParent40ToDefaultFrontierRetainsRowsXminAndStableLegacyUpdates() + throws Exception { + String schema = "world_fixture_upgrade_" + UUID.randomUUID().toString().replace("-", ""); + var source = dataSource(schema); + var connection = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + try { + var installed = migration(source, schema, "1002"); + assertThat(installed.getConfiguration().isOutOfOrder()).isFalse(); + installed.migrate(); + installed.validate(); + assertThat(versions(connection)).hasSize(34); + assertThat( + connection + .fetch("SELECT script FROM " + DSL.name(HISTORY) + " WHERE version IS NOT NULL") + .getValues(0, String.class)) + .containsExactlyInAnyOrderElementsOf(PARENT_MIGRATIONS.keySet()); + long worldId = + connection + .fetchSingle( + "INSERT INTO world_instance (tenant_id, game_instance_id, game_template_id, control_plane_request_id, launch_descriptor_id, version_id, runtime_flags_json, generation_config_revision, release_bundle_id, published_release_bundle_ref, version_state_epoch, status) VALUES (7001,8101,17,'retained-parent-world','retained-parent-descriptor',11,'{}','parent-generation',77,'retained-parent-release',3,'PREPARING') RETURNING id") + .get(0, Long.class); + long firstRegion = + connection + .fetchSingle( + "INSERT INTO region_instance (tenant_id, game_instance_id, world_instance_id, name, generation_seed) VALUES (7001,8101,?,'Retained parent region',42) RETURNING id", + worldId) + .get(0, Long.class); + long secondRegion = + connection + .fetchSingle( + "INSERT INTO region_instance (tenant_id, game_instance_id, world_instance_id, name, generation_seed) VALUES (7001,8101,?,'Independent parent region',43) RETURNING id", + worldId) + .get(0, Long.class); + long sagaId = + connection + .fetchSingle( + "INSERT INTO saga_instance (saga_name,state) VALUES ('retained-parent-saga','PENDING') RETURNING id") + .get(0, Long.class); + connection.execute( + "INSERT INTO saga_step (instance_id,name,status,attempt) VALUES (?,'retained-parent-step','PENDING',2)", + sagaId); + var write = new TransactionTemplate(new DataSourceTransactionManager(source)); + write.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var evidence = controlledEvidence(); + var sourceOwner = new WorldAuthoredSourceIntakeRepository(connection); + var versionOwner = new WorldAuthoredVersionIdentityRepository(connection); + UUID intakeRequest = UUID.randomUUID(); + var intake = + Objects.requireNonNull( + write.execute( + status -> + sourceOwner.acceptFresh( + "dev", intakeRequest, evidence.sourceReceipt().sourceEvidence()))); + var state = + AuthoredWorldVersionStateEvidence.create( + new AuthoredWorldVersionStateEvidence.Request( + 1, + "dev", + UUID.randomUUID(), + intake.canonicalTenantId(), + intake.worldSlug(), + intake.sourceOperationId(), + intake.sourceEvidenceDigest(), + evidence.launchDescriptor().versionId()), + intake.source(), + evidence.gameSessionAssociation().canonicalVersionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + evidence.launchDescriptor().versionStateEpoch()); + var version = + Objects.requireNonNull(write.execute(status -> versionOwner.acceptFresh(intake, state))); + Map> originalColumns = new LinkedHashMap<>(); + Map> originalRows = new LinkedHashMap<>(); + for (String table : + List.of( + "world_authored_source_tenant_association", + "world_authored_source_tenant_key_reservation", + "world_authored_source_intake", + "world_authored_version_identity", + "world_instance", + "region_instance", + "saga_instance", + "saga_step")) { + var columns = + connection + .fetch( + "SELECT column_name FROM information_schema.columns WHERE table_schema = ? AND table_name = ? ORDER BY ordinal_position", + schema, + table) + .getValues(0, String.class); + assertThat(columns).isNotEmpty(); + originalColumns.put(table, columns); + originalRows.put(table, retainedRows(connection, schema, table, columns)); + assertThat(originalRows.get(table)).isNotEmpty(); + } + var installedHistory = history(connection); + var parent = migration(source, schema, "1007.1"); + parent.migrate(); + parent.validate(); + assertThat(versions(connection)).hasSize(40); + assertThat(versions(connection).subList(34, 40)) + .containsExactly("1003", "1004", "1005", "1006", "1007", "1007.1"); + assertThat(history(connection).subList(0, 34)).isEqualTo(installedHistory); + for (var entry : originalColumns.entrySet()) + assertThat(retainedRows(connection, schema, entry.getKey(), entry.getValue())) + .isEqualTo(originalRows.get(entry.getKey())); + var parentHistory = history(connection); + var preparing = migration(source, schema, "1041"); + preparing.migrate(); + preparing.validate(); + assertThat(preparing.getConfiguration().isOutOfOrder()).isFalse(); + assertThat(versions(connection)).hasSize(75); + assertThat(versions(connection).subList(40, 75)) + .containsExactlyElementsOf(remainingVersionsThrough(1041)); + assertThat(history(connection).subList(0, 40)).isEqualTo(parentHistory); + for (var entry : originalColumns.entrySet()) + assertThat(retainedRows(connection, schema, entry.getKey(), entry.getValue())) + .isEqualTo(originalRows.get(entry.getKey())); + + // Create and materialize a controlled schema-3 fixture through the existing World owners at + // the V1041 checkpoint, then preserve that real fixture while advancing to V1042.8. + var fixtureAssociations = + new WorldCanonicalInstanceAssociationRepository( + connection, + new WorldCompleteLaunchBindingRepository(connection), + sourceOwner, + versionOwner); + var fixtureFence = new WorldDesignPublicationFenceRepository(connection, sourceOwner); + var gsAssociation = evidence.gameSessionAssociation(); + var descriptor = evidence.launchDescriptor(); + var fixtureRequest = + new PreparedWorldInstanceRequest( + gsAssociation.gameSessionTenantId(), + gsAssociation.gameInstanceId(), + descriptor.gameTemplateId(), + evidence.capability().operationId(), + descriptor.launchDescriptorId(), + descriptor.versionId(), + null, + descriptor.runtimeFlagsJson(), + descriptor.generationConfigRevision(), + descriptor.releaseBundleId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + null); + WorldCanonicalInstanceAssociation allocatedFixture = + write.execute( + status -> { + fixtureFence.lockOpen(binding(intake, version)); + return fixtureAssociations.allocateRunOwnedFixtureInOwnerTransaction( + evidence, fixtureRequest, intake, version); + }); + assertThat(allocatedFixture).isNotNull(); + var fixtureAssociation = + fixtureAssociations.readRunOwnedFixtureAssociation(evidence, fixtureRequest); + var fixturePlan = RunOwnedWorldFixedPresetResources.plan(fixtureAssociation, intake, version); + write.executeWithoutResult( + status -> + RunOwnedWorldFixedPresetResources.materialize( + connection, + evidence, + fixturePlan, + fixtureAssociation.worldInstanceId(), + fixtureAssociation.worldPrivateKeys().gameInstanceId())); + var preparedFixture = + connection.fetchSingle( + "SELECT status, lifecycle_epoch, row_version FROM world_instance WHERE id = ?", + fixtureAssociation.worldInstanceId()); + assertThat(preparedFixture.get(0, String.class)).isEqualTo("PREPARING"); + assertThat(preparedFixture.get(1, Long.class)).isEqualTo(1L); + assertThat(preparedFixture.get(2, Long.class)).isZero(); + assertThat( + connection + .fetchSingle( + "SELECT count(*) FROM world_canonical_instance_association WHERE world_instance_id = ? AND schema_version = 3 AND canonical_authority_kind = 'RUN_OWNED_FIXTURE'", + fixtureAssociation.worldInstanceId()) + .get(0, Long.class)) + .isEqualTo(1L); + String retainedPreparationAt10428 = + connection + .fetchSingle( + "SELECT (to_jsonb(p) - 'preparation_inserted_full_xid')::text " + + "|| ':xmin=' || p.xmin::text " + + "FROM world_canonical_instance_preparation p WHERE p.world_instance_id = ?", + fixtureAssociation.worldInstanceId()) + .get(0, String.class); + + var through10428 = migration(source, schema, "1042.8"); + through10428.migrate(); + through10428.validate(); + assertThat(through10428.getConfiguration().isOutOfOrder()).isFalse(); + assertThat(versions(connection)).contains("1042.8").doesNotContain("1042.9"); + String preservedPublicationRequestId = "pre-v1042-9-null-stamp"; + var preservedWorkflow = + PublicationDigestRequestBinding.full( + intake.canonicalTenantId().toString(), + Long.toString(version.gameDesignVersionId()), + preservedPublicationRequestId) + .derivedWorkflowIdentity(); + UUID preservedPublicationFence = UUID.randomUUID(); + connection.execute( + "INSERT INTO world_design_publication_fence_attempt " + + "(publication_fence, target_namespace, canonical_tenant_id, local_tenant_key, " + + "version_id, intake_operation_id, intake_request_id, source_operation_id, " + + "source_evidence_digest, intake_receipt_digest, publication_request_id, " + + "request_digest, version_state_epoch, publish_workflow_id, applied_commit_id, " + + "content_digest, digest_schema_version, owner_binding_schema_version, " + + "canonical_version_id, version_identity_operation_id, game_design_version_id, " + + "intake_request_digest, attempt_created_full_xid) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 3, 1, ?, ?, ?, ?, NULL)", + preservedPublicationFence, + intake.targetNamespace(), + intake.canonicalTenantId(), + intake.localTenantKey(), + version.localVersionKey(), + intake.operationId(), + intake.intakeRequestId(), + intake.sourceOperationId(), + intake.sourceEvidenceDigest(), + intake.receiptDigest(), + preservedPublicationRequestId, + "a".repeat(64), + evidence.launchDescriptor().versionStateEpoch(), + preservedWorkflow, + "retained-null-stamp-commit", + "b".repeat(64), + version.canonicalVersionId(), + version.operationId(), + version.gameDesignVersionId(), + intake.requestDigest()); + assertThat( + connection + .fetchSingle( + "SELECT attempt_created_full_xid::text FROM world_design_publication_fence_attempt " + + "WHERE publication_fence = ?", + preservedPublicationFence) + .get(0, String.class)) + .isNull(); + String preservedForgedRequestId = "pre-v1042-9-forged-stamp"; + var preservedForgedWorkflow = + PublicationDigestRequestBinding.full( + intake.canonicalTenantId().toString(), + Long.toString(version.gameDesignVersionId()), + preservedForgedRequestId) + .derivedWorkflowIdentity(); + UUID preservedForgedPublicationFence = UUID.randomUUID(); + connection.execute( + "INSERT INTO world_design_publication_fence_attempt " + + "(publication_fence, target_namespace, canonical_tenant_id, local_tenant_key, " + + "version_id, intake_operation_id, intake_request_id, source_operation_id, " + + "source_evidence_digest, intake_receipt_digest, publication_request_id, " + + "request_digest, version_state_epoch, publish_workflow_id, applied_commit_id, " + + "content_digest, digest_schema_version, owner_binding_schema_version, " + + "canonical_version_id, version_identity_operation_id, game_design_version_id, " + + "intake_request_digest, attempt_created_full_xid) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 3, 1, ?, ?, ?, ?, ?::xid8)", + preservedForgedPublicationFence, + intake.targetNamespace(), + intake.canonicalTenantId(), + intake.localTenantKey(), + version.localVersionKey(), + intake.operationId(), + intake.intakeRequestId(), + intake.sourceOperationId(), + intake.sourceEvidenceDigest(), + intake.receiptDigest(), + preservedForgedRequestId, + "c".repeat(64), + evidence.launchDescriptor().versionStateEpoch(), + preservedForgedWorkflow, + "retained-forged-stamp-commit", + "d".repeat(64), + version.canonicalVersionId(), + version.operationId(), + version.gameDesignVersionId(), + intake.requestDigest(), + "9223372036854775807"); + assertThat( + connection + .fetchSingle( + "SELECT attempt_created_full_xid::text FROM world_design_publication_fence_attempt " + + "WHERE publication_fence = ?", + preservedForgedPublicationFence) + .get(0, String.class)) + .isEqualTo("9223372036854775807"); + int versionedCountAt10428 = versions(connection).size(); + var retainedRowsAt10428 = new LinkedHashMap<>(allRows(connection)); + retainedRowsAt10428.remove(HISTORY); + var historyAt10428 = history(connection); + Map sameTransactionFunctionMetadata = new LinkedHashMap<>(); + for (String function : + List.of( + "world_validate_selected_publication_account_binding()", + "world_validate_selected_publication_artifact_inventory()", + "world_retain_preparation_start_location()", + "world_guard_preparation_start_location()", + "world_require_preparation_start_location(jsonb,jsonb,uuid)")) + sameTransactionFunctionMetadata.put( + function, + connection + .fetchSingle( + "SELECT jsonb_build_array(oid::text, proowner::text, prosecdef::text, " + + "proconfig::text, proacl::text)::text FROM pg_proc " + + "WHERE oid = to_regprocedure(?)", + schema + "." + function) + .get(0, String.class)); + Map sameTransactionTriggerMetadata = new LinkedHashMap<>(); + for (String trigger : + List.of( + "trg_world_publication_account_binding_validate", + "trg_world_publication_account_binding_immutable", + "trg_world_publication_account_binding_no_truncate", + "trg_world_selected_publication_artifact_inventory_validate", + "trg_world_selected_publication_artifact_inventory_immutable", + "trg_world_selected_publication_artifact_inventory_no_truncate", + "trg_world_preparation_retain_start_location", + "trg_world_preparation_start_location_guard", + "trg_world_preparation_start_location_no_truncate")) + sameTransactionTriggerMetadata.put( + trigger, + connection + .fetchSingle( + "SELECT jsonb_build_array(t.oid::text, t.tgfoid::text, t.tgtype::text, " + + "t.tgenabled::text, encode(t.tgargs, 'hex'), " + + "pg_get_expr(t.tgqual, t.tgrelid))::text " + + "FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid " + + "WHERE c.relnamespace = to_regnamespace(?) AND t.tgname = ?", + schema, + trigger) + .get(0, String.class)); + String guardProcedure = schema + ".world_guard_canonical_activation_transition()"; + var originalGuardIdentity = + connection.fetchSingle( + "SELECT oid::text, proowner::text, prosecdef, proconfig::text, proacl::text FROM pg_proc WHERE oid = to_regprocedure(?)", + guardProcedure); + var originalGuardTrigger = + connection.fetchSingle( + "SELECT t.oid::text, t.tgfoid::text, t.tgtype, t.tgenabled, t.tgargs::text, t.tgqual::text " + + "FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid " + + "WHERE c.relnamespace = to_regnamespace(?) AND t.tgname = 'trg_world_canonical_activation_transition'", + schema); + var full = migration(source, schema, null); + full.migrate(); + full.validate(); + assertThat(full.getConfiguration().isOutOfOrder()).isFalse(); + int resolvedVersionedCount = resolvedVersionedMigrationCount(full); + assertThat(versions(connection)).hasSize(resolvedVersionedCount); + assertThat(versions(connection).subList(40, resolvedVersionedCount)) + .containsExactlyElementsOf(remainingVersions()); + assertThat(history(connection).subList(0, 40)).isEqualTo(parentHistory); + assertThat(history(connection).subList(0, versionedCountAt10428)).isEqualTo(historyAt10428); + assertThat( + connection + .fetchSingle( + "SELECT attempt_created_full_xid::text FROM world_design_publication_fence_attempt " + + "WHERE publication_fence = ?", + preservedPublicationFence) + .get(0, String.class)) + .isNull(); + assertThat( + connection + .fetchSingle( + "SELECT attempt_inserted_full_xid::text FROM world_design_publication_fence_attempt " + + "WHERE publication_fence = ?", + preservedPublicationFence) + .get(0, String.class)) + .isNull(); + assertThat( + connection.fetchSingle( + "SELECT attempt_created_full_xid::text, attempt_inserted_full_xid::text " + + "FROM world_design_publication_fence_attempt WHERE publication_fence = ?", + preservedForgedPublicationFence)) + .as( + "the pre-1042.9 caller-forged stamp is retained while the new server stamp stays NULL") + .satisfies( + row -> { + assertThat(row.get(0, String.class)).isEqualTo("9223372036854775807"); + assertThat(row.get(1, String.class)).isNull(); + }); + assertThat( + connection + .fetchSingle( + "SELECT count(*) FROM world_design_publication_fence_attempt " + + "WHERE attempt_inserted_full_xid IS NOT NULL") + .get(0, Long.class)) + .isZero(); + for (var entry : sameTransactionFunctionMetadata.entrySet()) + assertThat( + connection + .fetchSingle( + "SELECT jsonb_build_array(oid::text, proowner::text, prosecdef::text, " + + "proconfig::text, proacl::text)::text FROM pg_proc " + + "WHERE oid = to_regprocedure(?)", + schema + "." + entry.getKey()) + .get(0, String.class)) + .as("function OID, owner, security, search_path and ACL for %s", entry.getKey()) + .isEqualTo(entry.getValue()); + for (var entry : sameTransactionTriggerMetadata.entrySet()) + assertThat( + connection + .fetchSingle( + "SELECT jsonb_build_array(t.oid::text, t.tgfoid::text, t.tgtype::text, " + + "t.tgenabled::text, encode(t.tgargs, 'hex'), " + + "pg_get_expr(t.tgqual, t.tgrelid))::text " + + "FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid " + + "WHERE c.relnamespace = to_regnamespace(?) AND t.tgname = ?", + schema, + entry.getKey()) + .get(0, String.class)) + .as("existing trigger identity and behavior for %s", entry.getKey()) + .isEqualTo(entry.getValue()); + assertThat( + connection + .fetchSingle( + "SELECT pg_get_functiondef(to_regprocedure(?))", + schema + ".world_guard_preparation_start_location()") + .get(0, String.class)) + .contains("p.preparation_inserted_full_xid=pg_current_xact_id()") + .doesNotContain("p.xmin::TEXT"); + var preparationStampFunction = + connection.fetchSingle( + "SELECT proowner::text, prosecdef, proconfig::text FROM pg_proc " + + "WHERE oid = to_regprocedure(?)", + schema + ".world_stamp_preparation_insert_full_xid()"); + assertThat(preparationStampFunction.get("prosecdef", Boolean.class)).isTrue(); + assertThat(preparationStampFunction.get("proconfig", String.class)) + .contains("pg_catalog") + .contains(schema); + assertThat( + connection + .fetchSingle( + "SELECT count(*) FROM pg_proc p CROSS JOIN LATERAL " + + "aclexplode(COALESCE(p.proacl, acldefault('f', p.proowner))) acl " + + "WHERE p.oid = to_regprocedure(?) AND acl.grantee = 0::oid " + + "AND acl.privilege_type = 'EXECUTE'", + schema + ".world_stamp_preparation_insert_full_xid()") + .get(0, Long.class)) + .as("the preparation stamp trigger function grants no EXECUTE to PUBLIC") + .isZero(); + assertThat( + connection.fetchSingle( + "SELECT t.tgtype::text, t.tgenabled::text, t.tgfoid::text " + + "FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid " + + "WHERE c.relnamespace = to_regnamespace(?) " + + "AND c.relname = 'world_canonical_instance_preparation' " + + "AND t.tgname = 'trg_world_preparation_full_xid_stamp'", + schema)) + .satisfies( + row -> { + assertThat(row.get(0, String.class)).isEqualTo("7"); + assertThat(row.get(1, String.class)).isEqualTo("O"); + assertThat(row.get(2, String.class)) + .isEqualTo( + connection + .fetchSingle( + "SELECT oid::text FROM pg_proc WHERE oid = to_regprocedure(?)", + schema + ".world_stamp_preparation_insert_full_xid()") + .get(0, String.class)); + }); + assertThat( + connection + .fetchSingle( + "SELECT count(*) FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid " + + "WHERE c.relnamespace = to_regnamespace(?) " + + "AND c.relname = 'world_canonical_instance_preparation' " + + "AND NOT t.tgisinternal AND (t.tgtype & 7) = 7", + schema) + .get(0, Long.class)) + .as( + "the exact manifest validator and server stamp are the only BEFORE INSERT row triggers") + .isEqualTo(2L); + assertThat("trg_world_canonical_instance_preparation_exact_insert") + .isLessThan("trg_world_preparation_full_xid_stamp"); + assertThat( + connection + .fetchSingle( + "SELECT preparation_inserted_full_xid::text " + + "FROM world_canonical_instance_preparation WHERE world_instance_id = ?", + fixtureAssociation.worldInstanceId()) + .get(0, String.class)) + .as("a preparation retained before V1042.11 remains unbackfilled") + .isNull(); + assertThat( + connection + .fetchSingle( + "SELECT (to_jsonb(p) - 'preparation_inserted_full_xid')::text " + + "|| ':xmin=' || p.xmin::text " + + "FROM world_canonical_instance_preparation p WHERE p.world_instance_id = ?", + fixtureAssociation.worldInstanceId()) + .get(0, String.class)) + .as("all original preparation columns and xmin survive the V1042.11 upgrade") + .isEqualTo(retainedPreparationAt10428); + for (var entry : originalColumns.entrySet()) + assertThat(retainedRows(connection, schema, entry.getKey(), entry.getValue())) + .as("all original values and xmin for %s", entry.getKey()) + .containsAll(originalRows.get(entry.getKey())); + var retainedRowsAtDefaultFrontierOriginalColumns = + new LinkedHashMap<>(allRowsWithoutNewServerStamps(connection)); + retainedRowsAtDefaultFrontierOriginalColumns.remove(HISTORY); + assertThat(retainedRowsAtDefaultFrontierOriginalColumns) + .as("all retained original row values and xmin from V1042.8 through the V1042.11 repairs") + .isEqualTo(retainedRowsAt10428); + var retainedRowsAtDefaultFrontier = new LinkedHashMap<>(allRows(connection)); + retainedRowsAtDefaultFrontier.remove(HISTORY); + assertThat( + connection.fetchSingle( + "SELECT oid::text, proowner::text, prosecdef, proconfig::text, proacl::text FROM pg_proc WHERE oid = to_regprocedure(?)", + guardProcedure)) + .isEqualTo(originalGuardIdentity); + var installedAccountBinding = + connection + .fetchSingle( + "SELECT pg_get_functiondef(to_regprocedure(?))", + schema + ".world_validate_selected_publication_account_binding()") + .get(0, String.class); + var installedArtifactInventory = + connection + .fetchSingle( + "SELECT pg_get_functiondef(to_regprocedure(?))", + schema + ".world_validate_selected_publication_artifact_inventory()") + .get(0, String.class); + var installedPreparationRetainer = + connection + .fetchSingle( + "SELECT pg_get_functiondef(to_regprocedure(?))", + schema + ".world_retain_preparation_start_location()") + .get(0, String.class); + assertThat(installedAccountBinding) + .contains("attempt_created_full_xid = pg_current_xact_id()") + .contains("attempt_inserted_full_xid = pg_current_xact_id()") + .doesNotContain("a.xmin::TEXT"); + assertThat(installedArtifactInventory) + .contains("attempt_created_full_xid = pg_current_xact_id()") + .contains("attempt_inserted_full_xid = pg_current_xact_id()") + .doesNotContain("a.xmin::TEXT"); + assertThat(installedPreparationRetainer) + .contains("to_jsonb(retained) = to_jsonb(NEW)") + .contains("world_canonical_instance_preparation_execution_manifest") + .doesNotContain("retained.xmin::TEXT"); + var stampFunction = + connection.fetchSingle( + "SELECT proowner::text, prosecdef, proconfig::text FROM pg_proc " + + "WHERE oid = to_regprocedure(?)", + schema + ".world_stamp_publication_attempt_full_xid()"); + assertThat(stampFunction.get("proowner", String.class)) + .isEqualTo( + connection + .fetchSingle( + "SELECT proowner::text FROM pg_proc WHERE oid = to_regprocedure(?)", + schema + ".world_validate_selected_publication_account_binding()") + .get(0, String.class)); + assertThat(stampFunction.get("prosecdef", Boolean.class)).isTrue(); + assertThat(stampFunction.get("proconfig", String.class)) + .contains("pg_catalog") + .contains(schema); + assertThat( + connection + .fetchSingle( + "SELECT count(*) FROM pg_proc p CROSS JOIN LATERAL " + + "aclexplode(COALESCE(p.proacl, acldefault('f', p.proowner))) acl " + + "WHERE p.oid = to_regprocedure(?) AND acl.grantee = 0::oid " + + "AND acl.privilege_type = 'EXECUTE'", + schema + ".world_stamp_publication_attempt_full_xid()") + .get(0, Long.class)) + .as("the stamp trigger function grants no EXECUTE privilege to PUBLIC") + .isZero(); + assertThat( + connection + .fetchSingle( + "SELECT count(*) FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid " + + "WHERE c.relnamespace = to_regnamespace(?) " + + "AND t.tgname = 'trg_world_publication_attempt_full_xid_stamp' " + + "AND c.relname = 'world_design_publication_fence_attempt' " + + "AND t.tgtype = 7 AND t.tgenabled = 'O' " + + "AND t.tgfoid = to_regprocedure(?)", + schema, + schema + ".world_stamp_publication_attempt_full_xid()") + .get(0, Long.class)) + .isEqualTo(1L); + assertThat( + connection.fetchSingle( + "SELECT t.oid::text, t.tgfoid::text, t.tgtype, t.tgenabled, t.tgargs::text, t.tgqual::text " + + "FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid " + + "WHERE c.relnamespace = to_regnamespace(?) AND t.tgname = 'trg_world_canonical_activation_transition'", + schema)) + .isEqualTo(originalGuardTrigger); + assertPredecessorLifecycleGuardProbe( + source, + schema, + fixtureAssociation.worldInstanceId(), + fixtureAssociation.identity().canonicalGameInstanceId().toString()); + List deniedMetadataUpdates = + List.of( + "failure_reason = 'fixture failure'", + "termination_request_id = 'fixture termination'", + "terminated_at = clock_timestamp()"); + for (String mutation : deniedMetadataUpdates) { + assertSqlState( + () -> + connection.execute( + "UPDATE world_instance SET " + mutation + " WHERE id = ?", + fixtureAssociation.worldInstanceId()), + "23514", + "World tenant key is reserved for a canonical authored source"); + } + // The earlier owner-manifest trigger denies naked production writes first. Exercise the + // actual installed activation guard separately on a connection-local copy of that same row; + // no production trigger is disabled and no owner execution manifest is fabricated. + try (var probeConnection = source.getConnection()) { + var probe = DSL.using(probeConnection, SQLDialect.POSTGRES); + probe.execute( + "CREATE TEMP TABLE fixture_row_guard_probe AS TABLE " + + DSL.name(schema, "world_instance") + + " WITH NO DATA"); + probe.execute( + "INSERT INTO pg_temp.fixture_row_guard_probe SELECT * FROM " + + DSL.name(schema, "world_instance") + + " WHERE id = ?", + fixtureAssociation.worldInstanceId()); + probe.execute( + "CREATE TRIGGER fixture_row_guard BEFORE UPDATE ON pg_temp.fixture_row_guard_probe " + + "FOR EACH ROW EXECUTE FUNCTION " + + DSL.name(schema, "world_guard_canonical_activation_transition") + + "()"); + var probeRowsBefore = + probe.fetch( + "SELECT row_to_json(t)::text, xmin::text FROM pg_temp.fixture_row_guard_probe t"); + for (String mutation : deniedMetadataUpdates) { + assertSqlState( + () -> probe.execute("UPDATE pg_temp.fixture_row_guard_probe SET " + mutation), + "23514", + "Run-owned fixture World row mutations are disabled"); + } + assertThat( + probe.fetch( + "SELECT row_to_json(t)::text, xmin::text FROM pg_temp.fixture_row_guard_probe t")) + .isEqualTo(probeRowsBefore); + } + assertThat(allRows(connection).get("world_instance")) + .as( + "fixture row remains byte-for-byte and xmin stable after denied lifecycle metadata writes") + .isEqualTo(retainedRowsAt10428.get("world_instance")); + assertThat(sourceOwner.read("dev", intakeRequest)).contains(intake); + assertThat( + versionOwner.readByCanonicalVersion( + "dev", + intake.canonicalTenantId(), + intake.worldSlug(), + version.canonicalVersionId())) + .contains(version); + assertThat( + connection + .fetchSingle( + "SELECT canonical_game_instance_id, canonical_target_namespace, canonical_tenant_id, canonical_world_slug, playable_state_namespace_id, playable_state_scope, public_production, canonical_launch_binding_operation_id, canonical_realm_id, catalog_revision, canonical_authority_kind, fixture_provenance_digest, game_session_tenant_id, game_session_game_instance_id, game_design_version_id FROM world_instance WHERE id = ?", + worldId) + .intoArray()) + .containsOnlyNulls(); + assertThat( + connection + .fetchSingle( + "SELECT canonical_region_instance_id FROM region_instance WHERE id = ?", + firstRegion) + .get(0)) + .isNull(); + assertThat( + connection + .fetchSingle( + "SELECT count(*) FROM world_canonical_instance_association WHERE world_instance_id = ?", + worldId) + .get(0, Long.class)) + .isZero(); + assertThat( + connection + .fetchSingle( + "SELECT count(*) FROM pg_trigger t JOIN pg_class c ON c.oid=t.tgrelid JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname=? AND NOT t.tgisinternal AND t.tgenabled='D'", + schema) + .get(0, Long.class)) + .isZero(); + // Stable UPDATE on disjoint rows remains independent even with the same legacy tenant. + // Roll both writes back, then recompare the complete retained row images and xmin. + try (var first = source.getConnection(); + var second = source.getConnection()) { + first.setAutoCommit(false); + second.setAutoCommit(false); + try (var statement = + first.prepareStatement( + "UPDATE region_instance SET name='held legacy row' WHERE id=?")) { + statement.setLong(1, firstRegion); + assertThat(statement.executeUpdate()).isEqualTo(1); + } + try (var timeout = second.createStatement(); + var statement = + second.prepareStatement( + "UPDATE region_instance SET name='independent legacy row' WHERE id=?")) { + timeout.execute("SET LOCAL lock_timeout='1000ms'"); + statement.setLong(1, secondRegion); + assertThat(statement.executeUpdate()).isEqualTo(1); + } finally { + second.rollback(); + first.rollback(); + } + } + var rowsAfterLegacyRollback = new LinkedHashMap<>(allRows(connection)); + rowsAfterLegacyRollback.remove(HISTORY); + assertThat(rowsAfterLegacyRollback) + .as("all retained row values and xmin after legacy rollback") + .isEqualTo(retainedRowsAtDefaultFrontier); + // No current Human protection is fabricated. Literal pre-extension legacy and owner + // receipts are retained; a historical canonical Human association requires a separate donor. + } finally { + connection.execute("DROP SCHEMA IF EXISTS " + DSL.name(schema) + " CASCADE"); + } + } + + @Test + void installedAssociationCheckExpressionsRejectRequiredNullsWithoutUnknowns() { + // This is a typed CHECK-expression/storage-shape proof, not authorized Human row creation. + String schemaCheck = + associationCheckExpression(dsl, "ck_world_canonical_instance_association_schema"); + String digestCheck = + associationCheckExpression(dsl, "ck_world_canonical_instance_association_digests"); + + for (int schemaVersion : List.of(1, 2)) { + var humanShape = associationShape(schemaVersion); + assertThat(evaluateAssociationCheck(dsl, schemaCheck, humanShape)) + .as("valid Human schema-%s storage shape", schemaVersion) + .isTrue(); + assertThat(evaluateAssociationCheck(dsl, digestCheck, humanShape)) + .as("valid Human schema-%s digest shape", schemaVersion) + .isTrue(); + + var missingBinding = new LinkedHashMap<>(humanShape); + missingBinding.put("canonical_launch_binding_operation_id", null); + assertThat(evaluateAssociationCheck(dsl, schemaCheck, missingBinding)) + .as("Human schema-%s binding NULL evaluates FALSE", schemaVersion) + .isFalse(); + + var missingReleaseDigest = new LinkedHashMap<>(humanShape); + missingReleaseDigest.put("release_attestation_digest", null); + assertThat(evaluateAssociationCheck(dsl, digestCheck, missingReleaseDigest)) + .as("Human schema-%s release digest NULL evaluates FALSE", schemaVersion) + .isFalse(); + } + + var schema2WithoutCatalog = associationShape(2); + schema2WithoutCatalog.put("catalog_revision", null); + assertThat(evaluateAssociationCheck(dsl, schemaCheck, schema2WithoutCatalog)) + .as("Human schema-2 catalog NULL evaluates FALSE") + .isFalse(); + + var fixtureShape = associationShape(3); + assertThat(evaluateAssociationCheck(dsl, schemaCheck, fixtureShape)) + .as("valid schema-3 fixture storage shape") + .isTrue(); + assertThat(evaluateAssociationCheck(dsl, digestCheck, fixtureShape)) + .as("schema-3 fixture retains absent Human release digest") + .isTrue(); + var fixtureWithoutCatalog = new LinkedHashMap<>(fixtureShape); + fixtureWithoutCatalog.put("catalog_revision", null); + assertThat(evaluateAssociationCheck(dsl, schemaCheck, fixtureWithoutCatalog)) + .as("schema-3 fixture catalog NULL evaluates FALSE") + .isFalse(); + } + + @Test + void malformedAndUnknownPlansAreDeniedBeforeAnyResourceWrite() { + long before = resourceCount(); + assertSqlState(() -> materialize("{", 9_100_001L, 9_100_002L), "22P02"); + + Map unknownPlan = validClosedPlan(UUID.randomUUID(), 9_100_003L, 9_100_004L); + unknownPlan.put("unrecognized", "must be rejected"); + assertSqlState( + () -> materialize(json(unknownPlan), 9_100_005L, 9_100_006L), + "23514", + "unknown or missing plan field"); + + assertThat(resourceCount()).isEqualTo(before); + } + + @Test + void missingOwnerAssociationRejectsPlanAndCannotAdoptAnExistingLegacyWorldRow() { + long before = resourceCount(); + long tenantKey = positiveLong(); + long privateKey = positiveLong(); + long versionKey = positiveLong(); + long worldInstanceId = insertLegacyWorldRow(tenantKey, privateKey, versionKey); + UUID canonicalGameInstanceId = UUID.randomUUID(); + Map plan = validClosedPlan(canonicalGameInstanceId, tenantKey, versionKey); + + assertSqlState(() -> materialize(json(plan), worldInstanceId, privateKey), "P0002"); + + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM world_canonical_instance_association WHERE world_instance_id = ?", + worldInstanceId) + .get(0, Long.class)) + .isZero(); + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM world_canonical_instance_preparation WHERE canonical_game_instance_id = ?", + canonicalGameInstanceId) + .get(0, Long.class)) + .isZero(); + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM world_canonical_instance_topology_identity WHERE world_instance_id = ?", + worldInstanceId) + .get(0, Long.class)) + .isZero(); + assertThat( + dsl.fetchValue( + "SELECT count(*) FROM world_instance WHERE id = ? AND tenant_id = ? " + + "AND game_instance_id = ? AND version_id = ? AND status = 'LEGACY_FIXTURE'", + worldInstanceId, + tenantKey, + privateKey, + versionKey)) + .isEqualTo(1L); + assertThat(resourceCount()).isEqualTo(before + 1); + } + + @Test + @SuppressWarnings("unchecked") + void realWorldOwnersMaterializeSixFixtureMappingsAndReplayExactCommittedBytes() { + RunOwnedCanonicalWorldLaunchEvidence evidence = controlledEvidence(); + var sourceRepository = new WorldAuthoredSourceIntakeRepository(dsl); + var versionRepository = new WorldAuthoredVersionIdentityRepository(dsl); + var associationRepository = + new WorldCanonicalInstanceAssociationRepository( + dsl, + new WorldCompleteLaunchBindingRepository(dsl), + sourceRepository, + versionRepository); + var sourceEvidence = evidence.sourceReceipt().sourceEvidence(); + UUID intakeRequestId = UUID.randomUUID(); + var source = + ownerTransaction() + .execute( + status -> sourceRepository.acceptFresh("dev", intakeRequestId, sourceEvidence)); + assertThat(source).isNotNull(); + assertThat(sourceRepository.read("dev", intakeRequestId)).contains(source); + var stateRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + "dev", + UUID.randomUUID(), + source.canonicalTenantId(), + source.worldSlug(), + source.sourceOperationId(), + source.sourceEvidenceDigest(), + evidence.launchDescriptor().versionId()); + var state = + AuthoredWorldVersionStateEvidence.create( + stateRequest, + sourceEvidence, + evidence.gameSessionAssociation().canonicalVersionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + evidence.launchDescriptor().versionStateEpoch()); + var version = + ownerTransaction().execute(status -> versionRepository.acceptFresh(source, state)); + assertThat(version).isNotNull(); + assertThat( + versionRepository.readByCanonicalVersion( + "dev", + source.canonicalTenantId(), + source.worldSlug(), + version.canonicalVersionId())) + .contains(version); + + // Establish V68's OPEN publication-owner prerequisite through its actual repository. This is + // an owner lock, not a Draft commit, revision, capture, freeze, or publication authorization. + var fenceRepository = new WorldDesignPublicationFenceRepository(dsl, sourceRepository); + var binding = + new OwnerBinding( + "dev", + source.canonicalTenantId(), + version.canonicalVersionId(), + version.operationId(), + version.gameDesignVersionId(), + source.intakeRequestId(), + source.operationId(), + source.requestDigest(), + source.sourceOperationId(), + source.sourceEvidenceDigest(), + source.receiptDigest()); + + var gs = evidence.gameSessionAssociation(); + var descriptor = evidence.launchDescriptor(); + var request = + new PreparedWorldInstanceRequest( + gs.gameSessionTenantId(), + gs.gameInstanceId(), + descriptor.gameTemplateId(), + evidence.capability().operationId(), + descriptor.launchDescriptorId(), + descriptor.versionId(), + null, + descriptor.runtimeFlagsJson(), + descriptor.generationConfigRevision(), + descriptor.releaseBundleId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + null); + WorldCanonicalInstanceAssociation allocated = + ownerTransaction() + .execute( + status -> { + fenceRepository.lockOpen(binding); + var association = + associationRepository.allocateRunOwnedFixtureInOwnerTransaction( + evidence, request, source, version); + return association; + }); + assertThat(allocated).isNotNull(); + assertNoPendingManifests(allocated.worldInstanceId()); + var association = associationRepository.readRunOwnedFixtureAssociation(evidence, request); + assertThat(association.isRunOwnedFixture()).isTrue(); + assertThat(association.worldInstanceId()).isEqualTo(allocated.worldInstanceId()); + assertThat(association.versionIdentity()).isEqualTo(version); + assertThat(association.runOwnedFixture().sourceIntakeReceipt()).isEqualTo(source); + var plan = RunOwnedWorldFixedPresetResources.plan(evidence, source, version); + assertThat(RunOwnedWorldFixedPresetResources.plan(association, source, version).planJson()) + .isEqualTo(plan.planJson()); + long worldId = association.worldInstanceId(); + long privateKey = association.worldPrivateKeys().gameInstanceId(); + long before = resourceCount(); + + // Negative SQL inputs use the actual retained World images. They establish statement + // rollback and exact-row denial only; they do not supply authenticated GS transport proof. + Map allocationWorld = + objectMapper.readValue( + dsl.fetchSingle("SELECT to_jsonb(w)::text FROM world_instance w WHERE id = ?", worldId) + .get(0, String.class), + Map.class); + for (String automaticField : + List.of( + "created_at", + "updated_at", + "row_version", + "failure_reason", + "termination_request_id", + "terminated_at")) { + allocationWorld.remove(automaticField); + } + Map allocationAssociation = + objectMapper.readValue( + dsl.fetchSingle( + "SELECT to_jsonb(a)::text FROM world_canonical_instance_association a WHERE world_instance_id = ?", + worldId) + .get(0, String.class), + Map.class); + // Retained fixture values cannot replay an association INSERT outside the atomic owner; + // changing a row field cannot turn those values into a new execution authorization either. + String unmanifestedAssociation = json(allocationAssociation); + assertSqlState( + () -> + ownerTransaction() + .executeWithoutResult( + status -> + dsl.execute( + "INSERT INTO world_canonical_instance_association " + + "SELECT (jsonb_populate_record(NULL::world_canonical_instance_association, ?::jsonb)).*", + unmanifestedAssociation)), + "23514", + "exact one-use transaction execution manifest"); + Map changedUnmanifestedAssociation = new LinkedHashMap<>(allocationAssociation); + changedUnmanifestedAssociation.put("game_session_tenant_id", gs.gameSessionTenantId() + 1); + assertSqlState( + () -> + ownerTransaction() + .executeWithoutResult( + status -> + dsl.execute( + "INSERT INTO world_canonical_instance_association " + + "SELECT (jsonb_populate_record(NULL::world_canonical_instance_association, ?::jsonb)).*", + json(changedUnmanifestedAssociation))), + "23514", + "exact one-use transaction execution manifest"); + assertThat(resourceCount()).isEqualTo(before); + assertNoPendingManifests(worldId); + + long rejectedWorldId = + dsl.fetchSingle("SELECT nextval('world_instance_id_seq')").get(0, Long.class); + long rejectedPrivateKey = + dsl.fetchSingle("SELECT nextval('world_canonical_private_game_instance_key_seq')") + .get(0, Long.class); + String rejectedCanonicalId = UUID.randomUUID().toString(); + String rejectedOperationId = UUID.randomUUID().toString(); + allocationWorld.put("id", rejectedWorldId); + allocationWorld.put("game_instance_id", rejectedPrivateKey); + allocationWorld.put("canonical_game_instance_id", rejectedCanonicalId); + allocationWorld.put("control_plane_request_id", rejectedOperationId); + allocationAssociation.put("world_instance_id", rejectedWorldId); + allocationAssociation.put("private_game_instance_key", rejectedPrivateKey); + allocationAssociation.put("canonical_game_instance_id", rejectedCanonicalId); + allocationAssociation.put("control_plane_request_id", rejectedOperationId); + + Map changedAllocationWorld = new LinkedHashMap<>(allocationWorld); + changedAllocationWorld.put("game_session_tenant_id", gs.gameSessionTenantId() + 1); + assertSqlState( + () -> + ownerTransaction() + .executeWithoutResult( + status -> + dsl.fetchSingle( + "SELECT world_allocate_run_owned_fixture_instance(?::jsonb, ?::jsonb)", + json(changedAllocationWorld), + json(allocationAssociation))), + "23514", + "no exact transaction execution manifest"); + assertThat(resourceCount()).isEqualTo(before); + assertNoPendingManifests(rejectedWorldId); + + // This value is not in the World row. Its association CHECK fails after the exact World + // insert consumes its manifest, proving that the SQL owner cannot leave a half allocation. + Map changedAllocationAssociation = new LinkedHashMap<>(allocationAssociation); + changedAllocationAssociation.put("descriptor_request_digest", "invalid"); + assertSqlState( + () -> + ownerTransaction() + .executeWithoutResult( + status -> + dsl.fetchSingle( + "SELECT world_allocate_run_owned_fixture_instance(?::jsonb, ?::jsonb)", + json(allocationWorld), + json(changedAllocationAssociation))), + "23514"); + assertThat(resourceCount()).isEqualTo(before); + assertThat(dsl.fetchValue("SELECT count(*) FROM world_instance WHERE id = ?", rejectedWorldId)) + .isEqualTo(0L); + assertThat( + dsl.fetchValue( + "SELECT count(*) FROM world_canonical_instance_association WHERE world_instance_id = ?", + rejectedWorldId)) + .isEqualTo(0L); + assertNoPendingManifests(rejectedWorldId); + + Map changedSeal = objectMapper.readValue(plan.planJson(), Map.class); + changedSeal.put("presetSealDigest", VALID_DIGEST); + assertSqlState( + () -> materialize(json(changedSeal), worldId, privateKey), "23514", "preset seal differs"); + Map changedProvenance = objectMapper.readValue(plan.planJson(), Map.class); + changedProvenance.put("fixturePolicyEvidenceDigest", VALID_DIGEST); + changedProvenance.put("presetSealDigest", framedSeal(changedProvenance)); + assertSqlState(() -> materialize(json(changedProvenance), worldId, privateKey), "23514"); + assertThat(resourceCount()).isEqualTo(before); + assertNoPendingManifests(worldId); + + // The existing canonical-tenant guards forbid introducing an unowned row through SQL. Keep + // this deny boundary enabled instead of manufacturing preexisting corruption by bypassing it. + assertSqlState( + () -> + ownerTransaction() + .executeWithoutResult( + status -> + dsl.execute( + "INSERT INTO region (tenant_id, version_id, name, shard_id, generation_seed, spacing_multiplier, version) " + + "VALUES (?, ?, 'unowned resource', 0, 0, 1.0, 0)", + source.localTenantKey(), + version.localVersionKey())), + "23514", + "no exact transaction execution manifest"); + assertThat(resourceCount()).isEqualTo(before); + + var result = + ownerTransaction() + .execute( + status -> { + fenceRepository.lockOpen(binding); + var replayAllocation = + associationRepository.allocateRunOwnedFixtureInOwnerTransaction( + evidence, request, source, version); + assertThat(replayAllocation.worldInstanceId()).isEqualTo(worldId); + return RunOwnedWorldFixedPresetResources.materialize( + dsl, evidence, plan, worldId, privateKey); + }); + assertThat(result).isNotNull(); + assertThat(result.regionCount()).isEqualTo(1); + assertThat(result.zoneCount()).isEqualTo(1); + assertThat(result.roomCount()).isEqualTo(2); + assertThat(result.exitCount()).isEqualTo(2); + var readbackRowsBefore = allRows(dsl); + assertFixedPresetReadbackMode( + "writable READ COMMITTED", + plan, + worldId, + privateKey, + result, + false, + TransactionDefinition.ISOLATION_READ_COMMITTED, + "read committed", + true, + readbackRowsBefore); + assertFixedPresetReadbackMode( + "read-only REPEATABLE READ", + plan, + worldId, + privateKey, + result, + true, + TransactionDefinition.ISOLATION_REPEATABLE_READ, + "repeatable read", + true, + readbackRowsBefore); + assertFixedPresetReadbackMode( + "read-only SERIALIZABLE", + plan, + worldId, + privateKey, + result, + true, + TransactionDefinition.ISOLATION_SERIALIZABLE, + "serializable", + true, + readbackRowsBefore); + assertFixedPresetReadbackMode( + "read-only READ COMMITTED", + plan, + worldId, + privateKey, + result, + true, + TransactionDefinition.ISOLATION_READ_COMMITTED, + "read committed", + false, + readbackRowsBefore); + assertFixedPresetReadbackMode( + "writable REPEATABLE READ", + plan, + worldId, + privateKey, + result, + false, + TransactionDefinition.ISOLATION_REPEATABLE_READ, + "repeatable read", + false, + readbackRowsBefore); + assertFixedPresetReadbackMode( + "writable SERIALIZABLE", + plan, + worldId, + privateKey, + result, + false, + TransactionDefinition.ISOLATION_SERIALIZABLE, + "serializable", + false, + readbackRowsBefore); + assertFixedPresetReadbackMode( + "writable READ UNCOMMITTED", + plan, + worldId, + privateKey, + result, + false, + TransactionDefinition.ISOLATION_READ_UNCOMMITTED, + "read uncommitted", + false, + readbackRowsBefore); + assertThat(RunOwnedWorldFixedPresetResources.readCommitted(dsl, plan, worldId, privateKey)) + .as("standalone readback in PostgreSQL's implicit writable READ COMMITTED transaction") + .isEqualTo(result); + assertThat(allRows(dsl)) + .as("no row or byte changes after standalone readback") + .isEqualTo(readbackRowsBefore); + assertRoomReadbackRequiresBothRooms(plan, worldId, privateKey, readbackRowsBefore); + assertNoPendingManifests(worldId); + assertThat( + scalarLong( + "SELECT count(*) FROM world_authored_topology_identity WHERE fixture_world_instance_id = ? " + + "AND preparation_authority_kind = 'RUN_OWNED_FIXTURE' AND fixture_operation_id = ? " + + "AND fixture_provenance_digest = ? AND request_id IS NULL AND commit_id IS NULL " + + "AND revision_id IS NULL AND revision_order IS NULL", + worldId, + evidence.capability().operationId(), + evidence.fixtureProvenanceDigest())) + .isEqualTo(6L); + assertThat( + scalarLong( + "SELECT count(*) FROM world_authored_topology_identity WHERE tenant_id = ? AND version_id = ?", + source.localTenantKey(), + version.localVersionKey())) + .isEqualTo(6L); + assertThat( + scalarLong( + "SELECT count(*) FROM world_topology_draft_commit WHERE local_tenant_key = ? AND local_version_key = ?", + source.localTenantKey(), + version.localVersionKey())) + .isZero(); + assertThat( + scalarLong( + "SELECT count(*) FROM world_design_revision_ledger WHERE tenant_id = ? AND version_id = ?", + source.localTenantKey(), + version.localVersionKey())) + .isZero(); + assertThat( + scalarLong( + "SELECT count(*) FROM world_canonical_instance_topology_identity WHERE world_instance_id = ?", + worldId)) + .isEqualTo(6L); + assertNoPendingManifests(worldId); + + assertThat( + scalarLong( + "SELECT count(*) FROM world_canonical_preparation_start_location WHERE world_instance_id = ?", + worldId)) + .isZero(); + + var retained = + dsl.fetchSingle( + "SELECT input_json, graph_bytes, graph_sha256, input_digest, capture_id FROM world_canonical_instance_preparation " + + "WHERE world_instance_id = ?", + worldId); + assertThat(retained.get("input_json", String.class)).isEqualTo(plan.planJson()); + assertThat(retained.get("graph_bytes", byte[].class)) + .isEqualTo(plan.planJson().getBytes(StandardCharsets.UTF_8)); + assertThat(retained.get("graph_sha256", String.class)).isEqualTo(plan.expectedGraphSha256()); + assertThat(retained.get("input_digest", String.class)).isEqualTo(plan.presetSealDigest()); + assertThat(retained.get("capture_id")).isNull(); + long materializedCount = resourceCount(); + String retainedWorld = + scalarText( + "SELECT to_jsonb(w)::text || w.xmin::text FROM world_instance w WHERE id = ?", worldId); + String retainedPreparation = + scalarText( + "SELECT to_jsonb(p)::text || p.xmin::text FROM world_canonical_instance_preparation p WHERE world_instance_id = ?", + worldId); + var replayResult = + ownerTransaction() + .execute( + status -> { + fenceRepository.lockOpen(binding); + var replayAllocation = + associationRepository.allocateRunOwnedFixtureInOwnerTransaction( + evidence, request, source, version); + assertThat(replayAllocation.worldInstanceId()).isEqualTo(worldId); + return RunOwnedWorldFixedPresetResources.materialize( + dsl, evidence, plan, worldId, privateKey); + }); + assertThat(replayResult).isEqualTo(result); + assertThat(resourceCount()).isEqualTo(materializedCount); + assertThat( + scalarText( + "SELECT to_jsonb(w)::text || w.xmin::text FROM world_instance w WHERE id = ?", + worldId)) + .isEqualTo(retainedWorld); + assertThat( + scalarText( + "SELECT to_jsonb(p)::text || p.xmin::text FROM world_canonical_instance_preparation p WHERE world_instance_id = ?", + worldId)) + .isEqualTo(retainedPreparation); + assertNoPendingManifests(worldId); + } + + private WorldLifecycleCommandServiceImpl nativeService( + RunOwnedCanonicalWorldLaunchEvidence evidence) { + return nativeService(evidence, new AtomicInteger()); + } + + private WorldLifecycleCommandServiceImpl nativeService( + RunOwnedCanonicalWorldLaunchEvidence evidence, AtomicInteger upstreamReads) { + // Only upstream replies are controlled. The fixture bridge uses real World SQL owners. + var source = mock(AuthoredWorldSourceClient.class); + when(source.read(any())) + .thenAnswer( + invocation -> { + upstreamReads.incrementAndGet(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return evidence.sourceReceipt().sourceEvidence(); + }); + var versions = mock(AuthoredWorldVersionStateClient.class); + when(versions.read(any())) + .thenAnswer( + invocation -> { + upstreamReads.incrementAndGet(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + AuthoredWorldVersionStateEvidence.Request request = invocation.getArgument(0); + return AuthoredWorldVersionStateEvidence.create( + request, + evidence.sourceReceipt().sourceEvidence(), + evidence.gameSessionAssociation().canonicalVersionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + evidence.launchDescriptor().versionStateEpoch()); + }); + // Package preparation consumes the closed-parser carrier directly; this enabled provider + // supplies configuration only and does not pretend to read files or authenticate producers. + var provider = + new RunOwnedCanonicalWorldLaunchEvidenceProvider( + true, + "/controlled-unused-capability", + "/controlled-unused-receipt", + evidence.capability().runId(), + evidence.capability().composeProjectName(), + new CommonGrpcClientProperties(), + gameDesignClient, + null, + null, + "dev"); + return RunOwnedWorldFixtureLifecycleTestFactory.create( + dsl, + transactionManager, + provider, + source, + versions, + gameDesignClient, + entityManagementClient); + } + + private WorldCanonicalInstanceAssociationRepository associationRepository() { + return new WorldCanonicalInstanceAssociationRepository( + dsl, + new WorldCompleteLaunchBindingRepository(dsl), + new WorldAuthoredSourceIntakeRepository(dsl), + new WorldAuthoredVersionIdentityRepository(dsl)); + } + + private static OwnerBinding binding( + WorldAuthoredSourceIntakeReceipt source, WorldAuthoredVersionIdentityReceipt version) { + return new OwnerBinding( + source.targetNamespace(), + source.canonicalTenantId(), + version.canonicalVersionId(), + version.operationId(), + version.gameDesignVersionId(), + source.intakeRequestId(), + source.operationId(), + source.requestDigest(), + source.sourceOperationId(), + source.sourceEvidenceDigest(), + source.receiptDigest()); + } + + private static T withControlledPeer(Supplier action) { + var certificate = mock(GrpcPeerCertificateEvidence.class); + when(certificate.leafSha256()).thenReturn("a".repeat(64)); + var context = + Context.ROOT + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/dev/sa/game-session-service", + "dev", + "game-session-service")) + .withValue(GrpcPeerCertificateEvidence.CONTEXT_KEY, certificate); + var previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) + throw new IllegalStateException("controlled barrier timed out"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("controlled barrier interrupted", interrupted); + } + } + + private static Map> allRows(DSLContext connection) { + String schema = connection.fetchSingle("SELECT current_schema()").get(0, String.class); + assertThat(schema).isNotBlank(); + var tables = + connection + .fetch( + "SELECT tablename FROM pg_tables WHERE schemaname = ? ORDER BY tablename", schema) + .getValues(0, String.class); + assertThat(tables).isNotEmpty().contains("world_instance"); + Map> rows = new LinkedHashMap<>(); + for (String table : tables) + rows.put( + table, + connection + .fetch( + "SELECT to_jsonb(retained)::text || ':xmin=' || retained.xmin::text FROM " + + DSL.name(schema, table) + + " retained ORDER BY 1") + .getValues(0, String.class)); + return rows; + } + + private static Map> allRowsWithoutNewServerStamps(DSLContext connection) { + String schema = connection.fetchSingle("SELECT current_schema()").get(0, String.class); + assertThat(schema).isNotBlank(); + var tables = + connection + .fetch( + "SELECT tablename FROM pg_tables WHERE schemaname = ? ORDER BY tablename", schema) + .getValues(0, String.class); + assertThat(tables).isNotEmpty().contains("world_design_publication_fence_attempt"); + Map> rows = new LinkedHashMap<>(); + for (String table : tables) { + String retainedRow = + switch (table) { + case "world_design_publication_fence_attempt" -> + "(to_jsonb(retained) - 'attempt_inserted_full_xid')"; + case "world_canonical_instance_preparation" -> + "(to_jsonb(retained) - 'preparation_inserted_full_xid')"; + default -> "to_jsonb(retained)"; + }; + rows.put( + table, + connection + .fetch( + "SELECT " + + retainedRow + + "::text || ':xmin=' || retained.xmin::text FROM " + + DSL.name(schema, table) + + " retained ORDER BY 1") + .getValues(0, String.class)); + } + return rows; + } + + /** + * Exercises the installed trigger against controlled copies of an owner-created row. This is SQL + * predicate and retention proof only; it does not invoke or stand in for the authenticated + * source-first predecessor owner, receipt, World hold, or lifecycle handoff. + */ + private static void assertPredecessorLifecycleGuardProbe( + DriverManagerDataSource source, + String schema, + long canonicalWorldInstanceId, + String canonicalGameInstanceId) + throws Exception { + String probeTable = "pg_temp.fixture_source_lifecycle_probe"; + String worldTable = DSL.name(schema, "world_instance").toString(); + List cases = + List.of( + new LifecycleGuardProbeCase(0, "exact source-only activation", null, null, null), + new LifecycleGuardProbeCase( + 1, + "binding removed on activation", + null, + "run_owned_fixture_binding_sha256 = NULL, status = 'ACTIVE', lifecycle_epoch = 2, row_version = row_version + 1", + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 2, + "malformed original binding", + "run_owned_fixture_binding_sha256 = repeat('A', 64)", + null, + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 3, + "changed binding on activation", + null, + "run_owned_fixture_binding_sha256 = CASE WHEN run_owned_fixture_binding_sha256 = repeat('0', 64) THEN repeat('1', 64) ELSE repeat('0', 64) END, status = 'ACTIVE', lifecycle_epoch = 2, row_version = row_version + 1", + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 4, + "changed preparing epoch", + "run_owned_fixture_preparing_lifecycle_epoch = 2", + null, + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 5, + "stale lifecycle epoch", + "lifecycle_epoch = 2", + "status = 'ACTIVE', lifecycle_epoch = 3, row_version = row_version + 1", + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 6, + "wrong original lifecycle state", + "status = 'FAILED_PRE_ACTIVATION'", + null, + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 7, + "unexpected next lifecycle epoch", + null, + "status = 'ACTIVE', lifecycle_epoch = 3, row_version = row_version + 1", + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 8, + "row version skips a compare-and-set step", + null, + "status = 'ACTIVE', lifecycle_epoch = 2, row_version = row_version + 2", + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 9, + "canonical identity partial", + "canonical_game_instance_id = '00000000-0000-0000-0000-000000000001'::uuid", + null, + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 10, + "realm-only partial", + "canonical_realm_id = '00000000-0000-0000-0000-000000000001'::uuid", + null, + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 11, + "catalog-only partial", + "catalog_revision = 7", + null, + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 12, + "realm/catalog-only partial pair", + "canonical_realm_id = '00000000-0000-0000-0000-000000000001'::uuid, catalog_revision = 7", + null, + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 13, + "fixture provenance partial", + "fixture_provenance_digest = 'sha256:' || repeat('a', 64)", + null, + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 14, + "Game Session tenant allocation partial", + "game_session_tenant_id = 44", + null, + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 15, + "Game Session instance allocation partial", + "game_session_game_instance_id = 45", + null, + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 16, + "Game Design version allocation partial", + "game_design_version_id = 46", + null, + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 17, + "allocation tuple without canonical identity", + "game_session_tenant_id = 44, game_session_game_instance_id = 45, game_design_version_id = 46", + null, + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 18, + "new row adds realm metadata", + null, + "canonical_realm_id = '00000000-0000-0000-0000-000000000001'::uuid, status = 'ACTIVE', lifecycle_epoch = 2, row_version = row_version + 1", + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 19, + "new row adds catalog metadata", + null, + "catalog_revision = 7, status = 'ACTIVE', lifecycle_epoch = 2, row_version = row_version + 1", + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 20, + "new row adopts canonical identity", + null, + "canonical_game_instance_id = '00000000-0000-0000-0000-000000000001'::uuid, status = 'ACTIVE', lifecycle_epoch = 2, row_version = row_version + 1", + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 21, + "new row adds fixture provenance", + null, + "fixture_provenance_digest = 'sha256:' || repeat('a', 64), status = 'ACTIVE', lifecycle_epoch = 2, row_version = row_version + 1", + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 22, + "new row adds allocation data", + null, + "game_session_tenant_id = 44, status = 'ACTIVE', lifecycle_epoch = 2, row_version = row_version + 1", + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 23, + "new row changes source request identity", + null, + "control_plane_request_id = 'different-source-operation', status = 'ACTIVE', lifecycle_epoch = 2, row_version = row_version + 1", + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 24, + "existing termination request", + "termination_request_id = 'staged-termination-request'", + null, + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 25, + "existing terminal timestamp", + "terminated_at = TIMESTAMPTZ '2026-10-14T00:00:00Z'", + null, + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 26, + "Human activation still needs its committed operation", + "run_owned_fixture_binding_sha256 = NULL, run_owned_fixture_preparing_lifecycle_epoch = NULL, " + + "canonical_game_instance_id = '" + + canonicalGameInstanceId + + "'::uuid, canonical_authority_kind = 'HUMAN', canonical_launch_binding_operation_id = '00000000-0000-0000-0000-000000000002'::uuid", + "status = 'ACTIVE', lifecycle_epoch = 2, row_version = row_version + 1", + "requires its exact activation operation"), + new LifecycleGuardProbeCase( + 27, + "null original preparing epoch", + "run_owned_fixture_preparing_lifecycle_epoch = NULL", + null, + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 28, + "null original lifecycle epoch", + "lifecycle_epoch = NULL", + null, + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 29, + "null original lifecycle status", + "status = NULL", + null, + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 30, + "null original row version", + "row_version = NULL", + null, + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 31, + "null resulting lifecycle epoch", + null, + "status = 'ACTIVE', lifecycle_epoch = NULL, row_version = row_version + 1", + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 32, + "null resulting row version", + null, + "status = 'ACTIVE', lifecycle_epoch = 2, row_version = NULL", + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 33, + "negative original row version", + "row_version = -1", + null, + "lifecycle transitions are disabled"), + new LifecycleGuardProbeCase( + 49, + "lifecycle transition cannot rewrite update timestamp", + null, + "updated_at = updated_at + INTERVAL '1 second', status = 'ACTIVE', lifecycle_epoch = 2, row_version = row_version + 1", + "lifecycle transitions are disabled")); + List transitionCases = + List.of( + new LifecycleTransitionGuardProbeCase( + 34, + "PREPARING cannot skip to TERMINATING", + null, + "status = 'TERMINATING', lifecycle_epoch = 2, row_version = row_version + 1, termination_request_id = 'preparing-skip'", + "lifecycle transitions are disabled"), + new LifecycleTransitionGuardProbeCase( + 35, + "PREPARING cannot skip to TERMINATED", + null, + "status = 'TERMINATED', lifecycle_epoch = 2, row_version = row_version + 1, termination_request_id = 'preparing-skip', terminated_at = TIMESTAMPTZ '2026-10-14T00:00:00Z'", + "lifecycle transitions are disabled"), + new LifecycleTransitionGuardProbeCase( + 36, + "FAILED_PRE_ACTIVATION cannot enter termination", + "status = 'FAILED_PRE_ACTIVATION', lifecycle_epoch = 2, row_version = 1, failure_reason = 'prepare failed'", + "status = 'TERMINATING', lifecycle_epoch = 3, row_version = row_version + 1, termination_request_id = 'failed-skip'", + "lifecycle transitions are disabled"), + new LifecycleTransitionGuardProbeCase( + 37, + "ACTIVE cannot skip to TERMINATED", + "status = 'ACTIVE', lifecycle_epoch = 2, row_version = 1", + "status = 'TERMINATED', lifecycle_epoch = 3, row_version = row_version + 1, termination_request_id = 'active-skip', terminated_at = TIMESTAMPTZ '2026-10-14T00:00:00Z'", + "lifecycle transitions are disabled"), + new LifecycleTransitionGuardProbeCase( + 38, + "ACTIVE termination requires a nonblank request ID", + "status = 'ACTIVE', lifecycle_epoch = 2, row_version = 1", + "status = 'TERMINATING', lifecycle_epoch = 3, row_version = row_version + 1, termination_request_id = ' '", + "lifecycle transitions are disabled"), + new LifecycleTransitionGuardProbeCase( + 39, + "ACTIVE termination requires a request ID", + "status = 'ACTIVE', lifecycle_epoch = 2, row_version = 1", + "status = 'TERMINATING', lifecycle_epoch = 3, row_version = row_version + 1", + "lifecycle transitions are disabled"), + new LifecycleTransitionGuardProbeCase( + 40, + "ACTIVE termination requires the next epoch", + "status = 'ACTIVE', lifecycle_epoch = 2, row_version = 1", + "status = 'TERMINATING', lifecycle_epoch = 4, row_version = row_version + 1, termination_request_id = 'stale-epoch'", + "lifecycle transitions are disabled"), + new LifecycleTransitionGuardProbeCase( + 41, + "ACTIVE termination requires one row-version step", + "status = 'ACTIVE', lifecycle_epoch = 2, row_version = 1", + "status = 'TERMINATING', lifecycle_epoch = 3, row_version = row_version + 2, termination_request_id = 'stale-row-version'", + "lifecycle transitions are disabled"), + new LifecycleTransitionGuardProbeCase( + 42, + "termination finalization preserves its request ID", + "status = 'TERMINATING', lifecycle_epoch = 3, row_version = 2, failure_reason = 'cleanup pending', termination_request_id = 'termination-42'", + "status = 'TERMINATED', lifecycle_epoch = 4, row_version = row_version + 1, termination_request_id = 'different-request', terminated_at = TIMESTAMPTZ '2026-10-14T00:00:00Z'", + "lifecycle transitions are disabled"), + new LifecycleTransitionGuardProbeCase( + 43, + "termination finalization requires a terminal timestamp", + "status = 'TERMINATING', lifecycle_epoch = 3, row_version = 2, termination_request_id = 'termination-43'", + "status = 'TERMINATED', lifecycle_epoch = 4, row_version = row_version + 1", + "lifecycle transitions are disabled"), + new LifecycleTransitionGuardProbeCase( + 44, + "termination finalization retains failure metadata", + "status = 'TERMINATING', lifecycle_epoch = 3, row_version = 2, failure_reason = 'cleanup pending', termination_request_id = 'termination-44'", + "status = 'TERMINATED', lifecycle_epoch = 4, row_version = row_version + 1, failure_reason = 'rewritten failure', terminated_at = TIMESTAMPTZ '2026-10-14T00:00:00Z'", + "lifecycle transitions are disabled"), + new LifecycleTransitionGuardProbeCase( + 45, + "TERMINATED cannot reopen as ACTIVE", + "status = 'TERMINATED', lifecycle_epoch = 4, row_version = 3, failure_reason = 'cleanup pending', termination_request_id = 'termination-45', terminated_at = TIMESTAMPTZ '2026-10-14T00:00:00Z'", + "status = 'ACTIVE', lifecycle_epoch = 5, row_version = row_version + 1", + "lifecycle transitions are disabled"), + new LifecycleTransitionGuardProbeCase( + 46, + "TERMINATED cannot reopen as TERMINATING", + "status = 'TERMINATED', lifecycle_epoch = 4, row_version = 3, failure_reason = 'cleanup pending', termination_request_id = 'termination-46', terminated_at = TIMESTAMPTZ '2026-10-14T00:00:00Z'", + "status = 'TERMINATING', lifecycle_epoch = 5, row_version = row_version + 1, terminated_at = NULL", + "lifecycle transitions are disabled"), + new LifecycleTransitionGuardProbeCase( + 47, + "termination finalization requires one row-version step", + "status = 'TERMINATING', lifecycle_epoch = 3, row_version = 2, termination_request_id = 'termination-47'", + "status = 'TERMINATED', lifecycle_epoch = 4, row_version = row_version + 2, terminated_at = TIMESTAMPTZ '2026-10-14T00:00:00Z'", + "lifecycle transitions are disabled"), + new LifecycleTransitionGuardProbeCase( + 48, + "source-only fixture row rejects metadata-only mutation", + null, + "failure_reason = 'unowned metadata change', row_version = row_version + 1", + "lifecycle transitions are disabled")); + + try (var connection = source.getConnection()) { + var probe = DSL.using(connection, SQLDialect.POSTGRES); + String originalBinding = + probe + .fetchSingle( + "SELECT run_owned_fixture_binding_sha256 FROM " + worldTable + " WHERE id = ?", + canonicalWorldInstanceId) + .get(0, String.class); + assertThat(originalBinding).matches("[0-9a-f]{64}"); + probe.execute( + "CREATE TEMP TABLE fixture_source_lifecycle_probe AS SELECT 0::INTEGER AS probe_key, source.* FROM " + + worldTable + + " source WITH NO DATA"); + for (LifecycleGuardProbeCase probeCase : cases) { + insertSourceOnlyLifecycleProbeRow( + probe, probeTable, worldTable, canonicalWorldInstanceId, probeCase.key()); + if (probeCase.oldMutation() != null) { + probe.execute( + "UPDATE " + probeTable + " SET " + probeCase.oldMutation() + " WHERE probe_key = ?", + probeCase.key()); + } + } + for (LifecycleTransitionGuardProbeCase probeCase : transitionCases) { + insertSourceOnlyLifecycleProbeRow( + probe, probeTable, worldTable, canonicalWorldInstanceId, probeCase.key()); + if (probeCase.startingMutation() != null) { + probe.execute( + "UPDATE " + + probeTable + + " SET " + + probeCase.startingMutation() + + " WHERE probe_key = ?", + probeCase.key()); + } + } + int failedPreparationKey = 100; + insertSourceOnlyLifecycleProbeRow( + probe, probeTable, worldTable, canonicalWorldInstanceId, failedPreparationKey); + // This row shape reaches the original Human activation-operation guard, but it is only a + // trigger probe; its Human label and copied fixture UUID do not represent Human authority. + probe.execute( + "CREATE TRIGGER fixture_source_lifecycle_guard BEFORE UPDATE ON " + + probeTable + + " FOR EACH ROW EXECUTE FUNCTION " + + DSL.name(schema, "world_guard_canonical_activation_transition") + + "()"); + + LifecycleGuardProbeCase valid = cases.getFirst(); + probe.execute( + "UPDATE " + + probeTable + + " SET status = 'ACTIVE', lifecycle_epoch = 2, row_version = row_version + 1 " + + "WHERE probe_key = ?", + valid.key()); + var activated = + probe.fetchSingle( + "SELECT status, lifecycle_epoch, row_version, run_owned_fixture_binding_sha256, " + + "run_owned_fixture_preparing_lifecycle_epoch, canonical_game_instance_id, " + + "canonical_realm_id, catalog_revision, fixture_provenance_digest, " + + "game_session_tenant_id, game_session_game_instance_id, game_design_version_id " + + "FROM " + + probeTable + + " WHERE probe_key = ?", + valid.key()); + assertThat(activated.get(0, String.class)).isEqualTo("ACTIVE"); + assertThat(activated.get(1, Long.class)).isEqualTo(2L); + assertThat(activated.get(2, Long.class)).isEqualTo(1L); + assertThat(activated.get(3, String.class)).isEqualTo(originalBinding); + assertThat(activated.get(4, Long.class)).isEqualTo(1L); + assertSourceOnlyCanonicalColumnsNull(probe, probeTable, valid.key()); + assertThat( + probe + .fetchSingle( + "SELECT canonical_game_instance_id, canonical_realm_id, catalog_revision, " + + "fixture_provenance_digest, game_session_tenant_id, " + + "game_session_game_instance_id, game_design_version_id FROM " + + probeTable + + " WHERE probe_key = ?", + valid.key()) + .intoArray()) + .containsOnlyNulls(); + + // Termination commits ACTIVE→TERMINATING before the Entity cleanup call. A cleanup error + // returns with these exact request/reason fields retained; it is not another row transition. + probe.execute( + "UPDATE " + + probeTable + + " SET status = 'TERMINATING', lifecycle_epoch = 3, row_version = row_version + 1, " + + "termination_request_id = 'entity-cleanup-request-0', " + + "failure_reason = 'Entity cleanup failure retained for retry' WHERE probe_key = ?", + valid.key()); + var terminating = + probe.fetchSingle( + "SELECT status, lifecycle_epoch, row_version, run_owned_fixture_binding_sha256, " + + "run_owned_fixture_preparing_lifecycle_epoch, termination_request_id, " + + "failure_reason, terminated_at FROM " + + probeTable + + " WHERE probe_key = ?", + valid.key()); + assertThat(terminating.get(0, String.class)).isEqualTo("TERMINATING"); + assertThat(terminating.get(1, Long.class)).isEqualTo(3L); + assertThat(terminating.get(2, Long.class)).isEqualTo(2L); + assertThat(terminating.get(3, String.class)).isEqualTo(originalBinding); + assertThat(terminating.get(4, Long.class)).isEqualTo(1L); + assertThat(terminating.get(5, String.class)).isEqualTo("entity-cleanup-request-0"); + assertThat(terminating.get(6, String.class)) + .isEqualTo("Entity cleanup failure retained for retry"); + assertThat(terminating.get(7)).isNull(); + assertSourceOnlyCanonicalColumnsNull(probe, probeTable, valid.key()); + var retainedAfterCleanupFailure = + probe.fetch( + "SELECT to_jsonb(row)::text || ':xmin=' || row.xmin::text FROM " + + probeTable + + " row WHERE probe_key = ?", + valid.key()); + assertSqlState( + () -> + probe.execute( + "UPDATE " + + probeTable + + " SET failure_reason = 'unowned cleanup retry metadata', " + + "row_version = row_version + 1 WHERE probe_key = ?", + valid.key()), + "23514", + "lifecycle transitions are disabled"); + assertThat( + probe.fetch( + "SELECT to_jsonb(row)::text || ':xmin=' || row.xmin::text FROM " + + probeTable + + " row WHERE probe_key = ?", + valid.key())) + .as("a rejected metadata-only update leaves the controlled TERMINATING row unchanged") + .isEqualTo(retainedAfterCleanupFailure); + + probe.execute( + "UPDATE " + + probeTable + + " SET status = 'TERMINATED', lifecycle_epoch = 4, row_version = row_version + 1, " + + "terminated_at = TIMESTAMPTZ '2026-10-14T00:00:00Z' WHERE probe_key = ?", + valid.key()); + var terminated = + probe.fetchSingle( + "SELECT status, lifecycle_epoch, row_version, termination_request_id, failure_reason, " + + "terminated_at FROM " + + probeTable + + " WHERE probe_key = ?", + valid.key()); + assertThat(terminated.get(0, String.class)).isEqualTo("TERMINATED"); + assertThat(terminated.get(1, Long.class)).isEqualTo(4L); + assertThat(terminated.get(2, Long.class)).isEqualTo(3L); + assertThat(terminated.get(3, String.class)).isEqualTo("entity-cleanup-request-0"); + assertThat(terminated.get(4, String.class)) + .isEqualTo("Entity cleanup failure retained for retry"); + assertThat(terminated.get(5)).isNotNull(); + assertSourceOnlyCanonicalColumnsNull(probe, probeTable, valid.key()); + var beforeTerminalReopen = + probe.fetch( + "SELECT to_jsonb(row)::text || ':xmin=' || row.xmin::text FROM " + + probeTable + + " row WHERE probe_key = ?", + valid.key()); + assertSqlState( + () -> + probe.execute( + "UPDATE " + + probeTable + + " SET status = 'ACTIVE', lifecycle_epoch = 5, row_version = row_version + 1 " + + "WHERE probe_key = ?", + valid.key()), + "23514", + "lifecycle transitions are disabled"); + assertThat( + probe.fetch( + "SELECT to_jsonb(row)::text || ':xmin=' || row.xmin::text FROM " + + probeTable + + " row WHERE probe_key = ?", + valid.key())) + .as("terminal lifecycle reopening fails without changing the controlled row") + .isEqualTo(beforeTerminalReopen); + + probe.execute( + "UPDATE " + + probeTable + + " SET status = 'FAILED_PRE_ACTIVATION', lifecycle_epoch = 2, " + + "row_version = row_version + 1, failure_reason = 'preparation failure retained' " + + "WHERE probe_key = ?", + failedPreparationKey); + var failedPreparation = + probe.fetchSingle( + "SELECT status, lifecycle_epoch, row_version, failure_reason, " + + "run_owned_fixture_binding_sha256, run_owned_fixture_preparing_lifecycle_epoch " + + "FROM " + + probeTable + + " WHERE probe_key = ?", + failedPreparationKey); + assertThat(failedPreparation.get(0, String.class)).isEqualTo("FAILED_PRE_ACTIVATION"); + assertThat(failedPreparation.get(1, Long.class)).isEqualTo(2L); + assertThat(failedPreparation.get(2, Long.class)).isEqualTo(1L); + assertThat(failedPreparation.get(3, String.class)).isEqualTo("preparation failure retained"); + assertThat(failedPreparation.get(4, String.class)).isEqualTo(originalBinding); + assertThat(failedPreparation.get(5, Long.class)).isEqualTo(1L); + assertSourceOnlyCanonicalColumnsNull(probe, probeTable, failedPreparationKey); + var beforeDowngrade = + probe.fetch( + "SELECT to_jsonb(row)::text || ':xmin=' || row.xmin::text FROM " + + probeTable + + " row WHERE probe_key = ?", + valid.key()); + assertSqlState( + () -> + probe.execute( + "UPDATE " + + probeTable + + " SET status = 'PREPARING', lifecycle_epoch = 1, row_version = row_version + 1 " + + "WHERE probe_key = ?", + valid.key()), + "23514", + "lifecycle transitions are disabled"); + assertThat( + probe.fetch( + "SELECT to_jsonb(row)::text || ':xmin=' || row.xmin::text FROM " + + probeTable + + " row WHERE probe_key = ?", + valid.key())) + .as("a lifecycle downgrade fails without changing the controlled row") + .isEqualTo(beforeDowngrade); + + for (LifecycleGuardProbeCase probeCase : cases.subList(1, cases.size())) { + String activation = + probeCase.activationMutation() == null + ? "status = 'ACTIVE', lifecycle_epoch = 2, row_version = row_version + 1" + : probeCase.activationMutation(); + var before = + probe.fetch( + "SELECT to_jsonb(row)::text || ':xmin=' || row.xmin::text FROM " + + probeTable + + " row WHERE probe_key = ?", + probeCase.key()); + assertSqlState( + () -> + probe.execute( + "UPDATE " + probeTable + " SET " + activation + " WHERE probe_key = ?", + probeCase.key()), + "23514", + probeCase.expectedDiagnostic()); + assertThat( + probe.fetch( + "SELECT to_jsonb(row)::text || ':xmin=' || row.xmin::text FROM " + + probeTable + + " row WHERE probe_key = ?", + probeCase.key())) + .as("%s fails without changing the controlled row", probeCase.label()) + .isEqualTo(before); + } + for (LifecycleTransitionGuardProbeCase probeCase : transitionCases) { + var before = + probe.fetch( + "SELECT to_jsonb(row)::text || ':xmin=' || row.xmin::text FROM " + + probeTable + + " row WHERE probe_key = ?", + probeCase.key()); + assertSqlState( + () -> + probe.execute( + "UPDATE " + + probeTable + + " SET " + + probeCase.transitionMutation() + + " WHERE probe_key = ?", + probeCase.key()), + "23514", + probeCase.expectedDiagnostic()); + assertThat( + probe.fetch( + "SELECT to_jsonb(row)::text || ':xmin=' || row.xmin::text FROM " + + probeTable + + " row WHERE probe_key = ?", + probeCase.key())) + .as("%s fails without changing the controlled row", probeCase.label()) + .isEqualTo(before); + } + } + } + + private static void insertSourceOnlyLifecycleProbeRow( + DSLContext probe, String probeTable, String worldTable, long worldInstanceId, int key) { + probe.execute( + "INSERT INTO " + + probeTable + + " SELECT ?, source.* FROM " + + worldTable + + " source WHERE source.id = ?", + key, + worldInstanceId); + probe.execute( + "UPDATE " + + probeTable + + " SET canonical_game_instance_id = NULL, canonical_target_namespace = NULL, " + + "canonical_tenant_id = NULL, canonical_world_slug = NULL, " + + "playable_state_namespace_id = NULL, playable_state_scope = NULL, " + + "public_production = NULL, playtest_lifecycle_id = NULL, " + + "playtest_state_generation = NULL, canonical_launch_binding_operation_id = NULL, " + + "canonical_authority_kind = NULL, fixture_provenance_digest = NULL, " + + "canonical_realm_id = NULL, catalog_revision = NULL, game_session_tenant_id = NULL, " + + "game_session_game_instance_id = NULL, game_design_version_id = NULL, " + + "run_owned_fixture_preparing_lifecycle_epoch = 1, " + + "status = 'PREPARING', lifecycle_epoch = 1, row_version = 0, failure_reason = NULL, " + + "termination_request_id = NULL, terminated_at = NULL WHERE probe_key = ?", + key); + } + + private static void assertSourceOnlyCanonicalColumnsNull( + DSLContext probe, String probeTable, int key) { + assertThat( + probe + .fetchSingle( + "SELECT canonical_game_instance_id, canonical_target_namespace, canonical_tenant_id, " + + "canonical_world_slug, playable_state_namespace_id, playable_state_scope, " + + "public_production, playtest_lifecycle_id, playtest_state_generation, " + + "canonical_launch_binding_operation_id, canonical_authority_kind, " + + "fixture_provenance_digest, canonical_realm_id, catalog_revision, " + + "game_session_tenant_id, game_session_game_instance_id, game_design_version_id " + + "FROM " + + probeTable + + " WHERE probe_key = ?", + key) + .intoArray()) + .containsOnlyNulls(); + } + + private void assertPresetContent(WorldCanonicalInstanceAssociation association) { + var definition = RunOwnedWorldFixedPresetResources.definition(); + long worldId = association.worldInstanceId(); + var templates = + dsl.fetch( + "SELECT family, template_id FROM world_authored_topology_identity WHERE fixture_world_instance_id = ? ORDER BY family, template_id", + worldId); + Map expected = new LinkedHashMap<>(); + expected.put(definition.region().templateId(), "REGION"); + expected.put(definition.zone().templateId(), "ZONE"); + definition.rooms().forEach(room -> expected.put(room.templateId(), "ROOM")); + definition.exits().forEach(exit -> expected.put(exit.templateId(), "ROOM_EXIT")); + assertThat( + templates.intoMap( + record -> record.get("template_id", UUID.class), + record -> record.get("family", String.class))) + .isEqualTo(expected); + var runtime = + dsl.fetch( + "SELECT family, template_id FROM world_canonical_instance_topology_identity WHERE world_instance_id = ? ORDER BY family, template_id", + worldId); + assertThat( + runtime.intoMap( + record -> record.get("template_id", UUID.class), + record -> record.get("family", String.class))) + .isEqualTo(expected); + assertThat( + scalarLong( + "SELECT count(*) FROM world_authored_topology_identity t JOIN world_canonical_instance_topology_identity r ON r.world_instance_id = t.fixture_world_instance_id AND r.family = t.family AND r.template_id = t.template_id AND r.template_private_row_key = t.private_row_key WHERE t.fixture_world_instance_id = ?", + worldId)) + .isEqualTo(6L); + var region = + dsl.fetchSingle( + "SELECT t.name, t.spacing_multiplier, t.generation_seed, r.name AS runtime_name, r.spacing_multiplier AS runtime_spacing, r.generation_seed AS runtime_seed FROM world_authored_topology_identity m JOIN region t ON t.id = m.private_row_key JOIN world_canonical_instance_topology_identity mi ON mi.world_instance_id = m.fixture_world_instance_id AND mi.template_id = m.template_id JOIN region_instance r ON r.id = mi.runtime_row_id WHERE m.fixture_world_instance_id = ? AND m.family = 'REGION'", + worldId); + assertThat(region.get("name", String.class)).isEqualTo(definition.region().name()); + assertThat(region.get("runtime_name", String.class)).isEqualTo(definition.region().name()); + assertThat(region.get("spacing_multiplier", Double.class)) + .isEqualTo(definition.region().spacingMultiplier()); + assertThat(region.get("runtime_spacing", Double.class)) + .isEqualTo(definition.region().spacingMultiplier()); + assertThat(region.get("generation_seed", Long.class)) + .isEqualTo(definition.region().generationSeed()); + assertThat(region.get("runtime_seed", Long.class)) + .isEqualTo(definition.region().generationSeed()); + var zone = + dsl.fetchSingle( + "SELECT z.name, zi.name AS runtime_name FROM world_authored_topology_identity m JOIN zone z ON z.id = m.private_row_key JOIN world_canonical_instance_topology_identity mi ON mi.world_instance_id = m.fixture_world_instance_id AND mi.template_id = m.template_id JOIN zone_instance zi ON zi.id = mi.runtime_row_id JOIN world_authored_topology_identity rm ON rm.fixture_world_instance_id = m.fixture_world_instance_id AND rm.family = 'REGION' AND rm.private_row_key = z.region_id JOIN world_canonical_instance_topology_identity ri ON ri.world_instance_id = mi.world_instance_id AND ri.template_id = rm.template_id AND ri.runtime_row_id = zi.region_instance_id WHERE m.fixture_world_instance_id = ? AND m.family = 'ZONE'", + worldId); + assertThat(zone.get("name", String.class)).isEqualTo(definition.zone().name()); + assertThat(zone.get("runtime_name", String.class)).isEqualTo(definition.zone().name()); + for (var room : definition.rooms()) { + var actual = + dsl.fetchSingle( + "SELECT r.name, r.description, ri.name AS runtime_name, ri.description AS runtime_description FROM world_authored_topology_identity m JOIN room r ON r.id = m.private_row_key JOIN world_canonical_instance_topology_identity mi ON mi.world_instance_id = m.fixture_world_instance_id AND mi.template_id = m.template_id JOIN room_instance ri ON ri.id = mi.runtime_row_id AND ri.room_instance_row_id = mi.runtime_room_instance_id JOIN world_authored_topology_identity zm ON zm.fixture_world_instance_id = m.fixture_world_instance_id AND zm.family = 'ZONE' AND zm.private_row_key = r.zone_id JOIN world_canonical_instance_topology_identity zi ON zi.world_instance_id = mi.world_instance_id AND zi.template_id = zm.template_id AND zi.runtime_row_id = ri.zone_instance_id WHERE m.fixture_world_instance_id = ? AND m.template_id = ?", + worldId, + room.templateId()); + assertThat(actual.get("name", String.class)).isEqualTo(room.name()); + assertThat(actual.get("runtime_name", String.class)).isEqualTo(room.name()); + assertThat(actual.get("description", String.class)).isEqualTo(room.description()); + assertThat(actual.get("runtime_description", String.class)).isEqualTo(room.description()); + } + for (var exit : definition.exits()) { + var actual = + dsl.fetchSingle( + "SELECT e.direction, e.cost, re.direction AS runtime_direction, re.cost AS runtime_cost FROM world_authored_topology_identity m JOIN room_exit e ON e.id = m.private_row_key JOIN world_canonical_instance_topology_identity mi ON mi.world_instance_id = m.fixture_world_instance_id AND mi.template_id = m.template_id JOIN room_instance_exit re ON re.id = mi.runtime_row_id JOIN world_authored_topology_identity fm ON fm.fixture_world_instance_id = m.fixture_world_instance_id AND fm.template_id = ? AND fm.private_row_key = e.from_room_id JOIN world_authored_topology_identity tm ON tm.fixture_world_instance_id = m.fixture_world_instance_id AND tm.template_id = ? AND tm.private_row_key = e.to_room_id JOIN world_canonical_instance_topology_identity fi ON fi.world_instance_id = mi.world_instance_id AND fi.template_id = fm.template_id AND fi.runtime_room_instance_id = re.from_room_instance_record_id JOIN world_canonical_instance_topology_identity ti ON ti.world_instance_id = mi.world_instance_id AND ti.template_id = tm.template_id AND ti.runtime_room_instance_id = re.to_room_instance_record_id WHERE m.fixture_world_instance_id = ? AND m.template_id = ?", + exit.fromRoomTemplateId(), + exit.toRoomTemplateId(), + worldId, + exit.templateId()); + assertThat(actual.get("direction", String.class)).isEqualTo(exit.direction()); + assertThat(actual.get("runtime_direction", String.class)).isEqualTo(exit.direction()); + assertThat(actual.get("cost", Integer.class)).isEqualTo(exit.cost()); + assertThat(actual.get("runtime_cost", Integer.class)).isEqualTo(exit.cost()); + } + var source = association.runOwnedFixture().sourceIntakeReceipt(); + var plan = + RunOwnedWorldFixedPresetResources.plan(association, source, association.versionIdentity()); + var read = new TransactionTemplate(transactionManager); + read.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + read.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + read.setReadOnly(true); + assertThat( + read.execute( + status -> + RunOwnedWorldFixedPresetResources.readCommitted( + dsl, plan, worldId, association.worldPrivateKeys().gameInstanceId()) + .graphSha256())) + .isEqualTo(plan.expectedGraphSha256()); + } + + private DriverManagerDataSource dataSource(String schema) { + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + return source; + } + + private static List versions(DSLContext connection) { + return connection + .fetch( + "SELECT version FROM " + + DSL.name(HISTORY) + + " WHERE version IS NOT NULL ORDER BY installed_rank") + .getValues(0, String.class); + } + + private static List history(DSLContext connection) { + return connection + .fetch( + "SELECT to_jsonb(h)::text FROM " + + DSL.name(HISTORY) + + " h WHERE version IS NOT NULL ORDER BY installed_rank") + .getValues(0, String.class); + } + + private static List remainingVersions() { + List versions = new ArrayList<>(remainingVersionsThrough(1042)); + versions.add("1042.1"); + versions.add("1042.2"); + versions.add("1042.3"); + versions.add("1042.4"); + versions.add("1042.5"); + versions.add("1042.6"); + versions.add("1042.7"); + versions.add("1042.8"); + versions.add("1042.9"); + versions.add("1042.10"); + versions.add("1042.11"); + versions.add("1042.12"); + versions.add("1042.13"); + return List.copyOf(versions); + } + + private static int resolvedVersionedMigrationCount(Flyway flyway) { + int count = 0; + for (var migration : flyway.info().all()) if (migration.getVersion() != null) count++; + return count; + } + + private static List remainingVersionsThrough(int latestWorldVersion) { + List versions = new ArrayList<>(List.of("1008", "1009", "1009.1")); + for (int version = 1010; version <= latestWorldVersion; version++) + versions.add(Integer.toString(version)); + return List.copyOf(versions); + } + + private static List retainedRows( + DSLContext connection, String schema, String table, List columns) { + String projection = + columns.stream() + .map(column -> DSL.name(column).toString()) + .collect(java.util.stream.Collectors.joining(",")); + return connection + .fetch( + "SELECT to_jsonb(retained)::text FROM (SELECT xmin::text AS retained_xmin, " + + projection + + " FROM " + + DSL.name(schema, table) + + ") retained ORDER BY 1") + .getValues(0, String.class); + } + + private long scalarLong(String sql, Object... bindings) { + return Objects.requireNonNull(dsl.fetchSingle(sql, bindings).get(0, Long.class)); + } + + private String scalarText(String sql, Object... bindings) { + return Objects.requireNonNull(dsl.fetchSingle(sql, bindings).get(0, String.class)); + } + + private String associationCheckExpression(DSLContext connection, String constraintName) { + return Objects.requireNonNull( + connection + .fetchSingle( + "SELECT pg_get_expr(c.conbin, c.conrelid) FROM pg_constraint c " + + "WHERE c.conrelid = 'world_canonical_instance_association'::regclass " + + "AND c.contype = 'c' AND c.conname = ?", + constraintName) + .get(0, String.class)); + } + + private Boolean evaluateAssociationCheck( + DSLContext connection, String expression, Map typedShape) { + return connection + .fetchSingle( + "SELECT (" + + expression + + ") FROM jsonb_populate_record(NULL::world_canonical_instance_association, ?::jsonb) AS candidate", + json(typedShape)) + .get(0, Boolean.class); + } + + private static Map associationShape(int schemaVersion) { + Map shape = new LinkedHashMap<>(); + shape.put("schema_version", schemaVersion); + shape.put("canonical_authority_kind", schemaVersion == 3 ? "RUN_OWNED_FIXTURE" : null); + shape.put("canonical_realm_id", schemaVersion == 1 ? null : UUID.randomUUID().toString()); + shape.put("catalog_revision", schemaVersion == 1 ? null : 1L); + shape.put( + "canonical_launch_binding_operation_id", + schemaVersion == 3 ? null : UUID.randomUUID().toString()); + shape.put("release_attestation_digest", schemaVersion == 3 ? null : VALID_DIGEST); + shape.put("source_evidence_digest", VALID_DIGEST); + shape.put("intake_request_digest", VALID_DIGEST); + shape.put("intake_receipt_digest", VALID_DIGEST); + shape.put("descriptor_request_digest", VALID_DIGEST); + shape.put("descriptor_result_digest", VALID_DIGEST); + if (schemaVersion == 3) { + shape.put("fixture_provenance_digest", VALID_DIGEST); + shape.put("game_session_tenant_id", 1L); + shape.put("game_session_game_instance_id", 1L); + shape.put("game_design_version_id", 1L); + shape.put("preparation_input_digest", VALID_DIGEST); + shape.put("preparing_lifecycle_epoch", 1L); + shape.put("game_session_association_response_bytes", "\\x01"); + } + return shape; + } + + private TransactionTemplate ownerTransaction() { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return transaction; + } + + private void assertFixedPresetReadbackMode( + String mode, + RunOwnedWorldFixedPresetResources.FixedPresetPlan plan, + long worldId, + long privateGameInstanceKey, + RunOwnedWorldFixedPresetResources.MaterializedFixedPreset expected, + boolean readOnly, + int isolationLevel, + String expectedIsolation, + boolean supported, + Map> rowsBefore) { + var transaction = new TransactionTemplate(transactionManager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(isolationLevel); + transaction.setReadOnly(readOnly); + if (supported) { + RunOwnedWorldFixedPresetResources.MaterializedFixedPreset actual = + transaction.execute( + status -> + readPresetInCurrentTransaction( + plan, worldId, privateGameInstanceKey, readOnly, expectedIsolation)); + assertThat(actual).as(mode).isEqualTo(expected); + } else { + assertSqlState( + () -> + transaction.execute( + status -> + readPresetInCurrentTransaction( + plan, worldId, privateGameInstanceKey, readOnly, expectedIsolation)), + "23514", + "Run-owned fixed-preset readback requires an owner read transaction"); + } + assertThat(allRows(dsl)).as("no row or byte changes after " + mode).isEqualTo(rowsBefore); + assertNoPendingManifests(worldId); + } + + private void assertRoomReadbackRequiresBothRooms( + RunOwnedWorldFixedPresetResources.FixedPresetPlan plan, + long worldId, + long privateGameInstanceKey, + Map> rowsBefore) { + String schema = dsl.fetchSingle("SELECT current_schema()").get(0, String.class); + String originalRoutine = + DSL.name(schema, "world_read_run_owned_fixed_preset") + "(text,text,bigint,bigint)"; + String installedDefinition = + dsl.fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", originalRoutine) + .get(0, String.class); + var originalReadback = + RunOwnedWorldFixedPresetResources.readCommitted(dsl, plan, worldId, privateGameInstanceKey); + String roomCountStart = + "OR (SELECT count(*)\n" + + " FROM \"" + + schema + + "\".world_authored_topology_identity m\n" + + " JOIN \"" + + schema + + "\".room r ON r.id = m.private_row_key"; + String anyRoomStart = + "OR NOT EXISTS (\n" + + " SELECT 1\n" + + " FROM \"" + + schema + + "\".world_authored_topology_identity m\n" + + " JOIN \"" + + schema + + "\".room r ON r.id = m.private_row_key"; + String roomCountEnd = + "AND ri.zone_instance_id = zi.runtime_row_id)) <> 2\n" + + " OR (SELECT count(*) FROM \"" + + schema + + "\".world_authored_topology_identity m\n" + + " JOIN \"" + + schema + + "\".room_exit e"; + String anyRoomEnd = + "AND ri.zone_instance_id = zi.runtime_row_id))\n" + + " OR (SELECT count(*) FROM \"" + + schema + + "\".world_authored_topology_identity m\n" + + " JOIN \"" + + schema + + "\".room_exit e"; + String callArguments = "(?, ?, ?, ?)"; + for (var roomMismatch : + List.of( + Map.entry("Candle-lit Antechamber", "Candle-lit Antechamber (test-only mismatch)"), + Map.entry("Smith''s Annex", "Smith''s Annex (test-only mismatch)"))) { + String expectedRoomName = "r.name = '" + roomMismatch.getKey() + "'"; + String substitutedRoomName = "r.name = '" + roomMismatch.getValue() + "'"; + String changedRoomDefinition = + replaceExactlyOnce( + installedDefinition, + expectedRoomName, + substitutedRoomName, + "fixed room expectation " + roomMismatch.getKey()); + + String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 8); + String oldName = "world_test_old_room_readback_" + suffix; + String currentName = "world_test_current_room_readback_" + suffix; + String oldQualifiedName = DSL.name(schema, oldName).toString(); + String currentQualifiedName = DSL.name(schema, currentName).toString(); + String nameAnchor = "world_read_run_owned_fixed_preset("; + String oldDefinition = + replaceExactlyOnce( + changedRoomDefinition, + nameAnchor, + oldName + "(", + "old test function name for " + roomMismatch.getKey()); + String currentDefinition = + replaceExactlyOnce( + changedRoomDefinition, + nameAnchor, + currentName + "(", + "current test function name for " + roomMismatch.getKey()); + oldDefinition = + replaceExactlyOnce( + oldDefinition, + roomCountStart, + anyRoomStart, + "old room predicate start for " + roomMismatch.getKey()); + oldDefinition = + replaceExactlyOnce( + oldDefinition, + roomCountEnd, + anyRoomEnd, + "old room predicate end for " + roomMismatch.getKey()); + + try { + dsl.execute(oldDefinition); + dsl.execute(currentDefinition); + assertThat( + dsl.fetchOne( + "SELECT * FROM " + oldQualifiedName + callArguments, + plan.planJson(), + plan.expectedContentDigest(), + worldId, + privateGameInstanceKey)) + .as( + "the former any-matching-room check accepts a mismatch for " + + roomMismatch.getKey()) + .isNotNull(); + assertSqlState( + () -> + dsl.fetchOne( + "SELECT * FROM " + currentQualifiedName + callArguments, + plan.planJson(), + plan.expectedContentDigest(), + worldId, + privateGameInstanceKey), + "23514", + "RUN_OWNED_WORLD_FIXED_PRESET_TOPOLOGY_MISMATCH"); + assertThat(allRows(dsl)) + .as("test-local read copies preserve rows and xmin for " + roomMismatch.getKey()) + .isEqualTo(rowsBefore); + } finally { + dsl.execute( + "DROP FUNCTION IF EXISTS " + + oldQualifiedName + + "(text,text,bigint,bigint), " + + currentQualifiedName + + "(text,text,bigint,bigint)"); + } + } + assertThat( + RunOwnedWorldFixedPresetResources.readCommitted( + dsl, plan, worldId, privateGameInstanceKey)) + .as("the installed committed read remains unchanged after the controlled copies") + .isEqualTo(originalReadback); + assertThat(allRows(dsl)) + .as("the installed read and test-local copies preserve every stored row and xmin") + .isEqualTo(rowsBefore); + } + + private static String replaceExactlyOnce( + String source, String anchor, String replacement, String description) { + int offset = source.indexOf(anchor); + assertThat(offset).as(description + " anchor exists").isGreaterThanOrEqualTo(0); + assertThat(source.indexOf(anchor, offset + anchor.length())) + .as(description + " anchor is unique") + .isEqualTo(-1); + return source.substring(0, offset) + replacement + source.substring(offset + anchor.length()); + } + + private RunOwnedWorldFixedPresetResources.MaterializedFixedPreset readPresetInCurrentTransaction( + RunOwnedWorldFixedPresetResources.FixedPresetPlan plan, + long worldId, + long privateGameInstanceKey, + boolean readOnly, + String expectedIsolation) { + var settings = + dsl.fetchSingle( + "SELECT current_setting('transaction_isolation'), " + + "current_setting('transaction_read_only')"); + assertThat(settings.get(0, String.class)).isEqualTo(expectedIsolation); + assertThat(settings.get(1, String.class)).isEqualTo(readOnly ? "on" : "off"); + return RunOwnedWorldFixedPresetResources.readCommitted( + dsl, plan, worldId, privateGameInstanceKey); + } + + private void assertNoPendingManifests(long worldInstanceId) { + assertThat( + scalarLong( + "SELECT (SELECT count(*) FROM world_region_draft_execution_manifest WHERE fixture_world_instance_id = ?) " + + "+ (SELECT count(*) FROM world_canonical_instance_preparation_execution_manifest WHERE fixture_world_instance_id = ?)", + worldInstanceId, + worldInstanceId)) + .isZero(); + } + + /** + * Mirrors Java's length-framed seal for closed negative SQL inputs, never grants owner authority. + */ + private static String framedSeal(Map plan) { + List fields = + List.of( + "presetId", + "expectedContentDigest", + "targetNamespace", + "fixtureOperationId", + "claimDigest", + "fixturePolicyRequestDigest", + "fixturePolicyEvidenceDigest", + "fixturePolicyBytesDigest", + "lifecycleBindingDigest", + "gameSessionResponseBytesDigest", + "canonicalTenantId", + "worldSlug", + "worldSourceIntakeOperationId", + "sourceOperationId", + "sourceEvidenceDigest", + "sourceReceiptDigest", + "worldLocalTenantKey", + "worldVersionIdentityOperationId", + "canonicalVersionId", + "gameDesignVersionId", + "versionEvidenceDigest", + "worldLocalVersionKey", + "launchDescriptorId", + "descriptorRequestDigest", + "descriptorResultDigest", + "descriptorRuntimeFlagsJson", + "launchGameDesignVersionId", + "releaseBundleId", + "publishedReleaseBundleRef", + "manifestHash", + "generationConfigRevision", + "versionStateEpoch", + "gameSessionTenantId", + "gameSessionGameInstanceId", + "gameSessionGameInstanceUuid", + "gameSessionCanonicalTenantId", + "gameSessionCanonicalVersionId", + "playableStateNamespaceId", + "canonicalRealmId", + "playableStateScope", + "publicProduction", + "catalogRevision", + "gameTemplateId"); + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + frame(digest, "firemud-world-run-owned-fixed-preset-binding/v1"); + for (String field : fields) frame(digest, Objects.requireNonNull(plan.get(field)).toString()); + return "sha256:" + HexFormat.of().formatHex(digest.digest()); + } catch (NoSuchAlgorithmException failure) { + throw new IllegalStateException(failure); + } + } + + private static void frame(MessageDigest digest, String value) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); + digest.update(bytes); + } + + private void materialize(String planJson, long worldInstanceId, long privateGameInstanceKey) { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.executeWithoutResult( + status -> + dsl.fetch( + "SELECT * FROM world_materialize_run_owned_fixed_preset(?, ?, ?, ?)", + planJson, + CONTENT_DIGEST, + worldInstanceId, + privateGameInstanceKey)); + } + + private long insertLegacyWorldRow(long tenantKey, long privateKey, long versionKey) { + return Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO world_instance (tenant_id, game_instance_id, game_template_id, " + + "control_plane_request_id, launch_descriptor_id, version_id, " + + "runtime_flags_json, generation_config_revision, release_bundle_id, " + + "published_release_bundle_ref, version_state_epoch, status) " + + "VALUES (?, ?, 71, 'legacy-fixed-preset-test', 'legacy-descriptor', ?, '{}', " + + "'legacy-config', 97, 'legacy-release', 5, 'LEGACY_FIXTURE') RETURNING id", + tenantKey, + privateKey, + versionKey), + "legacy World fixture row was not inserted") + .get("id", Long.class); + } + + private long resourceCount() { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT (SELECT count(*) FROM world_instance) " + + "+ (SELECT count(*) FROM region) + (SELECT count(*) FROM zone) " + + "+ (SELECT count(*) FROM room) + (SELECT count(*) FROM room_exit) " + + "+ (SELECT count(*) FROM world_authored_topology_identity) " + + "+ (SELECT count(*) FROM region_instance) + (SELECT count(*) FROM zone_instance) " + + "+ (SELECT count(*) FROM room_instance) + (SELECT count(*) FROM room_instance_exit) " + + "+ (SELECT count(*) FROM world_canonical_instance_topology_identity) " + + "+ (SELECT count(*) FROM world_canonical_instance_preparation)"), + "resource count query returned no row") + .get(0, Long.class); + } + + private static Map validClosedPlan( + UUID canonicalGameInstanceId, long tenantKey, long versionKey) { + Map plan = new LinkedHashMap<>(); + plan.put("canonicalRealmId", UUID.randomUUID()); + plan.put("canonicalTenantId", UUID.randomUUID()); + plan.put("canonicalVersionId", UUID.randomUUID()); + plan.put("catalogRevision", 1L); + plan.put("claimDigest", "a".repeat(64)); + plan.put("descriptorRequestDigest", VALID_DIGEST); + plan.put("descriptorResultDigest", VALID_DIGEST); + plan.put("descriptorRuntimeFlagsJson", "{}"); + plan.put("expectedContentDigest", CONTENT_DIGEST); + plan.put("fixtureOperationId", UUID.randomUUID()); + plan.put("fixturePolicyBytesDigest", VALID_DIGEST); + plan.put("fixturePolicyEvidenceDigest", VALID_DIGEST); + plan.put("fixturePolicyRequestDigest", VALID_DIGEST); + plan.put("gameDesignVersionId", 1L); + plan.put("gameSessionCanonicalTenantId", UUID.randomUUID()); + plan.put("gameSessionCanonicalVersionId", UUID.randomUUID()); + plan.put("gameSessionGameInstanceId", 1L); + plan.put("gameSessionGameInstanceUuid", canonicalGameInstanceId); + plan.put("gameSessionResponseBytesDigest", VALID_DIGEST); + plan.put("gameSessionTenantId", 1L); + plan.put("gameTemplateId", 1L); + plan.put("generationConfigRevision", "fixture-test"); + plan.put("launchDescriptorId", "fixture-test"); + plan.put("launchGameDesignVersionId", 1L); + plan.put("lifecycleBindingDigest", VALID_DIGEST); + plan.put("manifestHash", "fixture-test"); + plan.put("playableStateNamespaceId", UUID.randomUUID()); + plan.put("playableStateScope", "SHARED"); + plan.put("presetId", "firemud-demo-topology-v1"); + plan.put("presetSealDigest", VALID_DIGEST); + plan.put("publicProduction", false); + plan.put("publishedReleaseBundleRef", "fixture-test"); + plan.put("releaseBundleId", 1L); + plan.put("schemaVersion", 1); + plan.put("sourceEvidenceDigest", VALID_DIGEST); + plan.put("sourceOperationId", UUID.randomUUID()); + plan.put("sourceReceiptDigest", VALID_DIGEST); + plan.put("targetNamespace", "firemud"); + plan.put("topology", topology()); + plan.put("versionEvidenceDigest", VALID_DIGEST); + plan.put("versionStateEpoch", 1L); + plan.put("worldLocalTenantKey", tenantKey); + plan.put("worldLocalVersionKey", versionKey); + plan.put("worldSlug", "fixture-test"); + plan.put("worldSourceIntakeOperationId", UUID.randomUUID()); + plan.put("worldVersionIdentityOperationId", UUID.randomUUID()); + plan.put("presetSealDigest", framedSeal(plan)); + return plan; + } + + private static List> topology() { + return List.of( + Map.of( + "family", "REGION", + "templateId", "9affa11b-02f5-3cc9-a50e-6760083c71e9", + "name", "Demo Region", + "spacingMultiplier", 1.0, + "generationSeed", 0), + Map.of( + "family", "ZONE", + "templateId", "936c4d65-c460-3b73-9f4e-6ee6295bca24", + "parentRegionTemplateId", "9affa11b-02f5-3cc9-a50e-6760083c71e9", + "name", "Demo Zone"), + Map.of( + "family", "ROOM", + "templateId", "c6058518-f9e0-3f26-9b05-2bc786095089", + "parentZoneTemplateId", "936c4d65-c460-3b73-9f4e-6ee6295bca24", + "name", "Candle-lit Antechamber", + "description", + "Stalactites drip along the northern wall while a faint draft carries the smell of damp earth from the lower tunnels. Torches flicker in alcoves, casting motion into the shadowy archway to the north."), + Map.of( + "family", "ROOM", + "templateId", "e74cca03-3b53-3edc-84f5-890651f5fea8", + "parentZoneTemplateId", "936c4d65-c460-3b73-9f4e-6ee6295bca24", + "name", "Smith's Annex", + "description", + "An anvil, banked coals, and orderly tool racks mark this alcove as a working annex off the starter chamber."), + Map.of( + "family", "ROOM_EXIT", + "templateId", "18c4b7a2-6498-3865-a464-814b56e4d4c2", + "fromRoomTemplateId", "c6058518-f9e0-3f26-9b05-2bc786095089", + "toRoomTemplateId", "e74cca03-3b53-3edc-84f5-890651f5fea8", + "direction", "NORTH", + "cost", 1), + Map.of( + "family", "ROOM_EXIT", + "templateId", "ab46ef8f-e74f-3197-be62-9785ef63242e", + "fromRoomTemplateId", "e74cca03-3b53-3edc-84f5-890651f5fea8", + "toRoomTemplateId", "c6058518-f9e0-3f26-9b05-2bc786095089", + "direction", "SOUTH", + "cost", 1)); + } + + private String json(Map value) { + return objectMapper.writeValueAsString(value); + } + + private static long positiveLong() { + return Math.max(1L, UUID.randomUUID().getLeastSignificantBits() & Long.MAX_VALUE); + } + + private static void assertSqlState( + org.assertj.core.api.ThrowableAssert.ThrowingCallable action, String state) { + assertSqlState(action, state, null); + } + + private static void assertSqlState( + org.assertj.core.api.ThrowableAssert.ThrowingCallable action, String state, String message) { + assertThatThrownBy(action) + .satisfies( + failure -> { + Throwable cause = failure; + while (cause.getCause() != null) { + cause = cause.getCause(); + } + assertThat(cause).isInstanceOf(PSQLException.class); + PSQLException postgresFailure = (PSQLException) cause; + assertThat(postgresFailure.getSQLState()).isEqualTo(state); + if (message != null) { + assertThat(postgresFailure.getMessage()).contains(message); + } + }); + } + + private RunOwnedCanonicalWorldLaunchEvidence controlledEvidence() { + return RunOwnedWorldFixtureEvidenceTestFixtures.create(objectMapper); + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixtureEvidenceTestFixtures.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixtureEvidenceTestFixtures.java new file mode 100644 index 0000000000..98b4c8a95a --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixtureEvidenceTestFixtures.java @@ -0,0 +1,401 @@ +package net.firedevops.firemud.worldmanagement.data; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamedesign.v1.ArtifactState; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; +import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; +import tools.jackson.databind.ObjectMapper; + +/** + * Complete controlled upstream data only; construction supplies no genuine producer or TLS proof. + */ +public final class RunOwnedWorldFixtureEvidenceTestFixtures { + private RunOwnedWorldFixtureEvidenceTestFixtures() {} + + public static RunOwnedCanonicalWorldLaunchEvidence create(ObjectMapper objectMapper) { + long gameDesignTenant = 8_810_000L + (positiveLong() % 1_000_000L); + long gameSessionTenant = 18_810_000L + (positiveLong() % 1_000_000L); + long sourceGameRow = positiveLong(); + String sourceTenantKey = Long.toString(gameDesignTenant); + String tenantSlug = "fixture-tenant-" + UUID.randomUUID().toString().replace("-", ""); + String claimDigest = + UUID.randomUUID().toString().replace("-", "") + + UUID.randomUUID().toString().replace("-", ""); + String operationId = + RunOwnedInitialAdmissionFixtureWireCodec.fixtureOperationId( + claimDigest, "fixture-run", "firemud-fixture-run", "a".repeat(64), "b".repeat(64)) + .toString(); + String releaseRef = UUID.randomUUID().toString(); + UUID registrationId = UUID.fromString(operationId); + UUID sourceOperationId = UUID.randomUUID(); + UUID canonicalTenantId = UUID.randomUUID(); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + "dev", registrationId, canonicalTenantId, tenantSlug, "demo", "Demo World"); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + "dev", + registrationId, + sourceOperationId, + requestDigest, + canonicalTenantId, + tenantSlug, + "demo", + "Demo World", + sourceGameRow, + sourceTenantKey, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + "dev", + registrationId, + sourceOperationId, + requestDigest, + canonicalTenantId, + tenantSlug, + "demo", + "Demo World", + sourceGameRow, + sourceTenantKey, + "NEW_GAME_ROW", + sourceEvidenceDigest); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + "dev", + operationId, + canonicalTenantId, + "demo", + sourceOperationId, + sourceEvidenceDigest, + 17L, + false, + null, + false, + null, + false, + null, + false, + null); + var descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "launch-descriptor-fixture-11", + 11L, + false, + null, + "{}", + "genrev-11", + 77L, + 77L, + releaseRef, + false, + null); + String manifestHash = "sha256:" + "c".repeat(64); + var bundle = + PublishedReleaseBundle.newBuilder() + .setId(77L) + .setVersionId(11L) + .setVersionNumber(1) + .setAttestationSchemaVersion("v1") + .setCanonicalTenantId(canonicalTenantId.toString()) + .setCanonicalVersionId(UUID.randomUUID().toString()) + .setPublishedReleaseBundleRef(releaseRef) + .setGenerationConfigRevision("genrev-11") + .setManifestHash(manifestHash) + .build(); + var artifact = + VersionAssetArtifactState.newBuilder() + .setTenantId(sourceTenantKey) + .setVersionId(11L) + .setStateEpoch(2L) + .setExportedVersionNumber(1) + .setArtifactState(ArtifactState.ARTIFACT_STATE_PUBLISHED) + .setManifestHash(manifestHash) + .build(); + var version = + VersionStateSnapshot.newBuilder() + .setTenantId(sourceTenantKey) + .setVersionId(11L) + .setVersionState(VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED) + .setVersionStateEpoch(77L) + .setUpdatedAt("2026-10-11T10:00:00Z") + .build(); + RunOwnedInitialAdmissionFixtureWireCodec.Capability capability = + new RunOwnedInitialAdmissionFixtureWireCodec.Capability( + RunOwnedInitialAdmissionFixtureWireCodec.CAPABILITY_SCHEMA, + "fixture-run", + "firemud-fixture-run", + operationId, + gameDesignTenant, + 17L, + 9L, + "demo", + "Demo World", + "production", + "Live Realm", + true, + true, + false, + "SHARED", + "ALLOW_NEW", + "a".repeat(64), + RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, + "b".repeat(64), + RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, + "c".repeat(64), + claimDigest); + // Controlled constructor data remains untrusted; these commitments do not prove owner writes. + UUID creationRequestId = UUID.randomUUID(); + UUID creationOperationId = UUID.randomUUID(); + String creationRequestDigest = + GameTenantCreationDigest.requestDigest( + "dev", creationRequestId, sourceTenantKey, "Fixture Game", null); + var creation = + new FreshTenantCreationEvidence( + 1, + "dev", + creationRequestId, + creationOperationId, + creationRequestDigest, + canonicalTenantId, + sourceGameRow, + sourceTenantKey, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "dev", + creationRequestId, + creationOperationId, + creationRequestDigest, + canonicalTenantId, + sourceGameRow, + sourceTenantKey, + "NEW_GAME_ROW")); + var launchRead = + new RunOwnedInitialAdmissionFixtureWireCodec.LaunchReadEvidence( + RunOwnedInitialAdmissionFixtureWireCodec.LAUNCH_READ_EVIDENCE_SCHEMA, + 17L, + bundle, + artifact, + version, + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec + .toLaunchDescriptorMessage(descriptor)); + String policyRequestDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( + capability, creation, source, launchRead); + var policySeal = + new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal( + RunOwnedInitialAdmissionFixtureWireCodec.FIXTURE_POLICY_SEAL_SCHEMA, + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE, + UUID.fromString(operationId), + policyRequestDigest, + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + UUID.fromString(operationId), policyRequestDigest)); + var receipt = + new RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt( + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_SCHEMA, + "fixture-run", + "firemud-fixture-run", + operationId, + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE, + RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, + "a".repeat(64), + "b".repeat(64), + RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, + "c".repeat(64), + source, + launchRead, + creation, + policySeal); + var gsRequest = + new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest( + UUID.randomUUID(), "dev", UUID.fromString(operationId), policySeal.evidenceDigest()); + var gs = + new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult( + gsRequest, + gameSessionTenant, + positiveLong(), + canonicalTenantId, + UUID.randomUUID(), + UUID.fromString(bundle.getCanonicalVersionId()), + UUID.randomUUID(), + UUID.randomUUID(), + 1L, + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus.STARTING, + 0L, + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestBytes( + capability, creation, source, launchRead), + policySeal); + byte[] capabilityBytes = objectMapper.writeValueAsBytes(capability); + Map receiptWire = new LinkedHashMap<>(); + receiptWire.put("schema", receipt.schema()); + receiptWire.put("runId", receipt.runId()); + receiptWire.put("composeProjectName", receipt.composeProjectName()); + receiptWire.put("fixtureOperationId", receipt.fixtureOperationId()); + receiptWire.put("ownerService", receipt.ownerService()); + receiptWire.put("gameSessionUriSan", receipt.gameSessionUriSan()); + receiptWire.put("gameSessionLeafSha256", receipt.gameSessionLeafSha256()); + receiptWire.put("caCertificateSha256", receipt.caCertificateSha256()); + receiptWire.put("worldManagementUriSan", receipt.worldManagementUriSan()); + receiptWire.put("worldManagementLeafSha256", receipt.worldManagementLeafSha256()); + receiptWire.put("sourceEvidence", source); + receiptWire.put("creationEvidence", creation); + receiptWire.put("fixturePolicySeal", policySeal); + receiptWire.put( + "launchReadEvidence", + Map.of( + "schema", + launchRead.schema(), + "gameTemplateId", + launchRead.gameTemplateId(), + "publishedReleaseBundleBase64", + Base64.getEncoder().encodeToString(bundle.toByteArray()), + "versionAssetArtifactStateBase64", + Base64.getEncoder().encodeToString(artifact.toByteArray()), + "versionStateBase64", + Base64.getEncoder().encodeToString(version.toByteArray()), + "launchDescriptorBase64", + Base64.getEncoder().encodeToString(launchRead.launchDescriptor().toByteArray()))); + byte[] receiptBytes = objectMapper.writeValueAsBytes(receiptWire); + assertThat(RunOwnedInitialAdmissionFixtureWireCodec.parseCapability(capabilityBytes)) + .isEqualTo(capability); + assertThat( + RunOwnedInitialAdmissionFixtureWireCodec.parseSourceReceipt(receiptBytes, capability)) + .isEqualTo(receipt); + return new RunOwnedCanonicalWorldLaunchEvidence( + capability, + receipt, + descriptor, + capabilityBytes, + receiptBytes, + "a".repeat(64), + RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, + "c".repeat(64), + "b".repeat(64), + gs); + } + + public static RunOwnedCanonicalWorldLaunchEvidence create() { + return create(new ObjectMapper()); + } + + /** A fresh response correlation with identical allocation and original immutable policy bytes. */ + public static RunOwnedCanonicalWorldLaunchEvidence freshObservation( + RunOwnedCanonicalWorldLaunchEvidence original) { + var gs = original.gameSessionAssociation(); + var freshRequest = + new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest( + UUID.randomUUID(), + gs.request().targetNamespace(), + gs.request().fixtureOperationId(), + gs.request().expectedFixturePolicyEvidenceDigest()); + var fresh = + new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult( + freshRequest, + gs.gameSessionTenantId(), + gs.gameInstanceId(), + gs.canonicalTenantId(), + gs.gameInstanceUuid(), + gs.canonicalVersionId(), + gs.canonicalRealmId(), + gs.playableStateNamespaceId(), + gs.catalogRevision(), + gs.currentGameInstanceStatus(), + gs.currentRowVersion(), + gs.fixturePolicyRequestBytes(), + gs.fixturePolicySeal()); + return copy(original, original.sourceReceiptBytes(), fresh); + } + + /** Valid JSON with changed retained bytes must not replace the original preparation binding. */ + public static RunOwnedCanonicalWorldLaunchEvidence changedReceiptBytes( + RunOwnedCanonicalWorldLaunchEvidence original) { + byte[] bytes = original.sourceReceiptBytes(); + byte[] changed = java.util.Arrays.copyOf(bytes, bytes.length + 1); + changed[bytes.length] = '\n'; + assertThat( + RunOwnedInitialAdmissionFixtureWireCodec.parseSourceReceipt( + changed, original.capability())) + .isEqualTo(original.sourceReceipt()); + return copy(original, changed, original.gameSessionAssociation()); + } + + /** Controlled contradictory GS owner allocation, for the actual retained-owner conflict guard. */ + public static RunOwnedCanonicalWorldLaunchEvidence secondAssignment( + RunOwnedCanonicalWorldLaunchEvidence original) { + var gs = original.gameSessionAssociation(); + long otherInstance = gs.gameInstanceId() == Long.MAX_VALUE ? 1L : gs.gameInstanceId() + 1L; + var changed = + new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult( + gs.request(), + gs.gameSessionTenantId(), + otherInstance, + gs.canonicalTenantId(), + UUID.randomUUID(), + gs.canonicalVersionId(), + gs.canonicalRealmId(), + gs.playableStateNamespaceId(), + gs.catalogRevision(), + gs.currentGameInstanceStatus(), + gs.currentRowVersion(), + gs.fixturePolicyRequestBytes(), + gs.fixturePolicySeal()); + return copy(original, original.sourceReceiptBytes(), changed); + } + + public static PreparedWorldInstanceRequest request( + RunOwnedCanonicalWorldLaunchEvidence evidence) { + var gs = evidence.gameSessionAssociation(); + var descriptor = evidence.launchDescriptor(); + return new PreparedWorldInstanceRequest( + gs.gameSessionTenantId(), + gs.gameInstanceId(), + descriptor.gameTemplateId(), + evidence.capability().operationId(), + descriptor.launchDescriptorId(), + descriptor.versionId(), + null, + descriptor.runtimeFlagsJson(), + descriptor.generationConfigRevision(), + descriptor.releaseBundleId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + null); + } + + private static RunOwnedCanonicalWorldLaunchEvidence copy( + RunOwnedCanonicalWorldLaunchEvidence original, + byte[] receiptBytes, + CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult gs) { + return new RunOwnedCanonicalWorldLaunchEvidence( + original.capability(), + original.sourceReceipt(), + original.launchDescriptor(), + original.capabilityBytes(), + receiptBytes, + original.gameSessionLeafSha256(), + original.worldManagementUriSan(), + original.worldManagementLeafSha256(), + original.caCertificateSha256(), + gs); + } + + private static long positiveLong() { + return Math.max(1L, UUID.randomUUID().getLeastSignificantBits() & Long.MAX_VALUE); + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest.java new file mode 100644 index 0000000000..cb10dfd07d --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest.java @@ -0,0 +1,1160 @@ +package net.firedevops.firemud.worldmanagement.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermission; +import java.security.KeyStore; +import java.security.MessageDigest; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadGrpcCodec; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.runtime.RuntimeIdentity; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.GrpcClientAuth; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamedesign.v1.ArtifactState; +import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; +import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; +import net.firedevops.firemud.gamesession.v1.GameSessionControlPlaneServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetRunOwnedFixtureLaunchAssociationRequest; +import net.firedevops.firemud.gamesession.v1.GetRunOwnedFixtureLaunchAssociationResponse; +import net.firedevops.firemud.worldmanagement.client.GameDesignClient; +import net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidence; +import net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidenceProvider; +import net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleRequest; +import net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.test.util.ReflectionTestUtils; +import tools.jackson.databind.json.JsonMapper; + +/** Socket-level proof of authenticated World launch provenance reads from GS and GDS owners. */ +class RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest { + private static final String RUN_ID = "world-mtls-fixture-test"; + private static final String PROJECT = "firemud-world-mtls-fixture-test"; + private static final String GS_URI = "spiffe://firemud/ns/dev/sa/game-session-service"; + private static final String WORLD_URI = "spiffe://firemud/ns/dev/sa/world-management-service"; + private static final String GDS_URI = "spiffe://firemud/ns/dev/sa/game-design-service"; + private static final String RELEASE_REF = "8ce42642-53ae-4d07-aab8-37c43ce66e0c"; + private static final String STORE_PASSWORD = "test-only-world-mtls-password"; + private static final String TEST_JWT_SECRET = "testsecretkeytestsecretkeytest1234"; + private static final JwtUtil WORLD_JWT_UTIL = new JwtUtil(TEST_JWT_SECRET, 3_600_000L); + private static final RuntimeIdentity WORLD_RUNTIME_IDENTITY = + new RuntimeIdentity( + "world-management-service", + "world-mtls-fixture-test", + "localhost", + Instant.parse("2026-10-11T00:00:00Z"), + "test", + "test", + "local"); + + @TempDir static Path temporaryDirectory; + + private static TestPki pki; + private Server worldServer; + private Server gameSessionOwnerServer; + private Server gameDesignServer; + private GameDesignClient gameDesignClient; + private RunOwnedCanonicalWorldLaunchEvidenceProvider evidenceProvider; + private ManagedChannel gameSessionChannel; + + @BeforeAll + static void createCertificates() throws Exception { + pki = TestPki.create(temporaryDirectory); + } + + @AfterEach + void stopTransport() throws Exception { + SessionContext.clear(); + if (evidenceProvider != null) { + evidenceProvider.closeGameSessionFixtureClient(); + evidenceProvider = null; + } + if (gameSessionChannel != null) { + gameSessionChannel.shutdownNow(); + assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + gameSessionChannel = null; + } + if (gameDesignClient != null) { + gameDesignClient.close(); + gameDesignClient = null; + } + if (worldServer != null) { + worldServer.shutdownNow(); + assertThat(worldServer.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + worldServer = null; + } + if (gameDesignServer != null) { + gameDesignServer.shutdownNow(); + assertThat(gameDesignServer.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + gameDesignServer = null; + } + if (gameSessionOwnerServer != null) { + gameSessionOwnerServer.shutdownNow(); + assertThat(gameSessionOwnerServer.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + gameSessionOwnerServer = null; + } + } + + @Test + void physicalMtlsReadsExactStartingFixtureProvenanceWithoutWorldWrites() throws Exception { + Fixture fixture = Fixture.create(temporaryDirectory, pki); + AtomicInteger descriptorReads = new AtomicInteger(); + AtomicInteger fixtureReads = new AtomicInteger(); + AtomicReference worldAtGameDesign = new AtomicReference<>(); + AtomicReference worldCertificateAtGameDesign = + new AtomicReference<>(); + AtomicReference descriptorRequestAtOwner = new AtomicReference<>(); + AtomicReference worldAtGameSession = new AtomicReference<>(); + AtomicReference worldCertificateAtGameSession = + new AtomicReference<>(); + AtomicReference + fixtureRequestAtOwner = new AtomicReference<>(); + AtomicBoolean returnChangedDescriptor = new AtomicBoolean(); + startGameDesignServer( + fixture, + descriptorReads, + worldAtGameDesign, + worldCertificateAtGameDesign, + descriptorRequestAtOwner, + returnChangedDescriptor); + startGameSessionOwnerServer( + fixture, + fixtureReads, + worldAtGameSession, + worldCertificateAtGameSession, + fixtureRequestAtOwner); + + CommonGrpcClientProperties worldTls = pki.worldClientProperties(); + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + gameDesignServer.getPort()); + endpoints.setGameSessionService("localhost:" + gameSessionOwnerServer.getPort()); + gameDesignClient = + new GameDesignClient( + endpoints, + worldTls, + new GrpcChannelFactory(), + new BlockingGrpcStubCustomizer() { + @Override + public > T customize(T stub) { + return GrpcClientAuth.attach(stub, WORLD_JWT_UTIL, WORLD_RUNTIME_IDENTITY); + } + }); + String previousReload = System.getProperty("firemud.grpc.tls-reload.enabled"); + System.setProperty("firemud.grpc.tls-reload.enabled", "false"); + try { + ReflectionTestUtils.invokeMethod(gameDesignClient, "init"); + evidenceProvider = fixture.provider(gameDesignClient, endpoints); + AtomicReference readEvidence = new AtomicReference<>(); + WorldManagementGrpcService readOnlyHandler = + new WorldManagementGrpcService( + null, + null, + null, + null, + null, + null, + null, + new SimpleMeterRegistry(), + JsonMapper.builder().build(), + "dev") { + @Override + public void getWorldInstanceLifecycle( + GetWorldInstanceLifecycleRequest request, + StreamObserver responseObserver) { + try { + readEvidence.set(evidenceProvider.requireAuthenticatedEvidence()); + responseObserver.onNext( + GetWorldInstanceLifecycleResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("TEST_READ_PROVENANCE_ONLY") + .setMessage( + "Controlled handler captured provenance without World reads or writes")) + .build()); + } catch (RuntimeException rejected) { + responseObserver.onNext( + GetWorldInstanceLifecycleResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("RUN_OWNED_WORLD_LAUNCH_EVIDENCE_INVALID") + .setMessage("Controlled fixture provenance read was rejected")) + .build()); + } + responseObserver.onCompleted(); + } + }; + worldServer = startWorldServer(readOnlyHandler); + gameSessionChannel = channel("localhost", worldServer.getPort(), pki.gameSessionClient()); + var response = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .getWorldInstanceLifecycle( + GetWorldInstanceLifecycleRequest.newBuilder() + .setTenantId("142") + .setGameInstanceId("1001") + .build()); + + assertThat(response.hasError()).isTrue(); + assertThat(response.getError().getCode()).isEqualTo("TEST_READ_PROVENANCE_ONLY"); + assertThat(readEvidence.get()).isNotNull(); + assertThat(readEvidence.get().gameSessionAssociation().gameSessionTenantId()).isEqualTo(142L); + assertThat(readEvidence.get().gameSessionAssociation().gameInstanceId()).isEqualTo(1001L); + assertThat(readEvidence.get().gameSessionAssociation().currentGameInstanceStatus()) + .isEqualTo( + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus + .STARTING); + assertThat(readEvidence.get().gameSessionAssociation().fixturePolicySeal()) + .isEqualTo(fixture.policySeal); + assertThat(readEvidence.get().gameSessionAssociation().fixturePolicyRequestBytes()) + .isEqualTo( + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestBytes( + fixture.capability, + fixture.creationEvidence, + fixture.source, + fixture.launchReadEvidence)); + assertThat(readEvidence.get().gameSessionAssociation().canonicalTenantId()) + .isEqualTo(fixture.source.canonicalTenantId()); + assertThat(readEvidence.get().gameSessionAssociation().canonicalVersionId().toString()) + .isEqualTo(fixture.bundle.getCanonicalVersionId()); + assertThat(fixtureReads).hasValue(1); + assertThat(descriptorReads).hasValue(1); + assertThat(fixtureRequestAtOwner.get()).isNotNull(); + assertThat(fixtureRequestAtOwner.get().fixtureOperationId().toString()) + .isEqualTo(fixture.operationId); + assertThat(fixtureRequestAtOwner.get().expectedFixturePolicyEvidenceDigest()) + .isEqualTo(fixture.policySeal.evidenceDigest()); + assertThat(worldAtGameSession.get()) + .isNotNull() + .extracting(GrpcPeerIdentity::uri) + .isEqualTo(WORLD_URI); + assertThat(worldAtGameSession.get().isInNamespace("dev")).isTrue(); + assertThat(worldCertificateAtGameSession.get()) + .isNotNull() + .extracting(GrpcPeerCertificateEvidence::leafSha256) + .isEqualTo(fingerprint(pki.worldManagement().certificate())); + assertThat(worldAtGameDesign.get()) + .isNotNull() + .extracting(GrpcPeerIdentity::uri) + .isEqualTo(WORLD_URI); + assertThat(worldCertificateAtGameDesign.get()) + .isNotNull() + .extracting(GrpcPeerCertificateEvidence::leafSha256) + .isEqualTo(fingerprint(pki.worldManagement().certificate())); + assertThat(descriptorRequestAtOwner.get()).isNotNull(); + assertThat(descriptorRequestAtOwner.get().getControlPlaneRequestId()) + .isEqualTo(fixture.operationId); + assertThat(descriptorRequestAtOwner.get().getExpectedRequestDigest()) + .isEqualTo(fixture.descriptorEvidence.requestDigest()); + assertThat(descriptorRequestAtOwner.get().getExpectedResultDigest()) + .isEqualTo(fixture.descriptorEvidence.resultDigest()); + assertThat(Files.readAllBytes(fixture.capabilityPath)) + .isEqualTo(fixture.originalCapabilityBytes); + assertThat(Files.readAllBytes(fixture.receiptPath)).isEqualTo(fixture.originalReceiptBytes); + + returnChangedDescriptor.set(true); + var rejected = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .getWorldInstanceLifecycle( + GetWorldInstanceLifecycleRequest.newBuilder() + .setTenantId("142") + .setGameInstanceId("1001") + .build()); + assertThat(rejected.hasError()).isTrue(); + assertThat(rejected.getError().getCode()) + .isEqualTo("RUN_OWNED_WORLD_LAUNCH_EVIDENCE_INVALID"); + assertThat(descriptorReads).hasValue(2); + assertThat(fixtureReads).hasValue(1); + assertThat(Files.readAllBytes(fixture.capabilityPath)) + .isEqualTo(fixture.originalCapabilityBytes); + assertThat(Files.readAllBytes(fixture.receiptPath)).isEqualTo(fixture.originalReceiptBytes); + } finally { + if (previousReload == null) { + System.clearProperty("firemud.grpc.tls-reload.enabled"); + } else { + System.setProperty("firemud.grpc.tls-reload.enabled", previousReload); + } + } + } + + @Test + void gameDesignTransportRejectsMissingAndWrongJwtBeforeHandlerRead() throws Exception { + AtomicInteger descriptorReads = new AtomicInteger(); + Fixture fixture = Fixture.create(temporaryDirectory, pki); + startGameDesignServer( + fixture, + descriptorReads, + new AtomicReference<>(), + new AtomicReference<>(), + new AtomicReference<>(), + new AtomicBoolean()); + + gameSessionChannel = channel("localhost", gameDesignServer.getPort(), pki.worldManagement()); + var missingJwtStub = GameDesignServiceGrpc.newBlockingStub(gameSessionChannel); + assertThatThrownBy( + () -> + missingJwtStub.getLaunchDescriptor(GetLaunchDescriptorRequest.getDefaultInstance())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(descriptorReads).hasValue(0); + + JwtUtil wrongJwtUtil = new JwtUtil("different-testsecretkeytestsecretkey1234", 3_600_000L); + var wrongJwtStub = + GrpcClientAuth.attach( + GameDesignServiceGrpc.newBlockingStub(gameSessionChannel), + wrongJwtUtil, + WORLD_RUNTIME_IDENTITY); + assertThatThrownBy( + () -> wrongJwtStub.getLaunchDescriptor(GetLaunchDescriptorRequest.getDefaultInstance())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(descriptorReads).hasValue(0); + } + + private void startGameDesignServer( + Fixture fixture, + AtomicInteger descriptorReads, + AtomicReference worldAtOwner, + AtomicReference worldCertificateAtOwner, + AtomicReference requestAtOwner, + AtomicBoolean returnChangedDescriptor) + throws Exception { + String expectedWorldFingerprint = fingerprint(pki.worldManagement().certificate()); + var service = + new GameDesignServiceGrpc.GameDesignServiceImplBase() { + @Override + public void getLaunchDescriptor( + GetLaunchDescriptorRequest request, + StreamObserver responseObserver) { + descriptorReads.incrementAndGet(); + worldAtOwner.set(GrpcPeerIdentity.current()); + worldCertificateAtOwner.set(GrpcPeerCertificateEvidence.current()); + requestAtOwner.set(request); + if (worldAtOwner.get() == null + || !WORLD_URI.equals(worldAtOwner.get().uri()) + || !worldAtOwner.get().isService("world-management-service") + || !worldAtOwner.get().isInNamespace("dev") + || worldCertificateAtOwner.get() == null + || !expectedWorldFingerprint.equals(worldCertificateAtOwner.get().leafSha256()) + || !fixture + .descriptorEvidence() + .request() + .canonicalTenantId() + .toString() + .equals(request.getCanonicalTenantId()) + || !isExpectedReadRequestId(request.getRequestId(), fixture.operationId) + || !fixture.descriptorEvidence().worldSlug().equals(request.getWorldSlug()) + || !fixture.operationId.equals(request.getControlPlaneRequestId()) + || !fixture + .descriptorEvidence() + .requestDigest() + .equals(request.getExpectedRequestDigest()) + || !fixture + .descriptorEvidence() + .resultDigest() + .equals(request.getExpectedResultDigest())) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "World peer or exact launch descriptor read identity did not match") + .asRuntimeException()); + return; + } + responseObserver.onNext( + GetLaunchDescriptorResponse.newBuilder() + .setRequestId(request.getRequestId()) + .setLaunchDescriptor( + returnChangedDescriptor.get() + ? fixture.launchDescriptor().toBuilder() + .setRuntimeFlagsJson("{\"ownerChanged\":true}") + .build() + : fixture.launchDescriptor()) + .build()); + responseObserver.onCompleted(); + } + }; + gameDesignServer = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.gameDesignServer().privateKey(), + pki.gameDesignServer().certificate())) + .trustManager(pki.caCertificateValue()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, + new GrpcPeerIdentityInterceptor(), + new AuthTokenInterceptor(WORLD_JWT_UTIL))) + .build() + .start(); + } + + private void startGameSessionOwnerServer( + Fixture fixture, + AtomicInteger fixtureReads, + AtomicReference worldAtOwner, + AtomicReference worldCertificateAtOwner, + AtomicReference + requestAtOwner) + throws Exception { + String expectedWorldFingerprint = fingerprint(pki.worldManagement().certificate()); + var service = + new GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceImplBase() { + @Override + public void getRunOwnedFixtureLaunchAssociation( + GetRunOwnedFixtureLaunchAssociationRequest request, + StreamObserver responseObserver) { + fixtureReads.incrementAndGet(); + worldAtOwner.set(GrpcPeerIdentity.current()); + worldCertificateAtOwner.set(GrpcPeerCertificateEvidence.current()); + try { + var selector = + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureRequest(request); + requestAtOwner.set(selector); + if (worldAtOwner.get() == null + || !WORLD_URI.equals(worldAtOwner.get().uri()) + || !worldAtOwner.get().isService("world-management-service") + || !worldAtOwner.get().isInNamespace("dev") + || worldCertificateAtOwner.get() == null + || !expectedWorldFingerprint.equals(worldCertificateAtOwner.get().leafSha256()) + || !"dev".equals(selector.targetNamespace()) + || !fixture.operationId.equals(selector.fixtureOperationId().toString()) + || !fixture + .policySeal + .evidenceDigest() + .equals(selector.expectedFixturePolicyEvidenceDigest())) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "World peer or exact fixture launch selector did not match") + .asRuntimeException()); + return; + } + responseObserver.onNext( + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toFixtureResponse( + fixture.fixtureAssociation(selector))); + responseObserver.onCompleted(); + } catch (RuntimeException invalid) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Fixture owner read selector was invalid") + .asRuntimeException()); + } + } + }; + gameSessionOwnerServer = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.gameSessionClient().privateKey(), + pki.gameSessionClient().certificate())) + .trustManager(pki.caCertificateValue()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private Server startWorldServer(WorldManagementGrpcService service) throws Exception { + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.worldManagement().privateKey(), pki.worldManagement().certificate())) + .trustManager(pki.caCertificateValue()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private ManagedChannel channel(String host, int port, TestIdentity identity) throws Exception { + return NettyChannelBuilder.forAddress(host, port) + .overrideAuthority("localhost") + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forClient() + .keyManager(identity.privateKey(), identity.certificate()) + .trustManager(pki.caCertificateValue())) + .build()) + .build(); + } + + private static boolean isExpectedReadRequestId(String requestId, String operationId) { + try { + return !operationId.equals(UUID.fromString(requestId).toString()); + } catch (RuntimeException malformed) { + return false; + } + } + + private static final class Fixture { + private final TestPki pki; + private final Path directory; + private final Path capabilityPath; + private final Path receiptPath; + private final String operationId; + private final String claimDigest; + private final byte[] originalCapabilityBytes; + private final byte[] originalReceiptBytes; + private final AuthoredWorldSourceEvidence source; + private final PublishedReleaseBundle bundle; + private final VersionAssetArtifactState artifact; + private final VersionStateSnapshot version; + private final LaunchDescriptor launchDescriptor; + private final AuthoredWorldLaunchDescriptorEvidence descriptorEvidence; + private final FreshTenantCreationEvidence creationEvidence; + private final RunOwnedInitialAdmissionFixtureWireCodec.Capability capability; + private final RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt sourceReceipt; + private final RunOwnedInitialAdmissionFixtureWireCodec.LaunchReadEvidence launchReadEvidence; + private final RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal policySeal; + + private Fixture(Path parent, TestPki pki) throws Exception { + this.pki = pki; + directory = Files.createDirectories(parent.resolve("world-fixture-" + UUID.randomUUID())); + capabilityPath = directory.resolve("capability.json"); + receiptPath = directory.resolve("source-receipt.json"); + claimDigest = + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest((RUN_ID + "\n" + PROJECT + "\n").getBytes(StandardCharsets.UTF_8))); + operationId = + RunOwnedInitialAdmissionFixtureWireCodec.fixtureOperationId( + claimDigest, + RUN_ID, + PROJECT, + fingerprint(pki.gameSessionClient().certificate()), + fingerprint(pki.caCertificateValue())) + .toString(); + source = sourceEvidence(operationId); + bundle = publishedBundle(source); + artifact = artifactState(); + version = versionState(); + descriptorEvidence = + RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest.descriptorEvidence( + source, bundle, version, operationId); + launchDescriptor = + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(descriptorEvidence); + creationEvidence = creationEvidence(source); + launchReadEvidence = + new RunOwnedInitialAdmissionFixtureWireCodec.LaunchReadEvidence( + RunOwnedInitialAdmissionFixtureWireCodec.LAUNCH_READ_EVIDENCE_SCHEMA, + 17L, + bundle, + artifact, + version, + launchDescriptor); + String policyRequestDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( + RunOwnedInitialAdmissionFixtureWireCodec.parseCapability( + capabilityJson(pki, operationId, claimDigest).getBytes(StandardCharsets.UTF_8)), + creationEvidence, + source, + launchReadEvidence); + policySeal = + new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal( + RunOwnedInitialAdmissionFixtureWireCodec.FIXTURE_POLICY_SEAL_SCHEMA, + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE, + UUID.fromString(operationId), + policyRequestDigest, + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + UUID.fromString(operationId), policyRequestDigest)); + String capabilityJson = capabilityJson(pki, operationId, claimDigest); + String receiptJson = + receiptJson( + source, + bundle, + artifact, + version, + launchDescriptor, + creationEvidence, + policySeal, + operationId, + pki); + originalCapabilityBytes = capabilityJson.getBytes(StandardCharsets.UTF_8); + originalReceiptBytes = receiptJson.getBytes(StandardCharsets.UTF_8); + writeReadonly(capabilityPath, originalCapabilityBytes); + writeReadonly(receiptPath, originalReceiptBytes); + capability = + RunOwnedInitialAdmissionFixtureWireCodec.parseCapability(originalCapabilityBytes); + sourceReceipt = + RunOwnedInitialAdmissionFixtureWireCodec.parseSourceReceipt( + originalReceiptBytes, capability); + } + + static Fixture create(Path parent, TestPki pki) throws Exception { + return new Fixture(parent, pki); + } + + RunOwnedCanonicalWorldLaunchEvidenceProvider provider( + GameDesignClient client, ServiceEndpointsProperties endpoints) { + return new RunOwnedCanonicalWorldLaunchEvidenceProvider( + true, + capabilityPath.toString(), + receiptPath.toString(), + RUN_ID, + PROJECT, + pki.worldClientProperties(), + client, + endpoints, + new GrpcChannelFactory(), + "dev"); + } + + CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult fixtureAssociation( + CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest request) { + return new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult( + request, + 142L, + 1001L, + source.canonicalTenantId(), + UUID.fromString("20000000-0000-4000-8000-000000000011"), + UUID.fromString(bundle.getCanonicalVersionId()), + UUID.fromString("30000000-0000-4000-8000-000000000011"), + UUID.fromString("40000000-0000-4000-8000-000000000011"), + 1L, + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus.STARTING, + 0L, + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestBytes( + capability, creationEvidence, source, launchReadEvidence), + policySeal); + } + + LaunchDescriptor launchDescriptor() { + return launchDescriptor; + } + + AuthoredWorldLaunchDescriptorEvidence descriptorEvidence() { + return descriptorEvidence; + } + } + + private static AuthoredWorldSourceEvidence sourceEvidence(String operationId) { + UUID registrationId = UUID.fromString(operationId); + UUID tenant = UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6d"); + UUID sourceOperationId = UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + "dev", registrationId, tenant, "fixture-tenant", "demo", "Demo World"); + return new AuthoredWorldSourceEvidence( + 1, + "dev", + registrationId, + sourceOperationId, + requestDigest, + tenant, + "fixture-tenant", + "demo", + "Demo World", + 29L, + "42", + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + "dev", + registrationId, + sourceOperationId, + requestDigest, + tenant, + "fixture-tenant", + "demo", + "Demo World", + 29L, + "42", + "NEW_GAME_ROW")); + } + + private static FreshTenantCreationEvidence creationEvidence(AuthoredWorldSourceEvidence source) { + UUID creationRequestId = UUID.fromString("1b3fdbda-a9f6-4cf5-b21e-b43f0e855f65"); + UUID creationOperationId = UUID.fromString("31e36104-3336-4cf5-899a-cb419f2f361e"); + String requestDigest = + GameTenantCreationDigest.requestDigest( + "dev", creationRequestId, "42", "Fixture Game", null); + return new FreshTenantCreationEvidence( + 1, + "dev", + creationRequestId, + creationOperationId, + requestDigest, + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + GameTenantCreationDigest.evidenceDigest( + "dev", + creationRequestId, + creationOperationId, + requestDigest, + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind())); + } + + private static PublishedReleaseBundle publishedBundle(AuthoredWorldSourceEvidence source) { + return PublishedReleaseBundle.newBuilder() + .setId(77L) + .setVersionId(11L) + .setVersionNumber(1) + .setAttestationSchemaVersion("v1") + .setPublishWorkflowId("publish-11") + .setManifestHash("sha256:" + "c".repeat(64)) + .addRequiredManifestAssetKeys("manifest.json") + .setGenerationConfigRevision("genrev-11") + .setPublishedAt("2026-10-11T10:00:00Z") + .setPublishedReleaseBundleRef(RELEASE_REF) + .setCanonicalTenantId(source.canonicalTenantId().toString()) + .setCanonicalVersionId("10000000-0000-4000-8000-000000000011") + .setManifestSchemaVersion(1) + .addArtifactDigests( + net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest.newBuilder() + .setUsageKey("manifest.json") + .setArtifactKind("manifest") + .setImmutableObjectKey("artifacts/sha256/" + "d".repeat(64)) + .setContentDigest("sha256:" + "d".repeat(64)) + .setContentType("application/json") + .setArtifactSchemaVersion(1) + .build()) + .build(); + } + + private static VersionAssetArtifactState artifactState() { + return VersionAssetArtifactState.newBuilder() + .setTenantId("42") + .setVersionId(11L) + .setArtifactState(ArtifactState.ARTIFACT_STATE_PUBLISHED) + .setStateEpoch(2L) + .setManifestHash("sha256:" + "c".repeat(64)) + .setUpdatedAt("2026-10-11T10:00:00Z") + .addExportedManifestAssetKeys("manifest.json") + .setExportedVersionNumber(1) + .build(); + } + + private static VersionStateSnapshot versionState() { + return VersionStateSnapshot.newBuilder() + .setTenantId("42") + .setVersionId(11L) + .setVersionState(VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED) + .setVersionStateEpoch(77L) + .setUpdatedAt("2026-10-11T10:00:00Z") + .build(); + } + + private static AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest( + AuthoredWorldSourceEvidence source, String operationId) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + "dev", + operationId, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + 17L, + false, + null, + false, + null, + false, + null, + false, + null); + } + + private static AuthoredWorldLaunchDescriptorEvidence descriptorEvidence( + AuthoredWorldSourceEvidence source, + PublishedReleaseBundle bundle, + VersionStateSnapshot version, + String operationId) { + return AuthoredWorldLaunchDescriptorEvidence.create( + expectedRequest(source, operationId), + "launch-descriptor-fixture-11", + bundle.getVersionId(), + false, + null, + "{}", + bundle.getGenerationConfigRevision(), + version.getVersionStateEpoch(), + bundle.getId(), + bundle.getPublishedReleaseBundleRef(), + false, + null); + } + + private static String capabilityJson(TestPki pki, String operationId, String claimDigest) + throws Exception { + return """ + {"schema":"firemud.run-owned-initial-admission-fixture.v1","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":42,"gameTemplateId":17,"ownerAccountId":9,"worldSlug":"demo","worldDisplayName":"Demo World","realmSlug":"production","realmDisplayName":"Live Realm","visible":true,"publicProductionRealm":true,"requiresCharacterSelection":false,"stateScope":"SHARED","characterCreationPolicy":"ALLOW_NEW","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","claimDigest":"%s"}\ + """ + .formatted( + RUN_ID, + PROJECT, + operationId, + fingerprint(pki.gameSessionClient().certificate()), + GS_URI, + fingerprint(pki.caCertificateValue()), + WORLD_URI, + fingerprint(pki.worldManagement().certificate()), + claimDigest); + } + + private static String receiptJson( + AuthoredWorldSourceEvidence source, + PublishedReleaseBundle bundle, + VersionAssetArtifactState artifact, + VersionStateSnapshot version, + LaunchDescriptor descriptor, + FreshTenantCreationEvidence creation, + RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal seal, + String operationId, + TestPki pki) + throws Exception { + return """ + {"schema":"firemud.run-owned-authored-world-source-receipt.v1","runId":"%s","composeProjectName":"%s","fixtureOperationId":"%s","ownerService":"game-design-service","gameSessionUriSan":"%s","gameSessionLeafSha256":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","sourceEvidence":{"schemaVersion":1,"targetNamespace":"dev","registrationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","tenantSlug":"%s","worldSlug":"%s","worldDisplayName":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"launchReadEvidence":{"schema":"firemud.run-owned-v1-launch-read-evidence.v1","gameTemplateId":17,"publishedReleaseBundleBase64":"%s","versionAssetArtifactStateBase64":"%s","versionStateBase64":"%s","launchDescriptorBase64":"%s"},"creationEvidence":{"schemaVersion":%d,"targetNamespace":"%s","creationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"fixturePolicySeal":{"schema":"%s","ownerService":"%s","operationId":"%s","requestDigest":"%s","evidenceDigest":"%s"}}\ + """ + .formatted( + RUN_ID, + PROJECT, + operationId, + GS_URI, + fingerprint(pki.gameSessionClient().certificate()), + fingerprint(pki.caCertificateValue()), + WORLD_URI, + fingerprint(pki.worldManagement().certificate()), + source.registrationRequestId(), + source.operationId(), + source.requestDigest(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest(), + encode(bundle.toByteArray()), + encode(artifact.toByteArray()), + encode(version.toByteArray()), + encode(descriptor.toByteArray()), + creation.schemaVersion(), + creation.targetNamespace(), + creation.creationRequestId(), + creation.operationId(), + creation.requestDigest(), + creation.canonicalTenantId(), + creation.sourceGameRowId(), + creation.sourceGameTenantKey(), + creation.provenanceKind(), + creation.evidenceDigest(), + seal.schema(), + seal.ownerService(), + seal.operationId(), + seal.requestDigest(), + seal.evidenceDigest()); + } + + private static String encode(byte[] bytes) { + return Base64.getEncoder().encodeToString(bytes); + } + + private static String fingerprint(X509Certificate certificate) throws Exception { + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded())); + } + + private static void writeReadonly(Path path, byte[] value) throws IOException { + Files.write(path, value); + Files.setPosixFilePermissions( + path, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); + } + + private record TestIdentity( + PrivateKey privateKey, + X509Certificate certificate, + Path certificatePath, + Path privateKeyPath) {} + + private record TestPki( + X509Certificate caCertificateValue, + Path caCertificatePath, + TestIdentity worldManagement, + TestIdentity gameDesignServer, + TestIdentity gameSessionClient) { + static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("world-mtls-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=World mTLS test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path ca = directory.resolve("world-mtls-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + ca.toString(), + "-rfc"); + X509Certificate caCertificate; + try (var input = Files.newInputStream(ca)) { + caCertificate = + (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + return new TestPki( + caCertificate, + ca, + issueIdentity( + directory, caStore, ca, "world-management", WORLD_URI, "serverAuth,clientAuth"), + issueIdentity(directory, caStore, ca, "game-design", GDS_URI, "serverAuth"), + issueIdentity(directory, caStore, ca, "game-session", GS_URI, "serverAuth,clientAuth")); + } + + CommonGrpcClientProperties worldClientProperties() { + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(worldManagement.certificatePath().toString()); + properties.setPrivateKey(worldManagement.privateKeyPath().toString()); + properties.setCaCert(caCertificatePath.toString()); + properties.setPlaintext(false); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, + Path caStore, + Path caFile, + String alias, + String uri, + String extendedKeyUsage) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + uri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + extendedKeyUsage, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + extendedKeyUsage, + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + PrivateKey key = (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()); + X509Certificate leaf = (X509Certificate) keyStore.getCertificate(alias); + Path certificatePem = + writePem(directory.resolve(alias + "-chain.pem"), "CERTIFICATE", leaf.getEncoded()); + Path keyPem = + writePem(directory.resolve(alias + "-key.pem"), "PRIVATE KEY", key.getEncoded()); + return new TestIdentity(key, leaf, certificatePem, keyPem); + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + List command = new ArrayList<>(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + if (!process.waitFor(30, TimeUnit.SECONDS)) { + process.destroyForcibly(); + throw new IllegalStateException("keytool timed out"); + } + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (process.exitValue() != 0) { + throw new IllegalStateException("keytool failed: " + output); + } + } + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedWorldFixtureLifecycleTestFactory.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedWorldFixtureLifecycleTestFactory.java new file mode 100644 index 0000000000..59b0fe929e --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedWorldFixtureLifecycleTestFactory.java @@ -0,0 +1,96 @@ +package net.firedevops.firemud.worldmanagement.service.impl; + +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; +import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; +import net.firedevops.firemud.worldmanagement.client.GameDesignClient; +import net.firedevops.firemud.worldmanagement.config.WorldProperties; +import net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidence; +import net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidenceProvider; +import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldFixtureEvidenceTestFixtures; +import net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto; +import net.firedevops.firemud.worldmanagement.repository.RegionInstanceRepository; +import net.firedevops.firemud.worldmanagement.repository.RoomExitRepository; +import net.firedevops.firemud.worldmanagement.repository.RoomInstanceExitRepository; +import net.firedevops.firemud.worldmanagement.repository.RoomInstanceRepository; +import net.firedevops.firemud.worldmanagement.repository.RoomRepository; +import net.firedevops.firemud.worldmanagement.repository.WorldEventRepository; +import net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository; +import net.firedevops.firemud.worldmanagement.repository.ZoneInstanceRepository; +import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeService; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCompleteLaunchBindingRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository; +import org.jooq.DSLContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** Test-only package bridge; World owners/SQL are real and only upstream reads are controlled. */ +public final class RunOwnedWorldFixtureLifecycleTestFactory { + private RunOwnedWorldFixtureLifecycleTestFactory() {} + + public static WorldLifecycleCommandServiceImpl create( + DSLContext dsl, + PlatformTransactionManager transactions, + RunOwnedCanonicalWorldLaunchEvidenceProvider provider, + AuthoredWorldSourceClient sourceClient, + AuthoredWorldVersionStateClient versionClient, + GameDesignClient gameDesign, + EntityManagementClient entityManagement) { + var sources = new WorldAuthoredSourceIntakeRepository(dsl); + var versions = new WorldAuthoredVersionIdentityRepository(dsl); + var association = + new WorldCanonicalInstanceAssociationRepository( + dsl, new WorldCompleteLaunchBindingRepository(dsl), sources, versions); + var sourceService = + new WorldAuthoredSourceIntakeService(sourceClient, sources, transactions, "dev"); + var versionService = + new WorldAuthoredVersionIdentityService( + versionClient, versions, sources, transactions, "dev"); + var write = new TransactionTemplate(transactions); + write.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var properties = new WorldProperties(); + properties.setLocalShardId(7); + var service = + new WorldLifecycleCommandServiceImpl( + new WorldInstanceRepository(dsl), + new RegionInstanceRepository(dsl), + new ZoneRepository(dsl), + new ZoneInstanceRepository(dsl), + new RoomRepository(dsl), + new RoomExitRepository(dsl), + new RoomInstanceRepository(dsl), + new RoomInstanceExitRepository(dsl), + new WorldEventRepository(dsl), + properties, + gameDesign, + entityManagement, + new SimpleMeterRegistry(), + write, + provider, + dsl, + new WorldLifecycleCommandServiceImpl.RunOwnedWorldFixtureOwners( + sourceClient, + versionClient, + sourceService, + versionService, + association, + new WorldDesignPublicationFenceRepository(dsl, sources))); + service.initMetrics(); + return service; + } + + /** Owner-local preparation; callers must supply their real or explicitly controlled GS peer. */ + public static WorldInstanceLifecycleSnapshotDto prepare( + WorldLifecycleCommandServiceImpl service, RunOwnedCanonicalWorldLaunchEvidence evidence) { + return service.prepareRunOwnedFixture( + RunOwnedWorldFixtureEvidenceTestFixtures.request(evidence), evidence); + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionTerminalSchemaPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionTerminalSchemaPostgresIntegrationTest.java new file mode 100644 index 0000000000..db72d9c0be --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionTerminalSchemaPostgresIntegrationTest.java @@ -0,0 +1,347 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.HISTORY; +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.flyway; +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.repositoryRoot; +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.sagaMigrations; +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.worldMigrations; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Proves the forward V1042.1 repair preserves the installed V1035 trigger and retained schema. The + * protected fresh-execution guard is exercised as a denial. A temporary probe invokes the + * production deferred function only to prove its qualified lookup and missing-terminal denial; + * neither fixture claims Account authorization, StartSession admission, or successful settlement. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class WorldCanonicalInstanceExecutionTerminalSchemaPostgresIntegrationTest { + private static final String V1035_FILE = + "V1035__world_start_session_execution_terminal_fence.sql"; + private static final String V1035_SHA256 = + "a7931633a6e1c5ab03e12cc4026b543c8e64fa4c894f5d5f5fbe343c3c5a24be"; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void forwardRepairPreservesTerminalTriggerAndWorksWithoutWorldInCallerSearchPath() + throws Exception { + String schema = "world_terminal_schema_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + Path root = repositoryRoot(); + String worldLocation = worldMigrations(root); + String sagaLocation = sagaMigrations(root); + String qualifiedExecutionTable = qualified(schema, "world_canonical_instance_execution"); + try { + assertThat( + sha256( + Files.readAllBytes( + root.resolve( + "services/world-management-service/src/main/resources/db/migration/" + + V1035_FILE)))) + .isEqualTo(V1035_SHA256); + + Flyway through1042 = + flyway(source, schema, MigrationVersion.fromVersion("1042"), worldLocation, sagaLocation); + through1042.migrate(); + through1042.validate(); + assertThat(latestVersion(dsl)).isEqualTo("1042"); + + // The current table guard requires the exact Account owner observation. This direct fresh + // PENDING attempt is expected to fail; it does not synthesize that observation or authorize + // any production execution row. + assertThat(executionRows(dsl, qualifiedExecutionTable)).isEmpty(); + String originalV1035History = migrationHistory(dsl, "1035"); + var originalSchema = schemaInventory(dsl, schema); + var before = terminalTriggerMetadata(dsl, schema); + assertThat(before.publicExecuteGrant()).isFalse(); + var denied = executionRow(UUID.randomUUID().toString()); + assertThatThrownBy(() -> insertPending(dsl, qualifiedExecutionTable, denied)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining( + "A fresh World execution intent requires its exact Account owner observation") + .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("23514")); + assertThat(executionRows(dsl, qualifiedExecutionTable)).isEmpty(); + + Flyway current = + flyway( + source, schema, MigrationVersion.fromVersion("1042.1"), worldLocation, sagaLocation); + current.migrate(); + current.validate(); + assertThat(latestVersion(dsl)).isEqualTo("1042.1"); + assertThat(migrationHistory(dsl, "1035")).isEqualTo(originalV1035History); + assertThat(executionRows(dsl, qualifiedExecutionTable)).isEmpty(); + assertThat(schemaInventory(dsl, schema)).isEqualTo(originalSchema); + + var after = terminalTriggerMetadata(dsl, schema); + assertThat(after.functionOid()).isEqualTo(before.functionOid()); + assertThat(after.functionOwner()).isEqualTo(before.functionOwner()); + assertThat(after.functionAcl()).isEqualTo(before.functionAcl()); + assertThat(after.triggerOid()).isEqualTo(before.triggerOid()); + assertThat(after.triggerFunctionOid()).isEqualTo(before.triggerFunctionOid()); + assertThat(after.triggerDefinition()).isEqualTo(before.triggerDefinition()); + assertThat(after.triggerDeferrable()).isEqualTo(before.triggerDeferrable()).isTrue(); + assertThat(after.triggerInitiallyDeferred()) + .isEqualTo(before.triggerInitiallyDeferred()) + .isTrue(); + assertThat(after.triggerEnabled()).isEqualTo(before.triggerEnabled()).isEqualTo("O"); + assertThat(after.publicExecuteGrant()).isFalse(); + assertThat(after.securityDefiner()).isFalse(); + assertThat(after.functionConfig()).contains("search_path=pg_catalog"); + assertThat(after.functionSource()) + .contains("FROM \"" + schema + "\".world_canonical_instance_execution") + .doesNotContain("FROM world_canonical_instance_execution"); + + // This isolated TEMP trigger calls the production function with search_path pinned to + // pg_catalog. No matching production row exists, so 23514 proves the function resolved its + // service table and reached the expected missing-terminal denial rather than 42P01. It does + // not prove production admission or a successful terminal settlement. + assertThatThrownBy(() -> invokeProductionFunctionAgainstTempProbe(source, schema)) + .isInstanceOf(SQLException.class) + .satisfies( + failure -> { + SQLException sql = (SQLException) failure; + assertThat(sql.getSQLState()).isEqualTo("23514"); + assertThat(sql.getMessage()) + .contains( + "World EXECUTING state cannot commit without exact terminal settlement"); + }); + assertThat(executionRows(dsl, qualifiedExecutionTable)).isEmpty(); + } finally { + dsl.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + } + + private static ExecutionRow executionRow(String requestId) { + String inputJson = "{\"testOnly\":\"denied-direct-insert\"}"; + return new ExecutionRow( + "firemud", + UUID.randomUUID(), + requestId, + UUID.randomUUID(), + "sha256:" + sha256(inputJson.getBytes(java.nio.charset.StandardCharsets.UTF_8)), + UUID.randomUUID(), + UUID.randomUUID()); + } + + private static void insertPending(DSLContext dsl, String table, ExecutionRow row) { + String originalTuple = "{\"testOnly\":\"denied-direct-insert\"}"; + String inputJson = "{\"testOnly\":\"denied-direct-insert\"}"; + dsl.execute( + "INSERT INTO " + + table + + " (target_namespace,canonical_tenant_id,control_plane_request_id," + + "canonical_game_instance_id,canonical_world_slug,game_template_id," + + "original_post_authorization_tuple,original_post_authorization_tuple_sha256," + + "account_world_participation_id,account_world_participation_fence," + + "game_session_owner_attempt_id,game_session_owner_fence,preparation_input_digest," + + "preparation_input_json,world_execution_fence,operation_state) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'PENDING')", + row.namespace(), + row.tenantId(), + row.requestId(), + row.gameInstanceId(), + "test-denied-direct-insert", + 17L, + originalTuple.getBytes(java.nio.charset.StandardCharsets.UTF_8), + sha256(originalTuple.getBytes(java.nio.charset.StandardCharsets.UTF_8)), + row.accountParticipationId(), + 1L, + row.gameSessionAttemptId(), + 1L, + row.inputDigest(), + inputJson, + 1L); + } + + private static void invokeProductionFunctionAgainstTempProbe( + DriverManagerDataSource source, String schema) throws SQLException { + try (Connection connection = source.getConnection()) { + connection.setAutoCommit(false); + try { + try (Statement statement = connection.createStatement()) { + statement.execute("SET LOCAL search_path = pg_catalog"); + try (var result = statement.executeQuery("SELECT current_setting('search_path')")) { + assertThat(result.next()).isTrue(); + assertThat(result.getString(1)).isEqualTo("pg_catalog"); + } + statement.execute( + "CREATE TEMP TABLE terminal_lookup_probe (" + + "target_namespace TEXT NOT NULL, canonical_tenant_id UUID NOT NULL, " + + "control_plane_request_id TEXT NOT NULL) ON COMMIT DROP"); + } + DSL.using(connection, SQLDialect.POSTGRES) + .execute( + "CREATE CONSTRAINT TRIGGER terminal_lookup_probe_deferred " + + "AFTER INSERT OR UPDATE ON pg_temp.terminal_lookup_probe " + + "DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION {0}()", + DSL.name(schema, "world_require_canonical_instance_execution_terminal")); + try (PreparedStatement insert = + connection.prepareStatement( + "INSERT INTO pg_temp.terminal_lookup_probe VALUES (?, ?, ?)")) { + insert.setString(1, "firemud"); + insert.setObject(2, UUID.randomUUID()); + insert.setString(3, "missing-production-execution-row"); + insert.executeUpdate(); + } + connection.commit(); + } catch (SQLException failure) { + try { + connection.rollback(); + } catch (SQLException rollbackFailure) { + failure.addSuppressed(rollbackFailure); + } + throw failure; + } + } + } + + private static String latestVersion(DSLContext dsl) { + return dsl.fetchSingle( + "SELECT version FROM " + + HISTORY + + " WHERE success AND version IS NOT NULL ORDER BY installed_rank DESC LIMIT 1") + .get(0, String.class); + } + + private static String migrationHistory(DSLContext dsl, String version) { + return dsl.fetchSingle( + "SELECT to_jsonb(h)::text FROM " + HISTORY + " h WHERE version=? AND success", version) + .get(0, String.class); + } + + private static List executionRows(DSLContext dsl, String table) { + return dsl.fetch( + "SELECT xmin::text || ':' || to_jsonb(e)::text FROM " + + table + + " e ORDER BY target_namespace,canonical_tenant_id,control_plane_request_id") + .getValues(0, String.class); + } + + private static List schemaInventory(DSLContext dsl, String schema) { + return dsl.fetch( + "SELECT 'table:' || c.relname || ':' || c.relkind::text FROM pg_class c " + + "JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname=? " + + "AND c.relkind IN ('r','p') AND c.relname<>? " + + "UNION ALL SELECT 'column:' || c.relname || ':' || a.attnum || ':' " + + "|| a.attname || ':' || format_type(a.atttypid,a.atttypmod) || ':' " + + "|| a.attnotnull::text || ':' || COALESCE(pg_get_expr(d.adbin,d.adrelid),'') " + + "FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace " + + "JOIN pg_attribute a ON a.attrelid=c.oid LEFT JOIN pg_attrdef d " + + "ON d.adrelid=a.attrelid AND d.adnum=a.attnum WHERE n.nspname=? " + + "AND c.relkind IN ('r','p') AND c.relname<>? AND a.attnum>0 " + + "AND NOT a.attisdropped ORDER BY 1", + schema, + HISTORY, + schema, + HISTORY) + .getValues(0, String.class); + } + + private static TriggerMetadata terminalTriggerMetadata(DSLContext dsl, String schema) { + var row = + dsl.fetchSingle( + "SELECT p.oid::bigint AS function_oid,p.proowner::regrole::text AS function_owner," + + "p.proacl::text AS function_acl,p.prosecdef AS security_definer," + + "p.proconfig::text AS function_config,p.prosrc AS function_source," + + "t.oid::bigint AS trigger_oid,t.tgfoid::bigint AS trigger_function_oid," + + "t.tgdeferrable AS trigger_deferrable,t.tginitdeferred AS trigger_initially_deferred," + + "t.tgenabled::text AS trigger_enabled,pg_get_triggerdef(t.oid) AS trigger_definition," + + "(SELECT count(*) FROM aclexplode(COALESCE(p.proacl,acldefault('f',p.proowner))) a " + + "WHERE a.grantee=0 AND a.privilege_type='EXECUTE') AS public_execute_grants " + + "FROM pg_proc p JOIN pg_namespace pn ON pn.oid=p.pronamespace " + + "JOIN pg_trigger t ON t.tgfoid=p.oid JOIN pg_class c ON c.oid=t.tgrelid " + + "JOIN pg_namespace tn ON tn.oid=c.relnamespace " + + "WHERE pn.nspname=? AND tn.nspname=? " + + "AND p.proname='world_require_canonical_instance_execution_terminal' " + + "AND t.tgname='trg_world_canonical_instance_execution_no_inflight_commit'", + schema, + schema); + return new TriggerMetadata( + row.get("function_oid", Long.class), + row.get("function_owner", String.class), + row.get("function_acl", String.class), + row.get("security_definer", Boolean.class), + row.get("function_config", String.class), + row.get("function_source", String.class), + row.get("trigger_oid", Long.class), + row.get("trigger_function_oid", Long.class), + row.get("trigger_deferrable", Boolean.class), + row.get("trigger_initially_deferred", Boolean.class), + row.get("trigger_enabled", String.class), + row.get("trigger_definition", String.class), + row.get("public_execute_grants", Long.class) > 0); + } + + private static String sqlState(Throwable failure) { + for (Throwable current = failure; current != null; current = current.getCause()) + if (current instanceof SQLException sqlException) return sqlException.getSQLState(); + return null; + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is required by the Java platform", impossible); + } + } + + private static String qualified(String schema, String object) { + return "\"" + schema + "\".\"" + object + "\""; + } + + private record ExecutionRow( + String namespace, + UUID tenantId, + String requestId, + UUID gameInstanceId, + String inputDigest, + UUID accountParticipationId, + UUID gameSessionAttemptId) {} + + private record TriggerMetadata( + long functionOid, + String functionOwner, + String functionAcl, + boolean securityDefiner, + String functionConfig, + String functionSource, + long triggerOid, + long triggerFunctionOid, + boolean triggerDeferrable, + boolean triggerInitiallyDeferred, + String triggerEnabled, + String triggerDefinition, + boolean publicExecuteGrant) {} +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGraphApplicationReceiptDigestPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGraphApplicationReceiptDigestPostgresIntegrationTest.java new file mode 100644 index 0000000000..a8e51924cc --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGraphApplicationReceiptDigestPostgresIntegrationTest.java @@ -0,0 +1,805 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.HISTORY; +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.flyway; +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.repositoryRoot; +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.sagaMigrations; +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.worldMigrations; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.sql.SQLException; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicLong; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.postgresql.util.PSQLException; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Proves the forward semantic receipt-digest repair against the installed World guards. The + * positive APPLIED and receipt rows use controlled table clones with the original functions and + * predicates; they prove SQL predicate behavior only and do not claim genuine Account authority or + * production APPLIED creation. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class WorldGraphApplicationReceiptDigestPostgresIntegrationTest { + private static final String GRAPH_GUARD = "world_guard_graph_application"; + private static final String RECEIPT_GUARD = "world_guard_draft_start_location_receipt"; + private static final String INVALID_DIGEST_PREFIX = "sha256:"; + private static final AtomicLong NEXT_PRIVATE_KEY_BASE = new AtomicLong(71002); + private static final List PROBE_TABLES = + List.of( + "world_topology_draft_commit", + "world_design_publication_fence_owner", + "world_draft_terminal_outcome", + "world_authored_topology_identity", + "world_draft_start_location_receipt", + "world_draft_graph_application", + "world_design_aggregate_epoch", + "world_design_scope_epoch", + "region", + "zone", + "room", + "room_exit", + "generation_rule", + "world_entity_spawn_binding"); + private static final List PROBE_FUNCTIONS = + List.of( + GRAPH_GUARD, + RECEIPT_GUARD, + "world_reject_authored_source_history_mutation", + "world_reject_draft_start_location_receipt_mutation"); + private static final List FAMILY_NAMES = + List.of( + "REGION", "ZONE", "ROOM", "ROOM_EXIT", "GENERATION_RULE", "WORLD_ENTITY_SPAWN_BINDING"); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void forwardMigrationBindsSemanticReceiptDigestOnFreshAndUpgradedSchemas() throws Exception { + Path root = repositoryRoot(); + String worldLocation = worldMigrations(root); + String sagaLocation = sagaMigrations(root); + String upgradeSchema = schemaName("world_digest_upgrade_"); + String freshSchema = schemaName("world_digest_fresh_"); + String probeSchema = schemaName("world_digest_probe_"); + DriverManagerDataSource upgradeSource = source(upgradeSchema); + DriverManagerDataSource freshSource = source(freshSchema); + DriverManagerDataSource probeSource = source(probeSchema); + DSLContext upgradeDsl = DSL.using(upgradeSource, SQLDialect.POSTGRES); + DSLContext freshDsl = DSL.using(freshSource, SQLDialect.POSTGRES); + DSLContext probeDsl = DSL.using(probeSource, SQLDialect.POSTGRES); + + try { + Flyway through104211 = + flyway( + upgradeSource, + upgradeSchema, + MigrationVersion.fromVersion("1042.11"), + worldLocation, + sagaLocation); + through104211.migrate(); + through104211.validate(); + assertThat(latestVersion(upgradeDsl)).isEqualTo("1042.11"); + + String history1012Before = migrationHistory(upgradeDsl, "1012"); + String history1014Before = migrationHistory(upgradeDsl, "1014"); + String history104211Before = migrationHistory(upgradeDsl, "1042.11"); + + cloneProbeTables(upgradeDsl, upgradeSchema, probeSchema); + copyInstalledFunctions(upgradeDsl, upgradeSchema, probeSchema); + installProbeTriggers(probeDsl, probeSchema); + + Fixture retainedFixture = fixture(); + persistFixture(probeDsl, probeSchema, retainedFixture, Corruption.NONE); + + Flyway probeThrough104212 = + Flyway.configure() + .dataSource(probeSource) + .schemas(probeSchema) + .defaultSchema(probeSchema) + .table(HISTORY) + .baselineOnMigrate(true) + .baselineVersion(MigrationVersion.fromVersion("1042.11")) + .target(MigrationVersion.fromVersion("1042.12")) + .placeholders(Map.of("serviceSchema", probeSchema)) + .locations(worldLocation, sagaLocation) + .load(); + probeThrough104212.migrate(); + probeThrough104212.validate(); + assertThat(latestVersion(probeDsl)).isEqualTo("1042.12"); + + FunctionMetadata probeGraphBefore = functionMetadata(probeDsl, probeSchema, GRAPH_GUARD); + FunctionMetadata probeReceiptBefore = functionMetadata(probeDsl, probeSchema, RECEIPT_GUARD); + List probeGraphTriggersBefore = + triggerMetadata(probeDsl, probeSchema, "world_draft_graph_application"); + List probeReceiptTriggersBefore = + triggerMetadata(probeDsl, probeSchema, "world_draft_start_location_receipt"); + List probeApplicationRowsBefore = applicationRows(probeDsl, probeSchema); + List probeReceiptRowsBefore = receiptRows(probeDsl, probeSchema); + assertThat(probeApplicationRowsBefore).hasSize(1); + assertThat(probeReceiptRowsBefore).hasSize(1); + assertProtectedGuardMetadata( + probeGraphBefore, + probeReceiptBefore, + probeGraphTriggersBefore, + probeReceiptTriggersBefore); + + Flyway through104212 = + flyway( + upgradeSource, + upgradeSchema, + MigrationVersion.fromVersion("1042.12"), + worldLocation, + sagaLocation); + through104212.migrate(); + through104212.validate(); + assertThat(latestVersion(upgradeDsl)).isEqualTo("1042.12"); + + FunctionMetadata graphBefore = functionMetadata(upgradeDsl, upgradeSchema, GRAPH_GUARD); + FunctionMetadata receiptBefore = functionMetadata(upgradeDsl, upgradeSchema, RECEIPT_GUARD); + List graphTriggersBefore = + triggerMetadata(upgradeDsl, upgradeSchema, "world_draft_graph_application"); + List receiptTriggersBefore = + triggerMetadata(upgradeDsl, upgradeSchema, "world_draft_start_location_receipt"); + String history104212Before = migrationHistory(upgradeDsl, "1042.12"); + List applicationRowsBefore = applicationRows(upgradeDsl, upgradeSchema); + List receiptRowsBefore = receiptRows(upgradeDsl, upgradeSchema); + assertThat(applicationRowsBefore).isEmpty(); + assertThat(receiptRowsBefore).isEmpty(); + assertProtectedGuardMetadata( + graphBefore, receiptBefore, graphTriggersBefore, receiptTriggersBefore); + + Flyway current = flyway(upgradeSource, upgradeSchema, null, worldLocation, sagaLocation); + current.migrate(); + current.validate(); + assertThat(current.info().pending()).isEmpty(); + + Flyway fresh = flyway(freshSource, freshSchema, null, worldLocation, sagaLocation); + fresh.migrate(); + fresh.validate(); + assertThat(fresh.info().pending()).isEmpty(); + + Flyway probeCurrent = flyway(probeSource, probeSchema, null, worldLocation, sagaLocation); + probeCurrent.migrate(); + probeCurrent.validate(); + assertThat(probeCurrent.info().pending()).isEmpty(); + + assertThat(latestVersion(upgradeDsl)).isEqualTo("1042.13"); + assertThat(latestVersion(freshDsl)).isEqualTo(latestVersion(upgradeDsl)); + assertThat(latestVersion(probeDsl)).isEqualTo(latestVersion(upgradeDsl)); + assertThat(migrationHistory(upgradeDsl, "1012")).isEqualTo(history1012Before); + assertThat(migrationHistory(upgradeDsl, "1014")).isEqualTo(history1014Before); + assertThat(migrationHistory(upgradeDsl, "1042.11")).isEqualTo(history104211Before); + assertThat(migrationHistory(upgradeDsl, "1042.12")).isEqualTo(history104212Before); + assertThat(migrationHistory(upgradeDsl, "1042.13")).isNotNull(); + assertThat(migrationHistory(freshDsl, "1042.12")).isNotNull(); + assertThat(migrationHistory(freshDsl, "1042.13")).isNotNull(); + assertThat(applicationRows(upgradeDsl, upgradeSchema)).isEqualTo(applicationRowsBefore); + assertThat(receiptRows(upgradeDsl, upgradeSchema)).isEqualTo(receiptRowsBefore); + + FunctionMetadata graphAfter = functionMetadata(upgradeDsl, upgradeSchema, GRAPH_GUARD); + FunctionMetadata receiptAfter = functionMetadata(upgradeDsl, upgradeSchema, RECEIPT_GUARD); + assertFunctionPreservedExceptBody(graphBefore, graphAfter); + assertFunctionPreservedExceptBody(receiptBefore, receiptAfter); + assertThat(triggerMetadata(upgradeDsl, upgradeSchema, "world_draft_graph_application")) + .isEqualTo(graphTriggersBefore); + assertThat(triggerMetadata(upgradeDsl, upgradeSchema, "world_draft_start_location_receipt")) + .isEqualTo(receiptTriggersBefore); + assertDigestPredicates(graphAfter, receiptAfter); + + FunctionMetadata probeGraphAfter = functionMetadata(probeDsl, probeSchema, GRAPH_GUARD); + FunctionMetadata probeReceiptAfter = functionMetadata(probeDsl, probeSchema, RECEIPT_GUARD); + assertFunctionPreservedExceptBody(probeGraphBefore, probeGraphAfter); + assertFunctionPreservedExceptBody(probeReceiptBefore, probeReceiptAfter); + assertThat(triggerMetadata(probeDsl, probeSchema, "world_draft_graph_application")) + .isEqualTo(probeGraphTriggersBefore); + assertThat(triggerMetadata(probeDsl, probeSchema, "world_draft_start_location_receipt")) + .isEqualTo(probeReceiptTriggersBefore); + assertThat(applicationRows(probeDsl, probeSchema)).isEqualTo(probeApplicationRowsBefore); + assertThat(receiptRows(probeDsl, probeSchema)).isEqualTo(probeReceiptRowsBefore); + assertDigestPredicates(probeGraphAfter, probeReceiptAfter); + + FunctionMetadata freshGraph = functionMetadata(freshDsl, freshSchema, GRAPH_GUARD); + FunctionMetadata freshReceipt = functionMetadata(freshDsl, freshSchema, RECEIPT_GUARD); + assertProtectedGuardMetadata( + freshGraph, + freshReceipt, + triggerMetadata(freshDsl, freshSchema, "world_draft_graph_application"), + triggerMetadata(freshDsl, freshSchema, "world_draft_start_location_receipt")); + assertDigestPredicates(freshGraph, freshReceipt); + assertThat(normalizeSchema(graphAfter.source(), upgradeSchema)) + .isEqualTo(normalizeSchema(freshGraph.source(), freshSchema)); + assertThat(normalizeSchema(receiptAfter.source(), upgradeSchema)) + .isEqualTo(normalizeSchema(freshReceipt.source(), freshSchema)); + + persistFixture(probeDsl, probeSchema, fixture(), Corruption.NONE); + assertSqlState( + () -> persistFixture(probeDsl, probeSchema, fixture(), Corruption.RECEIPT_ACCOUNT_DIGEST), + "23514"); + assertSqlState( + () -> persistFixture(probeDsl, probeSchema, fixture(), Corruption.RECEIPT_DIGEST), + "23514"); + assertSqlState( + () -> persistFixture(probeDsl, probeSchema, fixture(), Corruption.RECEIPT_FIELD_MISMATCH), + "23514"); + assertSqlState( + () -> + persistFixture( + probeDsl, probeSchema, fixture(), Corruption.APPLICATION_ACCOUNT_DIGEST), + "23514"); + assertSqlState( + () -> persistFixture(probeDsl, probeSchema, fixture(), Corruption.RESULT_DIGEST), + "23514"); + assertSqlState( + () -> + persistFixture( + probeDsl, probeSchema, fixture(), Corruption.APPLICATION_RECEIPT_FIELD_MISMATCH), + "23514"); + } finally { + dropSchema(upgradeSource, upgradeSchema); + dropSchema(freshSource, freshSchema); + dropSchema(probeSource, probeSchema); + } + } + + private static void assertProtectedGuardMetadata( + FunctionMetadata graph, + FunctionMetadata receipt, + List graphTriggers, + List receiptTriggers) { + assertThat(graph.securityDefiner()).isTrue(); + assertThat(receipt.securityDefiner()).isTrue(); + assertThat(graph.configuration()).contains("search_path=pg_catalog"); + assertThat(receipt.configuration()).contains("search_path=pg_catalog"); + assertThat(graph.publicExecuteGrant()).isFalse(); + assertThat(receipt.publicExecuteGrant()).isFalse(); + assertThat(graphTriggers) + .anyMatch(value -> value.contains("trg_world_graph_application_guard")); + assertThat(receiptTriggers) + .anyMatch(value -> value.contains("trg_world_start_location_receipt_guard")); + } + + private static void assertFunctionPreservedExceptBody( + FunctionMetadata before, FunctionMetadata after) { + assertThat(after.oid()).isEqualTo(before.oid()); + assertThat(after.owner()).isEqualTo(before.owner()); + assertThat(after.acl()).isEqualTo(before.acl()); + assertThat(after.publicExecuteGrant()).isEqualTo(before.publicExecuteGrant()); + assertThat(after.securityDefiner()).isEqualTo(before.securityDefiner()); + assertThat(after.configuration()).isEqualTo(before.configuration()); + } + + private static void assertDigestPredicates(FunctionMetadata graph, FunctionMetadata receipt) { + assertThat(graph.source()) + .contains("encode(sha256(NEW.account_binding_bytes), 'hex')") + .contains("encode(sha256(NEW.result_bytes), 'hex')") + .contains("encode(sha256(receipt.account_binding_bytes), 'hex')") + .contains("world_start_location_receipt_matches(") + .doesNotContain("encode(sha256(receipt.receipt_bytes), 'hex')"); + assertThat(receipt.source()) + .contains("encode(sha256(NEW.account_binding_bytes), 'hex')") + .contains("world_start_location_receipt_matches(") + .doesNotContain("encode(sha256(NEW.receipt_bytes), 'hex')"); + } + + private static void cloneProbeTables(DSLContext dsl, String sourceSchema, String probeSchema) { + dsl.execute("CREATE SCHEMA " + DSL.name(probeSchema)); + for (String table : PROBE_TABLES) + dsl.execute( + "CREATE TABLE " + + DSL.name(probeSchema, table) + + " AS TABLE " + + DSL.name(sourceSchema, table) + + " WITH NO DATA"); + } + + private static void copyInstalledFunctions( + DSLContext dsl, String sourceSchema, String probeSchema) { + for (String function : PROBE_FUNCTIONS) { + String definition = + dsl.fetchSingle( + "SELECT pg_get_functiondef(to_regprocedure(?))", + sourceSchema + "." + function + "()") + .get(0, String.class); + definition = + definition + .replace("\"" + sourceSchema + "\"", "\"" + probeSchema + "\"") + .replace(sourceSchema + ".", probeSchema + ".") + .replace("'" + sourceSchema + "'", "'" + probeSchema + "'"); + dsl.execute(definition); + // Function definitions do not carry ACLs into this controlled clone. + dsl.execute("REVOKE ALL ON FUNCTION " + DSL.name(probeSchema, function) + "() FROM PUBLIC"); + } + } + + private static void installProbeTriggers(DSLContext dsl, String schema) { + dsl.execute( + "CREATE TRIGGER trg_world_graph_application_guard BEFORE INSERT OR UPDATE OR DELETE ON " + + DSL.name(schema, "world_draft_graph_application") + + " FOR EACH ROW EXECUTE FUNCTION " + + DSL.name(schema, GRAPH_GUARD) + + "()"); + dsl.execute( + "CREATE TRIGGER trg_world_graph_application_no_truncate BEFORE TRUNCATE ON " + + DSL.name(schema, "world_draft_graph_application") + + " FOR EACH STATEMENT EXECUTE FUNCTION " + + DSL.name(schema, "world_reject_authored_source_history_mutation") + + "()"); + dsl.execute( + "CREATE TRIGGER trg_world_start_location_receipt_guard BEFORE INSERT ON " + + DSL.name(schema, "world_draft_start_location_receipt") + + " FOR EACH ROW EXECUTE FUNCTION " + + DSL.name(schema, RECEIPT_GUARD) + + "()"); + dsl.execute( + "CREATE TRIGGER trg_world_start_location_receipt_immutable BEFORE UPDATE OR DELETE ON " + + DSL.name(schema, "world_draft_start_location_receipt") + + " FOR EACH ROW EXECUTE FUNCTION " + + DSL.name(schema, "world_reject_draft_start_location_receipt_mutation") + + "()"); + dsl.execute( + "CREATE TRIGGER trg_world_start_location_receipt_no_truncate BEFORE TRUNCATE ON " + + DSL.name(schema, "world_draft_start_location_receipt") + + " FOR EACH STATEMENT EXECUTE FUNCTION " + + DSL.name(schema, "world_reject_draft_start_location_receipt_mutation") + + "()"); + } + + private static void persistFixture( + DSLContext dsl, String schema, Fixture fixture, Corruption corruption) throws Exception { + boolean receiptFieldMismatch = + corruption == Corruption.RECEIPT_FIELD_MISMATCH + || corruption == Corruption.APPLICATION_RECEIPT_FIELD_MISMATCH; + UUID evidenceFenceId = + receiptFieldMismatch ? UUID.randomUUID() : fixture.authorizationFenceId(); + WorldDraftStartLocationEvidence receiptEvidence = receiptEvidence(fixture, evidenceFenceId); + byte[] receiptBytes = receiptEvidence.canonicalBytes(); + String claimedReceiptDigest = receiptEvidence.receiptDigest(); + String receiptDigest = + corruption == Corruption.RECEIPT_DIGEST + ? wrongDigest(claimedReceiptDigest) + : claimedReceiptDigest; + byte[] resultBytes = resultBytes(fixture, receiptBytes, receiptDigest); + String correctResultDigest = digest(resultBytes); + + dsl.transaction( + configuration -> { + DSLContext tx = DSL.using(configuration); + String commitTable = DSL.name(schema, "world_topology_draft_commit").toString(); + String ownerTable = DSL.name(schema, "world_design_publication_fence_owner").toString(); + String roomTable = DSL.name(schema, "room").toString(); + String identityTable = DSL.name(schema, "world_authored_topology_identity").toString(); + String receiptTable = DSL.name(schema, "world_draft_start_location_receipt").toString(); + String applicationTable = DSL.name(schema, "world_draft_graph_application").toString(); + + tx.execute( + "INSERT INTO " + + commitTable + + " (request_id, commit_id, target_namespace, canonical_tenant_id, " + + "canonical_version_id, local_tenant_key, local_version_key, binding_json, " + + "binding_digest, graph_bytes, graph_sha256, application_transaction_id) " + + "VALUES (?, ?, 'dev', ?, ?, ?, ?, ?::jsonb, ?, ?, ?, txid_current())", + fixture.requestId(), + fixture.commitId(), + fixture.tenantId(), + fixture.versionId(), + fixture.localTenantKey(), + fixture.localVersionKey(), + fixture.bindingJson(), + fixture.bindingDigest(), + fixture.graphBytes(), + fixture.graphSha256()); + tx.execute( + "INSERT INTO " + + ownerTable + + " (target_namespace, canonical_tenant_id, local_tenant_key, version_id, " + + "owner_freeze_phase, current_publication_fence) " + + "VALUES ('dev', ?, ?, ?, 'OPEN', NULL)", + fixture.tenantId(), + fixture.localTenantKey(), + fixture.localVersionKey()); + tx.execute( + "INSERT INTO " + roomTable + " (id, tenant_id, version_id) VALUES (?, ?, ?)", + fixture.roomRowId(), + fixture.localTenantKey(), + fixture.localVersionKey()); + tx.execute( + "INSERT INTO " + + identityTable + + " (target_namespace, canonical_tenant_id, canonical_version_id, family, " + + "template_id, private_row_key, tenant_id, version_id, " + + "version_identity_operation_id, request_id, commit_id, revision_id, revision_order) " + + "VALUES ('dev', ?, ?, 'ROOM', ?, ?, ?, ?, ?, ?, ?, ?, '0')", + fixture.tenantId(), + fixture.versionId(), + fixture.roomTemplateId(), + fixture.roomRowId(), + fixture.localTenantKey(), + fixture.localVersionKey(), + fixture.versionIdentityOperationId(), + fixture.requestId(), + fixture.commitId(), + fixture.revisionId()); + + String receiptAccountDigest = + corruption == Corruption.RECEIPT_ACCOUNT_DIGEST + ? wrongDigest(fixture.accountBindingDigest()) + : fixture.accountBindingDigest(); + boolean bypassReceiptGuard = corruption == Corruption.APPLICATION_RECEIPT_FIELD_MISMATCH; + if (bypassReceiptGuard) { + tx.execute( + "ALTER TABLE " + + receiptTable + + " DISABLE TRIGGER trg_world_start_location_receipt_guard"); + } + tx.execute( + "INSERT INTO " + + receiptTable + + " (operation_id, request_id, commit_id, authorization_fence_id, " + + "target_namespace, account_binding_bytes, account_binding_digest, binding_digest, " + + "canonical_tenant_id, canonical_version_id, room_template_id, graph_digest, " + + "receipt_digest, receipt_bytes) " + + "VALUES (?, ?, ?, ?, 'dev', ?, ?, ?, ?, ?, ?, ?, ?, ?)", + fixture.operationId(), + fixture.requestId(), + fixture.commitId(), + fixture.authorizationFenceId(), + fixture.accountBindingBytes(), + receiptAccountDigest, + fixture.bindingDigest(), + fixture.tenantId(), + fixture.versionId(), + fixture.roomTemplateId(), + fixture.graphDigest(), + receiptDigest, + receiptBytes); + if (bypassReceiptGuard) { + tx.execute( + "ALTER TABLE " + + receiptTable + + " ENABLE TRIGGER trg_world_start_location_receipt_guard"); + } + + String applicationAccountDigest = + corruption == Corruption.APPLICATION_ACCOUNT_DIGEST + ? wrongDigest(fixture.accountBindingDigest()) + : fixture.accountBindingDigest(); + String resultDigest = + corruption == Corruption.RESULT_DIGEST + ? wrongDigest(correctResultDigest) + : correctResultDigest; + tx.execute( + "INSERT INTO " + + applicationTable + + " (operation_id, request_id, commit_id, authorization_fence_id, " + + "operation_bytes, account_binding_bytes, account_binding_digest, result_bytes, " + + "result_digest, application_transaction_id) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, txid_current())", + fixture.operationId(), + fixture.requestId(), + fixture.commitId(), + fixture.authorizationFenceId(), + fixture.operationBytes(), + fixture.accountBindingBytes(), + applicationAccountDigest, + resultBytes, + resultDigest); + }); + } + + private static Fixture fixture() throws Exception { + UUID tenantId = UUID.randomUUID(); + UUID versionId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID commitId = UUID.randomUUID(); + UUID authorizationFenceId = UUID.randomUUID(); + UUID versionIdentityOperationId = UUID.randomUUID(); + UUID revisionId = UUID.randomUUID(); + UUID roomTemplateId = UUID.randomUUID(); + byte[] accountBindingBytes = + "{\"accountBinding\":\"controlled\"}".getBytes(StandardCharsets.UTF_8); + byte[] operationBytes = "{\"operation\":\"controlled\"}".getBytes(StandardCharsets.UTF_8); + byte[] graphBytes = + "{\"schemaVersion\":3,\"rows\":[{\"family\":\"ROOM\"}]}".getBytes(StandardCharsets.UTF_8); + String accountBindingDigest = digest(accountBindingBytes); + String graphDigest = digest(graphBytes); + String bindingDigest = "sha256:" + "b".repeat(64); + String bindingJson = bindingJson(tenantId, versionId, roomTemplateId); + WorldDraftStartLocationEvidence evidence = + WorldDraftStartLocationEvidence.create( + "dev", + operationId, + requestId, + commitId, + authorizationFenceId, + accountBindingDigest, + bindingDigest, + new RoomTemplateRef(tenantId, versionId, roomTemplateId), + graphDigest); + byte[] receiptBytes = evidence.canonicalBytes(); + String receiptDigest = evidence.receiptDigest(); + long privateKeyBase = NEXT_PRIVATE_KEY_BASE.getAndAdd(10); + byte[] resultBytes = + resultBytes(graphDigest, receiptBytes, receiptDigest, operationBytes, graphBytes); + return new Fixture( + tenantId, + versionId, + operationId, + requestId, + commitId, + authorizationFenceId, + versionIdentityOperationId, + revisionId, + roomTemplateId, + privateKeyBase, + privateKeyBase + 4, + privateKeyBase + 5, + accountBindingBytes, + accountBindingDigest, + receiptBytes, + receiptDigest, + operationBytes, + graphBytes, + graphDigest.substring("sha256:".length()), + graphDigest, + bindingDigest, + bindingJson, + resultBytes, + digest(resultBytes)); + } + + private static WorldDraftStartLocationEvidence receiptEvidence(Fixture fixture, UUID fenceId) { + return WorldDraftStartLocationEvidence.create( + "dev", + fixture.operationId(), + fixture.requestId(), + fixture.commitId(), + fenceId, + fixture.accountBindingDigest(), + fixture.bindingDigest(), + new RoomTemplateRef(fixture.tenantId(), fixture.versionId(), fixture.roomTemplateId()), + fixture.graphDigest()); + } + + private static byte[] resultBytes(Fixture fixture, byte[] receiptBytes, String receiptDigest) { + return resultBytes( + fixture.graphDigest(), + receiptBytes, + receiptDigest, + fixture.operationBytes(), + fixture.graphBytes()); + } + + private static byte[] resultBytes( + String graphDigest, + byte[] receiptBytes, + String receiptDigest, + byte[] operationBytes, + byte[] graphBytes) { + String resultJson = + "{\"schema\":\"world-draft-graph-applied/v2\",\"status\":\"APPLIED\"," + + "\"graphDigest\":\"" + + graphDigest + + "\",\"startLocationReceiptDigest\":\"" + + receiptDigest + + "\",\"startLocationReceiptBase64\":\"" + + Base64.getEncoder().encodeToString(receiptBytes) + + "\",\"operationBytesBase64\":\"" + + Base64.getEncoder().encodeToString(operationBytes) + + "\",\"graphBytesBase64\":\"" + + Base64.getEncoder().encodeToString(graphBytes) + + "\"}"; + return resultJson.getBytes(StandardCharsets.UTF_8); + } + + private static String bindingJson(UUID tenantId, UUID versionId, UUID roomTemplateId) { + String familyCounts = + FAMILY_NAMES.stream() + .map( + family -> + "{\"family\":\"WORLD_DESIGN_AGGREGATE_TYPE_" + + family + + "\",\"count\":" + + (family.equals("ROOM") ? 1 : 0) + + "}") + .reduce((left, right) -> left + "," + right) + .orElseThrow(); + return "{\"revisions\":[{\"owner\":\"WORLD_MANAGEMENT\",\"payload\":{" + + "\"freshGraphDeclaration\":{\"tenantId\":\"" + + tenantId + + "\",\"versionId\":\"" + + versionId + + "\",\"familyCounts\":[" + + familyCounts + + "],\"startLocation\":{\"tenantId\":\"" + + tenantId + + "\",\"versionId\":\"" + + versionId + + "\",\"roomTemplateId\":\"" + + roomTemplateId + + "\"}}}}],\"affectedUnits\":[]}"; + } + + private static FunctionMetadata functionMetadata(DSLContext dsl, String schema, String function) { + var row = + dsl.fetchSingle( + "SELECT p.oid::bigint, pg_get_userbyid(p.proowner), COALESCE(p.proacl::text, ''), " + + "EXISTS (SELECT 1 FROM pg_catalog.aclexplode(COALESCE(p.proacl, " + + "pg_catalog.acldefault('f', p.proowner))) acl " + + "WHERE acl.grantee=0::oid AND acl.privilege_type='EXECUTE'), " + + "p.prosecdef, COALESCE(p.proconfig::text, ''), pg_get_functiondef(p.oid) " + + "FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid=p.pronamespace " + + "WHERE n.nspname=? AND p.proname=? " + + "AND pg_get_function_identity_arguments(p.oid)=''", + schema, + function); + return new FunctionMetadata( + row.get(0, Long.class), + row.get(1, String.class), + row.get(2, String.class), + row.get(3, Boolean.class), + row.get(4, Boolean.class), + row.get(5, String.class), + row.get(6, String.class)); + } + + private static List triggerMetadata(DSLContext dsl, String schema, String table) { + return dsl.fetch( + "SELECT t.tgname || ':' || t.oid::text || ':' || t.tgfoid::text || ':' " + + "|| t.tgtype::text || ':' || t.tgenabled::text || ':' || t.tgdeferrable::text || ':' " + + "|| t.tginitdeferred::text || ':' || pg_get_triggerdef(t.oid) " + + "FROM pg_catalog.pg_trigger t JOIN pg_catalog.pg_class c ON c.oid=t.tgrelid " + + "JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace " + + "WHERE n.nspname=? AND c.relname=? AND NOT t.tgisinternal ORDER BY t.tgname", + schema, + table) + .getValues(0, String.class); + } + + private static List applicationRows(DSLContext dsl, String schema) { + return dsl.fetch( + "SELECT a.xmin::text || ':' || to_jsonb(a)::text FROM " + + DSL.name(schema, "world_draft_graph_application") + + " a ORDER BY operation_id") + .getValues(0, String.class); + } + + private static List receiptRows(DSLContext dsl, String schema) { + return dsl.fetch( + "SELECT r.xmin::text || ':' || to_jsonb(r)::text FROM " + + DSL.name(schema, "world_draft_start_location_receipt") + + " r ORDER BY operation_id") + .getValues(0, String.class); + } + + private static String latestVersion(DSLContext dsl) { + return dsl.fetchSingle( + "SELECT version FROM " + + HISTORY + + " WHERE success AND version IS NOT NULL ORDER BY installed_rank DESC LIMIT 1") + .get(0, String.class); + } + + private static String migrationHistory(DSLContext dsl, String version) { + return dsl.fetchSingle( + "SELECT to_jsonb(h)::text FROM " + HISTORY + " h WHERE version=? AND success", version) + .get(0, String.class); + } + + private static String normalizeSchema(String source, String schema) { + return source + .replace("\"" + schema + "\"", "\"service_schema\"") + .replace(schema + ".", "\"service_schema\".") + .replace("'" + schema + "'", "'service_schema'"); + } + + private static String digest(byte[] bytes) throws Exception { + return "sha256:" + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private static String wrongDigest(String digest) { + String hex = digest.substring(INVALID_DIGEST_PREFIX.length()); + char replacement = hex.charAt(0) == '0' ? '1' : '0'; + return INVALID_DIGEST_PREFIX + replacement + hex.substring(1); + } + + private static void assertSqlState( + org.assertj.core.api.ThrowableAssert.ThrowingCallable action, String state) { + assertThatThrownBy(action) + .satisfies( + failure -> { + Throwable cause = failure; + while (cause.getCause() != null) cause = cause.getCause(); + assertThat(cause).isInstanceOf(PSQLException.class); + assertThat(((PSQLException) cause).getSQLState()).isEqualTo(state); + }); + } + + private static DriverManagerDataSource source(String schema) { + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + return source; + } + + private static void dropSchema(DriverManagerDataSource source, String schema) + throws SQLException { + try (var connection = source.getConnection(); + var statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS " + DSL.name(schema) + " CASCADE"); + } + } + + private static String schemaName(String prefix) { + return prefix + UUID.randomUUID().toString().replace("-", ""); + } + + private enum Corruption { + NONE, + RECEIPT_ACCOUNT_DIGEST, + RECEIPT_DIGEST, + RECEIPT_FIELD_MISMATCH, + APPLICATION_ACCOUNT_DIGEST, + RESULT_DIGEST, + APPLICATION_RECEIPT_FIELD_MISMATCH + } + + private record FunctionMetadata( + long oid, + String owner, + String acl, + boolean publicExecuteGrant, + boolean securityDefiner, + String configuration, + String source) {} + + private record Fixture( + UUID tenantId, + UUID versionId, + UUID operationId, + UUID requestId, + UUID commitId, + UUID authorizationFenceId, + UUID versionIdentityOperationId, + UUID revisionId, + UUID roomTemplateId, + long localTenantKey, + long localVersionKey, + long roomRowId, + byte[] accountBindingBytes, + String accountBindingDigest, + byte[] receiptBytes, + String receiptDigest, + byte[] operationBytes, + byte[] graphBytes, + String graphSha256, + String graphDigest, + String bindingDigest, + String bindingJson, + byte[] resultBytes, + String resultDigest) {} +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java index 5230e989d5..b4457c4a2c 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java @@ -1,5 +1,11 @@ package net.firedevops.firemud.worldmanagement.tenant; +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.HISTORY; +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.PARENT_MIGRATIONS; +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.flyway; +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.repositoryRoot; +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.sagaMigrations; +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.worldMigrations; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -66,125 +72,23 @@ * Bounded native upgrade from the literal d7c8f84 World/Saga parent. External source and Version * values are controlled; real World repositories retain them with all storage guards enabled. The * parent World row is legacy storage, not a Human frozen graph or canonical activation claim. - * Physical Docker execution with zero skips is required to qualify this definition. + * Positive component storage remains explicitly historical at 1007.1; the retained schema-2 + * snapshot upgrades through the current default frontier. The guarded-store case also repeats its + * relevant denials at the current frontier. These component cases do not qualify current Account + * permission or genuine Human authority. Physical Docker execution with zero skips is required to + * qualify this definition. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") class WorldGuardedAuthoredGraphCapturePostgresIntegrationTest { - private static final String HISTORY = "flyway_schema_history_world_management_service"; private static final String NAMESPACE = "firemud"; - // Exact SHA-256 bytes at d7c8f84fa947644a651304205803c3919c81684e: 31 World and 3 Saga. - private static final Map PARENT_MIGRATIONS = - Map.ofEntries( - Map.entry( - "V1000__create_saga_schema.sql", - "13f58ab66bd9c12483e113c8758ef9907ab3d14d47f61a298dd18f929d5aa537"), - Map.entry( - "V1001__saga_instance_table.sql", - "ebc4bbfd1a10314850e19ca6017d654a98c2ee4f5b95d1cce2ee078d990eb2bf"), - Map.entry( - "V1002__saga_step_table.sql", - "d9d98a2e51d53d78d17d27b15fe696e8b1e161af7c6de142680ec7b8a0dc7c31"), - Map.entry( - "V10__room_exit_direction.sql", - "9b174b153af563916b409abdad3da24f2d88f8a547de6d2b1f1085da3f06264e"), - Map.entry( - "V11__room_localized_text_variants.sql", - "cded77589b64b740689276c96e346ffff97226294b72ef184ab9ae5eaeea7b65"), - Map.entry( - "V12__world_instance_activation.sql", - "3fb5eecc00edb542dd45dd8dd11a632732f47277f96cae4bfc26ebf0f905fa62"), - Map.entry( - "V13__world_instance_termination.sql", - "894f7002fe67c6c65ab04018be7802c78b505666a0d16e2d2794eac4fccd54d4"), - Map.entry( - "V14__room_instance_topology.sql", - "4134d648bb29fd22e4e9d0b0df38454a698f1ab9449c1118c027a4e256658bc4"), - Map.entry( - "V15__zone_instance_topology.sql", - "413445894f5f39eb726e5824566c7bacab8ab81e7c51aadfe3d5917544395677"), - Map.entry( - "V16__runtime_world_event_scope.sql", - "905ac02e6a65308ab70fc5e986608131043c7eec7a2ebd1615f13652d36a4ffb"), - Map.entry( - "V17__world_instance_remap_set.sql", - "286a77a1110a9f3b8d7f88a6a829edb5551dbef73f02de1cdbf184c5947181d8"), - Map.entry( - "V18__version_scoped_world_templates.sql", - "02b07237b04c64d9f4215c42b4cefe31bdc05bd066c6f0823f14733a9772819b"), - Map.entry( - "V19__world_design_mutation_ledger.sql", - "fbbec4b460ce5aa9d4ea9dce70b156840c4cb8d99a0a1589771bad7a220d2f59"), - Map.entry( - "V1__init.sql", "7c65f75f6d2e32f7c07e24ea0260768e5660987a54a9148cef3422f5352bee64"), - Map.entry( - "V20__world_entity_spawn_binding.sql", - "ac5c8c2c326f47c4782c5595d7bbde478320ebb05bcde14f8e02a3bee158afd7"), - Map.entry( - "V21__scoped_generation_rules.sql", - "9e358fe5dd4a41f92a5b16681ad2adc7d24b969e5f476152228b2462974e68dd"), - Map.entry( - "V22__room_instance_internal_record_naming.sql", - "f56fce69e28c9dd9457dc508b016657480abd78d2a3190e782b8e2c0e3c4f340"), - Map.entry( - "V23.0.1__world_run_owned_fixture_launch_binding.sql", - "f014485e67b32b6404bb5cd40dc5568c2d1d9bc1993bafe826660c5b438ceecc"), - Map.entry( - "V23.1__world_authored_source_intake.sql", - "a7ac30d48da1911eb3395716e827ac0f0ec612970d4f40b5a27530d634430445"), - Map.entry( - "V23__initial_admission_bind_hold.sql", - "5e6f6070a02fbf09836dcc663ee3c12390dcb0dbea33a9e15ddd021a913ca1f1"), - Map.entry( - "V24__world_canonical_tenant_mutation_guard.sql", - "6ad0933008cea2d0fe28c8e247277950f789ac1f6cc061f1204b23cb044e82ea"), - Map.entry( - "V25__world_design_publication_fence.sql", - "c852a2e24232df5aec8628c1046570b49edb465a416bbdf942b60fe80ae17f94"), - Map.entry( - "V26__world_complete_launch_binding.sql", - "171595e883d8d459bfd05b8331cc2ace6faf41406b26a743cdc6d133cba33f7e"), - Map.entry( - "V27.1__world_publication_owner_binding.sql", - "93def8666763a08b1db34fd3db88cfa9eea0d5bc7bf836cffe9ff8766d0468f1"), - Map.entry( - "V27.2__world_legacy_tenant_claim_concurrency.sql", - "5a0c8de956baf2dce47e45bff6b3e022dd24d6a4c7c0ebeb4d55fdafb757f9bc"), - Map.entry( - "V27__world_authored_version_identity.sql", - "e9ff823152776361f2ac79d08b6dddce72105892fce0706041e8956994d8db0d"), - Map.entry( - "V2__add_tenant_and_expiration.sql", - "180a5c49ce5dc144daeb442c833921a410c51828f8196d1bbb4e6fe2d1955838"), - Map.entry( - "V3__world_events.sql", - "b6aaa18a6f01c7270e062a9cf8d2b13e0a57a092e7f418b87eaa382e3c9f3f3d"), - Map.entry( - "V4__room_exits.sql", - "02fbaee1e529649fa6dbe803795ac78cc40f5121735399131592b32bd23cb23a"), - Map.entry( - "V5__generation_rules.sql", - "27ba4f1827c6eafa14ccd6a4b85c9eb5c3de312ee85cdcae2da846ee1d8817a4"), - Map.entry( - "V6__region_shard.sql", - "a8bca5bad73f02936a8971cc9c34c19921d02bee55f860cad08d2c73932025cb"), - Map.entry( - "V7__optimistic_locking_and_indexes.sql", - "40d428bf21b99351068ee6cf11778ab3171f720f00ad2d8c9230b245093f9261"), - Map.entry( - "V8__region_generation_metadata.sql", - "a3bc7811eff6743f771346188f811b14d882356f67ccdbf6213bb2cc87695570"), - Map.entry( - "V9__region_spacing_multiplier.sql", - "5a5e2279d78b88cfad19802bbdf37416df714ee864265b08472b61fb234b6c32")); - @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); @Test - void exactParentWithRetainedOwnerAndLegacyWorldRowsUpgradesInDefaultOrder( + void exactParentWithRetainedOwnerAndLegacyWorldRowsUpgradesToHistoricalGuardedFrontier( @TempDir Path parentMigrations) throws Exception { Path root = repositoryRoot(); Path worldMigrations = @@ -208,7 +112,7 @@ void exactParentWithRetainedOwnerAndLegacyWorldRowsUpgradesInDefaultOrder( dataSource.setSchema(schema); var dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); try { - Flyway parent = flyway(dataSource, schema, "filesystem:" + parentMigrations); + Flyway parent = flyway(dataSource, schema, null, "filesystem:" + parentMigrations); assertThat(parent.getConfiguration().isOutOfOrder()).isFalse(); parent.migrate(); parent.validate(); @@ -315,10 +219,15 @@ void exactParentWithRetainedOwnerAndLegacyWorldRowsUpgradesInDefaultOrder( assertThat(originalRows.get(table)).isNotEmpty(); } - // Actual service filesystem locations, including Saga; no repair, baseline, or outOfOrder. + // Historical 40-migration frontier from actual World/Saga locations, with every guard on. + // Current default-frontier retention is a separate native proof, not inferred here. Flyway current = flyway( - dataSource, schema, "filesystem:" + worldMigrations, "filesystem:" + sagaMigrations); + dataSource, + schema, + MigrationVersion.fromVersion("1007.1"), + "filesystem:" + worldMigrations, + "filesystem:" + sagaMigrations); assertThat(current.getConfiguration().isOutOfOrder()).isFalse(); current.migrate(); current.validate(); @@ -430,21 +339,10 @@ void schemaTwoRepositorySnapshotRetainsEveryOriginalByteAndXminThroughSchemaThre write.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); Path root = repositoryRoot(); - String worldLocation = - "filesystem:" - + root.resolve("services/world-management-service/src/main/resources/db/migration"); - String sagaLocation = - "filesystem:" + root.resolve("services/common-saga/src/main/resources/db/migration/saga"); + String worldLocation = worldMigrations(root); + String sagaLocation = sagaMigrations(root); try { - Flyway.configure() - .dataSource(source) - .schemas(schema) - .defaultSchema(schema) - .table(HISTORY) - .placeholders(Map.of("serviceSchema", schema)) - .locations(worldLocation, sagaLocation) - .target(MigrationVersion.fromVersion("1006")) - .load() + flyway(source, schema, MigrationVersion.fromVersion("1006"), worldLocation, sagaLocation) .migrate(); AuthoredWorldSourceEvidence upstream = controlledSource(); @@ -604,7 +502,9 @@ void schemaTwoRepositorySnapshotRetainsEveryOriginalByteAndXminThroughSchemaThre List before = retainedRows(dsl, "world_authored_graph_snapshot", columns); assertThat(before).hasSize(1); - flyway(source, schema, worldLocation, sagaLocation).migrate(); + // Keep the default current frontier: historical bytes/xmin remain retained storage + // through later guards, not newly minted schema-3 or Account-protected capture authority. + flyway(source, schema, null, worldLocation, sagaLocation).migrate(); assertThat( dsl.fetch( @@ -630,8 +530,10 @@ void schemaTwoRepositorySnapshotRetainsEveryOriginalByteAndXminThroughSchemaThre } @Test - void actualGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoint() throws Exception { - String schema = "world_guarded_graph_" + UUID.randomUUID().toString().replace("-", ""); + void historicalGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoint() + throws Exception { + String schema = + "world_historical_guarded_graph_" + UUID.randomUUID().toString().replace("-", ""); var source = new DriverManagerDataSource( postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); @@ -642,15 +544,12 @@ void actualGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoint() write.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); Path root = repositoryRoot(); + String worldLocation = worldMigrations(root); + String sagaLocation = sagaMigrations(root); try { - flyway( - source, - schema, - "filesystem:" - + root.resolve( - "services/world-management-service/src/main/resources/db/migration"), - "filesystem:" - + root.resolve("services/common-saga/src/main/resources/db/migration/saga")) + // Controlled permission-unverified component storage at the historical guarded frontier. + // Later Account/APPLIED owners retain their default-current denial requirements. + flyway(source, schema, MigrationVersion.fromVersion("1007.1"), worldLocation, sagaLocation) .migrate(); assertCanonicalFrozenMutationTriggerBindings(dsl, schema); var upstream = controlledSource(); @@ -851,7 +750,8 @@ void actualGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoint() "f".repeat(64), 1L, workflow); - // The checkpoint comes from the actual current digest writer. It does not prove APPLIED. + // The checkpoint comes from the actual historical component digest writer. It does not prove + // APPLIED. var frozen = Objects.requireNonNull( write.execute( @@ -890,7 +790,8 @@ void actualGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoint() actual.contentDigest(), actual.digestSchemaVersion(), tuples); - // Current capture must deny the actual synthetic checkpoint rather than invent APPLIED rows. + // Historical schema-3 capture must deny the synthetic checkpoint without invented APPLIED + // rows. var snapshotRepository = new WorldAuthoredGraphSnapshotRepository(dsl); var graphCapture = new WorldAuthoredGraphSnapshotCapture(dsl, digest, snapshotRepository); assertThatThrownBy(() -> write.execute(status -> graphCapture.capture(capture))) @@ -1036,6 +937,118 @@ void actualGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoint() dsl.fetch("SELECT to_jsonb(t)::text FROM world_topology_draft_commit t") .getValues(0, String.class)) .isEqualTo(rowsBefore); + + // Historical proof above remains separately attributed. These current-frontier denials + // cover refusal branches; the wrong-checkpoint probe does not isolate commit-mismatch + // causality. + Flyway currentFrontier = flyway(source, schema, null, worldLocation, sagaLocation); + currentFrontier.migrate(); + currentFrontier.validate(); + assertThat(currentFrontier.info().pending()).isEmpty(); + // V1012 added nullable application_transaction_id to retained draft-commit rows. Capture a + // complete row-image baseline after that historical-to-current schema change so the + // following denials prove current-frontier atomicity without conflating migration metadata. + List currentTopologyCommitRowsBefore = + dsl.fetch("SELECT to_jsonb(t)::text FROM world_topology_draft_commit t") + .getValues(0, String.class); + List currentRegionRowsBefore = + dsl.fetch( + "SELECT xmin::text || ':' || to_jsonb(r)::text FROM region r " + + "WHERE tenant_id=? ORDER BY id", + intake.localTenantKey()) + .getValues(0, String.class); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE region SET name='naked at current frontier' WHERE tenant_id=?", + intake.localTenantKey())) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .satisfies(exception -> assertThat(sqlState(exception)).isEqualTo("23514")); + assertThat( + dsl.fetch( + "SELECT xmin::text || ':' || to_jsonb(r)::text FROM region r " + + "WHERE tenant_id=? ORDER BY id", + intake.localTenantKey()) + .getValues(0, String.class)) + .isEqualTo(currentRegionRowsBefore); + + assertThatThrownBy(() -> write.execute(status -> graphCapture.capture(capture))) + .isInstanceOf(WorldAuthoredGraphSnapshotRepository.MissingOwnerHistoryException.class) + .hasMessageContaining("retained V19 revision history"); + assertThatThrownBy( + () -> + insertCanonicalFrozenCandidate( + dsl, + plan, + schemaTwoCapture, + stored, + mapper.writeValueAsString(schemaTwoCapture), + identityJson, + intakeJson)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("New canonical graph capture requires selected closure schema 4") + .satisfies(exception -> assertThat(sqlState(exception)).isEqualTo("23514")); + + // Override only the serialized freeze-request schema to cover the schema-4 checkpoint + // refusal branch with the original appliedCommitId. This establishes branch coverage, not + // isolated commit-mismatch causality. + var currentMatchingCheckpointFreezeRequest = + (tools.jackson.databind.node.ObjectNode) mapper.valueToTree(capture); + currentMatchingCheckpointFreezeRequest.put("digestSchemaVersion", 4); + assertThatThrownBy( + () -> + insertCanonicalFrozenCandidate( + dsl, + plan, + capture, + stored, + mapper.writeValueAsString(currentMatchingCheckpointFreezeRequest), + identityJson, + intakeJson)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("differs from exact FROZEN source and checkpoint") + .satisfies(exception -> assertThat(sqlState(exception)).isEqualTo("23514")); + + var currentWrongCheckpointCapture = + new WorldAuthoredGraphSnapshot.CaptureRequest( + capture.targetNamespace(), + capture.canonicalTenantId(), + capture.canonicalVersionId(), + capture.intakeRequestId(), + capture.publicationFence(), + capture.publicationRequestId(), + capture.requestDigest(), + capture.versionStateEpoch(), + capture.publishWorkflowId(), + capture.appliedCommitId() + "-current-mismatch", + capture.contentDigest(), + 3, + capture.suppliedOwnedAffectedTuples()); + var currentWrongCheckpointFreezeRequest = + (tools.jackson.databind.node.ObjectNode) + mapper.valueToTree(currentWrongCheckpointCapture); + currentWrongCheckpointFreezeRequest.put("digestSchemaVersion", 4); + assertThatThrownBy( + () -> + insertCanonicalFrozenCandidate( + dsl, + plan, + currentWrongCheckpointCapture, + stored, + mapper.writeValueAsString(currentWrongCheckpointFreezeRequest), + identityJson, + intakeJson)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("differs from exact FROZEN source and checkpoint") + .satisfies(exception -> assertThat(sqlState(exception)).isEqualTo("23514")); + assertThat( + dsl.fetchSingle("SELECT count(*) FROM world_canonical_frozen_topology") + .get(0, Long.class)) + .isZero(); + assertThat( + dsl.fetch("SELECT to_jsonb(t)::text FROM world_topology_draft_commit t") + .getValues(0, String.class)) + .isEqualTo(currentTopologyCommitRowsBefore); } finally { dsl.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); } @@ -1314,17 +1327,6 @@ private static AuthoredWorldSourceEvidence controlledSource() { "NEW_GAME_ROW")); } - private static Flyway flyway(DriverManagerDataSource source, String schema, String... locations) { - return Flyway.configure() - .dataSource(source) - .schemas(schema) - .defaultSchema(schema) - .table(HISTORY) - .placeholders(Map.of("serviceSchema", schema)) - .locations(locations) - .load(); - } - private static List history(DSLContext dsl) { return dsl.fetch( "SELECT to_jsonb(t)::text FROM " @@ -1349,13 +1351,4 @@ private static List retainedRows( + ") retained ORDER BY to_jsonb(retained)::text") .getValues(0, String.class); } - - private static Path repositoryRoot() { - Path candidate = Path.of("").toAbsolutePath(); - while (candidate != null) { - if (Files.exists(candidate.resolve("settings.gradle.kts"))) return candidate; - candidate = candidate.getParent(); - } - throw new IllegalStateException("Unable to locate repository filesystem migrations"); - } } diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldTerminalAndLocationOwnerGuardsPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldTerminalAndLocationOwnerGuardsPostgresIntegrationTest.java new file mode 100644 index 0000000000..0ce38dcbe0 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldTerminalAndLocationOwnerGuardsPostgresIntegrationTest.java @@ -0,0 +1,1465 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.HISTORY; +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.flyway; +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.repositoryRoot; +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.sagaMigrations; +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.worldMigrations; +import static org.assertj.core.api.Assertions.assertThat; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Savepoint; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Exercises the V1042.6, V1042.8, and V1042.10 forward owner-guard repairs against native + * PostgreSQL. Malformed terminal inputs run through test-local probes built from the installed + * function body; they do not create production owner rows or claim Account-authorized admission. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class WorldTerminalAndLocationOwnerGuardsPostgresIntegrationTest { + private static final String BINDING_CONSTRAINT = "ck_world_draft_terminal_binding"; + private static final String LOCATION_FUNCTION = "world_require_initial_location_operation_result"; + private static final String LOCATION_TRIGGER = + "trg_world_require_initial_location_operation_result"; + private static final String TERMINAL_FUNCTION = "world_draft_terminal_outcome_guard"; + private static final String TERMINAL_TRIGGER = "trg_world_draft_terminal_outcome_guard"; + private static final String LOCATION_DELETE_TRIGGER = + "trg_world_reject_character_location_delete"; + private static final String LOCATION_TRUNCATE_TRIGGER = + "trg_world_reject_character_location_truncate"; + private static final String LOCATION_RETENTION_FUNCTION = + "world_reject_authored_source_history_mutation"; + private static final String OPERATION_TRUNCATE_TRIGGER = + "trg_world_reject_initial_location_operation_truncate"; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void defaultInstallAndForwardUpgradeEnforceTerminalUnitsAndOwnerGuards() throws Exception { + Path root = repositoryRoot(); + String worldLocation = worldMigrations(root); + String sagaLocation = sagaMigrations(root); + String upgradeSchema = schemaName("world_guard_upgrade_"); + String freshSchema = schemaName("world_guard_fresh_"); + DriverManagerDataSource upgradeSource = source(upgradeSchema); + DriverManagerDataSource freshSource = source(freshSchema); + DSLContext upgradeDsl = DSL.using(upgradeSource, SQLDialect.POSTGRES); + DSLContext freshDsl = DSL.using(freshSource, SQLDialect.POSTGRES); + + try (AutoCloseable freshSchemaCleanup = () -> dropSchema(freshSource, freshSchema); + AutoCloseable upgradeSchemaCleanup = () -> dropSchema(upgradeSource, upgradeSchema)) { + Flyway through10425 = + flyway( + upgradeSource, + upgradeSchema, + MigrationVersion.fromVersion("1042.5"), + worldLocation, + sagaLocation); + through10425.migrate(); + through10425.validate(); + assertThat(latestVersion(upgradeDsl)).isEqualTo("1042.5"); + + String oldTerminalConstraint = constraintDefinition(upgradeDsl, upgradeSchema); + String oldTerminalHistory = migrationHistory(upgradeDsl, "1010"); + String oldLocationHistory = migrationHistory(upgradeDsl, "1019"); + LocationFunctionMetadata before = locationFunctionMetadata(upgradeDsl, upgradeSchema); + assertThat(before.publicExecuteGrant()).isFalse(); + assertThat(before.triggerDeferrable()).isTrue(); + assertThat(before.triggerInitiallyDeferred()).isTrue(); + assertThat(before.triggerEnabled()).isEqualTo("O"); + + // The exact V1010 predicate admits UNKNOWN in CHECK context when a required JSON key is + // absent or JSON null. This table copies only that installed predicate and is not a + // production terminal outcome or an Account-authorized abort. + exerciseTerminalBindingProbe(upgradeSource, oldTerminalConstraint, false); + + List productionRowsBefore = productionLocationRows(upgradeDsl, upgradeSchema); + assertThat(productionRowsBefore).isEmpty(); + + Flyway through10426 = + flyway( + upgradeSource, + upgradeSchema, + MigrationVersion.fromVersion("1042.6"), + worldLocation, + sagaLocation); + through10426.migrate(); + through10426.validate(); + assertThat(latestVersion(upgradeDsl)).isEqualTo("1042.6"); + assertThat(migrationHistory(upgradeDsl, "1010")).isEqualTo(oldTerminalHistory); + assertThat(migrationHistory(upgradeDsl, "1019")).isEqualTo(oldLocationHistory); + + String currentTerminalConstraint = constraintDefinition(upgradeDsl, upgradeSchema); + assertThat(currentTerminalConstraint).contains("IS TRUE"); + exerciseTerminalBindingProbe(upgradeSource, currentTerminalConstraint, true); + + LocationFunctionMetadata after = locationFunctionMetadata(upgradeDsl, upgradeSchema); + assertFunctionMetadataPreserved(before, after); + assertOnlyAppliedOperationIdentityWasAdded(before.functionSource(), after.functionSource()); + + // The pre-upgrade copy accepts a location owned by another operation because V1019 did not + // bind the APPLIED lookup to NEW.operation_id. After V1042.6, exact ownership commits and + // the otherwise identical borrowed-operation case is rejected at deferred commit. + exerciseLocationOperationProbe( + upgradeSource, upgradeSchema, before.functionSource(), true, false); + exerciseLocationOperationProbe( + upgradeSource, upgradeSchema, after.functionSource(), true, true); + exerciseLocationOperationProbe( + upgradeSource, upgradeSchema, after.functionSource(), false, false); + assertThat(productionLocationRows(upgradeDsl, upgradeSchema)).isEqualTo(productionRowsBefore); + + String repairedTerminalHistory = migrationHistory(upgradeDsl, "1042.6"); + Flyway through10427 = + flyway( + upgradeSource, + upgradeSchema, + MigrationVersion.fromVersion("1042.7"), + worldLocation, + sagaLocation); + through10427.migrate(); + through10427.validate(); + assertThat(latestVersion(upgradeDsl)).isEqualTo("1042.7"); + String predecessorHistory = migrationHistory(upgradeDsl, "1042.7"); + TerminalFunctionMetadata terminalBefore = terminalFunctionMetadata(upgradeDsl, upgradeSchema); + assertThat(terminalBefore.publicExecuteGrant()).isFalse(); + assertThat(terminalBefore.securityDefiner()).isTrue(); + List terminalRowsBefore = productionTerminalRows(upgradeDsl, upgradeSchema); + assertThat(terminalRowsBefore).isEmpty(); + + Flyway through10429 = + flyway( + upgradeSource, + upgradeSchema, + MigrationVersion.fromVersion("1042.9"), + worldLocation, + sagaLocation); + through10429.migrate(); + through10429.validate(); + assertThat(latestVersion(upgradeDsl)).isEqualTo("1042.9"); + TriggerMetadata operationTruncateBefore = + triggerMetadata( + upgradeDsl, + upgradeSchema, + "world_canonical_initial_player_location_operation", + OPERATION_TRUNCATE_TRIGGER); + assertThat(operationTruncateBefore.enabled()).isEqualTo("O"); + assertThat(operationTruncateBefore.definition()).contains("BEFORE TRUNCATE"); + assertThat( + triggerCount( + upgradeDsl, upgradeSchema, "character_location", LOCATION_DELETE_TRIGGER)) + .isZero(); + assertThat( + triggerCount( + upgradeDsl, upgradeSchema, "character_location", LOCATION_TRUNCATE_TRIGGER)) + .isZero(); + List locationRowsBeforeRetentionMigration = + productionLocationRows(upgradeDsl, upgradeSchema); + + Flyway current = flyway(upgradeSource, upgradeSchema, null, worldLocation, sagaLocation); + current.migrate(); + current.validate(); + assertThat(current.info().pending()).isEmpty(); + assertThat(migrationHistory(upgradeDsl, "1042.6")).isEqualTo(repairedTerminalHistory); + assertThat(migrationHistory(upgradeDsl, "1042.7")).isEqualTo(predecessorHistory); + assertThat(migrationHistory(upgradeDsl, "1010")).isEqualTo(oldTerminalHistory); + assertThat(migrationHistory(upgradeDsl, "1019")).isEqualTo(oldLocationHistory); + assertThat(constraintDefinition(upgradeDsl, upgradeSchema)) + .isEqualTo(currentTerminalConstraint); + LocationFunctionMetadata atCurrentFrontier = + locationFunctionMetadata(upgradeDsl, upgradeSchema); + assertFunctionMetadataPreserved(after, atCurrentFrontier); + TerminalFunctionMetadata terminalAfter = terminalFunctionMetadata(upgradeDsl, upgradeSchema); + assertTerminalFunctionMetadataPreserved(terminalBefore, terminalAfter); + List terminalRowsAfter = productionTerminalRows(upgradeDsl, upgradeSchema); + assertThat(terminalRowsAfter).isEqualTo(terminalRowsBefore); + exerciseTerminalAffectedUnitProbe( + upgradeSource, upgradeSchema, terminalAfter.functionSource()); + + // A clean default installation must also land on the same repaired frontier. + Flyway fresh = flyway(freshSource, freshSchema, null, worldLocation, sagaLocation); + fresh.migrate(); + fresh.validate(); + assertThat(fresh.info().pending()).isEmpty(); + assertThat(constraintDefinition(freshDsl, freshSchema)).contains("IS TRUE"); + assertThat( + normalizeFunctionSource( + locationFunctionMetadata(freshDsl, freshSchema).functionSource(), freshSchema)) + .isEqualTo(normalizeFunctionSource(after.functionSource(), upgradeSchema)); + TerminalFunctionMetadata freshTerminal = terminalFunctionMetadata(freshDsl, freshSchema); + assertThat(freshTerminal.publicExecuteGrant()).isFalse(); + assertThat(freshTerminal.securityDefiner()).isTrue(); + assertThat(normalizeSchemaQualifier(freshTerminal.functionSource(), freshSchema)) + .isEqualTo(normalizeSchemaQualifier(terminalAfter.functionSource(), upgradeSchema)); + assertThat(productionTerminalRows(freshDsl, freshSchema)).isEmpty(); + assertThat(productionLocationRows(freshDsl, freshSchema)).isEmpty(); + + assertThat(MigrationVersion.fromVersion(latestVersion(upgradeDsl))) + .isGreaterThanOrEqualTo(MigrationVersion.fromVersion("1042.10")); + assertThat(latestVersion(freshDsl)).isEqualTo(latestVersion(upgradeDsl)); + assertThat(productionLocationRows(upgradeDsl, upgradeSchema)) + .isEqualTo(locationRowsBeforeRetentionMigration); + assertLocationRetentionGuards(upgradeDsl, upgradeSchema); + assertLocationRetentionGuards(freshDsl, freshSchema); + assertThat( + triggerMetadata( + upgradeDsl, + upgradeSchema, + "world_canonical_initial_player_location_operation", + OPERATION_TRUNCATE_TRIGGER)) + .isEqualTo(operationTruncateBefore); + assertSqlState( + upgradeSource, + "TRUNCATE TABLE \"" + + upgradeSchema + + "\".world_canonical_initial_player_location_operation, \"" + + upgradeSchema + + "\".character_location", + "55000"); + assertSqlState( + upgradeSource, "TRUNCATE TABLE \"" + upgradeSchema + "\".character_location", "55000"); + exerciseCharacterLocationDeleteProbe(upgradeSource, upgradeSchema); + assertSqlState( + freshSource, + "TRUNCATE TABLE \"" + + freshSchema + + "\".world_canonical_initial_player_location_operation, \"" + + freshSchema + + "\".character_location", + "55000"); + assertSqlState( + freshSource, "TRUNCATE TABLE \"" + freshSchema + "\".character_location", "55000"); + exerciseCharacterLocationDeleteProbe(freshSource, freshSchema); + } + } + + private static void exerciseTerminalBindingProbe( + DriverManagerDataSource source, String installedConstraint, boolean strict) + throws SQLException { + TerminalBinding row = TerminalBinding.create(); + try (Connection connection = source.getConnection(); + Statement statement = connection.createStatement()) { + connection.setAutoCommit(false); + statement.execute( + "CREATE TEMP TABLE terminal_binding_probe (" + + "binding_json TEXT NOT NULL, owner_binding_json TEXT NOT NULL, " + + "canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, " + + "request_id UUID NOT NULL, commit_id UUID NOT NULL, target_namespace TEXT NOT NULL, " + + "version_identity_operation_id UUID NOT NULL, CONSTRAINT copied_installed_binding " + + installedConstraint + + ") ON COMMIT DROP"); + + insertTerminalProbe(connection, row.bindingJson(), row.ownerBindingJson(), row); + List requiredBindingKeys = + List.of("canonicalTenantId", "canonicalVersionId", "requestId", "commitId"); + List requiredOwnerKeys = + List.of( + "targetNamespace", + "canonicalTenantId", + "canonicalVersionId", + "versionIdentityOperationId"); + for (String key : requiredBindingKeys) { + String omitted = json(row.bindingValues(), key, Mutation.OMIT); + String jsonNull = json(row.bindingValues(), key, Mutation.NULL); + assertTerminalProbeOutcome(connection, row, omitted, row.ownerBindingJson(), strict); + assertTerminalProbeOutcome(connection, row, jsonNull, row.ownerBindingJson(), strict); + } + for (String key : requiredOwnerKeys) { + String omitted = json(row.ownerBindingValues(), key, Mutation.OMIT); + String jsonNull = json(row.ownerBindingValues(), key, Mutation.NULL); + assertTerminalProbeOutcome(connection, row, row.bindingJson(), omitted, strict); + assertTerminalProbeOutcome(connection, row, row.bindingJson(), jsonNull, strict); + } + connection.commit(); + } + } + + private static void assertTerminalProbeOutcome( + Connection connection, + TerminalBinding row, + String bindingJson, + String ownerBindingJson, + boolean strict) + throws SQLException { + Savepoint savepoint = connection.setSavepoint(); + try { + insertTerminalProbe(connection, bindingJson, ownerBindingJson, row); + if (strict) { + throw new AssertionError("Installed terminal binding CHECK accepted an incomplete tuple"); + } + connection.releaseSavepoint(savepoint); + } catch (SQLException failure) { + connection.rollback(savepoint); + if (!strict) throw failure; + assertThat(failure.getSQLState()).isEqualTo("23514"); + } + } + + private static void exerciseTerminalAffectedUnitProbe( + DriverManagerDataSource source, String schema, String functionSource) throws SQLException { + UUID tenantId = UUID.randomUUID(); + UUID versionId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID commitId = UUID.randomUUID(); + UUID aggregateId = UUID.randomUUID(); + UUID maxAggregateId = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + String targetNamespace = "terminal-guard-probe"; + long localTenantKey = 71_001L; + long localVersionKey = 81_001L; + long aggregateKey = 91_001L; + long maxAggregateKey = 91_002L; + + try (Connection connection = source.getConnection(); + Statement statement = connection.createStatement()) { + connection.setAutoCommit(false); + statement.execute( + "CREATE TEMP TABLE world_design_publication_fence_owner (" + + "target_namespace TEXT, canonical_tenant_id UUID, local_tenant_key BIGINT, " + + "version_id BIGINT, owner_freeze_phase TEXT, current_publication_fence UUID) " + + "ON COMMIT DROP"); + statement.execute( + "CREATE TEMP TABLE world_region_draft_commit (request_id UUID, commit_id UUID) " + + "ON COMMIT DROP"); + statement.execute( + "CREATE TEMP TABLE world_topology_draft_commit (request_id UUID, commit_id UUID) " + + "ON COMMIT DROP"); + statement.execute( + "CREATE TEMP TABLE world_authored_topology_identity (" + + "target_namespace TEXT, canonical_tenant_id UUID, canonical_version_id UUID, " + + "request_id UUID, commit_id UUID, private_row_key BIGINT, family TEXT, " + + "template_id UUID) ON COMMIT DROP"); + statement.execute( + "CREATE TEMP TABLE world_design_revision_ledger (" + + "tenant_id BIGINT, version_id BIGINT, commit_id TEXT) ON COMMIT DROP"); + statement.execute( + "CREATE TEMP TABLE world_design_aggregate_epoch (" + + "tenant_id BIGINT, version_id BIGINT, aggregate_type TEXT, aggregate_id BIGINT, " + + "draft_revision_epoch BIGINT) ON COMMIT DROP"); + statement.execute( + "CREATE TEMP TABLE world_design_scope_epoch (" + + "tenant_id BIGINT, version_id BIGINT, scope_type TEXT, scope_id TEXT, " + + "draft_scope_revision_epoch BIGINT) ON COMMIT DROP"); + statement.execute( + "CREATE TEMP TABLE world_draft_terminal_outcome_probe (" + + "target_namespace TEXT, canonical_tenant_id UUID, canonical_version_id UUID, " + + "local_tenant_key BIGINT, " + + "local_version_key BIGINT, request_id UUID, commit_id UUID, " + + "affected_units_json JSONB NOT NULL) ON COMMIT DROP"); + + try (PreparedStatement owner = + connection.prepareStatement( + "INSERT INTO pg_temp.world_design_publication_fence_owner VALUES (?, ?, ?, ?, 'OPEN', NULL)")) { + owner.setString(1, targetNamespace); + owner.setObject(2, tenantId); + owner.setLong(3, localTenantKey); + owner.setLong(4, localVersionKey); + owner.executeUpdate(); + } + insertTerminalProbeIdentity( + connection, targetNamespace, tenantId, versionId, aggregateId, aggregateKey, 4L); + insertTerminalProbeIdentity( + connection, + targetNamespace, + tenantId, + versionId, + maxAggregateId, + maxAggregateKey, + Long.MAX_VALUE); + try (PreparedStatement scope = + connection.prepareStatement( + "INSERT INTO pg_temp.world_design_scope_epoch VALUES (?, ?, 'REGION_SUBTREE', ?, 7)")) { + scope.setLong(1, localTenantKey); + scope.setLong(2, localVersionKey); + scope.setString(3, scopeId.toString()); + scope.executeUpdate(); + } + + String schemaQualifier = "\"" + schema + "\"."; + assertThat(functionSource).contains(schemaQualifier + "world_design_publication_fence_owner"); + String probeBody = functionSource.replace(schemaQualifier, "pg_temp."); + statement.execute( + "CREATE FUNCTION pg_temp.world_draft_terminal_outcome_guard_probe() RETURNS TRIGGER " + + "LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $probe$\n" + + probeBody + + "\n$probe$"); + statement.execute( + "CREATE TRIGGER terminal_outcome_probe_guard BEFORE INSERT " + + "ON pg_temp.world_draft_terminal_outcome_probe FOR EACH ROW " + + "EXECUTE FUNCTION pg_temp.world_draft_terminal_outcome_guard_probe()"); + + String validAggregate = + terminalUnitJson( + aggregateId, + aggregateId, + true, + "\"WORLD_MANAGEMENT\"", + true, + "\"AGGREGATE\"", + true, + "4"); + // Existing World writers use JSON integer epochs and DraftCommitBinding uses canonical + // decimal strings, so the installed guard must retain both representations. + String validScope = + terminalUnitJson( + aggregateId, + scopeId, + true, + "\"WORLD_MANAGEMENT\"", + true, + "\"REGION_SUBTREE\"", + true, + "\"7\""); + String validMaximum = + terminalUnitJson( + maxAggregateId, + maxAggregateId, + true, + "\"WORLD_MANAGEMENT\"", + true, + "\"AGGREGATE\"", + true, + "\"9223372036854775807\""); + insertTerminalAffectedUnitProbe( + connection, + targetNamespace, + tenantId, + versionId, + localTenantKey, + localVersionKey, + requestId, + commitId, + "[" + validAggregate + "," + validScope + "," + validMaximum + "]"); + + assertTerminalAffectedUnitRejected( + connection, + targetNamespace, + tenantId, + versionId, + localTenantKey, + localVersionKey, + requestId, + commitId, + "missing owner", + "[" + + terminalUnitJson( + aggregateId, aggregateId, false, "", true, "\"AGGREGATE\"", true, "4") + + "]"); + assertTerminalAffectedUnitRejected( + connection, + targetNamespace, + tenantId, + versionId, + localTenantKey, + localVersionKey, + requestId, + commitId, + "null owner", + "[" + + terminalUnitJson( + aggregateId, aggregateId, true, "null", true, "\"AGGREGATE\"", true, "4") + + "]"); + assertTerminalAffectedUnitRejected( + connection, + targetNamespace, + tenantId, + versionId, + localTenantKey, + localVersionKey, + requestId, + commitId, + "foreign owner", + "[" + + terminalUnitJson( + aggregateId, + aggregateId, + true, + "\"ENTITY_MANAGEMENT\"", + true, + "\"AGGREGATE\"", + true, + "4") + + "]"); + assertTerminalAffectedUnitRejected( + connection, + targetNamespace, + tenantId, + versionId, + localTenantKey, + localVersionKey, + requestId, + commitId, + "missing scope type", + "[" + + terminalUnitJson( + aggregateId, scopeId, true, "\"WORLD_MANAGEMENT\"", false, "", true, "0") + + "]"); + assertTerminalAffectedUnitRejected( + connection, + targetNamespace, + tenantId, + versionId, + localTenantKey, + localVersionKey, + requestId, + commitId, + "null scope type", + "[" + + terminalUnitJson( + aggregateId, scopeId, true, "\"WORLD_MANAGEMENT\"", true, "null", true, "0") + + "]"); + assertTerminalAffectedUnitRejected( + connection, + targetNamespace, + tenantId, + versionId, + localTenantKey, + localVersionKey, + requestId, + commitId, + "unknown scope type", + "[" + + terminalUnitJson( + aggregateId, + scopeId, + true, + "\"WORLD_MANAGEMENT\"", + true, + "\"UNKNOWN\"", + true, + "0") + + "]"); + + assertInvalidTerminalEpoch( + connection, + targetNamespace, + tenantId, + versionId, + localTenantKey, + localVersionKey, + requestId, + commitId, + aggregateId, + "missing epoch", + false, + ""); + assertInvalidTerminalEpoch( + connection, + targetNamespace, + tenantId, + versionId, + localTenantKey, + localVersionKey, + requestId, + commitId, + aggregateId, + "null epoch", + true, + "null"); + assertInvalidTerminalEpoch( + connection, + targetNamespace, + tenantId, + versionId, + localTenantKey, + localVersionKey, + requestId, + commitId, + aggregateId, + "malformed string epoch", + true, + "\"not-a-counter\""); + assertInvalidTerminalEpoch( + connection, + targetNamespace, + tenantId, + versionId, + localTenantKey, + localVersionKey, + requestId, + commitId, + aggregateId, + "fractional epoch", + true, + "4.4"); + assertInvalidTerminalEpoch( + connection, + targetNamespace, + tenantId, + versionId, + localTenantKey, + localVersionKey, + requestId, + commitId, + aggregateId, + "negative epoch", + true, + "-1"); + assertInvalidTerminalEpoch( + connection, + targetNamespace, + tenantId, + versionId, + localTenantKey, + localVersionKey, + requestId, + commitId, + aggregateId, + "out-of-range epoch", + true, + "9223372036854775808"); + assertInvalidTerminalEpoch( + connection, + targetNamespace, + tenantId, + versionId, + localTenantKey, + localVersionKey, + requestId, + commitId, + aggregateId, + "noncanonical decimal string epoch", + true, + "\"04\""); + connection.commit(); + } + } + + private static void insertTerminalProbeIdentity( + Connection connection, + String targetNamespace, + UUID tenantId, + UUID versionId, + UUID templateId, + long aggregateKey, + long epoch) + throws SQLException { + try (PreparedStatement identity = + connection.prepareStatement( + "INSERT INTO pg_temp.world_authored_topology_identity " + + "(target_namespace,canonical_tenant_id,canonical_version_id,request_id,commit_id," + + "private_row_key,family,template_id) VALUES (?, ?, ?, ?, ?, ?, 'REGION', ?)"); + PreparedStatement aggregate = + connection.prepareStatement( + "INSERT INTO pg_temp.world_design_aggregate_epoch " + + "VALUES (?, ?, 'REGION', ?, ?)")) { + identity.setString(1, targetNamespace); + identity.setObject(2, tenantId); + identity.setObject(3, versionId); + identity.setObject(4, UUID.randomUUID()); + identity.setObject(5, UUID.randomUUID()); + identity.setLong(6, aggregateKey); + identity.setObject(7, templateId); + identity.executeUpdate(); + aggregate.setLong(1, 71_001L); + aggregate.setLong(2, 81_001L); + aggregate.setLong(3, aggregateKey); + aggregate.setLong(4, epoch); + aggregate.executeUpdate(); + } + } + + private static void assertInvalidTerminalEpoch( + Connection connection, + String targetNamespace, + UUID tenantId, + UUID versionId, + long localTenantKey, + long localVersionKey, + UUID requestId, + UUID commitId, + UUID aggregateId, + String label, + boolean includeEpoch, + String epochJson) + throws SQLException { + String unit = + terminalUnitJson( + aggregateId, + aggregateId, + true, + "\"WORLD_MANAGEMENT\"", + true, + "\"AGGREGATE\"", + includeEpoch, + epochJson); + assertTerminalAffectedUnitRejected( + connection, + targetNamespace, + tenantId, + versionId, + localTenantKey, + localVersionKey, + requestId, + commitId, + label, + "[" + unit + "]"); + } + + private static String terminalUnitJson( + UUID aggregateId, + UUID scopeId, + boolean includeOwner, + String ownerJson, + boolean includeScopeType, + String scopeTypeJson, + boolean includeExpectedEpoch, + String expectedEpochJson) { + List fields = new ArrayList<>(); + fields.add("\"aggregateType\":\"REGION\""); + fields.add("\"aggregateId\":\"" + aggregateId + "\""); + if (includeOwner) fields.add("\"owner\":" + ownerJson); + if (includeScopeType) fields.add("\"scopeType\":" + scopeTypeJson); + fields.add("\"scopeId\":\"" + scopeId + "\""); + if (includeExpectedEpoch) fields.add("\"expectedEpoch\":" + expectedEpochJson); + return "{" + String.join(",", fields) + "}"; + } + + private static void assertTerminalAffectedUnitRejected( + Connection connection, + String targetNamespace, + UUID tenantId, + UUID versionId, + long localTenantKey, + long localVersionKey, + UUID requestId, + UUID commitId, + String label, + String affectedUnitsJson) + throws SQLException { + Savepoint savepoint = connection.setSavepoint(); + try { + insertTerminalAffectedUnitProbe( + connection, + targetNamespace, + tenantId, + versionId, + localTenantKey, + localVersionKey, + requestId, + commitId, + affectedUnitsJson); + throw new AssertionError("Installed terminal guard accepted " + label); + } catch (SQLException failure) { + connection.rollback(savepoint); + assertThat(failure.getSQLState()).as(label).isEqualTo("23514"); + } + } + + private static void insertTerminalAffectedUnitProbe( + Connection connection, + String targetNamespace, + UUID tenantId, + UUID versionId, + long localTenantKey, + long localVersionKey, + UUID requestId, + UUID commitId, + String affectedUnitsJson) + throws SQLException { + try (PreparedStatement insert = + connection.prepareStatement( + "INSERT INTO pg_temp.world_draft_terminal_outcome_probe " + + "(target_namespace, canonical_tenant_id, canonical_version_id, local_tenant_key, " + + "local_version_key, request_id, commit_id, affected_units_json) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?::jsonb)")) { + insert.setString(1, targetNamespace); + insert.setObject(2, tenantId); + insert.setObject(3, versionId); + insert.setLong(4, localTenantKey); + insert.setLong(5, localVersionKey); + insert.setObject(6, requestId); + insert.setObject(7, commitId); + insert.setString(8, affectedUnitsJson); + insert.executeUpdate(); + } + } + + private static void insertTerminalProbe( + Connection connection, String bindingJson, String ownerBindingJson, TerminalBinding row) + throws SQLException { + try (PreparedStatement insert = + connection.prepareStatement( + "INSERT INTO pg_temp.terminal_binding_probe VALUES (?, ?, ?, ?, ?, ?, ?, ?)")) { + insert.setString(1, bindingJson); + insert.setString(2, ownerBindingJson); + insert.setObject(3, row.tenantId()); + insert.setObject(4, row.versionId()); + insert.setObject(5, row.requestId()); + insert.setObject(6, row.commitId()); + insert.setString(7, row.targetNamespace()); + insert.setObject(8, row.versionIdentityOperationId()); + insert.executeUpdate(); + } + } + + private static void exerciseLocationOperationProbe( + DriverManagerDataSource source, + String schema, + String functionSource, + boolean borrowedOperation, + boolean shouldReject) + throws SQLException { + PlacementEvidence evidence = PlacementEvidence.create(); + UUID locationOperationId = UUID.randomUUID(); + UUID operationId = borrowedOperation ? UUID.randomUUID() : locationOperationId; + String lookupAnchor = "FROM \"" + schema + "\".character_location l"; + assertThat(occurrences(functionSource, lookupAnchor)).isEqualTo(2); + String probeFunctionSource = + functionSource.replace(lookupAnchor, "FROM pg_temp.initial_location_probe l"); + + SQLException commitFailure = null; + try (Connection connection = source.getConnection(); + Statement statement = connection.createStatement()) { + connection.setAutoCommit(false); + statement.execute( + "CREATE TEMP TABLE initial_location_probe (" + + "canonical_tenant_id UUID, playable_state_namespace_id UUID, " + + "canonical_game_instance_id UUID, canonical_account_id UUID, character_id UUID, " + + "entity_assignment_operation_id UUID, entity_assignment_digest TEXT, " + + "canonical_version_id UUID, initial_room_template_id UUID, " + + "initial_runtime_room_instance_id BIGINT, initial_admission_hold_id UUID, " + + "initial_admission_hold_fence UUID, realm_id UUID, world_slug TEXT, " + + "playable_state_scope TEXT, active_lifecycle_epoch BIGINT, " + + "initial_admission_request_id TEXT, initial_admission_request_digest TEXT, " + + "catalog_revision BIGINT, initial_admission_owner_proof_id TEXT, " + + "initial_admission_owner_proof_digest TEXT, pointer_audit_id TEXT, " + + "pointer_version BIGINT, initial_location_operation_id UUID) ON COMMIT DROP"); + statement.execute( + "CREATE TEMP TABLE initial_location_operation_probe (" + + "operation_id UUID NOT NULL, canonical_tenant_id UUID NOT NULL, " + + "playable_state_namespace_id UUID NOT NULL, canonical_game_instance_id UUID NOT NULL, " + + "request_bytes BYTEA NOT NULL, result_bytes BYTEA NOT NULL, " + + "outcome TEXT NOT NULL) ON COMMIT DROP"); + statement.execute( + "CREATE FUNCTION pg_temp.initial_location_operation_result_probe() RETURNS TRIGGER " + + "LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, \"" + + schema + + "\" AS $probe$" + + probeFunctionSource + + "$probe$"); + statement.execute( + "CREATE CONSTRAINT TRIGGER initial_location_operation_probe_deferred AFTER INSERT ON " + + "pg_temp.initial_location_operation_probe DEFERRABLE INITIALLY DEFERRED FOR EACH ROW " + + "EXECUTE FUNCTION pg_temp.initial_location_operation_result_probe()"); + insertPlacement(connection, evidence, locationOperationId); + insertLocationOperation(connection, evidence, operationId); + try { + connection.commit(); + } catch (SQLException failure) { + commitFailure = failure; + connection.rollback(); + } + } + + if (shouldReject) { + assertThat((Throwable) commitFailure) + .as("the copied deferred APPLIED guard rejects a location owned by another operation") + .isNotNull(); + assertThat(commitFailure.getSQLState()).isEqualTo("23514"); + assertThat(commitFailure.getMessage()) + .contains("Applied World initial-location operation has no atomic location row"); + } else { + assertThat((Throwable) commitFailure).isNull(); + } + } + + private static void insertPlacement( + Connection connection, PlacementEvidence evidence, UUID locationOperationId) + throws SQLException { + try (PreparedStatement insert = + connection.prepareStatement( + "INSERT INTO pg_temp.initial_location_probe VALUES (" + + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) { + int i = 1; + insert.setObject(i++, evidence.tenantId()); + insert.setObject(i++, evidence.playableNamespaceId()); + insert.setObject(i++, evidence.gameInstanceId()); + insert.setObject(i++, evidence.accountId()); + insert.setObject(i++, evidence.characterId()); + insert.setObject(i++, evidence.assignmentOperationId()); + insert.setString(i++, evidence.assignmentDigest()); + insert.setObject(i++, evidence.versionId()); + insert.setObject(i++, evidence.roomTemplateId()); + insert.setLong(i++, evidence.runtimeRoomId()); + insert.setObject(i++, evidence.holdId()); + insert.setObject(i++, evidence.holdFence()); + insert.setObject(i++, evidence.realmId()); + insert.setString(i++, evidence.worldSlug()); + insert.setString(i++, evidence.playableScope()); + insert.setLong(i++, evidence.lifecycleEpoch()); + insert.setString(i++, evidence.admissionRequestId()); + insert.setString(i++, evidence.admissionRequestDigest()); + insert.setLong(i++, evidence.catalogRevision()); + insert.setString(i++, evidence.ownerProofId()); + insert.setString(i++, evidence.ownerProofDigest()); + insert.setString(i++, evidence.pointerAuditId()); + insert.setLong(i++, evidence.pointerVersion()); + insert.setObject(i, locationOperationId); + insert.executeUpdate(); + } + } + + private static void insertLocationOperation( + Connection connection, PlacementEvidence evidence, UUID operationId) throws SQLException { + try (PreparedStatement insert = + connection.prepareStatement( + "INSERT INTO pg_temp.initial_location_operation_probe VALUES (?, ?, ?, ?, ?, ?, 'APPLIED')")) { + insert.setObject(1, operationId); + insert.setObject(2, evidence.tenantId()); + insert.setObject(3, evidence.playableNamespaceId()); + insert.setObject(4, evidence.gameInstanceId()); + insert.setBytes(5, evidence.requestJson().getBytes(StandardCharsets.UTF_8)); + insert.setBytes(6, evidence.resultJson().getBytes(StandardCharsets.UTF_8)); + insert.executeUpdate(); + } + } + + private static String constraintDefinition(DSLContext dsl, String schema) { + return dsl.fetchSingle( + "SELECT pg_get_constraintdef(c.oid) FROM pg_constraint c " + + "JOIN pg_class t ON t.oid=c.conrelid JOIN pg_namespace n ON n.oid=t.relnamespace " + + "WHERE n.nspname=? AND t.relname='world_draft_terminal_outcome' AND c.conname=?", + schema, + BINDING_CONSTRAINT) + .get(0, String.class); + } + + private static LocationFunctionMetadata locationFunctionMetadata(DSLContext dsl, String schema) { + var row = + dsl.fetchSingle( + "SELECT p.oid::bigint AS function_oid,p.proowner::regrole::text AS function_owner," + + "p.proacl::text AS function_acl,p.prosecdef AS security_definer," + + "p.proconfig::text AS function_config,p.prosrc AS function_source,l.lanname AS language," + + "t.oid::bigint AS trigger_oid,t.tgfoid::bigint AS trigger_function_oid," + + "t.tgdeferrable AS trigger_deferrable,t.tginitdeferred AS trigger_initially_deferred," + + "t.tgenabled::text AS trigger_enabled,pg_get_triggerdef(t.oid) AS trigger_definition," + + "(SELECT count(*) FROM aclexplode(COALESCE(p.proacl,acldefault('f',p.proowner))) a " + + "WHERE a.grantee=0 AND a.privilege_type='EXECUTE') AS public_execute_grants " + + "FROM pg_proc p JOIN pg_namespace pn ON pn.oid=p.pronamespace " + + "JOIN pg_language l ON l.oid=p.prolang JOIN pg_trigger t ON t.tgfoid=p.oid " + + "JOIN pg_class c ON c.oid=t.tgrelid JOIN pg_namespace tn ON tn.oid=c.relnamespace " + + "WHERE pn.nspname=? AND tn.nspname=? AND p.proname=? AND t.tgname=?", + schema, + schema, + LOCATION_FUNCTION, + LOCATION_TRIGGER); + return new LocationFunctionMetadata( + row.get("function_oid", Long.class), + row.get("function_owner", String.class), + row.get("function_acl", String.class), + row.get("security_definer", Boolean.class), + row.get("function_config", String.class), + row.get("function_source", String.class), + row.get("language", String.class), + row.get("trigger_oid", Long.class), + row.get("trigger_function_oid", Long.class), + row.get("trigger_deferrable", Boolean.class), + row.get("trigger_initially_deferred", Boolean.class), + row.get("trigger_enabled", String.class), + row.get("trigger_definition", String.class), + row.get("public_execute_grants", Long.class) > 0); + } + + private static TriggerMetadata triggerMetadata( + DSLContext dsl, String schema, String table, String trigger) { + var row = + dsl.fetchSingle( + "SELECT t.oid::bigint AS trigger_oid,t.tgfoid::bigint AS function_oid," + + "t.tgenabled::text AS enabled,pg_get_triggerdef(t.oid) AS definition " + + "FROM pg_trigger t JOIN pg_class c ON c.oid=t.tgrelid " + + "JOIN pg_namespace n ON n.oid=c.relnamespace " + + "WHERE n.nspname=? AND c.relname=? AND t.tgname=? AND NOT t.tgisinternal", + schema, + table, + trigger); + return new TriggerMetadata( + row.get("trigger_oid", Long.class), + row.get("function_oid", Long.class), + row.get("enabled", String.class), + row.get("definition", String.class)); + } + + private static long triggerCount(DSLContext dsl, String schema, String table, String trigger) { + return dsl.fetchSingle( + "SELECT count(*) FROM pg_trigger t JOIN pg_class c ON c.oid=t.tgrelid " + + "JOIN pg_namespace n ON n.oid=c.relnamespace " + + "WHERE n.nspname=? AND c.relname=? AND t.tgname=? AND NOT t.tgisinternal", + schema, + table, + trigger) + .get(0, Long.class); + } + + private static void assertLocationRetentionGuards(DSLContext dsl, String schema) { + long sharedFunctionOid = + dsl.fetchSingle( + "SELECT p.oid::bigint FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace " + + "WHERE n.nspname=? AND p.proname=? AND pg_get_function_identity_arguments(p.oid)=''", + schema, + LOCATION_RETENTION_FUNCTION) + .get(0, Long.class); + TriggerMetadata delete = + triggerMetadata(dsl, schema, "character_location", LOCATION_DELETE_TRIGGER); + TriggerMetadata truncate = + triggerMetadata(dsl, schema, "character_location", LOCATION_TRUNCATE_TRIGGER); + assertThat(delete.enabled()).isEqualTo("O"); + assertThat(delete.functionOid()).isEqualTo(sharedFunctionOid); + assertThat(delete.definition()).contains("BEFORE DELETE"); + assertThat(truncate.enabled()).isEqualTo("O"); + assertThat(truncate.functionOid()).isEqualTo(sharedFunctionOid); + assertThat(truncate.definition()).contains("BEFORE TRUNCATE"); + } + + private static void assertSqlState( + DriverManagerDataSource source, String sql, String expectedSqlState) throws SQLException { + try (Connection connection = source.getConnection(); + Statement statement = connection.createStatement()) { + try { + statement.execute(sql); + throw new AssertionError("Expected SQLSTATE " + expectedSqlState + " for: " + sql); + } catch (SQLException failure) { + assertThat(failure.getSQLState()).isEqualTo(expectedSqlState); + } + } + } + + private static void exerciseCharacterLocationDeleteProbe( + DriverManagerDataSource source, String schema) throws SQLException { + // Test-local probe: genuine APPLIED rows require future Account/World admission authority. + // This exercises the installed immutable-history function without fabricating that authority. + try (Connection connection = source.getConnection(); + Statement statement = connection.createStatement()) { + statement.execute( + "CREATE TEMP TABLE character_location_delete_probe (marker INTEGER NOT NULL)"); + statement.execute( + "CREATE TRIGGER trg_world_probe_character_location_delete BEFORE DELETE ON " + + "character_location_delete_probe FOR EACH ROW EXECUTE FUNCTION \"" + + schema + + "\"." + + LOCATION_RETENTION_FUNCTION + + "()"); + statement.execute("INSERT INTO character_location_delete_probe VALUES (1)"); + try { + statement.execute("DELETE FROM character_location_delete_probe"); + throw new AssertionError("Test-local character-location deletion probe was not rejected"); + } catch (SQLException failure) { + assertThat(failure.getSQLState()).isEqualTo("55000"); + } + } + } + + private static TerminalFunctionMetadata terminalFunctionMetadata(DSLContext dsl, String schema) { + var row = + dsl.fetchSingle( + "SELECT p.oid::bigint AS function_oid,p.proowner::regrole::text AS function_owner," + + "p.proacl::text AS function_acl,p.prosecdef AS security_definer," + + "p.proconfig::text AS function_config,p.prosrc AS function_source,l.lanname AS language," + + "t.oid::bigint AS trigger_oid,t.tgfoid::bigint AS trigger_function_oid," + + "t.tgdeferrable AS trigger_deferrable,t.tginitdeferred AS trigger_initially_deferred," + + "t.tgenabled::text AS trigger_enabled,pg_get_triggerdef(t.oid) AS trigger_definition," + + "(SELECT count(*) FROM aclexplode(COALESCE(p.proacl,acldefault('f',p.proowner))) a " + + "WHERE a.grantee=0 AND a.privilege_type='EXECUTE') AS public_execute_grants " + + "FROM pg_proc p JOIN pg_namespace pn ON pn.oid=p.pronamespace " + + "JOIN pg_language l ON l.oid=p.prolang JOIN pg_trigger t ON t.tgfoid=p.oid " + + "JOIN pg_class c ON c.oid=t.tgrelid JOIN pg_namespace tn ON tn.oid=c.relnamespace " + + "WHERE pn.nspname=? AND tn.nspname=? AND p.proname=? AND t.tgname=?", + schema, + schema, + TERMINAL_FUNCTION, + TERMINAL_TRIGGER); + return new TerminalFunctionMetadata( + row.get("function_oid", Long.class), + row.get("function_owner", String.class), + row.get("function_acl", String.class), + row.get("security_definer", Boolean.class), + row.get("function_config", String.class), + row.get("function_source", String.class), + row.get("language", String.class), + row.get("trigger_oid", Long.class), + row.get("trigger_function_oid", Long.class), + row.get("trigger_deferrable", Boolean.class), + row.get("trigger_initially_deferred", Boolean.class), + row.get("trigger_enabled", String.class), + row.get("trigger_definition", String.class), + row.get("public_execute_grants", Long.class) > 0); + } + + private static void assertFunctionMetadataPreserved( + LocationFunctionMetadata before, LocationFunctionMetadata after) { + assertThat(after.functionOid()).isEqualTo(before.functionOid()); + assertThat(after.functionOwner()).isEqualTo(before.functionOwner()); + assertThat(after.functionAcl()).isEqualTo(before.functionAcl()); + assertThat(after.securityDefiner()).isEqualTo(before.securityDefiner()).isTrue(); + assertThat(after.functionConfig()).isEqualTo(before.functionConfig()); + assertThat(after.language()).isEqualTo(before.language()).isEqualTo("plpgsql"); + assertThat(after.triggerOid()).isEqualTo(before.triggerOid()); + assertThat(after.triggerFunctionOid()).isEqualTo(before.triggerFunctionOid()); + assertThat(after.triggerDeferrable()).isEqualTo(before.triggerDeferrable()).isTrue(); + assertThat(after.triggerInitiallyDeferred()) + .isEqualTo(before.triggerInitiallyDeferred()) + .isTrue(); + assertThat(after.triggerEnabled()).isEqualTo(before.triggerEnabled()).isEqualTo("O"); + assertThat(after.triggerDefinition()).isEqualTo(before.triggerDefinition()); + assertThat(after.publicExecuteGrant()).isEqualTo(before.publicExecuteGrant()).isFalse(); + assertThat(after.functionConfig()).contains("search_path=pg_catalog"); + } + + private static void assertTerminalFunctionMetadataPreserved( + TerminalFunctionMetadata before, TerminalFunctionMetadata after) { + assertThat(after.functionOid()).isEqualTo(before.functionOid()); + assertThat(after.functionOwner()).isEqualTo(before.functionOwner()); + assertThat(after.functionAcl()).isEqualTo(before.functionAcl()); + assertThat(after.securityDefiner()).isEqualTo(before.securityDefiner()).isTrue(); + assertThat(after.functionConfig()).isEqualTo(before.functionConfig()); + assertThat(after.language()).isEqualTo(before.language()).isEqualTo("plpgsql"); + assertThat(after.triggerOid()).isEqualTo(before.triggerOid()); + assertThat(after.triggerFunctionOid()).isEqualTo(before.triggerFunctionOid()); + assertThat(after.triggerDeferrable()).isEqualTo(before.triggerDeferrable()).isFalse(); + assertThat(after.triggerInitiallyDeferred()) + .isEqualTo(before.triggerInitiallyDeferred()) + .isFalse(); + assertThat(after.triggerEnabled()).isEqualTo(before.triggerEnabled()).isEqualTo("O"); + assertThat(after.triggerDefinition()).isEqualTo(before.triggerDefinition()); + assertThat(after.publicExecuteGrant()).isEqualTo(before.publicExecuteGrant()).isFalse(); + assertThat(after.functionConfig()).contains("search_path=pg_catalog"); + } + + private static void assertOnlyAppliedOperationIdentityWasAdded(String before, String after) { + String normalizedBefore = normalizeSql(before); + String normalizedAfter = normalizeSql(after); + String appliedIdentityPredicate = + "and l.initial_location_operation_id = new.operation_id and l.canonical_account_id = "; + assertThat( + occurrences(normalizedAfter, "and l.initial_location_operation_id = new.operation_id")) + .isEqualTo( + occurrences(normalizedBefore, "and l.initial_location_operation_id = new.operation_id") + + 1); + assertThat(normalizedAfter) + .contains(appliedIdentityPredicate) + .doesNotContain("initial_location_operation_id = new.operation_id::"); + assertThat(normalizedAfter.replace(appliedIdentityPredicate, "and l.canonical_account_id = ")) + .isEqualTo(normalizedBefore); + } + + private static List productionLocationRows(DSLContext dsl, String schema) { + return dsl.fetch( + "SELECT 'operation:' || xmin::text || ':' || to_jsonb(o)::text FROM \"" + + schema + + "\".world_canonical_initial_player_location_operation o " + + "UNION ALL SELECT 'location:' || xmin::text || ':' || to_jsonb(l)::text FROM \"" + + schema + + "\".character_location l ORDER BY 1") + .getValues(0, String.class); + } + + private static List productionTerminalRows(DSLContext dsl, String schema) { + return dsl.fetch( + "SELECT jsonb_build_object('xmin',t.xmin::text,'row',to_jsonb(t))::text FROM \"" + + schema + + "\".world_draft_terminal_outcome t ORDER BY t.operation_id") + .getValues(0, String.class); + } + + private static String latestVersion(DSLContext dsl) { + return dsl.fetchSingle( + "SELECT version FROM " + + HISTORY + + " WHERE success AND version IS NOT NULL ORDER BY installed_rank DESC LIMIT 1") + .get(0, String.class); + } + + private static String migrationHistory(DSLContext dsl, String version) { + return dsl.fetchSingle( + "SELECT to_jsonb(h)::text FROM " + HISTORY + " h WHERE version=? AND success", version) + .get(0, String.class); + } + + private static DriverManagerDataSource source(String schema) { + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + return source; + } + + private static void dropSchema(DriverManagerDataSource source, String schema) + throws SQLException { + try (Connection connection = source.getConnection(); + Statement statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + } + + private static String schemaName(String prefix) { + return prefix + UUID.randomUUID().toString().replace("-", ""); + } + + private static String json(Map values, String changedKey, Mutation mutation) { + StringBuilder result = new StringBuilder("{"); + boolean first = true; + for (var entry : values.entrySet()) { + if (entry.getKey().equals(changedKey) && mutation == Mutation.OMIT) continue; + if (!first) result.append(','); + first = false; + result.append('"').append(entry.getKey()).append("\":"); + if (entry.getKey().equals(changedKey) && mutation == Mutation.NULL) { + result.append("null"); + } else { + result.append('"').append(entry.getValue()).append('"'); + } + } + return result.append('}').toString(); + } + + private static String normalizeSql(String sql) { + return sql.replaceAll("\\s+", " ").trim().toLowerCase(Locale.ROOT); + } + + private static String normalizeFunctionSource(String source, String schema) { + return normalizeSql( + source.replace( + "FROM \"" + schema + "\".character_location l", + "FROM .character_location l")); + } + + private static String normalizeSchemaQualifier(String source, String schema) { + return normalizeSql(source.replace("\"" + schema + "\".", ".")); + } + + private static int occurrences(String value, String fragment) { + int count = 0; + int start = 0; + while ((start = value.indexOf(fragment, start)) >= 0) { + count++; + start += fragment.length(); + } + return count; + } + + private enum Mutation { + OMIT, + NULL + } + + private record TerminalBinding( + UUID tenantId, + UUID versionId, + UUID requestId, + UUID commitId, + UUID versionIdentityOperationId, + String targetNamespace) { + private static TerminalBinding create() { + return new TerminalBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "firemud"); + } + + private Map bindingValues() { + Map result = new LinkedHashMap<>(); + result.put("canonicalTenantId", tenantId.toString()); + result.put("canonicalVersionId", versionId.toString()); + result.put("requestId", requestId.toString()); + result.put("commitId", commitId.toString()); + return result; + } + + private Map ownerBindingValues() { + Map result = new LinkedHashMap<>(); + result.put("targetNamespace", targetNamespace); + result.put("canonicalTenantId", tenantId.toString()); + result.put("canonicalVersionId", versionId.toString()); + result.put("versionIdentityOperationId", versionIdentityOperationId.toString()); + return result; + } + + private String bindingJson() { + return json(bindingValues(), "", Mutation.OMIT); + } + + private String ownerBindingJson() { + return json(ownerBindingValues(), "", Mutation.OMIT); + } + } + + private record PlacementEvidence( + UUID tenantId, + UUID playableNamespaceId, + UUID gameInstanceId, + UUID accountId, + UUID characterId, + UUID assignmentOperationId, + String assignmentDigest, + UUID versionId, + UUID roomTemplateId, + long runtimeRoomId, + UUID holdId, + UUID holdFence, + UUID realmId, + String worldSlug, + String playableScope, + long lifecycleEpoch, + String admissionRequestId, + String admissionRequestDigest, + long catalogRevision, + String ownerProofId, + String ownerProofDigest, + String pointerAuditId, + long pointerVersion) { + private static PlacementEvidence create() { + UUID versionId = UUID.randomUUID(); + UUID roomTemplateId = UUID.randomUUID(); + long runtimeRoomId = 991L; + return new PlacementEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "a".repeat(64), + versionId, + roomTemplateId, + runtimeRoomId, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "test-world", + "ISOLATED", + 3L, + "admission-request", + "b".repeat(64), + 7L, + "owner-proof", + "c".repeat(64), + "pointer-audit", + 11L); + } + + private String requestJson() { + String startLocation = startLocationJson(); + return "{\"canonicalAccountId\":\"" + + accountId + + "\",\"characterId\":\"" + + characterId + + "\",\"entityAssignmentOperationId\":\"" + + assignmentOperationId + + "\",\"entityAssignmentDigest\":\"" + + assignmentDigest + + "\",\"initialAdmissionHoldId\":\"" + + holdId + + "\",\"initialAdmissionHoldFence\":\"" + + holdFence + + "\",\"realmId\":\"" + + realmId + + "\",\"worldSlug\":\"" + + worldSlug + + "\",\"playableStateScope\":\"" + + playableScope + + "\",\"activeLifecycleEvidence\":{\"lifecycleEpoch\":\"" + + lifecycleEpoch + + "\",\"request\":{\"canonicalVersionId\":\"" + + versionId + + "\"},\"startLocation\":" + + startLocation + + ",\"runtimeRoomInstanceId\":\"" + + runtimeRoomId + + "\"},\"initialAdmissionRequestId\":\"" + + admissionRequestId + + "\",\"initialAdmissionRequestDigest\":\"" + + admissionRequestDigest + + "\",\"catalogRevision\":\"" + + catalogRevision + + "\",\"initialAdmissionOwnerProofId\":\"" + + ownerProofId + + "\",\"initialAdmissionOwnerProofDigest\":\"" + + ownerProofDigest + + "\",\"pointerAuditId\":\"" + + pointerAuditId + + "\",\"pointerVersion\":\"" + + pointerVersion + + "\"}"; + } + + private String resultJson() { + return "{\"startLocation\":" + + startLocationJson() + + ",\"runtimeRoomInstanceId\":\"" + + runtimeRoomId + + "\"}"; + } + + private String startLocationJson() { + return "{\"tenantId\":\"" + + tenantId + + "\",\"versionId\":\"" + + versionId + + "\",\"roomTemplateId\":\"" + + roomTemplateId + + "\"}"; + } + } + + private record LocationFunctionMetadata( + long functionOid, + String functionOwner, + String functionAcl, + boolean securityDefiner, + String functionConfig, + String functionSource, + String language, + long triggerOid, + long triggerFunctionOid, + boolean triggerDeferrable, + boolean triggerInitiallyDeferred, + String triggerEnabled, + String triggerDefinition, + boolean publicExecuteGrant) {} + + private record TerminalFunctionMetadata( + long functionOid, + String functionOwner, + String functionAcl, + boolean securityDefiner, + String functionConfig, + String functionSource, + String language, + long triggerOid, + long triggerFunctionOid, + boolean triggerDeferrable, + boolean triggerInitiallyDeferred, + String triggerEnabled, + String triggerDefinition, + boolean publicExecuteGrant) {} + + private record TriggerMetadata( + long triggerOid, long functionOid, String enabled, String definition) {} +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceProviderTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceProviderTest.java new file mode 100644 index 0000000000..7b303283bf --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceProviderTest.java @@ -0,0 +1,1122 @@ +package net.firedevops.firemud.worldmanagement.data; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermission; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.Security; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.Base64; +import java.util.Date; +import java.util.HexFormat; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationClient; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; +import net.firedevops.firemud.worldmanagement.client.GameDesignClient; +import net.firedevops.firemud.worldmanagement.client.GameDesignClient.LaunchDescriptorReadback; +import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.ExtendedKeyUsage; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; + +@ExtendWith(OutputCaptureExtension.class) +class RunOwnedCanonicalWorldLaunchEvidenceProviderTest { + private static final String OPERATION_ID = + fixtureEvidence(false, "a".repeat(64), "b".repeat(64), "c".repeat(64)) + .capability() + .operationId(); + private static final String RELEASE_REF = "8ce42642-53ae-4d07-aab8-37c43ce66e0c"; + + @TempDir Path temporaryDirectory; + + @Test + void retainedCarrierRequiresOriginalFixedPeerAndLeafForEveryOwnerOperation() { + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + assertThatThrownBy(() -> withControlledPeer(null, null, evidence::requireFixedGameSessionPeer)) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withControlledPeer( + peer("dev", "game-session-service"), + null, + evidence::requireFixedGameSessionPeer)) + .isInstanceOf(SecurityException.class); + for (GrpcPeerIdentity wrongPeer : + new GrpcPeerIdentity[] { + peer("dev", "world-management-service"), peer("other", "game-session-service") + }) { + assertThatThrownBy( + () -> + withControlledPeer( + wrongPeer, "a".repeat(64), evidence::requireFixedGameSessionPeer)) + .isInstanceOf(SecurityException.class); + } + assertThatThrownBy( + () -> + withControlledPeer( + peer("dev", "game-session-service"), + "d".repeat(64), + evidence::requireFixedGameSessionPeer)) + .isInstanceOf(SecurityException.class); + withControlledPeer( + peer("dev", "game-session-service"), + "a".repeat(64), + () -> { + evidence.requireFixedGameSessionPeer(); + SessionContext.setContext( + UUID.randomUUID().toString(), java.util.List.of(), java.util.Map.of()); + try { + assertThatThrownBy(evidence::requireFixedGameSessionPeer) + .isInstanceOf(SecurityException.class); + } finally { + SessionContext.clear(); + } + }); + assertThat(evidence.fixtureProvenanceDigest()) + .isEqualTo(evidence.sourceReceipt().fixturePolicySeal().evidenceDigest()); + assertThatThrownBy(evidence::requireFixedGameSessionPeer).isInstanceOf(SecurityException.class); + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static void withControlledPeer(GrpcPeerIdentity peer, String leaf, Runnable action) { + // Context/certificate doubles exercise only local checks, never a real TLS handshake. + Context context = Context.ROOT.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + if (leaf != null) { + GrpcPeerCertificateEvidence certificate = mock(GrpcPeerCertificateEvidence.class); + when(certificate.leafSha256()).thenReturn(leaf); + context = context.withValue(GrpcPeerCertificateEvidence.CONTEXT_KEY, certificate); + } + Context previous = context.attach(); + try { + action.run(); + } finally { + context.detach(previous); + } + } + + static { + Security.addProvider(new BouncyCastleProvider()); + } + + @Test + void bindingDigestNormalizesAcceptedBlankOptionalOverridesToAbsent() { + RunOwnedCanonicalWorldLaunchEvidence evidence = fixtureEvidence(); + + String absent = evidence.bindingDigest(request(null, null), 1L); + assertThat(evidence.bindingDigest(request("", ""), 1L)).isEqualTo(absent); + assertThat(evidence.bindingDigest(request(" ", " "), 1L)).isEqualTo(absent); + } + + @Test + void launchEvidenceBindsStartingAllocationPrivateKeysFromOwnerProjection() { + RunOwnedCanonicalWorldLaunchEvidence evidence = fixtureEvidence(); + + evidence.requireMatches(request(null, null)); + assertThat(evidence.gameSessionAssociation().gameSessionTenantId()).isEqualTo(142L); + assertThat(evidence.gameSessionAssociation().gameInstanceId()).isEqualTo(1001L); + assertThat(evidence.gameSessionAssociation().currentGameInstanceStatus()) + .isEqualTo( + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus.STARTING); + assertThat(evidence.capability().tenantId()).isEqualTo(42L); + assertThat(evidence.gameSessionAssociation().gameSessionTenantId()) + .isNotEqualTo(evidence.capability().tenantId()); + assertThatThrownBy(() -> evidence.requireGameSessionAllocation(42L, 1001L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageStartingWith("RUN_OWNED_WORLD_GAME_SESSION_ALLOCATION_MISMATCH:"); + } + + @Test + void launchEvidenceConstructorRejectsMismatchedGameSessionFixtureAssociation() { + assertThatThrownBy(() -> fixtureEvidence(true)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageStartingWith("RUN_OWNED_WORLD_GAME_SESSION_FIXTURE_ASSOCIATION_MISMATCH:"); + } + + @Test + void fixtureOwnerWireResultRejectsNonStartingAllocationsBeforeWorldConsumption() { + var original = fixtureEvidence().gameSessionAssociation(); + var response = + net.firedevops.firemud.common.gamesession + .CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toFixtureResponse(original); + for (var status : java.util.List.of("RUNNING", "STOPPED")) { + var changed = response.toBuilder().setCurrentGameInstanceStatus(status).build(); + assertThatThrownBy( + () -> + net.firedevops.firemud.common.gamesession + .CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureResponse( + original.request(), changed)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Fixture launch association read requires the current STARTING snapshot"); + } + } + + @Test + void disabledFixtureFailsBeforeReadingFilesOrCallingGameDesign(CapturedOutput output) { + GameDesignClient gameDesignClient = mock(GameDesignClient.class); + RunOwnedCanonicalWorldLaunchEvidenceProvider provider = + provider( + false, + temporaryDirectory.resolve("missing-capability.json").toString(), + temporaryDirectory.resolve("missing-receipt.json").toString(), + "fixture-run", + "firemud-fixture-run", + new CommonGrpcClientProperties(), + gameDesignClient); + + assertThatThrownBy(provider::requireAuthenticatedEvidence) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Run-owned World launch evidence is invalid"); + verifyNoInteractions(gameDesignClient); + + assertThat(output) + .contains("Run-owned World launch evidence verification rejected; stage=ENABLED") + .doesNotContain("missing-capability.json", "missing-receipt.json", "fixture-run"); + } + + @Test + void malformedWireLogsOnlyTheFixedVerificationStageAndPreservesWireError(CapturedOutput output) + throws Exception { + GameDesignClient gameDesignClient = mock(GameDesignClient.class); + Path capability = temporaryDirectory.resolve("sensitive-capability-path.json"); + Path receipt = temporaryDirectory.resolve("sensitive-receipt-path.json"); + Files.writeString(capability, "capability-payload-secret-marker", StandardCharsets.UTF_8); + Files.writeString(receipt, "source-receipt-payload-secret-marker", StandardCharsets.UTF_8); + Files.setPosixFilePermissions( + capability, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); + Files.setPosixFilePermissions( + receipt, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); + RunOwnedCanonicalWorldLaunchEvidenceProvider provider = + provider( + true, + capability.toString(), + receipt.toString(), + "fixture-run", + "firemud-fixture-run", + new CommonGrpcClientProperties(), + gameDesignClient); + + assertThatThrownBy(provider::requireAuthenticatedEvidence) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Run-owned initial-admission fixture wire data is invalid"); + verifyNoInteractions(gameDesignClient); + + assertThat(output) + .contains("Run-owned World launch evidence verification rejected; stage=WIRE_PARSE") + .doesNotContain( + "sensitive-capability-path.json", + "sensitive-receipt-path.json", + "capability-payload-secret-marker", + "source-receipt-payload-secret-marker", + "fixture-run", + "firemud-fixture-run", + "InvalidWireDataException", + "Caused by:"); + } + + @Test + void enabledFixtureRejectsRelativeCapabilityPathAtFileReadStage(CapturedOutput output) + throws Exception { + GameDesignClient gameDesignClient = mock(GameDesignClient.class); + Path capability = temporaryDirectory.resolve("relative-capability.json"); + Path receipt = temporaryDirectory.resolve("relative-receipt.json"); + Files.writeString(capability, "{}", StandardCharsets.UTF_8); + Files.writeString(receipt, "{}", StandardCharsets.UTF_8); + Files.setPosixFilePermissions( + capability, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); + Files.setPosixFilePermissions( + receipt, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); + Path workingDirectory = Path.of("").toAbsolutePath().normalize(); + String relativeCapabilityPath = + workingDirectory.relativize(capability.toAbsolutePath().normalize()).toString(); + RunOwnedCanonicalWorldLaunchEvidenceProvider provider = + provider( + true, + relativeCapabilityPath, + receipt.toString(), + "fixture-run", + "firemud-fixture-run", + new CommonGrpcClientProperties(), + gameDesignClient); + + assertThatThrownBy(provider::requireAuthenticatedEvidence) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Run-owned World launch evidence is invalid"); + verifyNoInteractions(gameDesignClient); + assertFileRejectionStoppedBeforeWireParse(output); + } + + @Test + void enabledFixtureRejectsWritableCapabilityAtFileReadStage(CapturedOutput output) + throws Exception { + GameDesignClient gameDesignClient = mock(GameDesignClient.class); + Path capability = temporaryDirectory.resolve("writable-capability.json"); + Files.writeString(capability, "{}", StandardCharsets.UTF_8); + Path receipt = temporaryDirectory.resolve("receipt.json"); + Files.writeString(receipt, "{}", StandardCharsets.UTF_8); + Files.setPosixFilePermissions( + receipt, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); + RunOwnedCanonicalWorldLaunchEvidenceProvider provider = + provider( + true, + capability.toString(), + receipt.toString(), + "fixture-run", + "firemud-fixture-run", + new CommonGrpcClientProperties(), + gameDesignClient); + + assertThatThrownBy(provider::requireAuthenticatedEvidence) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Run-owned World launch evidence is invalid"); + verifyNoInteractions(gameDesignClient); + assertFileRejectionStoppedBeforeWireParse(output); + } + + @Test + void enabledFixtureRejectsCapabilitySymlinkAtFileReadStage(CapturedOutput output) + throws Exception { + GameDesignClient gameDesignClient = mock(GameDesignClient.class); + Path target = temporaryDirectory.resolve("target.json"); + Path capability = temporaryDirectory.resolve("capability.json"); + Path receipt = temporaryDirectory.resolve("receipt.json"); + Files.writeString(target, "{}", StandardCharsets.UTF_8); + Files.writeString(receipt, "{}", StandardCharsets.UTF_8); + Files.setPosixFilePermissions( + target, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); + Files.setPosixFilePermissions( + receipt, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); + Files.createSymbolicLink(capability, target.getFileName()); + RunOwnedCanonicalWorldLaunchEvidenceProvider provider = + provider( + true, + capability.toString(), + receipt.toString(), + "fixture-run", + "firemud-fixture-run", + new CommonGrpcClientProperties(), + gameDesignClient); + + assertThatThrownBy(provider::requireAuthenticatedEvidence) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Run-owned World launch evidence is invalid"); + verifyNoInteractions(gameDesignClient); + assertFileRejectionStoppedBeforeWireParse(output); + } + + @Test + void fixtureOwnerReadFailureIsContentFreeAndLogsTheReadStage(CapturedOutput output) + throws Exception { + ProviderFixture fixture = providerFixture(); + GameDesignClient gameDesignClient = mockDescriptorReader(fixture.evidence()); + CanonicalGameInstanceLaunchAssociationClient fixtureClient = mock(); + when(fixtureClient.readFixture(any(), anyString())) + .thenThrow(new IllegalStateException("secret-owner-response")); + RunOwnedCanonicalWorldLaunchEvidenceProvider provider = + provider( + fixture, gameDesignClient, fixtureClient, fixture.endpoints(), fixture.tlsProperties()); + + try (PeerContext ignored = fixture.attachGameSessionPeer()) { + assertThatThrownBy(provider::requireAuthenticatedEvidence) + .isInstanceOf( + RunOwnedCanonicalWorldLaunchEvidenceProvider + .InvalidRunOwnedCanonicalWorldLaunchEvidenceException.class) + .hasMessage("Run-owned World launch evidence is invalid"); + } finally { + provider.closeGameSessionFixtureClient(); + } + + verify(fixtureClient) + .readFixture(any(), org.mockito.ArgumentMatchers.eq(fixture.gameSessionLeafSha256())); + verify(fixtureClient).close(); + assertThat(output) + .contains( + "Run-owned World launch evidence verification rejected; stage=GAME_SESSION_FIXTURE_READ") + .doesNotContain("secret-owner-response", "IllegalStateException", "Caused by:"); + } + + @Test + void retryableGameDesignOwnerReadFailuresArePreservedAndStopBeforeGameSessionRead() + throws Exception { + for (Status.Code code : + new Status.Code[] {Status.Code.UNAVAILABLE, Status.Code.DEADLINE_EXCEEDED}) { + ProviderFixture fixture = providerFixture(); + GameDesignClient gameDesignClient = mock(GameDesignClient.class); + StatusRuntimeException failure = Status.fromCode(code).asRuntimeException(); + when(gameDesignClient.getLaunchDescriptor(any())).thenThrow(failure); + RunOwnedCanonicalWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory = mock(); + RunOwnedCanonicalWorldLaunchEvidenceProvider provider = + provider( + fixture, + gameDesignClient, + null, + fixture.endpoints(), + fixture.tlsProperties(), + factory); + + try (PeerContext ignored = fixture.attachGameSessionPeer()) { + assertThatThrownBy(provider::requireAuthenticatedEvidence).isSameAs(failure); + } + + verify(gameDesignClient).getLaunchDescriptor(any()); + verifyNoInteractions(factory); + } + } + + @Test + void retryableGameSessionOwnerReadFailuresArePreserved() throws Exception { + for (Status.Code code : + new Status.Code[] {Status.Code.UNAVAILABLE, Status.Code.DEADLINE_EXCEEDED}) { + ProviderFixture fixture = providerFixture(); + GameDesignClient gameDesignClient = mockDescriptorReader(fixture.evidence()); + CanonicalGameInstanceLaunchAssociationClient fixtureClient = mock(); + StatusRuntimeException failure = Status.fromCode(code).asRuntimeException(); + when(fixtureClient.readFixture(any(), anyString())).thenThrow(failure); + RunOwnedCanonicalWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory = mock(); + when(factory.create(any(), any(), any(), anyString())).thenReturn(fixtureClient); + RunOwnedCanonicalWorldLaunchEvidenceProvider provider = + provider( + fixture, + gameDesignClient, + null, + fixture.endpoints(), + fixture.tlsProperties(), + factory); + + try (PeerContext ignored = fixture.attachGameSessionPeer()) { + assertThatThrownBy(provider::requireAuthenticatedEvidence).isSameAs(failure); + } finally { + provider.closeGameSessionFixtureClient(); + } + + verify(gameDesignClient).getLaunchDescriptor(any()); + verify(factory).create(any(), any(), any(), eq("dev")); + verify(fixtureClient).readFixture(any(), eq(fixture.gameSessionLeafSha256())); + verify(fixtureClient).close(); + } + } + + @Test + void nonretryableGameDesignOwnerReadFailureRemainsInvalidEvidence() throws Exception { + ProviderFixture fixture = providerFixture(); + GameDesignClient gameDesignClient = mock(GameDesignClient.class); + when(gameDesignClient.getLaunchDescriptor(any())) + .thenThrow(Status.PERMISSION_DENIED.asRuntimeException()); + RunOwnedCanonicalWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory = mock(); + RunOwnedCanonicalWorldLaunchEvidenceProvider provider = + provider( + fixture, gameDesignClient, null, fixture.endpoints(), fixture.tlsProperties(), factory); + + try (PeerContext ignored = fixture.attachGameSessionPeer()) { + assertThatThrownBy(provider::requireAuthenticatedEvidence) + .isInstanceOf( + RunOwnedCanonicalWorldLaunchEvidenceProvider + .InvalidRunOwnedCanonicalWorldLaunchEvidenceException.class) + .hasMessage("Run-owned World launch evidence is invalid"); + } + + verifyNoInteractions(factory); + } + + @Test + void validFixtureOwnerReadReachesCompareAndReturnsStartingEvidence(CapturedOutput output) + throws Exception { + ProviderFixture fixture = providerFixture(); + GameDesignClient gameDesignClient = mockDescriptorReader(fixture.evidence()); + CanonicalGameInstanceLaunchAssociationClient fixtureClient = mock(); + when(fixtureClient.readFixture(any(), anyString())) + .thenAnswer(invocation -> fixture.association(invocation.getArgument(0))); + RunOwnedCanonicalWorldLaunchEvidenceProvider provider = + provider( + fixture, gameDesignClient, fixtureClient, fixture.endpoints(), fixture.tlsProperties()); + + RunOwnedCanonicalWorldLaunchEvidence result; + try (PeerContext ignored = fixture.attachGameSessionPeer()) { + result = provider.requireAuthenticatedEvidence(); + } finally { + provider.closeGameSessionFixtureClient(); + } + + assertThat(result.gameSessionAssociation().currentGameInstanceStatus()) + .isEqualTo( + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus.STARTING); + verify(fixtureClient) + .readFixture(any(), org.mockito.ArgumentMatchers.eq(fixture.gameSessionLeafSha256())); + verify(fixtureClient).close(); + assertThat(output) + .doesNotContain("Run-owned World launch evidence verification rejected", "Caused by:"); + } + + // The controlled owner-client return is valid for its alternate policy; the real common client + // rejects its different request digest before this provider comparison boundary. + @Test + void validAlternateFixtureAssociationIsRejectedAtCompareStage(CapturedOutput output) + throws Exception { + ProviderFixture fixture = providerFixture(); + GameDesignClient gameDesignClient = mockDescriptorReader(fixture.evidence()); + CanonicalGameInstanceLaunchAssociationClient fixtureClient = mock(); + RunOwnedCanonicalWorldLaunchEvidence alternateFixture = + fixtureEvidence( + false, + fixture.gameSessionLeafSha256(), + fingerprint(fixture.pki().worldManagementCertificate()), + fingerprint(fixture.pki().caCertificate()), + UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6e")); + when(fixtureClient.readFixture(any(), anyString())) + .thenReturn(alternateFixture.gameSessionAssociation()); + RunOwnedCanonicalWorldLaunchEvidenceProvider provider = + provider( + fixture, gameDesignClient, fixtureClient, fixture.endpoints(), fixture.tlsProperties()); + + try (PeerContext ignored = fixture.attachGameSessionPeer()) { + assertThatThrownBy(provider::requireAuthenticatedEvidence) + .isInstanceOf( + RunOwnedCanonicalWorldLaunchEvidenceProvider + .InvalidRunOwnedCanonicalWorldLaunchEvidenceException.class) + .hasMessage("Run-owned World launch evidence is invalid"); + } finally { + provider.closeGameSessionFixtureClient(); + } + + verify(fixtureClient) + .readFixture(any(), org.mockito.ArgumentMatchers.eq(fixture.gameSessionLeafSha256())); + verify(fixtureClient).close(); + assertThat(output) + .contains( + "Run-owned World launch evidence verification rejected; stage=GAME_SESSION_FIXTURE_COMPARE") + .doesNotContain( + "fixture-run", "firemud-fixture-run", "IllegalArgumentException", "Caused by:"); + } + + @Test + void fixtureClientInitializationFailureClosesPartialClient(CapturedOutput output) + throws Exception { + ProviderFixture fixture = providerFixture(); + GameDesignClient gameDesignClient = mockDescriptorReader(fixture.evidence()); + CanonicalGameInstanceLaunchAssociationClient fixtureClient = mock(); + doThrow(new IOException("private-init-detail")).when(fixtureClient).init(); + RunOwnedCanonicalWorldLaunchEvidenceProvider provider = + new RunOwnedCanonicalWorldLaunchEvidenceProvider( + true, + fixture.capabilityPath().toString(), + fixture.receiptPath().toString(), + "fixture-run", + "firemud-fixture-run", + fixture.tlsProperties(), + gameDesignClient, + fixture.endpoints(), + new GrpcChannelFactory(), + "dev", + (endpoints, tls, channelFactory, namespace) -> fixtureClient); + + try (PeerContext ignored = fixture.attachGameSessionPeer()) { + assertThatThrownBy(provider::requireAuthenticatedEvidence) + .isInstanceOf( + RunOwnedCanonicalWorldLaunchEvidenceProvider + .InvalidRunOwnedCanonicalWorldLaunchEvidenceException.class) + .hasMessage("Run-owned World launch evidence is invalid"); + } + + verify(fixtureClient).init(); + verify(fixtureClient).close(); + assertThat(output) + .contains( + "Run-owned World launch evidence verification rejected; stage=GAME_SESSION_FIXTURE_READ") + .doesNotContain("private-init-detail", "IOException", "Caused by:"); + } + + @Test + void fixtureClientMissingConfigurationFailsAtReadStageWithoutCreatingClient(CapturedOutput output) + throws Exception { + ProviderFixture fixture = providerFixture(); + GameDesignClient gameDesignClient = mockDescriptorReader(fixture.evidence()); + RunOwnedCanonicalWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory = mock(); + RunOwnedCanonicalWorldLaunchEvidenceProvider provider = + provider(fixture, gameDesignClient, null, null, fixture.tlsProperties(), factory); + + try (PeerContext ignored = fixture.attachGameSessionPeer()) { + assertThatThrownBy(provider::requireAuthenticatedEvidence) + .isInstanceOf( + RunOwnedCanonicalWorldLaunchEvidenceProvider + .InvalidRunOwnedCanonicalWorldLaunchEvidenceException.class) + .hasMessage("Run-owned World launch evidence is invalid"); + } + + verifyNoInteractions(factory); + assertThat(output) + .contains( + "Run-owned World launch evidence verification rejected; stage=GAME_SESSION_FIXTURE_READ") + .doesNotContain("fixture-run", "firemud-fixture-run"); + } + + @Test + void blankWorkloadNamespaceFailsBeforeCreatingFixtureClient() throws Exception { + ProviderFixture fixture = providerFixture(); + for (String namespace : new String[] {null, "", " "}) { + GameDesignClient gameDesignClient = mockDescriptorReader(fixture.evidence()); + RunOwnedCanonicalWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory = mock(); + RunOwnedCanonicalWorldLaunchEvidenceProvider provider = + provider( + fixture, + gameDesignClient, + null, + fixture.endpoints(), + fixture.tlsProperties(), + factory, + namespace); + + try (PeerContext ignored = fixture.attachGameSessionPeer()) { + assertThatThrownBy(provider::requireAuthenticatedEvidence) + .isInstanceOf( + RunOwnedCanonicalWorldLaunchEvidenceProvider + .InvalidRunOwnedCanonicalWorldLaunchEvidenceException.class) + .hasMessage("Run-owned World launch evidence is invalid"); + } + + verifyNoInteractions(factory); + } + } + + @Test + void configuredWorkloadNamespaceIsPassedToFixtureClientFactory() throws Exception { + ProviderFixture fixture = providerFixture(); + GameDesignClient gameDesignClient = mockDescriptorReader(fixture.evidence()); + CanonicalGameInstanceLaunchAssociationClient fixtureClient = mock(); + when(fixtureClient.readFixture(any(), anyString())) + .thenAnswer(invocation -> fixture.association(invocation.getArgument(0))); + RunOwnedCanonicalWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory = mock(); + when(factory.create(any(), any(), any(), anyString())).thenReturn(fixtureClient); + RunOwnedCanonicalWorldLaunchEvidenceProvider provider = + provider( + fixture, + gameDesignClient, + fixtureClient, + fixture.endpoints(), + fixture.tlsProperties(), + factory, + "dev"); + + try (PeerContext ignored = fixture.attachGameSessionPeer()) { + provider.requireAuthenticatedEvidence(); + } finally { + provider.closeGameSessionFixtureClient(); + } + + verify(factory).create(any(), any(), any(), eq("dev")); + } + + @Test + void closingBeforeFirstUsePreventsFixtureClientCreation() throws Exception { + ProviderFixture fixture = providerFixture(); + GameDesignClient gameDesignClient = mockDescriptorReader(fixture.evidence()); + RunOwnedCanonicalWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory = mock(); + RunOwnedCanonicalWorldLaunchEvidenceProvider provider = + provider( + fixture, gameDesignClient, null, fixture.endpoints(), fixture.tlsProperties(), factory); + + provider.closeGameSessionFixtureClient(); + + try (PeerContext ignored = fixture.attachGameSessionPeer()) { + assertThatThrownBy(provider::requireAuthenticatedEvidence) + .isInstanceOf( + RunOwnedCanonicalWorldLaunchEvidenceProvider + .InvalidRunOwnedCanonicalWorldLaunchEvidenceException.class) + .hasMessage("Run-owned World launch evidence is invalid"); + } + + verifyNoInteractions(factory); + } + + @Test + void repeatedCloseClosesInitializedClientOnceAndPreventsProviderReuse() throws Exception { + ProviderFixture fixture = providerFixture(); + GameDesignClient gameDesignClient = mockDescriptorReader(fixture.evidence()); + CanonicalGameInstanceLaunchAssociationClient fixtureClient = mock(); + when(fixtureClient.readFixture(any(), anyString())) + .thenAnswer(invocation -> fixture.association(invocation.getArgument(0))); + RunOwnedCanonicalWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory = mock(); + when(factory.create(any(), any(), any(), anyString())).thenReturn(fixtureClient); + RunOwnedCanonicalWorldLaunchEvidenceProvider provider = + provider( + fixture, + gameDesignClient, + fixtureClient, + fixture.endpoints(), + fixture.tlsProperties(), + factory); + + try (PeerContext ignored = fixture.attachGameSessionPeer()) { + provider.requireAuthenticatedEvidence(); + } + provider.closeGameSessionFixtureClient(); + provider.closeGameSessionFixtureClient(); + + try (PeerContext ignored = fixture.attachGameSessionPeer()) { + assertThatThrownBy(provider::requireAuthenticatedEvidence) + .isInstanceOf( + RunOwnedCanonicalWorldLaunchEvidenceProvider + .InvalidRunOwnedCanonicalWorldLaunchEvidenceException.class) + .hasMessage("Run-owned World launch evidence is invalid"); + } + + verify(factory, times(1)).create(any(), any(), any(), eq("dev")); + verify(fixtureClient, times(1)).close(); + } + + private static void assertFileRejectionStoppedBeforeWireParse(CapturedOutput output) { + assertThat(output) + .contains("Run-owned World launch evidence verification rejected; stage=CAPABILITY_FILE") + .doesNotContain("stage=WIRE_PARSE"); + } + + private RunOwnedCanonicalWorldLaunchEvidenceProvider provider( + ProviderFixture fixture, + GameDesignClient gameDesignClient, + CanonicalGameInstanceLaunchAssociationClient fixtureClient, + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties) { + return provider( + fixture, + gameDesignClient, + fixtureClient, + endpoints, + tlsProperties, + (ignoredEndpoints, ignoredTls, ignoredChannelFactory, ignoredNamespace) -> fixtureClient); + } + + private RunOwnedCanonicalWorldLaunchEvidenceProvider provider( + ProviderFixture fixture, + GameDesignClient gameDesignClient, + CanonicalGameInstanceLaunchAssociationClient fixtureClient, + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + RunOwnedCanonicalWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory) { + return provider( + fixture, gameDesignClient, fixtureClient, endpoints, tlsProperties, factory, "dev"); + } + + private RunOwnedCanonicalWorldLaunchEvidenceProvider provider( + ProviderFixture fixture, + GameDesignClient gameDesignClient, + CanonicalGameInstanceLaunchAssociationClient fixtureClient, + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + RunOwnedCanonicalWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory, + String namespace) { + return new RunOwnedCanonicalWorldLaunchEvidenceProvider( + true, + fixture.capabilityPath().toString(), + fixture.receiptPath().toString(), + "fixture-run", + "firemud-fixture-run", + tlsProperties, + gameDesignClient, + endpoints, + new GrpcChannelFactory(), + namespace, + factory); + } + + private ProviderFixture providerFixture() throws Exception { + Path directory = + Files.createDirectories(temporaryDirectory.resolve("provider-" + UUID.randomUUID())); + TestPki pki = TestPki.create(); + String gameSessionLeaf = fingerprint(pki.gameSessionCertificate()); + String worldManagementLeaf = fingerprint(pki.worldManagementCertificate()); + String caFingerprint = fingerprint(pki.caCertificate()); + RunOwnedCanonicalWorldLaunchEvidence evidence = + fixtureEvidence(false, gameSessionLeaf, worldManagementLeaf, caFingerprint); + Path capability = directory.resolve("capability.json"); + Path receipt = directory.resolve("receipt.json"); + Files.writeString(capability, capabilityJson(evidence.capability()), StandardCharsets.UTF_8); + Files.writeString(receipt, receiptJson(evidence.sourceReceipt()), StandardCharsets.UTF_8); + Set immutablePermissions = + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ); + Files.setPosixFilePermissions(capability, immutablePermissions); + Files.setPosixFilePermissions(receipt, immutablePermissions); + Path worldCertificate = directory.resolve("world-management.crt"); + Path caCertificate = directory.resolve("ca.crt"); + Files.writeString( + worldCertificate, pem(pki.worldManagementCertificate()), StandardCharsets.UTF_8); + Files.writeString(caCertificate, pem(pki.caCertificate()), StandardCharsets.UTF_8); + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(worldCertificate.toString()); + tls.setCaCert(caCertificate.toString()); + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameSessionService("localhost:6565"); + return new ProviderFixture(evidence, capability, receipt, pki, tls, endpoints, gameSessionLeaf); + } + + private static GameDesignClient mockDescriptorReader( + RunOwnedCanonicalWorldLaunchEvidence evidence) { + GameDesignClient client = mock(GameDesignClient.class); + var message = + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec + .toLaunchDescriptorMessage(evidence.launchDescriptor()); + when(client.getLaunchDescriptor(any())) + .thenReturn(new LaunchDescriptorReadback(message, evidence.launchDescriptor())); + return client; + } + + private static String capabilityJson( + RunOwnedInitialAdmissionFixtureWireCodec.Capability capability) { + return """ + {"schema":"%s","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":%d,"gameTemplateId":%d,"ownerAccountId":%d,"worldSlug":"%s","worldDisplayName":"%s","realmSlug":"%s","realmDisplayName":"%s","visible":%s,"publicProductionRealm":%s,"requiresCharacterSelection":%s,"stateScope":"%s","characterCreationPolicy":"%s","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","claimDigest":"%s"}%n\ + """ + .formatted( + capability.schema(), + capability.runId(), + capability.composeProjectName(), + capability.operationId(), + capability.tenantId(), + capability.gameTemplateId(), + capability.ownerAccountId(), + capability.worldSlug(), + capability.worldDisplayName(), + capability.realmSlug(), + capability.realmDisplayName(), + capability.visible(), + capability.publicProductionRealm(), + capability.requiresCharacterSelection(), + capability.stateScope(), + capability.characterCreationPolicy(), + capability.gameSessionLeafSha256(), + capability.gameSessionUriSan(), + capability.caCertificateSha256(), + capability.worldManagementUriSan(), + capability.worldManagementLeafSha256(), + capability.claimDigest()); + } + + private static String receiptJson( + RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt receipt) { + var source = receipt.sourceEvidence(); + var creation = receipt.creationEvidence(); + var launch = receipt.launchReadEvidence(); + var seal = receipt.fixturePolicySeal(); + return """ + {"schema":"%s","runId":"%s","composeProjectName":"%s","fixtureOperationId":"%s","ownerService":"%s","gameSessionUriSan":"%s","gameSessionLeafSha256":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","sourceEvidence":{"schemaVersion":%d,"targetNamespace":"%s","registrationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","tenantSlug":"%s","worldSlug":"%s","worldDisplayName":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"launchReadEvidence":{"schema":"%s","gameTemplateId":%d,"publishedReleaseBundleBase64":"%s","versionAssetArtifactStateBase64":"%s","versionStateBase64":"%s","launchDescriptorBase64":"%s"},"creationEvidence":{"schemaVersion":%d,"targetNamespace":"%s","creationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"fixturePolicySeal":{"schema":"%s","ownerService":"%s","operationId":"%s","requestDigest":"%s","evidenceDigest":"%s"}}%n\ + """ + .formatted( + receipt.schema(), + receipt.runId(), + receipt.composeProjectName(), + receipt.fixtureOperationId(), + receipt.ownerService(), + receipt.gameSessionUriSan(), + receipt.gameSessionLeafSha256(), + receipt.caCertificateSha256(), + receipt.worldManagementUriSan(), + receipt.worldManagementLeafSha256(), + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.operationId(), + source.requestDigest(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest(), + launch.schema(), + launch.gameTemplateId(), + base64(launch.publishedReleaseBundle().toByteArray()), + base64(launch.versionAssetArtifactState().toByteArray()), + base64(launch.versionState().toByteArray()), + base64(launch.launchDescriptor().toByteArray()), + creation.schemaVersion(), + creation.targetNamespace(), + creation.creationRequestId(), + creation.operationId(), + creation.requestDigest(), + creation.canonicalTenantId(), + creation.sourceGameRowId(), + creation.sourceGameTenantKey(), + creation.provenanceKind(), + creation.evidenceDigest(), + seal.schema(), + seal.ownerService(), + seal.operationId(), + seal.requestDigest(), + seal.evidenceDigest()); + } + + private static String base64(byte[] value) { + return Base64.getEncoder().encodeToString(value); + } + + private static String pem(X509Certificate certificate) throws Exception { + return "-----BEGIN CERTIFICATE-----\n" + + Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(certificate.getEncoded()) + + "\n-----END CERTIFICATE-----\n"; + } + + private static String fingerprint(X509Certificate certificate) throws Exception { + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded())); + } + + private static PreparedWorldInstanceRequest request(String patch, String remap) { + return new PreparedWorldInstanceRequest( + 142L, + 1001L, + 17L, + OPERATION_ID, + "launch-descriptor-fixture-11", + 11L, + patch, + "{}", + "genrev-11", + 77L, + RELEASE_REF, + 77L, + remap); + } + + private static RunOwnedCanonicalWorldLaunchEvidence fixtureEvidence() { + return fixtureEvidence(false); + } + + private static RunOwnedCanonicalWorldLaunchEvidence fixtureEvidence(boolean mismatchedSeal) { + return fixtureEvidence(mismatchedSeal, "a".repeat(64), "b".repeat(64), "c".repeat(64)); + } + + private static RunOwnedCanonicalWorldLaunchEvidence fixtureEvidence( + boolean mismatchedSeal, + String gameSessionLeafSha256, + String worldManagementLeafSha256, + String caCertificateSha256) { + return fixtureEvidence( + mismatchedSeal, + gameSessionLeafSha256, + worldManagementLeafSha256, + caCertificateSha256, + UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6d")); + } + + private static RunOwnedCanonicalWorldLaunchEvidence fixtureEvidence( + boolean mismatchedSeal, + String gameSessionLeafSha256, + String worldManagementLeafSha256, + String caCertificateSha256, + UUID canonicalTenantId) { + return RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create( + mismatchedSeal, + gameSessionLeafSha256, + worldManagementLeafSha256, + caCertificateSha256, + canonicalTenantId, + 1L, + false, + false); + } + + private static RunOwnedCanonicalWorldLaunchEvidenceProvider provider( + boolean enabled, + String capabilityPath, + String receiptPath, + String runId, + String composeProjectName, + CommonGrpcClientProperties grpcProperties, + GameDesignClient gameDesignClient) { + return new RunOwnedCanonicalWorldLaunchEvidenceProvider( + enabled, + capabilityPath, + receiptPath, + runId, + composeProjectName, + grpcProperties, + gameDesignClient, + null, + null, + "dev"); + } + + private record ProviderFixture( + RunOwnedCanonicalWorldLaunchEvidence evidence, + Path capabilityPath, + Path receiptPath, + TestPki pki, + CommonGrpcClientProperties tlsProperties, + ServiceEndpointsProperties endpoints, + String gameSessionLeafSha256) { + private CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult association( + CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest request) { + var original = evidence.gameSessionAssociation(); + return new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult( + request, + original.gameSessionTenantId(), + original.gameInstanceId(), + original.canonicalTenantId(), + original.gameInstanceUuid(), + original.canonicalVersionId(), + original.canonicalRealmId(), + original.playableStateNamespaceId(), + original.catalogRevision(), + original.currentGameInstanceStatus(), + original.currentRowVersion(), + original.fixturePolicyRequestBytes(), + original.fixturePolicySeal()); + } + + private PeerContext attachGameSessionPeer() throws Exception { + Context context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, + "dev", + "game-session-service")) + .withValue( + GrpcPeerCertificateEvidence.CONTEXT_KEY, + GrpcPeerCertificateEvidence.fromCertificate(pki.gameSessionCertificate()) + .orElseThrow()); + return new PeerContext(context.attach()); + } + } + + private record PeerContext(io.grpc.Context previous) implements AutoCloseable { + @Override + public void close() { + Context.current().detach(previous); + } + } + + private record TestPki( + X509Certificate caCertificate, + X509Certificate worldManagementCertificate, + X509Certificate gameSessionCertificate) { + private static TestPki create() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + KeyPair caKey = generator.generateKeyPair(); + X500Name caName = new X500Name("CN=World provider test CA"); + X509Certificate ca = issueCertificate(caName, caKey.getPublic(), caName, caKey, true, null); + X509Certificate world = + issueLeaf( + caName, + caKey, + generator, + "world-management-service", + RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN); + X509Certificate gameSession = + issueLeaf( + caName, + caKey, + generator, + "game-session-service", + RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN); + return new TestPki(ca, world, gameSession); + } + + private static X509Certificate issueLeaf( + X500Name caName, + KeyPair caKey, + KeyPairGenerator generator, + String service, + String workloadUri) + throws Exception { + KeyPair leafKey = generator.generateKeyPair(); + GeneralNames names = + new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, workloadUri)); + return issueCertificate( + new X500Name("CN=" + service), leafKey.getPublic(), caName, caKey, false, names); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + KeyPair issuerKey, + boolean ca, + GeneralNames subjectAltNames) + throws Exception { + Instant now = Instant.now().minusSeconds(60); + JcaX509v3CertificateBuilder builder = + new JcaX509v3CertificateBuilder( + issuer, + BigInteger.valueOf(Math.abs(UUID.randomUUID().getMostSignificantBits()) + 1L), + Date.from(now), + Date.from(now.plusSeconds(86400L)), + subject, + publicKey); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(ca)); + if (ca) { + builder.addExtension( + Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign)); + } else { + builder.addExtension( + Extension.keyUsage, + true, + new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage( + new KeyPurposeId[] {KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth})); + builder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); + } + return new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .build(issuerKey.getPrivate()))); + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.java new file mode 100644 index 0000000000..30fa5e7de3 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.java @@ -0,0 +1,301 @@ +package net.firedevops.firemud.worldmanagement.data; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamedesign.v1.ArtifactState; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; + +/** + * Complete controlled upstream test values; this factory proves no owner writes or TLS authority. + */ +public final class RunOwnedCanonicalWorldLaunchEvidenceTestFixtures { + private static final String CLAIM_DIGEST = controlledClaimDigest(); + private static final String RELEASE_REF = "8ce42642-53ae-4d07-aab8-37c43ce66e0c"; + + private RunOwnedCanonicalWorldLaunchEvidenceTestFixtures() {} + + private static String controlledClaimDigest() { + try { + // Exact controlled fixture bytes; this is not a physical run claim. + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest("fixture-run\nfiremud-fixture-run\n".getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException(exception); + } + } + + public static RunOwnedCanonicalWorldLaunchEvidence create() { + return createWithDescriptorOverrides(false, false); + } + + public static RunOwnedCanonicalWorldLaunchEvidence createWithDescriptorOverrides( + boolean scriptPatchVersionPresent, boolean remapSetIdPresent) { + return create( + false, + "a".repeat(64), + "c".repeat(64), + "b".repeat(64), + UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6d"), + 9L, + scriptPatchVersionPresent, + remapSetIdPresent); + } + + static RunOwnedCanonicalWorldLaunchEvidence create( + boolean mismatchedSeal, + String gameSessionLeafSha256, + String worldManagementLeafSha256, + String caCertificateSha256, + UUID canonicalTenantId, + long ownerAccountId, + boolean scriptPatchVersionPresent, + boolean remapSetIdPresent) { + String operationId = + RunOwnedInitialAdmissionFixtureWireCodec.fixtureOperationId( + CLAIM_DIGEST, + "fixture-run", + "firemud-fixture-run", + gameSessionLeafSha256, + caCertificateSha256) + .toString(); + UUID registrationId = UUID.fromString(operationId); + UUID sourceOperationId = UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + "dev", registrationId, canonicalTenantId, "fixture-tenant", "demo", "Demo World"); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + "dev", + registrationId, + sourceOperationId, + requestDigest, + canonicalTenantId, + "fixture-tenant", + "demo", + "Demo World", + 29L, + "42", + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + "dev", + registrationId, + sourceOperationId, + requestDigest, + canonicalTenantId, + "fixture-tenant", + "demo", + "Demo World", + 29L, + "42", + "NEW_GAME_ROW", + sourceEvidenceDigest); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + "dev", + operationId, + canonicalTenantId, + "demo", + sourceOperationId, + sourceEvidenceDigest, + 17L, + false, + null, + false, + null, + false, + null, + false, + null); + var descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "launch-descriptor-fixture-11", + 11L, + scriptPatchVersionPresent, + scriptPatchVersionPresent ? "script-patch-fixture-11" : null, + "{}", + "genrev-11", + 77L, + 77L, + RELEASE_REF, + remapSetIdPresent, + remapSetIdPresent ? "remap-set-fixture-11" : null); + String manifestHash = "sha256:" + "c".repeat(64); + var bundle = + PublishedReleaseBundle.newBuilder() + .setId(77L) + .setVersionId(11L) + .setVersionNumber(1) + .setAttestationSchemaVersion("v1") + .setCanonicalTenantId(canonicalTenantId.toString()) + .setCanonicalVersionId("10000000-0000-4000-8000-000000000011") + .setPublishedReleaseBundleRef(RELEASE_REF) + .setGenerationConfigRevision("genrev-11") + .setManifestHash(manifestHash) + .build(); + var artifact = + VersionAssetArtifactState.newBuilder() + .setTenantId("42") + .setVersionId(11L) + .setStateEpoch(2L) + .setExportedVersionNumber(1) + .setArtifactState(ArtifactState.ARTIFACT_STATE_PUBLISHED) + .setManifestHash(manifestHash) + .build(); + var version = + VersionStateSnapshot.newBuilder() + .setTenantId("42") + .setVersionId(11L) + .setVersionState(VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED) + .setVersionStateEpoch(77L) + .setUpdatedAt("2026-10-11T10:00:00Z") + .build(); + RunOwnedInitialAdmissionFixtureWireCodec.Capability capability = + new RunOwnedInitialAdmissionFixtureWireCodec.Capability( + RunOwnedInitialAdmissionFixtureWireCodec.CAPABILITY_SCHEMA, + "fixture-run", + "firemud-fixture-run", + operationId, + 42L, + 17L, + ownerAccountId, + "demo", + "Demo World", + "production", + "Live Realm", + true, + true, + false, + "SHARED", + "ALLOW_NEW", + gameSessionLeafSha256, + RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, + caCertificateSha256, + RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, + worldManagementLeafSha256, + CLAIM_DIGEST); + // Controlled constructor data remains untrusted; these commitments do not prove owner writes. + UUID creationRequestId = UUID.fromString("1b3fdbda-a9f6-4cf5-b21e-b43f0e855f65"); + UUID creationOperationId = UUID.fromString("31e36104-3336-4cf5-899a-cb419f2f361e"); + String creationRequestDigest = + GameTenantCreationDigest.requestDigest( + "dev", creationRequestId, "42", "Fixture Game", null); + var creation = + new FreshTenantCreationEvidence( + 1, + "dev", + creationRequestId, + creationOperationId, + creationRequestDigest, + canonicalTenantId, + 29L, + "42", + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "dev", + creationRequestId, + creationOperationId, + creationRequestDigest, + canonicalTenantId, + 29L, + "42", + "NEW_GAME_ROW")); + var launchRead = + new RunOwnedInitialAdmissionFixtureWireCodec.LaunchReadEvidence( + RunOwnedInitialAdmissionFixtureWireCodec.LAUNCH_READ_EVIDENCE_SCHEMA, + 17L, + bundle, + artifact, + version, + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec + .toLaunchDescriptorMessage(descriptor)); + String policyRequestDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( + capability, creation, source, launchRead); + var policySeal = + new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal( + RunOwnedInitialAdmissionFixtureWireCodec.FIXTURE_POLICY_SEAL_SCHEMA, + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE, + UUID.fromString(operationId), + policyRequestDigest, + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + UUID.fromString(operationId), policyRequestDigest)); + UUID otherSealOperation = UUID.fromString("20000000-0000-4000-8000-000000000012"); + var receiptSeal = + mismatchedSeal + ? new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal( + policySeal.schema(), + policySeal.ownerService(), + otherSealOperation, + policySeal.requestDigest(), + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + otherSealOperation, policySeal.requestDigest())) + : policySeal; + var receipt = + new RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt( + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_SCHEMA, + "fixture-run", + "firemud-fixture-run", + operationId, + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE, + RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, + gameSessionLeafSha256, + caCertificateSha256, + RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, + worldManagementLeafSha256, + source, + launchRead, + creation, + receiptSeal); + var policyRequestBytes = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestBytes( + capability, creation, source, launchRead); + UUID readRequestId = UUID.fromString("5d85bfbe-ae28-4a86-a72a-57471a5761bf"); + var associationRequest = + new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest( + readRequestId, "dev", UUID.fromString(operationId), policySeal.evidenceDigest()); + var association = + new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult( + associationRequest, + 142L, + 1001L, + canonicalTenantId, + UUID.fromString("20000000-0000-4000-8000-000000000011"), + UUID.fromString(bundle.getCanonicalVersionId()), + UUID.fromString("30000000-0000-4000-8000-000000000011"), + UUID.fromString("40000000-0000-4000-8000-000000000011"), + 1L, + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus.STARTING, + 0L, + policyRequestBytes, + policySeal); + return new RunOwnedCanonicalWorldLaunchEvidence( + capability, + receipt, + descriptor, + new byte[] {1}, + new byte[] {2}, + gameSessionLeafSha256, + RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, + worldManagementLeafSha256, + caCertificateSha256, + association); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesTest.java new file mode 100644 index 0000000000..36d6780a62 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesTest.java @@ -0,0 +1,166 @@ +package net.firedevops.firemud.worldmanagement.data; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.nio.charset.StandardCharsets; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeDigest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityReceipt; +import org.junit.jupiter.api.Test; + +class RunOwnedWorldFixedPresetResourcesTest { + @Test + void runtimePresetMatchesTheOriginalMigrationLiterals() throws Exception { + String digest = "sha256:f817af2770072bab0384c30c19b8cd30fce7a5a33f7587faed0024aa7c0909bc"; + String[] templates = { + "9affa11b-02f5-3cc9-a50e-6760083c71e9", + "936c4d65-c460-3b73-9f4e-6ee6295bca24", + "c6058518-f9e0-3f26-9b05-2bc786095089", + "e74cca03-3b53-3edc-84f5-890651f5fea8", + "18c4b7a2-6498-3865-a464-814b56e4d4c2", + "ab46ef8f-e74f-3197-be62-9785ef63242e" + }; + var definition = RunOwnedWorldFixedPresetResources.definition(); + assertThat(definition.expectedContentDigest()).isEqualTo(digest); + assertThat( + java.util.stream.Stream.concat( + java.util.stream.Stream.of( + definition.region().templateId(), definition.zone().templateId()), + java.util.stream.Stream.concat( + definition.rooms().stream().map(room -> room.templateId()), + definition.exits().stream().map(exit -> exit.templateId()))) + .map(UUID::toString) + .toList()) + .containsExactly(templates); + try (var migration = + RunOwnedWorldFixedPresetResourcesTest.class.getResourceAsStream( + "/db/migration/V1041__world_run_owned_fixed_preset_preparation.sql")) { + assertThat(migration).isNotNull(); + String sql = new String(migration.readAllBytes(), StandardCharsets.UTF_8); + assertThat(sql).contains("'" + digest + "'"); + for (String template : templates) assertThat(sql).contains("'" + template + "'"); + } + } + + @Test + void rejectsResolvedScriptPatchOverrideAtInitialPlanBeforeMaterialization() { + assertOverrideRejected(true, false); + } + + @Test + void rejectsRemapSetOverrideAtInitialPlanBeforeMaterialization() { + assertOverrideRejected(false, true); + } + + private static void assertOverrideRejected( + boolean scriptPatchVersionPresent, boolean remapSetIdPresent) { + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.createWithDescriptorOverrides( + scriptPatchVersionPresent, remapSetIdPresent); + evidence.launchDescriptor().requireValid(); + assertThat(evidence.launchDescriptor().scriptPatchVersionPresent()) + .isEqualTo(scriptPatchVersionPresent); + assertThat(evidence.launchDescriptor().remapSetIdPresent()).isEqualTo(remapSetIdPresent); + assertThat(evidence.sourceReceipt().launchReadEvidence().launchDescriptor()) + .isEqualTo( + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage( + evidence.launchDescriptor())); + WorldAuthoredSourceIntakeReceipt sourceReceipt = sourceReceipt(evidence); + WorldAuthoredVersionIdentityReceipt versionReceipt = versionReceipt(evidence, sourceReceipt); + + assertThatThrownBy( + () -> + withFixturePeer( + evidence, + () -> + RunOwnedWorldFixedPresetResources.plan( + evidence, sourceReceipt, versionReceipt))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageStartingWith("RUN_OWNED_WORLD_FIXED_PRESET_OVERRIDES_UNSUPPORTED:"); + } + + private static WorldAuthoredSourceIntakeReceipt sourceReceipt( + RunOwnedCanonicalWorldLaunchEvidence evidence) { + var source = evidence.sourceReceipt().sourceEvidence(); + UUID intakeRequestId = UUID.fromString("11111111-1111-4111-8111-111111111111"); + UUID operationId = UUID.fromString("22222222-2222-4222-8222-222222222222"); + long localTenantKey = 9001L; + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest( + source.targetNamespace(), intakeRequestId, source); + return new WorldAuthoredSourceIntakeReceipt( + 1, + source.targetNamespace(), + intakeRequestId, + operationId, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + requestDigest, + WorldAuthoredSourceIntakeDigest.receiptDigest( + source.targetNamespace(), operationId, requestDigest, source, localTenantKey), + localTenantKey, + source); + } + + private static WorldAuthoredVersionIdentityReceipt versionReceipt( + RunOwnedCanonicalWorldLaunchEvidence evidence, + WorldAuthoredSourceIntakeReceipt sourceReceipt) { + var source = sourceReceipt.source(); + var snapshot = evidence.sourceReceipt().launchReadEvidence().versionState(); + var request = + new AuthoredWorldVersionStateEvidence.Request( + 1, + source.targetNamespace(), + UUID.fromString("33333333-3333-4333-8333-333333333333"), + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + snapshot.getVersionId()); + var stateEvidence = + AuthoredWorldVersionStateEvidence.create( + request, + source, + evidence.gameSessionAssociation().canonicalVersionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + snapshot.getVersionStateEpoch()); + return new WorldAuthoredVersionIdentityReceipt( + 1, + UUID.fromString("44444444-4444-4444-8444-444444444444"), + 9003L, + sourceReceipt, + stateEvidence); + } + + private static T withFixturePeer( + RunOwnedCanonicalWorldLaunchEvidence evidence, Supplier action) { + GrpcPeerIdentity peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/dev/sa/game-session-service", "dev", "game-session-service"); + GrpcPeerCertificateEvidence certificate = mock(GrpcPeerCertificateEvidence.class); + when(certificate.leafSha256()).thenReturn(evidence.capability().gameSessionLeafSha256()); + Context context = + Context.ROOT + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .withValue(GrpcPeerCertificateEvidence.CONTEXT_KEY, certificate); + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java index 9f66c370a0..33a3516917 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java @@ -56,6 +56,7 @@ import org.mockito.ArgumentCaptor; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionOperations; +import org.springframework.transaction.support.TransactionSynchronizationManager; class WorldLifecycleCommandServiceImplTest { private static final String PUBLISHED_RELEASE_BUNDLE_REF = "8ce42642-53ae-4d07-aab8-37c43ce66e0c"; @@ -73,6 +74,7 @@ class WorldLifecycleCommandServiceImplTest { private GameDesignClient gameDesignClient; private AtomicBoolean localTransactionActive; private AtomicBoolean worldInstanceReadInLocalTransaction; + private TransactionOperations lifecycleTransactionOperations; private WorldLifecycleCommandServiceImpl service; @BeforeEach @@ -90,7 +92,7 @@ void setUp() { gameDesignClient = mock(GameDesignClient.class); localTransactionActive = new AtomicBoolean(); worldInstanceReadInLocalTransaction = new AtomicBoolean(); - TransactionOperations transactionOperations = + lifecycleTransactionOperations = new TransactionOperations() { @Override public T execute(TransactionCallback action) { @@ -120,7 +122,7 @@ public T execute(TransactionCallback action) { gameDesignClient, entityManagementClient, new SimpleMeterRegistry(), - transactionOperations); + lifecycleTransactionOperations); service.initMetrics(); when(gameDesignClient.getPublishedReleaseBundle(42L, 11L)) .thenReturn( @@ -270,6 +272,8 @@ void activatePreparedWorldInstancePromotesPreparingRow() { instance.setStatus("PREPARING"); when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) .thenReturn(Optional.of(instance)); + when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) + .thenReturn(Optional.of(instance)); when(worldInstanceRepository.save(any(WorldInstance.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -279,6 +283,69 @@ void activatePreparedWorldInstancePromotesPreparingRow() { assertEquals(2L, snapshot.lifecycleEpoch()); } + @Test + void ordinaryActivationReplaysOriginalPreparingEpochAndCurrentActiveEpochWithoutEffects() { + WorldInstance instance = new WorldInstance(); + instance.setTenantId(42L); + instance.setGameInstanceId(101L); + instance.setGameTemplateId(7L); + instance.setControlPlaneRequestId("cp-1"); + instance.setLaunchDescriptorId("ld-1"); + instance.setVersionId(11L); + instance.setRuntimeFlagsJson("{}"); + instance.setGenerationConfigRevision("genrev-11"); + instance.setReleaseBundleId(77L); + instance.setPublishedReleaseBundleRef(PUBLISHED_RELEASE_BUNDLE_REF); + instance.setVersionStateEpoch(77L); + instance.setLifecycleEpoch(1L); + instance.setStatus("PREPARING"); + when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) + .thenReturn(Optional.of(instance)); + when(worldInstanceRepository.save(any(WorldInstance.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + + var activated = service.activatePreparedWorldInstance(42L, 101L, 1L); + var originalEpochReplay = service.activatePreparedWorldInstance(42L, 101L, 1L); + var currentEpochReplay = service.activatePreparedWorldInstance(42L, 101L, 2L); + + assertEquals("ACTIVE", activated.status()); + assertEquals(2L, activated.lifecycleEpoch()); + assertEquals(activated, originalEpochReplay); + assertEquals(activated, currentEpochReplay); + verify(worldInstanceRepository, times(1)).save(any(WorldInstance.class)); + verify(gameDesignClient, times(1)).getPublishedReleaseBundle(42L, 11L); + verify(gameDesignClient, times(1)).getVersionAssetArtifactState(42L, 11L); + verify(gameDesignClient, times(1)).getVersionState(42L, 11L); + } + + @Test + void ordinaryActiveReplayRejectsStaleUnrelatedInvalidAndOverflowEpochsWithoutEffects() { + WorldInstance instance = activeWorldInstance(); + instance.setLifecycleEpoch(3L); + when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) + .thenReturn(Optional.of(instance)); + + for (long expectedEpoch : new long[] {1L, 4L, 0L, -1L, Long.MAX_VALUE}) { + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> service.activatePreparedWorldInstance(42L, 101L, expectedEpoch)); + assertTrue(exception.getMessage().startsWith("WORLD_INSTANCE_LIFECYCLE_STALE:")); + } + + instance.setLifecycleEpoch(Long.MIN_VALUE); + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> service.activatePreparedWorldInstance(42L, 101L, Long.MAX_VALUE)); + assertTrue(exception.getMessage().startsWith("WORLD_INSTANCE_LIFECYCLE_STALE:")); + + verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); + verify(gameDesignClient, never()).getPublishedReleaseBundle(anyLong(), anyLong()); + verify(gameDesignClient, never()).getVersionAssetArtifactState(anyLong(), anyLong()); + verify(gameDesignClient, never()).getVersionState(anyLong(), anyLong()); + } + @Test void failPreparedWorldInstanceMarksPreparingRowFailed() { WorldInstance instance = new WorldInstance(); @@ -296,6 +363,8 @@ void failPreparedWorldInstanceMarksPreparingRowFailed() { instance.setStatus("PREPARING"); when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) .thenReturn(Optional.of(instance)); + when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) + .thenReturn(Optional.of(instance)); when(worldInstanceRepository.save(any(WorldInstance.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -305,6 +374,83 @@ void failPreparedWorldInstanceMarksPreparingRowFailed() { assertEquals(2L, snapshot.lifecycleEpoch()); } + @Test + void fixtureFailureRequiresExactOwnerAndUsesLockedLegacyRow() { + RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); + RunOwnedWorldLaunchEvidence evidence = mock(RunOwnedWorldLaunchEvidence.class); + when(provider.isEnabled()).thenReturn(true); + when(provider.requireAuthenticatedEvidence()) + .thenAnswer( + invocation -> { + assertFalse(localTransactionActive.get()); + return evidence; + }); + when(evidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn("c".repeat(64)); + WorldInstance instance = boundFixtureInstance("PREPARING", 1L); + AtomicReference persisted = stubPersistedWorldInstance(instance); + + var snapshot = + fixtureService(provider, lifecycleTransactionOperations) + .failPreparedWorldInstance(42L, 101L, 1L, "source failed"); + + assertEquals("FAILED_PRE_ACTIVATION", snapshot.status()); + assertEquals(2L, snapshot.lifecycleEpoch()); + assertEquals("c".repeat(64), persisted.get().getRunOwnedFixtureBindingSha256()); + assertEquals(1L, persisted.get().getRunOwnedFixturePreparingLifecycleEpoch()); + assertEquals(1L, persisted.get().getRowVersion()); + verify(provider).requireAuthenticatedEvidence(); + verify(worldInstanceRepository).findByTenantIdAndGameInstanceIdForUpdate(42L, 101L); + } + + @Test + void fixtureFailureRejectsChangedBindingBeforeSaving() { + RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); + RunOwnedWorldLaunchEvidence evidence = mock(RunOwnedWorldLaunchEvidence.class); + when(provider.isEnabled()).thenReturn(true); + when(provider.requireAuthenticatedEvidence()).thenReturn(evidence); + when(evidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn("d".repeat(64)); + WorldInstance instance = boundFixtureInstance("PREPARING", 1L); + stubPersistedWorldInstance(instance); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> + fixtureService(provider, lifecycleTransactionOperations) + .failPreparedWorldInstance(42L, 101L, 1L, "source failed")); + + assertTrue(error.getMessage().startsWith("RUN_OWNED_WORLD_LAUNCH_EVIDENCE_MISMATCH:")); + assertEquals("PREPARING", instance.getStatus()); + verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); + } + + @Test + void fixtureFailureRejectsAmbientTransactionBeforeLoadingOwnerEvidence() { + RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); + when(provider.isEnabled()).thenReturn(true); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + IllegalStateException error = + assertThrows( + IllegalStateException.class, + () -> + fixtureService(provider, lifecycleTransactionOperations) + .failPreparedWorldInstance(42L, 101L, 1L, "source failed")); + + assertTrue(error.getMessage().contains("no ambient transaction")); + verify(provider, never()).requireAuthenticatedEvidence(); + verify(worldInstanceRepository, never()).findByTenantIdAndGameInstanceIdForUpdate(42L, 101L); + verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); + verify(gameDesignClient, never()).getPublishedReleaseBundle(42L, 11L); + verify(entityManagementClient, never()) + .cleanupRuntimeInstance(anyLong(), anyLong(), anyString()); + } finally { + TransactionSynchronizationManager.clear(); + } + } + @Test void terminateWorldInstanceDeletesRuntimeWorldStateBeforeFinalizing() { WorldInstance instance = new WorldInstance(); @@ -374,6 +520,109 @@ void terminationDoesNotCrossAnUnresolvedInitialAdmissionBindHold() { verify(worldInstanceRepository, org.mockito.Mockito.never()).save(any(WorldInstance.class)); } + @Test + void fixtureTerminationKeepsActiveRowAndSkipsEntityWhenOwnerHoldIsUnresolved() { + RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); + RunOwnedWorldLaunchEvidence evidence = mock(RunOwnedWorldLaunchEvidence.class); + when(provider.isEnabled()).thenReturn(true); + when(provider.requireAuthenticatedEvidence()).thenReturn(evidence); + when(evidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn("c".repeat(64)); + WorldInstance instance = boundFixtureInstance("ACTIVE", 2L); + stubPersistedWorldInstance(instance); + when(worldInstanceRepository.hasNonterminalInitialAdmissionBindHold(42L, 101L)) + .thenAnswer( + invocation -> { + assertTrue(localTransactionActive.get()); + return true; + }); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> + fixtureService(provider, lifecycleTransactionOperations) + .terminateWorldInstance(42L, 101L, 2L, "term-fixture", "stop")); + + assertTrue(error.getMessage().startsWith("INITIAL_ADMISSION_BIND_HOLD_ACTIVE:")); + assertEquals("ACTIVE", instance.getStatus()); + verify(provider).requireAuthenticatedEvidence(); + verify(entityManagementClient, never()) + .cleanupRuntimeInstance(anyLong(), anyLong(), anyString()); + verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); + verify(worldEventRepository, never()).deleteByTenantIdAndGameInstanceId(42L, 101L); + } + + @Test + void fixtureEntityCleanupFailureRetainsTerminatingOwnerRowForSameRequestRetry() { + RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); + RunOwnedWorldLaunchEvidence evidence = mock(RunOwnedWorldLaunchEvidence.class); + when(provider.isEnabled()).thenReturn(true); + when(provider.requireAuthenticatedEvidence()).thenReturn(evidence); + when(evidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn("c".repeat(64)); + WorldInstance instance = boundFixtureInstance("ACTIVE", 2L); + AtomicReference persisted = stubPersistedWorldInstance(instance); + doThrow(new IllegalStateException("Entity cleanup unavailable")) + .when(entityManagementClient) + .cleanupRuntimeInstance(42L, 101L, "term-fixture"); + + assertThrows( + IllegalStateException.class, + () -> + fixtureService(provider, lifecycleTransactionOperations) + .terminateWorldInstance(42L, 101L, 2L, "term-fixture", "stop")); + + assertEquals("TERMINATING", persisted.get().getStatus()); + assertEquals(3L, persisted.get().getLifecycleEpoch()); + assertEquals("term-fixture", persisted.get().getTerminationRequestId()); + assertEquals("c".repeat(64), persisted.get().getRunOwnedFixtureBindingSha256()); + verify(worldInstanceRepository, times(1)).save(any(WorldInstance.class)); + verify(worldEventRepository, never()).deleteByTenantIdAndGameInstanceId(42L, 101L); + } + + @Test + void fixtureTerminatedReplayRequiresTheOriginalRequestIdAndDoesNotRepeatEffects() { + RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); + RunOwnedWorldLaunchEvidence evidence = mock(RunOwnedWorldLaunchEvidence.class); + when(provider.isEnabled()).thenReturn(true); + when(provider.requireAuthenticatedEvidence()).thenReturn(evidence); + when(evidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn("c".repeat(64)); + WorldInstance instance = boundFixtureInstance("ACTIVE", 2L); + AtomicReference persisted = stubPersistedWorldInstance(instance); + when(entityManagementClient.cleanupRuntimeInstance(42L, 101L, "term-fixture")) + .thenReturn(CleanupRuntimeInstanceResponse.newBuilder().build()); + WorldLifecycleCommandServiceImpl fixtureService = + fixtureService(provider, lifecycleTransactionOperations); + + var terminated = fixtureService.terminateWorldInstance(42L, 101L, 2L, "term-fixture", "stop"); + long terminalRowVersion = persisted.get().getRowVersion(); + var replay = fixtureService.terminateWorldInstance(42L, 101L, 2L, "term-fixture", "stop"); + + assertEquals("TERMINATED", terminated.status()); + assertEquals(4L, terminated.lifecycleEpoch()); + assertEquals(terminated, replay); + assertEquals(terminalRowVersion, persisted.get().getRowVersion()); + verify(entityManagementClient, times(1)).cleanupRuntimeInstance(42L, 101L, "term-fixture"); + verify(worldInstanceRepository, times(2)).save(any(WorldInstance.class)); + + WorldInstance retainedTerminal = copyWorldInstance(persisted.get()); + IllegalArgumentException conflict = + assertThrows( + IllegalArgumentException.class, + () -> fixtureService.terminateWorldInstance(42L, 101L, 2L, "term-other", "stop")); + + assertTrue(conflict.getMessage().startsWith("IDEMPOTENCY_CONFLICT:")); + assertEquals("TERMINATED", persisted.get().getStatus()); + assertEquals(retainedTerminal.getLifecycleEpoch(), persisted.get().getLifecycleEpoch()); + assertEquals( + retainedTerminal.getTerminationRequestId(), persisted.get().getTerminationRequestId()); + assertEquals(terminalRowVersion, persisted.get().getRowVersion()); + verify(entityManagementClient, times(1)).cleanupRuntimeInstance(42L, 101L, "term-fixture"); + verify(worldInstanceRepository, times(2)).save(any(WorldInstance.class)); + } + @Test void terminateWorldInstanceRetriesSameRequestAfterLocalCleanupFailure() { WorldInstance instance = activeWorldInstance(); @@ -991,6 +1240,11 @@ void fixtureActivationRejectsOriginalEpochForNonActiveRowsWithoutWrites() { private WorldLifecycleCommandServiceImpl fixtureService( RunOwnedWorldLaunchEvidenceProvider provider) { + return fixtureService(provider, null); + } + + private WorldLifecycleCommandServiceImpl fixtureService( + RunOwnedWorldLaunchEvidenceProvider provider, TransactionOperations transactionOperations) { WorldProperties worldProperties = new WorldProperties(); worldProperties.setLocalShardId(7); WorldLifecycleCommandServiceImpl fixtureService = @@ -1008,7 +1262,7 @@ private WorldLifecycleCommandServiceImpl fixtureService( gameDesignClient, entityManagementClient, new SimpleMeterRegistry(), - (TransactionOperations) null, + transactionOperations, provider); fixtureService.initMetrics(); return fixtureService; diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java index b2196d41da..5fb37a3bb6 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java @@ -3,8 +3,11 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -13,13 +16,17 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; +import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec.ReadRequest; +import net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidence; +import net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidenceTestFixtures; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -50,6 +57,242 @@ void clearTransactionState() { TransactionSynchronizationManager.clear(); } + @Test + void fixtureIntakeRevalidatesPeerAndCallerBeforeAnyOwnerReadOrTransaction() { + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + WorldAuthoredSourceIntakeService fixtureService = fixtureService(); + assertThatThrownBy(() -> withoutPeer(() -> fixtureService.intakeRunOwnedFixture(evidence))) + .isInstanceOf(SecurityException.class); + for (String[] candidate : + new String[][] { + {"dev", "world-management-service", "a".repeat(64)}, + {"other", "game-session-service", "a".repeat(64)}, + {"dev", "game-session-service", "d".repeat(64)}, + {"dev", "game-session-service", null} + }) { + assertThatThrownBy( + () -> + withFixturePeer( + candidate[0], + candidate[1], + candidate[2], + () -> fixtureService.intakeRunOwnedFixture(evidence))) + .isInstanceOf(SecurityException.class); + } + assertThatThrownBy( + () -> + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> withCallerContext(() -> fixtureService.intakeRunOwnedFixture(evidence)))) + .isInstanceOf(SecurityException.class); + verifyNoInteractions(client, repository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void fixtureIntakeReadsControlledSourceBeforeSqlAndIndependentlyReadsExactReceiptAndRetry() { + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + AuthoredWorldSourceEvidence source = evidence.sourceReceipt().sourceEvidence(); + AtomicInteger reads = new AtomicInteger(); + AtomicReference committed = new AtomicReference<>(); + when(repository.read(eq("dev"), any(UUID.class))) + .thenAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + if (reads.incrementAndGet() == 1) { + committed.set(receipt(source, 9001L, call.getArgument(1))); + return Optional.empty(); + } + return Optional.of(committed.get()); + }); + when(client.read(any(ReadRequest.class))) + .thenAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(transactionManager.startedWith).isNull(); + ReadRequest request = call.getArgument(0); + assertThat(request.targetNamespace()).isEqualTo("dev"); + assertThat(request.operationId()).isEqualTo(source.operationId()); + assertThat(request.canonicalTenantId()).isEqualTo(source.canonicalTenantId()); + assertThat(request.worldSlug()).isEqualTo(source.worldSlug()); + assertThat(request.requestId()).isNotEqualTo(committed.get().intakeRequestId()); + return source; + }); + when(repository.acceptFresh(eq("dev"), any(UUID.class), eq(source))) + .thenAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + assertThat(call.getArgument(1)).isEqualTo(committed.get().intakeRequestId()); + return committed.get(); + }); + WorldAuthoredSourceIntakeService fixtureService = fixtureService(); + WorldAuthoredSourceIntakeReceipt result = + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> fixtureService.intakeRunOwnedFixture(evidence)); + assertThat(result).isSameAs(committed.get()); + assertThat(result.localTenantKey()).isEqualTo(9001L); + assertThat(result.localTenantKey()).isNotEqualTo(evidence.capability().tenantId()); + assertThat(result.intakeRequestId()) + .isNotEqualTo(UUID.fromString(evidence.capability().operationId())); + assertThat( + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> fixtureService.intakeRunOwnedFixture(evidence))) + .isSameAs(result); + var order = inOrder(repository, client); + order.verify(repository).read("dev", result.intakeRequestId()); + order.verify(client).read(any(ReadRequest.class)); + order.verify(repository).acceptFresh("dev", result.intakeRequestId(), source); + order.verify(repository, times(2)).read("dev", result.intakeRequestId()); + verify(client, times(1)).read(any(ReadRequest.class)); + assertThat(transactionManager.startedWith.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(transactionManager.startedWith.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + } + + @Test + void fixtureIntakeDeniesChangedRemoteSourceBeforeSql() { + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + when(repository.read(eq("dev"), any(UUID.class))).thenReturn(Optional.empty()); + when(client.read(any(ReadRequest.class))) + .thenReturn(source("other", TENANT, SOURCE_OPERATION, WORLD)); + assertThatThrownBy( + () -> + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> fixtureService().intakeRunOwnedFixture(evidence))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class); + verify(repository, never()).acceptFresh(any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void fixtureIntakeDeniesNullOwnerReceiptBeforeIndependentReadback() { + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + AuthoredWorldSourceEvidence source = evidence.sourceReceipt().sourceEvidence(); + when(repository.read(eq("dev"), any(UUID.class))).thenReturn(Optional.empty()); + when(client.read(any(ReadRequest.class))).thenReturn(source); + + assertThatThrownBy( + () -> + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> fixtureService().intakeRunOwnedFixture(evidence))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class) + .hasMessageContaining("owner transaction returned no receipt"); + + verify(repository).acceptFresh(eq("dev"), any(UUID.class), eq(source)); + verify(repository, times(1)).read(eq("dev"), any(UUID.class)); + assertThat(transactionManager.startedWith.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + } + + @Test + void fixtureIntakeDeniesMissingIndependentReceiptAfterOwnerTransaction() { + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + var source = evidence.sourceReceipt().sourceEvidence(); + when(repository.read(eq("dev"), any(UUID.class))).thenReturn(Optional.empty()); + when(client.read(any(ReadRequest.class))).thenReturn(source); + when(repository.acceptFresh(eq("dev"), any(UUID.class), eq(source))) + .thenAnswer(call -> receipt(source, 9001L, call.getArgument(1))); + assertThatThrownBy( + () -> + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> fixtureService().intakeRunOwnedFixture(evidence))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class) + .hasMessageContaining("missing after its owner commit"); + verify(repository).acceptFresh(eq("dev"), any(UUID.class), eq(source)); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + } + + @Test + void fixtureIntakeDeniesChangedIndependentReceiptAfterOwnerTransaction() { + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + var source = evidence.sourceReceipt().sourceEvidence(); + AtomicInteger reads = new AtomicInteger(); + when(repository.read(eq("dev"), any(UUID.class))) + .thenAnswer( + call -> + reads.incrementAndGet() == 1 + ? Optional.empty() + : Optional.of(receipt(source, 9002L, call.getArgument(1)))); + when(client.read(any(ReadRequest.class))).thenReturn(source); + when(repository.acceptFresh(eq("dev"), any(UUID.class), eq(source))) + .thenAnswer(call -> receipt(source, 9001L, call.getArgument(1))); + assertThatThrownBy( + () -> + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> fixtureService().intakeRunOwnedFixture(evidence))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class) + .hasMessageContaining("changed during independent commit readback"); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + } + + @Test + void fixtureIntakeDeniesAmbientTransactionBeforeOwnerAccess() { + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy( + () -> + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> fixtureService().intakeRunOwnedFixture(evidence))) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(client, repository); + assertThat(transactionManager.startedWith).isNull(); + } + + private WorldAuthoredSourceIntakeService fixtureService() { + return new WorldAuthoredSourceIntakeService(client, repository, transactionManager, "dev"); + } + + private static T withFixturePeer( + String namespace, String service, String leaf, Supplier action) { + Context context = + Context.ROOT.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer(namespace, service)); + if (leaf != null) { + GrpcPeerCertificateEvidence certificate = mock(GrpcPeerCertificateEvidence.class); + when(certificate.leafSha256()).thenReturn(leaf); + context = context.withValue(GrpcPeerCertificateEvidence.CONTEXT_KEY, certificate); + } + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + @Test void requiresExactAuthenticatedGameDesignPeerBeforeOwnerAccess() { assertThatThrownBy( @@ -664,13 +907,19 @@ private static AuthoredWorldSourceEvidence source( private static WorldAuthoredSourceIntakeReceipt receipt( AuthoredWorldSourceEvidence source, long localTenantKey) { + return receipt(source, localTenantKey, INTAKE_REQUEST); + } + + private static WorldAuthoredSourceIntakeReceipt receipt( + AuthoredWorldSourceEvidence source, long localTenantKey, UUID intakeRequest) { String requestDigest = - WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, source); + WorldAuthoredSourceIntakeDigest.requestDigest( + source.targetNamespace(), intakeRequest, source); UUID operationId = UUID.fromString("55555555-5555-4555-8555-555555555555"); return new WorldAuthoredSourceIntakeReceipt( 1, - NAMESPACE, - INTAKE_REQUEST, + source.targetNamespace(), + intakeRequest, operationId, source.canonicalTenantId(), source.worldSlug(), @@ -678,7 +927,7 @@ private static WorldAuthoredSourceIntakeReceipt receipt( source.evidenceDigest(), requestDigest, WorldAuthoredSourceIntakeDigest.receiptDigest( - NAMESPACE, operationId, requestDigest, source, localTenantKey), + source.targetNamespace(), operationId, requestDigest, source, localTenantKey), localTenantKey, source); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java index 91392429b4..2253dd2001 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; @@ -18,13 +19,19 @@ import java.util.List; import java.util.Optional; import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidence; +import net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidenceTestFixtures; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeDigest; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; @@ -72,6 +79,509 @@ void clearTransactionState() { TransactionSynchronizationManager.clear(); } + @Test + void fixtureVersionRevalidatesPeerAndCallerBeforeAnyOwnerOrRemoteRead() { + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + var sourceReceipt = sourceReceipt(evidence.sourceReceipt().sourceEvidence()); + WorldAuthoredVersionIdentityService fixtureService = fixtureService(); + assertThatThrownBy( + () -> + withoutPeer(() -> fixtureService.associateRunOwnedFixture(evidence, sourceReceipt))) + .isInstanceOf(SecurityException.class); + for (String[] candidate : + new String[][] { + {"dev", "world-management-service", "a".repeat(64)}, + {"other", "game-session-service", "a".repeat(64)}, + {"dev", "game-session-service", "d".repeat(64)}, + {"dev", "game-session-service", null} + }) { + assertThatThrownBy( + () -> + withFixturePeer( + candidate[0], + candidate[1], + candidate[2], + () -> fixtureService.associateRunOwnedFixture(evidence, sourceReceipt))) + .isInstanceOf(SecurityException.class); + } + assertThatThrownBy( + () -> + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> { + SessionContext.setContext(TENANT.toString(), List.of(), java.util.Map.of()); + try { + return fixtureService.associateRunOwnedFixture(evidence, sourceReceipt); + } finally { + SessionContext.clear(); + } + })) + .isInstanceOf(SecurityException.class); + verifyNoInteractions(sourceIntakeRepository, repository, versionStateClient); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void fixtureVersionConsumesCommittedSourceThenControlledCurrentStateBeforeSqlAndExactRetry() { + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + var source = evidence.sourceReceipt().sourceEvidence(); + var intake = sourceReceipt(source); + var canonicalVersion = evidence.gameSessionAssociation().canonicalVersionId(); + long gameDesignVersion = evidence.launchDescriptor().versionId(); + AtomicInteger ownerReads = new AtomicInteger(); + AtomicReference committed = new AtomicReference<>(); + when(sourceIntakeRepository.readBySource( + "dev", + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .thenAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return Optional.of(intake); + }); + when(repository.readByCanonicalVersion( + "dev", source.canonicalTenantId(), source.worldSlug(), canonicalVersion)) + .thenAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return ownerReads.incrementAndGet() == 1 + ? Optional.empty() + : Optional.of(committed.get()); + }); + when(repository.readByGameDesignVersion( + "dev", source.canonicalTenantId(), source.worldSlug(), gameDesignVersion)) + .thenReturn(Optional.empty()); + when(versionStateClient.read(any())) + .thenAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(transactionManager.startedWith).isNull(); + AuthoredWorldVersionStateEvidence.Request request = call.getArgument(0); + assertThat(request.targetNamespace()).isEqualTo("dev"); + assertThat(request.canonicalTenantId()).isEqualTo(source.canonicalTenantId()); + assertThat(request.versionId()).isEqualTo(gameDesignVersion); + assertThat(request.readRequestId()) + .isNotEqualTo(intake.intakeRequestId()) + .isNotEqualTo(source.operationId()); + return AuthoredWorldVersionStateEvidence.create( + request, + source, + canonicalVersion, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + evidence + .sourceReceipt() + .launchReadEvidence() + .versionState() + .getVersionStateEpoch()); + }); + when(repository.acceptFresh(any(), any())) + .thenAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + assertThat(call.getArgument(0)).isEqualTo(intake); + committed.set(identityReceipt(intake, call.getArgument(1), 101L)); + return committed.get(); + }); + WorldAuthoredVersionIdentityService fixtureService = fixtureService(); + var result = + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> fixtureService.associateRunOwnedFixture(evidence, intake)); + assertThat(result).isSameAs(committed.get()); + assertThat(result.canonicalVersionId()).isEqualTo(canonicalVersion); + assertThat(result.localVersionKey()).isEqualTo(101L); + assertThat(result.sourceIntakeReceipt()).isEqualTo(intake); + InOrder order = inOrder(sourceIntakeRepository, repository, versionStateClient); + order + .verify(sourceIntakeRepository) + .readBySource( + "dev", + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest()); + order + .verify(repository) + .readByCanonicalVersion( + "dev", source.canonicalTenantId(), source.worldSlug(), canonicalVersion); + order + .verify(repository) + .readByGameDesignVersion( + "dev", source.canonicalTenantId(), source.worldSlug(), gameDesignVersion); + order.verify(versionStateClient).read(any()); + order.verify(repository).acceptFresh(intake, result.versionStateEvidence()); + order + .verify(repository) + .readByCanonicalVersion( + "dev", source.canonicalTenantId(), source.worldSlug(), canonicalVersion); + order + .verify(sourceIntakeRepository) + .readBySource( + "dev", + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest()); + assertThat( + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> fixtureService.associateRunOwnedFixture(evidence, intake))) + .isSameAs(result); + verify(versionStateClient, times(1)).read(any()); + verify(repository, times(1)).acceptFresh(any(), any()); + assertThat(transactionManager.startedWith.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(transactionManager.startedWith.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + } + + @Test + void fixtureVersionRejectsDifferentCommittedSourceBeforeVersionAccessOrSql() { + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + var source = evidence.sourceReceipt().sourceEvidence(); + var intake = sourceReceipt(source); + var different = + new WorldAuthoredSourceIntakeReceipt( + intake.schemaVersion(), + intake.targetNamespace(), + intake.intakeRequestId(), + intake.operationId(), + intake.canonicalTenantId(), + intake.worldSlug(), + intake.sourceOperationId(), + intake.sourceEvidenceDigest(), + intake.requestDigest(), + WorldAuthoredSourceIntakeDigest.receiptDigest( + intake.targetNamespace(), + intake.operationId(), + intake.requestDigest(), + source, + intake.localTenantKey() + 1), + intake.localTenantKey() + 1, + source); + when(sourceIntakeRepository.readBySource( + "dev", + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .thenReturn(Optional.of(different)); + assertThatThrownBy( + () -> + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> fixtureService().associateRunOwnedFixture(evidence, intake))) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.RegistrationConflictException.class); + verifyNoInteractions(repository, versionStateClient); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void fixtureVersionRejectsRemoteStateEpochCanonicalVersionAndRequestSubstitutionBeforeSql() { + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + var source = evidence.sourceReceipt().sourceEvidence(); + var intake = sourceReceipt(source); + when(sourceIntakeRepository.readBySource( + "dev", + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .thenReturn(Optional.of(intake)); + for (int variation = 0; variation < 4; variation++) { + int selected = variation; + doAnswer( + call -> { + AuthoredWorldVersionStateEvidence.Request request = call.getArgument(0); + if (selected == 3) { + request = + new AuthoredWorldVersionStateEvidence.Request( + request.schemaVersion(), + request.targetNamespace(), + UUID.randomUUID(), + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.expectedSourceEvidenceDigest(), + request.versionId()); + } + return AuthoredWorldVersionStateEvidence.create( + request, + source, + selected == 2 + ? OTHER_VERSION + : evidence.gameSessionAssociation().canonicalVersionId(), + selected == 0 + ? VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT + : VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + evidence + .sourceReceipt() + .launchReadEvidence() + .versionState() + .getVersionStateEpoch() + + (selected == 1 ? 1L : 0L)); + }) + .when(versionStateClient) + .read(any()); + assertThatThrownBy( + () -> + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> fixtureService().associateRunOwnedFixture(evidence, intake))) + .isInstanceOf( + WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException.class); + } + verify(versionStateClient, times(4)).read(any()); + verify(repository, never()).acceptFresh(any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void fixtureVersionRejectsChangedRetainedSnapshotOnExactRetryWithoutRemoteOrSql() { + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + var source = evidence.sourceReceipt().sourceEvidence(); + var intake = sourceReceipt(source); + var canonicalVersion = evidence.gameSessionAssociation().canonicalVersionId(); + long gameDesignVersion = evidence.launchDescriptor().versionId(); + AtomicReference originalState = new AtomicReference<>(); + AtomicReference retained = new AtomicReference<>(); + when(sourceIntakeRepository.readBySource( + "dev", + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .thenReturn(Optional.of(intake)); + when(repository.readByCanonicalVersion( + "dev", source.canonicalTenantId(), source.worldSlug(), canonicalVersion)) + .thenAnswer(call -> Optional.ofNullable(retained.get())); + when(repository.readByGameDesignVersion( + "dev", source.canonicalTenantId(), source.worldSlug(), gameDesignVersion)) + .thenReturn(Optional.empty()); + when(versionStateClient.read(any())) + .thenAnswer( + call -> { + AuthoredWorldVersionStateEvidence.Request request = call.getArgument(0); + assertThat(request.targetNamespace()).isEqualTo("dev"); + assertThat(request.canonicalTenantId()).isEqualTo(source.canonicalTenantId()); + assertThat(request.worldSlug()).isEqualTo(source.worldSlug()); + assertThat(request.sourceOperationId()).isEqualTo(source.operationId()); + assertThat(request.expectedSourceEvidenceDigest()).isEqualTo(source.evidenceDigest()); + assertThat(request.versionId()).isEqualTo(gameDesignVersion); + var current = + AuthoredWorldVersionStateEvidence.create( + request, + source, + canonicalVersion, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + evidence + .sourceReceipt() + .launchReadEvidence() + .versionState() + .getVersionStateEpoch()); + originalState.set(current); + return current; + }); + when(repository.acceptFresh(any(), any())) + .thenAnswer( + call -> { + var accepted = identityReceipt(intake, call.getArgument(1), 101L); + retained.set(accepted); + return accepted; + }); + + WorldAuthoredVersionIdentityService fixtureService = fixtureService(); + var accepted = + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> fixtureService.associateRunOwnedFixture(evidence, intake)); + assertThat(accepted).isSameAs(retained.get()); + assertThat(originalState.get()).isNotNull(); + assertThat(accepted.versionStateEvidence()).isSameAs(originalState.get()); + assertThat(accepted.versionStateEvidence().versionState()) + .isEqualTo(VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED); + assertThat(accepted.versionStateEvidence().versionStateEpoch()) + .isEqualTo( + evidence.sourceReceipt().launchReadEvidence().versionState().getVersionStateEpoch()); + assertThat(accepted.versionStateEvidence().request()).isEqualTo(originalState.get().request()); + int transactionStartsAfterAcceptance = transactionManager.transactionStarts; + + assertThat( + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> fixtureService.associateRunOwnedFixture(evidence, intake))) + .isSameAs(accepted); + verify(versionStateClient, times(1)).read(any()); + assertThat(transactionManager.transactionStarts).isEqualTo(transactionStartsAfterAcceptance); + + for (VersionLifecycleState retainedState : + List.of( + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED)) { + var changed = + AuthoredWorldVersionStateEvidence.create( + originalState.get().request(), + source, + canonicalVersion, + retainedState, + evidence.sourceReceipt().launchReadEvidence().versionState().getVersionStateEpoch() + + (retainedState == VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED + ? 1L + : 0L)); + retained.set(identityReceipt(intake, changed, 101L)); + assertThatThrownBy( + () -> + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> fixtureService().associateRunOwnedFixture(evidence, intake))) + .isInstanceOf( + WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException.class); + } + verify(versionStateClient, times(1)).read(any()); + verify(repository, times(1)).acceptFresh(any(), any()); + assertThat(transactionManager.transactionStarts).isEqualTo(transactionStartsAfterAcceptance); + } + + @Test + void fixtureVersionDeniesMissingOrSubstitutedIndependentVersionReceipt() { + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + var source = evidence.sourceReceipt().sourceEvidence(); + var intake = sourceReceipt(source); + var canonicalVersion = evidence.gameSessionAssociation().canonicalVersionId(); + long gameDesignVersion = evidence.launchDescriptor().versionId(); + when(sourceIntakeRepository.readBySource( + "dev", + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .thenReturn(Optional.of(intake)); + for (int variation = 0; variation < 2; variation++) { + int selected = variation; + AtomicInteger ownerReads = new AtomicInteger(); + AtomicReference current = new AtomicReference<>(); + when(repository.readByCanonicalVersion( + "dev", source.canonicalTenantId(), source.worldSlug(), canonicalVersion)) + .thenAnswer( + call -> { + if (ownerReads.incrementAndGet() == 1 || selected == 0) return Optional.empty(); + var original = current.get(); + var changed = + AuthoredWorldVersionStateEvidence.create( + original.request(), + source, + canonicalVersion, + original.versionState(), + original.versionStateEpoch() + 1L); + return Optional.of(identityReceipt(intake, changed, 101L)); + }); + when(repository.readByGameDesignVersion( + "dev", source.canonicalTenantId(), source.worldSlug(), gameDesignVersion)) + .thenReturn(Optional.empty()); + doAnswer( + call -> { + var state = + AuthoredWorldVersionStateEvidence.create( + call.getArgument(0), + source, + canonicalVersion, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + evidence + .sourceReceipt() + .launchReadEvidence() + .versionState() + .getVersionStateEpoch()); + current.set(state); + return state; + }) + .when(versionStateClient) + .read(any()); + doAnswer(call -> identityReceipt(intake, call.getArgument(1), 101L)) + .when(repository) + .acceptFresh(any(), any()); + assertThatThrownBy( + () -> + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> fixtureService().associateRunOwnedFixture(evidence, intake))) + .isInstanceOf( + WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException.class); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + } + verify(repository, times(2)).acceptFresh(any(), any()); + } + + @Test + void fixtureVersionDeniesAmbientTransactionBeforeOwnerAccess() { + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy( + () -> + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> + fixtureService() + .associateRunOwnedFixture( + evidence, + sourceReceipt(evidence.sourceReceipt().sourceEvidence())))) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(repository, sourceIntakeRepository, versionStateClient); + assertThat(transactionManager.startedWith).isNull(); + } + + private WorldAuthoredVersionIdentityService fixtureService() { + return new WorldAuthoredVersionIdentityService( + versionStateClient, repository, sourceIntakeRepository, transactionManager, "dev"); + } + + private static T withFixturePeer( + String namespace, String service, String leaf, Supplier action) { + Context context = + Context.ROOT.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer(namespace, service)); + if (leaf != null) { + GrpcPeerCertificateEvidence certificate = mock(GrpcPeerCertificateEvidence.class); + when(certificate.leafSha256()).thenReturn(leaf); + context = context.withValue(GrpcPeerCertificateEvidence.CONTEXT_KEY, certificate); + } + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + @Test void requiresExactSameNamespaceGameDesignPeerBeforeAnyOwnerOrRemoteAccess() { assertThatThrownBy(() -> withoutPeer(() -> associate(VERSION, GAME_DESIGN_VERSION_ID))) @@ -511,6 +1021,7 @@ private static T withoutPeer(Supplier action) { private static final class RecordingTransactionManager implements org.springframework.transaction.PlatformTransactionManager { private TransactionDefinition startedWith; + private int transactionStarts; private boolean loseCommitAcknowledgment; private boolean commitFailureThrown; @@ -518,6 +1029,7 @@ private static final class RecordingTransactionManager public TransactionStatus getTransaction(TransactionDefinition definition) { assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); startedWith = definition; + transactionStarts++; TransactionSynchronizationManager.setActualTransactionActive(true); TransactionSynchronizationManager.setCurrentTransactionReadOnly(definition.isReadOnly()); TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationTest.java new file mode 100644 index 0000000000..f93c2c2444 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationTest.java @@ -0,0 +1,184 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadGrpcCodec; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidence; +import net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidenceTestFixtures; +import org.junit.jupiter.api.Test; + +class WorldCanonicalInstanceAssociationTest { + @Test + void runOwnedFixtureUsesDeepValueEqualityAndRetainsDefensiveResponseBytes() { + FixtureCase fixtureCase = validFixtureCase(); + WorldCanonicalInstanceAssociation.RunOwnedFixture original = fixtureCase.fixture(); + byte[] constructorBytes = original.gameSessionAssociationResponseBytes(); + byte[] expectedBytes = constructorBytes.clone(); + + WorldCanonicalInstanceAssociation.RunOwnedFixture reconstructed = + copy(original, constructorBytes, original.preparationInputDigest()); + assertThat(reconstructed).isEqualTo(original); + assertThat(reconstructed.hashCode()).isEqualTo(original.hashCode()); + assertThat(reconstructed.gameSessionAssociationResponseBytes()).containsExactly(expectedBytes); + + WorldCanonicalInstanceAssociation reconstructedAssociation = + association( + fixtureCase.identity(), + fixtureCase.worldInstanceId(), + fixtureCase.versionIdentity(), + reconstructed); + assertThat(reconstructedAssociation).isEqualTo(fixtureCase.association()); + assertThat(reconstructedAssociation.hashCode()).isEqualTo(fixtureCase.association().hashCode()); + + constructorBytes[0] ^= 1; + assertThat(reconstructed.gameSessionAssociationResponseBytes()).containsExactly(expectedBytes); + assertThat(original.gameSessionAssociationResponseBytes()).containsExactly(expectedBytes); + byte[] accessorBytes = reconstructed.gameSessionAssociationResponseBytes(); + accessorBytes[0] ^= 1; + assertThat(reconstructed.gameSessionAssociationResponseBytes()).containsExactly(expectedBytes); + + WorldCanonicalInstanceAssociation.RunOwnedFixture changed = + copy(original, original.gameSessionAssociationResponseBytes(), digest('d')); + assertThat(changed).isNotEqualTo(original); + assertThat( + association( + fixtureCase.identity(), + fixtureCase.worldInstanceId(), + fixtureCase.versionIdentity(), + changed)) + .isNotEqualTo(fixtureCase.association()); + } + + private static FixtureCase validFixtureCase() { + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + var source = evidence.sourceReceipt().sourceEvidence(); + UUID intakeRequestId = UUID.fromString("11111111-1111-4111-8111-111111111111"); + UUID intakeOperationId = UUID.fromString("22222222-2222-4222-8222-222222222222"); + long worldTenantKey = 9001L; + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest( + source.targetNamespace(), intakeRequestId, source); + WorldAuthoredSourceIntakeReceipt sourceReceipt = + new WorldAuthoredSourceIntakeReceipt( + 1, + source.targetNamespace(), + intakeRequestId, + intakeOperationId, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + requestDigest, + WorldAuthoredSourceIntakeDigest.receiptDigest( + source.targetNamespace(), intakeOperationId, requestDigest, source, worldTenantKey), + worldTenantKey, + source); + + var versionSnapshot = evidence.sourceReceipt().launchReadEvidence().versionState(); + var versionRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + source.targetNamespace(), + UUID.fromString("33333333-3333-4333-8333-333333333333"), + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + versionSnapshot.getVersionId()); + var versionStateEvidence = + AuthoredWorldVersionStateEvidence.create( + versionRequest, + source, + evidence.gameSessionAssociation().canonicalVersionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + versionSnapshot.getVersionStateEpoch()); + WorldAuthoredVersionIdentityReceipt versionIdentity = + new WorldAuthoredVersionIdentityReceipt( + 1, + UUID.fromString("44444444-4444-4444-8444-444444444444"), + 9003L, + sourceReceipt, + versionStateEvidence); + + var gameSession = evidence.gameSessionAssociation(); + var capability = evidence.capability(); + var identity = + new WorldCanonicalInstanceAssociation.CanonicalIdentity( + gameSession.gameInstanceUuid(), + source.targetNamespace(), + source.canonicalTenantId(), + source.worldSlug(), + gameSession.playableStateNamespaceId(), + capability.stateScope(), + capability.publicProductionRealm(), + gameSession.canonicalRealmId(), + gameSession.catalogRevision(), + capability.operationId()); + long worldInstanceId = 9002L; + var privateKeys = + new WorldCanonicalInstanceAssociation.WorldPrivateKeys( + worldTenantKey, worldInstanceId, versionIdentity.localVersionKey()); + var fixture = + new WorldCanonicalInstanceAssociation.RunOwnedFixture( + privateKeys, + gameSession.gameSessionTenantId(), + gameSession.gameInstanceId(), + capability.gameTemplateId(), + UUID.fromString(capability.operationId()), + evidence.fixtureProvenanceDigest(), + digest('a'), + 1L, + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toFixtureResponse(gameSession) + .toByteArray(), + gameSession, + sourceReceipt); + return new FixtureCase( + identity, + worldInstanceId, + versionIdentity, + fixture, + association(identity, worldInstanceId, versionIdentity, fixture)); + } + + private static WorldCanonicalInstanceAssociation.RunOwnedFixture copy( + WorldCanonicalInstanceAssociation.RunOwnedFixture fixture, + byte[] responseBytes, + String preparationInputDigest) { + return new WorldCanonicalInstanceAssociation.RunOwnedFixture( + fixture.worldPrivateKeys(), + fixture.gameSessionTenantId(), + fixture.gameSessionGameInstanceId(), + fixture.gameTemplateId(), + fixture.fixtureOperationId(), + fixture.fixtureProvenanceDigest(), + preparationInputDigest, + fixture.preparingLifecycleEpoch(), + responseBytes, + fixture.gameSessionAssociation(), + fixture.sourceIntakeReceipt()); + } + + private static WorldCanonicalInstanceAssociation association( + WorldCanonicalInstanceAssociation.CanonicalIdentity identity, + long worldInstanceId, + WorldAuthoredVersionIdentityReceipt versionIdentity, + WorldCanonicalInstanceAssociation.RunOwnedFixture fixture) { + return new WorldCanonicalInstanceAssociation( + identity, worldInstanceId, null, versionIdentity, null, fixture); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } + + private record FixtureCase( + WorldCanonicalInstanceAssociation.CanonicalIdentity identity, + long worldInstanceId, + WorldAuthoredVersionIdentityReceipt versionIdentity, + WorldCanonicalInstanceAssociation.RunOwnedFixture fixture, + WorldCanonicalInstanceAssociation association) {} +}