From b66ab76848e375d23c83db8fd21eed5f451f997c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:42:47 +1300 Subject: [PATCH 01/45] Implement authenticated PREPARING-only fixed World owner --- .../game-design-service/api-contracts.md | 4 +- .../world-management-service/api-contracts.md | 4 +- .../runtime-and-data.md | 10 +- .../system-architecture-testing.md | 2 +- ...ame-authoring-publishing-and-activation.md | 4 + .../world-runtime-and-movement.md | 10 + services/game-design-service/build.gradle.kts | 2 + .../data/RunOwnedFixtureLaunchReadback.java | 77 + ...RunOwnedFixtureOwnerReadAuthorization.java | 159 ++ .../data/RunOwnedFixturePolicyProducer.java | 170 +- .../gamedesign/data/TestDataSeeder.java | 39 +- ...ureAuthoredWorldSourceReadGrpcService.java | 92 + ...eAuthoredWorldVersionStateGrpcService.java | 104 + .../src/main/resources/application-prod.yml | 2 + .../src/main/resources/application.yml | 2 + .../data/TestDataSeederIntegrationTest.java | 1308 ++++++++++- ...meDesignSourcePostgresIntegrationTest.java | 6 +- ...lmPolicySourcePostgresIntegrationTest.java | 12 +- ...StorageUpgradePostgresIntegrationTest.java | 32 +- ...ationOperationPostgresIntegrationTest.java | 8 +- ...icyPublicationPostgresIntegrationTest.java | 6 +- ...dWorldSourceRepositoryIntegrationTest.java | 6 +- ...nantCreationRepositoryIntegrationTest.java | 6 +- ...electorSchemaMigrationIntegrationTest.java | 6 +- ...ionAssetExportSnapshotIntegrationTest.java | 12 +- ...aunchDescriptorServiceIntegrationTest.java | 6 +- ...olicyPublicationReadConfigurationTest.java | 4 +- ...wnedFixtureOwnerReadAuthorizationTest.java | 208 ++ .../CanonicalLaunchGrpcAuthWiringTest.java | 39 +- .../TenantIdentityGrpcAuthWiringTest.java | 4 +- ...AuthoredWorldOwnerReadGrpcServiceTest.java | 128 ++ .../RunOwnedWorldFixedPresetResources.java | 1310 +++++++++++ .../data/RunOwnedWorldLaunchEvidence.java | 25 + .../WorldLifecycleCommandServiceImpl.java | 483 +++- .../WorldAuthoredSourceIntakeService.java | 127 ++ .../WorldAuthoredVersionIdentityService.java | 153 +- .../WorldCanonicalInstanceAssociation.java | 636 ++++++ ...anonicalInstanceAssociationRepository.java | 1994 +++++++++++++++++ ...__world_canonical_instance_association.sql | 506 +++++ ..._restore_stable_legacy_update_fastpath.sql | 26 + ...guarded_canonical_instance_preparation.sql | 858 +++++++ .../V1010__world_draft_terminal_outcomes.sql | 237 ++ ...__world_draft_terminal_guard_namespace.sql | 43 + ..._world_account_bound_graph_application.sql | 216 ++ ..._world_preparation_exact_release_graph.sql | 67 + ...ld_explicit_fresh_graph_start_location.sql | 292 +++ ...release_start_location_materialization.sql | 227 ++ ...anonical_instance_activation_operation.sql | 565 +++++ ...17__world_publication_terminal_handoff.sql | 354 +++ ...8__world_operational_region_assignment.sql | 93 + ...orld_canonical_initial_player_location.sql | 458 ++++ ...nonical_initial_admission_hold_binding.sql | 255 +++ ...onical_initial_admission_hold_terminal.sql | 334 +++ ...cal_initial_player_location_typed_hold.sql | 146 ++ ...cal_initial_location_operation_origins.sql | 148 ++ ..._world_canonical_player_admission_hold.sql | 241 ++ ...al_activation_complete_region_evidence.sql | 108 + ...d_selected_publication_account_binding.sql | 86 + ...d_publication_terminal_account_binding.sql | 115 + ...elected_publication_artifact_inventory.sql | 112 + ...29__publication_operation_inventory_v2.sql | 192 ++ ...cation_inventory_projection_precedence.sql | 19 + ...__publication_account_order_projection.sql | 19 + ...d_selected_inbound_closure_declaration.sql | 115 + ...lected_publication_inventory_schema_v2.sql | 63 + ..._world_selected_closure_schema4_guards.sql | 267 +++ ...start_session_execution_terminal_fence.sql | 817 +++++++ ...iginal_start_session_attempt_admission.sql | 583 +++++ ...world_launch_captured_catalog_identity.sql | 280 +++ ...nal_start_session_protected_activation.sql | 367 +++ ...anonical_activation_preparation_schema.sql | 38 + ...un_owned_fixture_canonical_association.sql | 665 ++++++ ...rld_run_owned_fixed_preset_preparation.sql | 1842 +++++++++++++++ ...LaunchEvidencePostgresIntegrationTest.java | 74 +- ...resetResourcesPostgresIntegrationTest.java | 1889 ++++++++++++++++ ...OwnedWorldFixtureEvidenceTestFixtures.java | 398 ++++ ...OwnedWorldFixtureLifecycleTestFactory.java | 96 + ...edGraphCapturePostgresIntegrationTest.java | 41 +- ...nOwnedWorldLaunchEvidenceProviderTest.java | 326 +-- ...nOwnedWorldLaunchEvidenceTestFixtures.java | 262 +++ .../WorldLifecycleCommandServiceImplTest.java | 29 +- .../WorldAuthoredSourceIntakeServiceTest.java | 226 +- ...rldAuthoredVersionIdentityServiceTest.java | 445 ++++ 83 files changed, 21361 insertions(+), 379 deletions(-) create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerReadAuthorization.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldSourceReadGrpcService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldVersionStateGrpcService.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerReadAuthorizationTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResources.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociation.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java create mode 100644 services/world-management-service/src/main/resources/db/migration/V1008__world_canonical_instance_association.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1009.1__world_restore_stable_legacy_update_fastpath.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1009__world_guarded_canonical_instance_preparation.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1010__world_draft_terminal_outcomes.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1011__world_draft_terminal_guard_namespace.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1012__world_account_bound_graph_application.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1013__world_preparation_exact_release_graph.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1014__world_explicit_fresh_graph_start_location.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1015__world_release_start_location_materialization.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1016__canonical_instance_activation_operation.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1017__world_publication_terminal_handoff.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1018__world_operational_region_assignment.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1019__world_canonical_initial_player_location.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1020__canonical_initial_admission_hold_binding.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1021__canonical_initial_admission_hold_terminal.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1022__canonical_initial_player_location_typed_hold.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1023__canonical_initial_location_operation_origins.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1024__world_canonical_player_admission_hold.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1025__canonical_activation_complete_region_evidence.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1026__world_selected_publication_account_binding.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1027__world_publication_terminal_account_binding.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1028__selected_publication_artifact_inventory.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1029__publication_operation_inventory_v2.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1030__world_publication_inventory_projection_precedence.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1031__publication_account_order_projection.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1032__world_selected_inbound_closure_declaration.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1033__world_selected_publication_inventory_schema_v2.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1034__world_selected_closure_schema4_guards.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1035__world_start_session_execution_terminal_fence.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1036__world_original_start_session_attempt_admission.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1037__world_launch_captured_catalog_identity.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1038__original_start_session_protected_activation.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1039__canonical_activation_preparation_schema.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1040__world_run_owned_fixture_canonical_association.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1041__world_run_owned_fixed_preset_preparation.sql create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixtureEvidenceTestFixtures.java create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedWorldFixtureLifecycleTestFactory.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceTestFixtures.java diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index bd0c08132c..acbeff50d7 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -69,7 +69,9 @@ For a `SaveRevision` request carrying `worldDesignMutation`, the same authorizat The coherent selected-publication receiver installs immutable source inventories, selected owner attestations and mandatory fresh-v2 operation/capture guards through V1023, then asset-bound reviewed-base v2 guards in V1024. Current Java callers supply complete v2 operation evidence and the ordinary asset owner participates in synchronized source and export projection. Original v1 operation/review bytes remain readable history without fresh write authority. This adds no registered publication ingress or activation authority. The canonical retention and fresh-operation rule is in [Version Control](./version-control.md#selected-publication-storage-and-retained-operations), with physical owner proof, controlled-input limits and current qualification in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#coherent-owner-receiving-prerequisite). -The first authored-world source-retention cut includes passive `GetAuthoredWorldVersionState` and `ResolveAuthoredWorldSource` reads for World Management, implemented by the owner-local `AuthoredWorldVersionStateService` and `GameAuthoredWorldSourceRepository`. Their RPC adapters (`AuthoredWorldVersionStateGrpcService` and `AuthoredWorldSourceReadGrpcService`) are standalone and unregistered, authenticate the exact same-namespace World workload, and use no caller-context propagation. They do not replace or alter the registered `TenantIdentityService.ResolveFreshTenantCreation` contract above, and introduce no registration or activation path. World proof status and exact scope are recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). Graph snapshot capture is a later World owner-digest/topology stage, not part of these reads. No external source application, runtime activation, or gameplay-admission claim is made. +The first authored-world source-retention cut includes passive `GetAuthoredWorldVersionState` and `ResolveAuthoredWorldSource` reads for World Management, implemented by the owner-local `AuthoredWorldVersionStateService` and `GameAuthoredWorldSourceRepository`. Their RPC adapters (`AuthoredWorldVersionStateGrpcService` and `AuthoredWorldSourceReadGrpcService`) are standalone and unregistered, authenticate the exact same-namespace World workload, and use no caller-context propagation. They do not replace or alter the registered `TenantIdentityService.ResolveFreshTenantCreation` contract above, and introduce no generic registration or activation path. World proof status and exact scope are recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). Graph snapshot capture is a later World owner-digest/topology stage, not part of these reads. No external source application, runtime activation, or gameplay-admission claim is made. + +The existing default-off run-owned fixture configuration registers operation-scoped wrappers for those same two RPCs. Before decoding selectors, each wrapper rejects caller context and requires the fixed `dev` World workload URI, its exact mounted leaf, and immutable run/project/capability/receipt/CA configuration. Exact selectors must match the retained closed fixture source and Version. Successful reads independently qualify actual committed creation, source, Version, bundle and descriptor owners plus the already sealed policy header; they never resolve a descriptor, seal a policy, allocate state or repair missing owners. The two exact RPC names bypass bearer validation in both profiles; the generic kernels retain their independent peer checks and remain unregistered. This fixture variant grants no Human source application, activation or admission authority. Its focused proof and runtime limits belong to the [implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#fixed-fixture-source-and-version-reads). The owner-local foundation persists authored-world source operations and delivery outbox rows, canonical Version and bundle identity, opaque release references, optional manifest/artifact metadata, and additive launch-descriptor bindings. There is no creator source-registration RPC. The complete fixture successor activates only the claimed run-owned producer and source-bound descriptor handlers described above; production launch-read authorization remains deny-only. Ordinary new Version and bundle writes derive identity from the exact persisted Game row; retained all-null descriptor reads and inserts remain supported. State-changing `CompareAndSetVersionState` calls return `VERSION_STATE_MUTATION_UNAVAILABLE` after tenant/version and expected-epoch checks; exact same-state requests remain no-ops. This containment does not establish legal lifecycle transitions, Account authorization, or database CAS proof. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 53d203163c..b50bc6873f 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 bounded canonical fixture launch successor reads the exact authenticated Game Session `STARTING` allocation as source evidence. World fixture bootstrap and prepare/activate refuse before repository effects while source/Version materialization, canonical World association and holds are unavailable. Ordinary demo topology remains under its existing separate configuration. This read neither adopts numeric source keys nor supplies an `ACTIVE` state, first admission bind, Entity placement or operational-region authority. The guarded graph owner's stored and capture states remain unverified; [the World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status) records physical proof and remaining phases. +The bounded canonical fixture launch successor reads the exact authenticated Game Session `STARTING` allocation as source evidence. The local PREPARING owner successor composes fresh authenticated Game Design source/Version reads, World-private allocation and exact fixed-preset materialization through the existing synchronous prepare RPC. Its bounded native producer/owner/socket composition passes; packaged composition remains unqualified. Fixture bootstrap, activation and admission remain unavailable before owner effects. Ordinary demo topology remains under its existing separate configuration. This read neither adopts numeric source keys nor supplies an `ACTIVE` state, first admission bind, Entity placement or operational-region authority. The guarded graph owner's stored and capture states remain unverified; [the World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status) records physical proof and remaining phases. 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. +The local follow-on adds typed fixed-fixture source intake and Version association operations. The retained provider carrier must revalidate its original fixed Game Session URI and leaf before owner access; caller context is rejected. Authenticated Game Design reads precede the short World owner transaction, and committed readback retains independently allocated World-private keys. Exact retries compare original source and sealed Version state/epoch, including owner-race recovery and independent receipt readback. The synchronous fixture prepare path composes these owners into the original `PREPARING` epoch 1, row version 0 allocation. It rejects ambient transactions before remote evidence reads; ordinary preparation retains its existing `REQUIRED` transaction boundary. The fixed plan retains the original Game Session association response bytes, while each retry independently verifies a fresh owner read without making its read nonce part of the retained seal. Only an explicit current typed evidence carrier can dispatch materialization. Fixture activation, hold acquire/finalize and initial placement remain denied by authenticated code and SQL owners; the fixture bootstrap and Temporal path remain unavailable. The [storage contract](./runtime-and-data.md#fixed-fixture-preparing-owner) records the local migration and manifest consequence. Bounded native owner/socket composition is qualified under controlled test capabilities and PKI; packaged proof remains unqualified. Proof attribution belongs to the [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#fixed-fixture-source-and-version-owner-preparation). + ## gRPC APIs - `GetRoom` – retrieves room data including exits and environmental effects through `RoomInstanceRef`. 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 bfdf4abc9d..5c31c9cece 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -16,10 +16,18 @@ - 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 current run-owned fixture independently authenticates the Game Design descriptor and canonical Game Session `STARTING` allocation. World fixture bootstrap and prepare/activate refuse before repository effects pending actual World source/Version materialization, association, fixed-preset preparation and holds. Retained fixture binding/epoch columns and passive repository readback do not establish lifecycle authority. The complete target ordering and replay contract remain in [Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence); candidate-specific implementation and proof limits are in [the World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#canonical-fixture-launch-receiving-boundary). +- The current run-owned fixture independently authenticates the Game Design descriptor and canonical Game Session `STARTING` allocation. The local PREPARING owner successor composes typed source/Version intake, canonical association and fixed-preset materialization; its bounded native physical composition passes. Fixture bootstrap, activation and admission remain unavailable before effects. Retained fixture binding/epoch columns and passive repository readback do not establish lifecycle authority. The complete target ordering and replay contract remain in [Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence); candidate-specific implementation and proof limits are in [the World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#canonical-fixture-launch-receiving-boundary). ## 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 local migration frontier preserves the immutable V1008–V1039 donor artifacts and the immediate V1009.1 legacy UPDATE repair, then adds the unpublished PREPARING-only V1040/V1041 extension. The complete World plus Saga history contains 75 files, adding 35 SQL paths to the preceding 40-file boundary. Historical Human rows retain their original fields, nullable realm/catalog metadata and existing permission guards; no fixture backfill or Human protection is inferred. The extension has no fixture activation function, ACTIVE readback arm or fixture hold authority. World lifecycle transition, hold acquire/finalize, initial placement and player-admission owners reject the fixture variant before effects. The [Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence) owns the complete launch and replay ordering; the [tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#fixed-fixture-preparing-owner-preparation) records current physical and runtime proof. + ### 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. diff --git a/design/architecture/system-architecture-testing.md b/design/architecture/system-architecture-testing.md index f6b4bb721b..255640cca7 100644 --- a/design/architecture/system-architecture-testing.md +++ b/design/architecture/system-architecture-testing.md @@ -179,7 +179,7 @@ Unknown, partial, stale, contradictory, or unavailable reset, mutation, or clean #### Run-owned v1 launch read evidence -Current bounded implementation stops after the closed Game Design producer and independently read canonical Game Session `STARTING` allocation. The existing fixture configuration selects those owners without a second launch flag. Authenticated allocation readback is source evidence only; World bootstrap and fixture prepare/activate refuse before effects while materialization and holds are unavailable. 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. +The published bounded launch owner stops after the closed Game Design producer and independently read canonical Game Session `STARTING` allocation. The local PREPARING successor composes the fixed source/Version registrations and World association/materialization owners through the existing synchronous prepare RPC; its bounded native owner/socket composition is qualified, while packaged proof remains unqualified. The existing default-off fixture configuration selects those owners without a second launch flag. Authenticated allocation readback supplies source evidence only. Bootstrap, activation, holds, first `OPEN` and placement remain unavailable before effects in their code and SQL owners. The complete preparation and first-`OPEN` ordering below is the target contract; owning service trackers retain candidate-specific implementation and proof limits. 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. 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 c387dd9567..ac720f2400 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 @@ -8,6 +8,10 @@ This is a non-normative implementation tracker for game authoring, publishing, a 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. +### Fixed fixture source and Version reads + +The local World follow-on registers default-off, operation-scoped wrappers around the existing Game Design 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. Whole unit proof retains 510 passing results from their earlier fresh execution on unchanged production inputs. The complete native suite passes 142 freshly executed PostgreSQL-backed cases, including 22 fixture cases and actual GDS producer → persisted GS `STARTING` → World `PREPARING` over three production mTLS handlers with unchanged owner rows, receipt bytes and `xmin` on retry and reconstruction. The fixed read adapters are registered in a real managed annotation context with actual producer owners; complete Spring Boot and packaged fresh/restart remain unqualified. The final native parent-file enumeration correction passes nine fresh storage-upgrade cases, formatting and all required static checks; the other native postimages retain their complete preceding execution attribution. This does not close any genuine Gameplay handoff. + ### 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. 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 c8a15e2341..94281bf7d3 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -10,6 +10,16 @@ This is a non-normative implementation tracker for world runtime and movement. C The canonical launch-owner successor adds authenticated fixed Game Session `STARTING` allocation readback. World bootstrap and fixture prepare/activate refuse before owner effects until actual World materialization and holds are composed. 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 local owner successor contains 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 passes formatting/static validation, 307 unit results reused from their preceding fresh execution and 75 freshly executed integrations (73 PostgreSQL-backed and two controlled mTLS). Game Design separately passes 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 passes nine freshly executed storage-upgrade cases and all required Game Design static checks; its 510 unit results are reused from earlier unchanged production inputs. Exact source and XML archives retain these separate scopes. The synchronous prepare entry uses fresh remote reads before SQL and preserves ordinary `REQUIRED` transactions. + +Fresh default-order 75-file installation, installed 34→40→75 upgrade, current-75 schema-2 snapshot retention, exact topology/manifest readback, rollback/races and reconstructed-owner retry pass physical execution. The GDS fixed read adapters are registered in a real managed annotation context with actual producer owners before serving their production handlers. Controlled test capabilities and PKI remain distinct from an actual claimed Compose deployment; complete packaged/Spring Boot fresh/restart proof remains open. Historical pre-1037 canonical Human schema-1 allocation retention is unconstructed because its genuine preparation/execution prerequisites are unavailable; no fake Account protection or disabled storage guard supplies that coverage. Historical guarded positive storage is explicitly pinned to 1007.1 and does not qualify current Account/APPLIED authority. Fixture bootstrap, activation, hold acquire/finalize, first OPEN prerequisites and initial placement stay unavailable; no Entity or operational-region evidence is 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 The World owner stage carries immutable donor migrations V1003–V1007 for guarded six-family topology, authored/canonical graph storage and schema-3 capture. The ordinary digest writer now emits schema 3 with tagged numeric-versus-canonical Entity references through its installed interface. The installed 31 World plus three Saga artifacts remain unchanged. New V1007.1 restores the installed V27.2 stable same-tenant legacy UPDATE fastpath after V1004; later donor guard replacements must preserve that same invariant through their own forward repairs. No shared/protobuf or Game Design/Game Session fixture contracts are introduced, and the existing private fixture bootstrap is unchanged. diff --git a/services/game-design-service/build.gradle.kts b/services/game-design-service/build.gradle.kts index f404aca6d2..8bf32c908a 100644 --- a/services/game-design-service/build.gradle.kts +++ b/services/game-design-service/build.gradle.kts @@ -28,5 +28,7 @@ dependencies { implementation(libs.aws.sdk.s3) testCompileOnly(libs.spotbugs.annotations) add("integrationTestCompileOnly", libs.spotbugs.annotations) + add("integrationTestImplementation", project(":game-session-service")) + add("integrationTestImplementation", project(":world-management-service")) testImplementation(libs.bouncycastle.pkix) } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureLaunchReadback.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureLaunchReadback.java index 20b0a98459..fa60d5ba64 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureLaunchReadback.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureLaunchReadback.java @@ -134,6 +134,83 @@ public net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence readComm return committed; } + /** + * Qualifies the immutable receipt through committed owners without resolving or writing a + * descriptor. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public CommittedReceipt readCommittedReceipt( + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt + receipt) { + readCommittedCreation(receipt.creationEvidence()); + var source = receipt.sourceEvidence(); + var committed = + sourceRepository + .read( + source.operationId(), + source.canonicalTenantId(), + source.worldSlug(), + source.targetNamespace()) + .orElseThrow(() -> new IllegalStateException("Committed fixture source unavailable")); + if (!source.equals(committed)) { + throw new IllegalStateException("Immutable fixture receipt differs from committed source"); + } + var launch = receipt.launchReadEvidence(); + Snapshot current = + snapshot( + source.sourceGameRowId(), + launch.gameTemplateId(), + launch.versionState().getVersionId(), + committed); + if (!current.bundleProto().equals(launch.publishedReleaseBundle()) + || !current.artifactProto().equals(launch.versionAssetArtifactState()) + || !current.versionProto().equals(launch.versionState())) { + throw new IllegalStateException( + "Immutable fixture receipt differs from committed launch snapshots"); + } + var request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + source.targetNamespace(), + receipt.fixtureOperationId(), + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + launch.gameTemplateId(), + false, + null, + false, + null, + false, + null, + false, + null); + var expected = + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec + .fromLaunchDescriptorMessage(request, launch.launchDescriptor()); + UUID readRequestId; + do { + readRequestId = UUID.randomUUID(); + } while (readRequestId.equals(request.authoredWorldSourceOperationId()) + || readRequestId.toString().equals(request.controlPlaneRequestId())); + ResolvedLaunchDescriptorDto descriptor = + launchDescriptorService.getLaunchDescriptor( + readRequestId, + request.canonicalTenantId(), + request.worldSlug(), + request.controlPlaneRequestId(), + expected.requestDigest(), + expected.resultDigest()); + if (!expected.equals(descriptor.authoredWorldBinding())) { + throw new IllegalStateException( + "Immutable fixture receipt differs from committed descriptor"); + } + requireDescriptorMatchesSnapshot(descriptor, request, current); + return new CommittedReceipt(current, descriptor); + } + + public record CommittedReceipt(Snapshot snapshot, ResolvedLaunchDescriptorDto descriptor) {} + /** Resolves and independently reads the committed descriptor outside the seeder transaction. */ @Transactional(propagation = Propagation.NOT_SUPPORTED) public ResolvedLaunchDescriptorDto resolveAndReadLaunchDescriptor( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerReadAuthorization.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerReadAuthorization.java new file mode 100644 index 0000000000..3ea0aee893 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerReadAuthorization.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.gamedesign.data; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.file.Path; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateGrpcCodec; +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.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.stereotype.Service; + +/** Fixed operation authorization backed by preexisting producer owners; not a wire issuer. */ +@Service +@ConditionalOnProperty( + name = "FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED", + havingValue = "true") +public class RunOwnedFixtureOwnerReadAuthorization { + private final RunOwnedFixtureLaunchReadback readback; + private final RunOwnedFixturePolicyProducer policy; + private final String namespace; + private final String runId; + private final String project; + private final String capabilityPath; + private final String receiptPath; + private final String sessionCertificate; + private final String worldCertificate; + private final String caCertificate; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Framework-managed owner collaborators are retained; invalid immutable fixture configuration intentionally refuses startup.") + public RunOwnedFixtureOwnerReadAuthorization( + RunOwnedFixtureLaunchReadback readback, + RunOwnedFixturePolicyProducer policy, + @Value("${firemud.grpc.workload-namespace:}") String namespace, + @Value("${FIREMUD_SMOKE_RUN_ID:}") String runId, + @Value("${FIREMUD_SMOKE_COMPOSE_PROJECT_NAME:}") String project, + @Value( + "${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH:/app/run-owned-initial-admission-capability.json}") + String capabilityPath, + @Value( + "${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH:/app/run-owned-authored-world-source/source-receipt.json}") + String receiptPath, + @Value("${FIREMUD_SMOKE_GAME_SESSION_LEAF_CERT_PATH:/app/game-session-fixture-client.crt}") + String sessionCertificate, + @Value( + "${FIREMUD_SMOKE_WORLD_MANAGEMENT_LEAF_CERT_PATH:/app/world-management-fixture-client.crt}") + String worldCertificate, + @Value("${firemud.grpc.ca-cert:certs/ca.crt}") String caCertificate) { + this.readback = Objects.requireNonNull(readback); + this.policy = Objects.requireNonNull(policy); + this.namespace = namespace; + this.runId = runId; + this.project = project; + this.capabilityPath = capabilityPath; + this.receiptPath = receiptPath; + this.sessionCertificate = sessionCertificate; + this.worldCertificate = worldCertificate; + this.caCertificate = caCertificate; + // Receipt publication happens after startup seeding. Configuration/certificates must already + // be valid, while missing or uncommitted receipt evidence is refused at every actual read. + configuration(); + } + + public SourceReceipt authorizeSource(ResolveAuthoredWorldSourceRequest wire) { + var trusted = authenticatedConfiguration(); + SourceReceipt receipt = receipt(trusted); + var request = AuthoredWorldSourceGrpcCodec.fromReadRequest(namespace, wire); + var source = receipt.sourceEvidence(); + if (!request.targetNamespace().equals(source.targetNamespace()) + || !request.operationId().equals(source.operationId()) + || !request.canonicalTenantId().equals(source.canonicalTenantId()) + || !request.worldSlug().equals(source.worldSlug())) { + throw new SecurityException("Fixed fixture source selector differs"); + } + qualifyOwners(trusted, receipt); + return receipt; + } + + public SourceReceipt authorizeVersion(GetAuthoredWorldVersionStateRequest wire) { + var trusted = authenticatedConfiguration(); + SourceReceipt receipt = receipt(trusted); + var request = AuthoredWorldVersionStateGrpcCodec.fromRequest(wire); + var source = receipt.sourceEvidence(); + if (!namespace.equals(request.targetNamespace()) + || !request.canonicalTenantId().equals(source.canonicalTenantId()) + || !request.worldSlug().equals(source.worldSlug()) + || !request.sourceOperationId().equals(source.operationId()) + || !request.expectedSourceEvidenceDigest().equals(source.evidenceDigest()) + || request.versionId() != receipt.launchReadEvidence().versionState().getVersionId()) { + throw new SecurityException("Fixed fixture Version selector differs"); + } + qualifyOwners(trusted, receipt); + return receipt; + } + + private TestDataSeeder.FixtureCapability authenticatedConfiguration() { + if (SessionContext.hasAuthenticatedCallerContext()) { + throw new SecurityException("Fixture owner reads reject caller context"); + } + var peer = GrpcPeerIdentity.current(); + var certificate = GrpcPeerCertificateEvidence.current(); + if (peer == null + || certificate == null + || !peer.uri().equals("spiffe://firemud/ns/dev/sa/world-management-service")) { + throw new SecurityException("Fixed World TLS peer required"); + } + var trusted = configuration(); + if (!peer.isInNamespace(namespace) + || !certificate.leafSha256().equals(trusted.worldManagementLeafSha256())) { + throw new SecurityException("Fixed World TLS leaf differs"); + } + return trusted; + } + + private TestDataSeeder.FixtureCapability configuration() { + return TestDataSeeder.verifyFixtureConfiguration( + namespace, + runId, + project, + capabilityPath, + receiptPath, + sessionCertificate, + worldCertificate, + caCertificate); + } + + private SourceReceipt receipt(TestDataSeeder.FixtureCapability trusted) { + byte[] bytes = + RunOwnedFixtureImmutableFileReader.readBoundedImmutableFile( + Path.of(receiptPath), + 16 * 1024, + () -> new IllegalStateException("Fixed fixture receipt unavailable")); + try { + return RunOwnedInitialAdmissionFixtureWireCodec.parseSourceReceipt(bytes, trusted.wire()); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException("Fixed fixture receipt invalid", invalid); + } + } + + private void qualifyOwners(TestDataSeeder.FixtureCapability trusted, SourceReceipt receipt) { + var committed = readback.readCommittedReceipt(receipt); + var actualSeal = + policy.readExisting( + trusted, receipt.creationEvidence(), committed.snapshot(), committed.descriptor()); + if (!actualSeal.equals(receipt.fixturePolicySeal())) { + throw new IllegalStateException("Fixed receipt policy seal differs from committed owner"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixturePolicyProducer.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixturePolicyProducer.java index de329a7415..3c1b54763e 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixturePolicyProducer.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixturePolicyProducer.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamedesign.data; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.Map; @@ -18,7 +19,7 @@ /** Fixed-capability fixture authority only; never emits human selected-publication evidence. */ @Service -final class RunOwnedFixturePolicyProducer { +public final class RunOwnedFixturePolicyProducer { private static final String SCHEMA = "firemud.run-owned-fixture-policy-seal.v1"; private static final String OWNER = "game-design-service"; private final DSLContext dsl; @@ -27,7 +28,11 @@ final class RunOwnedFixturePolicyProducer { private final TransactionTemplate write; private final TransactionTemplate read; - RunOwnedFixturePolicyProducer( + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Framework-managed SQL and JSON collaborators are retained for owner operations.") + public RunOwnedFixturePolicyProducer( DSLContext dsl, RunOwnedFixtureLaunchReadback readback, ObjectMapper json, @@ -49,6 +54,85 @@ RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal sealAndRead( FreshTenantCreationEvidence creation, RunOwnedFixtureLaunchReadback.Snapshot snapshot, ResolvedLaunchDescriptorDto descriptor) { + PolicyFrame frame = frame(trusted, creation, snapshot, descriptor); + var source = snapshot.sourceEvidence(); + byte[] request = frame.request(); + String requestDigest = frame.requestDigest(); + String bindingJson = frame.bindingJson(); + String policyJson = frame.policyJson(); + write.executeWithoutResult( + ignored -> { + dsl.fetchSingle( + "SELECT id FROM game WHERE id=? AND tenant_id=? FOR UPDATE", + creation.sourceGameRowId(), + creation.sourceGameTenantKey()); + dsl.fetchSingle( + "SELECT id FROM version WHERE id=? AND tenant_id=? FOR UPDATE", + snapshot.version().id(), + creation.sourceGameTenantKey()); + UUID operationId = trusted.operationId(); + String evidenceDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + operationId, requestDigest); + dsl.execute( + "INSERT INTO game_design_published_realm_policy_set " + + "(canonical_tenant_id, canonical_version_id, game_design_version_row_id, version_number, sealed, " + + "fixture_operation_id, fixture_request_bytes, fixture_request_digest, fixture_evidence_digest, " + + "fixture_binding_json, fixture_policy_json) VALUES (?, ?, ?, ?, TRUE, ?, ?, ?, ?, ?::jsonb, ?::jsonb) " + + "ON CONFLICT (canonical_tenant_id, canonical_version_id) DO NOTHING", + source.canonicalTenantId(), + snapshot.version().canonicalVersionId(), + snapshot.version().id(), + snapshot.version().versionNumber(), + operationId, + request, + requestDigest, + evidenceDigest, + bindingJson, + policyJson); + requireExactRow(snapshot, request, requestDigest, bindingJson, policyJson); + }); + var seal = + Objects.requireNonNull( + read.execute( + ignored -> + requireExactRow(snapshot, request, requestDigest, bindingJson, policyJson))); + // Independent owner read after seal commit; changing upstream rows cannot publish a receipt. + readback.readCommittedCreation(creation); + var committedSnapshot = readback.readCommittedOutcome(snapshot); + var committedDescriptor = + readback.resolveAndReadLaunchDescriptor(descriptor.authoredWorldBinding().request()); + if (!descriptor.equals(committedDescriptor)) { + throw new IllegalStateException("Fixture descriptor changed after policy seal commit"); + } + readback.requireDescriptorMatchesSnapshot( + committedDescriptor, descriptor.authoredWorldBinding().request(), committedSnapshot); + return seal; + } + + /** Reads only an already sealed fixture owner; never invokes the producer write transaction. */ + RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal readExisting( + TestDataSeeder.FixtureCapability trusted, + FreshTenantCreationEvidence creation, + RunOwnedFixtureLaunchReadback.Snapshot snapshot, + ResolvedLaunchDescriptorDto descriptor) { + PolicyFrame frame = frame(trusted, creation, snapshot, descriptor); + return Objects.requireNonNull( + read.execute( + ignored -> + requireExactRow( + snapshot, + frame.request(), + frame.requestDigest(), + frame.bindingJson(), + frame.policyJson()))); + } + + private PolicyFrame frame( + TestDataSeeder.FixtureCapability trusted, + FreshTenantCreationEvidence creation, + RunOwnedFixtureLaunchReadback.Snapshot snapshot, + ResolvedLaunchDescriptorDto descriptor) { var capability = trusted.wire(); var source = snapshot.sourceEvidence(); if (!creation.canonicalTenantId().equals(source.canonicalTenantId()) @@ -108,54 +192,19 @@ RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal sealAndRead( Map.entry("ownerAccountId", capability.ownerAccountId())); String bindingJson = serialize(binding); String policyJson = serialize(policy); - write.executeWithoutResult( - ignored -> { - dsl.fetchSingle( - "SELECT id FROM game WHERE id=? AND tenant_id=? FOR UPDATE", - creation.sourceGameRowId(), - creation.sourceGameTenantKey()); - dsl.fetchSingle( - "SELECT id FROM version WHERE id=? AND tenant_id=? FOR UPDATE", - snapshot.version().id(), - creation.sourceGameTenantKey()); - UUID operationId = trusted.operationId(); - String evidenceDigest = - RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( - operationId, requestDigest); - dsl.execute( - "INSERT INTO game_design_published_realm_policy_set " - + "(canonical_tenant_id, canonical_version_id, game_design_version_row_id, version_number, sealed, " - + "fixture_operation_id, fixture_request_bytes, fixture_request_digest, fixture_evidence_digest, " - + "fixture_binding_json, fixture_policy_json) VALUES (?, ?, ?, ?, TRUE, ?, ?, ?, ?, ?::jsonb, ?::jsonb) " - + "ON CONFLICT (canonical_tenant_id, canonical_version_id) DO NOTHING", - source.canonicalTenantId(), - snapshot.version().canonicalVersionId(), - snapshot.version().id(), - snapshot.version().versionNumber(), - operationId, - request, - requestDigest, - evidenceDigest, - bindingJson, - policyJson); - requireExactRow(snapshot, request, requestDigest, bindingJson, policyJson); - }); - var seal = - Objects.requireNonNull( - read.execute( - ignored -> - requireExactRow(snapshot, request, requestDigest, bindingJson, policyJson))); - // Independent owner read after seal commit; changing upstream rows cannot publish a receipt. - readback.readCommittedCreation(creation); - var committedSnapshot = readback.readCommittedOutcome(snapshot); - var committedDescriptor = - readback.resolveAndReadLaunchDescriptor(descriptor.authoredWorldBinding().request()); - if (!descriptor.equals(committedDescriptor)) { - throw new IllegalStateException("Fixture descriptor changed after policy seal commit"); + return new PolicyFrame(request, requestDigest, bindingJson, policyJson); + } + + private record PolicyFrame( + byte[] request, String requestDigest, String bindingJson, String policyJson) { + private PolicyFrame { + request = request.clone(); + } + + @Override + public byte[] request() { + return request.clone(); } - readback.requireDescriptorMatchesSnapshot( - committedDescriptor, descriptor.authoredWorldBinding().request(), committedSnapshot); - return seal; } private RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal requireExactRow( @@ -171,6 +220,9 @@ private RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal requireExactR snapshot.sourceEvidence().canonicalTenantId(), snapshot.version().canonicalVersionId()); if (row == null + || !snapshot.version().id().equals(row.get("game_design_version_row_id", Long.class)) + || !Integer.toString(snapshot.version().versionNumber()) + .equals(row.get("version_number", String.class)) || !Boolean.TRUE.equals(row.get("sealed", Boolean.class)) || row.get("fixture_operation_id", UUID.class) == null || !Arrays.equals(request, row.get("fixture_request_bytes", byte[].class)) @@ -180,6 +232,26 @@ private RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal requireExactR throw new IllegalStateException( "Fixture policy seal differs from its exact original evidence"); } + for (String humanField : + java.util.List.of( + "source_commit_id", + "source_epoch", + "target_proof_json", + "operation_bytes", + "capture_bytes", + "terminal_evidence_bytes", + "release_content_bytes", + "published_release_bundle_ref", + "published_release_bundle_digest", + "publish_workflow_id", + "manifest_hash", + "publication_version_state_epoch", + "policy_count", + "policy_set_digest")) { + if (row.get(humanField) != null) { + throw new IllegalStateException("Fixture policy owner contains mixed Human evidence"); + } + } UUID operation = row.get("fixture_operation_id", UUID.class); if (!operation .toString() diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java index c8b36019b6..245e0b7961 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java @@ -530,6 +530,27 @@ public void afterCommit() { } private FixtureCapability loadFixtureCapability() { + return verifyFixtureConfiguration( + workloadNamespace, + fixtureRunId, + fixtureComposeProjectName, + fixtureCapabilityPath, + fixtureReceiptPath, + gameSessionLeafCertPath, + worldManagementLeafCertPath, + caCertPath); + } + + /** The producer and fixed read adapters share the exact immutable configuration verifier. */ + static FixtureCapability verifyFixtureConfiguration( + String workloadNamespace, + String fixtureRunId, + String fixtureComposeProjectName, + String fixtureCapabilityPath, + String fixtureReceiptPath, + String gameSessionLeafCertPath, + String worldManagementLeafCertPath, + String caCertPath) { if (!FIXTURE_NAMESPACE.equals(workloadNamespace) || !safeFixtureId(fixtureRunId) || !safeFixtureId(fixtureComposeProjectName) @@ -738,7 +759,7 @@ private void requireExistingReceipt(Path destination, byte[] expected) throws IO } } - private byte[] readBoundedImmutableFile(Path path, String fileDescription) { + private static byte[] readBoundedImmutableFile(Path path, String fileDescription) { return RunOwnedFixtureImmutableFileReader.readBoundedImmutableFile( path, MAX_FIXTURE_FILE_BYTES, @@ -746,7 +767,7 @@ private byte[] readBoundedImmutableFile(Path path, String fileDescription) { new IllegalStateException("Run-owned fixture " + fileDescription + " file is invalid")); } - private X509Certificate readCertificate(Path path) { + private static X509Certificate readCertificate(Path path) { try { byte[] bytes = readBoundedImmutableFile(path, "TLS certificate"); return (X509Certificate) @@ -758,7 +779,7 @@ private X509Certificate readCertificate(Path path) { } } - private void requireCertificatePins( + private static void requireCertificatePins( X509Certificate gameSessionCertificate, X509Certificate worldManagementCertificate, X509Certificate caCertificate, @@ -781,7 +802,7 @@ private void requireCertificatePins( "World Management"); } - private void requireRecipientCertificatePins( + private static void requireRecipientCertificatePins( X509Certificate recipientCertificate, X509Certificate caCertificate, String expectedLeafDigest, @@ -817,19 +838,19 @@ private void requireRecipientCertificatePins( } } - private String sha256(byte[] bytes) throws Exception { + private static String sha256(byte[] bytes) throws Exception { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); } - private boolean safeFixtureId(String value) { + private static boolean safeFixtureId(String value) { return value != null && value.matches("[a-z0-9][a-z0-9-]{0,127}"); } - private boolean absolutePath(String value) { + private static boolean absolutePath(String value) { return value != null && !value.isBlank() && Path.of(value).isAbsolute(); } - private boolean validCapabilityPath(String value) { + private static boolean validCapabilityPath(String value) { if (!absolutePath(value)) { return false; } @@ -838,7 +859,7 @@ private boolean validCapabilityPath(String value) { && "run-owned-initial-admission-capability.json".equals(fileName.toString()); } - private boolean validReceiptPath(String value) { + private static boolean validReceiptPath(String value) { if (!absolutePath(value)) { return false; } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldSourceReadGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldSourceReadGrpcService.java new file mode 100644 index 0000000000..e422e83cef --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldSourceReadGrpcService.java @@ -0,0 +1,92 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec; +import net.firedevops.firemud.gamedesign.data.RunOwnedFixtureOwnerReadAuthorization; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.v1.AuthoredWorldSourceReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.grpc.server.service.GrpcService; + +/** Fixed-fixture registration of the existing standalone source owner kernel. */ +@GrpcService +@ConditionalOnProperty( + name = "FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED", + havingValue = "true") +public final class RunOwnedFixtureAuthoredWorldSourceReadGrpcService + extends AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceImplBase { + private final RunOwnedFixtureOwnerReadAuthorization authorization; + private final AuthoredWorldSourceReadGrpcService kernel; + private final String namespace; + + public RunOwnedFixtureAuthoredWorldSourceReadGrpcService( + RunOwnedFixtureOwnerReadAuthorization authorization, + GameAuthoredWorldSourceRepository repository, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + this.authorization = authorization; + this.namespace = namespace; + this.kernel = new AuthoredWorldSourceReadGrpcService(repository, namespace); + } + + @Override + public void resolveAuthoredWorldSource( + ResolveAuthoredWorldSourceRequest request, + StreamObserver observer) { + try { + var receipt = authorization.authorizeSource(request); + var expected = AuthoredWorldSourceGrpcCodec.fromReadRequest(namespace, request); + kernel.resolveAuthoredWorldSource( + request, + new StreamObserver<>() { + private ResolveAuthoredWorldSourceResponse result; + + @Override + public void onNext(ResolveAuthoredWorldSourceResponse value) { + result = value; + } + + @Override + public void onError(Throwable error) { + observer.onError(error); + } + + @Override + public void onCompleted() { + try { + var source = AuthoredWorldSourceGrpcCodec.fromReadResponse(expected, result); + if (!source.equals(receipt.sourceEvidence())) { + throw new IllegalStateException( + "Committed source changed after fixture qualification"); + } + observer.onNext(result); + observer.onCompleted(); + } catch (RuntimeException invalid) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Exact committed fixture source unavailable") + .asRuntimeException()); + } + } + }); + } catch (SecurityException denied) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("Fixed World fixture read denied") + .asRuntimeException()); + } catch (IllegalArgumentException invalid) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Closed fixture source request required") + .asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Committed fixture authority unavailable") + .asRuntimeException()); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldVersionStateGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldVersionStateGrpcService.java new file mode 100644 index 0000000000..4330c28d52 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldVersionStateGrpcService.java @@ -0,0 +1,104 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateGrpcCodec; +import net.firedevops.firemud.gamedesign.data.RunOwnedFixtureOwnerReadAuthorization; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.v1.AuthoredWorldVersionStateServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateRequest; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateResponse; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.grpc.server.service.GrpcService; +import org.springframework.transaction.PlatformTransactionManager; + +/** Fixed-fixture registration of the existing standalone source-qualified Version kernel. */ +@GrpcService +@ConditionalOnProperty( + name = "FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED", + havingValue = "true") +public final class RunOwnedFixtureAuthoredWorldVersionStateGrpcService + extends AuthoredWorldVersionStateServiceGrpc.AuthoredWorldVersionStateServiceImplBase { + private final RunOwnedFixtureOwnerReadAuthorization authorization; + private final AuthoredWorldVersionStateGrpcService kernel; + + public RunOwnedFixtureAuthoredWorldVersionStateGrpcService( + RunOwnedFixtureOwnerReadAuthorization authorization, + PlatformTransactionManager transactions, + GameAuthoredWorldSourceRepository repository, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + this.authorization = authorization; + this.kernel = + new AuthoredWorldVersionStateGrpcService( + new AuthoredWorldVersionStateService(transactions, repository), namespace); + } + + @Override + public void getAuthoredWorldVersionState( + GetAuthoredWorldVersionStateRequest request, + StreamObserver observer) { + try { + var receipt = authorization.authorizeVersion(request); + var expected = AuthoredWorldVersionStateGrpcCodec.fromRequest(request); + kernel.getAuthoredWorldVersionState( + request, + new StreamObserver<>() { + private GetAuthoredWorldVersionStateResponse result; + + @Override + public void onNext(GetAuthoredWorldVersionStateResponse value) { + result = value; + } + + @Override + public void onError(Throwable error) { + observer.onError(error); + } + + @Override + public void onCompleted() { + try { + var evidence = AuthoredWorldVersionStateGrpcCodec.fromResponse(expected, result); + var launch = receipt.launchReadEvidence(); + if (!evidence.sourceEvidence().equals(receipt.sourceEvidence()) + || !evidence + .canonicalVersionId() + .equals( + UUID.fromString( + launch.publishedReleaseBundle().getCanonicalVersionId())) + || evidence.versionState() != launch.versionState().getVersionState() + || evidence.versionStateEpoch() + != launch.versionState().getVersionStateEpoch()) { + throw new IllegalStateException( + "Committed Version changed after fixture qualification"); + } + observer.onNext(result); + observer.onCompleted(); + } catch (RuntimeException invalid) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Exact committed fixture Version unavailable") + .asRuntimeException()); + } + } + }); + } catch (SecurityException denied) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("Fixed World fixture read denied") + .asRuntimeException()); + } catch (IllegalArgumentException invalid) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Closed fixture Version request required") + .asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Committed fixture authority unavailable") + .asRuntimeException()); + } + } +} diff --git a/services/game-design-service/src/main/resources/application-prod.yml b/services/game-design-service/src/main/resources/application-prod.yml index 5f2bc1c4f4..2c82a2710e 100644 --- a/services/game-design-service/src/main/resources/application-prod.yml +++ b/services/game-design-service/src/main/resources/application-prod.yml @@ -56,6 +56,8 @@ firemud: - gamedesign.v1.GameDesignService/ResolveLaunchDescriptor - gamedesign.v1.GameDesignService/GetLaunchDescriptor - gamedesign.v1.GameDesignService/GetCompleteLaunchBinding + - gamedesign.v1.AuthoredWorldSourceReadService/ResolveAuthoredWorldSource + - gamedesign.v1.AuthoredWorldVersionStateService/GetAuthoredWorldVersionState grpc: workload-namespace: ${FIREMUD_GRPC_WORKLOAD_NAMESPACE:} cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} diff --git a/services/game-design-service/src/main/resources/application.yml b/services/game-design-service/src/main/resources/application.yml index aba342b57e..7272e16f83 100644 --- a/services/game-design-service/src/main/resources/application.yml +++ b/services/game-design-service/src/main/resources/application.yml @@ -67,6 +67,8 @@ firemud: - gamedesign.v1.GameDesignService/ResolveLaunchDescriptor - gamedesign.v1.GameDesignService/GetLaunchDescriptor - gamedesign.v1.GameDesignService/GetCompleteLaunchBinding + - gamedesign.v1.AuthoredWorldSourceReadService/ResolveAuthoredWorldSource + - gamedesign.v1.AuthoredWorldVersionStateService/GetAuthoredWorldVersionState http: enabled: true role-requirement: PRIVILEGED diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java index c0066cc8a3..13d143ea04 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java @@ -6,7 +6,17 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doAnswer; +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.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; import java.io.IOException; +import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -23,12 +33,26 @@ import java.util.Optional; import java.util.Set; import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.BiConsumer; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +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.GrpcChannelFactory; +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.AuthoredWorldSourceClient; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; +import net.firedevops.firemud.gamedesign.data.RunOwnedFixtureOwnerReadAuthorization; import net.firedevops.firemud.gamedesign.data.TestDataSeeder; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; @@ -48,13 +72,27 @@ import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; import net.firedevops.firemud.gamedesign.service.VersionService; import net.firedevops.firemud.gamedesign.service.impl.GameDesignLaunchReadProjectionMapper; +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.gamedesign.v1.LaunchDescriptor; import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; +import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionFixtureCoordinator; +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.RunOwnedWorldFixedPresetResources; +import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceProvider; +import net.firedevops.firemud.worldmanagement.service.impl.WorldInstanceActivationServiceImpl; +import net.firedevops.firemud.worldmanagement.service.impl.WorldLifecycleCommandServiceImpl; +import net.firedevops.firemud.worldmanagement.service.impl.WorldManagementGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationRepository; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.Field; @@ -127,6 +165,14 @@ class TestDataSeederIntegrationTest { static PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Container + static PostgreSQLContainer composedGameSessionPostgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static PostgreSQLContainer composedWorldPostgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + @DynamicPropertySource static void configure(DynamicPropertyRegistry registry) { PostgresBackedServiceTestSupport.registerPostgresService( @@ -134,6 +180,17 @@ static void configure(DynamicPropertyRegistry registry) { } @Autowired private TestDataSeeder seeder; + + @Autowired + private net.firedevops.firemud.gamedesign.service.impl.GameDesignGrpcService + gameDesignGrpcService; + + @MockitoSpyBean + private net.firedevops.firemud.gamedesign.data.RunOwnedFixtureLaunchReadback fixtureReadback; + + @MockitoSpyBean + private net.firedevops.firemud.gamedesign.data.RunOwnedFixturePolicyProducer fixturePolicy; + @Autowired private Flyway flyway; @MockitoSpyBean private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; @Autowired private GameRepository gameRepository; @@ -161,6 +218,1245 @@ void resetDisposableServiceSchema() { seeder.run(new DefaultApplicationArguments(new String[] {})); } + @Test + void fixedWorldReadsQualifyRealPreexistingOwnersWithoutRewritingOrResolving( + @TempDir Path testDirectory) throws Exception { + Fixture fixture = prepareFixture(testDirectory); + configureSeeder(fixture); + seeder.run(new DefaultApplicationArguments(new String[] {})); + var capability = + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .parseCapability(Files.readAllBytes(fixture.capabilityPath())); + var receipt = + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .parseSourceReceipt(Files.readAllBytes(fixture.receiptPath()), capability); + var authorization = + new net.firedevops.firemud.gamedesign.data.RunOwnedFixtureOwnerReadAuthorization( + fixtureReadback, + fixturePolicy, + NAMESPACE, + fixture.runId(), + fixture.composeProjectName(), + fixture.capabilityPath().toString(), + fixture.receiptPath().toString(), + fixture.gameSessionCertificatePath().toString(), + fixture.worldManagementCertificatePath().toString(), + fixture.caCertificatePath().toString()); + var source = receipt.sourceEvidence(); + var sourceRequest = + net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec.toReadRequest( + new net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, + UUID.randomUUID(), + source.operationId(), + source.canonicalTenantId(), + source.worldSlug())); + var versionRequest = + net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setReadRequestId(UUID.randomUUID().toString()) + .setCanonicalTenantId(source.canonicalTenantId().toString()) + .setWorldSlug(source.worldSlug()) + .setSourceOperationId(source.operationId().toString()) + .setExpectedSourceEvidenceDigest(source.evidenceDigest()) + .setVersionId(receipt.launchReadEvidence().versionState().getVersionId()) + .build(); + Map before = fixedReadOwnerRows(); + byte[] receiptBefore = Files.readAllBytes(fixture.receiptPath()); + X509Certificate actualMountedWorldLeaf; + try (var input = Files.newInputStream(fixture.worldManagementCertificatePath())) { + actualMountedWorldLeaf = + (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + // Peer context is controlled here; immutable PKI, producer and PostgreSQL owners are real. + var peerContext = + io.grpc.Context.current() + .withValue( + net.firedevops.firemud.common.grpc.GrpcPeerIdentity.CONTEXT_KEY, + net.firedevops.firemud.common.grpc.GrpcPeerIdentity.parseUri( + WORLD_MANAGEMENT_URI_SAN) + .orElseThrow()) + .withValue( + net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence.CONTEXT_KEY, + net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence.fromCertificate( + actualMountedWorldLeaf) + .orElseThrow()); + org.mockito.Mockito.clearInvocations(launchDescriptorService); + peerContext.run( + () -> { + assertThat(authorization.authorizeSource(sourceRequest)).isEqualTo(receipt); + assertThat(authorization.authorizeVersion(versionRequest)).isEqualTo(receipt); + var sourceOutput = + new FixedReadObserver< + net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse>(); + new net.firedevops.firemud.gamedesign.service.impl + .RunOwnedFixtureAuthoredWorldSourceReadGrpcService( + authorization, authoredWorldSourceRepository, NAMESPACE) + .resolveAuthoredWorldSource(sourceRequest, sourceOutput); + assertThat(sourceOutput.failure).isNull(); + assertThat(sourceOutput.completed).isTrue(); + assertThat( + net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec + .fromReadResponse( + net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec + .fromReadRequest(NAMESPACE, sourceRequest), + sourceOutput.value)) + .isEqualTo(source); + var versionOutput = + new FixedReadObserver< + net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateResponse>(); + new net.firedevops.firemud.gamedesign.service.impl + .RunOwnedFixtureAuthoredWorldVersionStateGrpcService( + authorization, transactionManager, authoredWorldSourceRepository, NAMESPACE) + .getAuthoredWorldVersionState(versionRequest, versionOutput); + assertThat(versionOutput.failure).isNull(); + assertThat(versionOutput.completed).isTrue(); + var actual = + net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateGrpcCodec + .fromResponse( + net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateGrpcCodec + .fromRequest(versionRequest), + versionOutput.value); + assertThat(actual.sourceEvidence()).isEqualTo(source); + assertThat(actual.versionStateEpoch()) + .isEqualTo(receipt.launchReadEvidence().versionState().getVersionStateEpoch()); + }); + org.mockito.Mockito.verify(launchDescriptorService, org.mockito.Mockito.never()) + .resolveLaunchDescriptor(any()); + assertThat(fixedReadOwnerRows()).isEqualTo(before); + assertThat(Files.readAllBytes(fixture.receiptPath())).containsExactly(receiptBefore); + org.mockito.Mockito.clearInvocations(authoredWorldSourceRepository, launchDescriptorService); + peerContext.run( + () -> { + assertThatThrownBy( + () -> + authorization.authorizeSource( + sourceRequest.toBuilder() + .setOperationId(UUID.randomUUID().toString()) + .build())) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + authorization.authorizeSource( + sourceRequest.toBuilder() + .setCanonicalTenantId(UUID.randomUUID().toString()) + .build())) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + authorization.authorizeSource( + sourceRequest.toBuilder().setWorldSlug("different-world").build())) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + authorization.authorizeVersion( + versionRequest.toBuilder().setTargetNamespace("other").build())) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + authorization.authorizeVersion( + versionRequest.toBuilder() + .setVersionId(versionRequest.getVersionId() + 1) + .build())) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + authorization.authorizeVersion( + versionRequest.toBuilder() + .setExpectedSourceEvidenceDigest("sha256:" + "f".repeat(64)) + .build())) + .isInstanceOf(SecurityException.class); + }); + org.mockito.Mockito.verifyNoInteractions( + authoredWorldSourceRepository, launchDescriptorService); + assertThat(fixedReadOwnerRows()).isEqualTo(before); + } + + @Test + void fixedWorldClientsReadActualProducerOwnersOverMutualTlsWithoutOwnerWrites( + @TempDir Path testDirectory) throws Exception { + Fixture fixture = prepareFixture(testDirectory); + configureSeeder(fixture); + seeder.run(new DefaultApplicationArguments(new String[] {})); + var capability = + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .parseCapability(Files.readAllBytes(fixture.capabilityPath())); + var receipt = + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .parseSourceReceipt(Files.readAllBytes(fixture.receiptPath()), capability); + var authorization = + new RunOwnedFixtureOwnerReadAuthorization( + fixtureReadback, + fixturePolicy, + NAMESPACE, + fixture.runId(), + fixture.composeProjectName(), + fixture.capabilityPath().toString(), + fixture.receiptPath().toString(), + fixture.gameSessionCertificatePath().toString(), + fixture.worldManagementCertificatePath().toString(), + fixture.caCertificatePath().toString()); + var source = receipt.sourceEvidence(); + var sourceRequest = + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, + UUID.randomUUID(), + source.operationId(), + source.canonicalTenantId(), + source.worldSlug()); + var versionRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + receipt.launchReadEvidence().versionState().getVersionId()); + var serverLeaf = + issueFixedReadLeaf( + fixture, "game-design-server", "spiffe://firemud/ns/dev/sa/game-design-service", true); + var otherWorldLeaf = + issueFixedReadLeaf(fixture, "different-world-client", WORLD_MANAGEMENT_URI_SAN, false); + var auth = + new AuthTokenInterceptor( + new JwtUtil("testsecretkeytestsecretkeytest1234", 60_000L), + Set.of( + AuthoredWorldSourceReadServiceGrpc.getResolveAuthoredWorldSourceMethod() + .getFullMethodName(), + AuthoredWorldVersionStateServiceGrpc.getGetAuthoredWorldVersionStateMethod() + .getFullMethodName())); + Map originalRows = fixedReadOwnerRows(); + byte[] originalReceipt = Files.readAllBytes(fixture.receiptPath()); + // Actual handlers/interceptors on a loopback socket; Spring registration and Compose are + // separate proofs. + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverLeaf.certificate().toFile(), serverLeaf.privateKey().toFile())) + .trustManager(fixture.caCertificatePath().toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + new RunOwnedFixtureAuthoredWorldSourceReadGrpcService( + authorization, authoredWorldSourceRepository, NAMESPACE), + new GrpcPeerIdentityInterceptor(), + auth)) + .addService( + ServerInterceptors.intercept( + new RunOwnedFixtureAuthoredWorldVersionStateGrpcService( + authorization, + transactionManager, + authoredWorldSourceRepository, + NAMESPACE), + new GrpcPeerIdentityInterceptor(), + auth)) + .build() + .start(); + try { + org.mockito.Mockito.clearInvocations(launchDescriptorService, fixturePolicy); + withFixedReadClients( + server, + fixture, + fixture.worldManagementCertificatePath(), + fixture.worldManagementCertificatePath().resolveSibling("world-management.key"), + (sourceClient, versionClient) -> { + assertThat(sourceClient.read(sourceRequest)).isEqualTo(source); + var actual = versionClient.read(versionRequest); + assertThat(actual.request()).isEqualTo(versionRequest); + assertThat(actual.sourceEvidence()).isEqualTo(source); + assertThat(actual.canonicalVersionId()) + .isEqualTo( + UUID.fromString( + receipt + .launchReadEvidence() + .publishedReleaseBundle() + .getCanonicalVersionId())); + assertThat(actual.versionState()) + .isEqualTo(receipt.launchReadEvidence().versionState().getVersionState()); + assertThat(actual.versionStateEpoch()) + .isEqualTo(receipt.launchReadEvidence().versionState().getVersionStateEpoch()); + }); + org.mockito.Mockito.verify(launchDescriptorService, org.mockito.Mockito.never()) + .resolveLaunchDescriptor(any()); + assertThat(org.mockito.Mockito.mockingDetails(fixturePolicy).getInvocations()) + .extracting(invocation -> invocation.getMethod().getName()) + .contains("readExisting") + .doesNotContain("sealAndRead"); + assertThat(fixedReadOwnerRows()).isEqualTo(originalRows); + assertThat(Files.readAllBytes(fixture.receiptPath())).containsExactly(originalReceipt); + org.mockito.Mockito.clearInvocations( + authoredWorldSourceRepository, launchDescriptorService, fixtureReadback, fixturePolicy); + for (var leaf : + java.util.List.of( + otherWorldLeaf, + new FixedReadLeaf( + fixture.gameSessionCertificatePath(), + fixture.gameSessionCertificatePath().resolveSibling("game-session.key")))) { + withFixedReadClients( + server, + fixture, + leaf.certificate(), + leaf.privateKey(), + (sourceClient, versionClient) -> { + assertSocketReadDenied(() -> sourceClient.read(sourceRequest)); + assertSocketReadDenied(() -> versionClient.read(versionRequest)); + }); + } + withFixedReadClients( + server, + fixture, + fixture.worldManagementCertificatePath(), + fixture.worldManagementCertificatePath().resolveSibling("world-management.key"), + (sourceClient, versionClient) -> { + assertSocketReadDenied( + () -> + sourceClient.read( + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, + UUID.randomUUID(), + UUID.randomUUID(), + source.canonicalTenantId(), + source.worldSlug()))); + assertSocketReadDenied( + () -> + sourceClient.read( + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, + UUID.randomUUID(), + source.operationId(), + UUID.randomUUID(), + source.worldSlug()))); + assertSocketReadDenied( + () -> + sourceClient.read( + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, + UUID.randomUUID(), + source.operationId(), + source.canonicalTenantId(), + "different-world"))); + assertSocketReadDenied( + () -> + versionClient.read( + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + versionRequest.versionId() + 1))); + assertSocketReadDenied( + () -> + versionClient.read( + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + "sha256:" + "f".repeat(64), + versionRequest.versionId()))); + }); + org.mockito.Mockito.verifyNoInteractions( + authoredWorldSourceRepository, launchDescriptorService, fixtureReadback, fixturePolicy); + assertThat(fixedReadOwnerRows()).isEqualTo(originalRows); + assertThat(Files.readAllBytes(fixture.receiptPath())).containsExactly(originalReceipt); + // No physical missing-header case: immutable producer seal precedes receipt publication. + // Controlled missing-policy denial is covered separately without forging/deleting owner + // evidence. + } finally { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + + private static void assertSocketReadDenied(Runnable read) { + assertThatThrownBy(read::run) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.PERMISSION_DENIED)); + } + + private void withFixedReadClients( + Server server, + Fixture fixture, + Path certificate, + Path privateKey, + BiConsumer reads) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("127.0.0.1:" + server.getPort()); + var tls = new CommonGrpcClientProperties(); + tls.setCertChain(certificate.toString()); + tls.setPrivateKey(privateKey.toString()); + tls.setCaCert(fixture.caCertificatePath().toString()); + var channels = new CopyOnWriteArrayList(); + var factory = + 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; + } + }; + try (var sourceClient = new AuthoredWorldSourceClient(endpoints, tls, factory, NAMESPACE); + var versionClient = + new AuthoredWorldVersionStateClient(endpoints, tls, factory, NAMESPACE)) { + sourceClient.init(); + versionClient.init(); + reads.accept(sourceClient, versionClient); + } finally { + for (ManagedChannel channel : channels) { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + } + + private FixedReadLeaf issueFixedReadLeaf(Fixture fixture, String name, String uri, boolean server) + throws Exception { + Path directory = java.util.Objects.requireNonNull(fixture.caCertificatePath().getParent()); + Path key = directory.resolve(name + ".key"); + Path csr = directory.resolve(name + ".csr"); + Path certificate = directory.resolve(name + ".crt"); + Path extensions = directory.resolve(name + ".ext"); + runOpenSsl( + "req", + "-new", + "-newkey", + "rsa:2048", + "-nodes", + "-sha256", + "-keyout", + key.toString(), + "-out", + csr.toString(), + "-subj", + "/CN=" + name); + Files.writeString( + extensions, + "basicConstraints=critical,CA:FALSE\n" + + "keyUsage=critical,digitalSignature,keyEncipherment\n" + + "extendedKeyUsage=" + + (server ? "serverAuth" : "clientAuth") + + "\n" + + "subjectAltName=URI:" + + uri + + (server + ? ",DNS:game-design-service,DNS:game-design-service.dev,DNS:game-design-service.dev.svc,DNS:game-design-service.dev.svc.cluster.local,DNS:localhost,IP:127.0.0.1" + : ",DNS:world-management-service") + + "\n"); + runOpenSsl( + "x509", + "-req", + "-in", + csr.toString(), + "-CA", + fixture.caCertificatePath().toString(), + "-CAkey", + directory.resolve("ca.key").toString(), + "-CAcreateserial", + "-out", + certificate.toString(), + "-days", + "2", + "-sha256", + "-extfile", + extensions.toString()); + Files.setPosixFilePermissions( + certificate, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + awaitFixtureCertificatesValid(certificate); + return new FixedReadLeaf(certificate, key); + } + + private record FixedReadLeaf(Path certificate, Path privateKey) {} + + @Test + void actualProducerStartingAndPreparingOwnersComposeOverThreeMutualTlsSockets( + @TempDir Path testDirectory) throws Exception { + 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(75L); + 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 coordinator = + new RunOwnedInitialAdmissionFixtureCoordinator( + true, + fixture.capabilityPath().toString(), + fixture.receiptPath().toString(), + fixture.runId(), + fixture.composeProjectName(), + gsTls, + beanFactory.getBeanProvider(GameSessionCanonicalInstanceLaunchRepository.class), + NAMESPACE); + // The production loader verifies real producer files and original mounted pins; no test-only GS + // carrier is used. + var gsEvidence = coordinator.loadFixedVerifiedEvidence(); + var starting = launchOwner.createVerifiedFixtureStartingLaunch(gsEvidence); + 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(coordinator, 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; + RunOwnedWorldLaunchEvidenceProvider 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 RunOwnedWorldLaunchEvidenceProvider( + 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 worldRepository = + new net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository( + worldDatabase.dsl()); + var worldHandler = actualWorldFixtureHandler(commands, provider, worldRepository, registry); + Server worldServer = + fixedProductionServer( + fixture, + new FixedReadLeaf( + fixture.worldManagementCertificatePath(), + fixture.worldManagementCertificatePath().resolveSibling("world-management.key")), + Set.of( + net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc + .getPrepareWorldInstanceMethod() + .getFullMethodName()), + worldHandler); + servers.add(worldServer); + var descriptor = receipt.launchReadEvidence().launchDescriptor(); + var bundle = receipt.launchReadEvidence().publishedReleaseBundle(); + var request = + net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceRequest.newBuilder() + .setTenantId(Long.toString(starting.catalog().association().gameSessionTenantId())) + .setGameInstanceId(Long.toString(starting.gameInstanceId())) + .setGameTemplateId(Long.toString(capability.gameTemplateId())) + .setControlPlaneRequestId(capability.operationId()) + .setLaunchDescriptorId(descriptor.getLaunchDescriptorId()) + .setVersionId(Long.toString(bundle.getVersionId())) + .setRuntimeFlagsJson(descriptor.getRuntimeFlagsJson()) + .setGenerationConfigRevision(bundle.getGenerationConfigRevision()) + .setReleaseBundleId(Long.toString(bundle.getId())) + .setPublishedReleaseBundleRef(bundle.getPublishedReleaseBundleRef()) + .setVersionStateEpoch( + receipt.launchReadEvidence().versionState().getVersionStateEpoch()) + .build(); + var originalGdsRows = fixedReadOwnerRows(); + var originalGsRows = allComposedOwnerRows(gsDatabase.dsl()); + ManagedChannel worldChannel = + factory.buildChannel( + "127.0.0.1:" + worldServer.getPort(), worldServer.getPort(), gsTls, false); + var stub = + net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc.newBlockingStub( + worldChannel) + .withCallCredentials( + new net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials( + WORLD_MANAGEMENT_URI_SAN)) + .withInterceptors( + new net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor( + WORLD_MANAGEMENT_URI_SAN)) + .withDeadlineAfter(30, TimeUnit.SECONDS); + var prepared = stub.prepareWorldInstance(request); + assertThat(prepared.hasError()).as("actual World prepare response").isFalse(); + assertThat(prepared.getWorldInstance().getStatus()) + .isEqualTo( + net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus + .WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING); + assertThat(prepared.getWorldInstance().getLifecycleEpoch()).isEqualTo(1L); + 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(stub.prepareWorldInstance(request)).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); + // Selector denial is an actual production response; no remote positive response is + // controlled. + assertThat( + stub.prepareWorldInstance( + request.toBuilder() + .setGameInstanceId(Long.toString(starting.gameInstanceId() + 1)) + .build()) + .hasError()) + .isTrue(); + 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 RunOwnedWorldLaunchEvidenceProvider( + 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 restartedHandler = + actualWorldFixtureHandler( + commands, + provider, + new net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository( + worldDatabase.dsl()), + registry); + Server restartedServer = + fixedProductionServer( + fixture, + new FixedReadLeaf( + fixture.worldManagementCertificatePath(), + fixture.worldManagementCertificatePath().resolveSibling("world-management.key")), + Set.of( + net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc + .getPrepareWorldInstanceMethod() + .getFullMethodName()), + restartedHandler); + servers.add(restartedServer); + ManagedChannel restartedChannel = + factory.buildChannel( + "127.0.0.1:" + restartedServer.getPort(), restartedServer.getPort(), gsTls, false); + assertThat(actualWorldPrepareStub(restartedChannel).prepareWorldInstance(request)) + .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(3)) + .getRunOwnedFixtureLaunchAssociation(reads.capture(), any()); + assertThat(reads.getAllValues()) + .extracting(value -> value.getReadRequestId()) + .doesNotHaveDuplicates(); + org.mockito.Mockito.clearInvocations( + gsHandler, launchDescriptorService, fixtureReadback, fixturePolicy); + var otherGsLeaf = + issueFixedReadLeaf(fixture, "different-game-session-client", SESSION_URI_SAN, false); + for (var wrongLeaf : + java.util.List.of( + otherGsLeaf, + new FixedReadLeaf( + fixture.worldManagementCertificatePath(), + fixture + .worldManagementCertificatePath() + .resolveSibling("world-management.key")))) { + var wrongTls = fixedReadTls(fixture, wrongLeaf.certificate(), wrongLeaf.privateKey()); + var wrongChannel = + factory.buildChannel( + "127.0.0.1:" + restartedServer.getPort(), + restartedServer.getPort(), + wrongTls, + false); + assertThat(actualWorldPrepareStub(wrongChannel).prepareWorldInstance(request).hasError()) + .isTrue(); + } + 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 WorldManagementGrpcService actualWorldFixtureHandler( + WorldLifecycleCommandServiceImpl commands, + RunOwnedWorldLaunchEvidenceProvider provider, + net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository repository, + io.micrometer.core.instrument.MeterRegistry registry) { + var activation = + new WorldInstanceActivationServiceImpl(commands, Optional.empty(), provider, repository); + return new WorldManagementGrpcService( + org.mockito.Mockito.mock(net.firedevops.firemud.worldmanagement.service.PingService.class), + org.mockito.Mockito.mock(net.firedevops.firemud.worldmanagement.service.RoomService.class), + activation, + org.mockito.Mockito.mock( + net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.worldmanagement.service.WorldDesignMutationService.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.worldmanagement.service.WorldUpgradeValidationService.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.common.security.GameplaySessionAttestationService.class), + registry, + objectMapper, + NAMESPACE); + } + + private net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc + .WorldManagementServiceBlockingStub + actualWorldPrepareStub(ManagedChannel channel) { + return net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc.newBlockingStub( + channel) + .withCallCredentials( + new net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials( + WORLD_MANAGEMENT_URI_SAN)) + .withInterceptors( + new net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor( + WORLD_MANAGEMENT_URI_SAN)) + .withDeadlineAfter(30, TimeUnit.SECONDS); + } + + 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 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.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() + .migrate(); + return new ComposedOwnerDatabase( + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES), + new DataSourceTransactionManager(dataSource)); + } + + private record ComposedOwnerDatabase(DSLContext dsl, PlatformTransactionManager transactions) {} + + 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, + RunOwnedWorldLaunchEvidenceProvider 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(), + 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; + } + + private Map fixedReadOwnerRows() { + Map rows = new LinkedHashMap<>(); + for (String table : + Set.of( + "game_tenant_creation_operations", + "game_design_authored_world_source_operations", + "game_design_authored_world_source_deliveries", + "game", + "game_templates", + "version", + "version_asset_artifact", + "published_release_bundle", + "launch_descriptor", + "game_design_published_realm_policy_set", + "game_design_realm_policy_capture", + "game_design_publication_operation", + "game_design_published_realm_policy")) { + rows.put( + table, + dsl.fetch( + "SELECT row_to_json(t)::text AS bytes, xmin::text AS row_version FROM " + + table + + " t ORDER BY row_to_json(t)::text") + .formatJSON()); + } + return rows; + } + + private static final class FixedReadObserver implements io.grpc.stub.StreamObserver { + private T value; + private Status.Code failure; + private boolean completed; + + @Override + public void onNext(T response) { + value = response; + } + + @Override + public void onError(Throwable error) { + failure = Status.fromThrowable(error).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } + @Test void fixtureRefusesExistingUnownedDemoInsteadOfBackfillingCreation(@TempDir Path testDirectory) throws Exception { @@ -866,13 +2162,13 @@ private Fixture prepareFixture(Path testDirectory) throws Exception { sessionExtensions, "basicConstraints=critical,CA:FALSE\n" + "keyUsage=critical,digitalSignature,keyEncipherment\n" - + "extendedKeyUsage=clientAuth\n" + + "extendedKeyUsage=clientAuth,serverAuth\n" + "subjectAltName=URI:" + SESSION_URI_SAN + ",DNS:game-session-service" + ",DNS:game-session-service.dev" + ",DNS:game-session-service.dev.svc" - + ",DNS:game-session-service.dev.svc.cluster.local" + + ",DNS:game-session-service.dev.svc.cluster.local,DNS:localhost,IP:127.0.0.1" + "\n"); runOpenSsl( "x509", @@ -908,13 +2204,13 @@ private Fixture prepareFixture(Path testDirectory) throws Exception { worldManagementExtensions, "basicConstraints=critical,CA:FALSE\n" + "keyUsage=critical,digitalSignature,keyEncipherment\n" - + "extendedKeyUsage=clientAuth\n" + + "extendedKeyUsage=clientAuth,serverAuth\n" + "subjectAltName=URI:" + WORLD_MANAGEMENT_URI_SAN + ",DNS:world-management-service" + ",DNS:world-management-service.dev" + ",DNS:world-management-service.dev.svc" - + ",DNS:world-management-service.dev.svc.cluster.local" + + ",DNS:world-management-service.dev.svc.cluster.local,DNS:localhost,IP:127.0.0.1" + "\n"); runOpenSsl( "x509", @@ -1458,7 +2754,9 @@ void migrate(String target) { .schemas(schema) .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration"); + .locations( + "filesystem:" + + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()); if (target != null) configuration.target(target); configuration.load().migrate(); } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java index b6090e4809..d8d340f0ff 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java @@ -962,7 +962,11 @@ private static Fixture fixture(boolean branding) { .schemas(schema) .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") + .locations( + "filesystem:" + + java.nio.file.Path.of("src/main/resources/db/migration") + .toAbsolutePath() + .normalize()) .table("flyway_schema_history_game_design_service") .load() .migrate(); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java index 7d9706c214..52ea0b005b 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java @@ -1032,7 +1032,11 @@ private static Fixture freshFixture() { .schemas(schema) .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") + .locations( + "filesystem:" + + java.nio.file.Path.of("src/main/resources/db/migration") + .toAbsolutePath() + .normalize()) .table("flyway_schema_history_game_design_service") .load() .migrate(); @@ -1206,7 +1210,11 @@ private static void migrate(DriverManagerDataSource dataSource, String schema, S .schemas(schema) .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") + .locations( + "filesystem:" + + java.nio.file.Path.of("src/main/resources/db/migration") + .toAbsolutePath() + .normalize()) .table("flyway_schema_history_game_design_service") .target(target) .load() diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java index e3f73cbc8f..c8f2599079 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java @@ -46,7 +46,6 @@ import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -168,16 +167,21 @@ void actualDefaultLocationsFreshBootstrapAppliesFullCombinedHistoryAndEnabledGua void actualReceivingParentIncludingSagaUpgradePreservesHistoryAndAppliesStorageTail( @TempDir Path parentMigrations) throws Exception { var fixture = fixture(true); - var resources = - new PathMatchingResourcePatternResolver().getResources("classpath*:db/migration/**/*.sql"); int copied = 0; - for (var resource : resources) { - String filename = java.util.Objects.requireNonNull(resource.getFilename()); - if (!PARENT_MIGRATION_SCRIPTS.contains(filename)) continue; - try (var input = resource.getInputStream()) { - Files.copy(input, parentMigrations.resolve(filename)); + for (Path directory : + List.of( + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(), + Path.of("../common-saga/src/main/resources/db/migration/saga") + .toAbsolutePath() + .normalize())) { + try (var migrations = Files.list(directory)) { + for (Path migration : migrations.filter(Files::isRegularFile).sorted().toList()) { + String filename = java.util.Objects.requireNonNull(migration.getFileName()).toString(); + if (!PARENT_MIGRATION_SCRIPTS.contains(filename)) continue; + Files.copy(migration, parentMigrations.resolve(filename)); + copied++; + } } - copied++; } assertThat(copied).isEqualTo(62); flyway(fixture.source(), fixture.schema(), null, "filesystem:" + parentMigrations).migrate(); @@ -944,7 +948,15 @@ private String reviewedBaseRow(Fixture fixture, DraftCommitBinding binding) { } private Flyway flyway(DriverManagerDataSource source, String schema, String target) { - return flyway(source, schema, target, "classpath:db/migration", "classpath:db/migration/saga"); + return flyway( + source, + schema, + target, + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(), + "filesystem:" + + Path.of("../common-saga/src/main/resources/db/migration/saga") + .toAbsolutePath() + .normalize()); } private Flyway flyway( diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java index e5f6313bcb..cf5dcca579 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java @@ -1433,7 +1433,9 @@ private Fixture fixture( .schemas(schema) .defaultSchema(schema) .placeholders(java.util.Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") + .locations( + "filesystem:" + + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) .table("flyway_schema_history_game_design_service"); if (migrationTarget != null) { flyway.target(migrationTarget); @@ -1579,7 +1581,9 @@ private Fixture fixture( .schemas(schema) .defaultSchema(schema) .placeholders(java.util.Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") + .locations( + "filesystem:" + + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) .table("flyway_schema_history_game_design_service") .load() .migrate()); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java index 22e514dc6b..6a6ddd9a12 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java @@ -550,7 +550,11 @@ private static void migrate( .schemas(schema) .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") + .locations( + "filesystem:" + + java.nio.file.Path.of("src/main/resources/db/migration") + .toAbsolutePath() + .normalize()) .table("flyway_schema_history_game_design_service"); if (migrationTarget != null) configuration.target(migrationTarget); configuration.load().migrate(); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java index 761f4b42df..8e9a89e7b9 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java @@ -545,7 +545,11 @@ private void migrate(DriverManagerDataSource dataSource, String schema, Migratio .defaultSchema(schema) .table(FLYWAY_TABLE) .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration"); + .locations( + "filesystem:" + + java.nio.file.Path.of("src/main/resources/db/migration") + .toAbsolutePath() + .normalize()); if (target != null) { configuration.target(target); } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java index ae59cafd2b..086d6446cc 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java @@ -109,7 +109,11 @@ private Fixture fixture() { .defaultSchema(schema) .table("flyway_schema_history_game_design_service") .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") + .locations( + "filesystem:" + + java.nio.file.Path.of("src/main/resources/db/migration") + .toAbsolutePath() + .normalize()) .load() .migrate(); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java index 278907d248..20f4480856 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java @@ -207,7 +207,11 @@ private void migrate(DriverManagerDataSource dataSource, String schema, Migratio .defaultSchema(schema) .table(FLYWAY_TABLE) .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration"); + .locations( + "filesystem:" + + java.nio.file.Path.of("src/main/resources/db/migration") + .toAbsolutePath() + .normalize()); if (target != null) { configuration.target(target); } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java index 7bf87d3332..437019f04c 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java @@ -601,7 +601,11 @@ private Fixture fixture(MigrationVersion target, byte[] sourceBytes) { .defaultSchema(schema) .table("flyway_schema_history_game_design_service") .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration"); + .locations( + "filesystem:" + + java.nio.file.Path.of("src/main/resources/db/migration") + .toAbsolutePath() + .normalize()); if (target != null) { configuration.target(target); } @@ -793,7 +797,11 @@ private static void migrateToLatest(Fixture fixture) { .defaultSchema(fixture.schema) .table("flyway_schema_history_game_design_service") .placeholders(Map.of("serviceSchema", fixture.schema)) - .locations("classpath:db/migration") + .locations( + "filesystem:" + + java.nio.file.Path.of("src/main/resources/db/migration") + .toAbsolutePath() + .normalize()) .load() .migrate(); } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java index 8a8b966cab..1a91814878 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java @@ -1000,7 +1000,11 @@ private void migrate(DriverManagerDataSource dataSource, String schema, Migratio .defaultSchema(schema) .table(FLYWAY_TABLE) .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration"); + .locations( + "filesystem:" + + java.nio.file.Path.of("src/main/resources/db/migration") + .toAbsolutePath() + .normalize()); if (target != null) { configuration.target(target); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java index 546d3fc31e..2486a381ff 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java @@ -97,6 +97,8 @@ private static void assertConfiguredGrpcMethods(String fileName) throws IOExcept .getFullMethodName(), "gamedesign.v1.GameDesignService/ResolveLaunchDescriptor", "gamedesign.v1.GameDesignService/GetLaunchDescriptor", - "gamedesign.v1.GameDesignService/GetCompleteLaunchBinding")); + "gamedesign.v1.GameDesignService/GetCompleteLaunchBinding", + "gamedesign.v1.AuthoredWorldSourceReadService/ResolveAuthoredWorldSource", + "gamedesign.v1.AuthoredWorldVersionStateService/GetAuthoredWorldVersionState")); } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerReadAuthorizationTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerReadAuthorizationTest.java new file mode 100644 index 0000000000..e1de4bc5c7 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerReadAuthorizationTest.java @@ -0,0 +1,208 @@ +package net.firedevops.firemud.gamedesign.data; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.security.cert.X509Certificate; +import java.util.List; +import java.util.Map; +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.gamedesign.v1.GetAuthoredWorldVersionStateRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; +import org.junit.jupiter.api.Test; + +/** Controlled configuration/peer doubles; committed producer/storage proof is native. */ +class RunOwnedFixtureOwnerReadAuthorizationTest { + @Test + void missingFixedConfigurationFailsClosedWithoutOwnerAccess() { + var readback = mock(RunOwnedFixtureLaunchReadback.class); + var policy = mock(RunOwnedFixturePolicyProducer.class); + assertThatThrownBy( + () -> + new RunOwnedFixtureOwnerReadAuthorization( + readback, policy, "dev", "", "", "", "", "", "", "")) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(readback, policy); + } + + @Test + void callerMissingPeerWrongNamespaceServiceAndLeafDenyBeforeMalformedSelector() throws Exception { + var readback = mock(RunOwnedFixtureLaunchReadback.class); + var policy = mock(RunOwnedFixturePolicyProducer.class); + var trusted = mock(TestDataSeeder.FixtureCapability.class); + when(trusted.worldManagementLeafSha256()).thenReturn("a".repeat(64)); + try (var configuration = mockStatic(TestDataSeeder.class)) { + configuration + .when( + () -> + TestDataSeeder.verifyFixtureConfiguration( + anyString(), + anyString(), + anyString(), + anyString(), + anyString(), + anyString(), + anyString(), + anyString())) + .thenReturn(trusted); + var authorization = + new RunOwnedFixtureOwnerReadAuthorization( + readback, + policy, + "dev", + "controlled-run", + "controlled-project", + "/controlled-capability", + "/controlled-receipt", + "/controlled-gs", + "/controlled-world", + "/controlled-ca"); + assertBothDeny(authorization); + SessionContext.setContext("controlled-account", List.of("player"), Map.of()); + try { + assertBothDeny(authorization); + } finally { + SessionContext.clear(); + } + X509Certificate controlledLeaf = mock(X509Certificate.class); + when(controlledLeaf.getEncoded()).thenReturn(new byte[] {1, 2, 3}); + var certificate = GrpcPeerCertificateEvidence.fromCertificate(controlledLeaf).orElseThrow(); + for (String uri : + List.of( + "spiffe://firemud/ns/dev/sa/game-session-service", + "spiffe://firemud/ns/other/sa/world-management-service", + "spiffe://firemud/ns/dev/sa/world-management-service")) { + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(uri).orElseThrow()) + .withValue(GrpcPeerCertificateEvidence.CONTEXT_KEY, certificate) + .run(() -> assertBothDeny(authorization)); + } + verifyNoInteractions(readback, policy); + } + } + + @Test + void rawReceiptAndQualifiedLaunchStillRequirePreexistingPolicyWithoutSealing() throws Exception { + var readback = mock(RunOwnedFixtureLaunchReadback.class); + var policy = mock(RunOwnedFixturePolicyProducer.class); + var trusted = mock(TestDataSeeder.FixtureCapability.class); + var capability = + mock( + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec.Capability + .class); + var receipt = + mock( + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .SourceReceipt.class); + var source = mock(net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence.class); + var operation = java.util.UUID.randomUUID(); + var canonical = java.util.UUID.randomUUID(); + when(source.targetNamespace()).thenReturn("dev"); + when(source.operationId()).thenReturn(operation); + when(source.canonicalTenantId()).thenReturn(canonical); + when(source.worldSlug()).thenReturn("fixture-world"); + when(receipt.sourceEvidence()).thenReturn(source); + var creation = mock(net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence.class); + when(receipt.creationEvidence()).thenReturn(creation); + when(trusted.wire()).thenReturn(capability); + var committed = + new RunOwnedFixtureLaunchReadback.CommittedReceipt( + mock(RunOwnedFixtureLaunchReadback.Snapshot.class), + mock(net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto.class)); + when(readback.readCommittedReceipt(receipt)).thenReturn(committed); + when(policy.readExisting(trusted, creation, committed.snapshot(), committed.descriptor())) + .thenThrow(new IllegalStateException("Preexisting sealed fixture policy unavailable")); + X509Certificate controlledLeaf = mock(X509Certificate.class); + when(controlledLeaf.getEncoded()).thenReturn(new byte[] {4, 5, 6}); + var certificate = GrpcPeerCertificateEvidence.fromCertificate(controlledLeaf).orElseThrow(); + when(trusted.worldManagementLeafSha256()).thenReturn(certificate.leafSha256()); + try (var configuration = mockStatic(TestDataSeeder.class); + var files = + mockStatic( + net.firedevops.firemud.common.smoke.RunOwnedFixtureImmutableFileReader.class); + var wire = + mockStatic( + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .class)) { + configuration + .when( + () -> + TestDataSeeder.verifyFixtureConfiguration( + anyString(), + anyString(), + anyString(), + anyString(), + anyString(), + anyString(), + anyString(), + anyString())) + .thenReturn(trusted); + byte[] controlledReceipt = new byte[] {7}; + files + .when( + () -> + net.firedevops.firemud.common.smoke.RunOwnedFixtureImmutableFileReader + .readBoundedImmutableFile(any(java.nio.file.Path.class), anyInt(), any())) + .thenReturn(controlledReceipt); + wire.when( + () -> + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .parseSourceReceipt(controlledReceipt, capability)) + .thenReturn(receipt); + var authorization = + new RunOwnedFixtureOwnerReadAuthorization( + readback, + policy, + "dev", + "controlled-run", + "controlled-project", + "/controlled-capability", + "/controlled-receipt", + "/controlled-gs", + "/controlled-world", + "/controlled-ca"); + var request = + net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec.toReadRequest( + new net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec.ReadRequest( + "dev", java.util.UUID.randomUUID(), operation, canonical, "fixture-world")); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/dev/sa/world-management-service") + .orElseThrow()) + .withValue(GrpcPeerCertificateEvidence.CONTEXT_KEY, certificate) + .run( + () -> + assertThatThrownBy(() -> authorization.authorizeSource(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Preexisting")); + verify(readback).readCommittedReceipt(receipt); + verify(policy).readExisting(trusted, creation, committed.snapshot(), committed.descriptor()); + verify(policy, never()).sealAndRead(any(), any(), any(), any()); + } + } + + private static void assertBothDeny(RunOwnedFixtureOwnerReadAuthorization authorization) { + assertThatThrownBy( + () -> + authorization.authorizeSource( + ResolveAuthoredWorldSourceRequest.getDefaultInstance())) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + authorization.authorizeVersion( + GetAuthoredWorldVersionStateRequest.getDefaultInstance())) + .isInstanceOf(SecurityException.class); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java index c422c55ff0..71e3c9938d 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java @@ -66,7 +66,9 @@ class CanonicalLaunchGrpcAuthWiringTest { "game_design.v1.PublishedRealmEntryPolicyService/ListPublishedRealmEntryPolicies", RESOLVE_LAUNCH_DESCRIPTOR_METHOD, GET_LAUNCH_DESCRIPTOR_METHOD, - GET_COMPLETE_LAUNCH_BINDING_METHOD); + GET_COMPLETE_LAUNCH_BINDING_METHOD, + "gamedesign.v1.AuthoredWorldSourceReadService/ResolveAuthoredWorldSource", + "gamedesign.v1.AuthoredWorldVersionStateService/GetAuthoredWorldVersionState"); private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; private static final String WORLD_MANAGEMENT_URI = "spiffe://firemud/ns/test/sa/world-management-service"; @@ -263,6 +265,41 @@ void playerJwtCannotSubstituteForMissingGameSessionPeerIdentity() { assertAllLaunchHandlersDeny(interceptor(jwtUtil), null, playerJwt); } + @Test + void fixedOwnerReadBypassesAreExactInBothConfigurationProfiles() throws Exception { + for (String resource : List.of("application.yml", "application-prod.yml")) { + var factory = new org.springframework.beans.factory.config.YamlPropertiesFactoryBean(); + factory.setResources( + new org.springframework.core.io.FileSystemResource("src/main/resources/" + resource)); + var properties = java.util.Objects.requireNonNull(factory.getObject()); + var methods = + properties.stringPropertyNames().stream() + .filter(key -> key.startsWith("firemud.auth.grpc.public-methods[")) + .map(properties::getProperty) + .toList(); + assertThat(methods).containsExactlyInAnyOrderElementsOf(ALLOWLISTED_METHODS); + assertThat(methods) + .doesNotContain( + UNLISTED_METHOD, + "gamedesign.v1.GameDesignService/GetVersionState", + "gamedesign.v1.GameDesignService/GetVersionAssetArtifactState"); + } + for (String method : ALLOWLISTED_METHODS.subList(6, 8)) { + var result = + dispatch( + interceptor(), + null, + new Metadata(), + method, + GetPublishedReleaseBundleRequest.getDefaultInstance(), + GetPublishedReleaseBundleResponse.getDefaultInstance(), + GetPublishedReleaseBundleRequest.getDefaultInstance(), + (request, observer) -> observer.onCompleted()); + assertThat(result.dispatched()).isTrue(); + assertThat(result.closedStatus()).isNull(); + } + } + @Test void unlistedGameDesignMethodStillRequiresBearerToken() { AuthTokenInterceptor interceptor = interceptor(); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java index c76256c058..949b1dd1ff 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java @@ -72,7 +72,9 @@ class TenantIdentityGrpcAuthWiringTest { POLICY_LIST_METHOD, RESOLVE_LAUNCH_DESCRIPTOR_METHOD, GET_LAUNCH_DESCRIPTOR_METHOD, - GET_COMPLETE_LAUNCH_BINDING_METHOD); + GET_COMPLETE_LAUNCH_BINDING_METHOD, + "gamedesign.v1.AuthoredWorldSourceReadService/ResolveAuthoredWorldSource", + "gamedesign.v1.AuthoredWorldVersionStateService/GetAuthoredWorldVersionState"); private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; private static final String SOURCE_KEY = "fresh-owner-key-91"; diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java new file mode 100644 index 0000000000..e5c0b6f6f3 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java @@ -0,0 +1,128 @@ +package unit.net.firedevops.firemud.gamedesign.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.gamedesign.data.RunOwnedFixtureOwnerReadAuthorization; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.service.impl.RunOwnedFixtureAuthoredWorldSourceReadGrpcService; +import net.firedevops.firemud.gamedesign.service.impl.RunOwnedFixtureAuthoredWorldVersionStateGrpcService; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.transaction.PlatformTransactionManager; + +class RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest { + @Test + void fixedServicesRemainUnregisteredByDefaultAndUseExistingServiceIdsWhenEnabled() { + var authorization = mock(RunOwnedFixtureOwnerReadAuthorization.class); + var repository = mock(GameAuthoredWorldSourceRepository.class); + var transactions = mock(PlatformTransactionManager.class); + // This registration test uses a controlled authorization bean, not producer authority. + var runner = + new ApplicationContextRunner() + .withBean(RunOwnedFixtureOwnerReadAuthorization.class, () -> authorization) + .withBean(GameAuthoredWorldSourceRepository.class, () -> repository) + .withBean(PlatformTransactionManager.class, () -> transactions) + .withUserConfiguration( + RunOwnedFixtureAuthoredWorldSourceReadGrpcService.class, + RunOwnedFixtureAuthoredWorldVersionStateGrpcService.class); + runner.run( + context -> { + assertThat(context) + .doesNotHaveBean(RunOwnedFixtureAuthoredWorldSourceReadGrpcService.class); + assertThat(context) + .doesNotHaveBean(RunOwnedFixtureAuthoredWorldVersionStateGrpcService.class); + }); + runner + .withPropertyValues("FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=false") + .run( + context -> { + assertThat(context) + .doesNotHaveBean(RunOwnedFixtureAuthoredWorldSourceReadGrpcService.class); + assertThat(context) + .doesNotHaveBean(RunOwnedFixtureAuthoredWorldVersionStateGrpcService.class); + }); + runner + .withPropertyValues( + "FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=true", + "firemud.grpc.workload-namespace=dev") + .run( + context -> { + assertThat( + context + .getBean(RunOwnedFixtureAuthoredWorldSourceReadGrpcService.class) + .bindService() + .getServiceDescriptor() + .getName()) + .isEqualTo("gamedesign.v1.AuthoredWorldSourceReadService"); + assertThat( + context + .getBean(RunOwnedFixtureAuthoredWorldVersionStateGrpcService.class) + .bindService() + .getServiceDescriptor() + .getName()) + .isEqualTo("gamedesign.v1.AuthoredWorldVersionStateService"); + }); + verifyNoInteractions(repository, transactions, authorization); + } + + @Test + void authorizationDenialAndMissingPreexistingOwnerNeverReachKernelsOrPublishResponses() { + for (RuntimeException refusal : + new RuntimeException[] { + new SecurityException("controlled peer refusal"), + new IllegalStateException("preexisting policy owner missing") + }) { + var authorization = mock(RunOwnedFixtureOwnerReadAuthorization.class); + var repository = mock(GameAuthoredWorldSourceRepository.class); + var transactions = mock(PlatformTransactionManager.class); + when(authorization.authorizeSource(any())).thenThrow(refusal); + when(authorization.authorizeVersion(any())).thenThrow(refusal); + var sourceFailure = new AtomicReference(); + var versionFailure = new AtomicReference(); + new RunOwnedFixtureAuthoredWorldSourceReadGrpcService(authorization, repository, "dev") + .resolveAuthoredWorldSource( + ResolveAuthoredWorldSourceRequest.getDefaultInstance(), + refusingObserver(sourceFailure)); + new RunOwnedFixtureAuthoredWorldVersionStateGrpcService( + authorization, transactions, repository, "dev") + .getAuthoredWorldVersionState( + GetAuthoredWorldVersionStateRequest.getDefaultInstance(), + refusingObserver(versionFailure)); + var expected = + refusal instanceof SecurityException + ? Status.Code.PERMISSION_DENIED + : Status.Code.FAILED_PRECONDITION; + assertThat(Status.fromThrowable(sourceFailure.get()).getCode()).isEqualTo(expected); + assertThat(Status.fromThrowable(versionFailure.get()).getCode()).isEqualTo(expected); + verifyNoInteractions(repository, transactions); + } + } + + private static StreamObserver refusingObserver(AtomicReference failure) { + return new StreamObserver<>() { + @Override + public void onNext(T value) { + throw new AssertionError("Refused read emitted success"); + } + + @Override + public void onError(Throwable error) { + failure.set(error); + } + + @Override + public void onCompleted() { + throw new AssertionError("Refused read completed"); + } + }; + } +} 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..e35f0ad364 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResources.java @@ -0,0 +1,1310 @@ +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.CanonicalGameInstanceLaunchAssociationReadGrpcCodec; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; +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( + RunOwnedWorldLaunchEvidence evidence, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + WorldAuthoredVersionIdentityReceipt versionReceipt) { + Objects.requireNonNull(evidence, "evidence").requireFixedGameSessionPeer(); + Objects.requireNonNull(sourceReceipt, "sourceReceipt"); + Objects.requireNonNull(versionReceipt, "versionReceipt"); + + var fixture = evidence.sourceReceipt(); + var capability = evidence.capability(); + var descriptor = evidence.launchDescriptor(); + var gameSession = evidence.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(evidence.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(evidence.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); + evidence.requireMatches(originalRequest); + String lifecycleBindingDigest = "sha256:" + evidence.bindingDigest(originalRequest, 1L); + String gameSessionResponseBytesDigest = + sha256Raw( + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toFixtureResponse(gameSession) + .toByteArray()); + + FixedPresetPlan unsealed = + new FixedPresetPlan( + PRESET_SCHEMA_VERSION, + PRESET_ID, + capability.operationId(), + capability.claimDigest(), + fixture.fixturePolicySeal().requestDigest(), + fixture.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)); + } + + /** 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"); + } + + FixedPresetPlan unsealed = + new FixedPresetPlan( + PRESET_SCHEMA_VERSION, + PRESET_ID, + fixtureOperationId, + 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, + RunOwnedWorldLaunchEvidence 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( + RunOwnedWorldLaunchEvidence 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/data/RunOwnedWorldLaunchEvidence.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java index cd39f90220..51375e9f73 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java @@ -8,6 +8,9 @@ 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; @@ -60,6 +63,28 @@ public final class RunOwnedWorldLaunchEvidence { Objects.requireNonNull(gameSessionAssociation, "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; } 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 b7072231c8..460c958b61 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,31 @@ 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.RunOwnedWorldFixedPresetResources; +import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidence; import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceProvider; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto; @@ -35,13 +47,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,11 +96,23 @@ public class WorldLifecycleCommandServiceImpl implements WorldLifecycleCommandSe private final TransactionOperations transactionOperations; private final RunOwnedWorldLaunchEvidenceProvider runOwnedWorldLaunchEvidenceProvider; + 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, @@ -111,6 +147,52 @@ 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, + 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, + dsl, + transactionManager, + serviceEndpoints, + grpcClientProperties, + grpcChannelFactory, + workloadNamespace); + } + WorldLifecycleCommandServiceImpl( WorldInstanceRepository worldInstanceRepository, RegionInstanceRepository regionInstanceRepository, @@ -160,6 +242,100 @@ 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); + } + + @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, + 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, + DSLContext dsl, + PlatformTransactionManager fixtureTransactionManager, + ServiceEndpointsProperties serviceEndpoints, + CommonGrpcClientProperties grpcClientProperties, + GrpcChannelFactory grpcChannelFactory, + String workloadNamespace) { this.worldInstanceRepository = worldInstanceRepository; this.regionInstanceRepository = regionInstanceRepository; this.zoneRepository = zoneRepository; @@ -175,6 +351,27 @@ public WorldLifecycleCommandServiceImpl( this.meterRegistry = meterRegistry; this.transactionOperations = transactionOperations; this.runOwnedWorldLaunchEvidenceProvider = runOwnedWorldLaunchEvidenceProvider; + 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( @@ -214,6 +411,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"); @@ -221,14 +427,147 @@ void initMetrics() { failCounter = meterRegistry.counter("world_instance_fail_total"); } + /** + * Composes authenticated fixture owners into the original PREPARING allocation only. Activation + * and admission remain unavailable through both Java and SQL owners. + */ + WorldInstanceLifecycleSnapshotDto prepareRunOwnedFixture( + PreparedWorldInstanceRequest originalGameSessionRequest, + RunOwnedWorldLaunchEvidence fixtureEvidence) { + Objects.requireNonNull(fixtureEvidence, "fixtureEvidence").requireFixedGameSessionPeer(); + requireNoAmbientFixtureReadTransaction(); + if (!fixtureModeEnabled()) 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(); + return snapshot(materialized); + } + + 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 (fixtureModeEnabled()) { - throw fixtureWritesUnavailable(); + requireNoAmbientFixtureReadTransaction(); + return prepareRunOwnedFixture( + request, runOwnedWorldLaunchEvidenceProvider.requireAuthenticatedEvidence()); } + if (prepareTransactionOperations == null) return prepareOrdinaryWorldInstance(request); + return Objects.requireNonNull( + prepareTransactionOperations.execute(status -> prepareOrdinaryWorldInstance(request)), + "Ordinary preparation transaction returned no World snapshot"); + } + + private WorldInstanceLifecycleSnapshotDto prepareOrdinaryWorldInstance( + PreparedWorldInstanceRequest request) { validatePrepareRequest(request); WorldInstance existing = worldInstanceRepository @@ -341,6 +680,127 @@ private PreparedWorldInstanceRequest preparedRequest(WorldInstance worldInstance worldInstance.getRemapSetId()); } + 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 (!fixtureModeEnabled() + || 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(); @@ -353,7 +813,7 @@ private static IllegalArgumentException fixtureEvidenceUnavailable() { private static IllegalArgumentException fixtureWritesUnavailable() { return new IllegalArgumentException( - "RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE: fixture prepare and activation are disabled until World-owned materialization is available"); + "RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE: fixture activation and admission are unavailable until their owner closure is qualified"); } @Override @@ -712,6 +1172,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..d2a4c8341e 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.RunOwnedWorldLaunchEvidence; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -153,6 +155,120 @@ 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( + RunOwnedWorldLaunchEvidence 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()) + || !fixtureEvidence + .fixtureProvenanceDigest() + .equals(trustedReceipt.fixturePolicySeal().evidenceDigest()) + || !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)); + 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 +486,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..689b7fc891 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.RunOwnedWorldLaunchEvidence; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -70,6 +72,91 @@ 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( + RunOwnedWorldLaunchEvidence 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()) + || !fixtureEvidence + .fixtureProvenanceDigest() + .equals(fixtureEvidence.sourceReceipt().fixturePolicySeal().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, + RunOwnedWorldLaunchEvidence expectedFixtureEvidence) { requireNoAmbientTransaction(); validateRequest( targetNamespace, @@ -84,6 +171,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 +182,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 +196,8 @@ public WorldAuthoredVersionIdentityReceipt associate( priorByGameDesignVersion.orElseThrow(), sourceReceipt, expectedCanonicalVersionId, - gameDesignVersionId); + gameDesignVersionId, + expectedFixtureEvidence); } AuthoredWorldVersionStateEvidence.Request currentRequest = @@ -124,6 +220,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 +241,8 @@ public WorldAuthoredVersionIdentityReceipt associate( committed.orElseThrow(), sourceReceipt, expectedCanonicalVersionId, - gameDesignVersionId); + gameDesignVersionId, + expectedFixtureEvidence); } Optional claimedSelector = repository.readByGameDesignVersion( @@ -156,7 +256,8 @@ public WorldAuthoredVersionIdentityReceipt associate( claimedSelector.orElseThrow(), sourceReceipt, expectedCanonicalVersionId, - gameDesignVersionId); + gameDesignVersionId, + expectedFixtureEvidence); } throw ownerFailure; } @@ -164,7 +265,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 +284,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 +297,36 @@ public WorldAuthoredVersionIdentityReceipt associate( return readback; } + private static void requireFixtureVersionStateMatches( + RunOwnedWorldLaunchEvidence 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, + RunOwnedWorldLaunchEvidence expectedFixtureEvidence) { if (!receipt.targetNamespace().equals(workloadNamespace) || !receipt.sourceIntakeReceipt().equals(sourceReceipt) || !receipt.canonicalTenantId().equals(sourceReceipt.canonicalTenantId()) @@ -200,6 +336,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..e9aee52837 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociation.java @@ -0,0 +1,636 @@ +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(); + } + + 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..6ca09ed5c0 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java @@ -0,0 +1,1994 @@ +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.RunOwnedWorldLaunchEvidence; +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( + RunOwnedWorldLaunchEvidence 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( + RunOwnedWorldLaunchEvidence 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 = + gameSessionRequest.runtimeFlagsJson() == null + || gameSessionRequest.runtimeFlagsJson().isBlank() + ? "{}" + : gameSessionRequest.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, + RunOwnedWorldLaunchEvidence 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, + RunOwnedWorldLaunchEvidence 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, + RunOwnedWorldLaunchEvidence 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( + RunOwnedWorldLaunchEvidence 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( + RunOwnedWorldLaunchEvidence 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, + RunOwnedWorldLaunchEvidence 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, + RunOwnedWorldLaunchEvidence 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/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 2efe463ca7..53daca60e6 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 @@ -108,6 +108,10 @@ void fixturePrepareAndActivationRetryAndRestartDenyBeforeReadsOrPostgresEffects( // This pre-existing controlled storage row supplies no canonical association or authority. repository.save(passiveStorageRow(request, "a".repeat(64))); when(fixtureProvider.isEnabled()).thenReturn(true); + when(fixtureProvider.requireAuthenticatedEvidence()) + .thenThrow( + new IllegalArgumentException( + "RUN_OWNED_WORLD_LAUNCH_EVIDENCE_UNAVAILABLE: controlled unavailable authenticated evidence")); clearInvocations( repository, fixtureEvidence, @@ -117,13 +121,13 @@ void fixturePrepareAndActivationRetryAndRestartDenyBeforeReadsOrPostgresEffects( bindProofClient); Map> before = postgresState(); try { - assertFixtureDenied(() -> lifecycleService.prepareWorldInstance(request)); - assertFixtureDenied(() -> lifecycleService.prepareWorldInstance(request)); + assertFixturePrepareDenied(() -> lifecycleService.prepareWorldInstance(request)); + assertFixturePrepareDenied(() -> lifecycleService.prepareWorldInstance(request)); assertFixtureDenied( () -> lifecycleService.activatePreparedWorldInstance(tenantId, gameInstanceId, 1L)); assertFixtureDenied( () -> lifecycleService.activatePreparedWorldInstance(tenantId, gameInstanceId, 1L)); - assertFixtureDenied( + assertFixturePrepareDenied( () -> lifecycleService.prepareWorldInstance( request(tenantId, uniqueId(), request.controlPlaneRequestId()))); @@ -131,17 +135,21 @@ void fixturePrepareAndActivationRetryAndRestartDenyBeforeReadsOrPostgresEffects( RunOwnedWorldLaunchEvidenceProvider restartedProvider = mock(RunOwnedWorldLaunchEvidenceProvider.class); when(restartedProvider.isEnabled()).thenReturn(true); + when(restartedProvider.requireAuthenticatedEvidence()) + .thenThrow( + new IllegalArgumentException( + "RUN_OWNED_WORLD_LAUNCH_EVIDENCE_UNAVAILABLE: controlled unavailable authenticated evidence")); WorldInstanceRepository restartedRepository = spy(new WorldInstanceRepository(dsl)); WorldLifecycleCommandServiceImpl restartedService = restartedLifecycleService(restartedRepository, restartedProvider); - assertFixtureDenied(() -> restartedService.prepareWorldInstance(request)); + assertFixturePrepareDenied(() -> restartedService.prepareWorldInstance(request)); assertFixtureDenied( () -> restartedService.activatePreparedWorldInstance(tenantId, gameInstanceId, 1L)); assertThat(postgresState()).isEqualTo(before); verifyNoInteractions(repository, restartedRepository); - org.mockito.Mockito.verify(restartedProvider, org.mockito.Mockito.never()) + org.mockito.Mockito.verify(restartedProvider, org.mockito.Mockito.times(1)) .requireAuthenticatedEvidence(); - verifyNoUpstreamReads(); + verifyNoUpstreamReads(3); } finally { dsl.execute("DELETE FROM world_instance WHERE tenant_id = ?", tenantId); } @@ -208,6 +216,38 @@ void controlledPassiveStorageRetainsBindingAndEnforcesConstraintsUniquenessAndCa .usingRecursiveComparison() .isEqualTo(stored); + Map> beforeLifecycleDenials = postgresState(); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_instance SET status = 'ACTIVE' WHERE id = ?", stored.getId())) + .hasRootCauseInstanceOf(org.postgresql.util.PSQLException.class) + .rootCause() + .hasMessageContaining("lifecycle transitions are disabled"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_instance SET lifecycle_epoch = lifecycle_epoch + 1 WHERE id = ?", + stored.getId())) + .hasRootCauseInstanceOf(org.postgresql.util.PSQLException.class) + .rootCause() + .hasMessageContaining("lifecycle transitions are disabled"); + // Direct SQL cannot create an ACTIVE row from a passive fixture storage image either. + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO world_instance SELECT (jsonb_populate_record(NULL::world_instance, " + + "to_jsonb(w) || jsonb_build_object('id', ?, 'game_instance_id', ?, " + + "'control_plane_request_id', ?, 'status', 'ACTIVE'))).* FROM world_instance w WHERE id = ?", + uniqueId(), + uniqueId(), + operationId(), + stored.getId())) + .hasRootCauseInstanceOf(org.postgresql.util.PSQLException.class) + .rootCause() + .hasMessageContaining("must begin PREPARING"); + assertThat(postgresState()).isEqualTo(beforeLifecycleDenials); + WorldInstance staleCopy = repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); WorldInstance winningCopy = @@ -284,6 +324,10 @@ void concurrentFixturePrepareAndActivationRetriesDenyWithoutPostgresOrUpstreamEf long gameInstanceId = uniqueId(); PreparedWorldInstanceRequest request = request(tenantId, gameInstanceId, operationId()); when(fixtureProvider.isEnabled()).thenReturn(true); + when(fixtureProvider.requireAuthenticatedEvidence()) + .thenThrow( + new IllegalArgumentException( + "RUN_OWNED_WORLD_LAUNCH_EVIDENCE_UNAVAILABLE: controlled unavailable authenticated evidence")); clearInvocations( repository, fixtureEvidence, @@ -300,7 +344,7 @@ void concurrentFixturePrepareAndActivationRetriesDenyWithoutPostgresOrUpstreamEf () -> { ready.countDown(); await(start); - assertFixtureDenied(() -> lifecycleService.prepareWorldInstance(request)); + assertFixturePrepareDenied(() -> lifecycleService.prepareWorldInstance(request)); assertFixtureDenied( () -> lifecycleService.activatePreparedWorldInstance( @@ -311,7 +355,7 @@ void concurrentFixturePrepareAndActivationRetriesDenyWithoutPostgresOrUpstreamEf () -> { ready.countDown(); await(start); - assertFixtureDenied(() -> lifecycleService.prepareWorldInstance(request)); + assertFixturePrepareDenied(() -> lifecycleService.prepareWorldInstance(request)); assertFixtureDenied( () -> lifecycleService.activatePreparedWorldInstance( @@ -323,7 +367,7 @@ void concurrentFixturePrepareAndActivationRetriesDenyWithoutPostgresOrUpstreamEf second.get(20, TimeUnit.SECONDS); assertThat(postgresState()).isEqualTo(before); verifyNoInteractions(repository); - verifyNoUpstreamReads(); + verifyNoUpstreamReads(2); } finally { start.countDown(); } @@ -336,8 +380,16 @@ private static void assertFixtureDenied( .hasMessageStartingWith("RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE:"); } - private void verifyNoUpstreamReads() { - org.mockito.Mockito.verify(fixtureProvider, org.mockito.Mockito.never()) + private static void assertFixturePrepareDenied( + org.assertj.core.api.ThrowableAssert.ThrowingCallable call) { + assertThatThrownBy(call) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageStartingWith("RUN_OWNED_WORLD_LAUNCH_EVIDENCE_UNAVAILABLE:"); + } + + private void verifyNoUpstreamReads(int preparationVerifications) { + // Only preparation enters the controlled verifier; activation remains before-effects denied. + org.mockito.Mockito.verify(fixtureProvider, org.mockito.Mockito.times(preparationVerifications)) .requireAuthenticatedEvidence(); verifyNoInteractions( fixtureEvidence, 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..78014da21c --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java @@ -0,0 +1,1889 @@ +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.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.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.flywaydb.core.api.MigrationVersion; +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 static final String CONTENT_DIGEST = + "sha256:f817af2770072bab0384c30c19b8cd30fce7a5a33f7587faed0024aa7c0909bc"; + private static final String VALID_DIGEST = "sha256:" + "a".repeat(64); + + 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")); + + private static final String HISTORY = "flyway_schema_history_world_management_service"; + // Literal disclosed donor postimages, not qualification or current authority. + 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( + "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()); + } + assertThat(versions(dsl)).hasSize(75); + assertThat(versions(dsl).subList(34, 40)) + .containsExactly("1003", "1004", "1005", "1006", "1007", "1007.1"); + assertThat(versions(dsl).subList(40, 75)).containsExactlyElementsOf(remainingVersions()); + var configured = + migration(dataSource("world_management_service"), "world_management_service", null); + assertThat(configured.getConfiguration().isOutOfOrder()).isFalse(); + configured.validate(); + } + + @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 association = + associationRepository() + .readRunOwnedFixtureAssociation( + evidence, RunOwnedWorldFixtureEvidenceTestFixtures.request(evidence)); + assertThat(prepared.tenantId()).isEqualTo(association.worldPrivateKeys().tenantId()); + assertThat(prepared.gameInstanceId()) + .isEqualTo(association.worldPrivateKeys().gameInstanceId()); + assertThat(prepared.versionId()).isEqualTo(association.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); + assertThat(RunOwnedWorldFixtureLifecycleTestFactory.prepare(nativeService(fresh), fresh)) + .isEqualTo(prepared); + 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 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 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 installed34ThroughParent40ToFull75RetainsOriginalRowsXminAndStableLegacyUpdates() + 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 full = migration(source, schema, null); + full.migrate(); + full.validate(); + assertThat(full.getConfiguration().isOutOfOrder()).isFalse(); + assertThat(versions(connection)).hasSize(75); + assertThat(versions(connection).subList(40, 75)) + .containsExactlyElementsOf(remainingVersions()); + assertThat(history(connection).subList(0, 40)).isEqualTo(parentHistory); + for (var entry : originalColumns.entrySet()) + assertThat(retainedRows(connection, schema, entry.getKey(), entry.getValue())) + .as("all original values and xmin for %s", entry.getKey()) + .isEqualTo(originalRows.get(entry.getKey())); + 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") + .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 original 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(); + } + } + for (var entry : originalColumns.entrySet()) + assertThat(retainedRows(connection, schema, entry.getKey(), entry.getValue())) + .isEqualTo(originalRows.get(entry.getKey())); + // 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 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() { + RunOwnedWorldLaunchEvidence 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); + TransactionTemplate committedRead = new TransactionTemplate(transactionManager); + committedRead.setReadOnly(true); + committedRead.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + RunOwnedWorldFixedPresetResources.MaterializedFixedPreset committedResult = + committedRead.execute( + status -> + RunOwnedWorldFixedPresetResources.readCommitted(dsl, association, source, version)); + assertThat(committedResult).isEqualTo(result); + 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(RunOwnedWorldLaunchEvidence evidence) { + return nativeService(evidence, new AtomicInteger()); + } + + private WorldLifecycleCommandServiceImpl nativeService( + RunOwnedWorldLaunchEvidence 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 RunOwnedWorldLaunchEvidenceProvider( + 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 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 Flyway migration(DriverManagerDataSource source, String schema, String target) { + Path root = repositoryRoot(); + var configuration = + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .table(HISTORY) + .placeholders(Map.of("serviceSchema", schema)) + .locations( + "filesystem:" + + root.resolve( + "services/world-management-service/src/main/resources/db/migration"), + "filesystem:" + + root.resolve("services/common-saga/src/main/resources/db/migration/saga")); + if (target != null) configuration.target(MigrationVersion.fromVersion(target)); + return configuration.load(); + } + + 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<>(List.of("1008", "1009", "1009.1")); + for (int version = 1010; version <= 1041; version++) versions.add(Integer.toString(version)); + return List.copyOf(versions); + } + + 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("FireMUD repository root unavailable"); + } + + 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 TransactionTemplate ownerTransaction() { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return transaction; + } + + 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 RunOwnedWorldLaunchEvidence 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..f35ce6f96e --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixtureEvidenceTestFixtures.java @@ -0,0 +1,398 @@ +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 RunOwnedWorldLaunchEvidence 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 RunOwnedWorldLaunchEvidence( + capability, + receipt, + descriptor, + capabilityBytes, + receiptBytes, + "a".repeat(64), + RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, + "c".repeat(64), + "b".repeat(64), + gs); + } + + public static RunOwnedWorldLaunchEvidence create() { + return create(new ObjectMapper()); + } + + /** A fresh response correlation with identical allocation and original immutable policy bytes. */ + public static RunOwnedWorldLaunchEvidence freshObservation(RunOwnedWorldLaunchEvidence 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 RunOwnedWorldLaunchEvidence changedReceiptBytes( + RunOwnedWorldLaunchEvidence 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 RunOwnedWorldLaunchEvidence secondAssignment(RunOwnedWorldLaunchEvidence 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(RunOwnedWorldLaunchEvidence 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 RunOwnedWorldLaunchEvidence copy( + RunOwnedWorldLaunchEvidence original, + byte[] receiptBytes, + CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult gs) { + return new RunOwnedWorldLaunchEvidence( + 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/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..ba06b1b84e --- /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.RunOwnedWorldFixtureEvidenceTestFixtures; +import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidence; +import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceProvider; +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, + RunOwnedWorldLaunchEvidenceProvider 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, RunOwnedWorldLaunchEvidence evidence) { + return service.prepareRunOwnedFixture( + RunOwnedWorldFixtureEvidenceTestFixtures.request(evidence), evidence); + } +} 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 f67212d8ea..75a2d31137 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 @@ -66,6 +66,9 @@ * 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. + * Positive component storage and the 40-migration endpoint are explicitly historical at 1007.1; the + * retained schema-2 snapshot separately upgrades through the current default frontier. These + * historical 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) @@ -184,7 +187,7 @@ class WorldGuardedAuthoredGraphCapturePostgresIntegrationTest { new PostgreSQLContainer<>(TestContainerImages.postgres()); @Test - void exactParentWithRetainedOwnerAndLegacyWorldRowsUpgradesInDefaultOrder( + void exactParentWithRetainedOwnerAndLegacyWorldRowsUpgradesToHistoricalGuardedFrontier( @TempDir Path parentMigrations) throws Exception { Path root = repositoryRoot(); Path worldMigrations = @@ -315,9 +318,10 @@ 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( + historicalGuardedStage( dataSource, schema, "filesystem:" + worldMigrations, "filesystem:" + sagaMigrations); assertThat(current.getConfiguration().isOutOfOrder()).isFalse(); current.migrate(); @@ -604,6 +608,8 @@ void schemaTwoRepositorySnapshotRetainsEveryOriginalByteAndXminThroughSchemaThre List before = retainedRows(dsl, "world_authored_graph_snapshot", columns); assertThat(before).hasSize(1); + // 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, worldLocation, sagaLocation).migrate(); assertThat( @@ -630,8 +636,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()); @@ -643,7 +651,9 @@ void actualGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoint() write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); Path root = repositoryRoot(); try { - flyway( + // Controlled permission-unverified component storage at the historical guarded frontier. + // Later Account/APPLIED owners retain their default-current denial requirements. + historicalGuardedStage( source, schema, "filesystem:" @@ -843,7 +853,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( @@ -882,7 +893,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, mapper); @@ -1093,6 +1105,19 @@ private static AuthoredWorldSourceEvidence controlledSource() { "NEW_GAME_ROW")); } + private static Flyway historicalGuardedStage( + DriverManagerDataSource source, String schema, String... locations) { + return Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .table(HISTORY) + .placeholders(Map.of("serviceSchema", schema)) + .locations(locations) + .target(MigrationVersion.fromVersion("1007.1")) + .load(); + } + private static Flyway flyway(DriverManagerDataSource source, String schema, String... locations) { return Flyway.configure() .dataSource(source) diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java index 38328a1538..5813c45133 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java @@ -4,29 +4,20 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; +import io.grpc.Context; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.PosixFilePermission; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; import java.util.Set; import java.util.UUID; -import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; -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.common.grpc.GrpcPeerCertificateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.worldmanagement.client.GameDesignClient; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; import org.junit.jupiter.api.Test; @@ -37,30 +28,80 @@ @ExtendWith(OutputCaptureExtension.class) class RunOwnedWorldLaunchEvidenceProviderTest { - private static final String CLAIM_DIGEST = controlledClaimDigest(); - private static final String OPERATION_ID = - RunOwnedInitialAdmissionFixtureWireCodec.fixtureOperationId( - CLAIM_DIGEST, "fixture-run", "firemud-fixture-run", "a".repeat(64), "b".repeat(64)) - .toString(); - private static final String RELEASE_REF = "8ce42642-53ae-4d07-aab8-37c43ce66e0c"; - @TempDir Path temporaryDirectory; - private static String controlledClaimDigest() { + @Test + void retainedCarrierRequiresOriginalFixedPeerAndLeafForEveryOwnerOperation() { + RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.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 { - // 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); + action.run(); + } finally { + context.detach(previous); } } @Test void bindingDigestNormalizesAcceptedBlankOptionalOverridesToAbsent() { - RunOwnedWorldLaunchEvidence evidence = fixtureEvidence(); + RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.create(); String absent = evidence.bindingDigest(request(null, null), 1L); assertThat(evidence.bindingDigest(request("", ""), 1L)).isEqualTo(absent); @@ -69,7 +110,7 @@ void bindingDigestNormalizesAcceptedBlankOptionalOverridesToAbsent() { @Test void launchEvidenceBindsStartingAllocationPrivateKeysFromOwnerProjection() { - RunOwnedWorldLaunchEvidence evidence = fixtureEvidence(); + RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.create(); evidence.requireMatches(request(null, null)); assertThat(evidence.gameSessionAssociation().gameSessionTenantId()).isEqualTo(142L); @@ -249,235 +290,20 @@ private static PreparedWorldInstanceRequest request(String patch, String remap) 142L, 1001L, 17L, - OPERATION_ID, + RunOwnedWorldLaunchEvidenceTestFixtures.create().capability().operationId(), "launch-descriptor-fixture-11", 11L, patch, "{}", "genrev-11", 77L, - RELEASE_REF, + RunOwnedWorldLaunchEvidenceTestFixtures.create() + .launchDescriptor() + .publishedReleaseBundleRef(), 77L, remap); } - private static RunOwnedWorldLaunchEvidence fixtureEvidence() { - UUID registrationId = UUID.fromString(OPERATION_ID); - UUID sourceOperationId = UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"); - UUID canonicalTenantId = UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6d"); - 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", - OPERATION_ID, - 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, - RELEASE_REF, - false, - 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", - OPERATION_ID, - 42L, - 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), - 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(OPERATION_ID), - policyRequestDigest, - RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( - UUID.fromString(OPERATION_ID), policyRequestDigest)); - var receipt = - new RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt( - RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_SCHEMA, - "fixture-run", - "firemud-fixture-run", - OPERATION_ID, - 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 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(OPERATION_ID), 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 RunOwnedWorldLaunchEvidence( - capability, - receipt, - descriptor, - new byte[] {1}, - new byte[] {2}, - "a".repeat(64), - RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, - "c".repeat(64), - "b".repeat(64), - association); - } - private static RunOwnedWorldLaunchEvidenceProvider provider( boolean enabled, String capabilityPath, diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceTestFixtures.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceTestFixtures.java new file mode 100644 index 0000000000..fe79bb86b5 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceTestFixtures.java @@ -0,0 +1,262 @@ +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 RunOwnedWorldLaunchEvidenceTestFixtures { + private static final String CLAIM_DIGEST = controlledClaimDigest(); + private static final String OPERATION_ID = + RunOwnedInitialAdmissionFixtureWireCodec.fixtureOperationId( + CLAIM_DIGEST, "fixture-run", "firemud-fixture-run", "a".repeat(64), "b".repeat(64)) + .toString(); + private static final String RELEASE_REF = "8ce42642-53ae-4d07-aab8-37c43ce66e0c"; + + private RunOwnedWorldLaunchEvidenceTestFixtures() {} + + 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 RunOwnedWorldLaunchEvidence create() { + UUID registrationId = UUID.fromString(OPERATION_ID); + UUID sourceOperationId = UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"); + UUID canonicalTenantId = UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6d"); + 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", + OPERATION_ID, + 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, + RELEASE_REF, + false, + 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", + OPERATION_ID, + 42L, + 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), + 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(OPERATION_ID), + policyRequestDigest, + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + UUID.fromString(OPERATION_ID), policyRequestDigest)); + var receipt = + new RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt( + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_SCHEMA, + "fixture-run", + "firemud-fixture-run", + OPERATION_ID, + 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 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(OPERATION_ID), 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 RunOwnedWorldLaunchEvidence( + capability, + receipt, + descriptor, + new byte[] {1}, + new byte[] {2}, + "a".repeat(64), + RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, + "c".repeat(64), + "b".repeat(64), + association); + } +} 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 99182918b5..ec3dd3baca 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 @@ -749,9 +749,11 @@ void prepareWorldInstanceRejectsMissingRequiredManifestAssetKeyProof() { } @Test - void fixturePrepareRefusesBeforeProviderEvidenceOrRepositoryInteraction() { + void fixturePrepareRejectsUnavailableAuthenticatedEvidenceBeforeRepositoryInteraction() { RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); when(provider.isEnabled()).thenReturn(true); + IllegalArgumentException unavailable = new IllegalArgumentException("unverified fixture peer"); + when(provider.requireAuthenticatedEvidence()).thenThrow(unavailable); WorldLifecycleCommandServiceImpl fixtureService = fixtureService(provider); IllegalArgumentException error = @@ -759,12 +761,33 @@ void fixturePrepareRefusesBeforeProviderEvidenceOrRepositoryInteraction() { IllegalArgumentException.class, () -> fixtureService.prepareWorldInstance(ordinaryPreparedRequest())); - assertTrue(error.getMessage().startsWith("RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE:")); + assertEquals(unavailable, error); verify(provider).isEnabled(); - verify(provider, never()).requireAuthenticatedEvidence(); + verify(provider).requireAuthenticatedEvidence(); verifyNoWorldRepositoryOrOwnerInteraction(); } + @Test + void fixturePrepareRejectsAmbientTransactionBeforeRemoteEvidence() { + RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); + when(provider.isEnabled()).thenReturn(true); + WorldLifecycleCommandServiceImpl fixtureService = fixtureService(provider); + org.springframework.transaction.support.TransactionSynchronizationManager + .setActualTransactionActive(true); + try { + IllegalStateException error = + assertThrows( + IllegalStateException.class, + () -> fixtureService.prepareWorldInstance(ordinaryPreparedRequest())); + assertTrue(error.getMessage().contains("no ambient transaction")); + verify(provider, never()).requireAuthenticatedEvidence(); + verifyNoWorldRepositoryOrOwnerInteraction(); + } finally { + org.springframework.transaction.support.TransactionSynchronizationManager + .setActualTransactionActive(false); + } + } + @Test void fixtureActivationRefusesBeforeWorldReadOrProviderEvidence() { RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); 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..dc643daeac 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.RunOwnedWorldLaunchEvidence; +import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceTestFixtures; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -50,6 +57,211 @@ void clearTransactionState() { TransactionSynchronizationManager.clear(); } + @Test + void fixtureIntakeRevalidatesPeerAndCallerBeforeAnyOwnerReadOrTransaction() { + RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.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() { + RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.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() { + RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.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 fixtureIntakeDeniesMissingIndependentReceiptAfterOwnerTransaction() { + RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.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() { + RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.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() { + RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.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 +876,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 +896,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..1446c229a7 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.RunOwnedWorldLaunchEvidence; +import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceTestFixtures; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeDigest; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; @@ -72,6 +79,444 @@ void clearTransactionState() { TransactionSynchronizationManager.clear(); } + @Test + void fixtureVersionRevalidatesPeerAndCallerBeforeAnyOwnerOrRemoteRead() { + RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.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() { + RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.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() { + RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.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() { + RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.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(repository, never()).acceptFresh(any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void fixtureVersionRejectsChangedRetainedSnapshotOnExactRetryWithoutRemoteOrSql() { + RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.create(); + var source = evidence.sourceReceipt().sourceEvidence(); + var intake = sourceReceipt(source); + var canonicalVersion = evidence.gameSessionAssociation().canonicalVersionId(); + when(sourceIntakeRepository.readBySource( + "dev", + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .thenReturn(Optional.of(intake)); + var request = + new AuthoredWorldVersionStateEvidence.Request( + 1, + "dev", + READ_REQUEST, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + evidence.launchDescriptor().versionId()); + for (VersionLifecycleState changedState : + List.of( + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED)) { + var changed = + AuthoredWorldVersionStateEvidence.create( + request, + source, + canonicalVersion, + changedState, + evidence.sourceReceipt().launchReadEvidence().versionState().getVersionStateEpoch() + + (changedState == VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED + ? 1L + : 0L)); + when(repository.readByCanonicalVersion( + "dev", source.canonicalTenantId(), source.worldSlug(), canonicalVersion)) + .thenReturn(Optional.of(identityReceipt(intake, changed, 101L))); + assertThatThrownBy( + () -> + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> fixtureService().associateRunOwnedFixture(evidence, intake))) + .isInstanceOf( + WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException.class); + } + verifyNoInteractions(versionStateClient); + verify(repository, never()).acceptFresh(any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void fixtureVersionDeniesMissingOrSubstitutedIndependentVersionReceipt() { + RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.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() { + RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.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))) From f02ab6c997edd463e10f1659dc2c4ed2f4b7276e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:07:43 +1300 Subject: [PATCH 02/45] Stabilize TLS watcher recovery observation and record receiving proof --- ...ame-authoring-publishing-and-activation.md | 2 ++ .../world-runtime-and-movement.md | 2 ++ .../grpc/TlsCertificateWatcherTest.java | 21 +++++++++++++++---- 3 files changed, 21 insertions(+), 4 deletions(-) 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 a75aefe6d8..48b13b58e1 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 @@ -14,6 +14,8 @@ The coherent receiving successor for [PR #3196](https://github.com/benhook1013/F ### Fixed fixture source and Version reads +After the qualified readiness-child carry at `f9e62a9b99850dc9cb526635e416f25e91f0e908`, the local receiving merge `a5f76d8cfa2092f01ccfe6ad0641878b8adc362b` passes all 515 freshly executed Game Design unit cases and 142 freshly executed native integrations, with formatting, static and documentation checks. The three-service native composition includes the current shared creation/source provenance comparison and real committed Game Session/World owners; controlled test capabilities and PKI remain its upstream boundary. This proof does not qualify deployed claimed Compose startup/restart, genuine Account authority or alternate already-applied Game Session migration bytes. + The local World follow-on registers default-off, operation-scoped wrappers around the existing Game Design 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. Whole unit proof retains 510 passing results from their earlier fresh execution on unchanged production inputs. The complete native suite passes 142 freshly executed PostgreSQL-backed cases, including 22 fixture cases and actual GDS producer → persisted GS `STARTING` → World `PREPARING` over three production mTLS handlers with unchanged owner rows, receipt bytes and `xmin` on retry and reconstruction. The fixed read adapters are registered in a real managed annotation context with actual producer owners; complete Spring Boot and packaged fresh/restart remain unqualified. The final native parent-file enumeration correction passes nine fresh storage-upgrade cases, formatting and all required static checks; the other native postimages retain their complete preceding execution attribution. This does not close any genuine Gameplay handoff. ### Closed fixture policy producer 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 a8130cffaa..aedf6c9092 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -16,6 +16,8 @@ The local follow-on implements typed source intake and Version association after ### Fixed fixture PREPARING owner preparation +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. + The local owner successor contains 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 passes formatting/static validation, 307 unit results reused from their preceding fresh execution and 75 freshly executed integrations (73 PostgreSQL-backed and two controlled mTLS). Game Design separately passes 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 passes nine freshly executed storage-upgrade cases and all required Game Design static checks; its 510 unit results are reused from earlier unchanged production inputs. Exact source and XML archives retain these separate scopes. The synchronous prepare entry uses fresh remote reads before SQL and preserves ordinary `REQUIRED` transactions. Fresh default-order 75-file installation, installed 34→40→75 upgrade, current-75 schema-2 snapshot retention, exact topology/manifest readback, rollback/races and reconstructed-owner retry pass physical execution. The GDS fixed read adapters are registered in a real managed annotation context with actual producer owners before serving their production handlers. Controlled test capabilities and PKI remain distinct from an actual claimed Compose deployment; complete packaged/Spring Boot fresh/restart proof remains open. Historical pre-1037 canonical Human schema-1 allocation retention is unconstructed because its genuine preparation/execution prerequisites are unavailable; no fake Account protection or disabled storage guard supplies that coverage. Historical guarded positive storage is explicitly pinned to 1007.1 and does not qualify current Account/APPLIED authority. Fixture bootstrap, activation, hold acquire/finalize, first OPEN prerequisites and initial placement stay unavailable; no Entity or operational-region evidence is 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. 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); From 1bd7b90bff4a64b237759ec32567eca82e343e7b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:52:35 +1300 Subject: [PATCH 03/45] Record corrected receiving proof and watcher recovery lesson --- design/project-management/ai-observations.md | 5 +++++ .../game-authoring-publishing-and-activation.md | 2 ++ .../implementation-tracking/world-runtime-and-movement.md | 2 ++ 3 files changed, 9 insertions(+) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index fdfdb3479b..09b017d0e2 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -275,3 +275,8 @@ Entry format: - Context: a canonical Game Session pin test established its real PostgreSQL INSERT lock wait, then expected a finite owner lease to have expired after a fixed host sleep. The database still reported the lease live, so the intended post-expiry race was not established. - Expected pattern: retain the original finite lease and exact blocker, poll the same PostgreSQL expiry predicate used by the owner within a bounded deadline, then release the lock and assert refusal without mutation. Do not change the lease, renew authority, weaken the refusal assertion or infer clock skew from the failed sleep assumption. - Current status: the test now waits for the database-owned expiry condition; current physical qualification remains required. + +- `2026-10-14`: Hold asynchronous recovery until failure-state assertions finish + - Context: the TLS certificate watcher callback-failure test signalled its first attempt before the watcher recorded an unhealthy state. A successful retry could restore health before the test observed that state. + - Expected pattern: gate the successful test callback until the existing unhealthy-state and aggregate-health assertions finish, release the gate in `finally`, then verify retry and recovered health. Preserve the production retry policy and every failure/recovery assertion. + - Current status: the test-only latch correction passed the full 486-case Common unit suite and static checks. The separate PostgreSQL refusal and cleanup chronology remains unexplained under the existing local PostgreSQL availability observation; later passing proof does not identify that cause. 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 48b13b58e1..b49d734dbd 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 @@ -14,6 +14,8 @@ The coherent receiving successor for [PR #3196](https://github.com/benhook1013/F ### Fixed fixture source and Version reads +After the corrected readiness child `7ab19d077f021b044b2d45409d892324c6204a48` restores original Game Session migration artifacts and adds forward V1011, local receiving merge `ec340c6a41a53127ca6fb3b57c399c12c843108e` passes all 17 freshly executed fixture-producer cases, including actual authenticated Game Design → Game Session → World composition. Ten Game Session original-history PostgreSQL cases also pass, with owning generation, affected formatting and documentation checks. This is focused receiving proof under controlled capabilities/PKI; unchanged broader proof keeps its earlier attribution, and actual deployment cohorts, mixed migration histories and genuine authority remain unqualified. + After the qualified readiness-child carry at `f9e62a9b99850dc9cb526635e416f25e91f0e908`, the local receiving merge `a5f76d8cfa2092f01ccfe6ad0641878b8adc362b` passes all 515 freshly executed Game Design unit cases and 142 freshly executed native integrations, with formatting, static and documentation checks. The three-service native composition includes the current shared creation/source provenance comparison and real committed Game Session/World owners; controlled test capabilities and PKI remain its upstream boundary. This proof does not qualify deployed claimed Compose startup/restart, genuine Account authority or alternate already-applied Game Session migration bytes. The local World follow-on registers default-off, operation-scoped wrappers around the existing Game Design 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. Whole unit proof retains 510 passing results from their earlier fresh execution on unchanged production inputs. The complete native suite passes 142 freshly executed PostgreSQL-backed cases, including 22 fixture cases and actual GDS producer → persisted GS `STARTING` → World `PREPARING` over three production mTLS handlers with unchanged owner rows, receipt bytes and `xmin` on retry and reconstruction. The fixed read adapters are registered in a real managed annotation context with actual producer owners; complete Spring Boot and packaged fresh/restart remain unqualified. The final native parent-file enumeration correction passes nine fresh storage-upgrade cases, formatting and all required static checks; the other native postimages retain their complete preceding execution attribution. This does not close any genuine Gameplay handoff. 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 aedf6c9092..2648bfde75 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -16,6 +16,8 @@ The local follow-on implements typed source intake and Version association after ### Fixed fixture PREPARING owner preparation +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. The local owner successor contains 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 passes formatting/static validation, 307 unit results reused from their preceding fresh execution and 75 freshly executed integrations (73 PostgreSQL-backed and two controlled mTLS). Game Design separately passes 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 passes nine freshly executed storage-upgrade cases and all required Game Design static checks; its 510 unit results are reused from earlier unchanged production inputs. Exact source and XML archives retain these separate scopes. The synchronous prepare entry uses fresh remote reads before SQL and preserves ordinary `REQUIRED` transactions. From 2ea6b6eec6fa2f7d63a834b3ee07f34f66720209 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:55:14 +1300 Subject: [PATCH 04/45] Record qualified fixture injection and transport receiving proof --- .../game-authoring-publishing-and-activation.md | 2 ++ .../implementation-tracking/world-runtime-and-movement.md | 2 ++ 2 files changed, 4 insertions(+) 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 b49d734dbd..0e75616db4 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 @@ -14,6 +14,8 @@ The coherent receiving successor for [PR #3196](https://github.com/benhook1013/F ### Fixed fixture source and Version reads +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. + After the corrected readiness child `7ab19d077f021b044b2d45409d892324c6204a48` restores original Game Session migration artifacts and adds forward V1011, local receiving merge `ec340c6a41a53127ca6fb3b57c399c12c843108e` passes all 17 freshly executed fixture-producer cases, including actual authenticated Game Design → Game Session → World composition. Ten Game Session original-history PostgreSQL cases also pass, with owning generation, affected formatting and documentation checks. This is focused receiving proof under controlled capabilities/PKI; unchanged broader proof keeps its earlier attribution, and actual deployment cohorts, mixed migration histories and genuine authority remain unqualified. After the qualified readiness-child carry at `f9e62a9b99850dc9cb526635e416f25e91f0e908`, the local receiving merge `a5f76d8cfa2092f01ccfe6ad0641878b8adc362b` passes all 515 freshly executed Game Design unit cases and 142 freshly executed native integrations, with formatting, static and documentation checks. The three-service native composition includes the current shared creation/source provenance comparison and real committed Game Session/World owners; controlled test capabilities and PKI remain its upstream boundary. This proof does not qualify deployed claimed Compose startup/restart, genuine Account authority or alternate already-applied Game Session migration bytes. 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 2648bfde75..4dcbe2e7cf 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -16,6 +16,8 @@ The local follow-on implements typed source intake and Version association after ### Fixed fixture PREPARING owner preparation +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. From 9e7c82733de22a61d06b1c614400f4169c990d66 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:40:42 +1300 Subject: [PATCH 05/45] Repair fixed World PREPARING evidence and required-field checks --- .../world-management-service/api-contracts.md | 2 +- .../runtime-and-data.md | 2 +- .../world-creation-workflow.md | 2 +- .../world-runtime-and-movement.md | 6 +- .../data/TestDataSeederIntegrationTest.java | 2 +- .../RunOwnedWorldFixedPresetResources.java | 26 ++- .../WorldAuthoredSourceIntakeService.java | 4 + .../WorldCanonicalInstanceAssociation.java | 35 +++ ...ical_association_required_field_checks.sql | 65 ++++++ ...resetResourcesPostgresIntegrationTest.java | 217 +++++++++++++++++- ...RunOwnedWorldFixedPresetResourcesTest.java | 130 +++++++++++ ...nOwnedWorldLaunchEvidenceTestFixtures.java | 13 +- .../WorldAuthoredSourceIntakeServiceTest.java | 24 ++ ...WorldCanonicalInstanceAssociationTest.java | 183 +++++++++++++++ 14 files changed, 679 insertions(+), 32 deletions(-) create mode 100644 services/world-management-service/src/main/resources/db/migration/V1042__world_canonical_association_required_field_checks.sql create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationTest.java diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 06fb2ebe28..1dccaf2c04 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -287,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). -Current fixture bootstrap skips runtime seeding; prepare and activate refuse before repository effects because World-owned materialization remains unavailable. The provider’s bounded descriptor and authenticated Game Session read exist as source capability, with controlled proof, but no current production lifecycle caller invokes them. 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 synchronous prepare RPC consumes the authenticated provider evidence and composes World-owned intake, canonical association and fixed-preset materialization at `PREPARING` epoch 1 and row version 0. Fixture bootstrap still skips runtime seeding; activation, holds and first admission remain unavailable before effects. The controlled native owner/socket proof qualifies this bounded preparation, while packaged startup/restart and genuine owner handoffs remain unqualified. Current capability and revision-specific proof are recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#fixed-fixture-preparing-owner-preparation). ## 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 76d0c2a62a..6066931183 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -26,7 +26,7 @@ The fixed fixture uses existing World source intake, Version identity, canonical 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 local migration frontier preserves the immutable V1008–V1039 donor artifacts and the immediate V1009.1 legacy UPDATE repair, then adds the unpublished PREPARING-only V1040/V1041 extension. The complete World plus Saga history contains 75 files, adding 35 SQL paths to the preceding 40-file boundary. Historical Human rows retain their original fields, nullable realm/catalog metadata and existing permission guards; no fixture backfill or Human protection is inferred. The extension has no fixture activation function, ACTIVE readback arm or fixture hold authority. World lifecycle transition, hold acquire/finalize, initial placement and player-admission owners reject the fixture variant before effects. The [Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence) owns the complete launch and replay ordering; the [tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#fixed-fixture-preparing-owner-preparation) records current physical and runtime proof. +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. 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. These storage checks do not grant Human protection, fixture activation or hold authority. World lifecycle transition, hold acquire/finalize, initial placement and player-admission owners reject the fixture variant before effects. 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. ### Authored-world source retention 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..7178d13605 100644 --- a/design/architecture/microservices/world-management-service/world-creation-workflow.md +++ b/design/architecture/microservices/world-management-service/world-creation-workflow.md @@ -17,7 +17,7 @@ The cross-platform workflow placement and adopter-proof requirements are owned b 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 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 default-off run-owned fixture uses the existing synchronous prepare command after the fixed-server World evidence provider validates the immutable receipt, exact Game Session TLS caller, World recipient pins and current Game Design descriptor. World retains the original PREPARING epoch and complete fixture binding digest for exact prepare replay; fixture activation and ACTIVE replay remain unavailable. 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: 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 2662199b42..d4fa653834 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -52,7 +52,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. Earlier coordinator-driven holds and World fixture PREPARING/ACTIVE binding belong to predecessor revisions. The current run-owned coordinator completes canonical Game Session STARTING allocation and independent readback only; World fixture bootstrap skips seeding, and prepare/activate refuse before owner effects. The World provider’s authenticated Game Session read verifies immutable fixture provenance and private allocation identity, but has no production lifecycle caller in this phase; it grants no 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. Earlier coordinator-driven holds and World fixture PREPARING/ACTIVE binding belong to predecessor revisions. The current run-owned coordinator completes canonical Game Session STARTING allocation and independent readback only. The separate synchronous World prepare RPC consumes the authenticated provider evidence and commits typed intake, canonical association and fixed-preset materialization at PREPARING epoch 1 and row version 0, with controlled native owner/socket proof. World fixture bootstrap skips seeding; activation, holds and first OPEN remain unavailable, and packaged startup/restart and genuine owner handoffs remain unqualified. 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. @@ -72,7 +72,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 run-owned coordinator completes Game Session STARTING allocation and readback only. Earlier Compose-driven holds, preparing-epoch binding and ACTIVE replay belong to predecessor evidence. The World provider implements a bounded authenticated Game Session read, but the current lifecycle has no caller because prepare/activate refuse before effects; controlled provider proof is not production execution. Fixture bootstrap skips seeding without granting 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 current run-owned fixture path verifies the sealed Game Design receipt and authenticated Game Session STARTING allocation; fixture bootstrap skips all seeding with a diagnostic, and prepare/activate refuse before materialization, lifecycle, hold or first-OPEN effects. Earlier binding/ACTIVE replay and coordinator-driven hold execution are predecessor proof, not current fixture capability. | [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) | Current fixture materialization, 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.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 run-owned coordinator completes Game Session STARTING allocation and readback only. Earlier Compose-driven holds, preparing-epoch binding and ACTIVE replay belong to predecessor evidence. The synchronous World prepare RPC consumes the bounded authenticated Game Session read and materializes the sealed fixed preset at PREPARING epoch 1 and row version 0, with controlled native production-handler proof. Fixture bootstrap skips seeding; activation, holds and first OPEN remain unavailable, and claimed packaged runtime and genuine owner handoffs remain unqualified. 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 current run-owned fixture prepare RPC verifies the sealed Game Design receipt and authenticated Game Session STARTING allocation, then commits typed intake, canonical association and fixed-preset materialization at PREPARING epoch 1 and row version 0. Fixture bootstrap skips all seeding with a diagnostic; activation, holds and first OPEN remain unavailable. Earlier binding/ACTIVE replay and coordinator-driven hold execution are predecessor proof, not current fixture capability. | [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) | Bounded fixture PREPARING materialization is implemented with controlled native proof; 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. | @@ -163,7 +163,7 @@ These links add decision provenance only; they do not upgrade world runtime, lif - 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. - 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. -- The current run-owned Compose coordinator completes canonical Game Session STARTING allocation/readback only. World fixture bootstrap, prepare and activate remain unavailable before effects; materialization, activation, holds and first OPEN are explicit gaps. Earlier coordinator/hold implementation and proof are historical. 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) and [focused integration proof](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java). +- The current run-owned Compose coordinator completes canonical Game Session STARTING allocation/readback only. The separate World prepare RPC commits bounded fixed-preset PREPARING materialization with controlled native proof; fixture bootstrap, activation, holds and first OPEN remain unavailable. Earlier coordinator/hold implementation and proof are historical. 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) 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/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java index 78f80e9dae..97350d071b 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java @@ -717,7 +717,7 @@ void actualProducerStartingAndPreparingOwnersComposeOverThreeMutualTlsSockets( "SELECT count(*) AS count FROM flyway_schema_history " + "WHERE success AND type='SQL' AND version IS NOT NULL") .get("count", Long.class)) - .isEqualTo(75L); + .isEqualTo(76L); assertThat( worldDatabase .dsl() 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 index e35f0ad364..cdc40fa248 100644 --- 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 @@ -94,14 +94,19 @@ public static FixedPresetPlan plan( RunOwnedWorldLaunchEvidence evidence, WorldAuthoredSourceIntakeReceipt sourceReceipt, WorldAuthoredVersionIdentityReceipt versionReceipt) { - Objects.requireNonNull(evidence, "evidence").requireFixedGameSessionPeer(); + RunOwnedWorldLaunchEvidence 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 = evidence.sourceReceipt(); - var capability = evidence.capability(); - var descriptor = evidence.launchDescriptor(); - var gameSession = evidence.gameSessionAssociation(); + 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(); @@ -116,7 +121,7 @@ public static FixedPresetPlan plan( if (gameSession == null || !sourceReceipt.source().equals(fixture.sourceEvidence()) || !sourceReceipt.targetNamespace().equals(descriptor.targetNamespace()) - || !capability.worldManagementUriSan().equals(evidence.worldManagementUriSan()) + || !capability.worldManagementUriSan().equals(typedEvidence.worldManagementUriSan()) || !sourceReceipt.canonicalTenantId().equals(descriptor.canonicalTenantId()) || !sourceReceipt.worldSlug().equals(descriptor.worldSlug()) || !sourceReceipt.sourceOperationId().equals(descriptor.authoredWorldSourceOperationId()) @@ -147,7 +152,10 @@ public static FixedPresetPlan plan( || !fixture.fixturePolicySeal().operationId().toString().equals(capability.operationId()) || !gameSession.canonicalTenantId().equals(sourceReceipt.canonicalTenantId()) || !gameSession.fixturePolicySeal().equals(fixture.fixturePolicySeal()) - || !fixture.fixturePolicySeal().evidenceDigest().equals(evidence.fixtureProvenanceDigest()) + || !fixture + .fixturePolicySeal() + .evidenceDigest() + .equals(typedEvidence.fixtureProvenanceDigest()) || !gameSession .request() .expectedFixturePolicyEvidenceDigest() @@ -184,8 +192,8 @@ public static FixedPresetPlan plan( descriptor.publishedReleaseBundleRef(), descriptor.versionStateEpoch(), descriptor.remapSetIdPresent() ? descriptor.remapSetId() : null); - evidence.requireMatches(originalRequest); - String lifecycleBindingDigest = "sha256:" + evidence.bindingDigest(originalRequest, 1L); + typedEvidence.requireMatches(originalRequest); + String lifecycleBindingDigest = "sha256:" + typedEvidence.bindingDigest(originalRequest, 1L); String gameSessionResponseBytesDigest = sha256Raw( CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toFixtureResponse(gameSession) 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 d2a4c8341e..730a3d6433 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 @@ -239,6 +239,10 @@ public WorldAuthoredSourceIntakeReceipt intakeRunOwnedFixture( 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, 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 index e9aee52837..4be3824534 100644 --- 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 @@ -164,6 +164,41 @@ 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(); } 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/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java index 78014da21c..3283b4445f 100644 --- 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 @@ -317,6 +317,12 @@ class RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest { 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( "V1007.1__world_restore_stable_legacy_update_fastpath.sql", "56efb5521ba235ce413caa8ed6ce54dad2c169064f9478e1d31bf1dd869743ed"), @@ -393,10 +399,10 @@ void freshDefaultHistoryRetainsLiteralProtectedArtifactsAndNumericFrontier() thr .as("literal migration %s", artifact.getKey()) .isEqualTo(artifact.getValue()); } - assertThat(versions(dsl)).hasSize(75); + assertThat(versions(dsl)).hasSize(76); assertThat(versions(dsl).subList(34, 40)) .containsExactly("1003", "1004", "1005", "1006", "1007", "1007.1"); - assertThat(versions(dsl).subList(40, 75)).containsExactlyElementsOf(remainingVersions()); + assertThat(versions(dsl).subList(40, 76)).containsExactlyElementsOf(remainingVersions()); var configured = migration(dataSource("world_management_service"), "world_management_service", null); assertThat(configured.getConfiguration().isOutOfOrder()).isFalse(); @@ -728,7 +734,7 @@ void fixturePreparingCannotActivateAcquireHoldsPlaceActorsOrReuseConsumedManifes } @Test - void installed34ThroughParent40ToFull75RetainsOriginalRowsXminAndStableLegacyUpdates() + void installed34ThroughParent40ToLatest76RetainsRowsXminAndStableLegacyUpdates() throws Exception { String schema = "world_fixture_upgrade_" + UUID.randomUUID().toString().replace("-", ""); var source = dataSource(schema); @@ -835,18 +841,97 @@ void installed34ThroughParent40ToFull75RetainsOriginalRowsXminAndStableLegacyUpd 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 prove V1042 retains every stored row image and xmin. + 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); + + var rowsAt75 = new LinkedHashMap<>(allRows(connection)); + rowsAt75.remove(HISTORY); + var historyAt75 = history(connection); var full = migration(source, schema, null); full.migrate(); full.validate(); assertThat(full.getConfiguration().isOutOfOrder()).isFalse(); - assertThat(versions(connection)).hasSize(75); - assertThat(versions(connection).subList(40, 75)) + assertThat(versions(connection)).hasSize(76); + assertThat(versions(connection).subList(40, 76)) .containsExactlyElementsOf(remainingVersions()); assertThat(history(connection).subList(0, 40)).isEqualTo(parentHistory); + assertThat(history(connection).subList(0, 75)).isEqualTo(historyAt75); for (var entry : originalColumns.entrySet()) assertThat(retainedRows(connection, schema, entry.getKey(), entry.getValue())) .as("all original values and xmin for %s", entry.getKey()) - .isEqualTo(originalRows.get(entry.getKey())); + .containsAll(originalRows.get(entry.getKey())); + var rowsAt76 = new LinkedHashMap<>(allRows(connection)); + rowsAt76.remove(HISTORY); + assertThat(rowsAt76).as("all retained row values and xmin across V1042").isEqualTo(rowsAt75); assertThat(sourceOwner.read("dev", intakeRequest)).contains(intake); assertThat( versionOwner.readByCanonicalVersion( @@ -871,7 +956,9 @@ void installed34ThroughParent40ToFull75RetainsOriginalRowsXminAndStableLegacyUpd .isNull(); assertThat( connection - .fetchSingle("SELECT count(*) FROM world_canonical_instance_association") + .fetchSingle( + "SELECT count(*) FROM world_canonical_instance_association WHERE world_instance_id = ?", + worldId) .get(0, Long.class)) .isZero(); assertThat( @@ -882,7 +969,7 @@ void installed34ThroughParent40ToFull75RetainsOriginalRowsXminAndStableLegacyUpd .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 original row images and xmin. + // 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); @@ -905,9 +992,11 @@ void installed34ThroughParent40ToFull75RetainsOriginalRowsXminAndStableLegacyUpd first.rollback(); } } - for (var entry : originalColumns.entrySet()) - assertThat(retainedRows(connection, schema, entry.getKey(), entry.getValue())) - .isEqualTo(originalRows.get(entry.getKey())); + var rowsAfterLegacyRollback = new LinkedHashMap<>(allRows(connection)); + rowsAfterLegacyRollback.remove(HISTORY); + assertThat(rowsAfterLegacyRollback) + .as("all retained row values and xmin after legacy rollback") + .isEqualTo(rowsAt76); // 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 { @@ -915,6 +1004,56 @@ void installed34ThroughParent40ToFull75RetainsOriginalRowsXminAndStableLegacyUpd } } + @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(); @@ -1593,8 +1732,13 @@ private static List history(DSLContext connection) { } private static List remainingVersions() { + return remainingVersionsThrough(1042); + } + + private static List remainingVersionsThrough(int latestWorldVersion) { List versions = new ArrayList<>(List.of("1008", "1009", "1009.1")); - for (int version = 1010; version <= 1041; version++) versions.add(Integer.toString(version)); + for (int version = 1010; version <= latestWorldVersion; version++) + versions.add(Integer.toString(version)); return List.copyOf(versions); } @@ -1631,6 +1775,55 @@ 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); 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..f66888d401 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesTest.java @@ -0,0 +1,130 @@ +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.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 rejectsResolvedScriptPatchOverrideAtInitialPlanBeforeMaterialization() { + assertOverrideRejected(true, false); + } + + @Test + void rejectsRemapSetOverrideAtInitialPlanBeforeMaterialization() { + assertOverrideRejected(false, true); + } + + private static void assertOverrideRejected( + boolean scriptPatchVersionPresent, boolean remapSetIdPresent) { + RunOwnedWorldLaunchEvidence evidence = + RunOwnedWorldLaunchEvidenceTestFixtures.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( + RunOwnedWorldLaunchEvidence 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( + RunOwnedWorldLaunchEvidence 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(RunOwnedWorldLaunchEvidence 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/data/RunOwnedWorldLaunchEvidenceTestFixtures.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceTestFixtures.java index fe79bb86b5..b329bb91e8 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceTestFixtures.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceTestFixtures.java @@ -44,6 +44,11 @@ private static String controlledClaimDigest() { } public static RunOwnedWorldLaunchEvidence create() { + return createWithDescriptorOverrides(false, false); + } + + public static RunOwnedWorldLaunchEvidence createWithDescriptorOverrides( + boolean scriptPatchVersionPresent, boolean remapSetIdPresent) { UUID registrationId = UUID.fromString(OPERATION_ID); UUID sourceOperationId = UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"); UUID canonicalTenantId = UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6d"); @@ -100,15 +105,15 @@ public static RunOwnedWorldLaunchEvidence create() { descriptorRequest, "launch-descriptor-fixture-11", 11L, - false, - null, + scriptPatchVersionPresent, + scriptPatchVersionPresent ? "script-patch-fixture-11" : null, "{}", "genrev-11", 77L, 77L, RELEASE_REF, - false, - null); + remapSetIdPresent, + remapSetIdPresent ? "remap-set-fixture-11" : null); String manifestHash = "sha256:" + "c".repeat(64); var bundle = PublishedReleaseBundle.newBuilder() 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 dc643daeac..c483874b59 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 @@ -178,6 +178,30 @@ void fixtureIntakeDeniesChangedRemoteSourceBeforeSql() { assertThat(transactionManager.startedWith).isNull(); } + @Test + void fixtureIntakeDeniesNullOwnerReceiptBeforeIndependentReadback() { + RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.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() { RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.create(); 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..0831ecc3fe --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationTest.java @@ -0,0 +1,183 @@ +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.RunOwnedWorldLaunchEvidence; +import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceTestFixtures; +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() { + RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.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) {} +} From 8a14a3c5b662b391fd93bf92c8f04c3088170415 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:42:28 +1300 Subject: [PATCH 06/45] Record qualified H1 proof scopes and shell failure propagation --- design/project-management/ai-observations.md | 5 +++++ .../implementation-tracking/world-runtime-and-movement.md | 4 ++++ 2 files changed, 9 insertions(+) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 451310ce51..bf73f3688b 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -281,3 +281,8 @@ Entry format: - Context: the TLS certificate watcher callback-failure test signalled its first attempt before the watcher recorded an unhealthy state. A successful retry could restore health before the test observed that state. - Expected pattern: gate the successful test callback until the existing unhealthy-state and aggregate-health assertions finish, release the gate in `finally`, then verify retry and recovered health. Preserve the production retry policy and every failure/recovery assertion. - Current status: the test-only latch correction passed the full 486-case Common unit suite and static checks. The separate PostgreSQL refusal and cleanup chronology remains unexplained under the existing local PostgreSQL availability observation; later passing proof does not identify that cause. + +- 2026-10-14: Use explicit shell failure propagation for dependent proof and publication steps. + - Observation: a multiline Bash execution continued to stage and commit after an auxiliary Python count assertion failed because the shell did not enable `errexit`. The actual gate passed 11 PostgreSQL cases; the failed assertion used a preliminary count of 10. The committed code remained qualified, but the command sequence did not enforce its intended dependency. + - Guidance: use `set -euo pipefail` or separate sequential tool calls when a proof assertion must succeed before staging, committing or publishing. Read actual result counts before pinning them; an overall shell exit code can otherwise hide an earlier failure. + - Current status: the [#3211](https://github.com/benhook1013/FireMUD/pull/3211) result was checked against the actual XML, corrected to 11 passing cases, and subsequent dependent commands use explicit failure propagation. 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 d4fa653834..ec902d90c2 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -16,6 +16,10 @@ The local follow-on implements typed source intake and Version association after ### 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. + +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. The final 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 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. From e54c18a51db691311038c687bc3cd0da66d1ae9a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 07:18:04 +1300 Subject: [PATCH 07/45] fix(world): qualify terminal lookup and strengthen fixture proof --- ...ame-authoring-publishing-and-activation.md | 2 +- .../world-runtime-and-movement.md | 2 +- ...anonicalInstanceAssociationRepository.java | 6 +- ...orld_execution_terminal_service_schema.sql | 26 ++ ...resetResourcesPostgresIntegrationTest.java | 24 +- ...TerminalSchemaPostgresIntegrationTest.java | 368 ++++++++++++++++++ ...edGraphCapturePostgresIntegrationTest.java | 120 +++++- ...rldAuthoredVersionIdentityServiceTest.java | 91 ++++- 8 files changed, 593 insertions(+), 46 deletions(-) create mode 100644 services/world-management-service/src/main/resources/db/migration/V1042.1__world_execution_terminal_service_schema.sql create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionTerminalSchemaPostgresIntegrationTest.java 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 6934743b27..0141983f7c 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 @@ -20,7 +20,7 @@ After the corrected readiness child `7ab19d077f021b044b2d45409d892324c6204a48` r After the qualified readiness-child carry at `f9e62a9b99850dc9cb526635e416f25e91f0e908`, the local receiving merge `a5f76d8cfa2092f01ccfe6ad0641878b8adc362b` passes all 515 freshly executed Game Design unit cases and 142 freshly executed native integrations, with formatting, static and documentation checks. The three-service native composition includes the current shared creation/source provenance comparison and real committed Game Session/World owners; controlled test capabilities and PKI remain its upstream boundary. This proof does not qualify deployed claimed Compose startup/restart, genuine Account authority or alternate already-applied Game Session migration bytes. -The local World follow-on registers default-off, operation-scoped wrappers around the existing Game Design 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. Whole unit proof retains 510 passing results from their earlier fresh execution on unchanged production inputs. The complete native suite passes 142 freshly executed PostgreSQL-backed cases, including 22 fixture cases and actual GDS producer → persisted GS `STARTING` → World `PREPARING` over three production mTLS handlers with unchanged owner rows, receipt bytes and `xmin` on retry and reconstruction. The fixed read adapters are registered in a real managed annotation context with actual producer owners; complete Spring Boot and packaged fresh/restart remain unqualified. The final native parent-file enumeration correction passes nine fresh storage-upgrade cases, formatting and all required static checks; the other native postimages retain their complete preceding execution attribution. This does not close any genuine Gameplay handoff. +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 receiving Game Design cut, 510 unit results retain their earlier fresh execution on unchanged production inputs, while 142 native PostgreSQL-backed cases execute freshly, including 22 fixture cases and the actual producer → persisted Game Session `STARTING` → World `PREPARING` composition across three production mTLS handlers. The fixed read adapters are registered in a real managed annotation context with their actual producer owners. The final native parent-file enumeration correction passes nine fresh storage-upgrade cases, formatting and required static checks; the other native postimages retain their preceding execution attribution. The shared World PREPARING implementation and proof are maintained by [World Runtime and Movement](./world-runtime-and-movement.md#fixed-fixture-preparing-owner-preparation). Complete Spring Boot and packaged fresh/restart remain unqualified, and no genuine Gameplay handoff is closed. ### Closed fixture policy producer 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 ec902d90c2..b24a207cac 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -76,7 +76,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 run-owned coordinator completes Game Session STARTING allocation and readback only. Earlier Compose-driven holds, preparing-epoch binding and ACTIVE replay belong to predecessor evidence. The synchronous World prepare RPC consumes the bounded authenticated Game Session read and materializes the sealed fixed preset at PREPARING epoch 1 and row version 0, with controlled native production-handler proof. Fixture bootstrap skips seeding; activation, holds and first OPEN remain unavailable, and claimed packaged runtime and genuine owner handoffs remain unqualified. 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 current run-owned fixture prepare RPC verifies the sealed Game Design receipt and authenticated Game Session STARTING allocation, then commits typed intake, canonical association and fixed-preset materialization at PREPARING epoch 1 and row version 0. Fixture bootstrap skips all seeding with a diagnostic; activation, holds and first OPEN remain unavailable. Earlier binding/ACTIVE replay and coordinator-driven hold execution are predecessor proof, not current fixture capability. | [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) | Bounded fixture PREPARING materialization is implemented with controlled native proof; 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.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 run-owned coordinator completes Game Session STARTING allocation and readback only. Earlier Compose-driven holds, preparing-epoch binding and ACTIVE replay belong to predecessor evidence. The synchronous World prepare RPC consumes the bounded authenticated Game Session read and materializes the sealed fixed preset at PREPARING epoch 1 and row version 0, with controlled native production-handler proof. Fixture bootstrap skips seeding; activation, holds and first OPEN remain unavailable, and claimed packaged runtime and genuine owner handoffs remain unqualified. 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 current run-owned fixture prepare RPC verifies the sealed Game Design receipt and authenticated Game Session STARTING allocation, then commits typed intake, canonical association and fixed-preset materialization at PREPARING epoch 1 and row version 0. Fixture bootstrap skips all seeding with a diagnostic; activation, holds and first OPEN remain unavailable. Earlier binding/ACTIVE replay and coordinator-driven hold execution are predecessor proof, not current fixture capability. | [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); [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); [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); [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 is implemented with controlled native proof; 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. | 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 index 6ca09ed5c0..df274a7f92 100644 --- 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 @@ -578,11 +578,7 @@ public WorldCanonicalInstanceAssociation allocateRunOwnedFixtureInOwnerTransacti String preparationInputDigest = "sha256:" + fixtureBindingSha256; byte[] associationResponseBytes = CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toFixtureResponse(gs).toByteArray(); - String runtimeFlagsJson = - gameSessionRequest.runtimeFlagsJson() == null - || gameSessionRequest.runtimeFlagsJson().isBlank() - ? "{}" - : gameSessionRequest.runtimeFlagsJson(); + String runtimeFlagsJson = descriptor.runtimeFlagsJson(); WorldCanonicalInstanceAssociation.CanonicalIdentity identity = new WorldCanonicalInstanceAssociation.CanonicalIdentity( 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/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 index 3283b4445f..3ee10747ae 100644 --- 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 @@ -399,10 +399,10 @@ void freshDefaultHistoryRetainsLiteralProtectedArtifactsAndNumericFrontier() thr .as("literal migration %s", artifact.getKey()) .isEqualTo(artifact.getValue()); } - assertThat(versions(dsl)).hasSize(76); + assertThat(versions(dsl)).hasSize(77); assertThat(versions(dsl).subList(34, 40)) .containsExactly("1003", "1004", "1005", "1006", "1007", "1007.1"); - assertThat(versions(dsl).subList(40, 76)).containsExactlyElementsOf(remainingVersions()); + assertThat(versions(dsl).subList(40, 77)).containsExactlyElementsOf(remainingVersions()); var configured = migration(dataSource("world_management_service"), "world_management_service", null); assertThat(configured.getConfiguration().isOutOfOrder()).isFalse(); @@ -734,7 +734,7 @@ void fixturePreparingCannotActivateAcquireHoldsPlaceActorsOrReuseConsumedManifes } @Test - void installed34ThroughParent40ToLatest76RetainsRowsXminAndStableLegacyUpdates() + void installed34ThroughParent40ToLatest77RetainsRowsXminAndStableLegacyUpdates() throws Exception { String schema = "world_fixture_upgrade_" + UUID.randomUUID().toString().replace("-", ""); var source = dataSource(schema); @@ -920,8 +920,8 @@ void installed34ThroughParent40ToLatest76RetainsRowsXminAndStableLegacyUpdates() full.migrate(); full.validate(); assertThat(full.getConfiguration().isOutOfOrder()).isFalse(); - assertThat(versions(connection)).hasSize(76); - assertThat(versions(connection).subList(40, 76)) + assertThat(versions(connection)).hasSize(77); + assertThat(versions(connection).subList(40, 77)) .containsExactlyElementsOf(remainingVersions()); assertThat(history(connection).subList(0, 40)).isEqualTo(parentHistory); assertThat(history(connection).subList(0, 75)).isEqualTo(historyAt75); @@ -929,9 +929,11 @@ void installed34ThroughParent40ToLatest76RetainsRowsXminAndStableLegacyUpdates() assertThat(retainedRows(connection, schema, entry.getKey(), entry.getValue())) .as("all original values and xmin for %s", entry.getKey()) .containsAll(originalRows.get(entry.getKey())); - var rowsAt76 = new LinkedHashMap<>(allRows(connection)); - rowsAt76.remove(HISTORY); - assertThat(rowsAt76).as("all retained row values and xmin across V1042").isEqualTo(rowsAt75); + var rowsAt77 = new LinkedHashMap<>(allRows(connection)); + rowsAt77.remove(HISTORY); + assertThat(rowsAt77) + .as("all retained row values and xmin across V1042.1") + .isEqualTo(rowsAt75); assertThat(sourceOwner.read("dev", intakeRequest)).contains(intake); assertThat( versionOwner.readByCanonicalVersion( @@ -996,7 +998,7 @@ void installed34ThroughParent40ToLatest76RetainsRowsXminAndStableLegacyUpdates() rowsAfterLegacyRollback.remove(HISTORY); assertThat(rowsAfterLegacyRollback) .as("all retained row values and xmin after legacy rollback") - .isEqualTo(rowsAt76); + .isEqualTo(rowsAt77); // 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 { @@ -1732,7 +1734,9 @@ private static List history(DSLContext connection) { } private static List remainingVersions() { - return remainingVersionsThrough(1042); + List versions = new ArrayList<>(remainingVersionsThrough(1042)); + versions.add("1042.1"); + return List.copyOf(versions); } private static List remainingVersionsThrough(int latestWorldVersion) { 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..c6cb8e69c3 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionTerminalSchemaPostgresIntegrationTest.java @@ -0,0 +1,368 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +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.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.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 HISTORY = "flyway_schema_history_world_management_service"; + 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 = + "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 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, null, 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 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(); + } + + 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 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"); + } + + 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/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java index 4117f7d983..3c6154bc7f 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 @@ -66,10 +66,11 @@ * 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. - * Positive component storage and the 40-migration endpoint are explicitly historical at 1007.1; the - * retained schema-2 snapshot separately upgrades through the current default frontier. These - * historical component cases do not qualify current Account permission or genuine Human authority. - * 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") @@ -650,18 +651,15 @@ void historicalGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoin 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"); try { // Controlled permission-unverified component storage at the historical guarded frontier. // Later Account/APPLIED owners retain their default-current denial requirements. - historicalGuardedStage( - 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")) - .migrate(); + historicalGuardedStage(source, schema, worldLocation, sagaLocation).migrate(); assertCanonicalFrozenMutationTriggerBindings(dsl, schema); var upstream = controlledSource(); var intake = @@ -1048,6 +1046,102 @@ void historicalGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoin dsl.fetch("SELECT to_jsonb(t)::text FROM world_topology_draft_commit t") .getValues(0, String.class)) .isEqualTo(rowsBefore); + + // Historical storage proof above is retained as such. Repeat the actual naked-write, + // schema-2 capture, wrong-checkpoint capture, and missing-owner-history denials after the + // complete current World/Saga migration frontier. + Flyway currentFrontier = flyway(source, schema, worldLocation, sagaLocation); + currentFrontier.migrate(); + currentFrontier.validate(); + assertThat( + dsl.fetchSingle( + "SELECT version FROM " + + HISTORY + + " WHERE success AND version IS NOT NULL ORDER BY installed_rank DESC LIMIT 1") + .get(0, String.class)) + .isEqualTo("1042.1"); + // 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")); + + // The retained current DTO accepts only schema 3; its altered checkpoint is therefore + // rejected at the current schema-4 boundary before a schema-4 checkpoint comparison. + 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()); + assertThatThrownBy( + () -> + insertCanonicalFrozenCandidate( + dsl, + plan, + currentWrongCheckpointCapture, + stored, + mapper.writeValueAsString(currentWrongCheckpointCapture), + 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")); + 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"); } 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 1446c229a7..126ef9d385 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 @@ -355,6 +355,9 @@ void fixtureVersionRejectsChangedRetainedSnapshotOnExactRetryWithoutRemoteOrSql( 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(), @@ -362,23 +365,79 @@ void fixtureVersionRejectsChangedRetainedSnapshotOnExactRetryWithoutRemoteOrSql( source.operationId(), source.evidenceDigest())) .thenReturn(Optional.of(intake)); - var request = - new AuthoredWorldVersionStateEvidence.Request( - 1, + 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", - READ_REQUEST, - source.canonicalTenantId(), - source.worldSlug(), - source.operationId(), - source.evidenceDigest(), - evidence.launchDescriptor().versionId()); + "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 changedState : List.of( VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED)) { var changed = AuthoredWorldVersionStateEvidence.create( - request, + originalState.get().request(), source, canonicalVersion, changedState, @@ -386,9 +445,7 @@ void fixtureVersionRejectsChangedRetainedSnapshotOnExactRetryWithoutRemoteOrSql( + (changedState == VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED ? 1L : 0L)); - when(repository.readByCanonicalVersion( - "dev", source.canonicalTenantId(), source.worldSlug(), canonicalVersion)) - .thenReturn(Optional.of(identityReceipt(intake, changed, 101L))); + retained.set(identityReceipt(intake, changed, 101L)); assertThatThrownBy( () -> withFixturePeer( @@ -399,9 +456,9 @@ void fixtureVersionRejectsChangedRetainedSnapshotOnExactRetryWithoutRemoteOrSql( .isInstanceOf( WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException.class); } - verifyNoInteractions(versionStateClient); - verify(repository, never()).acceptFresh(any(), any()); - assertThat(transactionManager.startedWith).isNull(); + verify(versionStateClient, times(1)).read(any()); + verify(repository, times(1)).acceptFresh(any(), any()); + assertThat(transactionManager.transactionStarts).isEqualTo(transactionStartsAfterAcceptance); } @Test @@ -956,6 +1013,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; @@ -963,6 +1021,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( From 67cca1cc75b016bb1a5d29eb70dc1d80989212ad Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 07:23:39 +1300 Subject: [PATCH 08/45] test(gamedesign): derive composed World migration count --- .../data/TestDataSeederIntegrationTest.java | 46 +++++++++++-------- 1 file changed, 27 insertions(+), 19 deletions(-) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java index 97350d071b..fc09fa3a6a 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java @@ -717,7 +717,7 @@ void actualProducerStartingAndPreparingOwnersComposeOverThreeMutualTlsSockets( "SELECT count(*) AS count FROM flyway_schema_history " + "WHERE success AND type='SQL' AND version IS NOT NULL") .get("count", Long.class)) - .isEqualTo(76L); + .isEqualTo(worldDatabase.versionedSqlMigrationCount()); assertThat( worldDatabase .dsl() @@ -1269,28 +1269,36 @@ private ComposedOwnerDatabase composedOwnerDatabase( container.getJdbcUrl(), container.getUsername(), container.getPassword()); dataSource.setDriverClassName("org.postgresql.Driver"); dataSource.setSchema(schema); - 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() - .migrate(); + 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)); + new DataSourceTransactionManager(dataSource), + versionedSqlMigrationCount); } - private record ComposedOwnerDatabase(DSLContext dsl, PlatformTransactionManager transactions) {} + private record ComposedOwnerDatabase( + DSLContext dsl, PlatformTransactionManager transactions, long versionedSqlMigrationCount) {} private static GrpcChannelFactory composedChannelFactory( java.util.List channels) { From b1f11cc15d270e6b373825b399b9fbbec72273a9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 08:19:57 +1300 Subject: [PATCH 09/45] Fix fixed-preset read transaction modes and configuration proof --- .../runtime-and-data.md | 2 + .../data/TestDataSeederIntegrationTest.java | 50 +++++ ...aunchDescriptorServiceIntegrationTest.java | 42 +++- ...2__world_fixed_preset_read_transaction.sql | 34 ++++ ...resetResourcesPostgresIntegrationTest.java | 189 +++++++++++++++--- ...TerminalSchemaPostgresIntegrationTest.java | 4 +- ...edGraphCapturePostgresIntegrationTest.java | 8 +- 7 files changed, 295 insertions(+), 34 deletions(-) create mode 100644 services/world-management-service/src/main/resources/db/migration/V1042.2__world_fixed_preset_read_transaction.sql 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 6066931183..67853508c0 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -26,6 +26,8 @@ The fixed fixture uses existing World source intake, Version identity, canonical 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. 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. These storage checks do not grant Human protection, fixture activation or hold authority. World lifecycle transition, hold acquire/finalize, initial placement and player-admission owners reject the fixture variant before effects. 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. ### Authored-world source retention diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java index fc09fa3a6a..96bdc6922e 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java @@ -108,6 +108,7 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Import; import org.springframework.core.Ordered; +import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -131,6 +132,7 @@ 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", @@ -192,6 +194,7 @@ static void configure(DynamicPropertyRegistry registry) { private net.firedevops.firemud.gamedesign.data.RunOwnedFixturePolicyProducer fixturePolicy; @Autowired private Flyway flyway; + @Autowired private ConfigurableEnvironment environment; @MockitoSpyBean private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; @Autowired private GameRepository gameRepository; @@ -696,6 +699,53 @@ private record FixedReadLeaf(Path certificate, Path privateKey) {} @Test void actualProducerStartingAndPreparingOwnersComposeOverThreeMutualTlsSockets( @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[] {})); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java index 1a91814878..2649cdb0e7 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.nio.file.Path; import java.sql.SQLException; import java.time.LocalDateTime; import java.util.Map; @@ -48,6 +49,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Import; +import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.jdbc.core.JdbcTemplate; @@ -69,6 +71,7 @@ classes = GameDesignServiceApplication.class, properties = { "spring.profiles.active=test", + "spring.config.import=file:src/main/resources/application.yml", "firemud.auth.jwt-secret=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "firemud.grpc.plaintext=true", "firemud.grpc.workload-namespace=launch-descriptor-test", @@ -115,9 +118,46 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private PlatformTransactionManager transactionManager; @Autowired private DSLContext dsl; @Autowired private JdbcTemplate jdbcTemplate; + @Autowired private ConfigurableEnvironment environment; @Test - void legacyNumericResolveFailsClosedWithoutPersistingDescriptor() { + void legacyNumericResolveFailsClosedWithoutPersistingDescriptor() 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); + assertThatThrownBy( () -> legacyLaunchDescriptorService.resolveLaunchDescriptor( 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/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 index 3ee10747ae..5ba7d6f842 100644 --- 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 @@ -399,14 +399,16 @@ void freshDefaultHistoryRetainsLiteralProtectedArtifactsAndNumericFrontier() thr .as("literal migration %s", artifact.getKey()) .isEqualTo(artifact.getValue()); } - assertThat(versions(dsl)).hasSize(77); - assertThat(versions(dsl).subList(34, 40)) - .containsExactly("1003", "1004", "1005", "1006", "1007", "1007.1"); - assertThat(versions(dsl).subList(40, 77)).containsExactlyElementsOf(remainingVersions()); 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 @@ -734,7 +736,7 @@ void fixturePreparingCannotActivateAcquireHoldsPlaceActorsOrReuseConsumedManifes } @Test - void installed34ThroughParent40ToLatest77RetainsRowsXminAndStableLegacyUpdates() + void installed34ThroughParent40ToDefaultFrontierRetainsRowsXminAndStableLegacyUpdates() throws Exception { String schema = "world_fixture_upgrade_" + UUID.randomUUID().toString().replace("-", ""); var source = dataSource(schema); @@ -913,27 +915,28 @@ void installed34ThroughParent40ToLatest77RetainsRowsXminAndStableLegacyUpdates() .get(0, Long.class)) .isEqualTo(1L); - var rowsAt75 = new LinkedHashMap<>(allRows(connection)); - rowsAt75.remove(HISTORY); - var historyAt75 = history(connection); + var retainedRowsAtV1042 = new LinkedHashMap<>(allRows(connection)); + retainedRowsAtV1042.remove(HISTORY); + var historyAtV1042 = history(connection); var full = migration(source, schema, null); full.migrate(); full.validate(); assertThat(full.getConfiguration().isOutOfOrder()).isFalse(); - assertThat(versions(connection)).hasSize(77); - assertThat(versions(connection).subList(40, 77)) + 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, 75)).isEqualTo(historyAt75); + assertThat(history(connection).subList(0, 75)).isEqualTo(historyAtV1042); 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 rowsAt77 = new LinkedHashMap<>(allRows(connection)); - rowsAt77.remove(HISTORY); - assertThat(rowsAt77) - .as("all retained row values and xmin across V1042.1") - .isEqualTo(rowsAt75); + var retainedRowsAtDefaultFrontier = new LinkedHashMap<>(allRows(connection)); + retainedRowsAtDefaultFrontier.remove(HISTORY); + assertThat(retainedRowsAtDefaultFrontier) + .as("all retained row values and xmin from V1042 through the default frontier") + .isEqualTo(retainedRowsAtV1042); assertThat(sourceOwner.read("dev", intakeRequest)).contains(intake); assertThat( versionOwner.readByCanonicalVersion( @@ -998,7 +1001,7 @@ void installed34ThroughParent40ToLatest77RetainsRowsXminAndStableLegacyUpdates() rowsAfterLegacyRollback.remove(HISTORY); assertThat(rowsAfterLegacyRollback) .as("all retained row values and xmin after legacy rollback") - .isEqualTo(rowsAt77); + .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 { @@ -1373,14 +1376,91 @@ void realWorldOwnersMaterializeSixFixtureMappingsAndReplayExactCommittedBytes() assertThat(result.zoneCount()).isEqualTo(1); assertThat(result.roomCount()).isEqualTo(2); assertThat(result.exitCount()).isEqualTo(2); - TransactionTemplate committedRead = new TransactionTemplate(transactionManager); - committedRead.setReadOnly(true); - committedRead.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); - RunOwnedWorldFixedPresetResources.MaterializedFixedPreset committedResult = - committedRead.execute( - status -> - RunOwnedWorldFixedPresetResources.readCommitted(dsl, association, source, version)); - assertThat(committedResult).isEqualTo(result); + 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); + assertNoPendingManifests(worldId); assertThat( scalarLong( "SELECT count(*) FROM world_authored_topology_identity WHERE fixture_world_instance_id = ? " @@ -1736,9 +1816,16 @@ private static List history(DSLContext connection) { private static List remainingVersions() { List versions = new ArrayList<>(remainingVersionsThrough(1042)); versions.add("1042.1"); + versions.add("1042.2"); 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++) @@ -1834,6 +1921,58 @@ private TransactionTemplate ownerTransaction() { 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 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( 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 index c6cb8e69c3..8aa523ed1a 100644 --- 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 @@ -93,7 +93,9 @@ void forwardRepairPreservesTerminalTriggerAndWorksWithoutWorldInCallerSearchPath .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("23514")); assertThat(executionRows(dsl, qualifiedExecutionTable)).isEmpty(); - Flyway current = flyway(source, schema, null, worldLocation, sagaLocation); + Flyway current = + flyway( + source, schema, MigrationVersion.fromVersion("1042.1"), worldLocation, sagaLocation); current.migrate(); current.validate(); assertThat(latestVersion(dsl)).isEqualTo("1042.1"); 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 3c6154bc7f..8b1281a7a2 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 @@ -1053,13 +1053,7 @@ void historicalGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoin Flyway currentFrontier = flyway(source, schema, worldLocation, sagaLocation); currentFrontier.migrate(); currentFrontier.validate(); - assertThat( - dsl.fetchSingle( - "SELECT version FROM " - + HISTORY - + " WHERE success AND version IS NOT NULL ORDER BY installed_rank DESC LIMIT 1") - .get(0, String.class)) - .isEqualTo("1042.1"); + 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. From 746bc5d76dfb5a1f2f400203388e98f52a2f0aac Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 08:48:23 +1300 Subject: [PATCH 10/45] Preserve fixture owner status and closed lifecycle mutation boundaries --- .../runtime-and-data.md | 2 +- ...RunOwnedFixtureOwnerReadAuthorization.java | 22 ++++- .../AuthoredWorldSourceReadGrpcService.java | 61 ++++++------- ...ureAuthoredWorldSourceReadGrpcService.java | 21 ++++- ...eAuthoredWorldVersionStateGrpcService.java | 22 ++++- ...AuthoredWorldOwnerReadGrpcServiceTest.java | 64 ++++++++++++++ .../RunOwnedWorldFixedPresetResources.java | 86 +++++++------------ .../WorldLifecycleCommandServiceImpl.java | 11 +++ ..._world_fixture_row_mutation_diagnostic.sql | 29 +++++++ ...resetResourcesPostgresIntegrationTest.java | 62 +++++++++++++ .../WorldLifecycleCommandServiceImplTest.java | 74 ++++++++++++++++ 11 files changed, 357 insertions(+), 97 deletions(-) create mode 100644 services/world-management-service/src/main/resources/db/migration/V1042.3__world_fixture_row_mutation_diagnostic.sql 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 67853508c0..1d832a2f70 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -28,7 +28,7 @@ The owner materializes the exact sealed fixed preset into one region, one zone, 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. 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. These storage checks do not grant Human protection, fixture activation or hold authority. World lifecycle transition, hold acquire/finalize, initial placement and player-admission owners reject the fixture variant before effects. 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. +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. 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. These storage checks do not grant Human protection, fixture activation or hold authority. Later fixture World row mutations, lifecycle transitions, hold acquire/finalize, initial placement and player-admission owners reject the fixture variant before effects. 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. ### Authored-world source retention diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerReadAuthorization.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerReadAuthorization.java index 3ea0aee893..b4461d154c 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerReadAuthorization.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerReadAuthorization.java @@ -3,6 +3,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.nio.file.Path; import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateGrpcCodec; import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; @@ -74,7 +75,12 @@ public RunOwnedFixtureOwnerReadAuthorization( public SourceReceipt authorizeSource(ResolveAuthoredWorldSourceRequest wire) { var trusted = authenticatedConfiguration(); SourceReceipt receipt = receipt(trusted); - var request = AuthoredWorldSourceGrpcCodec.fromReadRequest(namespace, wire); + final AuthoredWorldSourceGrpcCodec.ReadRequest request; + try { + request = AuthoredWorldSourceGrpcCodec.fromReadRequest(namespace, wire); + } catch (IllegalArgumentException invalidRequest) { + throw new RequestDecodingException(invalidRequest); + } var source = receipt.sourceEvidence(); if (!request.targetNamespace().equals(source.targetNamespace()) || !request.operationId().equals(source.operationId()) @@ -89,7 +95,12 @@ public SourceReceipt authorizeSource(ResolveAuthoredWorldSourceRequest wire) { public SourceReceipt authorizeVersion(GetAuthoredWorldVersionStateRequest wire) { var trusted = authenticatedConfiguration(); SourceReceipt receipt = receipt(trusted); - var request = AuthoredWorldVersionStateGrpcCodec.fromRequest(wire); + final AuthoredWorldVersionStateEvidence.Request request; + try { + request = AuthoredWorldVersionStateGrpcCodec.fromRequest(wire); + } catch (IllegalArgumentException invalidRequest) { + throw new RequestDecodingException(invalidRequest); + } var source = receipt.sourceEvidence(); if (!namespace.equals(request.targetNamespace()) || !request.canonicalTenantId().equals(source.canonicalTenantId()) @@ -156,4 +167,11 @@ private void qualifyOwners(TestDataSeeder.FixtureCapability trusted, SourceRecei throw new IllegalStateException("Fixed receipt policy seal differs from committed owner"); } } + + /** Marks only malformed wire requests; owner-side argument failures have different semantics. */ + public static final class RequestDecodingException extends IllegalArgumentException { + public RequestDecodingException(IllegalArgumentException cause) { + super("Fixture owner request could not be decoded", cause); + } + } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java index 9b01b0ca02..fb83d87fc8 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java @@ -13,8 +13,10 @@ import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.dao.TransientDataAccessException; +import org.springframework.transaction.TransactionException; /** Standalone exact authored-source owner read; deliberately not registered as a gRPC service. */ public final class AuthoredWorldSourceReadGrpcService @@ -70,40 +72,13 @@ public void resolveAuthoredWorldSource( .withDescription("Authored-world source evidence is incomplete or inconsistent") .asRuntimeException()); return; - } catch (DataAccessResourceFailureException - | TransientDataAccessException - | org.springframework.transaction.TransactionException exception) { - responseObserver.onError( - Status.UNAVAILABLE - .withDescription("Authored-world source evidence is temporarily unavailable") - .asRuntimeException()); - return; - } catch (org.springframework.dao.DataAccessException exception) { - Status.Code code = - hasConnectionFailureSqlState(exception) ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL; - responseObserver.onError( - Status.fromCode(code) - .withDescription( - code == Status.Code.UNAVAILABLE - ? "Authored-world source evidence is temporarily unavailable" - : "Authored-world source evidence could not be read") - .asRuntimeException()); - return; - } catch (org.jooq.exception.DataAccessException exception) { - Status.Code code = - hasConnectionFailureSqlState(exception) ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL; - responseObserver.onError( - Status.fromCode(code) - .withDescription( - code == Status.Code.UNAVAILABLE - ? "Authored-world source evidence is temporarily unavailable" - : "Authored-world source evidence could not be read") - .asRuntimeException()); - return; } catch (RuntimeException exception) { + Status storageStatus = storageFailureStatus(exception); responseObserver.onError( - Status.INTERNAL - .withDescription("Authored-world source evidence could not be read") + (storageStatus == null + ? Status.INTERNAL.withDescription( + "Authored-world source evidence could not be read") + : storageStatus) .asRuntimeException()); return; } @@ -129,6 +104,26 @@ public void resolveAuthoredWorldSource( responseObserver.onCompleted(); } + /** Returns the existing owner storage classification, or {@code null} for non-storage errors. */ + static Status storageFailureStatus(Throwable failure) { + if (failure instanceof DataAccessResourceFailureException + || failure instanceof TransientDataAccessException + || failure instanceof TransactionException) { + return Status.UNAVAILABLE.withDescription( + "Authored-world source evidence is temporarily unavailable"); + } + if (failure instanceof DataAccessException + || failure instanceof org.jooq.exception.DataAccessException) { + boolean connectionFailure = hasConnectionFailureSqlState(failure); + return Status.fromCode(connectionFailure ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL) + .withDescription( + connectionFailure + ? "Authored-world source evidence is temporarily unavailable" + : "Authored-world source evidence could not be read"); + } + return null; + } + private boolean isWorldManagementPeer() { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); return peer != null @@ -137,7 +132,7 @@ private boolean isWorldManagementPeer() { .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"); } - private static boolean hasConnectionFailureSqlState(Throwable failure) { + static boolean hasConnectionFailureSqlState(Throwable failure) { for (Throwable cause = failure; cause != null; cause = cause.getCause()) { if (cause instanceof SQLException exception) { String sqlState = exception.getSQLState(); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldSourceReadGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldSourceReadGrpcService.java index e422e83cef..58fce2e750 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldSourceReadGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldSourceReadGrpcService.java @@ -38,7 +38,12 @@ public void resolveAuthoredWorldSource( StreamObserver observer) { try { var receipt = authorization.authorizeSource(request); - var expected = AuthoredWorldSourceGrpcCodec.fromReadRequest(namespace, request); + final AuthoredWorldSourceGrpcCodec.ReadRequest expected; + try { + expected = AuthoredWorldSourceGrpcCodec.fromReadRequest(namespace, request); + } catch (IllegalArgumentException invalidRequest) { + throw new RunOwnedFixtureOwnerReadAuthorization.RequestDecodingException(invalidRequest); + } kernel.resolveAuthoredWorldSource( request, new StreamObserver<>() { @@ -77,15 +82,23 @@ public void onCompleted() { Status.PERMISSION_DENIED .withDescription("Fixed World fixture read denied") .asRuntimeException()); - } catch (IllegalArgumentException invalid) { + } catch (RunOwnedFixtureOwnerReadAuthorization.RequestDecodingException invalid) { observer.onError( Status.INVALID_ARGUMENT .withDescription("Closed fixture source request required") .asRuntimeException()); - } catch (RuntimeException unavailable) { + } catch (IllegalArgumentException invalid) { observer.onError( Status.FAILED_PRECONDITION - .withDescription("Committed fixture authority unavailable") + .withDescription("Committed fixture authority does not match the request") + .asRuntimeException()); + } catch (RuntimeException failure) { + Status storageStatus = AuthoredWorldSourceReadGrpcService.storageFailureStatus(failure); + observer.onError( + (storageStatus != null + ? storageStatus + : Status.FAILED_PRECONDITION.withDescription( + "Committed fixture authority unavailable")) .asRuntimeException()); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldVersionStateGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldVersionStateGrpcService.java index 4330c28d52..1e321cf2ea 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldVersionStateGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldVersionStateGrpcService.java @@ -3,6 +3,7 @@ import io.grpc.Status; import io.grpc.stub.StreamObserver; import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateGrpcCodec; import net.firedevops.firemud.gamedesign.data.RunOwnedFixtureOwnerReadAuthorization; import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; @@ -41,7 +42,12 @@ public void getAuthoredWorldVersionState( StreamObserver observer) { try { var receipt = authorization.authorizeVersion(request); - var expected = AuthoredWorldVersionStateGrpcCodec.fromRequest(request); + final AuthoredWorldVersionStateEvidence.Request expected; + try { + expected = AuthoredWorldVersionStateGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException invalidRequest) { + throw new RunOwnedFixtureOwnerReadAuthorization.RequestDecodingException(invalidRequest); + } kernel.getAuthoredWorldVersionState( request, new StreamObserver<>() { @@ -89,15 +95,23 @@ public void onCompleted() { Status.PERMISSION_DENIED .withDescription("Fixed World fixture read denied") .asRuntimeException()); - } catch (IllegalArgumentException invalid) { + } catch (RunOwnedFixtureOwnerReadAuthorization.RequestDecodingException invalid) { observer.onError( Status.INVALID_ARGUMENT .withDescription("Closed fixture Version request required") .asRuntimeException()); - } catch (RuntimeException unavailable) { + } catch (IllegalArgumentException invalid) { observer.onError( Status.FAILED_PRECONDITION - .withDescription("Committed fixture authority unavailable") + .withDescription("Committed fixture authority does not match the request") + .asRuntimeException()); + } catch (RuntimeException failure) { + Status storageStatus = AuthoredWorldSourceReadGrpcService.storageFailureStatus(failure); + observer.onError( + (storageStatus != null + ? storageStatus + : Status.FAILED_PRECONDITION.withDescription( + "Committed fixture authority unavailable")) .asRuntimeException()); } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java index e5c0b6f6f3..85365a5621 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java @@ -8,6 +8,7 @@ import io.grpc.Status; import io.grpc.stub.StreamObserver; +import java.sql.SQLException; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.gamedesign.data.RunOwnedFixtureOwnerReadAuthorization; import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; @@ -17,6 +18,10 @@ import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.dao.TransientDataAccessResourceException; +import org.springframework.transaction.CannotCreateTransactionException; import org.springframework.transaction.PlatformTransactionManager; class RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest { @@ -107,6 +112,65 @@ void authorizationDenialAndMissingPreexistingOwnerNeverReachKernelsOrPublishResp } } + @Test + void fixtureReadFailuresKeepRequestAuthorityAndStorageStatusesDistinct() { + for (var failure : + new FailureCase[] { + new FailureCase( + new SecurityException("controlled peer refusal"), Status.Code.PERMISSION_DENIED), + new FailureCase( + new IllegalArgumentException("owner selector mismatch"), + Status.Code.FAILED_PRECONDITION), + new FailureCase( + new RunOwnedFixtureOwnerReadAuthorization.RequestDecodingException( + new IllegalArgumentException("malformed wire request")), + Status.Code.INVALID_ARGUMENT), + new FailureCase( + new DataAccessResourceFailureException("storage unavailable"), + Status.Code.UNAVAILABLE), + new FailureCase( + new TransientDataAccessResourceException("transient storage failure"), + Status.Code.UNAVAILABLE), + new FailureCase( + new CannotCreateTransactionException("transaction unavailable"), + Status.Code.UNAVAILABLE), + new FailureCase( + new DataIntegrityViolationException( + "connection failed", new SQLException("connection lost", "08006")), + Status.Code.UNAVAILABLE), + new FailureCase( + new DataIntegrityViolationException( + "constraint rejected", new SQLException("duplicate key", "23505")), + Status.Code.INTERNAL) + }) { + var authorization = mock(RunOwnedFixtureOwnerReadAuthorization.class); + var repository = mock(GameAuthoredWorldSourceRepository.class); + var transactions = mock(PlatformTransactionManager.class); + when(authorization.authorizeSource(any())).thenThrow(failure.exception()); + when(authorization.authorizeVersion(any())).thenThrow(failure.exception()); + var sourceFailure = new AtomicReference(); + var versionFailure = new AtomicReference(); + new RunOwnedFixtureAuthoredWorldSourceReadGrpcService(authorization, repository, "dev") + .resolveAuthoredWorldSource( + ResolveAuthoredWorldSourceRequest.getDefaultInstance(), + refusingObserver(sourceFailure)); + new RunOwnedFixtureAuthoredWorldVersionStateGrpcService( + authorization, transactions, repository, "dev") + .getAuthoredWorldVersionState( + GetAuthoredWorldVersionStateRequest.getDefaultInstance(), + refusingObserver(versionFailure)); + assertThat(Status.fromThrowable(sourceFailure.get()).getCode()) + .isEqualTo(failure.expectedCode()); + assertThat(Status.fromThrowable(versionFailure.get()).getCode()) + .isEqualTo(failure.expectedCode()); + assertThat(Status.fromThrowable(sourceFailure.get()).getDescription()) + .doesNotContain("connection lost", "duplicate key", "storage unavailable"); + verifyNoInteractions(repository, transactions); + } + } + + private record FailureCase(RuntimeException exception, Status.Code expectedCode) {} + private static StreamObserver refusingObserver(AtomicReference failure) { return new StreamObserver<>() { @Override 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 index cdc40fa248..06c6ad810b 100644 --- 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 @@ -13,8 +13,10 @@ 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; @@ -199,58 +201,15 @@ public static FixedPresetPlan plan( CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toFixtureResponse(gameSession) .toByteArray()); - FixedPresetPlan unsealed = - new FixedPresetPlan( - PRESET_SCHEMA_VERSION, - PRESET_ID, - capability.operationId(), - capability.claimDigest(), - fixture.fixturePolicySeal().requestDigest(), - fixture.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)); + return sealPlan( + capability, + gameSession, + sourceReceipt, + versionReceipt, + descriptor, + bundle, + lifecycleBindingDigest, + gameSessionResponseBytesDigest); } /** Rebuilds the expected plan from immutable, typed World-owner receipts for restart reads. */ @@ -372,11 +331,32 @@ public static FixedPresetPlan plan( "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, - fixtureOperationId, + capability.operationId(), capability.claimDigest(), gameSession.fixturePolicySeal().requestDigest(), gameSession.fixturePolicySeal().evidenceDigest(), 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 460c958b61..bd49f210f8 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 @@ -821,7 +821,9 @@ private static IllegalArgumentException fixtureWritesUnavailable() { @Timed(value = "world.failPreparedInstance") public WorldInstanceLifecycleSnapshotDto failPreparedWorldInstance( long tenantId, long gameInstanceId, long expectedLifecycleEpoch, String reason) { + if (fixtureModeEnabled()) throw fixtureWritesUnavailable(); WorldInstance worldInstance = requireWorldInstance(tenantId, gameInstanceId); + rejectFixtureLifecycleMutation(worldInstance); requireLifecycleEpoch(worldInstance, expectedLifecycleEpoch); if (STATUS_FAILED_PRE_ACTIVATION.equals(worldInstance.getStatus())) { return snapshot(worldInstance); @@ -863,6 +865,7 @@ public WorldInstanceLifecycleSnapshotDto terminateWorldInstance( long expectedLifecycleEpoch, String terminationRequestId, String reason) { + if (fixtureModeEnabled()) throw fixtureWritesUnavailable(); if (terminationRequestId == null || terminationRequestId.isBlank()) { throw new IllegalArgumentException("INVALID_ARGUMENT: terminationRequestId is required"); } @@ -892,6 +895,7 @@ public WorldInstanceLifecycleSnapshotDto terminateWorldInstance( () -> { WorldInstance finalWorldInstance = requireLockedWorldInstance(tenantId, gameInstanceId); + rejectFixtureLifecycleMutation(finalWorldInstance); if (!terminationRequestId.equals(finalWorldInstance.getTerminationRequestId())) { throw new IllegalArgumentException( "INVALID_WORLD_INSTANCE_STATE: world instance termination request changed before finalization"); @@ -924,6 +928,7 @@ private WorldInstance beginOrResumeTermination( String terminationRequestId, String reason) { WorldInstance worldInstance = requireLockedWorldInstance(tenantId, gameInstanceId); + rejectFixtureLifecycleMutation(worldInstance); if (STATUS_TERMINATED.equals(worldInstance.getStatus())) { return worldInstance; } @@ -974,6 +979,12 @@ private void cleanupWorldRuntimeState(long tenantId, long gameInstanceId) { regionInstanceRepository.deleteByTenantIdAndGameInstanceId(tenantId, gameInstanceId); } + private static void rejectFixtureLifecycleMutation(WorldInstance worldInstance) { + if (worldInstance.getRunOwnedFixtureBindingSha256() != null) { + throw fixtureEvidenceUnavailable(); + } + } + private void validatePrepareRequest(PreparedWorldInstanceRequest request) { if (request.tenantId() <= 0L || request.gameInstanceId() <= 0L 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/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 index 5ba7d6f842..7541ecff3f 100644 --- 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 @@ -918,6 +918,11 @@ void installed34ThroughParent40ToDefaultFrontierRetainsRowsXminAndStableLegacyUp var retainedRowsAtV1042 = new LinkedHashMap<>(allRows(connection)); retainedRowsAtV1042.remove(HISTORY); var historyAtV1042 = history(connection); + String guardProcedure = schema + ".world_guard_canonical_activation_transition()"; + var originalGuardIdentity = + connection.fetchSingle( + "SELECT oid::text, prosecdef, proacl::text FROM pg_proc WHERE oid = to_regprocedure(?)", + guardProcedure); var full = migration(source, schema, null); full.migrate(); full.validate(); @@ -937,6 +942,62 @@ void installed34ThroughParent40ToDefaultFrontierRetainsRowsXminAndStableLegacyUp assertThat(retainedRowsAtDefaultFrontier) .as("all retained row values and xmin from V1042 through the default frontier") .isEqualTo(retainedRowsAtV1042); + assertThat( + connection.fetchSingle( + "SELECT oid::text, prosecdef, proacl::text FROM pg_proc WHERE oid = to_regprocedure(?)", + guardProcedure)) + .isEqualTo(originalGuardIdentity); + 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(retainedRowsAtV1042.get("world_instance")); assertThat(sourceOwner.read("dev", intakeRequest)).contains(intake); assertThat( versionOwner.readByCanonicalVersion( @@ -1817,6 +1878,7 @@ private static List remainingVersions() { List versions = new ArrayList<>(remainingVersionsThrough(1042)); versions.add("1042.1"); versions.add("1042.2"); + versions.add("1042.3"); return List.copyOf(versions); } 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 ec3dd3baca..1d235fe5b5 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 @@ -13,6 +13,7 @@ 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; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; @@ -805,6 +806,60 @@ void fixtureActivationRefusesBeforeWorldReadOrProviderEvidence() { verifyNoWorldRepositoryOrOwnerInteraction(); } + @Test + void fixtureFailureAndTerminationRefuseBeforeWorldReadOrOtherEffects() { + RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); + when(provider.isEnabled()).thenReturn(true); + WorldLifecycleCommandServiceImpl fixtureService = fixtureService(provider); + + IllegalArgumentException failure = + assertThrows( + IllegalArgumentException.class, + () -> fixtureService.failPreparedWorldInstance(42L, 101L, 1L, "failed")); + IllegalArgumentException termination = + assertThrows( + IllegalArgumentException.class, + () -> fixtureService.terminateWorldInstance(42L, 101L, 2L, "term-1", "stop")); + + assertTrue(failure.getMessage().startsWith("RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE:")); + assertTrue(termination.getMessage().startsWith("RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE:")); + verify(provider, times(2)).isEnabled(); + verifyNoWorldRepositoryOrOwnerInteraction(); + } + + @Test + void failureRejectsRetainedFixtureBindingBeforeSaving() { + WorldInstance fixture = fixtureWorldInstance(); + when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) + .thenReturn(Optional.of(fixture)); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> service.failPreparedWorldInstance(42L, 101L, 1L, "failed")); + + assertTrue(error.getMessage().startsWith("RUN_OWNED_WORLD_LAUNCH_EVIDENCE_UNAVAILABLE:")); + verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); + verifyNoInteractionsWithRuntimeCleanupOwners(); + } + + @Test + void terminationRejectsRetainedFixtureBindingBeforeWriteOrCleanup() { + WorldInstance fixture = fixtureWorldInstance(); + when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) + .thenReturn(Optional.of(fixture)); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> service.terminateWorldInstance(42L, 101L, 2L, "term-1", "stop")); + + assertTrue(error.getMessage().startsWith("RUN_OWNED_WORLD_LAUNCH_EVIDENCE_UNAVAILABLE:")); + verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); + verifyNoInteractions(entityManagementClient); + verifyNoInteractionsWithRuntimeCleanupOwners(); + } + private void verifyNoWorldRepositoryOrOwnerInteraction() { org.mockito.Mockito.verifyNoInteractions( worldInstanceRepository, @@ -820,6 +875,15 @@ private void verifyNoWorldRepositoryOrOwnerInteraction() { entityManagementClient); } + private void verifyNoInteractionsWithRuntimeCleanupOwners() { + org.mockito.Mockito.verifyNoInteractions( + regionInstanceRepository, + zoneInstanceRepository, + roomInstanceRepository, + roomInstanceExitRepository, + worldEventRepository); + } + private WorldLifecycleCommandServiceImpl fixtureService( RunOwnedWorldLaunchEvidenceProvider provider) { WorldProperties worldProperties = new WorldProperties(); @@ -881,6 +945,16 @@ private WorldInstance activeWorldInstance() { return instance; } + private static WorldInstance fixtureWorldInstance() { + WorldInstance instance = new WorldInstance(); + instance.setTenantId(42L); + instance.setGameInstanceId(101L); + instance.setLifecycleEpoch(1L); + instance.setStatus("PREPARING"); + instance.setRunOwnedFixtureBindingSha256("a".repeat(64)); + return instance; + } + private AtomicReference stubPersistedWorldInstance(WorldInstance initiallyLoaded) { AtomicReference persisted = new AtomicReference<>(copyWorldInstance(initiallyLoaded)); From 2b648090b986e239a6e0b092a1916fad2330fd1e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 10:10:22 +1300 Subject: [PATCH 11/45] Fix fixture key echoes, isolate composition proof and refine owner failures --- .../runtime-and-data.md | 2 +- ...ame-authoring-publishing-and-activation.md | 2 +- .../world-runtime-and-movement.md | 6 +- services/game-design-service/build.gradle.kts | 8 +- .../AuthoredWorldSourceReadGrpcService.java | 16 +- .../TestDataSeederIntegrationSupport.java | 654 ++++++++ ...xtureOwnerCompositionCrossServiceTest.java | 870 ++++++++++ .../data/TestDataSeederIntegrationTest.java | 1454 +---------------- ...uthoredWorldSourceReadGrpcServiceTest.java | 31 +- ...AuthoredWorldOwnerReadGrpcServiceTest.java | 20 + .../WorldLifecycleCommandServiceImpl.java | 20 +- .../WorldAuthoredSourceIntakeService.java | 3 - .../WorldAuthoredVersionIdentityService.java | 3 - .../WorldPostgresMigrationTestSupport.java | 163 ++ ...resetResourcesPostgresIntegrationTest.java | 175 +- ...TerminalSchemaPostgresIntegrationTest.java | 37 +- ...edGraphCapturePostgresIntegrationTest.java | 186 +-- ...nOwnedWorldLaunchEvidenceProviderTest.java | 265 +-- ...nOwnedWorldLaunchEvidenceTestFixtures.java | 80 +- 19 files changed, 1936 insertions(+), 2059 deletions(-) create mode 100644 services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationSupport.java create mode 100644 services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPostgresMigrationTestSupport.java 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 1d832a2f70..4505ab9ea4 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -28,7 +28,7 @@ The owner materializes the exact sealed fixed preset into one region, one zone, 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. 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. These storage checks do not grant Human protection, fixture activation or hold authority. Later fixture World row mutations, lifecycle transitions, hold acquire/finalize, initial placement and player-admission owners reject the fixture variant before effects. 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. +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, and V1042.3 gives forbidden fixture row updates their own diagnostic without changing guard predicates or 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. These storage checks do not grant Human protection, fixture activation or hold authority. Later fixture World row mutations, lifecycle transitions, hold acquire/finalize, initial placement and player-admission owners reject the fixture variant before effects. 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. ### Authored-world source retention 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 0141983f7c..4fbafc24cc 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 @@ -133,7 +133,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 b24a207cac..9e73433161 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -18,7 +18,9 @@ The local follow-on implements typed source intake and Version association after 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. -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. The final 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. +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 current frontier adds 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 exercise the current default 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 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. @@ -76,7 +78,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 run-owned coordinator completes Game Session STARTING allocation and readback only. Earlier Compose-driven holds, preparing-epoch binding and ACTIVE replay belong to predecessor evidence. The synchronous World prepare RPC consumes the bounded authenticated Game Session read and materializes the sealed fixed preset at PREPARING epoch 1 and row version 0, with controlled native production-handler proof. Fixture bootstrap skips seeding; activation, holds and first OPEN remain unavailable, and claimed packaged runtime and genuine owner handoffs remain unqualified. 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 current run-owned fixture prepare RPC verifies the sealed Game Design receipt and authenticated Game Session STARTING allocation, then commits typed intake, canonical association and fixed-preset materialization at PREPARING epoch 1 and row version 0. Fixture bootstrap skips all seeding with a diagnostic; activation, holds and first OPEN remain unavailable. Earlier binding/ACTIVE replay and coordinator-driven hold execution are predecessor proof, not current fixture capability. | [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); [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); [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); [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 is implemented with controlled native proof; 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.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 run-owned coordinator completes Game Session STARTING allocation and readback only. Earlier Compose-driven holds, preparing-epoch binding and ACTIVE replay belong to predecessor evidence. The synchronous World prepare RPC consumes the bounded authenticated Game Session read and materializes the sealed fixed preset at PREPARING epoch 1 and row version 0, with controlled native production-handler proof. Fixture bootstrap skips seeding; activation, holds and first OPEN remain unavailable, and claimed packaged runtime and genuine owner handoffs remain unqualified. 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 current run-owned fixture prepare RPC verifies the sealed Game Design receipt and authenticated Game Session STARTING allocation, then commits typed intake, canonical association and fixed-preset materialization at PREPARING epoch 1 and row version 0. Fixture bootstrap skips all seeding with a diagnostic; activation, holds and first OPEN remain unavailable. Earlier binding/ACTIVE replay and coordinator-driven hold execution are predecessor proof, not current fixture capability. | [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); [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); [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 is implemented with controlled native proof; 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. | diff --git a/services/game-design-service/build.gradle.kts b/services/game-design-service/build.gradle.kts index 8bf32c908a..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,7 +31,8 @@ dependencies { implementation(libs.aws.sdk.s3) testCompileOnly(libs.spotbugs.annotations) add("integrationTestCompileOnly", libs.spotbugs.annotations) - add("integrationTestImplementation", project(":game-session-service")) - add("integrationTestImplementation", project(":world-management-service")) + 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/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java index fb83d87fc8..ca66a01436 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java @@ -106,9 +106,21 @@ public void resolveAuthoredWorldSource( /** Returns the existing owner storage classification, or {@code null} for non-storage errors. */ static Status storageFailureStatus(Throwable failure) { + if (failure instanceof TransactionException) { + boolean retryable = + (failure instanceof org.springframework.transaction.CannotCreateTransactionException + && !(failure + instanceof + org.springframework.transaction.NestedTransactionNotSupportedException)) + || failure instanceof org.springframework.transaction.TransactionTimedOutException; + return Status.fromCode(retryable ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL) + .withDescription( + retryable + ? "Authored-world source evidence is temporarily unavailable" + : "Authored-world source evidence could not be read"); + } if (failure instanceof DataAccessResourceFailureException - || failure instanceof TransientDataAccessException - || failure instanceof TransactionException) { + || failure instanceof TransientDataAccessException) { return Status.UNAVAILABLE.withDescription( "Authored-world source evidence is temporarily unavailable"); } diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationSupport.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationSupport.java new file mode 100644 index 0000000000..dfd63e52e0 --- /dev/null +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationSupport.java @@ -0,0 +1,654 @@ +package net.firedevops.firemud.gamedesign.data; + +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.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermission; +import java.security.MessageDigest; +import java.security.cert.CertificateFactory; +import java.security.cert.CertificateNotYetValidException; +import java.security.cert.X509Certificate; +import java.util.HashSet; +import java.util.HexFormat; +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 java.util.function.BiConsumer; +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.grpc.ResolvedGrpcTlsMaterial; +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.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTemplateRepository; +import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; +import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; +import net.firedevops.firemud.gamedesign.service.VersionService; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.BeforeEach; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.DefaultApplicationArguments; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +public abstract class TestDataSeederIntegrationSupport { + protected static final String NAMESPACE = "dev"; + protected static final String SESSION_URI_SAN = "spiffe://firemud/ns/dev/sa/game-session-service"; + protected static final String WORLD_MANAGEMENT_URI_SAN = + "spiffe://firemud/ns/dev/sa/world-management-service"; + protected static final Table SOURCE_OPERATIONS = + DSL.table(DSL.name("game_design_authored_world_source_operations")); + protected static final Table SOURCE_DELIVERIES = + DSL.table(DSL.name("game_design_authored_world_source_deliveries")); + protected static final Field REGISTRATION_REQUEST_ID = + DSL.field(DSL.name("registration_request_id"), UUID.class); + protected static final Field SOURCE_OPERATION_ID = + DSL.field(DSL.name("operation_id"), UUID.class); + protected static final Field DELIVERY_WORLD_OPERATION_ID = + DSL.field(DSL.name("world_operation_id"), UUID.class); + + @Container + protected static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @DynamicPropertySource + protected static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "game_design_service"); + } + + @Autowired protected TestDataSeeder seeder; + + @Autowired + protected net.firedevops.firemud.gamedesign.service.impl.GameDesignGrpcService + gameDesignGrpcService; + + @MockitoSpyBean + protected net.firedevops.firemud.gamedesign.data.RunOwnedFixtureLaunchReadback fixtureReadback; + + @MockitoSpyBean + protected net.firedevops.firemud.gamedesign.data.RunOwnedFixturePolicyProducer fixturePolicy; + + @Autowired protected Flyway flyway; + @Autowired protected ConfigurableEnvironment environment; + @MockitoSpyBean protected GameAuthoredWorldSourceRepository authoredWorldSourceRepository; + @Autowired protected GameRepository gameRepository; + + @Autowired + protected net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository + creationRepository; + + @Autowired protected GameTemplateRepository templateRepository; + @Autowired protected VersionRepository versionRepository; + @Autowired protected VersionAssetArtifactRepository artifactRepository; + @Autowired protected VersionService versionService; + @Autowired protected VersionAssetArtifactService artifactService; + @Autowired protected LaunchDescriptorRepository launchDescriptorRepository; + @MockitoSpyBean protected LaunchDescriptorService launchDescriptorService; + @Autowired protected PlatformTransactionManager transactionManager; + @Autowired protected DSLContext dsl; + @Autowired protected ObjectMapper objectMapper; + + @BeforeEach + protected void resetDisposableServiceSchema() { + ReflectionTestUtils.setField(seeder, "initialAdmissionFixtureEnabled", false); + flyway.clean(); + flyway.migrate(); + seeder.run(new DefaultApplicationArguments(new String[] {})); + } + + protected static void assertSocketReadDenied(Runnable read) { + assertThatThrownBy(read::run) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.PERMISSION_DENIED)); + } + + protected void withFixedReadClients( + Server server, + Fixture fixture, + Path certificate, + Path privateKey, + BiConsumer reads) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("127.0.0.1:" + server.getPort()); + var tls = new CommonGrpcClientProperties(); + tls.setCertChain(certificate.toString()); + tls.setPrivateKey(privateKey.toString()); + tls.setCaCert(fixture.caCertificatePath().toString()); + var channels = new CopyOnWriteArrayList(); + var factory = + 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; + } + }; + try (var sourceClient = new AuthoredWorldSourceClient(endpoints, tls, factory, NAMESPACE); + var versionClient = + new AuthoredWorldVersionStateClient(endpoints, tls, factory, NAMESPACE)) { + sourceClient.init(); + versionClient.init(); + reads.accept(sourceClient, versionClient); + } finally { + for (ManagedChannel channel : channels) { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + } + + protected FixedReadLeaf issueFixedReadLeaf( + Fixture fixture, String name, String uri, boolean server) throws Exception { + Path directory = java.util.Objects.requireNonNull(fixture.caCertificatePath().getParent()); + Path key = directory.resolve(name + ".key"); + Path csr = directory.resolve(name + ".csr"); + Path certificate = directory.resolve(name + ".crt"); + Path extensions = directory.resolve(name + ".ext"); + runOpenSsl( + "req", + "-new", + "-newkey", + "rsa:2048", + "-nodes", + "-sha256", + "-keyout", + key.toString(), + "-out", + csr.toString(), + "-subj", + "/CN=" + name); + Files.writeString( + extensions, + "basicConstraints=critical,CA:FALSE\n" + + "keyUsage=critical,digitalSignature,keyEncipherment\n" + + "extendedKeyUsage=" + + (server ? "serverAuth" : "clientAuth") + + "\n" + + "subjectAltName=URI:" + + uri + + (server + ? ",DNS:game-design-service,DNS:game-design-service.dev,DNS:game-design-service.dev.svc,DNS:game-design-service.dev.svc.cluster.local,DNS:localhost,IP:127.0.0.1" + : ",DNS:world-management-service") + + "\n"); + runOpenSsl( + "x509", + "-req", + "-in", + csr.toString(), + "-CA", + fixture.caCertificatePath().toString(), + "-CAkey", + directory.resolve("ca.key").toString(), + "-CAcreateserial", + "-out", + certificate.toString(), + "-days", + "2", + "-sha256", + "-extfile", + extensions.toString()); + Files.setPosixFilePermissions( + certificate, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + awaitFixtureCertificatesValid(certificate); + return new FixedReadLeaf(certificate, key); + } + + protected record FixedReadLeaf(Path certificate, Path privateKey) { + public FixedReadLeaf {} + } + + protected Map fixedReadOwnerRows() { + Map rows = new LinkedHashMap<>(); + for (String table : + Set.of( + "game_tenant_creation_operations", + "game_design_authored_world_source_operations", + "game_design_authored_world_source_deliveries", + "game", + "game_templates", + "version", + "version_asset_artifact", + "published_release_bundle", + "launch_descriptor", + "game_design_published_realm_policy_set", + "game_design_realm_policy_capture", + "game_design_publication_operation", + "game_design_published_realm_policy")) { + rows.put( + table, + dsl.fetch( + "SELECT row_to_json(t)::text AS bytes, xmin::text AS row_version FROM " + + table + + " t ORDER BY row_to_json(t)::text") + .formatJSON()); + } + return rows; + } + + protected Set fieldNames(JsonNode object) { + Set fields = new HashSet<>(); + object.propertyNames().forEach(fields::add); + return fields; + } + + protected byte[] readPublishedReleaseBundleBytes() { + Record row = + dsl.fetchOne( + "select convert_to(row_to_json(release_bundle)::text, 'UTF8') as bundle_bytes " + + "from published_release_bundle as release_bundle " + + "where tenant_id = ? and version_id = ?", + "1", + 1L); + assertThat(row).isNotNull(); + return row.get("bundle_bytes", byte[].class); + } + + protected void writeVersionStateEpoch( + TransactionTemplate transaction, String tenantId, Long versionId, long epoch) { + transaction.executeWithoutResult( + status -> { + int updated = + dsl.execute( + "update version set version_state_epoch = ? where tenant_id = ? and id = ?", + epoch, + tenantId, + versionId); + assertThat(updated).isOne(); + }); + } + + protected Fixture prepareFixture(Path testDirectory) throws Exception { + return prepareFixture(testDirectory, true); + } + + protected Fixture prepareFixture(Path testDirectory, boolean prepareExistingOwner) + throws Exception { + Path certificateDirectory = Files.createDirectory(testDirectory.resolve("certificates")); + Path caKey = certificateDirectory.resolve("ca.key"); + Path caCertificate = certificateDirectory.resolve("ca.crt"); + Path sessionKey = certificateDirectory.resolve("game-session.key"); + Path sessionRequest = certificateDirectory.resolve("game-session.csr"); + Path sessionCertificate = certificateDirectory.resolve("game-session.crt"); + Path sessionExtensions = certificateDirectory.resolve("game-session.ext"); + Path worldManagementKey = certificateDirectory.resolve("world-management.key"); + Path worldManagementRequest = certificateDirectory.resolve("world-management.csr"); + Path worldManagementCertificate = certificateDirectory.resolve("world-management.crt"); + Path worldManagementExtensions = certificateDirectory.resolve("world-management.ext"); + runOpenSsl( + "req", + "-x509", + "-newkey", + "rsa:2048", + "-nodes", + "-sha256", + "-days", + "2", + "-keyout", + caKey.toString(), + "-out", + caCertificate.toString(), + "-subj", + "/CN=FireMUD test fixture CA", + "-addext", + "basicConstraints=critical,CA:TRUE", + "-addext", + "keyUsage=critical,keyCertSign,cRLSign"); + runOpenSsl( + "req", + "-new", + "-newkey", + "rsa:2048", + "-nodes", + "-sha256", + "-keyout", + sessionKey.toString(), + "-out", + sessionRequest.toString(), + "-subj", + "/CN=game-session-service"); + Files.writeString( + sessionExtensions, + "basicConstraints=critical,CA:FALSE\n" + + "keyUsage=critical,digitalSignature,keyEncipherment\n" + + "extendedKeyUsage=clientAuth,serverAuth\n" + + "subjectAltName=URI:" + + SESSION_URI_SAN + + ",DNS:game-session-service" + + ",DNS:game-session-service.dev" + + ",DNS:game-session-service.dev.svc" + + ",DNS:game-session-service.dev.svc.cluster.local,DNS:localhost,IP:127.0.0.1" + + "\n"); + runOpenSsl( + "x509", + "-req", + "-in", + sessionRequest.toString(), + "-CA", + caCertificate.toString(), + "-CAkey", + caKey.toString(), + "-CAcreateserial", + "-out", + sessionCertificate.toString(), + "-days", + "2", + "-sha256", + "-extfile", + sessionExtensions.toString()); + runOpenSsl( + "req", + "-new", + "-newkey", + "rsa:2048", + "-nodes", + "-sha256", + "-keyout", + worldManagementKey.toString(), + "-out", + worldManagementRequest.toString(), + "-subj", + "/CN=world-management-service"); + Files.writeString( + worldManagementExtensions, + "basicConstraints=critical,CA:FALSE\n" + + "keyUsage=critical,digitalSignature,keyEncipherment\n" + + "extendedKeyUsage=clientAuth,serverAuth\n" + + "subjectAltName=URI:" + + WORLD_MANAGEMENT_URI_SAN + + ",DNS:world-management-service" + + ",DNS:world-management-service.dev" + + ",DNS:world-management-service.dev.svc" + + ",DNS:world-management-service.dev.svc.cluster.local,DNS:localhost,IP:127.0.0.1" + + "\n"); + runOpenSsl( + "x509", + "-req", + "-in", + worldManagementRequest.toString(), + "-CA", + caCertificate.toString(), + "-CAkey", + caKey.toString(), + "-CAcreateserial", + "-out", + worldManagementCertificate.toString(), + "-days", + "2", + "-sha256", + "-extfile", + worldManagementExtensions.toString()); + Files.setPosixFilePermissions( + caCertificate, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + Files.setPosixFilePermissions( + sessionCertificate, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + Files.setPosixFilePermissions( + worldManagementCertificate, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + + String leafDigest = certificateDigest(sessionCertificate); + String worldManagementLeafDigest = certificateDigest(worldManagementCertificate); + String caDigest = certificateDigest(caCertificate); + String runId = "fixture-commit-proof"; + String composeProjectName = "firemud-smoke-fixture-commit-proof"; + String claimDigest = "e".repeat(64); + UUID operationId = + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .fixtureOperationId(claimDigest, runId, composeProjectName, leafDigest, caDigest); + Path capabilityPath = testDirectory.resolve("run-owned-initial-admission-capability.json"); + Map capability = new LinkedHashMap<>(); + capability.put("schema", "firemud.run-owned-initial-admission-fixture.v1"); + capability.put("runId", runId); + capability.put("composeProjectName", composeProjectName); + capability.put("claimDigest", claimDigest); + capability.put("operationId", operationId.toString()); + capability.put("tenantId", 1); + capability.put( + "gameTemplateId", + templateRepository.findByTenantIdAndName("1", "Default Template").orElseThrow().getId()); + capability.put("ownerAccountId", 1); + capability.put("worldSlug", "demo"); + capability.put("worldDisplayName", "Demo World"); + capability.put("realmSlug", "production"); + capability.put("realmDisplayName", "Live Realm"); + capability.put("visible", true); + capability.put("publicProductionRealm", true); + capability.put("requiresCharacterSelection", false); + capability.put("stateScope", "SHARED"); + capability.put("characterCreationPolicy", "ALLOW_NEW"); + capability.put("gameSessionLeafSha256", leafDigest); + capability.put("gameSessionUriSan", SESSION_URI_SAN); + capability.put("worldManagementLeafSha256", worldManagementLeafDigest); + capability.put("worldManagementUriSan", WORLD_MANAGEMENT_URI_SAN); + capability.put("caCertificateSha256", caDigest); + Files.write(capabilityPath, objectMapper.writeValueAsBytes(capability)); + Files.setPosixFilePermissions( + capabilityPath, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + + awaitFixtureCertificatesValid(sessionCertificate, worldManagementCertificate, caCertificate); + + Path receiptDirectory = + Files.createDirectory(testDirectory.resolve("run-owned-authored-world-source")); + Files.setPosixFilePermissions( + receiptDirectory, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.OWNER_EXECUTE, + PosixFilePermission.GROUP_READ, + PosixFilePermission.GROUP_WRITE, + PosixFilePermission.GROUP_EXECUTE, + PosixFilePermission.OTHERS_READ, + PosixFilePermission.OTHERS_WRITE, + PosixFilePermission.OTHERS_EXECUTE)); + Fixture fixture = + new Fixture( + operationId, + runId, + composeProjectName, + capabilityPath, + receiptDirectory.resolve("source-receipt.json"), + sessionCertificate, + worldManagementCertificate, + caCertificate, + leafDigest, + worldManagementLeafDigest, + caDigest); + configureSeeder(fixture); + ReflectionTestUtils.invokeMethod(seeder, "loadFixtureCapability"); + // Disposable test schema only: create the real fixture owner from inception, never backfill. + flyway.clean(); + flyway.migrate(); + if (prepareExistingOwner) { + new TransactionTemplate(transactionManager) + .executeWithoutResult( + status -> + creationRepository.createCandidate( + NAMESPACE, operationId, "1", "Demo Game", "Seed game")); + ReflectionTestUtils.setField(seeder, "initialAdmissionFixtureEnabled", false); + seeder.run(new DefaultApplicationArguments(new String[] {})); + } + return fixture; + } + + protected void configureSeeder(Fixture fixture) { + ReflectionTestUtils.setField(seeder, "initialAdmissionFixtureEnabled", true); + ReflectionTestUtils.setField(seeder, "fixtureRunId", fixture.runId()); + ReflectionTestUtils.setField(seeder, "fixtureComposeProjectName", fixture.composeProjectName()); + ReflectionTestUtils.setField( + seeder, "fixtureCapabilityPath", fixture.capabilityPath().toString()); + ReflectionTestUtils.setField(seeder, "fixtureReceiptPath", fixture.receiptPath().toString()); + ReflectionTestUtils.setField( + seeder, "gameSessionLeafCertPath", fixture.gameSessionCertificatePath().toString()); + ReflectionTestUtils.setField( + seeder, "worldManagementLeafCertPath", fixture.worldManagementCertificatePath().toString()); + ReflectionTestUtils.setField(seeder, "workloadNamespace", NAMESPACE); + ReflectionTestUtils.setField(seeder, "caCertPath", fixture.caCertificatePath().toString()); + } + + protected String certificateDigest(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + X509Certificate certificate = + (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded())); + } + } + + protected void awaitFixtureCertificatesValid(Path... certificatePaths) throws Exception { + long deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (true) { + try { + for (Path path : certificatePaths) { + try (var input = Files.newInputStream(path)) { + X509Certificate certificate = + (X509Certificate) + CertificateFactory.getInstance("X.509").generateCertificate(input); + certificate.checkValidity(); + } + } + return; + } catch (CertificateNotYetValidException exception) { + long remainingNanos = deadlineNanos - System.nanoTime(); + if (remainingNanos <= 0L) { + throw new IllegalStateException( + "Run-owned fixture certificates did not become valid within 5 seconds", exception); + } + TimeUnit.NANOSECONDS.sleep(Math.min(TimeUnit.MILLISECONDS.toNanos(10), remainingNanos)); + } + } + } + + protected AuthoredWorldSourceEvidence changedSourceEvidence(AuthoredWorldSourceEvidence source) { + String changedWorldSlug = source.worldSlug() + "-changed"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + source.targetNamespace(), + source.registrationRequestId(), + source.canonicalTenantId(), + source.tenantSlug(), + changedWorldSlug, + source.worldDisplayName()); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + source.targetNamespace(), + source.registrationRequestId(), + source.operationId(), + requestDigest, + source.canonicalTenantId(), + source.tenantSlug(), + changedWorldSlug, + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + return new AuthoredWorldSourceEvidence( + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.operationId(), + requestDigest, + source.canonicalTenantId(), + source.tenantSlug(), + changedWorldSlug, + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + evidenceDigest); + } + + protected void runOpenSsl(String... arguments) throws Exception { + Process process = + new ProcessBuilder(concat(new String[] {"openssl"}, arguments)) + .redirectErrorStream(true) + .start(); + String output = new String(process.getInputStream().readAllBytes()); + if (process.waitFor() != 0) { + throw new IOException("OpenSSL fixture certificate generation failed: " + output); + } + } + + protected String[] concat(String[] prefix, String[] suffix) { + String[] combined = new String[prefix.length + suffix.length]; + System.arraycopy(prefix, 0, combined, 0, prefix.length); + System.arraycopy(suffix, 0, combined, prefix.length, suffix.length); + return combined; + } + + protected record Fixture( + UUID operationId, + String runId, + String composeProjectName, + Path capabilityPath, + Path receiptPath, + Path gameSessionCertificatePath, + Path worldManagementCertificatePath, + Path caCertificatePath, + String gameSessionLeafSha256, + String worldManagementLeafSha256, + String caCertificateSha256) {} +} 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..c1d31e8167 --- /dev/null +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java @@ -0,0 +1,870 @@ +package crossservice.net.firedevops.firemud.gamedesign.data; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; + +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.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +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.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.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.RunOwnedInitialAdmissionFixtureCoordinator; +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.RunOwnedWorldFixedPresetResources; +import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceProvider; +import net.firedevops.firemud.worldmanagement.service.impl.WorldInstanceActivationServiceImpl; +import net.firedevops.firemud.worldmanagement.service.impl.WorldLifecycleCommandServiceImpl; +import net.firedevops.firemud.worldmanagement.service.impl.WorldManagementGrpcService; +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 actualProducerStartingAndPreparingOwnersComposeOverThreeMutualTlsSockets( + @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 coordinator = + new RunOwnedInitialAdmissionFixtureCoordinator( + true, + fixture.capabilityPath().toString(), + fixture.receiptPath().toString(), + fixture.runId(), + fixture.composeProjectName(), + gsTls, + beanFactory.getBeanProvider(GameSessionCanonicalInstanceLaunchRepository.class), + NAMESPACE); + // The production loader verifies real producer files and original mounted pins; no test-only GS + // carrier is used. + var gsEvidence = coordinator.loadFixedVerifiedEvidence(); + var starting = launchOwner.createVerifiedFixtureStartingLaunch(gsEvidence); + 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(coordinator, 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; + RunOwnedWorldLaunchEvidenceProvider 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 RunOwnedWorldLaunchEvidenceProvider( + 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 worldRepository = + new net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository( + worldDatabase.dsl()); + var worldHandler = actualWorldFixtureHandler(commands, provider, worldRepository, registry); + Server worldServer = + fixedProductionServer( + fixture, + new FixedReadLeaf( + fixture.worldManagementCertificatePath(), + fixture.worldManagementCertificatePath().resolveSibling("world-management.key")), + Set.of( + net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc + .getPrepareWorldInstanceMethod() + .getFullMethodName()), + worldHandler); + servers.add(worldServer); + var descriptor = receipt.launchReadEvidence().launchDescriptor(); + var bundle = receipt.launchReadEvidence().publishedReleaseBundle(); + var request = + net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceRequest.newBuilder() + .setTenantId(Long.toString(starting.catalog().association().gameSessionTenantId())) + .setGameInstanceId(Long.toString(starting.gameInstanceId())) + .setGameTemplateId(Long.toString(capability.gameTemplateId())) + .setControlPlaneRequestId(capability.operationId()) + .setLaunchDescriptorId(descriptor.getLaunchDescriptorId()) + .setVersionId(Long.toString(bundle.getVersionId())) + .setRuntimeFlagsJson(descriptor.getRuntimeFlagsJson()) + .setGenerationConfigRevision(bundle.getGenerationConfigRevision()) + .setReleaseBundleId(Long.toString(bundle.getId())) + .setPublishedReleaseBundleRef(bundle.getPublishedReleaseBundleRef()) + .setVersionStateEpoch( + receipt.launchReadEvidence().versionState().getVersionStateEpoch()) + .build(); + var originalGdsRows = fixedReadOwnerRows(); + var originalGsRows = allComposedOwnerRows(gsDatabase.dsl()); + ManagedChannel worldChannel = + factory.buildChannel( + "127.0.0.1:" + worldServer.getPort(), worldServer.getPort(), gsTls, false); + var stub = + net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc.newBlockingStub( + worldChannel) + .withCallCredentials( + new net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials( + WORLD_MANAGEMENT_URI_SAN)) + .withInterceptors( + new net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor( + WORLD_MANAGEMENT_URI_SAN)) + .withDeadlineAfter(30, TimeUnit.SECONDS); + var prepared = stub.prepareWorldInstance(request); + assertThat(prepared.hasError()).as("actual World prepare response").isFalse(); + assertThat(prepared.getWorldInstance().getStatus()) + .isEqualTo( + net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus + .WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING); + assertThat(prepared.getWorldInstance().getLifecycleEpoch()).isEqualTo(1L); + assertThat(prepared.getWorldInstance().getTenantId()).isEqualTo(request.getTenantId()); + assertThat(prepared.getWorldInstance().getGameInstanceId()) + .isEqualTo(request.getGameInstanceId()); + assertThat(prepared.getWorldInstance().getVersionId()).isEqualTo(request.getVersionId()); + 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(stub.prepareWorldInstance(request)).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); + // Selector denial is an actual production response; no remote positive response is + // controlled. + assertThat( + stub.prepareWorldInstance( + request.toBuilder() + .setGameInstanceId(Long.toString(starting.gameInstanceId() + 1)) + .build()) + .hasError()) + .isTrue(); + 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 RunOwnedWorldLaunchEvidenceProvider( + 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 restartedHandler = + actualWorldFixtureHandler( + commands, + provider, + new net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository( + worldDatabase.dsl()), + registry); + Server restartedServer = + fixedProductionServer( + fixture, + new FixedReadLeaf( + fixture.worldManagementCertificatePath(), + fixture.worldManagementCertificatePath().resolveSibling("world-management.key")), + Set.of( + net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc + .getPrepareWorldInstanceMethod() + .getFullMethodName()), + restartedHandler); + servers.add(restartedServer); + ManagedChannel restartedChannel = + factory.buildChannel( + "127.0.0.1:" + restartedServer.getPort(), restartedServer.getPort(), gsTls, false); + assertThat(actualWorldPrepareStub(restartedChannel).prepareWorldInstance(request)) + .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(3)) + .getRunOwnedFixtureLaunchAssociation(reads.capture(), any()); + assertThat(reads.getAllValues()) + .extracting(value -> value.getReadRequestId()) + .doesNotHaveDuplicates(); + org.mockito.Mockito.clearInvocations( + gsHandler, launchDescriptorService, fixtureReadback, fixturePolicy); + var otherGsLeaf = + issueFixedReadLeaf(fixture, "different-game-session-client", SESSION_URI_SAN, false); + for (var wrongLeaf : + java.util.List.of( + otherGsLeaf, + new FixedReadLeaf( + fixture.worldManagementCertificatePath(), + fixture + .worldManagementCertificatePath() + .resolveSibling("world-management.key")))) { + var wrongTls = fixedReadTls(fixture, wrongLeaf.certificate(), wrongLeaf.privateKey()); + var wrongChannel = + factory.buildChannel( + "127.0.0.1:" + restartedServer.getPort(), + restartedServer.getPort(), + wrongTls, + false); + assertThat(actualWorldPrepareStub(wrongChannel).prepareWorldInstance(request).hasError()) + .isTrue(); + } + 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 WorldManagementGrpcService actualWorldFixtureHandler( + WorldLifecycleCommandServiceImpl commands, + RunOwnedWorldLaunchEvidenceProvider provider, + net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository repository, + io.micrometer.core.instrument.MeterRegistry registry) { + var activation = + new WorldInstanceActivationServiceImpl(commands, Optional.empty(), provider, repository); + return new WorldManagementGrpcService( + org.mockito.Mockito.mock(net.firedevops.firemud.worldmanagement.service.PingService.class), + org.mockito.Mockito.mock(net.firedevops.firemud.worldmanagement.service.RoomService.class), + activation, + org.mockito.Mockito.mock( + net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.worldmanagement.service.WorldDesignMutationService.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.worldmanagement.service.WorldUpgradeValidationService.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.common.security.GameplaySessionAttestationService.class), + registry, + objectMapper, + NAMESPACE); + } + + private net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc + .WorldManagementServiceBlockingStub + actualWorldPrepareStub(ManagedChannel channel) { + return net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc.newBlockingStub( + channel) + .withCallCredentials( + new net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials( + WORLD_MANAGEMENT_URI_SAN)) + .withInterceptors( + new net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor( + WORLD_MANAGEMENT_URI_SAN)) + .withDeadlineAfter(30, TimeUnit.SECONDS); + } + + 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 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, + RunOwnedWorldLaunchEvidenceProvider 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(), + 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/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java index 96bdc6922e..a924b10f07 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java @@ -6,54 +6,38 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doAnswer; -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.NettyServerBuilder; import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; -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.MessageDigest; import java.security.cert.CertificateFactory; -import java.security.cert.CertificateNotYetValidException; import java.security.cert.X509Certificate; import java.util.Base64; -import java.util.HashSet; -import java.util.HexFormat; -import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; -import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.BiConsumer; -import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; -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.GrpcChannelFactory; 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.AuthoredWorldSourceClient; -import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; import net.firedevops.firemud.gamedesign.data.RunOwnedFixtureOwnerReadAuthorization; import net.firedevops.firemud.gamedesign.data.TestDataSeeder; +import net.firedevops.firemud.gamedesign.data.TestDataSeederIntegrationSupport; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; import net.firedevops.firemud.gamedesign.dto.VersionAssetArtifactStateDto; @@ -68,9 +52,6 @@ import net.firedevops.firemud.gamedesign.repository.RevisionRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; -import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; -import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; -import net.firedevops.firemud.gamedesign.service.VersionService; import net.firedevops.firemud.gamedesign.service.impl.GameDesignLaunchReadProjectionMapper; import net.firedevops.firemud.gamedesign.service.impl.RunOwnedFixtureAuthoredWorldSourceReadGrpcService; import net.firedevops.firemud.gamedesign.service.impl.RunOwnedFixtureAuthoredWorldVersionStateGrpcService; @@ -80,49 +61,25 @@ import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; -import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionFixtureCoordinator; -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.RunOwnedWorldFixedPresetResources; -import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceProvider; -import net.firedevops.firemud.worldmanagement.service.impl.WorldInstanceActivationServiceImpl; -import net.firedevops.firemud.worldmanagement.service.impl.WorldLifecycleCommandServiceImpl; -import net.firedevops.firemud.worldmanagement.service.impl.WorldManagementGrpcService; -import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationRepository; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; -import org.jooq.Field; -import org.jooq.Record; import org.jooq.SQLDialect; -import org.jooq.Table; import org.jooq.impl.DSL; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.DefaultApplicationArguments; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Import; import org.springframework.core.Ordered; -import org.springframework.core.env.ConfigurableEnvironment; 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.MockitoSpyBean; import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; -import org.testcontainers.containers.PostgreSQLContainer; -import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; @@ -147,80 +104,7 @@ "asset.store.secret-key=test-secret-key" }) @Import(NoGrpcServerTestConfiguration.class) -class TestDataSeederIntegrationTest { - private static final String NAMESPACE = "dev"; - private static final String SESSION_URI_SAN = "spiffe://firemud/ns/dev/sa/game-session-service"; - private static final String WORLD_MANAGEMENT_URI_SAN = - "spiffe://firemud/ns/dev/sa/world-management-service"; - private static final Table SOURCE_OPERATIONS = - DSL.table(DSL.name("game_design_authored_world_source_operations")); - private static final Table SOURCE_DELIVERIES = - DSL.table(DSL.name("game_design_authored_world_source_deliveries")); - private static final Field REGISTRATION_REQUEST_ID = - DSL.field(DSL.name("registration_request_id"), UUID.class); - private static final Field SOURCE_OPERATION_ID = - DSL.field(DSL.name("operation_id"), UUID.class); - private static final Field DELIVERY_WORLD_OPERATION_ID = - DSL.field(DSL.name("world_operation_id"), UUID.class); - - @Container - static PostgreSQLContainer postgres = - new PostgreSQLContainer<>(TestContainerImages.postgres()); - - @Container - static PostgreSQLContainer composedGameSessionPostgres = - new PostgreSQLContainer<>(TestContainerImages.postgres()); - - @Container - static PostgreSQLContainer composedWorldPostgres = - new PostgreSQLContainer<>(TestContainerImages.postgres()); - - @DynamicPropertySource - static void configure(DynamicPropertyRegistry registry) { - PostgresBackedServiceTestSupport.registerPostgresService( - registry, postgres, "game_design_service"); - } - - @Autowired private TestDataSeeder seeder; - - @Autowired - private net.firedevops.firemud.gamedesign.service.impl.GameDesignGrpcService - gameDesignGrpcService; - - @MockitoSpyBean - private net.firedevops.firemud.gamedesign.data.RunOwnedFixtureLaunchReadback fixtureReadback; - - @MockitoSpyBean - private net.firedevops.firemud.gamedesign.data.RunOwnedFixturePolicyProducer fixturePolicy; - - @Autowired private Flyway flyway; - @Autowired private ConfigurableEnvironment environment; - @MockitoSpyBean private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; - @Autowired private GameRepository gameRepository; - - @Autowired - private net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository - creationRepository; - - @Autowired private GameTemplateRepository templateRepository; - @Autowired private VersionRepository versionRepository; - @Autowired private VersionAssetArtifactRepository artifactRepository; - @Autowired private VersionService versionService; - @Autowired private VersionAssetArtifactService artifactService; - @Autowired private LaunchDescriptorRepository launchDescriptorRepository; - @MockitoSpyBean private LaunchDescriptorService launchDescriptorService; - @Autowired private PlatformTransactionManager transactionManager; - @Autowired private DSLContext dsl; - @Autowired private ObjectMapper objectMapper; - - @BeforeEach - void resetDisposableServiceSchema() { - ReflectionTestUtils.setField(seeder, "initialAdmissionFixtureEnabled", false); - flyway.clean(); - flyway.migrate(); - seeder.run(new DefaultApplicationArguments(new String[] {})); - } - +class TestDataSeederIntegrationTest extends TestDataSeederIntegrationSupport { @Test void fixedWorldReadsQualifyRealPreexistingOwnersWithoutRewritingOrResolving( @TempDir Path testDirectory) throws Exception { @@ -582,939 +466,6 @@ void fixedWorldClientsReadActualProducerOwnersOverMutualTlsWithoutOwnerWrites( } } - private static void assertSocketReadDenied(Runnable read) { - assertThatThrownBy(read::run) - .isInstanceOfSatisfying( - StatusRuntimeException.class, - failure -> - assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.PERMISSION_DENIED)); - } - - private void withFixedReadClients( - Server server, - Fixture fixture, - Path certificate, - Path privateKey, - BiConsumer reads) - throws Exception { - var endpoints = new ServiceEndpointsProperties(); - endpoints.setGameDesignService("127.0.0.1:" + server.getPort()); - var tls = new CommonGrpcClientProperties(); - tls.setCertChain(certificate.toString()); - tls.setPrivateKey(privateKey.toString()); - tls.setCaCert(fixture.caCertificatePath().toString()); - var channels = new CopyOnWriteArrayList(); - var factory = - 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; - } - }; - try (var sourceClient = new AuthoredWorldSourceClient(endpoints, tls, factory, NAMESPACE); - var versionClient = - new AuthoredWorldVersionStateClient(endpoints, tls, factory, NAMESPACE)) { - sourceClient.init(); - versionClient.init(); - reads.accept(sourceClient, versionClient); - } finally { - for (ManagedChannel channel : channels) { - channel.shutdownNow(); - assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); - } - } - } - - private FixedReadLeaf issueFixedReadLeaf(Fixture fixture, String name, String uri, boolean server) - throws Exception { - Path directory = java.util.Objects.requireNonNull(fixture.caCertificatePath().getParent()); - Path key = directory.resolve(name + ".key"); - Path csr = directory.resolve(name + ".csr"); - Path certificate = directory.resolve(name + ".crt"); - Path extensions = directory.resolve(name + ".ext"); - runOpenSsl( - "req", - "-new", - "-newkey", - "rsa:2048", - "-nodes", - "-sha256", - "-keyout", - key.toString(), - "-out", - csr.toString(), - "-subj", - "/CN=" + name); - Files.writeString( - extensions, - "basicConstraints=critical,CA:FALSE\n" - + "keyUsage=critical,digitalSignature,keyEncipherment\n" - + "extendedKeyUsage=" - + (server ? "serverAuth" : "clientAuth") - + "\n" - + "subjectAltName=URI:" - + uri - + (server - ? ",DNS:game-design-service,DNS:game-design-service.dev,DNS:game-design-service.dev.svc,DNS:game-design-service.dev.svc.cluster.local,DNS:localhost,IP:127.0.0.1" - : ",DNS:world-management-service") - + "\n"); - runOpenSsl( - "x509", - "-req", - "-in", - csr.toString(), - "-CA", - fixture.caCertificatePath().toString(), - "-CAkey", - directory.resolve("ca.key").toString(), - "-CAcreateserial", - "-out", - certificate.toString(), - "-days", - "2", - "-sha256", - "-extfile", - extensions.toString()); - Files.setPosixFilePermissions( - certificate, - Set.of( - PosixFilePermission.OWNER_READ, - PosixFilePermission.GROUP_READ, - PosixFilePermission.OTHERS_READ)); - awaitFixtureCertificatesValid(certificate); - return new FixedReadLeaf(certificate, key); - } - - private record FixedReadLeaf(Path certificate, Path privateKey) {} - - @Test - void actualProducerStartingAndPreparingOwnersComposeOverThreeMutualTlsSockets( - @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 coordinator = - new RunOwnedInitialAdmissionFixtureCoordinator( - true, - fixture.capabilityPath().toString(), - fixture.receiptPath().toString(), - fixture.runId(), - fixture.composeProjectName(), - gsTls, - beanFactory.getBeanProvider(GameSessionCanonicalInstanceLaunchRepository.class), - NAMESPACE); - // The production loader verifies real producer files and original mounted pins; no test-only GS - // carrier is used. - var gsEvidence = coordinator.loadFixedVerifiedEvidence(); - var starting = launchOwner.createVerifiedFixtureStartingLaunch(gsEvidence); - 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(coordinator, 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; - RunOwnedWorldLaunchEvidenceProvider 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 RunOwnedWorldLaunchEvidenceProvider( - 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 worldRepository = - new net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository( - worldDatabase.dsl()); - var worldHandler = actualWorldFixtureHandler(commands, provider, worldRepository, registry); - Server worldServer = - fixedProductionServer( - fixture, - new FixedReadLeaf( - fixture.worldManagementCertificatePath(), - fixture.worldManagementCertificatePath().resolveSibling("world-management.key")), - Set.of( - net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc - .getPrepareWorldInstanceMethod() - .getFullMethodName()), - worldHandler); - servers.add(worldServer); - var descriptor = receipt.launchReadEvidence().launchDescriptor(); - var bundle = receipt.launchReadEvidence().publishedReleaseBundle(); - var request = - net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceRequest.newBuilder() - .setTenantId(Long.toString(starting.catalog().association().gameSessionTenantId())) - .setGameInstanceId(Long.toString(starting.gameInstanceId())) - .setGameTemplateId(Long.toString(capability.gameTemplateId())) - .setControlPlaneRequestId(capability.operationId()) - .setLaunchDescriptorId(descriptor.getLaunchDescriptorId()) - .setVersionId(Long.toString(bundle.getVersionId())) - .setRuntimeFlagsJson(descriptor.getRuntimeFlagsJson()) - .setGenerationConfigRevision(bundle.getGenerationConfigRevision()) - .setReleaseBundleId(Long.toString(bundle.getId())) - .setPublishedReleaseBundleRef(bundle.getPublishedReleaseBundleRef()) - .setVersionStateEpoch( - receipt.launchReadEvidence().versionState().getVersionStateEpoch()) - .build(); - var originalGdsRows = fixedReadOwnerRows(); - var originalGsRows = allComposedOwnerRows(gsDatabase.dsl()); - ManagedChannel worldChannel = - factory.buildChannel( - "127.0.0.1:" + worldServer.getPort(), worldServer.getPort(), gsTls, false); - var stub = - net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc.newBlockingStub( - worldChannel) - .withCallCredentials( - new net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials( - WORLD_MANAGEMENT_URI_SAN)) - .withInterceptors( - new net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor( - WORLD_MANAGEMENT_URI_SAN)) - .withDeadlineAfter(30, TimeUnit.SECONDS); - var prepared = stub.prepareWorldInstance(request); - assertThat(prepared.hasError()).as("actual World prepare response").isFalse(); - assertThat(prepared.getWorldInstance().getStatus()) - .isEqualTo( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING); - assertThat(prepared.getWorldInstance().getLifecycleEpoch()).isEqualTo(1L); - 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(stub.prepareWorldInstance(request)).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); - // Selector denial is an actual production response; no remote positive response is - // controlled. - assertThat( - stub.prepareWorldInstance( - request.toBuilder() - .setGameInstanceId(Long.toString(starting.gameInstanceId() + 1)) - .build()) - .hasError()) - .isTrue(); - 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 RunOwnedWorldLaunchEvidenceProvider( - 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 restartedHandler = - actualWorldFixtureHandler( - commands, - provider, - new net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository( - worldDatabase.dsl()), - registry); - Server restartedServer = - fixedProductionServer( - fixture, - new FixedReadLeaf( - fixture.worldManagementCertificatePath(), - fixture.worldManagementCertificatePath().resolveSibling("world-management.key")), - Set.of( - net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc - .getPrepareWorldInstanceMethod() - .getFullMethodName()), - restartedHandler); - servers.add(restartedServer); - ManagedChannel restartedChannel = - factory.buildChannel( - "127.0.0.1:" + restartedServer.getPort(), restartedServer.getPort(), gsTls, false); - assertThat(actualWorldPrepareStub(restartedChannel).prepareWorldInstance(request)) - .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(3)) - .getRunOwnedFixtureLaunchAssociation(reads.capture(), any()); - assertThat(reads.getAllValues()) - .extracting(value -> value.getReadRequestId()) - .doesNotHaveDuplicates(); - org.mockito.Mockito.clearInvocations( - gsHandler, launchDescriptorService, fixtureReadback, fixturePolicy); - var otherGsLeaf = - issueFixedReadLeaf(fixture, "different-game-session-client", SESSION_URI_SAN, false); - for (var wrongLeaf : - java.util.List.of( - otherGsLeaf, - new FixedReadLeaf( - fixture.worldManagementCertificatePath(), - fixture - .worldManagementCertificatePath() - .resolveSibling("world-management.key")))) { - var wrongTls = fixedReadTls(fixture, wrongLeaf.certificate(), wrongLeaf.privateKey()); - var wrongChannel = - factory.buildChannel( - "127.0.0.1:" + restartedServer.getPort(), - restartedServer.getPort(), - wrongTls, - false); - assertThat(actualWorldPrepareStub(wrongChannel).prepareWorldInstance(request).hasError()) - .isTrue(); - } - 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 WorldManagementGrpcService actualWorldFixtureHandler( - WorldLifecycleCommandServiceImpl commands, - RunOwnedWorldLaunchEvidenceProvider provider, - net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository repository, - io.micrometer.core.instrument.MeterRegistry registry) { - var activation = - new WorldInstanceActivationServiceImpl(commands, Optional.empty(), provider, repository); - return new WorldManagementGrpcService( - org.mockito.Mockito.mock(net.firedevops.firemud.worldmanagement.service.PingService.class), - org.mockito.Mockito.mock(net.firedevops.firemud.worldmanagement.service.RoomService.class), - activation, - org.mockito.Mockito.mock( - net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService.class), - org.mockito.Mockito.mock( - net.firedevops.firemud.worldmanagement.service.WorldDesignMutationService.class), - org.mockito.Mockito.mock( - net.firedevops.firemud.worldmanagement.service.WorldUpgradeValidationService.class), - org.mockito.Mockito.mock( - net.firedevops.firemud.common.security.GameplaySessionAttestationService.class), - registry, - objectMapper, - NAMESPACE); - } - - private net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc - .WorldManagementServiceBlockingStub - actualWorldPrepareStub(ManagedChannel channel) { - return net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc.newBlockingStub( - channel) - .withCallCredentials( - new net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials( - WORLD_MANAGEMENT_URI_SAN)) - .withInterceptors( - new net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor( - WORLD_MANAGEMENT_URI_SAN)) - .withDeadlineAfter(30, TimeUnit.SECONDS); - } - - 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 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, - RunOwnedWorldLaunchEvidenceProvider 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(), - 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; - } - - private Map fixedReadOwnerRows() { - Map rows = new LinkedHashMap<>(); - for (String table : - Set.of( - "game_tenant_creation_operations", - "game_design_authored_world_source_operations", - "game_design_authored_world_source_deliveries", - "game", - "game_templates", - "version", - "version_asset_artifact", - "published_release_bundle", - "launch_descriptor", - "game_design_published_realm_policy_set", - "game_design_realm_policy_capture", - "game_design_publication_operation", - "game_design_published_realm_policy")) { - rows.put( - table, - dsl.fetch( - "SELECT row_to_json(t)::text AS bytes, xmin::text AS row_version FROM " - + table - + " t ORDER BY row_to_json(t)::text") - .formatJSON()); - } - return rows; - } - - private static final class FixedReadObserver implements io.grpc.stub.StreamObserver { - private T value; - private Status.Code failure; - private boolean completed; - - @Override - public void onNext(T response) { - value = response; - } - - @Override - public void onError(Throwable error) { - failure = Status.fromThrowable(error).getCode(); - } - - @Override - public void onCompleted() { - completed = true; - } - } - @Test void fixtureRefusesExistingUnownedDemoInsteadOfBackfillingCreation(@TempDir Path testDirectory) throws Exception { @@ -2150,384 +1101,6 @@ void preservesConflictingReceiptInsteadOfReplacingIt(@TempDir Path testDirectory .isOne(); } - private Set fieldNames(JsonNode object) { - Set fields = new HashSet<>(); - object.propertyNames().forEach(fields::add); - return fields; - } - - private byte[] readPublishedReleaseBundleBytes() { - Record row = - dsl.fetchOne( - "select convert_to(row_to_json(release_bundle)::text, 'UTF8') as bundle_bytes " - + "from published_release_bundle as release_bundle " - + "where tenant_id = ? and version_id = ?", - "1", - 1L); - assertThat(row).isNotNull(); - return row.get("bundle_bytes", byte[].class); - } - - private void writeVersionStateEpoch( - TransactionTemplate transaction, String tenantId, Long versionId, long epoch) { - transaction.executeWithoutResult( - status -> { - int updated = - dsl.execute( - "update version set version_state_epoch = ? where tenant_id = ? and id = ?", - epoch, - tenantId, - versionId); - assertThat(updated).isOne(); - }); - } - - private Fixture prepareFixture(Path testDirectory) throws Exception { - return prepareFixture(testDirectory, true); - } - - private Fixture prepareFixture(Path testDirectory, boolean prepareExistingOwner) - throws Exception { - Path certificateDirectory = Files.createDirectory(testDirectory.resolve("certificates")); - Path caKey = certificateDirectory.resolve("ca.key"); - Path caCertificate = certificateDirectory.resolve("ca.crt"); - Path sessionKey = certificateDirectory.resolve("game-session.key"); - Path sessionRequest = certificateDirectory.resolve("game-session.csr"); - Path sessionCertificate = certificateDirectory.resolve("game-session.crt"); - Path sessionExtensions = certificateDirectory.resolve("game-session.ext"); - Path worldManagementKey = certificateDirectory.resolve("world-management.key"); - Path worldManagementRequest = certificateDirectory.resolve("world-management.csr"); - Path worldManagementCertificate = certificateDirectory.resolve("world-management.crt"); - Path worldManagementExtensions = certificateDirectory.resolve("world-management.ext"); - runOpenSsl( - "req", - "-x509", - "-newkey", - "rsa:2048", - "-nodes", - "-sha256", - "-days", - "2", - "-keyout", - caKey.toString(), - "-out", - caCertificate.toString(), - "-subj", - "/CN=FireMUD test fixture CA", - "-addext", - "basicConstraints=critical,CA:TRUE", - "-addext", - "keyUsage=critical,keyCertSign,cRLSign"); - runOpenSsl( - "req", - "-new", - "-newkey", - "rsa:2048", - "-nodes", - "-sha256", - "-keyout", - sessionKey.toString(), - "-out", - sessionRequest.toString(), - "-subj", - "/CN=game-session-service"); - Files.writeString( - sessionExtensions, - "basicConstraints=critical,CA:FALSE\n" - + "keyUsage=critical,digitalSignature,keyEncipherment\n" - + "extendedKeyUsage=clientAuth,serverAuth\n" - + "subjectAltName=URI:" - + SESSION_URI_SAN - + ",DNS:game-session-service" - + ",DNS:game-session-service.dev" - + ",DNS:game-session-service.dev.svc" - + ",DNS:game-session-service.dev.svc.cluster.local,DNS:localhost,IP:127.0.0.1" - + "\n"); - runOpenSsl( - "x509", - "-req", - "-in", - sessionRequest.toString(), - "-CA", - caCertificate.toString(), - "-CAkey", - caKey.toString(), - "-CAcreateserial", - "-out", - sessionCertificate.toString(), - "-days", - "2", - "-sha256", - "-extfile", - sessionExtensions.toString()); - runOpenSsl( - "req", - "-new", - "-newkey", - "rsa:2048", - "-nodes", - "-sha256", - "-keyout", - worldManagementKey.toString(), - "-out", - worldManagementRequest.toString(), - "-subj", - "/CN=world-management-service"); - Files.writeString( - worldManagementExtensions, - "basicConstraints=critical,CA:FALSE\n" - + "keyUsage=critical,digitalSignature,keyEncipherment\n" - + "extendedKeyUsage=clientAuth,serverAuth\n" - + "subjectAltName=URI:" - + WORLD_MANAGEMENT_URI_SAN - + ",DNS:world-management-service" - + ",DNS:world-management-service.dev" - + ",DNS:world-management-service.dev.svc" - + ",DNS:world-management-service.dev.svc.cluster.local,DNS:localhost,IP:127.0.0.1" - + "\n"); - runOpenSsl( - "x509", - "-req", - "-in", - worldManagementRequest.toString(), - "-CA", - caCertificate.toString(), - "-CAkey", - caKey.toString(), - "-CAcreateserial", - "-out", - worldManagementCertificate.toString(), - "-days", - "2", - "-sha256", - "-extfile", - worldManagementExtensions.toString()); - Files.setPosixFilePermissions( - caCertificate, - Set.of( - PosixFilePermission.OWNER_READ, - PosixFilePermission.GROUP_READ, - PosixFilePermission.OTHERS_READ)); - Files.setPosixFilePermissions( - sessionCertificate, - Set.of( - PosixFilePermission.OWNER_READ, - PosixFilePermission.GROUP_READ, - PosixFilePermission.OTHERS_READ)); - Files.setPosixFilePermissions( - worldManagementCertificate, - Set.of( - PosixFilePermission.OWNER_READ, - PosixFilePermission.GROUP_READ, - PosixFilePermission.OTHERS_READ)); - - String leafDigest = certificateDigest(sessionCertificate); - String worldManagementLeafDigest = certificateDigest(worldManagementCertificate); - String caDigest = certificateDigest(caCertificate); - String runId = "fixture-commit-proof"; - String composeProjectName = "firemud-smoke-fixture-commit-proof"; - String claimDigest = "e".repeat(64); - UUID operationId = - net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec - .fixtureOperationId(claimDigest, runId, composeProjectName, leafDigest, caDigest); - Path capabilityPath = testDirectory.resolve("run-owned-initial-admission-capability.json"); - Map capability = new LinkedHashMap<>(); - capability.put("schema", "firemud.run-owned-initial-admission-fixture.v1"); - capability.put("runId", runId); - capability.put("composeProjectName", composeProjectName); - capability.put("claimDigest", claimDigest); - capability.put("operationId", operationId.toString()); - capability.put("tenantId", 1); - capability.put( - "gameTemplateId", - templateRepository.findByTenantIdAndName("1", "Default Template").orElseThrow().getId()); - capability.put("ownerAccountId", 1); - capability.put("worldSlug", "demo"); - capability.put("worldDisplayName", "Demo World"); - capability.put("realmSlug", "production"); - capability.put("realmDisplayName", "Live Realm"); - capability.put("visible", true); - capability.put("publicProductionRealm", true); - capability.put("requiresCharacterSelection", false); - capability.put("stateScope", "SHARED"); - capability.put("characterCreationPolicy", "ALLOW_NEW"); - capability.put("gameSessionLeafSha256", leafDigest); - capability.put("gameSessionUriSan", SESSION_URI_SAN); - capability.put("worldManagementLeafSha256", worldManagementLeafDigest); - capability.put("worldManagementUriSan", WORLD_MANAGEMENT_URI_SAN); - capability.put("caCertificateSha256", caDigest); - Files.write(capabilityPath, objectMapper.writeValueAsBytes(capability)); - Files.setPosixFilePermissions( - capabilityPath, - Set.of( - PosixFilePermission.OWNER_READ, - PosixFilePermission.GROUP_READ, - PosixFilePermission.OTHERS_READ)); - - awaitFixtureCertificatesValid(sessionCertificate, worldManagementCertificate, caCertificate); - - Path receiptDirectory = - Files.createDirectory(testDirectory.resolve("run-owned-authored-world-source")); - Files.setPosixFilePermissions( - receiptDirectory, - Set.of( - PosixFilePermission.OWNER_READ, - PosixFilePermission.OWNER_WRITE, - PosixFilePermission.OWNER_EXECUTE, - PosixFilePermission.GROUP_READ, - PosixFilePermission.GROUP_WRITE, - PosixFilePermission.GROUP_EXECUTE, - PosixFilePermission.OTHERS_READ, - PosixFilePermission.OTHERS_WRITE, - PosixFilePermission.OTHERS_EXECUTE)); - Fixture fixture = - new Fixture( - operationId, - runId, - composeProjectName, - capabilityPath, - receiptDirectory.resolve("source-receipt.json"), - sessionCertificate, - worldManagementCertificate, - caCertificate, - leafDigest, - worldManagementLeafDigest, - caDigest); - configureSeeder(fixture); - ReflectionTestUtils.invokeMethod(seeder, "loadFixtureCapability"); - // Disposable test schema only: create the real fixture owner from inception, never backfill. - flyway.clean(); - flyway.migrate(); - if (prepareExistingOwner) { - new TransactionTemplate(transactionManager) - .executeWithoutResult( - status -> - creationRepository.createCandidate( - NAMESPACE, operationId, "1", "Demo Game", "Seed game")); - ReflectionTestUtils.setField(seeder, "initialAdmissionFixtureEnabled", false); - seeder.run(new DefaultApplicationArguments(new String[] {})); - } - return fixture; - } - - private void configureSeeder(Fixture fixture) { - ReflectionTestUtils.setField(seeder, "initialAdmissionFixtureEnabled", true); - ReflectionTestUtils.setField(seeder, "fixtureRunId", fixture.runId()); - ReflectionTestUtils.setField(seeder, "fixtureComposeProjectName", fixture.composeProjectName()); - ReflectionTestUtils.setField( - seeder, "fixtureCapabilityPath", fixture.capabilityPath().toString()); - ReflectionTestUtils.setField(seeder, "fixtureReceiptPath", fixture.receiptPath().toString()); - ReflectionTestUtils.setField( - seeder, "gameSessionLeafCertPath", fixture.gameSessionCertificatePath().toString()); - ReflectionTestUtils.setField( - seeder, "worldManagementLeafCertPath", fixture.worldManagementCertificatePath().toString()); - ReflectionTestUtils.setField(seeder, "workloadNamespace", NAMESPACE); - ReflectionTestUtils.setField(seeder, "caCertPath", fixture.caCertificatePath().toString()); - } - - private String certificateDigest(Path path) throws Exception { - try (var input = Files.newInputStream(path)) { - X509Certificate certificate = - (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); - return HexFormat.of() - .formatHex(MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded())); - } - } - - private void awaitFixtureCertificatesValid(Path... certificatePaths) throws Exception { - long deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); - while (true) { - try { - for (Path path : certificatePaths) { - try (var input = Files.newInputStream(path)) { - X509Certificate certificate = - (X509Certificate) - CertificateFactory.getInstance("X.509").generateCertificate(input); - certificate.checkValidity(); - } - } - return; - } catch (CertificateNotYetValidException exception) { - long remainingNanos = deadlineNanos - System.nanoTime(); - if (remainingNanos <= 0L) { - throw new IllegalStateException( - "Run-owned fixture certificates did not become valid within 5 seconds", exception); - } - TimeUnit.NANOSECONDS.sleep(Math.min(TimeUnit.MILLISECONDS.toNanos(10), remainingNanos)); - } - } - } - - private AuthoredWorldSourceEvidence changedSourceEvidence(AuthoredWorldSourceEvidence source) { - String changedWorldSlug = source.worldSlug() + "-changed"; - String requestDigest = - AuthoredWorldSourceDigest.requestDigest( - source.targetNamespace(), - source.registrationRequestId(), - source.canonicalTenantId(), - source.tenantSlug(), - changedWorldSlug, - source.worldDisplayName()); - String evidenceDigest = - AuthoredWorldSourceDigest.evidenceDigest( - source.targetNamespace(), - source.registrationRequestId(), - source.operationId(), - requestDigest, - source.canonicalTenantId(), - source.tenantSlug(), - changedWorldSlug, - source.worldDisplayName(), - source.sourceGameRowId(), - source.sourceGameTenantKey(), - source.provenanceKind()); - return new AuthoredWorldSourceEvidence( - source.schemaVersion(), - source.targetNamespace(), - source.registrationRequestId(), - source.operationId(), - requestDigest, - source.canonicalTenantId(), - source.tenantSlug(), - changedWorldSlug, - source.worldDisplayName(), - source.sourceGameRowId(), - source.sourceGameTenantKey(), - source.provenanceKind(), - evidenceDigest); - } - - private void runOpenSsl(String... arguments) throws Exception { - Process process = - new ProcessBuilder(concat(new String[] {"openssl"}, arguments)) - .redirectErrorStream(true) - .start(); - String output = new String(process.getInputStream().readAllBytes()); - if (process.waitFor() != 0) { - throw new IOException("OpenSSL fixture certificate generation failed: " + output); - } - } - - private String[] concat(String[] prefix, String[] suffix) { - String[] combined = new String[prefix.length + suffix.length]; - System.arraycopy(prefix, 0, combined, 0, prefix.length); - System.arraycopy(suffix, 0, combined, prefix.length, suffix.length); - return combined; - } - - private record Fixture( - UUID operationId, - String runId, - String composeProjectName, - Path capabilityPath, - Path receiptPath, - Path gameSessionCertificatePath, - Path worldManagementCertificatePath, - Path caCertificatePath, - String gameSessionLeafSha256, - String worldManagementLeafSha256, - String caCertificateSha256) {} - @Test void freshBaselineSeedAndRestartReuseActualOwnerIdentityAndOpaqueBundle() { FoundationFixture fixture = foundationFixture(null); @@ -2885,4 +1458,27 @@ String artifactXmin() { .get("xmin", String.class); } } + + private static final class FixedReadObserver implements io.grpc.stub.StreamObserver { + public FixedReadObserver() {} + + public T value; + public Status.Code failure; + public boolean completed; + + @Override + public void onNext(T response) { + value = response; + } + + @Override + public void onError(Throwable error) { + failure = Status.fromThrowable(error).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java index 0455f09e6f..fef128fe17 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java @@ -1,6 +1,7 @@ package unit.net.firedevops.firemud.gamedesign.service.impl; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -180,7 +181,7 @@ void classifiesJooqStorageFailuresByConnectionSqlStateWithoutLeakingDetails() { } private static void assertStorageFailure(WorldSourceObserver observer, Status.Code expectedCode) { - assertThat(observer.failure).isEqualTo(expectedCode); + assertThat(observer.failure).as("owner storage code").isEqualTo(expectedCode); assertThat(observer.response).isNull(); assertThat(observer.completed).isFalse(); assertThat(observer.failureDescription) @@ -298,4 +299,32 @@ public void onCompleted() { completed = true; } } + + @Test + void storageFailureClassificationRetriesOnlyConnectionAndTimeoutTransactions() { + var failures = + new org.springframework.transaction.TransactionException[] { + new org.springframework.transaction.CannotCreateTransactionException( + "connection unavailable"), + new org.springframework.transaction.TransactionTimedOutException("timed out"), + new org.springframework.transaction.IllegalTransactionStateException( + "propagation mismatch"), + new org.springframework.transaction.UnexpectedRollbackException("rollback only"), + new org.springframework.transaction.NestedTransactionNotSupportedException( + "nested unsupported"), + new org.springframework.transaction.InvalidIsolationLevelException( + "isolation unsupported") + }; + for (int index = 0; index < failures.length; index++) { + var failure = failures[index]; + doThrow(failure) + .when(authoredWorldSourceRepository) + .read(SOURCE_OPERATION_ID, WORLD_TENANT_ID, WORLD_SLUG, "test"); + var observer = callWorldSource(worldSourceRequest(), WORLD_URI); + assertThat(observer.failure) + .as("transaction %s", failure.getClass().getSimpleName()) + .isEqualTo(index < 2 ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL); + assertStorageFailure(observer, index < 2 ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL); + } + } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java index 85365a5621..8165da98d3 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java @@ -134,6 +134,25 @@ void fixtureReadFailuresKeepRequestAuthorityAndStorageStatusesDistinct() { new FailureCase( new CannotCreateTransactionException("transaction unavailable"), Status.Code.UNAVAILABLE), + new FailureCase( + new org.springframework.transaction.TransactionTimedOutException( + "transaction timed out"), + Status.Code.UNAVAILABLE), + new FailureCase( + new org.springframework.transaction.IllegalTransactionStateException( + "propagation mismatch"), + Status.Code.INTERNAL), + new FailureCase( + new org.springframework.transaction.UnexpectedRollbackException("rollback only"), + Status.Code.INTERNAL), + new FailureCase( + new org.springframework.transaction.NestedTransactionNotSupportedException( + "nested unsupported"), + Status.Code.INTERNAL), + new FailureCase( + new org.springframework.transaction.InvalidIsolationLevelException( + "isolation unsupported"), + Status.Code.INTERNAL), new FailureCase( new DataIntegrityViolationException( "connection failed", new SQLException("connection lost", "08006")), @@ -160,6 +179,7 @@ void fixtureReadFailuresKeepRequestAuthorityAndStorageStatusesDistinct() { GetAuthoredWorldVersionStateRequest.getDefaultInstance(), refusingObserver(versionFailure)); assertThat(Status.fromThrowable(sourceFailure.get()).getCode()) + .as("source transaction/storage %s", failure.exception().getClass().getSimpleName()) .isEqualTo(failure.expectedCode()); assertThat(Status.fromThrowable(versionFailure.get()).getCode()) .isEqualTo(failure.expectedCode()); 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 bd49f210f8..411b6d6fc6 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 @@ -541,7 +541,25 @@ WorldInstanceLifecycleSnapshotDto prepareRunOwnedFixture( throw fixtureEvidenceMismatch(); } prepareCounter.increment(); - return snapshot(materialized); + 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) { 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 730a3d6433..d5a24d6c9e 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 @@ -183,9 +183,6 @@ public WorldAuthoredSourceIntakeReceipt intakeRunOwnedFixture( expectedSource.operationId(), expectedSource.evidenceDigest()); if (!fixtureOperationId.toString().equals(trustedReceipt.fixtureOperationId()) - || !fixtureEvidence - .fixtureProvenanceDigest() - .equals(trustedReceipt.fixturePolicySeal().evidenceDigest()) || !workloadNamespace.equals(expectedSource.targetNamespace()) || !fixtureEvidence .launchDescriptor() 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 689b7fc891..b210d42746 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 @@ -111,9 +111,6 @@ public WorldAuthoredVersionIdentityReceipt associateRunOwnedFixture( || !sourceReceipt.worldSlug().equals(trustedSource.worldSlug()) || !sourceReceipt.sourceOperationId().equals(trustedSource.operationId()) || !sourceReceipt.sourceEvidenceDigest().equals(trustedSource.evidenceDigest()) - || !fixtureEvidence - .fixtureProvenanceDigest() - .equals(fixtureEvidence.sourceReceipt().fixturePolicySeal().evidenceDigest()) || !gs.fixturePolicySeal().equals(fixtureEvidence.sourceReceipt().fixturePolicySeal()) || !gs.canonicalTenantId().equals(trustedSource.canonicalTenantId()) || !gs.canonicalVersionId() 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/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java index 7541ecff3f..f5ca868fe2 100644 --- 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 @@ -1,5 +1,9 @@ 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; @@ -55,7 +59,6 @@ import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository; import org.flywaydb.core.Flyway; -import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -98,112 +101,6 @@ class RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest { "sha256:f817af2770072bab0384c30c19b8cd30fce7a5a33f7587faed0024aa7c0909bc"; private static final String VALID_DIGEST = "sha256:" + "a".repeat(64); - 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")); - - private static final String HISTORY = "flyway_schema_history_world_management_service"; - // Literal disclosed donor postimages, not qualification or current authority. private static final Map PROTECTED_ARTIFACTS = Map.ofEntries( Map.entry( @@ -465,14 +362,27 @@ void packageOwnerPreparationRestartAndFreshObservationRetainAllRowsAndXmin() { 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)); - assertThat(prepared.tenantId()).isEqualTo(association.worldPrivateKeys().tenantId()); - assertThat(prepared.gameInstanceId()) - .isEqualTo(association.worldPrivateKeys().gameInstanceId()); - assertThat(prepared.versionId()).isEqualTo(association.worldPrivateKeys().versionId()); + 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 = ?", @@ -481,8 +391,19 @@ void packageOwnerPreparationRestartAndFreshObservationRetainAllRowsAndXmin() { assertPresetContent(association); var original = allRows(dsl); var fresh = RunOwnedWorldFixtureEvidenceTestFixtures.freshObservation(evidence); - assertThat(RunOwnedWorldFixtureLifecycleTestFactory.prepare(nativeService(fresh), fresh)) - .isEqualTo(prepared); + 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( @@ -1837,25 +1758,6 @@ private DriverManagerDataSource dataSource(String schema) { return source; } - private static Flyway migration(DriverManagerDataSource source, String schema, String target) { - Path root = repositoryRoot(); - var configuration = - Flyway.configure() - .dataSource(source) - .schemas(schema) - .defaultSchema(schema) - .table(HISTORY) - .placeholders(Map.of("serviceSchema", schema)) - .locations( - "filesystem:" - + root.resolve( - "services/world-management-service/src/main/resources/db/migration"), - "filesystem:" - + root.resolve("services/common-saga/src/main/resources/db/migration/saga")); - if (target != null) configuration.target(MigrationVersion.fromVersion(target)); - return configuration.load(); - } - private static List versions(DSLContext connection) { return connection .fetch( @@ -1895,15 +1797,6 @@ private static List remainingVersionsThrough(int latestWorldVersion) { return List.copyOf(versions); } - 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("FireMUD repository root unavailable"); - } - private static List retainedRows( DSLContext connection, String schema, String table, List columns) { String projection = 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 index 8aa523ed1a..db72d9c0be 100644 --- 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 @@ -1,5 +1,10 @@ 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; @@ -12,7 +17,6 @@ import java.sql.Statement; import java.util.HexFormat; import java.util.List; -import java.util.Map; import java.util.UUID; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; @@ -36,7 +40,6 @@ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") class WorldCanonicalInstanceExecutionTerminalSchemaPostgresIntegrationTest { - private static final String HISTORY = "flyway_schema_history_world_management_service"; private static final String V1035_FILE = "V1035__world_start_session_execution_terminal_fence.sql"; private static final String V1035_SHA256 = @@ -56,11 +59,8 @@ void forwardRepairPreservesTerminalTriggerAndWorksWithoutWorldInCallerSearchPath source.setSchema(schema); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); 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); String qualifiedExecutionTable = qualified(schema, "world_canonical_instance_execution"); try { assertThat( @@ -142,20 +142,6 @@ void forwardRepairPreservesTerminalTriggerAndWorksWithoutWorldInCallerSearchPath } } - private 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(); - } - private static ExecutionRow executionRow(String requestId) { String inputJson = "{\"testOnly\":\"denied-direct-insert\"}"; return new ExecutionRow( @@ -335,15 +321,6 @@ private static String qualified(String schema, String object) { return "\"" + schema + "\".\"" + object + "\""; } - 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"); - } - private record ExecutionRow( String namespace, UUID tenantId, 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 8b1281a7a2..00191008b7 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; @@ -75,114 +81,8 @@ @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()); @@ -212,7 +112,7 @@ void exactParentWithRetainedOwnerAndLegacyWorldRowsUpgradesToHistoricalGuardedFr 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(); @@ -322,8 +222,12 @@ void exactParentWithRetainedOwnerAndLegacyWorldRowsUpgradesToHistoricalGuardedFr // 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 = - historicalGuardedStage( - dataSource, schema, "filesystem:" + worldMigrations, "filesystem:" + sagaMigrations); + flyway( + dataSource, + schema, + MigrationVersion.fromVersion("1007.1"), + "filesystem:" + worldMigrations, + "filesystem:" + sagaMigrations); assertThat(current.getConfiguration().isOutOfOrder()).isFalse(); current.migrate(); current.validate(); @@ -435,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(); @@ -611,7 +504,7 @@ void schemaTwoRepositorySnapshotRetainsEveryOriginalByteAndXminThroughSchemaThre // 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, worldLocation, sagaLocation).migrate(); + flyway(source, schema, null, worldLocation, sagaLocation).migrate(); assertThat( dsl.fetch( @@ -651,15 +544,13 @@ void historicalGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoin 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 { // Controlled permission-unverified component storage at the historical guarded frontier. // Later Account/APPLIED owners retain their default-current denial requirements. - historicalGuardedStage(source, schema, worldLocation, sagaLocation).migrate(); + flyway(source, schema, MigrationVersion.fromVersion("1007.1"), worldLocation, sagaLocation) + .migrate(); assertCanonicalFrozenMutationTriggerBindings(dsl, schema); var upstream = controlledSource(); var intake = @@ -1050,7 +941,7 @@ void historicalGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoin // Historical storage proof above is retained as such. Repeat the actual naked-write, // schema-2 capture, wrong-checkpoint capture, and missing-owner-history denials after the // complete current World/Saga migration frontier. - Flyway currentFrontier = flyway(source, schema, worldLocation, sagaLocation); + Flyway currentFrontier = flyway(source, schema, null, worldLocation, sagaLocation); currentFrontier.migrate(); currentFrontier.validate(); assertThat(currentFrontier.info().pending()).isEmpty(); @@ -1414,30 +1305,6 @@ private static AuthoredWorldSourceEvidence controlledSource() { "NEW_GAME_ROW")); } - private static Flyway historicalGuardedStage( - DriverManagerDataSource source, String schema, String... locations) { - return Flyway.configure() - .dataSource(source) - .schemas(schema) - .defaultSchema(schema) - .table(HISTORY) - .placeholders(Map.of("serviceSchema", schema)) - .locations(locations) - .target(MigrationVersion.fromVersion("1007.1")) - .load(); - } - - 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 " @@ -1462,13 +1329,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/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java index 3670dbf2fd..881670c0a0 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java @@ -21,7 +21,6 @@ import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.security.Security; import java.security.cert.X509Certificate; import java.time.Instant; @@ -31,7 +30,6 @@ import java.util.Set; import java.util.UUID; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; -import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationClient; import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; @@ -40,15 +38,6 @@ 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.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.client.GameDesignClient; import net.firedevops.firemud.worldmanagement.client.GameDesignClient.LaunchDescriptorReadback; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; @@ -72,11 +61,10 @@ @ExtendWith(OutputCaptureExtension.class) class RunOwnedWorldLaunchEvidenceProviderTest { - private static final String CLAIM_DIGEST = controlledClaimDigest(); private static final String OPERATION_ID = - RunOwnedInitialAdmissionFixtureWireCodec.fixtureOperationId( - CLAIM_DIGEST, "fixture-run", "firemud-fixture-run", "a".repeat(64), "c".repeat(64)) - .toString(); + 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; @@ -154,18 +142,6 @@ private static void withControlledPeer(GrpcPeerIdentity peer, String leaf, Runna Security.addProvider(new BouncyCastleProvider()); } - 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); - } - } - @Test void bindingDigestNormalizesAcceptedBlankOptionalOverridesToAbsent() { RunOwnedWorldLaunchEvidence evidence = fixtureEvidence(); @@ -827,238 +803,15 @@ private static RunOwnedWorldLaunchEvidence fixtureEvidence( String worldManagementLeafSha256, String caCertificateSha256, UUID canonicalTenantId) { - 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, - false, - null, - "{}", - "genrev-11", - 77L, - 77L, - RELEASE_REF, - false, - 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, - 1L, - "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 RunOwnedWorldLaunchEvidence( - capability, - receipt, - descriptor, - new byte[] {1}, - new byte[] {2}, + return RunOwnedWorldLaunchEvidenceTestFixtures.create( + mismatchedSeal, gameSessionLeafSha256, - RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, worldManagementLeafSha256, caCertificateSha256, - association); + canonicalTenantId, + 1L, + false, + false); } private static RunOwnedWorldLaunchEvidenceProvider provider( diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceTestFixtures.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceTestFixtures.java index b329bb91e8..12eb6f9201 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceTestFixtures.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceTestFixtures.java @@ -23,10 +23,6 @@ */ public final class RunOwnedWorldLaunchEvidenceTestFixtures { private static final String CLAIM_DIGEST = controlledClaimDigest(); - private static final String OPERATION_ID = - RunOwnedInitialAdmissionFixtureWireCodec.fixtureOperationId( - CLAIM_DIGEST, "fixture-run", "firemud-fixture-run", "a".repeat(64), "b".repeat(64)) - .toString(); private static final String RELEASE_REF = "8ce42642-53ae-4d07-aab8-37c43ce66e0c"; private RunOwnedWorldLaunchEvidenceTestFixtures() {} @@ -49,9 +45,36 @@ public static RunOwnedWorldLaunchEvidence create() { public static RunOwnedWorldLaunchEvidence createWithDescriptorOverrides( boolean scriptPatchVersionPresent, boolean remapSetIdPresent) { - UUID registrationId = UUID.fromString(OPERATION_ID); + return create( + false, + "a".repeat(64), + "c".repeat(64), + "b".repeat(64), + UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6d"), + 9L, + scriptPatchVersionPresent, + remapSetIdPresent); + } + + static RunOwnedWorldLaunchEvidence create( + boolean mismatchedSeal, + String gameSessionLeafSha256, + String worldManagementLeafSha256, + String caCertificateSha256, + UUID canonicalTenantId, + long capabilityEpoch, + 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"); - UUID canonicalTenantId = UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6d"); String requestDigest = AuthoredWorldSourceDigest.requestDigest( "dev", registrationId, canonicalTenantId, "fixture-tenant", "demo", "Demo World"); @@ -86,7 +109,7 @@ public static RunOwnedWorldLaunchEvidence createWithDescriptorOverrides( var descriptorRequest = new AuthoredWorldLaunchDescriptorEvidence.Request( "dev", - OPERATION_ID, + operationId, canonicalTenantId, "demo", sourceOperationId, @@ -149,10 +172,10 @@ public static RunOwnedWorldLaunchEvidence createWithDescriptorOverrides( RunOwnedInitialAdmissionFixtureWireCodec.CAPABILITY_SCHEMA, "fixture-run", "firemud-fixture-run", - OPERATION_ID, + operationId, 42L, 17L, - 9L, + capabilityEpoch, "demo", "Demo World", "production", @@ -162,11 +185,11 @@ public static RunOwnedWorldLaunchEvidence createWithDescriptorOverrides( false, "SHARED", "ALLOW_NEW", - "a".repeat(64), + gameSessionLeafSha256, RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, - "b".repeat(64), + caCertificateSha256, RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, - "c".repeat(64), + worldManagementLeafSha256, CLAIM_DIGEST); // Controlled constructor data remains untrusted; these commitments do not prove owner writes. UUID creationRequestId = UUID.fromString("1b3fdbda-a9f6-4cf5-b21e-b43f0e855f65"); @@ -210,33 +233,44 @@ public static RunOwnedWorldLaunchEvidence createWithDescriptorOverrides( new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal( RunOwnedInitialAdmissionFixtureWireCodec.FIXTURE_POLICY_SEAL_SCHEMA, RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE, - UUID.fromString(OPERATION_ID), + UUID.fromString(operationId), policyRequestDigest, RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( - UUID.fromString(OPERATION_ID), policyRequestDigest)); + 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", - OPERATION_ID, + operationId, RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE, RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, - "a".repeat(64), - "b".repeat(64), + gameSessionLeafSha256, + caCertificateSha256, RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, - "c".repeat(64), + worldManagementLeafSha256, source, launchRead, creation, - policySeal); + 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(OPERATION_ID), policySeal.evidenceDigest()); + readRequestId, "dev", UUID.fromString(operationId), policySeal.evidenceDigest()); var association = new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult( associationRequest, @@ -258,10 +292,10 @@ public static RunOwnedWorldLaunchEvidence createWithDescriptorOverrides( descriptor, new byte[] {1}, new byte[] {2}, - "a".repeat(64), + gameSessionLeafSha256, RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, - "c".repeat(64), - "b".repeat(64), + worldManagementLeafSha256, + caCertificateSha256, association); } } From 0cf5a607f7e7e1354293a2b604ac86719371a0c5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 12:17:32 +1300 Subject: [PATCH 12/45] Keep one receiving-proof owner and pin preset migration identities --- ...ame-authoring-publishing-and-activation.md | 6 +--- ...RunOwnedWorldFixedPresetResourcesTest.java | 34 +++++++++++++++++++ 2 files changed, 35 insertions(+), 5 deletions(-) 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 4fbafc24cc..caad2cc78c 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 @@ -14,11 +14,7 @@ The coherent receiving successor for [PR #3196](https://github.com/benhook1013/F ### Fixed fixture source and Version reads -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. - -After the corrected readiness child `7ab19d077f021b044b2d45409d892324c6204a48` restores original Game Session migration artifacts and adds forward V1011, local receiving merge `ec340c6a41a53127ca6fb3b57c399c12c843108e` passes all 17 freshly executed fixture-producer cases, including actual authenticated Game Design → Game Session → World composition. Ten Game Session original-history PostgreSQL cases also pass, with owning generation, affected formatting and documentation checks. This is focused receiving proof under controlled capabilities/PKI; unchanged broader proof keeps its earlier attribution, and actual deployment cohorts, mixed migration histories and genuine authority remain unqualified. - -After the qualified readiness-child carry at `f9e62a9b99850dc9cb526635e416f25e91f0e908`, the local receiving merge `a5f76d8cfa2092f01ccfe6ad0641878b8adc362b` passes all 515 freshly executed Game Design unit cases and 142 freshly executed native integrations, with formatting, static and documentation checks. The three-service native composition includes the current shared creation/source provenance comparison and real committed Game Session/World owners; controlled test capabilities and PKI remain its upstream boundary. This proof does not qualify deployed claimed Compose startup/restart, genuine Account authority or alternate already-applied Game Session migration bytes. +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 receiving Game Design cut, 510 unit results retain their earlier fresh execution on unchanged production inputs, while 142 native PostgreSQL-backed cases execute freshly, including 22 fixture cases and the actual producer → persisted Game Session `STARTING` → World `PREPARING` composition across three production mTLS handlers. The fixed read adapters are registered in a real managed annotation context with their actual producer owners. The final native parent-file enumeration correction passes nine fresh storage-upgrade cases, formatting and required static checks; the other native postimages retain their preceding execution attribution. The shared World PREPARING implementation and proof are maintained by [World Runtime and Movement](./world-runtime-and-movement.md#fixed-fixture-preparing-owner-preparation). Complete Spring Boot and packaged fresh/restart remain unqualified, and no genuine Gameplay handoff is closed. 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 index f66888d401..dd71ea93b7 100644 --- 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 @@ -6,6 +6,7 @@ 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; @@ -19,6 +20,39 @@ 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); From f3eb4778d93ec1ad5e030c2c0c9a33b5246a4adc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 13:18:02 +1300 Subject: [PATCH 13/45] Bind fixture association copies to retained World authority --- ...ame-authoring-publishing-and-activation.md | 2 +- .../world-runtime-and-movement.md | 8 +- ..._fixture_association_owner_copy_checks.sql | 28 ++++ ...resetResourcesPostgresIntegrationTest.java | 156 ++++++++++++++++++ 4 files changed, 190 insertions(+), 4 deletions(-) create mode 100644 services/world-management-service/src/main/resources/db/migration/V1042.4__world_fixture_association_owner_copy_checks.sql 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 caad2cc78c..e16c1055bd 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 @@ -16,7 +16,7 @@ The coherent receiving successor for [PR #3196](https://github.com/benhook1013/F 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 receiving Game Design cut, 510 unit results retain their earlier fresh execution on unchanged production inputs, while 142 native PostgreSQL-backed cases execute freshly, including 22 fixture cases and the actual producer → persisted Game Session `STARTING` → World `PREPARING` composition across three production mTLS handlers. The fixed read adapters are registered in a real managed annotation context with their actual producer owners. The final native parent-file enumeration correction passes nine fresh storage-upgrade cases, formatting and required static checks; the other native postimages retain their preceding execution attribution. The shared World PREPARING implementation and proof are maintained by [World Runtime and Movement](./world-runtime-and-movement.md#fixed-fixture-preparing-owner-preparation). Complete Spring Boot and packaged fresh/restart remain unqualified, and no genuine Gameplay handoff is closed. +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. The current actual producer → persisted Game Session `STARTING` → World `PREPARING` composition across three production mTLS handlers is covered by [RunOwnedFixtureOwnerCompositionCrossServiceTest](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java); its current proof is recorded in [World Runtime and Movement](./world-runtime-and-movement.md#fixed-fixture-preparing-owner-preparation). 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 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 9e73433161..105927008b 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -20,7 +20,9 @@ The terminal Hosted fix batch is qualified at `9e7c82733de22a61d06b1c614400f4169 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 current frontier adds 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 exercise the current default 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 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 adds forward V1042.4, bringing the default 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 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. @@ -28,9 +30,9 @@ The corrected receiving child `7ab19d077f021b044b2d45409d892324c6204a48` restore 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. -The local owner successor contains 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 passes formatting/static validation, 307 unit results reused from their preceding fresh execution and 75 freshly executed integrations (73 PostgreSQL-backed and two controlled mTLS). Game Design separately passes 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 passes nine freshly executed storage-upgrade cases and all required Game Design static checks; its 510 unit results are reused from earlier unchanged production inputs. Exact source and XML archives retain these separate scopes. The synchronous prepare entry uses fresh remote reads before SQL and preserves ordinary `REQUIRED` transactions. +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. -Fresh default-order 75-file installation, installed 34→40→75 upgrade, current-75 schema-2 snapshot retention, exact topology/manifest readback, rollback/races and reconstructed-owner retry pass physical execution. The GDS fixed read adapters are registered in a real managed annotation context with actual producer owners before serving their production handlers. Controlled test capabilities and PKI remain distinct from an actual claimed Compose deployment; complete packaged/Spring Boot fresh/restart proof remains open. Historical pre-1037 canonical Human schema-1 allocation retention is unconstructed because its genuine preparation/execution prerequisites are unavailable; no fake Account protection or disabled storage guard supplies that coverage. Historical guarded positive storage is explicitly pinned to 1007.1 and does not qualify current Account/APPLIED authority. Fixture bootstrap, activation, hold acquire/finalize, first OPEN prerequisites and initial placement stay unavailable; no Entity or operational-region evidence is 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. +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 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/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 index f5ca868fe2..2a1bb5cc4b 100644 --- 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 @@ -419,6 +419,161 @@ void packageOwnerPreparationRestartAndFreshObservationRetainAllRowsAndXmin() { 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(); @@ -1781,6 +1936,7 @@ private static List remainingVersions() { versions.add("1042.1"); versions.add("1042.2"); versions.add("1042.3"); + versions.add("1042.4"); return List.copyOf(versions); } From ecf6c946846e7f66fa16de8ea4f3df08656e500e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 13:50:35 +1300 Subject: [PATCH 14/45] Require both fixture rooms and prove authorized owner storage failures --- .../runtime-and-data.md | 2 +- .../world-runtime-and-movement.md | 4 +- .../AuthoredWorldVersionStateGrpcService.java | 8 +- ...AuthoredWorldOwnerReadGrpcServiceTest.java | 179 +++++++++++++----- ...ld_fixed_preset_complete_room_readback.sql | 35 ++++ ...resetResourcesPostgresIntegrationTest.java | 149 +++++++++++++++ 6 files changed, 325 insertions(+), 52 deletions(-) create mode 100644 services/world-management-service/src/main/resources/db/migration/V1042.5__world_fixed_preset_complete_room_readback.sql 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 4505ab9ea4..dacb24540e 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -28,7 +28,7 @@ The owner materializes the exact sealed fixed preset into one region, one zone, 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, and V1042.3 gives forbidden fixture row updates their own diagnostic without changing guard predicates or 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. These storage checks do not grant Human protection, fixture activation or hold authority. Later fixture World row mutations, lifecycle transitions, hold acquire/finalize, initial placement and player-admission owners reject the fixture variant before effects. 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. +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. 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. These storage checks do not grant Human protection, fixture activation or hold authority. Later fixture World row mutations, lifecycle transitions, hold acquire/finalize, initial placement and player-admission owners reject the fixture variant before effects. 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. ### Authored-world source retention 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 105927008b..bc6ceca5b2 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -22,7 +22,9 @@ Historical qualification before V1042.1–V1042.3: owning generation and affecte 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 adds forward V1042.4, bringing the default 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 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 the current inventory 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 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. diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java index 338defa01c..eef3178b22 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java @@ -107,9 +107,13 @@ public void getAuthoredWorldVersionState( : "Game Design owner storage could not be read") .asRuntimeException()); } catch (TransactionException exception) { + Status storageStatus = AuthoredWorldSourceReadGrpcService.storageFailureStatus(exception); responseObserver.onError( - Status.UNAVAILABLE - .withDescription("Game Design owner snapshot is temporarily unavailable") + storageStatus + .withDescription( + storageStatus.getCode() == Status.Code.UNAVAILABLE + ? "Game Design owner snapshot is temporarily unavailable" + : "Game Design owner snapshot could not be read") .asRuntimeException()); } catch (IllegalStateException exception) { responseObserver.onError( diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java index 8165da98d3..90da25395d 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java @@ -3,13 +3,17 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; +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.stub.StreamObserver; import java.sql.SQLException; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt; import net.firedevops.firemud.gamedesign.data.RunOwnedFixtureOwnerReadAuthorization; import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.service.impl.RunOwnedFixtureAuthoredWorldSourceReadGrpcService; @@ -23,6 +27,7 @@ import org.springframework.dao.TransientDataAccessResourceException; import org.springframework.transaction.CannotCreateTransactionException; import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.SimpleTransactionStatus; class RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest { @Test @@ -114,54 +119,7 @@ void authorizationDenialAndMissingPreexistingOwnerNeverReachKernelsOrPublishResp @Test void fixtureReadFailuresKeepRequestAuthorityAndStorageStatusesDistinct() { - for (var failure : - new FailureCase[] { - new FailureCase( - new SecurityException("controlled peer refusal"), Status.Code.PERMISSION_DENIED), - new FailureCase( - new IllegalArgumentException("owner selector mismatch"), - Status.Code.FAILED_PRECONDITION), - new FailureCase( - new RunOwnedFixtureOwnerReadAuthorization.RequestDecodingException( - new IllegalArgumentException("malformed wire request")), - Status.Code.INVALID_ARGUMENT), - new FailureCase( - new DataAccessResourceFailureException("storage unavailable"), - Status.Code.UNAVAILABLE), - new FailureCase( - new TransientDataAccessResourceException("transient storage failure"), - Status.Code.UNAVAILABLE), - new FailureCase( - new CannotCreateTransactionException("transaction unavailable"), - Status.Code.UNAVAILABLE), - new FailureCase( - new org.springframework.transaction.TransactionTimedOutException( - "transaction timed out"), - Status.Code.UNAVAILABLE), - new FailureCase( - new org.springframework.transaction.IllegalTransactionStateException( - "propagation mismatch"), - Status.Code.INTERNAL), - new FailureCase( - new org.springframework.transaction.UnexpectedRollbackException("rollback only"), - Status.Code.INTERNAL), - new FailureCase( - new org.springframework.transaction.NestedTransactionNotSupportedException( - "nested unsupported"), - Status.Code.INTERNAL), - new FailureCase( - new org.springframework.transaction.InvalidIsolationLevelException( - "isolation unsupported"), - Status.Code.INTERNAL), - new FailureCase( - new DataIntegrityViolationException( - "connection failed", new SQLException("connection lost", "08006")), - Status.Code.UNAVAILABLE), - new FailureCase( - new DataIntegrityViolationException( - "constraint rejected", new SQLException("duplicate key", "23505")), - Status.Code.INTERNAL) - }) { + for (var failure : failureCases()) { var authorization = mock(RunOwnedFixtureOwnerReadAuthorization.class); var repository = mock(GameAuthoredWorldSourceRepository.class); var transactions = mock(PlatformTransactionManager.class); @@ -189,6 +147,131 @@ void fixtureReadFailuresKeepRequestAuthorityAndStorageStatusesDistinct() { } } + @Test + void authorizedStorageFailuresReachRepositoriesAndTransactions() { + var sourceRequest = + ResolveAuthoredWorldSourceRequest.newBuilder() + .setRequestId("11111111-1111-4111-8111-111111111111") + .setOperationId("22222222-2222-4222-8222-222222222222") + .setCanonicalTenantId("33333333-3333-4333-8333-333333333333") + .setWorldSlug("demo-world") + .build(); + var versionRequest = + GetAuthoredWorldVersionStateRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace("dev") + .setReadRequestId(sourceRequest.getRequestId()) + .setSourceOperationId(sourceRequest.getOperationId()) + .setCanonicalTenantId(sourceRequest.getCanonicalTenantId()) + .setWorldSlug(sourceRequest.getWorldSlug()) + .setExpectedSourceEvidenceDigest("sha256:" + "a".repeat(64)) + .setVersionId(1) + .build(); + var peer = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/dev/sa/world-management-service") + .orElseThrow()); + for (var failure : failureCases()) { + if (failure.expectedCode() != Status.Code.UNAVAILABLE + && failure.expectedCode() != Status.Code.INTERNAL) continue; + for (boolean transactionFailure : new boolean[] {false, true}) { + var authorization = mock(RunOwnedFixtureOwnerReadAuthorization.class); + var repository = mock(GameAuthoredWorldSourceRepository.class); + var transactions = mock(PlatformTransactionManager.class); + var receipt = mock(SourceReceipt.class); + when(authorization.authorizeSource(sourceRequest)).thenReturn(receipt); + when(authorization.authorizeVersion(versionRequest)).thenReturn(receipt); + when(repository.read(any(), any(), any(), any())).thenThrow(failure.exception()); + if (transactionFailure) { + when(transactions.getTransaction(any())).thenThrow(failure.exception()); + } else { + when(transactions.getTransaction(any())).thenReturn(new SimpleTransactionStatus()); + when(repository.readVersionStateSnapshot( + any(), any(), any(), any(), any(), any(), org.mockito.ArgumentMatchers.anyLong())) + .thenThrow(failure.exception()); + } + var sourceFailure = new AtomicReference(); + var versionFailure = new AtomicReference(); + peer.run( + () -> { + new RunOwnedFixtureAuthoredWorldSourceReadGrpcService( + authorization, repository, "dev") + .resolveAuthoredWorldSource(sourceRequest, refusingObserver(sourceFailure)); + new RunOwnedFixtureAuthoredWorldVersionStateGrpcService( + authorization, transactions, repository, "dev") + .getAuthoredWorldVersionState(versionRequest, refusingObserver(versionFailure)); + }); + assertThat(Status.fromThrowable(sourceFailure.get()).getCode()) + .as("authorized source storage %s", failure.exception().getClass().getSimpleName()) + .isEqualTo(failure.expectedCode()); + assertThat(Status.fromThrowable(versionFailure.get()).getCode()) + .as( + "authorized Version %s failure %s", + transactionFailure ? "transaction" : "repository", + failure.exception().getClass().getSimpleName()) + .isEqualTo(failure.expectedCode()); + assertThat(Status.fromThrowable(sourceFailure.get()).getDescription()) + .doesNotContain(failure.exception().getMessage()); + assertThat(Status.fromThrowable(versionFailure.get()).getDescription()) + .doesNotContain(failure.exception().getMessage()); + verify(repository).read(any(), any(), any(), any()); + verify(transactions).getTransaction(any()); + if (!transactionFailure) + verify(repository) + .readVersionStateSnapshot( + any(), any(), any(), any(), any(), any(), org.mockito.ArgumentMatchers.anyLong()); + } + } + } + + private static FailureCase[] failureCases() { + return new FailureCase[] { + new FailureCase( + new SecurityException("controlled peer refusal"), Status.Code.PERMISSION_DENIED), + new FailureCase( + new IllegalArgumentException("owner selector mismatch"), Status.Code.FAILED_PRECONDITION), + new FailureCase( + new RunOwnedFixtureOwnerReadAuthorization.RequestDecodingException( + new IllegalArgumentException("malformed wire request")), + Status.Code.INVALID_ARGUMENT), + new FailureCase( + new DataAccessResourceFailureException("storage unavailable"), Status.Code.UNAVAILABLE), + new FailureCase( + new TransientDataAccessResourceException("transient storage failure"), + Status.Code.UNAVAILABLE), + new FailureCase( + new CannotCreateTransactionException("transaction unavailable"), Status.Code.UNAVAILABLE), + new FailureCase( + new org.springframework.transaction.TransactionTimedOutException("transaction timed out"), + Status.Code.UNAVAILABLE), + new FailureCase( + new org.springframework.transaction.IllegalTransactionStateException( + "propagation mismatch"), + Status.Code.INTERNAL), + new FailureCase( + new org.springframework.transaction.UnexpectedRollbackException("rollback only"), + Status.Code.INTERNAL), + new FailureCase( + new org.springframework.transaction.NestedTransactionNotSupportedException( + "nested unsupported"), + Status.Code.INTERNAL), + new FailureCase( + new org.springframework.transaction.InvalidIsolationLevelException( + "isolation unsupported"), + Status.Code.INTERNAL), + new FailureCase( + new DataIntegrityViolationException( + "connection failed", new SQLException("connection lost", "08006")), + Status.Code.UNAVAILABLE), + new FailureCase( + new DataIntegrityViolationException( + "constraint rejected", new SQLException("duplicate key", "23505")), + Status.Code.INTERNAL) + }; + } + private record FailureCase(RuntimeException exception, Status.Code expectedCode) {} private static StreamObserver refusingObserver(AtomicReference failure) { 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/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 index 2a1bb5cc4b..1ed719ff01 100644 --- 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 @@ -1597,6 +1597,7 @@ void realWorldOwnersMaterializeSixFixtureMappingsAndReplayExactCommittedBytes() assertThat(allRows(dsl)) .as("no row or byte changes after standalone readback") .isEqualTo(readbackRowsBefore); + assertRoomReadbackRequiresBothRooms(plan, worldId, privateKey, readbackRowsBefore); assertNoPendingManifests(worldId); assertThat( scalarLong( @@ -1937,6 +1938,7 @@ private static List remainingVersions() { versions.add("1042.2"); versions.add("1042.3"); versions.add("1042.4"); + versions.add("1042.5"); return List.copyOf(versions); } @@ -2068,6 +2070,153 @@ private void assertFixedPresetReadbackMode( 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, From bdd3340838179f1f23023528c8a6ce7d0ba16953 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 17:20:47 +1300 Subject: [PATCH 15/45] Stage canonical World source and restore authenticated predecessor lifecycle --- design/project-management/ai-observations.md | 4 + ...xtureOwnerCompositionCrossServiceTest.java | 368 ++--- .../RunOwnedCanonicalWorldLaunchEvidence.java | 331 +++++ ...dCanonicalWorldLaunchEvidenceProvider.java | 479 +++++++ .../RunOwnedWorldFixedPresetResources.java | 8 +- .../data/RunOwnedWorldLaunchEvidence.java | 102 +- .../RunOwnedWorldLaunchEvidenceProvider.java | 135 +- .../worldmanagement/data/TestDataSeeder.java | 11 - .../WorldLifecycleCommandServiceImpl.java | 259 +++- .../WorldAuthoredSourceIntakeService.java | 4 +- .../WorldAuthoredVersionIdentityService.java | 10 +- ...anonicalInstanceAssociationRepository.java | 20 +- ..._predecessor_fixture_lifecycle_staging.sql | 138 ++ ...orldLaunchEvidenceMtlsIntegrationTest.java | 1160 +++++++++++++++ ...orldLaunchEvidenceMtlsIntegrationTest.java | 1259 ++++++++++++----- ...LaunchEvidencePostgresIntegrationTest.java | 605 ++++---- ...resetResourcesPostgresIntegrationTest.java | 718 +++++++++- ...OwnedWorldFixtureEvidenceTestFixtures.java | 22 +- ...OwnedWorldFixtureLifecycleTestFactory.java | 8 +- ...onicalWorldLaunchEvidenceProviderTest.java | 972 +++++++++++++ ...nicalWorldLaunchEvidenceTestFixtures.java} | 12 +- ...RunOwnedWorldFixedPresetResourcesTest.java | 10 +- ...nOwnedWorldLaunchEvidenceProviderTest.java | 966 +++---------- .../data/TestDataSeederTest.java | 10 - .../WorldLifecycleCommandServiceImplTest.java | 498 +++++-- .../WorldAuthoredSourceIntakeServiceTest.java | 18 +- ...rldAuthoredVersionIdentityServiceTest.java | 18 +- ...WorldCanonicalInstanceAssociationTest.java | 6 +- 28 files changed, 6185 insertions(+), 1966 deletions(-) create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidence.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceProvider.java create mode 100644 services/world-management-service/src/main/resources/db/migration/V1042.7__world_predecessor_fixture_lifecycle_staging.sql create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceProviderTest.java rename services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/{RunOwnedWorldLaunchEvidenceTestFixtures.java => RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.java} (96%) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 39c4853660..cc05bf8ced 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -327,3 +327,7 @@ Entry format: - Context: Document R57/R65 and Gameplay #2967 failed with a 1.4 GiB maximum heap amid repeated garbage-collection thrashing. The receiving task passed with a per-run 3 GiB heap in 1m27s, while WSL was configured with a 10 GB limit and had 5.2–6.8 GiB available without swap-out or OOM evidence. - Observation: the repeated failures support a higher shared local daemon heap for serialized work; the passing run was mostly up-to-date and does not establish cold-build speedup or a total-memory guarantee. - Qualification: the 3 GiB setting is not a restoration of an earlier default; the shared 1500m setting predates the recent guard since August 28. Worker, test, and code-generation JVM memory remains additional, and the hosted module runner's explicit 2500m setting is unchanged. + +- 2026-10-15: Two sequential same-candidate Controller `reviews decide reconcile` operations for #3206 (Hosted and CLI) succeeded after a several-minute silent execution. The slow phase is not isolated; a long-running administrative-looking command is difficult to distinguish from a stall without phase/duration output. Reported to Overseer as nonblocking, alongside the terminology friction that queue inspection uses `reviews stack show` rather than `reviews queue`. Consider progress/duration diagnostics or a guarded shared-evidence operation; no timing, admission or review authority was bypassed. + +- 2026-10-15: Gameplay published the #3210 receiving carry after its runtime/source gate passed but before consuming the separate final proof-note-only documentation session, which was still running. The final documentation result therefore remained pending at publication; the PR/job/Overseer report explicitly retain that limit and no READY claim was made. A yielded session is not completion: dependent mutation must be gated on its consumed terminal exit status, even when earlier runtime proof passed. The pending documentation session subsequently passed in 21 seconds, and Gameplay consumed its exit 0 before recording the final documentation proof. The publication-order mistake remains recorded; a later pass does not change that ordering. 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 index c1d31e8167..a73da9e155 100644 --- 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 @@ -3,6 +3,7 @@ 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; @@ -13,9 +14,10 @@ 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.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.CopyOnWriteArrayList; @@ -23,10 +25,14 @@ 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; @@ -34,7 +40,7 @@ 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.RunOwnedInitialAdmissionFixtureCoordinator; +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; @@ -42,10 +48,9 @@ import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldFixedPresetResources; -import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceProvider; -import net.firedevops.firemud.worldmanagement.service.impl.WorldInstanceActivationServiceImpl; +import net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidence; +import net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidenceProvider; import net.firedevops.firemud.worldmanagement.service.impl.WorldLifecycleCommandServiceImpl; -import net.firedevops.firemud.worldmanagement.service.impl.WorldManagementGrpcService; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationRepository; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; @@ -95,7 +100,7 @@ class RunOwnedFixtureOwnerCompositionCrossServiceTest extends TestDataSeederInte new PostgreSQLContainer<>(TestContainerImages.postgres()); @Test - void actualProducerStartingAndPreparingOwnersComposeOverThreeMutualTlsSockets( + void actualProducerAndCanonicalOwnersComposeOverMutualTlsOwnerReads( @TempDir Path testDirectory) throws Exception { assertThat(environment.getRequiredProperty("spring.application.name")) .isEqualTo("game-design-service"); @@ -203,8 +208,8 @@ void actualProducerStartingAndPreparingOwnersComposeOverThreeMutualTlsSockets( fixture, fixture.worldManagementCertificatePath(), fixture.worldManagementCertificatePath().resolveSibling("world-management.key")); - var coordinator = - new RunOwnedInitialAdmissionFixtureCoordinator( + var preparationOwner = + new RunOwnedCanonicalLaunchPreparationOwner( true, fixture.capabilityPath().toString(), fixture.receiptPath().toString(), @@ -213,10 +218,12 @@ void actualProducerStartingAndPreparingOwnersComposeOverThreeMutualTlsSockets( gsTls, beanFactory.getBeanProvider(GameSessionCanonicalInstanceLaunchRepository.class), NAMESPACE); - // The production loader verifies real producer files and original mounted pins; no test-only GS - // carrier is used. - var gsEvidence = coordinator.loadFixedVerifiedEvidence(); - var starting = launchOwner.createVerifiedFixtureStartingLaunch(gsEvidence); + // 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()); @@ -230,7 +237,8 @@ void actualProducerStartingAndPreparingOwnersComposeOverThreeMutualTlsSockets( assertThat(starting.rowVersion()).isZero(); var registry = new io.micrometer.core.instrument.simple.SimpleMeterRegistry(); var gsHandler = org.mockito.Mockito.spy(actualGsFixtureReadHandler(registry)); - gsHandler.configureRunOwnedFixtureLaunchAssociationReadBoundary(coordinator, true, NAMESPACE); + gsHandler.configureRunOwnedFixtureLaunchAssociationReadBoundary( + preparationOwner, true, NAMESPACE); var gdsLeaf = issueFixedReadLeaf( fixture, @@ -241,7 +249,7 @@ void actualProducerStartingAndPreparingOwnersComposeOverThreeMutualTlsSockets( var factory = composedChannelFactory(channels); var servers = new java.util.ArrayList(); net.firedevops.firemud.worldmanagement.client.GameDesignClient remoteDesign = null; - RunOwnedWorldLaunchEvidenceProvider provider = null; + RunOwnedCanonicalWorldLaunchEvidenceProvider provider = null; WorldLifecycleCommandServiceImpl commands = null; var fixedOwnerContext = actualFixedReadContext(fixture); try { @@ -282,7 +290,7 @@ void actualProducerStartingAndPreparingOwnersComposeOverThreeMutualTlsSockets( net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer.noop()); ReflectionTestUtils.invokeMethod(remoteDesign, "init"); provider = - new RunOwnedWorldLaunchEvidenceProvider( + new RunOwnedCanonicalWorldLaunchEvidenceProvider( true, fixture.capabilityPath().toString(), fixture.receiptPath().toString(), @@ -306,65 +314,45 @@ void actualProducerStartingAndPreparingOwnersComposeOverThreeMutualTlsSockets( worldTls, factory, registry); - var worldRepository = - new net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository( - worldDatabase.dsl()); - var worldHandler = actualWorldFixtureHandler(commands, provider, worldRepository, registry); - Server worldServer = - fixedProductionServer( - fixture, - new FixedReadLeaf( - fixture.worldManagementCertificatePath(), - fixture.worldManagementCertificatePath().resolveSibling("world-management.key")), - Set.of( - net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc - .getPrepareWorldInstanceMethod() - .getFullMethodName()), - worldHandler); - servers.add(worldServer); - var descriptor = receipt.launchReadEvidence().launchDescriptor(); var bundle = receipt.launchReadEvidence().publishedReleaseBundle(); - var request = - net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceRequest.newBuilder() - .setTenantId(Long.toString(starting.catalog().association().gameSessionTenantId())) - .setGameInstanceId(Long.toString(starting.gameInstanceId())) - .setGameTemplateId(Long.toString(capability.gameTemplateId())) - .setControlPlaneRequestId(capability.operationId()) - .setLaunchDescriptorId(descriptor.getLaunchDescriptorId()) - .setVersionId(Long.toString(bundle.getVersionId())) - .setRuntimeFlagsJson(descriptor.getRuntimeFlagsJson()) - .setGenerationConfigRevision(bundle.getGenerationConfigRevision()) - .setReleaseBundleId(Long.toString(bundle.getId())) - .setPublishedReleaseBundleRef(bundle.getPublishedReleaseBundleRef()) - .setVersionStateEpoch( - receipt.launchReadEvidence().versionState().getVersionStateEpoch()) - .build(); var originalGdsRows = fixedReadOwnerRows(); var originalGsRows = allComposedOwnerRows(gsDatabase.dsl()); - ManagedChannel worldChannel = - factory.buildChannel( - "127.0.0.1:" + worldServer.getPort(), worldServer.getPort(), gsTls, false); - var stub = - net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc.newBlockingStub( - worldChannel) - .withCallCredentials( - new net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials( - WORLD_MANAGEMENT_URI_SAN)) - .withInterceptors( - new net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor( - WORLD_MANAGEMENT_URI_SAN)) - .withDeadlineAfter(30, TimeUnit.SECONDS); - var prepared = stub.prepareWorldInstance(request); - assertThat(prepared.hasError()).as("actual World prepare response").isFalse(); - assertThat(prepared.getWorldInstance().getStatus()) - .isEqualTo( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING); - assertThat(prepared.getWorldInstance().getLifecycleEpoch()).isEqualTo(1L); - assertThat(prepared.getWorldInstance().getTenantId()).isEqualTo(request.getTenantId()); - assertThat(prepared.getWorldInstance().getGameInstanceId()) - .isEqualTo(request.getGameInstanceId()); - assertThat(prepared.getWorldInstance().getVersionId()).isEqualTo(request.getVersionId()); + RunOwnedCanonicalWorldLaunchEvidence worldEvidence = + withControlledGameSessionPeer( + fixture, provider::requireAuthenticatedEvidence); + var request = exactPreparedWorldRequest(worldEvidence); + var emptyWorldRows = allComposedOwnerRows(worldDatabase.dsl()); + var changedSource = changedSourceEvidence(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( + commands, "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( + commands, "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(); @@ -460,7 +448,18 @@ void actualProducerStartingAndPreparingOwnersComposeOverThreeMutualTlsSockets( .get("count", Long.class)) .isOne(); var worldRows = allComposedOwnerRows(worldDatabase.dsl()); - assertThat(stub.prepareWorldInstance(request)).isEqualTo(prepared); + assertThat( + withControlledGameSessionPeer( + fixture, + () -> + (net.firedevops.firemud.worldmanagement.dto + .WorldInstanceLifecycleSnapshotDto) + ReflectionTestUtils.invokeMethod( + commands, + "prepareRunOwnedFixture", + request, + provider.requireAuthenticatedEvidence()))) + .isEqualTo(prepared); var reread = independentlyReadWorldFixture(worldDatabase.dsl(), starting.gameInstanceUuid()); assertThat( RunOwnedWorldFixedPresetResources.readCommitted( @@ -473,15 +472,34 @@ void actualProducerStartingAndPreparingOwnersComposeOverThreeMutualTlsSockets( assertThat(allComposedOwnerRows(gsDatabase.dsl())).isEqualTo(originalGsRows); assertThat(fixedReadOwnerRows()).isEqualTo(originalGdsRows); assertThat(Files.readAllBytes(fixture.receiptPath())).containsExactly(originalReceipt); - // Selector denial is an actual production response; no remote positive response is - // controlled. - assertThat( - stub.prepareWorldInstance( - request.toBuilder() - .setGameInstanceId(Long.toString(starting.gameInstanceId() + 1)) - .build()) - .hasError()) - .isTrue(); + // 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( + commands, + "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. @@ -496,7 +514,7 @@ void actualProducerStartingAndPreparingOwnersComposeOverThreeMutualTlsSockets( net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer.noop()); ReflectionTestUtils.invokeMethod(remoteDesign, "init"); provider = - new RunOwnedWorldLaunchEvidenceProvider( + new RunOwnedCanonicalWorldLaunchEvidenceProvider( true, fixture.capabilityPath().toString(), fixture.receiptPath().toString(), @@ -517,62 +535,41 @@ void actualProducerStartingAndPreparingOwnersComposeOverThreeMutualTlsSockets( worldTls, factory, registry); - var restartedHandler = - actualWorldFixtureHandler( - commands, - provider, - new net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository( - worldDatabase.dsl()), - registry); - Server restartedServer = - fixedProductionServer( - fixture, - new FixedReadLeaf( - fixture.worldManagementCertificatePath(), - fixture.worldManagementCertificatePath().resolveSibling("world-management.key")), - Set.of( - net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc - .getPrepareWorldInstanceMethod() - .getFullMethodName()), - restartedHandler); - servers.add(restartedServer); - ManagedChannel restartedChannel = - factory.buildChannel( - "127.0.0.1:" + restartedServer.getPort(), restartedServer.getPort(), gsTls, false); - assertThat(actualWorldPrepareStub(restartedChannel).prepareWorldInstance(request)) + var replayEvidence = + withControlledGameSessionPeer(fixture, provider::requireAuthenticatedEvidence); + assertThat( + withControlledGameSessionPeer( + fixture, + () -> + (net.firedevops.firemud.worldmanagement.dto + .WorldInstanceLifecycleSnapshotDto) + ReflectionTestUtils.invokeMethod( + commands, "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(3)) + 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); - for (var wrongLeaf : - java.util.List.of( - otherGsLeaf, - new FixedReadLeaf( - fixture.worldManagementCertificatePath(), - fixture - .worldManagementCertificatePath() - .resolveSibling("world-management.key")))) { - var wrongTls = fixedReadTls(fixture, wrongLeaf.certificate(), wrongLeaf.privateKey()); - var wrongChannel = - factory.buildChannel( - "127.0.0.1:" + restartedServer.getPort(), - restartedServer.getPort(), - wrongTls, - false); - assertThat(actualWorldPrepareStub(wrongChannel).prepareWorldInstance(request).hasError()) - .isTrue(); - } + var wrongSessionCertificate = readCertificate(otherGsLeaf.certificate()); + org.assertj.core.api.Assertions.assertThatThrownBy( + () -> + withControlledPeer( + wrongSessionCertificate, provider::requireAuthenticatedEvidence)) + .isInstanceOf( + RunOwnedCanonicalWorldLaunchEvidenceProvider + .InvalidRunOwnedCanonicalWorldLaunchEvidenceException.class); org.mockito.Mockito.verifyNoInteractions( gsHandler, launchDescriptorService, fixtureReadback, fixturePolicy, entityClient); assertThat(allComposedOwnerRows(worldDatabase.dsl())).isEqualTo(worldRows); @@ -668,44 +665,6 @@ private GameSessionControlPlaneGrpcService actualGsFixtureReadHandler( } } - private WorldManagementGrpcService actualWorldFixtureHandler( - WorldLifecycleCommandServiceImpl commands, - RunOwnedWorldLaunchEvidenceProvider provider, - net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository repository, - io.micrometer.core.instrument.MeterRegistry registry) { - var activation = - new WorldInstanceActivationServiceImpl(commands, Optional.empty(), provider, repository); - return new WorldManagementGrpcService( - org.mockito.Mockito.mock(net.firedevops.firemud.worldmanagement.service.PingService.class), - org.mockito.Mockito.mock(net.firedevops.firemud.worldmanagement.service.RoomService.class), - activation, - org.mockito.Mockito.mock( - net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService.class), - org.mockito.Mockito.mock( - net.firedevops.firemud.worldmanagement.service.WorldDesignMutationService.class), - org.mockito.Mockito.mock( - net.firedevops.firemud.worldmanagement.service.WorldUpgradeValidationService.class), - org.mockito.Mockito.mock( - net.firedevops.firemud.common.security.GameplaySessionAttestationService.class), - registry, - objectMapper, - NAMESPACE); - } - - private net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc - .WorldManagementServiceBlockingStub - actualWorldPrepareStub(ManagedChannel channel) { - return net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc.newBlockingStub( - channel) - .withCallCredentials( - new net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials( - WORLD_MANAGEMENT_URI_SAN)) - .withInterceptors( - new net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor( - WORLD_MANAGEMENT_URI_SAN)) - .withDeadlineAfter(30, TimeUnit.SECONDS); - } - private CommonGrpcClientProperties fixedReadTls(Fixture fixture, Path certificate, Path key) { var tls = new CommonGrpcClientProperties(); tls.setCertChain(certificate.toString()); @@ -714,6 +673,88 @@ private CommonGrpcClientProperties fixedReadTls(Fixture fixture, Path certificat 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 changedSourceEvidence(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 = @@ -793,7 +834,7 @@ private Server fixedProductionServer( private WorldLifecycleCommandServiceImpl actualWorldFixtureCommands( ComposedOwnerDatabase database, - RunOwnedWorldLaunchEvidenceProvider provider, + RunOwnedCanonicalWorldLaunchEvidenceProvider provider, net.firedevops.firemud.worldmanagement.client.GameDesignClient design, net.firedevops.firemud.worldmanagement.client.EntityManagementClient entities, ServiceEndpointsProperties endpoints, @@ -823,6 +864,7 @@ private WorldLifecycleCommandServiceImpl actualWorldFixtureCommands( entities, registry, database.transactions(), + null, provider, database.dsl(), endpoints, 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..69f9aee50c --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceProvider.java @@ -0,0 +1,479 @@ +package net.firedevops.firemud.worldmanagement.data; + +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; + + @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; + } + throw invalidEvidence(); + } + } catch (RuntimeException exception) { + logger.warn("Run-owned World launch evidence verification rejected; stage={}", stage); + throw exception; + } + } + + private static UUID freshFixtureReadRequestId(UUID fixtureOperationId) { + UUID readRequestId; + do { + readRequestId = UUID.randomUUID(); + } while (readRequestId.equals(fixtureOperationId)); + return readRequestId; + } + + private synchronized CanonicalGameInstanceLaunchAssociationClient gameSessionFixtureClient() { + 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() { + 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 index 06c6ad810b..496e66f510 100644 --- 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 @@ -93,10 +93,10 @@ public static Definition definition() { * accepted. */ public static FixedPresetPlan plan( - RunOwnedWorldLaunchEvidence evidence, + RunOwnedCanonicalWorldLaunchEvidence evidence, WorldAuthoredSourceIntakeReceipt sourceReceipt, WorldAuthoredVersionIdentityReceipt versionReceipt) { - RunOwnedWorldLaunchEvidence typedEvidence = Objects.requireNonNull(evidence, "evidence"); + RunOwnedCanonicalWorldLaunchEvidence typedEvidence = Objects.requireNonNull(evidence, "evidence"); typedEvidence.requireFixedGameSessionPeer(); var descriptor = typedEvidence.launchDescriptor(); if (descriptor.scriptPatchVersionPresent() || descriptor.remapSetIdPresent()) { @@ -411,7 +411,7 @@ private static FixedPresetPlan sealPlan( */ public static MaterializedFixedPreset materialize( DSLContext dsl, - RunOwnedWorldLaunchEvidence fixtureEvidence, + RunOwnedCanonicalWorldLaunchEvidence fixtureEvidence, FixedPresetPlan plan, long worldInstanceId, long privateGameInstanceKey) { @@ -482,7 +482,7 @@ public static MaterializedFixedPreset readCommitted( /** The retained seal survives retries; only the independent GS read correlation may change. */ private static void requireCurrentFixtureMatchesRetainedPlan( - RunOwnedWorldLaunchEvidence evidence, FixedPresetPlan plan) { + RunOwnedCanonicalWorldLaunchEvidence evidence, FixedPresetPlan plan) { var capability = evidence.capability(); var receipt = evidence.sourceReceipt(); var source = receipt.sourceEvidence(); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java index 42fec8207e..37ca38c9d3 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java @@ -3,14 +3,9 @@ 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; @@ -26,8 +21,6 @@ public final class RunOwnedWorldLaunchEvidence { 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; @@ -44,8 +37,7 @@ public final class RunOwnedWorldLaunchEvidence { String gameSessionLeafSha256, String worldManagementUriSan, String worldManagementLeafSha256, - String caCertificateSha256, - CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult gameSessionAssociation) { + String caCertificateSha256) { this.capability = Objects.requireNonNull(capability, "capability"); this.sourceReceipt = Objects.requireNonNull(sourceReceipt, "sourceReceipt"); this.launchDescriptor = Objects.requireNonNull(launchDescriptor, "launchDescriptor"); @@ -59,32 +51,6 @@ public final class RunOwnedWorldLaunchEvidence { 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() { @@ -99,20 +65,6 @@ 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; } @@ -143,7 +95,7 @@ public void requireMatches(PreparedWorldInstanceRequest request) { || version.getVersionState() == net.firedevops.firemud.gamedesign.v1.VersionLifecycleState .VERSION_LIFECYCLE_STATE_ACTIVE; - if (request.tenantId() <= 0L + if (request.tenantId() != capability.tenantId() || request.gameInstanceId() <= 0L || request.gameTemplateId() != capability.gameTemplateId() || !capability.operationId().equals(request.controlPlaneRequestId()) @@ -191,56 +143,6 @@ public void requireMatches(PreparedWorldInstanceRequest request) { 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"); - } } /** diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java index 42bfeb4d6c..f5a29e382e 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java @@ -1,6 +1,5 @@ package net.firedevops.firemud.worldmanagement.data; -import jakarta.annotation.PreDestroy; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -18,13 +17,9 @@ 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; @@ -34,19 +29,15 @@ 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. + * the configured immutable files and performs the exact authenticated Game Design owner read. */ @Component public final class RunOwnedWorldLaunchEvidenceProvider { @@ -67,13 +58,7 @@ public final class RunOwnedWorldLaunchEvidenceProvider { 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; - @Autowired public RunOwnedWorldLaunchEvidenceProvider( @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}") boolean enabled, @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH:}") String capabilityPath, @@ -81,38 +66,7 @@ public RunOwnedWorldLaunchEvidenceProvider( @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)); - } - - RunOwnedWorldLaunchEvidenceProvider( - boolean enabled, - String capabilityPath, - String sourceReceiptPath, - String runId, - String composeProjectName, - CommonGrpcClientProperties grpcProperties, - GameDesignClient gameDesignClient, - ServiceEndpointsProperties serviceEndpoints, - GrpcChannelFactory grpcChannelFactory, - String workloadNamespace, - GameSessionFixtureClientFactory gameSessionFixtureClientFactory) { + GameDesignClient gameDesignClient) { this.enabled = enabled; this.capabilityPath = capabilityPath; this.sourceReceiptPath = sourceReceiptPath; @@ -120,11 +74,6 @@ public RunOwnedWorldLaunchEvidenceProvider( 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. */ @@ -133,9 +82,8 @@ public boolean isEnabled() { } /** - * 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. + * Independently loads all fixed evidence and verifies the actual authenticated request context. + * This is invoked on every prepare, activate, and exact retry. */ public RunOwnedWorldLaunchEvidence requireAuthenticatedEvidence() { VerificationStage stage = VerificationStage.ENABLED; @@ -201,18 +149,6 @@ public RunOwnedWorldLaunchEvidence requireAuthenticatedEvidence() { 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 RunOwnedWorldLaunchEvidence( capability, receipt, @@ -222,8 +158,7 @@ public RunOwnedWorldLaunchEvidence requireAuthenticatedEvidence() { capability.gameSessionLeafSha256(), worldPins.uriSan(), worldPins.leafSha256(), - worldPins.caSha256(), - gameSessionAssociation); + worldPins.caSha256()); } catch (RuntimeException exception) { if (exception instanceof InvalidRunOwnedWorldLaunchEvidenceException invalid) { throw invalid; @@ -236,53 +171,6 @@ public RunOwnedWorldLaunchEvidence requireAuthenticatedEvidence() { } } - private static UUID freshFixtureReadRequestId(UUID fixtureOperationId) { - UUID readRequestId; - do { - readRequestId = UUID.randomUUID(); - } while (readRequestId.equals(fixtureOperationId)); - return readRequestId; - } - - private synchronized CanonicalGameInstanceLaunchAssociationClient gameSessionFixtureClient() { - 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() { - 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) { @@ -445,15 +333,6 @@ private static InvalidRunOwnedWorldLaunchEvidenceException invalidEvidence() { 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, @@ -464,9 +343,7 @@ private enum VerificationStage { GAME_SESSION_PEER, DESCRIPTOR_PARSE, OWNER_DESCRIPTOR_READ, - OWNER_DESCRIPTOR_COMPARE, - GAME_SESSION_FIXTURE_READ, - GAME_SESSION_FIXTURE_COMPARE + OWNER_DESCRIPTOR_COMPARE } /** Content-free failure so malformed or secret-bearing fixture bytes never reach logs. */ diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/TestDataSeeder.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/TestDataSeeder.java index e132c8f914..3a6c802b90 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/TestDataSeeder.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/TestDataSeeder.java @@ -1,7 +1,6 @@ package net.firedevops.firemud.worldmanagement.data; import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; import net.firedevops.firemud.worldmanagement.entity.Region; import net.firedevops.firemud.worldmanagement.entity.Room; import net.firedevops.firemud.worldmanagement.entity.RoomExit; @@ -10,7 +9,6 @@ import net.firedevops.firemud.worldmanagement.repository.RoomExitRepository; import net.firedevops.firemud.worldmanagement.repository.RoomRepository; import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; -import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -25,7 +23,6 @@ havingValue = "true", matchIfMissing = false) @RequiredArgsConstructor -@Slf4j public class TestDataSeeder implements ApplicationRunner { private static final long DEMO_TENANT_ID = 1L; private static final long DEMO_VERSION_ID = 1L; @@ -45,17 +42,9 @@ public class TestDataSeeder implements ApplicationRunner { private final RoomRepository roomRepository; private final RoomExitRepository roomExitRepository; - @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}") - private boolean runOwnedFixtureMode; - @Override @Transactional public void run(ApplicationArguments args) { - if (runOwnedFixtureMode) { - log.warn( - "RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE: fixture runtime seeding skipped until World-owned materialization is available"); - return; - } ensureDemoTopology(); } 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 411b6d6fc6..75b1418f44 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 @@ -24,6 +24,8 @@ 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; @@ -95,6 +97,8 @@ 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; @@ -164,6 +168,7 @@ public WorldLifecycleCommandServiceImpl( MeterRegistry meterRegistry, PlatformTransactionManager transactionManager, RunOwnedWorldLaunchEvidenceProvider runOwnedWorldLaunchEvidenceProvider, + RunOwnedCanonicalWorldLaunchEvidenceProvider runOwnedCanonicalWorldLaunchEvidenceProvider, DSLContext dsl, ServiceEndpointsProperties serviceEndpoints, CommonGrpcClientProperties grpcClientProperties, @@ -185,6 +190,7 @@ public WorldLifecycleCommandServiceImpl( meterRegistry, transactionTemplate(transactionManager), runOwnedWorldLaunchEvidenceProvider, + runOwnedCanonicalWorldLaunchEvidenceProvider, dsl, transactionManager, serviceEndpoints, @@ -263,6 +269,7 @@ public WorldLifecycleCommandServiceImpl( null, null, null, + null, null); } @@ -304,6 +311,56 @@ public WorldLifecycleCommandServiceImpl( 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, @@ -330,6 +387,7 @@ private WorldLifecycleCommandServiceImpl( MeterRegistry meterRegistry, TransactionOperations transactionOperations, RunOwnedWorldLaunchEvidenceProvider runOwnedWorldLaunchEvidenceProvider, + RunOwnedCanonicalWorldLaunchEvidenceProvider runOwnedCanonicalWorldLaunchEvidenceProvider, DSLContext dsl, PlatformTransactionManager fixtureTransactionManager, ServiceEndpointsProperties serviceEndpoints, @@ -351,6 +409,8 @@ private WorldLifecycleCommandServiceImpl( this.meterRegistry = meterRegistry; this.transactionOperations = transactionOperations; this.runOwnedWorldLaunchEvidenceProvider = runOwnedWorldLaunchEvidenceProvider; + this.runOwnedCanonicalWorldLaunchEvidenceProvider = + runOwnedCanonicalWorldLaunchEvidenceProvider; this.dsl = dsl; this.fixtureTransactionManager = fixtureTransactionManager; this.serviceEndpoints = serviceEndpoints; @@ -428,15 +488,15 @@ void initMetrics() { } /** - * Composes authenticated fixture owners into the original PREPARING allocation only. Activation - * and admission remain unavailable through both Java and SQL owners. + * 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, - RunOwnedWorldLaunchEvidence fixtureEvidence) { + RunOwnedCanonicalWorldLaunchEvidence fixtureEvidence) { Objects.requireNonNull(fixtureEvidence, "fixtureEvidence").requireFixedGameSessionPeer(); requireNoAmbientFixtureReadTransaction(); - if (!fixtureModeEnabled()) throw fixtureWritesUnavailable(); + if (!canonicalFixtureModeEnabled()) throw fixtureWritesUnavailable(); fixtureEvidence.requireMatches(originalGameSessionRequest); RunOwnedWorldFixtureOwners owners = requireRunOwnedWorldFixtureOwners(); var sourceReceipt = owners.sourceIntakeService().intakeRunOwnedFixture(fixtureEvidence); @@ -573,35 +633,53 @@ private T executeFixtureOwnerTransaction(Supplier operation) { @Timed(value = "world.prepareInstance") public WorldInstanceLifecycleSnapshotDto prepareWorldInstance( PreparedWorldInstanceRequest request) { - if (fixtureModeEnabled()) { - requireNoAmbientFixtureReadTransaction(); - return prepareRunOwnedFixture( - request, runOwnedWorldLaunchEvidenceProvider.requireAuthenticatedEvidence()); - } - if (prepareTransactionOperations == null) return prepareOrdinaryWorldInstance(request); + if (prepareTransactionOperations == null) return preparePublishedWorldInstance(request); return Objects.requireNonNull( - prepareTransactionOperations.execute(status -> prepareOrdinaryWorldInstance(request)), + prepareTransactionOperations.execute(status -> preparePublishedWorldInstance(request)), "Ordinary preparation transaction returned no World snapshot"); } - private WorldInstanceLifecycleSnapshotDto prepareOrdinaryWorldInstance( + private WorldInstanceLifecycleSnapshotDto preparePublishedWorldInstance( PreparedWorldInstanceRequest request) { validatePrepareRequest(request); + RunOwnedWorldLaunchEvidence fixtureEvidence = configuredFixtureEvidence(); + if (fixtureEvidence != null) { + fixtureEvidence.requireMatches(request); + worldInstanceRepository.lockRunOwnedFixtureOperation( + request.tenantId(), request.controlPlaneRequestId()); + WorldInstance operationInstance = + worldInstanceRepository + .findRunOwnedFixtureByTenantIdAndControlPlaneRequestIdForUpdate( + request.tenantId(), request.controlPlaneRequestId()) + .orElse(null); + if (operationInstance != null + && !operationInstance.getGameInstanceId().equals(request.gameInstanceId())) { + throw fixtureIdentityConflict(); + } + } WorldInstance existing = - worldInstanceRepository - .findByTenantIdAndGameInstanceId(request.tenantId(), request.gameInstanceId()) - .orElse(null); + fixtureEvidence == null + ? worldInstanceRepository + .findByTenantIdAndGameInstanceId(request.tenantId(), request.gameInstanceId()) + .orElse(null) + : worldInstanceRepository + .findByTenantIdAndGameInstanceIdForUpdate( + request.tenantId(), request.gameInstanceId()) + .orElse(null); if (existing != null) { if (existing.getRunOwnedFixtureBindingSha256() != null) { - throw fixtureEvidenceUnavailable(); + if (fixtureEvidence == null) throw fixtureEvidenceUnavailable(); + requireRunOwnedFixtureBinding(existing, fixtureEvidence, request); + return snapshot(existing); } + if (fixtureEvidence != null) throw fixtureIdentityConflict(); if (!samePreparedRequest(existing, request)) { throw new IllegalArgumentException( "INVALID_ARGUMENT: gameInstanceId already exists with different activation inputs"); } return snapshot(existing); } - validateAttestedLaunchInputs(request); + if (fixtureEvidence == null) validateAttestedLaunchInputs(request); WorldInstance worldInstance = new WorldInstance(); worldInstance.setTenantId(request.tenantId()); worldInstance.setGameInstanceId(request.gameInstanceId()); @@ -619,6 +697,10 @@ private WorldInstanceLifecycleSnapshotDto prepareOrdinaryWorldInstance( worldInstance.setRemapSetId(normalizeBlank(request.remapSetId())); worldInstance.setLifecycleEpoch(1L); worldInstance.setStatus(STATUS_PREPARING); + if (fixtureEvidence != null) { + worldInstance.setRunOwnedFixtureBindingSha256(fixtureEvidence.bindingDigest(request, 1L)); + worldInstance.setRunOwnedFixturePreparingLifecycleEpoch(1L); + } worldInstance.setCreatedAt(Instant.now()); worldInstance.setUpdatedAt(Instant.now()); WorldInstance saved = worldInstanceRepository.save(worldInstance); @@ -652,22 +734,36 @@ private WorldInstanceLifecycleSnapshotDto prepareOrdinaryWorldInstance( @Timed(value = "world.activateInstance") public WorldInstanceLifecycleSnapshotDto activatePreparedWorldInstance( long tenantId, long gameInstanceId, long expectedLifecycleEpoch) { - if (fixtureModeEnabled()) { - throw fixtureWritesUnavailable(); - } WorldInstance worldInstance = requireWorldInstance(tenantId, gameInstanceId); if (worldInstance.getRunOwnedFixtureBindingSha256() != null) { - throw fixtureEvidenceUnavailable(); - } - requireLifecycleEpoch(worldInstance, expectedLifecycleEpoch); - if (STATUS_ACTIVE.equals(worldInstance.getStatus())) { - return snapshot(worldInstance); + if (!fixtureModeEnabled()) throw fixtureEvidenceUnavailable(); + RunOwnedWorldLaunchEvidence fixtureEvidence = + runOwnedWorldLaunchEvidenceProvider.requireAuthenticatedEvidence(); + worldInstance = requireLockedWorldInstance(tenantId, gameInstanceId); + PreparedWorldInstanceRequest existingRequest = preparedRequest(worldInstance); + requireRunOwnedFixtureBinding(worldInstance, fixtureEvidence, existingRequest); + if (STATUS_ACTIVE.equals(worldInstance.getStatus())) { + long preparingEpoch = worldInstance.getRunOwnedFixturePreparingLifecycleEpoch(); + if (worldInstance.getLifecycleEpoch() != preparingEpoch + 1L + || (expectedLifecycleEpoch != preparingEpoch + && expectedLifecycleEpoch != worldInstance.getLifecycleEpoch())) { + throw lifecycleEpochMismatch(); + } + return snapshot(worldInstance); + } + requireLifecycleEpoch(worldInstance, expectedLifecycleEpoch); + } else { + if (fixtureModeEnabled()) throw fixtureIdentityConflict(); + requireLifecycleEpoch(worldInstance, expectedLifecycleEpoch); + if (STATUS_ACTIVE.equals(worldInstance.getStatus())) return snapshot(worldInstance); } if (!STATUS_PREPARING.equals(worldInstance.getStatus())) { throw new IllegalArgumentException( "INVALID_WORLD_INSTANCE_STATE: world instance is not in PREPARING state"); } - validateAttestedLaunchInputs(preparedRequest(worldInstance)); + if (worldInstance.getRunOwnedFixtureBindingSha256() == null) { + validateAttestedLaunchInputs(preparedRequest(worldInstance)); + } worldInstance.setStatus(STATUS_ACTIVE); worldInstance.setLifecycleEpoch(worldInstance.getLifecycleEpoch() + 1L); worldInstance.setFailureReason(null); @@ -698,6 +794,28 @@ private PreparedWorldInstanceRequest preparedRequest(WorldInstance worldInstance worldInstance.getRemapSetId()); } + private void requireRunOwnedFixtureBinding( + WorldInstance instance, + RunOwnedWorldLaunchEvidence fixtureEvidence, + PreparedWorldInstanceRequest request) { + Long preparingEpoch = instance.getRunOwnedFixturePreparingLifecycleEpoch(); + if (instance.getRunOwnedFixtureBindingSha256() == null + || preparingEpoch == null + || preparingEpoch <= 0L + || preparingEpoch != 1L + || !samePreparedRequest(instance, request) + || !instance + .getRunOwnedFixtureBindingSha256() + .equals(fixtureEvidence.bindingDigest(request, preparingEpoch))) { + throw fixtureEvidenceMismatch(); + } + } + + private RunOwnedWorldLaunchEvidence configuredFixtureEvidence() { + if (!fixtureModeEnabled()) return null; + return runOwnedWorldLaunchEvidenceProvider.requireAuthenticatedEvidence(); + } + private static void requireSameFixtureAllocation( WorldCanonicalInstanceAssociation expected, WorldCanonicalInstanceAssociation actual) { if (!expected.isRunOwnedFixture() @@ -730,7 +848,7 @@ private synchronized RunOwnedWorldFixtureOwners requireRunOwnedWorldFixtureOwner if (runOwnedWorldFixtureOwners != null) { return runOwnedWorldFixtureOwners; } - if (!fixtureModeEnabled() + if (!canonicalFixtureModeEnabled() || dsl == null || fixtureTransactionManager == null || serviceEndpoints == null @@ -824,6 +942,11 @@ private boolean fixtureModeEnabled() { && 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"); @@ -831,17 +954,52 @@ private static IllegalArgumentException fixtureEvidenceUnavailable() { private static IllegalArgumentException fixtureWritesUnavailable() { return new IllegalArgumentException( - "RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE: fixture activation and admission are unavailable until their owner closure is qualified"); + "RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE: fixture mutation requires its verified owner"); + } + + private static IllegalArgumentException fixtureIdentityConflict() { + return new IllegalArgumentException( + "RUN_OWNED_WORLD_LAUNCH_IDENTITY_CONFLICT: fixture operation is bound to another instance"); + } + + private static IllegalArgumentException lifecycleEpochMismatch() { + return new IllegalArgumentException( + "WORLD_INSTANCE_LIFECYCLE_STALE: world instance lifecycle epoch mismatch"); } @Override - @Transactional @Timed(value = "world.failPreparedInstance") public WorldInstanceLifecycleSnapshotDto failPreparedWorldInstance( long tenantId, long gameInstanceId, long expectedLifecycleEpoch, String reason) { - if (fixtureModeEnabled()) throw fixtureWritesUnavailable(); - WorldInstance worldInstance = requireWorldInstance(tenantId, gameInstanceId); - rejectFixtureLifecycleMutation(worldInstance); + 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); @@ -883,19 +1041,20 @@ public WorldInstanceLifecycleSnapshotDto terminateWorldInstance( long expectedLifecycleEpoch, String terminationRequestId, String reason) { - if (fixtureModeEnabled()) throw fixtureWritesUnavailable(); 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); } @@ -909,11 +1068,11 @@ public WorldInstanceLifecycleSnapshotDto terminateWorldInstance( cleanupResponse.getError().getCode() + ": " + cleanupResponse.getError().getMessage()); } WorldInstanceLifecycleSnapshotDto terminatedSnapshot = - executeLocalTermination( + executeOwnedLifecycleTransaction( () -> { WorldInstance finalWorldInstance = requireLockedWorldInstance(tenantId, gameInstanceId); - rejectFixtureLifecycleMutation(finalWorldInstance); + requireLegacyFixtureLifecycleOwner(finalWorldInstance, fixtureEvidence); if (!terminationRequestId.equals(finalWorldInstance.getTerminationRequestId())) { throw new IllegalArgumentException( "INVALID_WORLD_INSTANCE_STATE: world instance termination request changed before finalization"); @@ -944,10 +1103,15 @@ private WorldInstance beginOrResumeTermination( long gameInstanceId, long expectedLifecycleEpoch, String terminationRequestId, - String reason) { + String reason, + RunOwnedWorldLaunchEvidence fixtureEvidence) { WorldInstance worldInstance = requireLockedWorldInstance(tenantId, gameInstanceId); - rejectFixtureLifecycleMutation(worldInstance); + requireLegacyFixtureLifecycleOwner(worldInstance, fixtureEvidence); if (STATUS_TERMINATED.equals(worldInstance.getStatus())) { + if (!terminationRequestId.equals(worldInstance.getTerminationRequestId())) { + throw new IllegalArgumentException( + "INVALID_WORLD_INSTANCE_STATE: world instance terminated under a different request id"); + } return worldInstance; } if (STATUS_ACTIVE.equals(worldInstance.getStatus())) { @@ -974,11 +1138,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) { @@ -997,8 +1161,15 @@ private void cleanupWorldRuntimeState(long tenantId, long gameInstanceId) { regionInstanceRepository.deleteByTenantIdAndGameInstanceId(tenantId, gameInstanceId); } - private static void rejectFixtureLifecycleMutation(WorldInstance worldInstance) { - if (worldInstance.getRunOwnedFixtureBindingSha256() != null) { + 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(); } } 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 d5a24d6c9e..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 @@ -12,7 +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.RunOwnedWorldLaunchEvidence; +import net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidence; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -161,7 +161,7 @@ public WorldAuthoredSourceIntakeReceipt intake( * supplied source DTOs cannot invoke the owner path. */ public WorldAuthoredSourceIntakeReceipt intakeRunOwnedFixture( - RunOwnedWorldLaunchEvidence fixtureEvidence) { + RunOwnedCanonicalWorldLaunchEvidence fixtureEvidence) { Objects.requireNonNull(fixtureEvidence, "fixtureEvidence"); fixtureEvidence.requireFixedGameSessionPeer(); requireNoAmbientTransaction(); 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 b210d42746..e1d45c61c7 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 @@ -11,7 +11,7 @@ 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.RunOwnedWorldLaunchEvidence; +import net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidence; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -91,7 +91,7 @@ public WorldAuthoredVersionIdentityReceipt associate( * bypass the ordinary authenticated Game Design entry point. */ public WorldAuthoredVersionIdentityReceipt associateRunOwnedFixture( - RunOwnedWorldLaunchEvidence fixtureEvidence, WorldAuthoredSourceIntakeReceipt sourceReceipt) { + RunOwnedCanonicalWorldLaunchEvidence fixtureEvidence, WorldAuthoredSourceIntakeReceipt sourceReceipt) { Objects.requireNonNull(fixtureEvidence, "fixtureEvidence"); fixtureEvidence.requireFixedGameSessionPeer(); Objects.requireNonNull(sourceReceipt, "sourceReceipt"); @@ -153,7 +153,7 @@ private WorldAuthoredVersionIdentityReceipt associateInternal( long gameDesignVersionId, UUID readRequestId, WorldAuthoredSourceIntakeReceipt expectedSourceReceipt, - RunOwnedWorldLaunchEvidence expectedFixtureEvidence) { + RunOwnedCanonicalWorldLaunchEvidence expectedFixtureEvidence) { requireNoAmbientTransaction(); validateRequest( targetNamespace, @@ -295,7 +295,7 @@ private WorldAuthoredVersionIdentityReceipt associateInternal( } private static void requireFixtureVersionStateMatches( - RunOwnedWorldLaunchEvidence fixtureEvidence, AuthoredWorldVersionStateEvidence current) { + RunOwnedCanonicalWorldLaunchEvidence fixtureEvidence, AuthoredWorldVersionStateEvidence current) { if (current == null) { throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( "Game Design returned no current Version state for the sealed run-owned fixture"); @@ -323,7 +323,7 @@ private WorldAuthoredVersionIdentityReceipt requireSameIdentity( WorldAuthoredSourceIntakeReceipt sourceReceipt, UUID expectedCanonicalVersionId, long gameDesignVersionId, - RunOwnedWorldLaunchEvidence expectedFixtureEvidence) { + RunOwnedCanonicalWorldLaunchEvidence expectedFixtureEvidence) { if (!receipt.targetNamespace().equals(workloadNamespace) || !receipt.sourceIntakeReceipt().equals(sourceReceipt) || !receipt.canonicalTenantId().equals(sourceReceipt.canonicalTenantId()) 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 index df274a7f92..0daf9e996c 100644 --- 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 @@ -14,7 +14,7 @@ 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.RunOwnedWorldLaunchEvidence; +import net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidence; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; import org.jooq.DSLContext; import org.jooq.Field; @@ -418,7 +418,7 @@ public void retainClaimInOwnerTransaction(WorldCanonicalInstanceAssociation.Clai * safe. */ public void lockRunOwnedFixtureInOwnerTransaction( - RunOwnedWorldLaunchEvidence fixtureEvidence, + RunOwnedCanonicalWorldLaunchEvidence fixtureEvidence, PreparedWorldInstanceRequest gameSessionRequest) { Objects.requireNonNull(fixtureEvidence, "fixtureEvidence").requireFixedGameSessionPeer(); requireWritableReadCommittedOwnerTransaction(); @@ -469,7 +469,7 @@ public void lockRunOwnedFixtureInOwnerTransaction( * Design private keys as World keys. */ public WorldCanonicalInstanceAssociation allocateRunOwnedFixtureInOwnerTransaction( - RunOwnedWorldLaunchEvidence fixtureEvidence, + RunOwnedCanonicalWorldLaunchEvidence fixtureEvidence, PreparedWorldInstanceRequest gameSessionRequest, WorldAuthoredSourceIntakeReceipt sourceReceipt, WorldAuthoredVersionIdentityReceipt versionIdentity) { @@ -663,7 +663,7 @@ public WorldCanonicalInstanceAssociation allocateRunOwnedFixtureInOwnerTransacti private Map runOwnedFixtureWorldInstanceRow( long worldInstanceId, WorldCanonicalInstanceAssociation.WorldPrivateKeys worldPrivateKeys, - RunOwnedWorldLaunchEvidence evidence, + RunOwnedCanonicalWorldLaunchEvidence evidence, WorldCanonicalInstanceAssociation.CanonicalIdentity identity, String fixtureBindingSha256, String runtimeFlagsJson) { @@ -720,7 +720,7 @@ private Map runOwnedFixtureAssociationRow( WorldCanonicalInstanceAssociation.CanonicalIdentity identity, long worldInstanceId, WorldCanonicalInstanceAssociation.WorldPrivateKeys worldPrivateKeys, - RunOwnedWorldLaunchEvidence evidence, + RunOwnedCanonicalWorldLaunchEvidence evidence, WorldAuthoredSourceIntakeReceipt sourceReceipt, WorldAuthoredVersionIdentityReceipt versionIdentity, String preparationInputDigest, @@ -831,7 +831,7 @@ private Record findFixtureConflict( private static void requireSameRunOwnedFixture( WorldCanonicalInstanceAssociation stored, - RunOwnedWorldLaunchEvidence evidence, + RunOwnedCanonicalWorldLaunchEvidence evidence, PreparedWorldInstanceRequest request, WorldAuthoredSourceIntakeReceipt sourceReceipt, WorldAuthoredVersionIdentityReceipt versionIdentity) { @@ -903,7 +903,7 @@ public Optional readOwnerAssociation( * never used as a World key. */ public WorldCanonicalInstanceAssociation readRunOwnedFixtureAssociation( - RunOwnedWorldLaunchEvidence evidence, + RunOwnedCanonicalWorldLaunchEvidence evidence, PreparedWorldInstanceRequest originalGameSessionRequest) { Objects.requireNonNull(evidence, "evidence").requireFixedGameSessionPeer(); requireNoActiveTransaction("Run-owned World fixture association read"); @@ -943,7 +943,7 @@ Optional readOwnerAssociationInActivationTran * Locks and verifies the immutable fixture association inside a writable lifecycle transaction. */ public WorldCanonicalInstanceAssociation readRunOwnedFixtureAssociationInActivationTransaction( - RunOwnedWorldLaunchEvidence evidence, + RunOwnedCanonicalWorldLaunchEvidence evidence, PreparedWorldInstanceRequest originalGameSessionRequest) { Objects.requireNonNull(evidence, "evidence").requireFixedGameSessionPeer(); requireWritableActivationTransaction(); @@ -974,7 +974,7 @@ public void activateRunOwnedFixtureInOwnerTransaction( private static void requireFixtureAssociationMatches( WorldCanonicalInstanceAssociation stored, - RunOwnedWorldLaunchEvidence evidence, + RunOwnedCanonicalWorldLaunchEvidence evidence, PreparedWorldInstanceRequest originalGameSessionRequest) { if (!stored.isRunOwnedFixture()) { throw new RegistrationConflictException( @@ -1419,7 +1419,7 @@ private void requireInsertBornFixtureIdentity( WorldCanonicalInstanceAssociation.CanonicalIdentity identity, WorldCanonicalInstanceAssociation.WorldPrivateKeys worldPrivateKeys, PreparedWorldInstanceRequest request, - RunOwnedWorldLaunchEvidence evidence, + RunOwnedCanonicalWorldLaunchEvidence evidence, String fixtureBindingSha256) { evidence.requireMatches(request); var gameSession = evidence.gameSessionAssociation(); 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/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest.java new file mode 100644 index 0000000000..cb10dfd07d --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/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/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java index a101b0159a..580fabfa6b 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 @@ -2,6 +2,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.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import io.grpc.ManagedChannel; import io.grpc.Server; @@ -37,11 +42,10 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.entitymanagement.v1.CleanupRuntimeInstanceResponse; 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; @@ -67,33 +71,59 @@ 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.EntityManagementClient; import net.firedevops.firemud.worldmanagement.client.GameDesignClient; -import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidence; +import net.firedevops.firemud.worldmanagement.config.WorldProperties; import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceProvider; -import net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleRequest; -import net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleResponse; +import net.firedevops.firemud.worldmanagement.entity.WorldInstance; +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.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; 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 org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; import tools.jackson.databind.json.JsonMapper; -/** Socket-level proof of authenticated World launch provenance reads from GS and GDS owners. */ +/** Socket-level proof of authenticated GS to World and World to exact GDS descriptor transport. */ class RunOwnedWorldLaunchEvidenceMtlsIntegrationTest { private static final String RUN_ID = "world-mtls-fixture-test"; private static final String PROJECT = "firemud-world-mtls-fixture-test"; + private static final String CLAIM_DIGEST = sha256Hex("controlled-world-mtls-fixture-claim-v1"); 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 WRONG_GS_URI = "spiffe://firemud/ns/other/sa/game-session-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 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", @@ -108,10 +138,8 @@ class RunOwnedWorldLaunchEvidenceMtlsIntegrationTest { private static TestPki pki; private Server worldServer; - private Server gameSessionOwnerServer; private Server gameDesignServer; private GameDesignClient gameDesignClient; - private RunOwnedWorldLaunchEvidenceProvider evidenceProvider; private ManagedChannel gameSessionChannel; @BeforeAll @@ -122,10 +150,6 @@ static void createCertificates() throws Exception { @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(); @@ -145,46 +169,27 @@ void stopTransport() throws Exception { 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 { + void physicalMtlsPrepareActivateAndOriginalEpochReplayReverifyReceiptAndOwnerDescriptor() + 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<>(); + AtomicReference worldAtOwner = new AtomicReference<>(); + AtomicReference worldCertificateAtOwner = new AtomicReference<>(); + AtomicReference requestAtOwner = new AtomicReference<>(); AtomicBoolean returnChangedDescriptor = new AtomicBoolean(); startGameDesignServer( fixture, descriptorReads, - worldAtGameDesign, - worldCertificateAtGameDesign, - descriptorRequestAtOwner, + worldAtOwner, + worldCertificateAtOwner, + requestAtOwner, 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, @@ -200,13 +205,22 @@ public > T customize(T stub) { System.setProperty("firemud.grpc.tls-reload.enabled", "false"); try { ReflectionTestUtils.invokeMethod(gameDesignClient, "init"); - evidenceProvider = fixture.provider(gameDesignClient, endpoints); - AtomicReference readEvidence = new AtomicReference<>(); - WorldManagementGrpcService readOnlyHandler = + 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, entityCleanupCalls); + WorldInstanceActivationServiceImpl activationService = + new WorldInstanceActivationServiceImpl( + commandService, java.util.Optional.empty(), evidenceProvider, worldRepository); + AtomicReference gameSessionAtWorld = new AtomicReference<>(); + WorldManagementGrpcService grpcService = new WorldManagementGrpcService( null, null, - null, + activationService, null, null, null, @@ -215,114 +229,507 @@ public > T customize(T stub) { 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(); + public void prepareWorldInstance( + PrepareWorldInstanceRequest request, + StreamObserver< + net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse> + responseObserver) { + gameSessionAtWorld.set(GrpcPeerIdentity.current()); + super.prepareWorldInstance(request, responseObserver); + } + + @Override + public void activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest request, + StreamObserver< + net.firedevops.firemud.worldmanagement.v1 + .ActivatePreparedWorldInstanceResponse> + responseObserver) { + gameSessionAtWorld.set(GrpcPeerIdentity.current()); + 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(readOnlyHandler); + worldServer = startWorldServer(grpcService); gameSessionChannel = channel("localhost", worldServer.getPort(), pki.gameSessionClient()); - var response = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) - .getWorldInstanceLifecycle( - GetWorldInstanceLifecycleRequest.newBuilder() - .setTenantId("142") - .setGameInstanceId("1001") + WorldManagementServiceGrpc.WorldManagementServiceBlockingStub gameSession = + 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(worldSaves).hasValue(writesAfterPrepare); + assertThat(descriptorReads).hasValue(readsAfterPrepare); + + var wrongReference = + 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("11111111-1111-4111-8111-111111111111") + .setVersionStateEpoch(77L) + .build()); + assertThat(wrongReference.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterPrepare); + assertThat(descriptorReads).hasValue(2); + + var activated = + gameSession.activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(activated.hasError()).isFalse(); + assertThat(activated.getWorldInstance().getStatus()) + .isEqualTo(WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE); + assertThat(activated.getWorldInstance().getLifecycleEpoch()).isEqualTo(2L); + int writesAfterActivation = worldSaves.get(); - 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()) + var replay = + gameSession.activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(replay.hasError()).isFalse(); + assertThat(replay.getWorldInstance()).isEqualTo(activated.getWorldInstance()); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + assertThat(worldAtOwner.get()) .isNotNull() .extracting(GrpcPeerIdentity::uri) .isEqualTo(WORLD_URI); - assertThat(worldAtGameSession.get().isInNamespace("dev")).isTrue(); - assertThat(worldCertificateAtGameSession.get()) + assertThat(worldAtOwner.get().isService("world-management-service")).isTrue(); + assertThat(worldAtOwner.get().isInNamespace("dev")).isTrue(); + assertThat(worldCertificateAtOwner.get()) .isNotNull() .extracting(GrpcPeerCertificateEvidence::leafSha256) .isEqualTo(fingerprint(pki.worldManagement().certificate())); - assertThat(worldAtGameDesign.get()) + assertThat(requestAtOwner.get()).isNotNull(); + assertThat(requestAtOwner.get().getRequestId()).isNotBlank(); + assertThat(requestAtOwner.get().getCanonicalTenantId()) + .isEqualTo(fixture.descriptorEvidence().request().canonicalTenantId().toString()); + assertThat(requestAtOwner.get().getWorldSlug()) + .isEqualTo(fixture.descriptorEvidence().worldSlug()); + assertThat(requestAtOwner.get().getControlPlaneRequestId()).isEqualTo(fixture.operationId()); + assertThat(requestAtOwner.get().getExpectedRequestDigest()) + .isEqualTo(fixture.descriptorEvidence().requestDigest()); + assertThat(requestAtOwner.get().getExpectedResultDigest()) + .isEqualTo(fixture.descriptorEvidence().resultDigest()); + assertThat(gameSessionAtWorld.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); + .isEqualTo(GS_URI); + + SessionContext.setContext("42", List.of("tenantAdmin"), java.util.Map.of()); + var ordinaryCaller = + authenticatedPlayerGameSessionStub() + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + SessionContext.clear(); + assertThat(ordinaryCaller.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + + gameSessionChannel.shutdownNow(); + assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + gameSessionChannel = channelWithoutClientIdentity("localhost", worldServer.getPort()); + assertThatThrownBy( + () -> + authenticatedGameSessionStub() + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build())) + .isInstanceOf(StatusRuntimeException.class); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + + gameSessionChannel.shutdownNow(); + assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + gameSessionChannel = + channel("localhost", worldServer.getPort(), pki.wrongNamespaceGameSessionClient()); + var wrongPeer = + authenticatedGameSessionStub() + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(wrongPeer.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + + gameSessionChannel.shutdownNow(); + assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + gameSessionChannel = + channel("localhost", worldServer.getPort(), pki.wrongGameSessionLeafClient()); + var wrongLeaf = + authenticatedGameSessionStub() + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(wrongLeaf.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + + gameSessionChannel.shutdownNow(); + assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + gameSessionChannel = + channel("localhost", worldServer.getPort(), pki.wrongCaGameSessionClient()); + assertThatThrownBy( + () -> + authenticatedGameSessionStub() + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build())) + .isInstanceOf(StatusRuntimeException.class); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + + gameSessionChannel.shutdownNow(); + assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + gameSessionChannel = channel("localhost", worldServer.getPort(), pki.gameSessionClient()); + fixture.reset(); + Fixture.writeFieldMismatch(fixture, "caCertificateSha256", "f".repeat(64)); + var wrongCa = + authenticatedGameSessionStub() + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(wrongCa.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + + fixture.reset(); + Fixture.writeFieldMismatch(fixture, "worldManagementLeafSha256", "e".repeat(64)); + var wrongWorldRecipient = + authenticatedGameSessionStub() + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(wrongWorldRecipient.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + + fixture.reset(); + Fixture.writeFieldMismatch( + fixture, "worldManagementUriSan", "spiffe://firemud/ns/dev/sa/other-world-service"); + var wrongWorldUri = + authenticatedGameSessionStub() + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(wrongWorldUri.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + + fixture.reset(); + var unknownInstance = + authenticatedGameSessionStub() + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("202") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(unknownInstance.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + + var duplicateOperation = + authenticatedGameSessionStub() + .prepareWorldInstance( + PrepareWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("202") + .setGameTemplateId("17") + .setControlPlaneRequestId(fixture.operationId()) + .setLaunchDescriptorId("launch-descriptor-fixture-11") + .setVersionId("11") + .setRuntimeFlagsJson("{}") + .setGenerationConfigRevision("genrev-11") + .setReleaseBundleId("77") + .setPublishedReleaseBundleRef(RELEASE_REF) + .setVersionStateEpoch(77L) + .build()); + assertThat(duplicateOperation.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(5); + + var staleAttempt = + authenticatedGameSessionStub() + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(99L) + .build()); + assertThat(staleAttempt.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(6); + + fixture.reset(); + Fixture.writeReceiptFieldMismatch(fixture, "sourceGameTenantKey", "43"); + var changedSource = + authenticatedGameSessionStub() + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(changedSource.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(6); + + fixture.reset(); + Fixture.writeFieldMismatch(fixture, "runId", "changed-run"); + var changedRun = + authenticatedGameSessionStub() + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(changedRun.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(6); + fixture.reset(); + Fixture.writeFieldMismatch(fixture, "composeProjectName", "different-project"); + var changedProject = + authenticatedGameSessionStub() + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(changedProject.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(6); + + fixture.reset(); + Fixture.writeReceiptFieldMismatch( + fixture, "fixtureOperationId", "11111111-1111-4111-8111-111111111111"); + var changedReceipt = + authenticatedGameSessionStub() + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(changedReceipt.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(6); + + fixture.reset(); + Fixture.writeReceiptFieldMismatch(fixture, "launchDescriptorBase64", "AAAA"); + var changedReceiptDescriptor = + authenticatedGameSessionStub() + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(changedReceiptDescriptor.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(6); + + fixture.reset(); returnChangedDescriptor.set(true); - var rejected = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) - .getWorldInstanceLifecycle( - GetWorldInstanceLifecycleRequest.newBuilder() - .setTenantId("142") - .setGameInstanceId("1001") + var changedOwnerDescriptor = + authenticatedGameSessionStub() + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) .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); + returnChangedDescriptor.set(false); + 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(worldSaves).hasValue(writesBeforeTermination); + assertThat(entityCleanupCalls).hasValue(0); + + 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"); @@ -401,9 +808,9 @@ public void getLaunchDescriptor( .canonicalTenantId() .toString() .equals(request.getCanonicalTenantId()) - || !isExpectedReadRequestId(request.getRequestId(), fixture.operationId) + || !isExpectedReadRequestId(request.getRequestId(), fixture.operationId()) || !fixture.descriptorEvidence().worldSlug().equals(request.getWorldSlug()) - || !fixture.operationId.equals(request.getControlPlaneRequestId()) + || !fixture.operationId().equals(request.getControlPlaneRequestId()) || !fixture .descriptorEvidence() .requestDigest() @@ -451,74 +858,6 @@ public void getLaunchDescriptor( .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( @@ -528,11 +867,33 @@ 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") @@ -545,6 +906,16 @@ private ManagedChannel channel(String host, int port, TestIdentity identity) thr .build(); } + private ManagedChannel channelWithoutClientIdentity(String host, int port) throws Exception { + return NettyChannelBuilder.forAddress(host, port) + .overrideAuthority("localhost") + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forClient().trustManager(pki.caCertificateValue())) + .build()) + .build(); + } + private static boolean isExpectedReadRequestId(String requestId, String operationId) { try { return !operationId.equals(UUID.fromString(requestId).toString()); @@ -553,40 +924,156 @@ private static boolean isExpectedReadRequestId(String requestId, String operatio } } + private RunOwnedWorldLaunchEvidenceProvider provider(Path directory, GameDesignClient client) { + CommonGrpcClientProperties tls = pki.worldClientProperties(); + return new RunOwnedWorldLaunchEvidenceProvider( + true, + directory.resolve("capability.json").toString(), + directory.resolve("source-receipt.json").toString(), + RUN_ID, + PROJECT, + tls, + client); + } + + private WorldInstanceRepository mockWorldRepository( + AtomicReference storedWorld, AtomicInteger worldSaves) { + WorldInstanceRepository repository = mock(WorldInstanceRepository.class); + when(repository.findByTenantIdAndGameInstanceId(anyLong(), anyLong())) + .thenAnswer( + invocation -> { + WorldInstance instance = storedWorld.get(); + return instance != null + && instance.getTenantId().equals(invocation.getArgument(0)) + && instance.getGameInstanceId().equals(invocation.getArgument(1)) + ? java.util.Optional.of(instance) + : java.util.Optional.empty(); + }); + when(repository.findByTenantIdAndGameInstanceIdForUpdate(anyLong(), anyLong())) + .thenAnswer( + invocation -> { + WorldInstance instance = storedWorld.get(); + return instance != null + && instance.getTenantId().equals(invocation.getArgument(0)) + && instance.getGameInstanceId().equals(invocation.getArgument(1)) + ? java.util.Optional.of(instance) + : java.util.Optional.empty(); + }); + when(repository.findRunOwnedFixtureByTenantIdAndControlPlaneRequestIdForUpdate( + anyLong(), any(String.class))) + .thenAnswer( + invocation -> { + WorldInstance instance = storedWorld.get(); + return instance != null + && instance.getTenantId().equals(invocation.getArgument(0)) + && instance.getControlPlaneRequestId().equals(invocation.getArgument(1)) + ? java.util.Optional.of(instance) + : java.util.Optional.empty(); + }); + when(repository.save(any(WorldInstance.class))) + .thenAnswer( + invocation -> { + WorldInstance instance = invocation.getArgument(0); + if (instance.getId() == null) { + instance.setId(101L); + } + worldSaves.incrementAndGet(); + storedWorld.set(instance); + return instance; + }); + return repository; + } + + private WorldLifecycleCommandServiceImpl newCommandService( + WorldInstanceRepository worldRepository, + RunOwnedWorldLaunchEvidenceProvider evidenceProvider, + GameDesignClient client, + AtomicInteger entityCleanupCalls) { + RegionInstanceRepository regionRepository = mock(RegionInstanceRepository.class); + ZoneRepository zoneRepository = mock(ZoneRepository.class); + ZoneInstanceRepository zoneInstanceRepository = mock(ZoneInstanceRepository.class); + RoomRepository roomRepository = mock(RoomRepository.class); + RoomExitRepository roomExitRepository = mock(RoomExitRepository.class); + RoomInstanceRepository roomInstanceRepository = mock(RoomInstanceRepository.class); + RoomInstanceExitRepository roomInstanceExitRepository = mock(RoomInstanceExitRepository.class); + when(regionRepository.save(any())).thenAnswer(invocation -> invocation.getArgument(0)); + when(zoneRepository.findByTenantIdAndVersionIdOrderByIdAsc(anyLong(), anyLong())) + .thenReturn(List.of()); + when(zoneInstanceRepository.save(any())).thenAnswer(invocation -> invocation.getArgument(0)); + when(roomRepository.findByTenantIdAndVersionIdOrderByIdAsc(anyLong(), anyLong())) + .thenReturn(List.of()); + when(roomExitRepository.findByTenantIdAndVersionIdOrderByIdAsc(anyLong(), anyLong())) + .thenReturn(List.of()); + 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 = + new WorldLifecycleCommandServiceImpl( + worldRepository, + regionRepository, + zoneRepository, + zoneInstanceRepository, + roomRepository, + roomExitRepository, + roomInstanceRepository, + roomInstanceExitRepository, + mock(WorldEventRepository.class), + properties, + client, + entityManagementClient, + new SimpleMeterRegistry(), + new PlatformTransactionManager() { + @Override + public SimpleTransactionStatus getTransaction(TransactionDefinition definition) { + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) {} + + @Override + public void rollback(TransactionStatus status) {} + }, + evidenceProvider); + commandService.initMetrics(); + return commandService; + } + + /** Controlled closed local evidence; the launch descriptor is checked against the TLS owner. */ 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 String originalCapabilityJson; + private final String originalReceiptJson; + private String capabilityJson; + private String receiptJson; 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 final String operationId; 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, + CLAIM_DIGEST, RUN_ID, PROJECT, fingerprint(pki.gameSessionClient().certificate()), @@ -598,11 +1085,12 @@ private Fixture(Path parent, TestPki pki) throws Exception { version = versionState(); descriptorEvidence = RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.descriptorEvidence( - source, bundle, version, operationId); + source, bundle, version); launchDescriptor = AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(descriptorEvidence); - creationEvidence = creationEvidence(source); - launchReadEvidence = + var capability = capability(pki, operationId); + var creationEvidence = creationEvidence(source); + var launchReadEvidence = new RunOwnedInitialAdmissionFixtureWireCodec.LaunchReadEvidence( RunOwnedInitialAdmissionFixtureWireCodec.LAUNCH_READ_EVIDENCE_SCHEMA, 17L, @@ -612,12 +1100,8 @@ private Fixture(Path parent, TestPki pki) throws Exception { launchDescriptor); String policyRequestDigest = RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( - RunOwnedInitialAdmissionFixtureWireCodec.parseCapability( - capabilityJson(pki, operationId, claimDigest).getBytes(StandardCharsets.UTF_8)), - creationEvidence, - source, - launchReadEvidence); - policySeal = + capability, creationEvidence, source, launchReadEvidence); + var policySeal = new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal( RunOwnedInitialAdmissionFixtureWireCodec.FIXTURE_POLICY_SEAL_SCHEMA, RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE, @@ -625,8 +1109,8 @@ private Fixture(Path parent, TestPki pki) throws Exception { policyRequestDigest, RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( UUID.fromString(operationId), policyRequestDigest)); - String capabilityJson = capabilityJson(pki, operationId, claimDigest); - String receiptJson = + capabilityJson = capabilityJson(capability); + receiptJson = receiptJson( source, bundle, @@ -635,55 +1119,27 @@ private Fixture(Path parent, TestPki pki) throws Exception { 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); + originalCapabilityJson = capabilityJson; + originalReceiptJson = receiptJson; + writeReadonly(capabilityPath, capabilityJson.getBytes(StandardCharsets.UTF_8)); + writeReadonly(receiptPath, receiptJson.getBytes(StandardCharsets.UTF_8)); } static Fixture create(Path parent, TestPki pki) throws Exception { return new Fixture(parent, pki); } - RunOwnedWorldLaunchEvidenceProvider provider( - GameDesignClient client, ServiceEndpointsProperties endpoints) { + RunOwnedWorldLaunchEvidenceProvider provider(GameDesignClient client) { + CommonGrpcClientProperties tls = pki.worldClientProperties(); return new RunOwnedWorldLaunchEvidenceProvider( true, - capabilityPath.toString(), - receiptPath.toString(), + directory.resolve("capability.json").toString(), + directory.resolve("source-receipt.json").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); + tls, + client); } LaunchDescriptor launchDescriptor() { @@ -693,12 +1149,51 @@ LaunchDescriptor launchDescriptor() { AuthoredWorldLaunchDescriptorEvidence descriptorEvidence() { return descriptorEvidence; } + + String operationId() { + return operationId; + } + + void reset() throws IOException { + capabilityJson = originalCapabilityJson; + receiptJson = originalReceiptJson; + writeReadonly(capabilityPath, capabilityJson.getBytes(StandardCharsets.UTF_8)); + writeReadonly(receiptPath, receiptJson.getBytes(StandardCharsets.UTF_8)); + } + + static void writeFieldMismatch(Fixture fixture, String fieldName, String replacement) + throws IOException { + fixture.capabilityJson = replaceField(fixture.capabilityJson, fieldName, replacement); + fixture.receiptJson = replaceField(fixture.receiptJson, fieldName, replacement); + writeReadonly( + fixture.capabilityPath, fixture.capabilityJson.getBytes(StandardCharsets.UTF_8)); + writeReadonly(fixture.receiptPath, fixture.receiptJson.getBytes(StandardCharsets.UTF_8)); + } + + static void writeReceiptFieldMismatch(Fixture fixture, String fieldName, String replacement) + throws IOException { + fixture.receiptJson = replaceField(fixture.receiptJson, fieldName, replacement); + writeReadonly(fixture.receiptPath, fixture.receiptJson.getBytes(StandardCharsets.UTF_8)); + } + + private static String replaceField(String json, String fieldName, String replacement) { + String marker = "\"" + fieldName + "\":\""; + int start = json.indexOf(marker); + if (start < 0) { + throw new IllegalStateException("Fixture field was not present: " + fieldName); + } + int valueStart = start + marker.length(); + int end = json.indexOf('"', valueStart); + if (end < 0) { + throw new IllegalStateException("Fixture field value was not terminated: " + fieldName); + } + return json.substring(0, valueStart) + replacement + json.substring(end); + } } 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"); @@ -706,7 +1201,7 @@ private static AuthoredWorldSourceEvidence sourceEvidence(String operationId) { 1, "dev", registrationId, - sourceOperationId, + UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"), requestDigest, tenant, "fixture-tenant", @@ -718,7 +1213,7 @@ private static AuthoredWorldSourceEvidence sourceEvidence(String operationId) { AuthoredWorldSourceDigest.evidenceDigest( "dev", registrationId, - sourceOperationId, + UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"), requestDigest, tenant, "fixture-tenant", @@ -729,33 +1224,6 @@ private static AuthoredWorldSourceEvidence sourceEvidence(String operationId) { "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) @@ -807,10 +1275,10 @@ private static VersionStateSnapshot versionState() { } private static AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest( - AuthoredWorldSourceEvidence source, String operationId) { + AuthoredWorldSourceEvidence source) { return new AuthoredWorldLaunchDescriptorEvidence.Request( "dev", - operationId, + source.registrationRequestId().toString(), source.canonicalTenantId(), source.worldSlug(), source.operationId(), @@ -829,10 +1297,9 @@ private static AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest( private static AuthoredWorldLaunchDescriptorEvidence descriptorEvidence( AuthoredWorldSourceEvidence source, PublishedReleaseBundle bundle, - VersionStateSnapshot version, - String operationId) { + VersionStateSnapshot version) { return AuthoredWorldLaunchDescriptorEvidence.create( - expectedRequest(source, operationId), + expectedRequest(source), "launch-descriptor-fixture-11", bundle.getVersionId(), false, @@ -846,21 +1313,92 @@ private static AuthoredWorldLaunchDescriptorEvidence descriptorEvidence( null); } - private static String capabilityJson(TestPki pki, String operationId, String claimDigest) - throws Exception { + private static RunOwnedInitialAdmissionFixtureWireCodec.Capability capability( + TestPki pki, String operationId) throws Exception { + return new RunOwnedInitialAdmissionFixtureWireCodec.Capability( + RunOwnedInitialAdmissionFixtureWireCodec.CAPABILITY_SCHEMA, + RUN_ID, + PROJECT, + operationId, + 42L, + 17L, + 9L, + "demo", + "Demo World", + "production", + "Live Realm", + true, + true, + false, + "SHARED", + "ALLOW_NEW", + fingerprint(pki.gameSessionClient().certificate()), + GS_URI, + fingerprint(pki.caCertificateValue()), + WORLD_URI, + fingerprint(pki.worldManagement().certificate()), + CLAIM_DIGEST); + } + + private static String capabilityJson( + RunOwnedInitialAdmissionFixtureWireCodec.Capability capability) { 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"}\ + {"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"}\ """ .formatted( - RUN_ID, - PROJECT, + 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 FreshTenantCreationEvidence creationEvidence(AuthoredWorldSourceEvidence source) { + UUID requestId = UUID.fromString("21a3b51a-444e-4c08-bbd5-31d40f643ba2"); + UUID operationId = UUID.fromString("3a78e019-c907-49ba-a80a-6d132aeb2135"); + String requestDigest = + GameTenantCreationDigest.requestDigest( + source.targetNamespace(), + requestId, + source.sourceGameTenantKey(), + source.worldDisplayName(), + null); + return new FreshTenantCreationEvidence( + 1, + source.targetNamespace(), + requestId, + operationId, + requestDigest, + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + GameTenantCreationDigest.evidenceDigest( + source.targetNamespace(), + requestId, operationId, - fingerprint(pki.gameSessionClient().certificate()), - GS_URI, - fingerprint(pki.caCertificateValue()), - WORLD_URI, - fingerprint(pki.worldManagement().certificate()), - claimDigest); + requestDigest, + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind())); } private static String receiptJson( @@ -870,8 +1408,7 @@ private static String receiptJson( VersionStateSnapshot version, LaunchDescriptor descriptor, FreshTenantCreationEvidence creation, - RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal seal, - String operationId, + RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal policySeal, TestPki pki) throws Exception { return """ @@ -880,7 +1417,7 @@ private static String receiptJson( .formatted( RUN_ID, PROJECT, - operationId, + source.registrationRequestId(), GS_URI, fingerprint(pki.gameSessionClient().certificate()), fingerprint(pki.caCertificateValue()), @@ -911,11 +1448,11 @@ private static String receiptJson( creation.sourceGameTenantKey(), creation.provenanceKind(), creation.evidenceDigest(), - seal.schema(), - seal.ownerService(), - seal.operationId(), - seal.requestDigest(), - seal.evidenceDigest()); + policySeal.schema(), + policySeal.ownerService(), + policySeal.operationId(), + policySeal.requestDigest(), + policySeal.evidenceDigest()); } private static String encode(byte[] bytes) { @@ -927,7 +1464,25 @@ private static String fingerprint(X509Certificate certificate) throws Exception .formatHex(MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded())); } + private static String sha256Hex(String value) { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (java.security.NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is required", exception); + } + } + private static void writeReadonly(Path path, byte[] value) throws IOException { + if (Files.exists(path)) { + Files.setPosixFilePermissions( + path, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.GROUP_READ)); + } Files.write(path, value); Files.setPosixFilePermissions( path, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); @@ -944,7 +1499,10 @@ private record TestPki( Path caCertificatePath, TestIdentity worldManagement, TestIdentity gameDesignServer, - TestIdentity gameSessionClient) { + TestIdentity gameSessionClient, + TestIdentity wrongNamespaceGameSessionClient, + TestIdentity wrongGameSessionLeafClient, + TestIdentity wrongCaGameSessionClient) { static TestPki create(Path directory) throws Exception { Path caStore = directory.resolve("world-mtls-ca.p12"); runKeytool( @@ -990,13 +1548,56 @@ static TestPki create(Path directory) throws Exception { caCertificate = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); } + Path wrongCaStore = directory.resolve("world-mtls-untrusted-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=Untrusted World mTLS test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + wrongCaStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path wrongCa = directory.resolve("world-mtls-untrusted-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + wrongCaStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + wrongCa.toString(), + "-rfc"); 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")); + issueIdentity(directory, caStore, ca, "game-session", GS_URI, "clientAuth"), + issueIdentity(directory, caStore, ca, "wrong-game-session", WRONG_GS_URI, "clientAuth"), + issueIdentity(directory, caStore, ca, "wrong-game-session-leaf", GS_URI, "clientAuth"), + issueIdentity( + directory, wrongCaStore, wrongCa, "wrong-ca-game-session", GS_URI, "clientAuth")); } CommonGrpcClientProperties worldClientProperties() { 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 cd429bf2bd..ea2f6eee68 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 @@ -2,23 +2,32 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.clearInvocations; +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.spy; -import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.time.Instant; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; 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.AtomicBoolean; +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.entitymanagement.v1.CleanupRuntimeInstanceResponse; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; @@ -29,6 +38,7 @@ import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidence; import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceProvider; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; +import net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto; import net.firedevops.firemud.worldmanagement.entity.WorldInstance; import net.firedevops.firemud.worldmanagement.repository.RegionInstanceRepository; import net.firedevops.firemud.worldmanagement.repository.RoomExitRepository; @@ -40,12 +50,8 @@ 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.service.impl.InitialAdmissionBindHoldReconciler; -import net.firedevops.firemud.worldmanagement.service.impl.InstanceServiceImpl; -import net.firedevops.firemud.worldmanagement.service.impl.WorldEventServiceImpl; import net.firedevops.firemud.worldmanagement.service.impl.WorldLifecycleCommandServiceImpl; import org.jooq.DSLContext; -import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; @@ -54,7 +60,6 @@ import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; -import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.GenericContainer; @@ -63,8 +68,7 @@ import org.testcontainers.junit.jupiter.Testcontainers; /** - * PostgreSQL proof of fixture lifecycle denial before effects and passive binding storage. - * Controlled storage rows do not establish World materialization or activation authority. + * Real PostgreSQL proof for fixture binding durability, uniqueness, lock serialization, and CAS. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -91,105 +95,107 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private DSLContext dsl; @Autowired private AutowireCapableBeanFactory beanFactory; - @MockitoSpyBean private WorldInstanceRepository repository; + @Autowired private WorldInstanceRepository repository; @Autowired private WorldLifecycleCommandService lifecycleService; @Autowired private PlatformTransactionManager transactionManager; @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + // Controlled evidence inputs keep this proof focused on the real PostgreSQL lifecycle/CAS. @MockitoBean private RunOwnedWorldLaunchEvidenceProvider fixtureProvider; @MockitoBean private RunOwnedWorldLaunchEvidence fixtureEvidence; @MockitoBean private GameDesignClient gameDesignClient; @MockitoBean private GameSessionClient gameSessionClient; @MockitoBean private EntityManagementClient entityManagementClient; @MockitoBean private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; - // Keep unrelated scheduled writers inert so whole-schema snapshots measure fixture effects. - @MockitoBean private InitialAdmissionBindHoldReconciler initialAdmissionBindHoldReconciler; - @MockitoBean private WorldEventServiceImpl worldEventService; - @MockitoBean private InstanceServiceImpl instanceService; @Test - void fixturePrepareAndActivationRetryAndRestartDenyBeforeReadsOrPostgresEffects() { + void prepareActivationReplayRestartChangedReceiptAndDuplicateOperationUseDurableBinding() { long tenantId = 8_810_001L; long gameInstanceId = uniqueId(); PreparedWorldInstanceRequest request = request(tenantId, gameInstanceId, operationId()); - // This pre-existing controlled storage row supplies no canonical association or authority. - repository.save(passiveStorageRow(request, "a".repeat(64))); - when(fixtureProvider.isEnabled()).thenReturn(true); - when(fixtureProvider.requireAuthenticatedEvidence()) - .thenThrow( - new IllegalArgumentException( - "RUN_OWNED_WORLD_LAUNCH_EVIDENCE_UNAVAILABLE: controlled unavailable authenticated evidence")); - clearInvocations( - repository, - fixtureEvidence, - gameDesignClient, - gameSessionClient, - entityManagementClient, - bindProofClient); - Map> before = postgresState(); + String binding = "a".repeat(64); + configureEvidence(binding); try { - assertFixturePrepareDenied(() -> lifecycleService.prepareWorldInstance(request)); - assertFixturePrepareDenied(() -> lifecycleService.prepareWorldInstance(request)); - assertFixtureDenied( - () -> lifecycleService.activatePreparedWorldInstance(tenantId, gameInstanceId, 1L)); - assertFixtureDenied( - () -> lifecycleService.activatePreparedWorldInstance(tenantId, gameInstanceId, 1L)); - assertFixturePrepareDenied( - () -> - lifecycleService.prepareWorldInstance( - request(tenantId, uniqueId(), request.controlPlaneRequestId()))); + var prepared = lifecycleService.prepareWorldInstance(request); + WorldInstance stored = + repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); + assertThat(prepared.status()).isEqualTo("PREPARING"); + assertThat(stored.getLifecycleEpoch()).isEqualTo(1L); + assertThat(stored.getRunOwnedFixturePreparingLifecycleEpoch()).isEqualTo(1L); + assertThat(stored.getRunOwnedFixtureBindingSha256()).isEqualTo(binding); + assertThat(stored.getPublishedReleaseBundleRef()).isEqualTo(RELEASE_REF); + assertThat(stored.getRowVersion()).isZero(); + + var active = lifecycleService.activatePreparedWorldInstance(tenantId, gameInstanceId, 1L); + assertThat(active.status()).isEqualTo("ACTIVE"); + assertThat(active.lifecycleEpoch()).isEqualTo(2L); + WorldInstance activeRow = + repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); + assertThat(activeRow.getRunOwnedFixtureBindingSha256()).isEqualTo(binding); + assertThat(activeRow.getRunOwnedFixturePreparingLifecycleEpoch()).isEqualTo(1L); + long activeRowVersion = activeRow.getRowVersion(); RunOwnedWorldLaunchEvidenceProvider restartedProvider = mock(RunOwnedWorldLaunchEvidenceProvider.class); + RunOwnedWorldLaunchEvidence restartedEvidence = mock(RunOwnedWorldLaunchEvidence.class); when(restartedProvider.isEnabled()).thenReturn(true); - when(restartedProvider.requireAuthenticatedEvidence()) - .thenThrow( - new IllegalArgumentException( - "RUN_OWNED_WORLD_LAUNCH_EVIDENCE_UNAVAILABLE: controlled unavailable authenticated evidence")); - WorldInstanceRepository restartedRepository = spy(new WorldInstanceRepository(dsl)); + when(restartedProvider.requireAuthenticatedEvidence()).thenReturn(restartedEvidence); + when(restartedEvidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn(binding); + WorldInstanceRepository restartedRepository = new WorldInstanceRepository(dsl); WorldLifecycleCommandServiceImpl restartedService = restartedLifecycleService(restartedRepository, restartedProvider); - assertFixturePrepareDenied(() -> restartedService.prepareWorldInstance(request)); - assertFixtureDenied( - () -> restartedService.activatePreparedWorldInstance(tenantId, gameInstanceId, 1L)); - assertThat(postgresState()).isEqualTo(before); - verifyNoInteractions(repository, restartedRepository); - org.mockito.Mockito.verify(restartedProvider, org.mockito.Mockito.times(1)) - .requireAuthenticatedEvidence(); - verifyNoUpstreamReads(3); - } finally { - dsl.execute("DELETE FROM world_instance WHERE tenant_id = ?", tenantId); - } - } - @Test - void controlledPassiveStorageRetainsBindingAndEnforcesConstraintsUniquenessAndCas() { - clearInvocations(fixtureProvider, fixtureEvidence); - long tenantId = 8_810_004L; - long gameInstanceId = uniqueId(); - PreparedWorldInstanceRequest request = request(tenantId, gameInstanceId, operationId()); - try { - WorldInstance stored = repository.save(passiveStorageRow(request, "a".repeat(64))); - assertThat(stored.getStatus()).isEqualTo("PREPARING"); - assertThat(stored.getLifecycleEpoch()).isEqualTo(1L); - assertThat(stored.getRunOwnedFixturePreparingLifecycleEpoch()).isEqualTo(1L); - assertThat(stored.getRunOwnedFixtureBindingSha256()).isEqualTo("a".repeat(64)); - assertThat(stored.getPublishedReleaseBundleRef()).isEqualTo(RELEASE_REF); - assertThat(stored.getRowVersion()).isZero(); - WorldInstanceRepository restartedRepository = new WorldInstanceRepository(dsl); + var replay = restartedService.activatePreparedWorldInstance(tenantId, gameInstanceId, 1L); + assertThat(replay).isEqualTo(active); + verify(restartedProvider).requireAuthenticatedEvidence(); assertThat( - restartedRepository + repository .findByTenantIdAndGameInstanceId(tenantId, gameInstanceId) - .orElseThrow()) - .usingRecursiveComparison() - .isEqualTo(stored); + .orElseThrow() + .getRowVersion()) + .isEqualTo(activeRowVersion); + var prepareReplay = restartedService.prepareWorldInstance(request); + assertThat(prepareReplay).isEqualTo(active); assertThat( - restartedRepository - .findRunOwnedFixtureByTenantIdAndControlPlaneRequestId( - tenantId, request.controlPlaneRequestId()) - .orElseThrow()) - .usingRecursiveComparison() - .isEqualTo(stored); + repository + .findByTenantIdAndGameInstanceId(tenantId, gameInstanceId) + .orElseThrow() + .getRowVersion()) + .isEqualTo(activeRowVersion); + verify(restartedProvider, org.mockito.Mockito.times(2)).requireAuthenticatedEvidence(); + + RunOwnedWorldLaunchEvidenceProvider changedProvider = + mock(RunOwnedWorldLaunchEvidenceProvider.class); + RunOwnedWorldLaunchEvidence changedEvidence = mock(RunOwnedWorldLaunchEvidence.class); + when(changedProvider.isEnabled()).thenReturn(true); + when(changedProvider.requireAuthenticatedEvidence()).thenReturn(changedEvidence); + when(changedEvidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn("b".repeat(64)); + assertThatThrownBy( + () -> + restartedLifecycleService(new WorldInstanceRepository(dsl), changedProvider) + .activatePreparedWorldInstance(tenantId, gameInstanceId, 1L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageStartingWith("RUN_OWNED_WORLD_LAUNCH_EVIDENCE_MISMATCH:"); + assertThat( + repository + .findByTenantIdAndGameInstanceId(tenantId, gameInstanceId) + .orElseThrow() + .getRowVersion()) + .isEqualTo(activeRowVersion); + + PreparedWorldInstanceRequest duplicateOperation = + request(tenantId, uniqueId(), request.controlPlaneRequestId()); + when(fixtureEvidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn(binding); + assertThatThrownBy(() -> lifecycleService.prepareWorldInstance(duplicateOperation)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageStartingWith("RUN_OWNED_WORLD_LAUNCH_IDENTITY_CONFLICT:"); + verify(gameDesignClient, never()).getPublishedReleaseBundle(anyLong(), anyLong()); + verify(gameDesignClient, never()).getVersionAssetArtifactState(anyLong(), anyLong()); + verify(gameDesignClient, never()).getVersionState(anyLong(), anyLong()); + verify(fixtureProvider, org.mockito.Mockito.atLeast(3)).requireAuthenticatedEvidence(); assertThatThrownBy( () -> @@ -216,45 +222,6 @@ void controlledPassiveStorageRetainsBindingAndEnforcesConstraintsUniquenessAndCa gameInstanceId)) .isInstanceOf(RuntimeException.class); - assertThat( - restartedRepository - .findByTenantIdAndGameInstanceId(tenantId, gameInstanceId) - .orElseThrow()) - .usingRecursiveComparison() - .isEqualTo(stored); - - Map> beforeLifecycleDenials = postgresState(); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE world_instance SET status = 'ACTIVE' WHERE id = ?", stored.getId())) - .hasRootCauseInstanceOf(org.postgresql.util.PSQLException.class) - .rootCause() - .hasMessageContaining("lifecycle transitions are disabled"); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE world_instance SET lifecycle_epoch = lifecycle_epoch + 1 WHERE id = ?", - stored.getId())) - .hasRootCauseInstanceOf(org.postgresql.util.PSQLException.class) - .rootCause() - .hasMessageContaining("lifecycle transitions are disabled"); - // Direct SQL cannot create an ACTIVE row from a passive fixture storage image either. - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO world_instance SELECT (jsonb_populate_record(NULL::world_instance, " - + "to_jsonb(w) || jsonb_build_object('id', ?, 'game_instance_id', ?, " - + "'control_plane_request_id', ?, 'status', 'ACTIVE'))).* FROM world_instance w WHERE id = ?", - uniqueId(), - uniqueId(), - operationId(), - stored.getId())) - .hasRootCauseInstanceOf(org.postgresql.util.PSQLException.class) - .rootCause() - .hasMessageContaining("must begin PREPARING"); - assertThat(postgresState()).isEqualTo(beforeLifecycleDenials); - WorldInstance staleCopy = repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); WorldInstance winningCopy = @@ -269,19 +236,27 @@ void controlledPassiveStorageRetainsBindingAndEnforcesConstraintsUniquenessAndCa repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); assertThat(durableWinner.getFailureReason()).isEqualTo("CAS winner"); assertThat(durableWinner.getRowVersion()).isEqualTo(savedWinningCopy.getRowVersion()); - assertThat(durableWinner.getRunOwnedFixtureBindingSha256()).isEqualTo("a".repeat(64)); - assertThat(durableWinner.getRunOwnedFixturePreparingLifecycleEpoch()).isEqualTo(1L); - WorldInstance duplicate = - passiveStorageRow( - request(tenantId, uniqueId(), request.controlPlaneRequestId()), "c".repeat(64)); + + WorldInstance duplicate = new WorldInstance(); + duplicate.setTenantId(tenantId); + duplicate.setGameInstanceId(uniqueId()); + duplicate.setGameTemplateId(17L); + duplicate.setControlPlaneRequestId(request.controlPlaneRequestId()); + duplicate.setLaunchDescriptorId("launch-descriptor-fixture-11"); + duplicate.setVersionId(11L); + duplicate.setRuntimeFlagsJson("{}"); + duplicate.setGenerationConfigRevision("genrev-11"); + duplicate.setReleaseBundleId(77L); + duplicate.setPublishedReleaseBundleRef(RELEASE_REF); + duplicate.setVersionStateEpoch(77L); + duplicate.setLifecycleEpoch(1L); + duplicate.setStatus("PREPARING"); + duplicate.setCreatedAt(Instant.now()); + duplicate.setUpdatedAt(Instant.now()); + duplicate.setRowVersion(0L); + duplicate.setRunOwnedFixtureBindingSha256("c".repeat(64)); + duplicate.setRunOwnedFixturePreparingLifecycleEpoch(1L); assertThatThrownBy(() -> repository.save(duplicate)).isInstanceOf(RuntimeException.class); - assertThat( - restartedRepository - .findByTenantIdAndGameInstanceId(tenantId, gameInstanceId) - .orElseThrow()) - .usingRecursiveComparison() - .isEqualTo(durableWinner); - verifyNoInteractions(fixtureProvider, fixtureEvidence); } finally { dsl.execute("DELETE FROM world_instance WHERE tenant_id = ?", tenantId); } @@ -325,138 +300,280 @@ void operationAdvisoryLockSerializesConcurrentRetriesOnPostgres() throws Excepti } @Test - void concurrentFixturePrepareAndActivationRetriesDenyWithoutPostgresOrUpstreamEffects() - throws Exception { + 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; long gameInstanceId = uniqueId(); PreparedWorldInstanceRequest request = request(tenantId, gameInstanceId, operationId()); - when(fixtureProvider.isEnabled()).thenReturn(true); - when(fixtureProvider.requireAuthenticatedEvidence()) - .thenThrow( - new IllegalArgumentException( - "RUN_OWNED_WORLD_LAUNCH_EVIDENCE_UNAVAILABLE: controlled unavailable authenticated evidence")); - clearInvocations( - repository, - fixtureEvidence, - gameDesignClient, - gameSessionClient, - entityManagementClient, - bindProofClient); - Map> before = postgresState(); + configureEvidence("d".repeat(64)); CountDownLatch ready = new CountDownLatch(2); CountDownLatch start = new CountDownLatch(1); try (ExecutorService executor = Executors.newFixedThreadPool(2)) { - Future first = + Future first = executor.submit( () -> { ready.countDown(); await(start); - assertFixturePrepareDenied(() -> lifecycleService.prepareWorldInstance(request)); - assertFixtureDenied( - () -> - lifecycleService.activatePreparedWorldInstance( - tenantId, gameInstanceId, 1L)); + return lifecycleService.prepareWorldInstance(request); }); - Future second = + Future second = executor.submit( () -> { ready.countDown(); await(start); - assertFixturePrepareDenied(() -> lifecycleService.prepareWorldInstance(request)); - assertFixtureDenied( - () -> - lifecycleService.activatePreparedWorldInstance( - tenantId, gameInstanceId, 1L)); + return lifecycleService.prepareWorldInstance(request); }); assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); start.countDown(); - first.get(20, TimeUnit.SECONDS); - second.get(20, TimeUnit.SECONDS); - assertThat(postgresState()).isEqualTo(before); - verifyNoInteractions(repository); - verifyNoUpstreamReads(2); + + var firstResult = first.get(20, TimeUnit.SECONDS); + var secondResult = second.get(20, TimeUnit.SECONDS); + assertThat(firstResult).isEqualTo(secondResult); + assertThat(firstResult.status()).isEqualTo("PREPARING"); + WorldInstance stored = + repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); + assertThat(stored.getRunOwnedFixtureBindingSha256()).isEqualTo("d".repeat(64)); + assertThat(stored.getRunOwnedFixturePreparingLifecycleEpoch()).isEqualTo(1L); + verify(fixtureProvider, org.mockito.Mockito.atLeast(2)).requireAuthenticatedEvidence(); } finally { start.countDown(); + dsl.execute("DELETE FROM world_instance WHERE tenant_id = ?", tenantId); } } - private static void assertFixtureDenied( - org.assertj.core.api.ThrowableAssert.ThrowingCallable call) { - assertThatThrownBy(call) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageStartingWith("RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE:"); - } - - private static void assertFixturePrepareDenied( - org.assertj.core.api.ThrowableAssert.ThrowingCallable call) { - assertThatThrownBy(call) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageStartingWith("RUN_OWNED_WORLD_LAUNCH_EVIDENCE_UNAVAILABLE:"); - } - - private void verifyNoUpstreamReads(int preparationVerifications) { - // Only preparation enters the controlled verifier; activation remains before-effects denied. - org.mockito.Mockito.verify(fixtureProvider, org.mockito.Mockito.times(preparationVerifications)) - .requireAuthenticatedEvidence(); - verifyNoInteractions( - fixtureEvidence, - gameDesignClient, - gameSessionClient, - entityManagementClient, - bindProofClient); - } - - private Map> postgresState() { - String schema = dsl.fetchSingle("SELECT current_schema()").get(0, String.class); - assertThat(schema).isEqualTo("world_management_service"); - List tables = - dsl.fetch("SELECT tablename FROM pg_tables WHERE schemaname = ? ORDER BY tablename", schema) - .getValues(0, String.class); - assertThat(tables).isNotEmpty().contains("world_instance"); - Map> state = new LinkedHashMap<>(); - for (String table : tables) { - // Entire rows and xmin retain source/resource bytes as well as lifecycle/CAS state. - state.put( - table, - dsl.fetch( - "SELECT to_jsonb(retained)::text || ':xmin=' || retained.xmin::text FROM " - + DSL.name(schema, table) - + " retained ORDER BY 1") - .getValues(0, String.class)); - } - List sequences = - dsl.fetch( - "SELECT to_jsonb(retained)::text FROM (SELECT sequencename, last_value " - + "FROM pg_sequences WHERE schemaname = ? ORDER BY sequencename) retained", - schema) - .getValues(0, String.class); - assertThat(sequences).isNotEmpty(); - state.put("sequences", sequences); - return state; + private void configureEvidence(String binding) { + when(fixtureProvider.isEnabled()).thenReturn(true); + when(fixtureProvider.requireAuthenticatedEvidence()).thenReturn(fixtureEvidence); + when(fixtureEvidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn(binding); } - private static WorldInstance passiveStorageRow( - PreparedWorldInstanceRequest request, String binding) { - WorldInstance row = new WorldInstance(); - row.setTenantId(request.tenantId()); - row.setGameInstanceId(request.gameInstanceId()); - row.setGameTemplateId(request.gameTemplateId()); - row.setControlPlaneRequestId(request.controlPlaneRequestId()); - row.setLaunchDescriptorId(request.launchDescriptorId()); - row.setVersionId(request.versionId()); - row.setRuntimeFlagsJson(request.runtimeFlagsJson()); - row.setGenerationConfigRevision(request.generationConfigRevision()); - row.setReleaseBundleId(request.releaseBundleId()); - row.setPublishedReleaseBundleRef(request.publishedReleaseBundleRef()); - row.setVersionStateEpoch(request.versionStateEpoch()); - row.setLifecycleEpoch(1L); - row.setStatus("PREPARING"); - row.setCreatedAt(Instant.now()); - row.setUpdatedAt(Instant.now()); - row.setRowVersion(0L); - row.setRunOwnedFixtureBindingSha256(binding); - row.setRunOwnedFixturePreparingLifecycleEpoch(1L); - return row; + 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( 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 index a749b0b1c2..2fbed6f387 100644 --- 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 @@ -97,6 +97,20 @@ 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); @@ -220,6 +234,27 @@ class RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest { 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"), @@ -997,8 +1032,14 @@ void installed34ThroughParent40ToDefaultFrontierRetainsRowsXminAndStableLegacyUp String guardProcedure = schema + ".world_guard_canonical_activation_transition()"; var originalGuardIdentity = connection.fetchSingle( - "SELECT oid::text, prosecdef, proacl::text FROM pg_proc WHERE oid = to_regprocedure(?)", + "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(); @@ -1020,9 +1061,21 @@ void installed34ThroughParent40ToDefaultFrontierRetainsRowsXminAndStableLegacyUp .isEqualTo(retainedRowsAtV1042); assertThat( connection.fetchSingle( - "SELECT oid::text, prosecdef, proacl::text FROM pg_proc WHERE oid = to_regprocedure(?)", + "SELECT oid::text, proowner::text, prosecdef, proconfig::text, proacl::text FROM pg_proc WHERE oid = to_regprocedure(?)", guardProcedure)) .isEqualTo(originalGuardIdentity); + 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'", @@ -1256,7 +1309,7 @@ void missingOwnerAssociationRejectsPlanAndCannotAdoptAnExistingLegacyWorldRow() @Test @SuppressWarnings("unchecked") void realWorldOwnersMaterializeSixFixtureMappingsAndReplayExactCommittedBytes() { - RunOwnedWorldLaunchEvidence evidence = controlledEvidence(); + RunOwnedCanonicalWorldLaunchEvidence evidence = controlledEvidence(); var sourceRepository = new WorldAuthoredSourceIntakeRepository(dsl); var versionRepository = new WorldAuthoredVersionIdentityRepository(dsl); var associationRepository = @@ -1686,12 +1739,12 @@ void realWorldOwnersMaterializeSixFixtureMappingsAndReplayExactCommittedBytes() assertNoPendingManifests(worldId); } - private WorldLifecycleCommandServiceImpl nativeService(RunOwnedWorldLaunchEvidence evidence) { + private WorldLifecycleCommandServiceImpl nativeService(RunOwnedCanonicalWorldLaunchEvidence evidence) { return nativeService(evidence, new AtomicInteger()); } private WorldLifecycleCommandServiceImpl nativeService( - RunOwnedWorldLaunchEvidence evidence, AtomicInteger upstreamReads) { + 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())) @@ -1718,7 +1771,7 @@ private WorldLifecycleCommandServiceImpl nativeService( // 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 RunOwnedWorldLaunchEvidenceProvider( + new RunOwnedCanonicalWorldLaunchEvidenceProvider( true, "/controlled-unused-capability", "/controlled-unused-receipt", @@ -1815,6 +1868,656 @@ private static Map> allRows(DSLContext connection) { 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(); @@ -1940,6 +2643,7 @@ private static List remainingVersions() { versions.add("1042.4"); versions.add("1042.5"); versions.add("1042.6"); + versions.add("1042.7"); return List.copyOf(versions); } @@ -2480,7 +3184,7 @@ private static void assertSqlState( }); } - private RunOwnedWorldLaunchEvidence controlledEvidence() { + 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 index f35ce6f96e..dcf7712d55 100644 --- 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 @@ -27,7 +27,7 @@ public final class RunOwnedWorldFixtureEvidenceTestFixtures { private RunOwnedWorldFixtureEvidenceTestFixtures() {} - public static RunOwnedWorldLaunchEvidence create(ObjectMapper objectMapper) { + 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(); @@ -277,7 +277,7 @@ public static RunOwnedWorldLaunchEvidence create(ObjectMapper objectMapper) { assertThat( RunOwnedInitialAdmissionFixtureWireCodec.parseSourceReceipt(receiptBytes, capability)) .isEqualTo(receipt); - return new RunOwnedWorldLaunchEvidence( + return new RunOwnedCanonicalWorldLaunchEvidence( capability, receipt, descriptor, @@ -290,12 +290,12 @@ public static RunOwnedWorldLaunchEvidence create(ObjectMapper objectMapper) { gs); } - public static RunOwnedWorldLaunchEvidence create() { + public static RunOwnedCanonicalWorldLaunchEvidence create() { return create(new ObjectMapper()); } /** A fresh response correlation with identical allocation and original immutable policy bytes. */ - public static RunOwnedWorldLaunchEvidence freshObservation(RunOwnedWorldLaunchEvidence original) { + public static RunOwnedCanonicalWorldLaunchEvidence freshObservation(RunOwnedCanonicalWorldLaunchEvidence original) { var gs = original.gameSessionAssociation(); var freshRequest = new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest( @@ -322,8 +322,8 @@ public static RunOwnedWorldLaunchEvidence freshObservation(RunOwnedWorldLaunchEv } /** Valid JSON with changed retained bytes must not replace the original preparation binding. */ - public static RunOwnedWorldLaunchEvidence changedReceiptBytes( - RunOwnedWorldLaunchEvidence original) { + public static RunOwnedCanonicalWorldLaunchEvidence changedReceiptBytes( + RunOwnedCanonicalWorldLaunchEvidence original) { byte[] bytes = original.sourceReceiptBytes(); byte[] changed = java.util.Arrays.copyOf(bytes, bytes.length + 1); changed[bytes.length] = '\n'; @@ -335,7 +335,7 @@ public static RunOwnedWorldLaunchEvidence changedReceiptBytes( } /** Controlled contradictory GS owner allocation, for the actual retained-owner conflict guard. */ - public static RunOwnedWorldLaunchEvidence secondAssignment(RunOwnedWorldLaunchEvidence original) { + public static RunOwnedCanonicalWorldLaunchEvidence secondAssignment(RunOwnedCanonicalWorldLaunchEvidence original) { var gs = original.gameSessionAssociation(); long otherInstance = gs.gameInstanceId() == Long.MAX_VALUE ? 1L : gs.gameInstanceId() + 1L; var changed = @@ -356,7 +356,7 @@ public static RunOwnedWorldLaunchEvidence secondAssignment(RunOwnedWorldLaunchEv return copy(original, original.sourceReceiptBytes(), changed); } - public static PreparedWorldInstanceRequest request(RunOwnedWorldLaunchEvidence evidence) { + public static PreparedWorldInstanceRequest request(RunOwnedCanonicalWorldLaunchEvidence evidence) { var gs = evidence.gameSessionAssociation(); var descriptor = evidence.launchDescriptor(); return new PreparedWorldInstanceRequest( @@ -375,11 +375,11 @@ public static PreparedWorldInstanceRequest request(RunOwnedWorldLaunchEvidence e null); } - private static RunOwnedWorldLaunchEvidence copy( - RunOwnedWorldLaunchEvidence original, + private static RunOwnedCanonicalWorldLaunchEvidence copy( + RunOwnedCanonicalWorldLaunchEvidence original, byte[] receiptBytes, CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult gs) { - return new RunOwnedWorldLaunchEvidence( + return new RunOwnedCanonicalWorldLaunchEvidence( original.capability(), original.sourceReceipt(), original.launchDescriptor(), 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 index ba06b1b84e..02bc94a803 100644 --- 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 @@ -7,8 +7,8 @@ import net.firedevops.firemud.worldmanagement.client.GameDesignClient; import net.firedevops.firemud.worldmanagement.config.WorldProperties; import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldFixtureEvidenceTestFixtures; -import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidence; -import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceProvider; +import net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidence; +import net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidenceProvider; import net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto; import net.firedevops.firemud.worldmanagement.repository.RegionInstanceRepository; import net.firedevops.firemud.worldmanagement.repository.RoomExitRepository; @@ -38,7 +38,7 @@ private RunOwnedWorldFixtureLifecycleTestFactory() {} public static WorldLifecycleCommandServiceImpl create( DSLContext dsl, PlatformTransactionManager transactions, - RunOwnedWorldLaunchEvidenceProvider provider, + RunOwnedCanonicalWorldLaunchEvidenceProvider provider, AuthoredWorldSourceClient sourceClient, AuthoredWorldVersionStateClient versionClient, GameDesignClient gameDesign, @@ -89,7 +89,7 @@ public static WorldLifecycleCommandServiceImpl create( /** Owner-local preparation; callers must supply their real or explicitly controlled GS peer. */ public static WorldInstanceLifecycleSnapshotDto prepare( - WorldLifecycleCommandServiceImpl service, RunOwnedWorldLaunchEvidence evidence) { + WorldLifecycleCommandServiceImpl service, RunOwnedCanonicalWorldLaunchEvidence evidence) { return service.prepareRunOwnedFixture( RunOwnedWorldFixtureEvidenceTestFixtures.request(evidence), evidence); } 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..45a74bf9c4 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceProviderTest.java @@ -0,0 +1,972 @@ +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.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +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 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")); + } + + 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/RunOwnedWorldLaunchEvidenceTestFixtures.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.java similarity index 96% rename from services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceTestFixtures.java rename to services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.java index 12eb6f9201..9410a88a6a 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceTestFixtures.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.java @@ -21,11 +21,11 @@ /** * Complete controlled upstream test values; this factory proves no owner writes or TLS authority. */ -public final class RunOwnedWorldLaunchEvidenceTestFixtures { +public final class RunOwnedCanonicalWorldLaunchEvidenceTestFixtures { private static final String CLAIM_DIGEST = controlledClaimDigest(); private static final String RELEASE_REF = "8ce42642-53ae-4d07-aab8-37c43ce66e0c"; - private RunOwnedWorldLaunchEvidenceTestFixtures() {} + private RunOwnedCanonicalWorldLaunchEvidenceTestFixtures() {} private static String controlledClaimDigest() { try { @@ -39,11 +39,11 @@ private static String controlledClaimDigest() { } } - public static RunOwnedWorldLaunchEvidence create() { + public static RunOwnedCanonicalWorldLaunchEvidence create() { return createWithDescriptorOverrides(false, false); } - public static RunOwnedWorldLaunchEvidence createWithDescriptorOverrides( + public static RunOwnedCanonicalWorldLaunchEvidence createWithDescriptorOverrides( boolean scriptPatchVersionPresent, boolean remapSetIdPresent) { return create( false, @@ -56,7 +56,7 @@ public static RunOwnedWorldLaunchEvidence createWithDescriptorOverrides( remapSetIdPresent); } - static RunOwnedWorldLaunchEvidence create( + static RunOwnedCanonicalWorldLaunchEvidence create( boolean mismatchedSeal, String gameSessionLeafSha256, String worldManagementLeafSha256, @@ -286,7 +286,7 @@ static RunOwnedWorldLaunchEvidence create( 0L, policyRequestBytes, policySeal); - return new RunOwnedWorldLaunchEvidence( + return new RunOwnedCanonicalWorldLaunchEvidence( capability, receipt, descriptor, 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 index dd71ea93b7..06bb2db647 100644 --- 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 @@ -65,8 +65,8 @@ void rejectsRemapSetOverrideAtInitialPlanBeforeMaterialization() { private static void assertOverrideRejected( boolean scriptPatchVersionPresent, boolean remapSetIdPresent) { - RunOwnedWorldLaunchEvidence evidence = - RunOwnedWorldLaunchEvidenceTestFixtures.createWithDescriptorOverrides( + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.createWithDescriptorOverrides( scriptPatchVersionPresent, remapSetIdPresent); evidence.launchDescriptor().requireValid(); assertThat(evidence.launchDescriptor().scriptPatchVersionPresent()) @@ -91,7 +91,7 @@ private static void assertOverrideRejected( } private static WorldAuthoredSourceIntakeReceipt sourceReceipt( - RunOwnedWorldLaunchEvidence evidence) { + 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"); @@ -116,7 +116,7 @@ private static WorldAuthoredSourceIntakeReceipt sourceReceipt( } private static WorldAuthoredVersionIdentityReceipt versionReceipt( - RunOwnedWorldLaunchEvidence evidence, WorldAuthoredSourceIntakeReceipt sourceReceipt) { + RunOwnedCanonicalWorldLaunchEvidence evidence, WorldAuthoredSourceIntakeReceipt sourceReceipt) { var source = sourceReceipt.source(); var snapshot = evidence.sourceReceipt().launchReadEvidence().versionState(); var request = @@ -144,7 +144,7 @@ private static WorldAuthoredVersionIdentityReceipt versionReceipt( stateEvidence); } - private static T withFixturePeer(RunOwnedWorldLaunchEvidence evidence, Supplier action) { + private static T withFixturePeer(RunOwnedCanonicalWorldLaunchEvidence evidence, Supplier action) { GrpcPeerIdentity peer = new GrpcPeerIdentity( "spiffe://firemud/ns/dev/sa/game-session-service", "dev", "game-session-service"); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java index 881670c0a0..05f602cc9d 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java @@ -2,57 +2,27 @@ 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.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; -import io.grpc.Context; -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.gamedesign.AuthoredWorldLaunchDescriptorEvidence; 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.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +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.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; @@ -61,87 +31,15 @@ @ExtendWith(OutputCaptureExtension.class) class RunOwnedWorldLaunchEvidenceProviderTest { + private static final String CLAIM_DIGEST = "d".repeat(64); private static final String OPERATION_ID = - fixtureEvidence(false, "a".repeat(64), "b".repeat(64), "c".repeat(64)) - .capability() - .operationId(); + RunOwnedInitialAdmissionFixtureWireCodec.fixtureOperationId( + CLAIM_DIGEST, "fixture-run", "firemud-fixture-run", "a".repeat(64), "b".repeat(64)) + .toString(); private static final String RELEASE_REF = "8ce42642-53ae-4d07-aab8-37c43ce66e0c"; @TempDir Path temporaryDirectory; - @Test - void retainedCarrierRequiresOriginalFixedPeerAndLeafForEveryOwnerOperation() { - RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.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() { RunOwnedWorldLaunchEvidence evidence = fixtureEvidence(); @@ -151,54 +49,11 @@ void bindingDigestNormalizesAcceptedBlankOptionalOverridesToAbsent() { assertThat(evidence.bindingDigest(request(" ", " "), 1L)).isEqualTo(absent); } - @Test - void launchEvidenceBindsStartingAllocationPrivateKeysFromOwnerProjection() { - RunOwnedWorldLaunchEvidence 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); RunOwnedWorldLaunchEvidenceProvider provider = - provider( + new RunOwnedWorldLaunchEvidenceProvider( false, temporaryDirectory.resolve("missing-capability.json").toString(), temporaryDirectory.resolve("missing-receipt.json").toString(), @@ -230,7 +85,7 @@ void malformedWireLogsOnlyTheFixedVerificationStageAndPreservesWireError(Capture Files.setPosixFilePermissions( receipt, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); RunOwnedWorldLaunchEvidenceProvider provider = - provider( + new RunOwnedWorldLaunchEvidenceProvider( true, capability.toString(), receipt.toString(), @@ -273,7 +128,7 @@ void enabledFixtureRejectsRelativeCapabilityPathAtFileReadStage(CapturedOutput o String relativeCapabilityPath = workingDirectory.relativize(capability.toAbsolutePath().normalize()).toString(); RunOwnedWorldLaunchEvidenceProvider provider = - provider( + new RunOwnedWorldLaunchEvidenceProvider( true, relativeCapabilityPath, receipt.toString(), @@ -300,7 +155,7 @@ void enabledFixtureRejectsWritableCapabilityAtFileReadStage(CapturedOutput outpu Files.setPosixFilePermissions( receipt, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); RunOwnedWorldLaunchEvidenceProvider provider = - provider( + new RunOwnedWorldLaunchEvidenceProvider( true, capability.toString(), receipt.toString(), @@ -331,7 +186,7 @@ void enabledFixtureRejectsCapabilitySymlinkAtFileReadStage(CapturedOutput output receipt, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); Files.createSymbolicLink(capability, target.getFileName()); RunOwnedWorldLaunchEvidenceProvider provider = - provider( + new RunOwnedWorldLaunchEvidenceProvider( true, capability.toString(), receipt.toString(), @@ -347,422 +202,16 @@ void enabledFixtureRejectsCapabilitySymlinkAtFileReadStage(CapturedOutput output 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")); - RunOwnedWorldLaunchEvidenceProvider provider = - provider( - fixture, gameDesignClient, fixtureClient, fixture.endpoints(), fixture.tlsProperties()); - - try (PeerContext ignored = fixture.attachGameSessionPeer()) { - assertThatThrownBy(provider::requireAuthenticatedEvidence) - .isInstanceOf( - RunOwnedWorldLaunchEvidenceProvider.InvalidRunOwnedWorldLaunchEvidenceException.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 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))); - RunOwnedWorldLaunchEvidenceProvider provider = - provider( - fixture, gameDesignClient, fixtureClient, fixture.endpoints(), fixture.tlsProperties()); - - RunOwnedWorldLaunchEvidence 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(); - RunOwnedWorldLaunchEvidence 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()); - RunOwnedWorldLaunchEvidenceProvider provider = - provider( - fixture, gameDesignClient, fixtureClient, fixture.endpoints(), fixture.tlsProperties()); - - try (PeerContext ignored = fixture.attachGameSessionPeer()) { - assertThatThrownBy(provider::requireAuthenticatedEvidence) - .isInstanceOf( - RunOwnedWorldLaunchEvidenceProvider.InvalidRunOwnedWorldLaunchEvidenceException.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(); - RunOwnedWorldLaunchEvidenceProvider provider = - new RunOwnedWorldLaunchEvidenceProvider( - 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( - RunOwnedWorldLaunchEvidenceProvider.InvalidRunOwnedWorldLaunchEvidenceException.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()); - RunOwnedWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory = mock(); - RunOwnedWorldLaunchEvidenceProvider provider = - provider(fixture, gameDesignClient, null, null, fixture.tlsProperties(), factory); - - try (PeerContext ignored = fixture.attachGameSessionPeer()) { - assertThatThrownBy(provider::requireAuthenticatedEvidence) - .isInstanceOf( - RunOwnedWorldLaunchEvidenceProvider.InvalidRunOwnedWorldLaunchEvidenceException.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()); - RunOwnedWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory = mock(); - RunOwnedWorldLaunchEvidenceProvider provider = - provider( - fixture, - gameDesignClient, - null, - fixture.endpoints(), - fixture.tlsProperties(), - factory, - namespace); - - try (PeerContext ignored = fixture.attachGameSessionPeer()) { - assertThatThrownBy(provider::requireAuthenticatedEvidence) - .isInstanceOf( - RunOwnedWorldLaunchEvidenceProvider.InvalidRunOwnedWorldLaunchEvidenceException - .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))); - RunOwnedWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory = mock(); - when(factory.create(any(), any(), any(), anyString())).thenReturn(fixtureClient); - RunOwnedWorldLaunchEvidenceProvider 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")); - } - private static void assertFileRejectionStoppedBeforeWireParse(CapturedOutput output) { assertThat(output) .contains("Run-owned World launch evidence verification rejected; stage=CAPABILITY_FILE") .doesNotContain("stage=WIRE_PARSE"); } - private RunOwnedWorldLaunchEvidenceProvider provider( - ProviderFixture fixture, - GameDesignClient gameDesignClient, - CanonicalGameInstanceLaunchAssociationClient fixtureClient, - ServiceEndpointsProperties endpoints, - CommonGrpcClientProperties tlsProperties) { - return provider( - fixture, - gameDesignClient, - fixtureClient, - endpoints, - tlsProperties, - (ignoredEndpoints, ignoredTls, ignoredChannelFactory, ignoredNamespace) -> fixtureClient); - } - - private RunOwnedWorldLaunchEvidenceProvider provider( - ProviderFixture fixture, - GameDesignClient gameDesignClient, - CanonicalGameInstanceLaunchAssociationClient fixtureClient, - ServiceEndpointsProperties endpoints, - CommonGrpcClientProperties tlsProperties, - RunOwnedWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory) { - return provider( - fixture, gameDesignClient, fixtureClient, endpoints, tlsProperties, factory, "dev"); - } - - private RunOwnedWorldLaunchEvidenceProvider provider( - ProviderFixture fixture, - GameDesignClient gameDesignClient, - CanonicalGameInstanceLaunchAssociationClient fixtureClient, - ServiceEndpointsProperties endpoints, - CommonGrpcClientProperties tlsProperties, - RunOwnedWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory, - String namespace) { - return new RunOwnedWorldLaunchEvidenceProvider( - 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()); - RunOwnedWorldLaunchEvidence 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(RunOwnedWorldLaunchEvidence 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, + 42L, + 101L, 17L, OPERATION_ID, "launch-descriptor-fixture-11", @@ -777,196 +226,195 @@ private static PreparedWorldInstanceRequest request(String patch, String remap) } private static RunOwnedWorldLaunchEvidence fixtureEvidence() { - return fixtureEvidence(false); - } - - private static RunOwnedWorldLaunchEvidence fixtureEvidence(boolean mismatchedSeal) { - return fixtureEvidence(mismatchedSeal, "a".repeat(64), "b".repeat(64), "c".repeat(64)); - } - - private static RunOwnedWorldLaunchEvidence fixtureEvidence( - boolean mismatchedSeal, - String gameSessionLeafSha256, - String worldManagementLeafSha256, - String caCertificateSha256) { - return fixtureEvidence( - mismatchedSeal, - gameSessionLeafSha256, - worldManagementLeafSha256, - caCertificateSha256, - UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6d")); - } - - private static RunOwnedWorldLaunchEvidence fixtureEvidence( - boolean mismatchedSeal, - String gameSessionLeafSha256, - String worldManagementLeafSha256, - String caCertificateSha256, - UUID canonicalTenantId) { - return RunOwnedWorldLaunchEvidenceTestFixtures.create( - mismatchedSeal, - gameSessionLeafSha256, - worldManagementLeafSha256, - caCertificateSha256, - canonicalTenantId, - 1L, - false, - false); - } - - private static RunOwnedWorldLaunchEvidenceProvider provider( - boolean enabled, - String capabilityPath, - String receiptPath, - String runId, - String composeProjectName, - CommonGrpcClientProperties grpcProperties, - GameDesignClient gameDesignClient) { - return new RunOwnedWorldLaunchEvidenceProvider( - enabled, - capabilityPath, - receiptPath, - runId, - composeProjectName, - grpcProperties, - gameDesignClient, - null, - null, - "dev"); - } - - private record ProviderFixture( - RunOwnedWorldLaunchEvidence 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, + UUID registrationId = UUID.fromString(OPERATION_ID); + UUID sourceOperationId = UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"); + UUID canonicalTenantId = UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6d"); + 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", + OPERATION_ID, + 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, + RELEASE_REF, + false, + 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) + .setUpdatedAt("2026-10-15T03:00:00") + .setVersionState(VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED) + .setVersionStateEpoch(77L) + .build(); + RunOwnedInitialAdmissionFixtureWireCodec.Capability capability = + new RunOwnedInitialAdmissionFixtureWireCodec.Capability( + RunOwnedInitialAdmissionFixtureWireCodec.CAPABILITY_SCHEMA, + "fixture-run", + "firemud-fixture-run", + OPERATION_ID, + 42L, + 17L, + 9L, + "demo", + "Demo World", + "production", + "Live Realm", + true, 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()))); - } + "SHARED", + "ALLOW_NEW", + "a".repeat(64), + RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, + "b".repeat(64), + RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, + "c".repeat(64), + CLAIM_DIGEST); + UUID creationRequestId = UUID.fromString(OPERATION_ID); + UUID creationOperationId = UUID.fromString("b2af0092-07d6-433b-93ae-21120d88dd51"); + String creationRequestDigest = + net.firedevops.firemud.common.tenant.GameTenantCreationDigest.requestDigest( + "dev", creationRequestId, "42", "Demo World", null); + var creation = + new net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence( + 1, + "dev", + creationRequestId, + creationOperationId, + creationRequestDigest, + canonicalTenantId, + 29L, + "42", + "NEW_GAME_ROW", + net.firedevops.firemud.common.tenant.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 seal = + new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal( + RunOwnedInitialAdmissionFixtureWireCodec.FIXTURE_POLICY_SEAL_SCHEMA, + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE, + UUID.fromString(OPERATION_ID), + policyRequestDigest, + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + UUID.fromString(OPERATION_ID), policyRequestDigest)); + var receipt = + new RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt( + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_SCHEMA, + "fixture-run", + "firemud-fixture-run", + OPERATION_ID, + 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, + seal); + return new RunOwnedWorldLaunchEvidence( + capability, + receipt, + descriptor, + new byte[] {1}, + new byte[] {2}, + "a".repeat(64), + RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, + "c".repeat(64), + "b".repeat(64)); } } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/TestDataSeederTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/TestDataSeederTest.java index dee68973b3..c7b61de93d 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/TestDataSeederTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/TestDataSeederTest.java @@ -7,7 +7,6 @@ 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; import java.util.List; @@ -26,7 +25,6 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.boot.DefaultApplicationArguments; -import org.springframework.test.util.ReflectionTestUtils; class TestDataSeederTest { @Mock RegionRepository regionRepository; @@ -109,14 +107,6 @@ void runSeedsCanonicalTopologyWhenMissing() throws Exception { assertEquals(1021L, exitCaptor.getAllValues().get(1).getToRoom().getId()); } - @Test - void fixtureModeSkipsSeedingWithoutPreventingStartupOrAccessingRepositories() { - ReflectionTestUtils.setField(seeder, "runOwnedFixtureMode", true); - - seeder.run(new DefaultApplicationArguments(new String[] {})); - verifyNoInteractions(regionRepository, zoneRepository, roomRepository, roomExitRepository); - } - @Test void runReassertsCanonicalTopologyWhenRowsAlreadyExist() throws Exception { Region existingRegion = new Region(); 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 1d235fe5b5..85dfb51c37 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 @@ -9,11 +9,11 @@ import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doThrow; +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; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; @@ -32,8 +32,10 @@ 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.RunOwnedWorldLaunchEvidence; import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceProvider; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; +import net.firedevops.firemud.worldmanagement.entity.RegionInstance; import net.firedevops.firemud.worldmanagement.entity.Room; import net.firedevops.firemud.worldmanagement.entity.RoomExit; import net.firedevops.firemud.worldmanagement.entity.RoomInstance; @@ -54,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"; @@ -71,6 +74,7 @@ class WorldLifecycleCommandServiceImplTest { private GameDesignClient gameDesignClient; private AtomicBoolean localTransactionActive; private AtomicBoolean worldInstanceReadInLocalTransaction; + private TransactionOperations lifecycleTransactionOperations; private WorldLifecycleCommandServiceImpl service; @BeforeEach @@ -88,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) { @@ -118,7 +122,7 @@ public T execute(TransactionCallback action) { gameDesignClient, entityManagementClient, new SimpleMeterRegistry(), - transactionOperations); + lifecycleTransactionOperations); service.initMetrics(); when(gameDesignClient.getPublishedReleaseBundle(42L, 11L)) .thenReturn( @@ -268,6 +272,10 @@ 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.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) + .thenReturn(Optional.of(instance)); when(worldInstanceRepository.save(any(WorldInstance.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -294,6 +302,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)); @@ -303,6 +313,84 @@ 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.setActualTransactionActive(false); + } + } + @Test void terminateWorldInstanceDeletesRuntimeWorldStateBeforeFinalizing() { WorldInstance instance = new WorldInstance(); @@ -372,6 +460,105 @@ 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)); + + IllegalArgumentException conflict = + assertThrows( + IllegalArgumentException.class, + () -> fixtureService.terminateWorldInstance(42L, 101L, 2L, "term-other", "stop")); + + assertTrue(conflict.getMessage().contains("terminated under a different request id")); + 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(); @@ -750,142 +937,250 @@ void prepareWorldInstanceRejectsMissingRequiredManifestAssetKeyProof() { } @Test - void fixturePrepareRejectsUnavailableAuthenticatedEvidenceBeforeRepositoryInteraction() { + void fixturePrepareBindsOriginalPreparingEpochAndExactRetryDoesNotRepeatMaterialization() { RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); + RunOwnedWorldLaunchEvidence evidence = mock(RunOwnedWorldLaunchEvidence.class); when(provider.isEnabled()).thenReturn(true); - IllegalArgumentException unavailable = new IllegalArgumentException("unverified fixture peer"); - when(provider.requireAuthenticatedEvidence()).thenThrow(unavailable); + when(provider.requireAuthenticatedEvidence()).thenReturn(evidence); + when(evidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn("a".repeat(64)); + AtomicReference persisted = new AtomicReference<>(); + when(worldInstanceRepository.findRunOwnedFixtureByTenantIdAndControlPlaneRequestIdForUpdate( + 42L, "cp-1")) + .thenAnswer(invocation -> Optional.ofNullable(persisted.get())); + when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) + .thenAnswer(invocation -> Optional.ofNullable(persisted.get())); + when(worldInstanceRepository.save(any(WorldInstance.class))) + .thenAnswer( + invocation -> { + WorldInstance submitted = invocation.getArgument(0); + submitted.setId(101L); + persisted.set(copyWorldInstance(submitted)); + return submitted; + }); WorldLifecycleCommandServiceImpl fixtureService = fixtureService(provider); + PreparedWorldInstanceRequest request = ordinaryPreparedRequest(); - IllegalArgumentException error = - assertThrows( - IllegalArgumentException.class, - () -> fixtureService.prepareWorldInstance(ordinaryPreparedRequest())); + var prepared = fixtureService.prepareWorldInstance(request); - assertEquals(unavailable, error); - verify(provider).isEnabled(); - verify(provider).requireAuthenticatedEvidence(); - verifyNoWorldRepositoryOrOwnerInteraction(); + assertEquals("PREPARING", prepared.status()); + assertEquals(1L, prepared.lifecycleEpoch()); + assertEquals("a".repeat(64), persisted.get().getRunOwnedFixtureBindingSha256()); + assertEquals(1L, persisted.get().getRunOwnedFixturePreparingLifecycleEpoch()); + verify(evidence).requireMatches(request); + verify(worldInstanceRepository).lockRunOwnedFixtureOperation(42L, "cp-1"); + verify(gameDesignClient, never()).getPublishedReleaseBundle(42L, 11L); + verify(gameDesignClient, never()).getVersionAssetArtifactState(42L, 11L); + verify(gameDesignClient, never()).getVersionState(42L, 11L); + + var retry = fixtureService.prepareWorldInstance(request); + + assertEquals(prepared, retry); + persisted.get().setStatus("ACTIVE"); + persisted.get().setLifecycleEpoch(2L); + + var activeReplay = fixtureService.prepareWorldInstance(request); + + assertEquals("ACTIVE", activeReplay.status()); + assertEquals(2L, activeReplay.lifecycleEpoch()); + assertEquals("a".repeat(64), persisted.get().getRunOwnedFixtureBindingSha256()); + assertEquals(1L, persisted.get().getRunOwnedFixturePreparingLifecycleEpoch()); + verify(worldInstanceRepository, org.mockito.Mockito.times(1)).save(any(WorldInstance.class)); + verify(regionInstanceRepository, org.mockito.Mockito.times(1)).save(any(RegionInstance.class)); + verify(roomInstanceRepository, org.mockito.Mockito.times(1)).save(any(RoomInstance.class)); + verify(evidence, org.mockito.Mockito.times(3)).requireMatches(request); } @Test - void fixturePrepareRejectsAmbientTransactionBeforeRemoteEvidence() { + void fixturePrepareRejectsChangedBindingForExistingActiveRow() { RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); + RunOwnedWorldLaunchEvidence evidence = mock(RunOwnedWorldLaunchEvidence.class); when(provider.isEnabled()).thenReturn(true); - WorldLifecycleCommandServiceImpl fixtureService = fixtureService(provider); - org.springframework.transaction.support.TransactionSynchronizationManager - .setActualTransactionActive(true); - try { - IllegalStateException error = - assertThrows( - IllegalStateException.class, - () -> fixtureService.prepareWorldInstance(ordinaryPreparedRequest())); - assertTrue(error.getMessage().contains("no ambient transaction")); - verify(provider, never()).requireAuthenticatedEvidence(); - verifyNoWorldRepositoryOrOwnerInteraction(); - } finally { - org.springframework.transaction.support.TransactionSynchronizationManager - .setActualTransactionActive(false); - } + when(provider.requireAuthenticatedEvidence()).thenReturn(evidence); + when(evidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn("d".repeat(64)); + WorldInstance active = boundFixtureInstance("ACTIVE", 2L); + when(worldInstanceRepository.findRunOwnedFixtureByTenantIdAndControlPlaneRequestIdForUpdate( + 42L, "cp-1")) + .thenReturn(Optional.of(active)); + when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) + .thenReturn(Optional.of(active)); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> fixtureService(provider).prepareWorldInstance(ordinaryPreparedRequest())); + + assertTrue(error.getMessage().startsWith("RUN_OWNED_WORLD_LAUNCH_EVIDENCE_MISMATCH:")); + verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); } @Test - void fixtureActivationRefusesBeforeWorldReadOrProviderEvidence() { + void fixtureOperationCannotBeAssignedToASecondWorldInstance() { RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); + RunOwnedWorldLaunchEvidence evidence = mock(RunOwnedWorldLaunchEvidence.class); when(provider.isEnabled()).thenReturn(true); - WorldLifecycleCommandServiceImpl fixtureService = fixtureService(provider); + when(provider.requireAuthenticatedEvidence()).thenReturn(evidence); + when(evidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn("b".repeat(64)); + WorldInstance operationInstance = new WorldInstance(); + operationInstance.setGameInstanceId(101L); + when(worldInstanceRepository.findRunOwnedFixtureByTenantIdAndControlPlaneRequestIdForUpdate( + 42L, "cp-1")) + .thenReturn(Optional.of(operationInstance)); IllegalArgumentException error = assertThrows( IllegalArgumentException.class, - () -> fixtureService.activatePreparedWorldInstance(42L, 101L, 1L)); - - assertTrue(error.getMessage().startsWith("RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE:")); - verify(provider).isEnabled(); - verify(provider, never()).requireAuthenticatedEvidence(); - verifyNoWorldRepositoryOrOwnerInteraction(); + () -> + fixtureService(provider) + .prepareWorldInstance( + new PreparedWorldInstanceRequest( + 42L, + 202L, + 7L, + "cp-1", + "ld-1", + 11L, + null, + "{}", + "genrev-11", + 77L, + PUBLISHED_RELEASE_BUNDLE_REF, + 77L))); + + assertTrue(error.getMessage().startsWith("RUN_OWNED_WORLD_LAUNCH_IDENTITY_CONFLICT:")); + verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); + verify(gameDesignClient, never()).getPublishedReleaseBundle(42L, 11L); } @Test - void fixtureFailureAndTerminationRefuseBeforeWorldReadOrOtherEffects() { + void fixtureActivationVerifiesBindingThenAllowsOnlyOriginalEpochActiveReplayWithoutWrite() { 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 preparing = boundFixtureInstance("PREPARING", 1L); + AtomicReference persisted = new AtomicReference<>(copyWorldInstance(preparing)); + when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) + .thenAnswer(invocation -> Optional.of(copyWorldInstance(persisted.get()))); + when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) + .thenAnswer(invocation -> Optional.of(copyWorldInstance(persisted.get()))); + when(worldInstanceRepository.save(any(WorldInstance.class))) + .thenAnswer( + invocation -> { + WorldInstance submitted = invocation.getArgument(0); + submitted.setRowVersion(submitted.getRowVersion() + 1L); + persisted.set(copyWorldInstance(submitted)); + return copyWorldInstance(submitted); + }); WorldLifecycleCommandServiceImpl fixtureService = fixtureService(provider); - IllegalArgumentException failure = - assertThrows( - IllegalArgumentException.class, - () -> fixtureService.failPreparedWorldInstance(42L, 101L, 1L, "failed")); - IllegalArgumentException termination = - assertThrows( - IllegalArgumentException.class, - () -> fixtureService.terminateWorldInstance(42L, 101L, 2L, "term-1", "stop")); + var active = fixtureService.activatePreparedWorldInstance(42L, 101L, 1L); + assertEquals("ACTIVE", active.status()); + assertEquals(2L, active.lifecycleEpoch()); + assertEquals("c".repeat(64), persisted.get().getRunOwnedFixtureBindingSha256()); - assertTrue(failure.getMessage().startsWith("RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE:")); - assertTrue(termination.getMessage().startsWith("RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE:")); - verify(provider, times(2)).isEnabled(); - verifyNoWorldRepositoryOrOwnerInteraction(); + var replay = fixtureService.activatePreparedWorldInstance(42L, 101L, 1L); + assertEquals(active, replay); + verify(worldInstanceRepository, org.mockito.Mockito.times(1)).save(any(WorldInstance.class)); + verify(provider, org.mockito.Mockito.times(2)).requireAuthenticatedEvidence(); + verify(gameDesignClient, never()).getPublishedReleaseBundle(42L, 11L); + + var inOrder = inOrder(provider, worldInstanceRepository); + inOrder.verify(provider).requireAuthenticatedEvidence(); + inOrder.verify(worldInstanceRepository).findByTenantIdAndGameInstanceIdForUpdate(42L, 101L); + inOrder.verify(provider).requireAuthenticatedEvidence(); + inOrder.verify(worldInstanceRepository).findByTenantIdAndGameInstanceIdForUpdate(42L, 101L); } @Test - void failureRejectsRetainedFixtureBindingBeforeSaving() { - WorldInstance fixture = fixtureWorldInstance(); + void configuredFixtureRejectsUnboundExistingRowsAndStaleActiveReplayEpoch() { + 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 unbound = activeWorldInstance(); when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) - .thenReturn(Optional.of(fixture)); + .thenReturn(Optional.of(unbound)); + when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) + .thenReturn(Optional.of(unbound)); - IllegalArgumentException error = + IllegalArgumentException unboundError = assertThrows( IllegalArgumentException.class, - () -> service.failPreparedWorldInstance(42L, 101L, 1L, "failed")); + () -> fixtureService(provider).activatePreparedWorldInstance(42L, 101L, 2L)); + assertTrue(unboundError.getMessage().startsWith("RUN_OWNED_WORLD_LAUNCH_IDENTITY_CONFLICT:")); + verify(gameDesignClient, never()).getPublishedReleaseBundle(42L, 11L); - assertTrue(error.getMessage().startsWith("RUN_OWNED_WORLD_LAUNCH_EVIDENCE_UNAVAILABLE:")); + WorldInstance active = boundFixtureInstance("ACTIVE", 2L); + when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) + .thenReturn(Optional.of(active)); + when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) + .thenReturn(Optional.of(active)); + IllegalArgumentException stale = + assertThrows( + IllegalArgumentException.class, + () -> fixtureService(provider).activatePreparedWorldInstance(42L, 101L, 0L)); + assertTrue(stale.getMessage().startsWith("WORLD_INSTANCE_LIFECYCLE_STALE:")); verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); - verifyNoInteractionsWithRuntimeCleanupOwners(); } @Test - void terminationRejectsRetainedFixtureBindingBeforeWriteOrCleanup() { - WorldInstance fixture = fixtureWorldInstance(); + void fixtureActivationRejectsOriginalEpochForNonActiveRowsWithoutWrites() { + 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)); + WorldLifecycleCommandServiceImpl fixtureService = fixtureService(provider); + AtomicReference currentRow = new AtomicReference<>(); + when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) + .thenAnswer(invocation -> Optional.of(currentRow.get())); when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) - .thenReturn(Optional.of(fixture)); + .thenAnswer(invocation -> Optional.of(currentRow.get())); - IllegalArgumentException error = - assertThrows( - IllegalArgumentException.class, - () -> service.terminateWorldInstance(42L, 101L, 2L, "term-1", "stop")); + String[] statuses = {"FAILED_PRE_ACTIVATION", "TERMINATING", "TERMINATED"}; + long[] lifecycleEpochs = {2L, 3L, 4L}; + for (int index = 0; index < statuses.length; index++) { + WorldInstance row = boundFixtureInstance(statuses[index], lifecycleEpochs[index]); + currentRow.set(row); - assertTrue(error.getMessage().startsWith("RUN_OWNED_WORLD_LAUNCH_EVIDENCE_UNAVAILABLE:")); - verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); - verifyNoInteractions(entityManagementClient); - verifyNoInteractionsWithRuntimeCleanupOwners(); - } + IllegalArgumentException stale = + assertThrows( + IllegalArgumentException.class, + () -> fixtureService.activatePreparedWorldInstance(42L, 101L, 1L)); - private void verifyNoWorldRepositoryOrOwnerInteraction() { - org.mockito.Mockito.verifyNoInteractions( - worldInstanceRepository, - regionInstanceRepository, - zoneRepository, - zoneInstanceRepository, - roomRepository, - roomExitRepository, - roomInstanceRepository, - roomInstanceExitRepository, - worldEventRepository, - gameDesignClient, - entityManagementClient); - } + assertTrue(stale.getMessage().startsWith("WORLD_INSTANCE_LIFECYCLE_STALE:")); + assertEquals(statuses[index], row.getStatus()); + assertEquals(lifecycleEpochs[index], row.getLifecycleEpoch()); + } - private void verifyNoInteractionsWithRuntimeCleanupOwners() { - org.mockito.Mockito.verifyNoInteractions( - regionInstanceRepository, - zoneInstanceRepository, - roomInstanceRepository, - roomInstanceExitRepository, - worldEventRepository); + verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); + verify(regionInstanceRepository, never()).save(any()); + verify(zoneInstanceRepository, never()).save(any()); + verify(roomInstanceRepository, never()).save(any()); + verify(roomInstanceExitRepository, never()).save(any()); + verify(worldEventRepository, never()).save(any()); + verify(regionInstanceRepository, never()).deleteByTenantIdAndGameInstanceId(42L, 101L); + verify(zoneInstanceRepository, never()).deleteByTenantIdAndGameInstanceId(42L, 101L); + verify(roomInstanceRepository, never()).deleteByTenantIdAndGameInstanceId(42L, 101L); + verify(roomInstanceExitRepository, never()).deleteByTenantIdAndGameInstanceId(42L, 101L); + verify(worldEventRepository, never()).deleteByTenantIdAndGameInstanceId(42L, 101L); } 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 = @@ -903,7 +1198,7 @@ private WorldLifecycleCommandServiceImpl fixtureService( gameDesignClient, entityManagementClient, new SimpleMeterRegistry(), - (TransactionOperations) null, + transactionOperations, provider); fixtureService.initMetrics(); return fixtureService; @@ -925,6 +1220,15 @@ private static PreparedWorldInstanceRequest ordinaryPreparedRequest() { 77L); } + private WorldInstance boundFixtureInstance(String status, long lifecycleEpoch) { + WorldInstance instance = activeWorldInstance(); + instance.setLifecycleEpoch(lifecycleEpoch); + instance.setStatus(status); + instance.setRunOwnedFixtureBindingSha256("c".repeat(64)); + instance.setRunOwnedFixturePreparingLifecycleEpoch(1L); + return instance; + } + private WorldInstance activeWorldInstance() { WorldInstance instance = new WorldInstance(); instance.setId(101L); @@ -945,16 +1249,6 @@ private WorldInstance activeWorldInstance() { return instance; } - private static WorldInstance fixtureWorldInstance() { - WorldInstance instance = new WorldInstance(); - instance.setTenantId(42L); - instance.setGameInstanceId(101L); - instance.setLifecycleEpoch(1L); - instance.setStatus("PREPARING"); - instance.setRunOwnedFixtureBindingSha256("a".repeat(64)); - return instance; - } - private AtomicReference stubPersistedWorldInstance(WorldInstance initiallyLoaded) { AtomicReference persisted = new AtomicReference<>(copyWorldInstance(initiallyLoaded)); 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 c483874b59..870c6e5137 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 @@ -25,8 +25,8 @@ 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.RunOwnedWorldLaunchEvidence; -import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceTestFixtures; +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; @@ -59,7 +59,7 @@ void clearTransactionState() { @Test void fixtureIntakeRevalidatesPeerAndCallerBeforeAnyOwnerReadOrTransaction() { - RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.create(); + RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); WorldAuthoredSourceIntakeService fixtureService = fixtureService(); assertThatThrownBy(() -> withoutPeer(() -> fixtureService.intakeRunOwnedFixture(evidence))) .isInstanceOf(SecurityException.class); @@ -93,7 +93,7 @@ void fixtureIntakeRevalidatesPeerAndCallerBeforeAnyOwnerReadOrTransaction() { @Test void fixtureIntakeReadsControlledSourceBeforeSqlAndIndependentlyReadsExactReceiptAndRetry() { - RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.create(); + RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); AuthoredWorldSourceEvidence source = evidence.sourceReceipt().sourceEvidence(); AtomicInteger reads = new AtomicInteger(); AtomicReference committed = new AtomicReference<>(); @@ -162,7 +162,7 @@ void fixtureIntakeReadsControlledSourceBeforeSqlAndIndependentlyReadsExactReceip @Test void fixtureIntakeDeniesChangedRemoteSourceBeforeSql() { - RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.create(); + 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)); @@ -180,7 +180,7 @@ void fixtureIntakeDeniesChangedRemoteSourceBeforeSql() { @Test void fixtureIntakeDeniesNullOwnerReceiptBeforeIndependentReadback() { - RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.create(); + 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); @@ -204,7 +204,7 @@ void fixtureIntakeDeniesNullOwnerReceiptBeforeIndependentReadback() { @Test void fixtureIntakeDeniesMissingIndependentReceiptAfterOwnerTransaction() { - RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.create(); + 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); @@ -225,7 +225,7 @@ void fixtureIntakeDeniesMissingIndependentReceiptAfterOwnerTransaction() { @Test void fixtureIntakeDeniesChangedIndependentReceiptAfterOwnerTransaction() { - RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.create(); + RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); var source = evidence.sourceReceipt().sourceEvidence(); AtomicInteger reads = new AtomicInteger(); when(repository.read(eq("dev"), any(UUID.class))) @@ -251,7 +251,7 @@ void fixtureIntakeDeniesChangedIndependentReceiptAfterOwnerTransaction() { @Test void fixtureIntakeDeniesAmbientTransactionBeforeOwnerAccess() { - RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.create(); + RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); TransactionSynchronizationManager.setActualTransactionActive(true); assertThatThrownBy( () -> 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 126ef9d385..c9bc330d65 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 @@ -30,8 +30,8 @@ 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.RunOwnedWorldLaunchEvidence; -import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceTestFixtures; +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; @@ -81,7 +81,7 @@ void clearTransactionState() { @Test void fixtureVersionRevalidatesPeerAndCallerBeforeAnyOwnerOrRemoteRead() { - RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.create(); + RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); var sourceReceipt = sourceReceipt(evidence.sourceReceipt().sourceEvidence()); WorldAuthoredVersionIdentityService fixtureService = fixtureService(); assertThatThrownBy( @@ -125,7 +125,7 @@ void fixtureVersionRevalidatesPeerAndCallerBeforeAnyOwnerOrRemoteRead() { @Test void fixtureVersionConsumesCommittedSourceThenControlledCurrentStateBeforeSqlAndExactRetry() { - RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.create(); + RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); var source = evidence.sourceReceipt().sourceEvidence(); var intake = sourceReceipt(source); var canonicalVersion = evidence.gameSessionAssociation().canonicalVersionId(); @@ -247,7 +247,7 @@ void fixtureVersionConsumesCommittedSourceThenControlledCurrentStateBeforeSqlAnd @Test void fixtureVersionRejectsDifferentCommittedSourceBeforeVersionAccessOrSql() { - RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.create(); + RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); var source = evidence.sourceReceipt().sourceEvidence(); var intake = sourceReceipt(source); var different = @@ -290,7 +290,7 @@ void fixtureVersionRejectsDifferentCommittedSourceBeforeVersionAccessOrSql() { @Test void fixtureVersionRejectsRemoteStateEpochCanonicalVersionAndRequestSubstitutionBeforeSql() { - RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.create(); + RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); var source = evidence.sourceReceipt().sourceEvidence(); var intake = sourceReceipt(source); when(sourceIntakeRepository.readBySource( @@ -351,7 +351,7 @@ void fixtureVersionRejectsRemoteStateEpochCanonicalVersionAndRequestSubstitution @Test void fixtureVersionRejectsChangedRetainedSnapshotOnExactRetryWithoutRemoteOrSql() { - RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.create(); + RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); var source = evidence.sourceReceipt().sourceEvidence(); var intake = sourceReceipt(source); var canonicalVersion = evidence.gameSessionAssociation().canonicalVersionId(); @@ -463,7 +463,7 @@ void fixtureVersionRejectsChangedRetainedSnapshotOnExactRetryWithoutRemoteOrSql( @Test void fixtureVersionDeniesMissingOrSubstitutedIndependentVersionReceipt() { - RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.create(); + RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); var source = evidence.sourceReceipt().sourceEvidence(); var intake = sourceReceipt(source); var canonicalVersion = evidence.gameSessionAssociation().canonicalVersionId(); @@ -534,7 +534,7 @@ void fixtureVersionDeniesMissingOrSubstitutedIndependentVersionReceipt() { @Test void fixtureVersionDeniesAmbientTransactionBeforeOwnerAccess() { - RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.create(); + RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); TransactionSynchronizationManager.setActualTransactionActive(true); assertThatThrownBy( () -> 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 index 0831ecc3fe..5a5720e6fc 100644 --- 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 @@ -6,8 +6,8 @@ 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.RunOwnedWorldLaunchEvidence; -import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceTestFixtures; +import net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidence; +import net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidenceTestFixtures; import org.junit.jupiter.api.Test; class WorldCanonicalInstanceAssociationTest { @@ -53,7 +53,7 @@ void runOwnedFixtureUsesDeepValueEqualityAndRetainsDefensiveResponseBytes() { } private static FixtureCase validFixtureCase() { - RunOwnedWorldLaunchEvidence evidence = RunOwnedWorldLaunchEvidenceTestFixtures.create(); + 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"); From b36824cdc89e6eb421bf3ef77b44d3bab784951a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 17:58:34 +1300 Subject: [PATCH 16/45] test: align source-first proofs with lifecycle staging --- design/project-management/ai-observations.md | 2 + ...ame-authoring-publishing-and-activation.md | 2 +- ...xtureOwnerCompositionCrossServiceTest.java | 43 ++++++------ .../RunOwnedWorldFixedPresetResources.java | 3 +- .../WorldLifecycleCommandServiceImpl.java | 3 +- .../WorldAuthoredVersionIdentityService.java | 6 +- ...orldLaunchEvidenceMtlsIntegrationTest.java | 28 +++----- ...LaunchEvidencePostgresIntegrationTest.java | 67 +++++++++++++++++-- ...resetResourcesPostgresIntegrationTest.java | 29 ++++---- ...OwnedWorldFixtureEvidenceTestFixtures.java | 9 ++- ...OwnedWorldFixtureLifecycleTestFactory.java | 2 +- ...ionOwnerGuardsPostgresIntegrationTest.java | 35 +++++++--- ...onicalWorldLaunchEvidenceProviderTest.java | 22 +++--- ...RunOwnedWorldFixedPresetResourcesTest.java | 6 +- .../WorldLifecycleCommandServiceImplTest.java | 6 +- .../WorldAuthoredSourceIntakeServiceTest.java | 21 ++++-- ...rldAuthoredVersionIdentityServiceTest.java | 21 ++++-- ...WorldCanonicalInstanceAssociationTest.java | 3 +- 18 files changed, 200 insertions(+), 108 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 1eed5d1aca..ae559ca525 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -335,3 +335,5 @@ Entry format: - 2026-10-15: Preflight native Actions response shapes before publishing trusted callbacks. Completed Validation runs `38662647370` (20 modules) and `38651777538` (zero modules) both returned `pull_requests: []` despite canonical PR/base-SHA/head titles; association-required fixtures would have passed locally while disabling reporting. The optional summary now distinguishes title/SHA attribution from a separately pinned current-ref write fence; this is not historical-ref or required-gate provenance proof. Native webhook execution and partial-rerun shape still need hosted qualification. - 2026-10-15 follow-up to the #3210 pending-documentation report: Overseer clarified that publishing a coherent CI checkpoint with an explicit pending-check limitation is permitted and is not, by itself, a publication-safety violation. Consume results before claiming qualification; distinguish a pending proof state or inaccurate qualification report from a genuine safety incident. Routine proof completion belongs in the next aggregated milestone. + +- 2026-10-15: Review admission can report PR-wide `PARENT_MOVED` after a focused fix even when the live base, effective parent and latest Hosted parent are unchanged: an older CLI checkpoint retains a different parent and its prior reconciliation binds the preceding child head. On #3206, both new channel requests refused before quota use; compact status identified the historical evidence, and exact reconciliation was initiated. Admission diagnostics should identify the offending channel/checkpoint and reconciliation action. Reported to Overseer; this establishes diagnostic friction, not a policy defect. 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 e16c1055bd..a765f59ee5 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 @@ -16,7 +16,7 @@ The coherent receiving successor for [PR #3196](https://github.com/benhook1013/F 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. The current actual producer → persisted Game Session `STARTING` → World `PREPARING` composition across three production mTLS handlers is covered by [RunOwnedFixtureOwnerCompositionCrossServiceTest](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java); its current proof is recorded in [World Runtime and Movement](./world-runtime-and-movement.md#fixed-fixture-preparing-owner-preparation). 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. +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, but invokes the explicit canonical World owner under controlled peer/certificate context in [RunOwnedFixtureOwnerCompositionCrossServiceTest](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java); that changed candidate has compiled but its combined proof has not yet run. It does not qualify a production canonical World prepare RPC or 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 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 index a73da9e155..db5e87639d 100644 --- 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 @@ -47,9 +47,9 @@ import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; -import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldFixedPresetResources; 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; @@ -100,8 +100,8 @@ class RunOwnedFixtureOwnerCompositionCrossServiceTest extends TestDataSeederInte new PostgreSQLContainer<>(TestContainerImages.postgres()); @Test - void actualProducerAndCanonicalOwnersComposeOverMutualTlsOwnerReads( - @TempDir Path testDirectory) throws Exception { + void actualProducerAndCanonicalOwnersComposeOverMutualTlsOwnerReads(@TempDir Path testDirectory) + throws Exception { assertThat(environment.getRequiredProperty("spring.application.name")) .isEqualTo("game-design-service"); var applicationNameOrigin = @@ -314,15 +314,17 @@ void actualProducerAndCanonicalOwnersComposeOverMutualTlsOwnerReads( 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); + withControlledGameSessionPeer(fixture, provider::requireAuthenticatedEvidence); var request = exactPreparedWorldRequest(worldEvidence); var emptyWorldRows = allComposedOwnerRows(worldDatabase.dsl()); - var changedSource = changedSourceEvidence(receipt.sourceEvidence()); + 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)); @@ -332,7 +334,7 @@ void actualProducerAndCanonicalOwnersComposeOverMutualTlsOwnerReads( fixture, () -> ReflectionTestUtils.invokeMethod( - commands, "prepareRunOwnedFixture", request, worldEvidence))) + initialCommands, "prepareRunOwnedFixture", request, worldEvidence))) .isInstanceOf(RuntimeException.class); assertThat(allComposedOwnerRows(worldDatabase.dsl())).isEqualTo(emptyWorldRows); org.mockito.Mockito.verify(authoredWorldSourceRepository) @@ -346,7 +348,7 @@ void actualProducerAndCanonicalOwnersComposeOverMutualTlsOwnerReads( () -> (net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto) ReflectionTestUtils.invokeMethod( - commands, "prepareRunOwnedFixture", request, worldEvidence)); + initialCommands, "prepareRunOwnedFixture", request, worldEvidence)); assertThat(prepared).isNotNull(); assertThat(prepared.status()).isEqualTo("PREPARING"); assertThat(prepared.lifecycleEpoch()).isEqualTo(1L); @@ -452,13 +454,12 @@ void actualProducerAndCanonicalOwnersComposeOverMutualTlsOwnerReads( withControlledGameSessionPeer( fixture, () -> - (net.firedevops.firemud.worldmanagement.dto - .WorldInstanceLifecycleSnapshotDto) + (net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto) ReflectionTestUtils.invokeMethod( - commands, + initialCommands, "prepareRunOwnedFixture", request, - provider.requireAuthenticatedEvidence()))) + initialProvider.requireAuthenticatedEvidence()))) .isEqualTo(prepared); var reread = independentlyReadWorldFixture(worldDatabase.dsl(), starting.gameInstanceUuid()); assertThat( @@ -495,7 +496,7 @@ void actualProducerAndCanonicalOwnersComposeOverMutualTlsOwnerReads( fixture, () -> ReflectionTestUtils.invokeMethod( - commands, + initialCommands, "prepareRunOwnedFixture", mismatchedRequest, worldEvidence))) @@ -535,16 +536,17 @@ void actualProducerAndCanonicalOwnersComposeOverMutualTlsOwnerReads( worldTls, factory, registry); + var replayProvider = provider; + var replayCommands = commands; var replayEvidence = withControlledGameSessionPeer(fixture, provider::requireAuthenticatedEvidence); assertThat( withControlledGameSessionPeer( fixture, () -> - (net.firedevops.firemud.worldmanagement.dto - .WorldInstanceLifecycleSnapshotDto) + (net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto) ReflectionTestUtils.invokeMethod( - commands, "prepareRunOwnedFixture", request, replayEvidence))) + replayCommands, "prepareRunOwnedFixture", request, replayEvidence))) .isEqualTo(prepared); assertThat(allComposedOwnerRows(worldDatabase.dsl())).isEqualTo(worldRows); var reads = @@ -566,7 +568,7 @@ void actualProducerAndCanonicalOwnersComposeOverMutualTlsOwnerReads( org.assertj.core.api.Assertions.assertThatThrownBy( () -> withControlledPeer( - wrongSessionCertificate, provider::requireAuthenticatedEvidence)) + wrongSessionCertificate, replayProvider::requireAuthenticatedEvidence)) .isInstanceOf( RunOwnedCanonicalWorldLaunchEvidenceProvider .InvalidRunOwnedCanonicalWorldLaunchEvidenceException.class); @@ -673,8 +675,8 @@ private CommonGrpcClientProperties fixedReadTls(Fixture fixture, Path certificat return tls; } - private T withControlledGameSessionPeer(Fixture fixture, java.util.concurrent.Callable work) - throws Exception { + private T withControlledGameSessionPeer( + Fixture fixture, java.util.concurrent.Callable work) throws Exception { return withControlledPeer(readCertificate(fixture.gameSessionCertificatePath()), work); } @@ -714,7 +716,8 @@ private X509Certificate readCertificate(Path path) throws Exception { descriptor.remapSetIdPresent() ? descriptor.remapSetId() : null); } - private AuthoredWorldSourceEvidence changedSourceEvidence(AuthoredWorldSourceEvidence original) { + private AuthoredWorldSourceEvidence changedPreparedSourceEvidence( + AuthoredWorldSourceEvidence original) { String changedDisplayName = original.worldDisplayName() + " changed"; long changedSourceRowId = original.sourceGameRowId() == Long.MAX_VALUE ? 1L : original.sourceGameRowId() + 1L; 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 index 496e66f510..8fd648bf0b 100644 --- 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 @@ -96,7 +96,8 @@ public static FixedPresetPlan plan( RunOwnedCanonicalWorldLaunchEvidence evidence, WorldAuthoredSourceIntakeReceipt sourceReceipt, WorldAuthoredVersionIdentityReceipt versionReceipt) { - RunOwnedCanonicalWorldLaunchEvidence typedEvidence = Objects.requireNonNull(evidence, "evidence"); + RunOwnedCanonicalWorldLaunchEvidence typedEvidence = + Objects.requireNonNull(evidence, "evidence"); typedEvidence.requireFixedGameSessionPeer(); var descriptor = typedEvidence.launchDescriptor(); if (descriptor.scriptPatchVersionPresent() || descriptor.remapSetIdPresent()) { 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 75b1418f44..f0be244316 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 @@ -1167,8 +1167,7 @@ private void requireLegacyFixtureLifecycleOwner( if (fixtureModeEnabled()) { if (!fixtureBound) throw fixtureIdentityConflict(); if (fixtureEvidence == null) throw fixtureEvidenceUnavailable(); - requireRunOwnedFixtureBinding( - worldInstance, fixtureEvidence, preparedRequest(worldInstance)); + requireRunOwnedFixtureBinding(worldInstance, fixtureEvidence, preparedRequest(worldInstance)); } else if (fixtureBound) { throw fixtureEvidenceUnavailable(); } 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 e1d45c61c7..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 @@ -91,7 +91,8 @@ public WorldAuthoredVersionIdentityReceipt associate( * bypass the ordinary authenticated Game Design entry point. */ public WorldAuthoredVersionIdentityReceipt associateRunOwnedFixture( - RunOwnedCanonicalWorldLaunchEvidence fixtureEvidence, WorldAuthoredSourceIntakeReceipt sourceReceipt) { + RunOwnedCanonicalWorldLaunchEvidence fixtureEvidence, + WorldAuthoredSourceIntakeReceipt sourceReceipt) { Objects.requireNonNull(fixtureEvidence, "fixtureEvidence"); fixtureEvidence.requireFixedGameSessionPeer(); Objects.requireNonNull(sourceReceipt, "sourceReceipt"); @@ -295,7 +296,8 @@ private WorldAuthoredVersionIdentityReceipt associateInternal( } private static void requireFixtureVersionStateMatches( - RunOwnedCanonicalWorldLaunchEvidence fixtureEvidence, AuthoredWorldVersionStateEvidence current) { + RunOwnedCanonicalWorldLaunchEvidence fixtureEvidence, + AuthoredWorldVersionStateEvidence current) { if (current == null) { throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( "Game Design returned no current Version state for the sealed run-owned fixture"); 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 580fabfa6b..f182a90702 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 @@ -42,7 +42,6 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; -import net.firedevops.firemud.entitymanagement.v1.CleanupRuntimeInstanceResponse; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; @@ -62,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; @@ -211,7 +211,8 @@ public > T customize(T stub) { AtomicInteger entityCleanupCalls = new AtomicInteger(); WorldInstanceRepository worldRepository = mockWorldRepository(storedWorld, worldSaves); WorldLifecycleCommandServiceImpl commandService = - newCommandService(worldRepository, evidenceProvider, gameDesignClient, entityCleanupCalls); + newCommandService( + worldRepository, evidenceProvider, gameDesignClient, entityCleanupCalls); WorldInstanceActivationServiceImpl activationService = new WorldInstanceActivationServiceImpl( commandService, java.util.Optional.empty(), evidenceProvider, worldRepository); @@ -660,8 +661,7 @@ public void terminateWorldInstance( SessionContext.setContext("42", List.of("tenantAdmin"), java.util.Map.of()); var playerContextTermination = - authenticatedPlayerGameSessionStub() - .terminateWorldInstance(terminationRequest); + authenticatedPlayerGameSessionStub().terminateWorldInstance(terminationRequest); SessionContext.clear(); assertThat(playerContextTermination.hasError()).isTrue(); assertThat(worldSaves).hasValue(writesBeforeTermination); @@ -672,8 +672,7 @@ public void terminateWorldInstance( gameSessionChannel = channel("localhost", worldServer.getPort(), pki.wrongNamespaceGameSessionClient()); var wrongPeerTermination = - authenticatedGameSessionStub() - .terminateWorldInstance(terminationRequest); + authenticatedGameSessionStub().terminateWorldInstance(terminationRequest); assertThat(wrongPeerTermination.hasError()).isTrue(); assertThat(worldSaves).hasValue(writesBeforeTermination); assertThat(entityCleanupCalls).hasValue(0); @@ -684,8 +683,7 @@ public void terminateWorldInstance( gameSessionChannel = channel("localhost", worldServer.getPort(), pki.wrongGameSessionLeafClient()); var wrongLeafTermination = - authenticatedGameSessionStub() - .terminateWorldInstance(terminationRequest); + authenticatedGameSessionStub().terminateWorldInstance(terminationRequest); assertThat(wrongLeafTermination.hasError()).isTrue(); assertThat(worldSaves).hasValue(writesBeforeTermination); assertThat(entityCleanupCalls).hasValue(0); @@ -695,9 +693,7 @@ public void terminateWorldInstance( assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); gameSessionChannel = channelWithoutClientIdentity("localhost", worldServer.getPort()); assertThatThrownBy( - () -> - authenticatedGameSessionStub() - .terminateWorldInstance(terminationRequest)) + () -> authenticatedGameSessionStub().terminateWorldInstance(terminationRequest)) .isInstanceOf(StatusRuntimeException.class); assertThat(worldSaves).hasValue(writesBeforeTermination); assertThat(entityCleanupCalls).hasValue(0); @@ -705,9 +701,7 @@ public void terminateWorldInstance( gameSessionChannel.shutdownNow(); assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); gameSessionChannel = channel("localhost", worldServer.getPort(), pki.gameSessionClient()); - var terminated = - authenticatedGameSessionStub() - .terminateWorldInstance(terminationRequest); + var terminated = authenticatedGameSessionStub().terminateWorldInstance(terminationRequest); assertThat(terminated.hasError()).isFalse(); assertThat(terminated.getWorldInstance().getStatus()) .isEqualTo(WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_TERMINATED); @@ -716,8 +710,7 @@ public void terminateWorldInstance( assertThat(entityCleanupCalls).hasValue(1); var terminalReplay = - authenticatedGameSessionStub() - .terminateWorldInstance(terminationRequest); + authenticatedGameSessionStub().terminateWorldInstance(terminationRequest); assertThat(terminalReplay.hasError()).isFalse(); assertThat(terminalReplay.getWorldInstance()).isEqualTo(terminated.getWorldInstance()); assertThat(worldSaves).hasValue(writesBeforeTermination + 2); @@ -872,8 +865,7 @@ private Server startWorldServer(WorldManagementGrpcService service) throws Excep service, new GrpcPeerIdentityInterceptor(), new AuthTokenInterceptor( - WORLD_JWT_UTIL, - Set.of("world_management.v1.WorldManagementService/Ping")))) + WORLD_JWT_UTIL, Set.of("world_management.v1.WorldManagementService/Ping")))) .build() .start(); } 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 ea2f6eee68..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 @@ -19,6 +19,7 @@ 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; @@ -27,7 +28,6 @@ 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.entitymanagement.v1.CleanupRuntimeInstanceResponse; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; @@ -222,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"); @@ -233,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()); @@ -259,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); } } @@ -317,7 +369,9 @@ void fixtureFailureRequiresExactOwnerAndPersistsTheLockedPredecessorTransition() when(fixtureEvidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) .thenReturn("d".repeat(64)); assertThatThrownBy( - () -> lifecycleService.failPreparedWorldInstance(tenantId, gameInstanceId, 1L, "failed")) + () -> + lifecycleService.failPreparedWorldInstance( + tenantId, gameInstanceId, 1L, "failed")) .isInstanceOf(IllegalArgumentException.class) .hasMessageStartingWith("RUN_OWNED_WORLD_LAUNCH_EVIDENCE_MISMATCH:"); WorldInstance unchanged = @@ -458,8 +512,7 @@ void ordinaryFailureJoinsAndRollsBackWithItsCallerTransaction() { configureOrdinaryLaunchInputs(tenantId); try { var prepared = - lifecycleService.prepareWorldInstance( - request(tenantId, gameInstanceId, operationId())); + lifecycleService.prepareWorldInstance(request(tenantId, gameInstanceId, operationId())); assertThat(prepared.status()).isEqualTo("PREPARING"); TransactionTemplate callerTransaction = new TransactionTemplate(transactionManager); 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 index 2fbed6f387..5f5cd42ab2 100644 --- 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 @@ -1739,7 +1739,8 @@ void realWorldOwnersMaterializeSixFixtureMappingsAndReplayExactCommittedBytes() assertNoPendingManifests(worldId); } - private WorldLifecycleCommandServiceImpl nativeService(RunOwnedCanonicalWorldLaunchEvidence evidence) { + private WorldLifecycleCommandServiceImpl nativeService( + RunOwnedCanonicalWorldLaunchEvidence evidence) { return nativeService(evidence, new AtomicInteger()); } @@ -1869,8 +1870,8 @@ private static Map> allRows(DSLContext connection) { } /** - * 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 + * 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( @@ -2187,10 +2188,9 @@ private static void assertPredecessorLifecycleGuardProbe( 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 = ?", + probe + .fetchSingle( + "SELECT run_owned_fixture_binding_sha256 FROM " + worldTable + " WHERE id = ?", canonicalWorldInstanceId) .get(0, String.class); assertThat(originalBinding).matches("[0-9a-f]{64}"); @@ -2256,7 +2256,8 @@ private static void assertPredecessorLifecycleGuardProbe( assertThat(activated.get(4, Long.class)).isEqualTo(1L); assertSourceOnlyCanonicalColumnsNull(probe, probeTable, valid.key()); assertThat( - probe.fetchSingle( + 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 " @@ -2382,8 +2383,7 @@ private static void assertPredecessorLifecycleGuardProbe( 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(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); @@ -2426,11 +2426,7 @@ private static void assertPredecessorLifecycleGuardProbe( assertSqlState( () -> probe.execute( - "UPDATE " - + probeTable - + " SET " - + activation - + " WHERE probe_key = ?", + "UPDATE " + probeTable + " SET " + activation + " WHERE probe_key = ?", probeCase.key()), "23514", probeCase.expectedDiagnostic()); @@ -2503,7 +2499,8 @@ private static void insertSourceOnlyLifecycleProbeRow( private static void assertSourceOnlyCanonicalColumnsNull( DSLContext probe, String probeTable, int key) { assertThat( - probe.fetchSingle( + 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, " 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 index dcf7712d55..98b4c8a95a 100644 --- 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 @@ -295,7 +295,8 @@ public static RunOwnedCanonicalWorldLaunchEvidence create() { } /** A fresh response correlation with identical allocation and original immutable policy bytes. */ - public static RunOwnedCanonicalWorldLaunchEvidence freshObservation(RunOwnedCanonicalWorldLaunchEvidence original) { + public static RunOwnedCanonicalWorldLaunchEvidence freshObservation( + RunOwnedCanonicalWorldLaunchEvidence original) { var gs = original.gameSessionAssociation(); var freshRequest = new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest( @@ -335,7 +336,8 @@ public static RunOwnedCanonicalWorldLaunchEvidence changedReceiptBytes( } /** Controlled contradictory GS owner allocation, for the actual retained-owner conflict guard. */ - public static RunOwnedCanonicalWorldLaunchEvidence secondAssignment(RunOwnedCanonicalWorldLaunchEvidence original) { + public static RunOwnedCanonicalWorldLaunchEvidence secondAssignment( + RunOwnedCanonicalWorldLaunchEvidence original) { var gs = original.gameSessionAssociation(); long otherInstance = gs.gameInstanceId() == Long.MAX_VALUE ? 1L : gs.gameInstanceId() + 1L; var changed = @@ -356,7 +358,8 @@ public static RunOwnedCanonicalWorldLaunchEvidence secondAssignment(RunOwnedCano return copy(original, original.sourceReceiptBytes(), changed); } - public static PreparedWorldInstanceRequest request(RunOwnedCanonicalWorldLaunchEvidence evidence) { + public static PreparedWorldInstanceRequest request( + RunOwnedCanonicalWorldLaunchEvidence evidence) { var gs = evidence.gameSessionAssociation(); var descriptor = evidence.launchDescriptor(); return new PreparedWorldInstanceRequest( 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 index 02bc94a803..59b0fe929e 100644 --- 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 @@ -6,9 +6,9 @@ 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.RunOwnedWorldFixtureEvidenceTestFixtures; 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; 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 index bf06b735b2..1a6c03c406 100644 --- 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 @@ -32,9 +32,10 @@ import org.testcontainers.junit.jupiter.Testcontainers; /** - * Exercises V1042.6's two forward owner-guard repairs against native PostgreSQL. The malformed - * terminal tuples and APPLIED location operations run only through test-local predicate probes; - * they do not create production owner rows or claim Account-authorized admission. + * Exercises V1042.6's two forward owner-guard repairs at the V1042.7 migration frontier against + * native PostgreSQL. The malformed terminal tuples and APPLIED location operations run only + * through test-local predicate probes; they do not create production owner rows or claim + * Account-authorized admission. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -90,10 +91,15 @@ void defaultInstallAndForwardUpgradeEnforceCompleteBindingAndSameOperationPlacem List productionRowsBefore = productionLocationRows(upgradeDsl, upgradeSchema); assertThat(productionRowsBefore).isEmpty(); - // Targetless migrate is the normal forward path from the installed V1042.5 frontier. - Flyway current = flyway(upgradeSource, upgradeSchema, null, worldLocation, sagaLocation); - current.migrate(); - current.validate(); + 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); @@ -117,11 +123,24 @@ void defaultInstallAndForwardUpgradeEnforceCompleteBindingAndSameOperationPlacem upgradeSource, upgradeSchema, after.functionSource(), false, false); assertThat(productionLocationRows(upgradeDsl, upgradeSchema)).isEqualTo(productionRowsBefore); + String repairedTerminalHistory = migrationHistory(upgradeDsl, "1042.6"); + Flyway current = flyway(upgradeSource, upgradeSchema, null, worldLocation, sagaLocation); + current.migrate(); + current.validate(); + assertThat(latestVersion(upgradeDsl)).isEqualTo("1042.7"); + assertThat(migrationHistory(upgradeDsl, "1042.6")).isEqualTo(repairedTerminalHistory); + 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); + // 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(latestVersion(freshDsl)).isEqualTo("1042.6"); + assertThat(latestVersion(freshDsl)).isEqualTo("1042.7"); assertThat(constraintDefinition(freshDsl, freshSchema)).contains("IS TRUE"); assertThat( normalizeFunctionSource( 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 index 45a74bf9c4..58d20d35da 100644 --- 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 @@ -71,7 +71,8 @@ class RunOwnedCanonicalWorldLaunchEvidenceProviderTest { @Test void retainedCarrierRequiresOriginalFixedPeerAndLeafForEveryOwnerOperation() { - RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); assertThatThrownBy(() -> withControlledPeer(null, null, evidence::requireFixedGameSessionPeer)) .isInstanceOf(SecurityException.class); assertThatThrownBy( @@ -362,7 +363,8 @@ void fixtureOwnerReadFailureIsContentFreeAndLogsTheReadStage(CapturedOutput outp try (PeerContext ignored = fixture.attachGameSessionPeer()) { assertThatThrownBy(provider::requireAuthenticatedEvidence) .isInstanceOf( - RunOwnedCanonicalWorldLaunchEvidenceProvider.InvalidRunOwnedCanonicalWorldLaunchEvidenceException.class) + RunOwnedCanonicalWorldLaunchEvidenceProvider + .InvalidRunOwnedCanonicalWorldLaunchEvidenceException.class) .hasMessage("Run-owned World launch evidence is invalid"); } finally { provider.closeGameSessionFixtureClient(); @@ -430,7 +432,8 @@ void validAlternateFixtureAssociationIsRejectedAtCompareStage(CapturedOutput out try (PeerContext ignored = fixture.attachGameSessionPeer()) { assertThatThrownBy(provider::requireAuthenticatedEvidence) .isInstanceOf( - RunOwnedCanonicalWorldLaunchEvidenceProvider.InvalidRunOwnedCanonicalWorldLaunchEvidenceException.class) + RunOwnedCanonicalWorldLaunchEvidenceProvider + .InvalidRunOwnedCanonicalWorldLaunchEvidenceException.class) .hasMessage("Run-owned World launch evidence is invalid"); } finally { provider.closeGameSessionFixtureClient(); @@ -470,7 +473,8 @@ void fixtureClientInitializationFailureClosesPartialClient(CapturedOutput output try (PeerContext ignored = fixture.attachGameSessionPeer()) { assertThatThrownBy(provider::requireAuthenticatedEvidence) .isInstanceOf( - RunOwnedCanonicalWorldLaunchEvidenceProvider.InvalidRunOwnedCanonicalWorldLaunchEvidenceException.class) + RunOwnedCanonicalWorldLaunchEvidenceProvider + .InvalidRunOwnedCanonicalWorldLaunchEvidenceException.class) .hasMessage("Run-owned World launch evidence is invalid"); } @@ -494,7 +498,8 @@ void fixtureClientMissingConfigurationFailsAtReadStageWithoutCreatingClient(Capt try (PeerContext ignored = fixture.attachGameSessionPeer()) { assertThatThrownBy(provider::requireAuthenticatedEvidence) .isInstanceOf( - RunOwnedCanonicalWorldLaunchEvidenceProvider.InvalidRunOwnedCanonicalWorldLaunchEvidenceException.class) + RunOwnedCanonicalWorldLaunchEvidenceProvider + .InvalidRunOwnedCanonicalWorldLaunchEvidenceException.class) .hasMessage("Run-owned World launch evidence is invalid"); } @@ -524,8 +529,8 @@ void blankWorkloadNamespaceFailsBeforeCreatingFixtureClient() throws Exception { try (PeerContext ignored = fixture.attachGameSessionPeer()) { assertThatThrownBy(provider::requireAuthenticatedEvidence) .isInstanceOf( - RunOwnedCanonicalWorldLaunchEvidenceProvider.InvalidRunOwnedCanonicalWorldLaunchEvidenceException - .class) + RunOwnedCanonicalWorldLaunchEvidenceProvider + .InvalidRunOwnedCanonicalWorldLaunchEvidenceException.class) .hasMessage("Run-owned World launch evidence is invalid"); } @@ -648,7 +653,8 @@ private ProviderFixture providerFixture() throws Exception { return new ProviderFixture(evidence, capability, receipt, pki, tls, endpoints, gameSessionLeaf); } - private static GameDesignClient mockDescriptorReader(RunOwnedCanonicalWorldLaunchEvidence evidence) { + private static GameDesignClient mockDescriptorReader( + RunOwnedCanonicalWorldLaunchEvidence evidence) { GameDesignClient client = mock(GameDesignClient.class); var message = net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec 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 index 06bb2db647..36d6780a62 100644 --- 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 @@ -116,7 +116,8 @@ private static WorldAuthoredSourceIntakeReceipt sourceReceipt( } private static WorldAuthoredVersionIdentityReceipt versionReceipt( - RunOwnedCanonicalWorldLaunchEvidence evidence, WorldAuthoredSourceIntakeReceipt sourceReceipt) { + RunOwnedCanonicalWorldLaunchEvidence evidence, + WorldAuthoredSourceIntakeReceipt sourceReceipt) { var source = sourceReceipt.source(); var snapshot = evidence.sourceReceipt().launchReadEvidence().versionState(); var request = @@ -144,7 +145,8 @@ private static WorldAuthoredVersionIdentityReceipt versionReceipt( stateEvidence); } - private static T withFixturePeer(RunOwnedCanonicalWorldLaunchEvidence evidence, Supplier action) { + private static T withFixturePeer( + RunOwnedCanonicalWorldLaunchEvidence evidence, Supplier action) { GrpcPeerIdentity peer = new GrpcPeerIdentity( "spiffe://firemud/ns/dev/sa/game-session-service", "dev", "game-session-service"); 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 85dfb51c37..8d565c3c38 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 @@ -380,8 +380,7 @@ void fixtureFailureRejectsAmbientTransactionBeforeLoadingOwnerEvidence() { assertTrue(error.getMessage().contains("no ambient transaction")); verify(provider, never()).requireAuthenticatedEvidence(); - verify(worldInstanceRepository, never()) - .findByTenantIdAndGameInstanceIdForUpdate(42L, 101L); + verify(worldInstanceRepository, never()).findByTenantIdAndGameInstanceIdForUpdate(42L, 101L); verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); verify(gameDesignClient, never()).getPublishedReleaseBundle(42L, 11L); verify(entityManagementClient, never()) @@ -536,8 +535,7 @@ void fixtureTerminatedReplayRequiresTheOriginalRequestIdAndDoesNotRepeatEffects( WorldLifecycleCommandServiceImpl fixtureService = fixtureService(provider, lifecycleTransactionOperations); - var terminated = - fixtureService.terminateWorldInstance(42L, 101L, 2L, "term-fixture", "stop"); + 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"); 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 870c6e5137..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 @@ -59,7 +59,8 @@ void clearTransactionState() { @Test void fixtureIntakeRevalidatesPeerAndCallerBeforeAnyOwnerReadOrTransaction() { - RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); WorldAuthoredSourceIntakeService fixtureService = fixtureService(); assertThatThrownBy(() -> withoutPeer(() -> fixtureService.intakeRunOwnedFixture(evidence))) .isInstanceOf(SecurityException.class); @@ -93,7 +94,8 @@ void fixtureIntakeRevalidatesPeerAndCallerBeforeAnyOwnerReadOrTransaction() { @Test void fixtureIntakeReadsControlledSourceBeforeSqlAndIndependentlyReadsExactReceiptAndRetry() { - RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); AuthoredWorldSourceEvidence source = evidence.sourceReceipt().sourceEvidence(); AtomicInteger reads = new AtomicInteger(); AtomicReference committed = new AtomicReference<>(); @@ -162,7 +164,8 @@ void fixtureIntakeReadsControlledSourceBeforeSqlAndIndependentlyReadsExactReceip @Test void fixtureIntakeDeniesChangedRemoteSourceBeforeSql() { - RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + 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)); @@ -180,7 +183,8 @@ void fixtureIntakeDeniesChangedRemoteSourceBeforeSql() { @Test void fixtureIntakeDeniesNullOwnerReceiptBeforeIndependentReadback() { - RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + 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); @@ -204,7 +208,8 @@ void fixtureIntakeDeniesNullOwnerReceiptBeforeIndependentReadback() { @Test void fixtureIntakeDeniesMissingIndependentReceiptAfterOwnerTransaction() { - RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + 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); @@ -225,7 +230,8 @@ void fixtureIntakeDeniesMissingIndependentReceiptAfterOwnerTransaction() { @Test void fixtureIntakeDeniesChangedIndependentReceiptAfterOwnerTransaction() { - RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); var source = evidence.sourceReceipt().sourceEvidence(); AtomicInteger reads = new AtomicInteger(); when(repository.read(eq("dev"), any(UUID.class))) @@ -251,7 +257,8 @@ void fixtureIntakeDeniesChangedIndependentReceiptAfterOwnerTransaction() { @Test void fixtureIntakeDeniesAmbientTransactionBeforeOwnerAccess() { - RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); TransactionSynchronizationManager.setActualTransactionActive(true); assertThatThrownBy( () -> 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 c9bc330d65..831c656b38 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 @@ -81,7 +81,8 @@ void clearTransactionState() { @Test void fixtureVersionRevalidatesPeerAndCallerBeforeAnyOwnerOrRemoteRead() { - RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); var sourceReceipt = sourceReceipt(evidence.sourceReceipt().sourceEvidence()); WorldAuthoredVersionIdentityService fixtureService = fixtureService(); assertThatThrownBy( @@ -125,7 +126,8 @@ void fixtureVersionRevalidatesPeerAndCallerBeforeAnyOwnerOrRemoteRead() { @Test void fixtureVersionConsumesCommittedSourceThenControlledCurrentStateBeforeSqlAndExactRetry() { - RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); var source = evidence.sourceReceipt().sourceEvidence(); var intake = sourceReceipt(source); var canonicalVersion = evidence.gameSessionAssociation().canonicalVersionId(); @@ -247,7 +249,8 @@ void fixtureVersionConsumesCommittedSourceThenControlledCurrentStateBeforeSqlAnd @Test void fixtureVersionRejectsDifferentCommittedSourceBeforeVersionAccessOrSql() { - RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); var source = evidence.sourceReceipt().sourceEvidence(); var intake = sourceReceipt(source); var different = @@ -290,7 +293,8 @@ void fixtureVersionRejectsDifferentCommittedSourceBeforeVersionAccessOrSql() { @Test void fixtureVersionRejectsRemoteStateEpochCanonicalVersionAndRequestSubstitutionBeforeSql() { - RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); var source = evidence.sourceReceipt().sourceEvidence(); var intake = sourceReceipt(source); when(sourceIntakeRepository.readBySource( @@ -351,7 +355,8 @@ void fixtureVersionRejectsRemoteStateEpochCanonicalVersionAndRequestSubstitution @Test void fixtureVersionRejectsChangedRetainedSnapshotOnExactRetryWithoutRemoteOrSql() { - RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); var source = evidence.sourceReceipt().sourceEvidence(); var intake = sourceReceipt(source); var canonicalVersion = evidence.gameSessionAssociation().canonicalVersionId(); @@ -463,7 +468,8 @@ void fixtureVersionRejectsChangedRetainedSnapshotOnExactRetryWithoutRemoteOrSql( @Test void fixtureVersionDeniesMissingOrSubstitutedIndependentVersionReceipt() { - RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); var source = evidence.sourceReceipt().sourceEvidence(); var intake = sourceReceipt(source); var canonicalVersion = evidence.gameSessionAssociation().canonicalVersionId(); @@ -534,7 +540,8 @@ void fixtureVersionDeniesMissingOrSubstitutedIndependentVersionReceipt() { @Test void fixtureVersionDeniesAmbientTransactionBeforeOwnerAccess() { - RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + RunOwnedCanonicalWorldLaunchEvidence evidence = + RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); TransactionSynchronizationManager.setActualTransactionActive(true); assertThatThrownBy( () -> 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 index 5a5720e6fc..f93c2c2444 100644 --- 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 @@ -53,7 +53,8 @@ void runOwnedFixtureUsesDeepValueEqualityAndRetainsDefensiveResponseBytes() { } private static FixtureCase validFixtureCase() { - RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); + 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"); From 959c15df7de2bbf695ac030b58e136941929d0c1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 18:39:13 +1300 Subject: [PATCH 17/45] Record qualified World source-first proof and format guard test --- .../world-runtime-and-movement.md | 6 +++--- ...nalAndLocationOwnerGuardsPostgresIntegrationTest.java | 9 +++++---- 2 files changed, 8 insertions(+), 7 deletions(-) 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 b1e3bec676..652dc930a0 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -8,11 +8,11 @@ This is a non-normative implementation tracker for world runtime and movement. C ### Canonical fixture launch receiving boundary -The current source-first reconstruction separates canonical World evidence and explicit 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. This candidate has not yet executed its combined proof; all historical results below retain their recorded scope. +The current source-first reconstruction separates canonical World evidence and explicit 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. At World candidate `4ae539f3e4538b22891477a90ffd3015f534356f`, the 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. Standalone Game Design run 46074 passed 519 fresh unit and 141 fresh native cases. Generation, static, formatting, link and Markdown checks passed. The cross-service 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. That retained-bootstrap result does not qualify this changed World source/owner candidate or canonical activation, holds, first-`OPEN` or genuine handoffs. +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 rebuilt fresh and restarted the same version, then passed WebSocket and Telnet `WORLDS`/`LOGIN`/`PLAY`/`LOOK` and successful original-capability cleanup. Its packaged scripts also force fixture mode off, so this proves only the ordinary default-off baseline, not the enabled fixture flow or canonical admission/first-`OPEN`. -Forward V1042.7 stages only predecessor `PREPARING→ACTIVE`, `PREPARING→FAILED_PRE_ACTIVATION`, `ACTIVE→TERMINATING` and `TERMINATING→TERMINATED`. Both row versions must have all seventeen canonical/provenance/realm/catalog/allocation fields absent and retain the original valid binding, preparing epoch and identity. Exact Game Session peer/certificate and binding checks precede failure/termination effects; the locked row, unresolved-hold refusal, Entity-cleanup failure retention and local finalization transaction remain required. Ordinary failure retains caller REQUIRED transaction participation. Canonical fixture and Human guards remain closed, and published migration bytes are unchanged. The staging exception must be retired forward after old writers drain and legitimate cleanup settles; it defines no second runtime target. New SQL/owner/JWT/mTLS and rollback proof sources are pending execution. +Forward V1042.7 stages only predecessor `PREPARING→ACTIVE`, `PREPARING→FAILED_PRE_ACTIVATION`, `ACTIVE→TERMINATING` and `TERMINATING→TERMINATED`. Both row versions must have all seventeen canonical/provenance/realm/catalog/allocation fields absent and retain the original valid binding, preparing epoch and identity. Exact Game Session peer/certificate and binding checks precede failure/termination effects; the locked row, unresolved-hold refusal, Entity-cleanup failure retention and local finalization transaction remain required. Ordinary failure retains caller REQUIRED transaction participation. Canonical fixture and Human guards remain closed, and published migration bytes are unchanged. The four predecessor transitions and failure/termination owner boundaries are now physically qualified, 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. The staging exception must be retired forward after old writers drain and legitimate cleanup settles; it defines no second runtime target. Historical qualification before this source-first separation: 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 index 1a6c03c406..4b0d681cdb 100644 --- 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 @@ -33,9 +33,9 @@ /** * Exercises V1042.6's two forward owner-guard repairs at the V1042.7 migration frontier against - * native PostgreSQL. The malformed terminal tuples and APPLIED location operations run only - * through test-local predicate probes; they do not create production owner rows or claim - * Account-authorized admission. + * native PostgreSQL. The malformed terminal tuples and APPLIED location operations run only through + * test-local predicate probes; they do not create production owner rows or claim Account-authorized + * admission. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -131,7 +131,8 @@ void defaultInstallAndForwardUpgradeEnforceCompleteBindingAndSameOperationPlacem assertThat(migrationHistory(upgradeDsl, "1042.6")).isEqualTo(repairedTerminalHistory); assertThat(migrationHistory(upgradeDsl, "1010")).isEqualTo(oldTerminalHistory); assertThat(migrationHistory(upgradeDsl, "1019")).isEqualTo(oldLocationHistory); - assertThat(constraintDefinition(upgradeDsl, upgradeSchema)).isEqualTo(currentTerminalConstraint); + assertThat(constraintDefinition(upgradeDsl, upgradeSchema)) + .isEqualTo(currentTerminalConstraint); LocationFunctionMetadata atCurrentFrontier = locationFunctionMetadata(upgradeDsl, upgradeSchema); assertFunctionMetadataPreserved(after, atCurrentFrontier); From 3ec9bc6c2bf3bec9a18dcf42461447812687fb71 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 20:59:36 +1300 Subject: [PATCH 18/45] Fix World activation replay and terminal affected-unit guards --- .../runtime-and-data.md | 4 +- .../world-creation-workflow.md | 4 +- ...ame-authoring-publishing-and-activation.md | 2 +- .../world-runtime-and-movement.md | 8 +- .../WorldLifecycleCommandServiceImpl.java | 12 +- ...orld_terminal_affected_unit_validation.sql | 45 ++ ...resetResourcesPostgresIntegrationTest.java | 1 + ...ionOwnerGuardsPostgresIntegrationTest.java | 614 +++++++++++++++++- .../WorldLifecycleCommandServiceImplTest.java | 59 ++ 9 files changed, 732 insertions(+), 17 deletions(-) create mode 100644 services/world-management-service/src/main/resources/db/migration/V1042.8__world_terminal_affected_unit_validation.sql 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 68453145ca..458f7b4c57 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -11,7 +11,7 @@ - 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 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. Current owner, socket and PostgreSQL proof is pending; the [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status) records that boundary and the broader lifecycle gaps. +- 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; it does not newly qualify terminal-identity socket or physical PostgreSQL proof, or Temporal retry behavior. The [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status) records these proof boundaries 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. This does not close the terminal request-identity mismatch above or the Temporal lost-response gaps 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. @@ -28,7 +28,7 @@ The owner materializes the exact sealed fixed preset into one region, one zone, 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. 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. These storage checks do not grant Human protection, fixture activation or hold authority. Later fixture World row mutations, lifecycle transitions, hold acquire/finalize, initial placement and player-admission owners reject the fixture variant before effects. 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. +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. Published prior SQL remains unchanged, and this validation grants 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. ### Authored-world source retention 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 7178d13605..ba4b40bca7 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 `INVALID_WORLD_INSTANCE_STATE`, 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. This proof does not newly qualify terminal-identity socket or physical PostgreSQL behavior, 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 default-off run-owned fixture uses the existing synchronous prepare command after the fixed-server World evidence provider validates the immutable receipt, exact Game Session TLS caller, World recipient pins and current Game Design descriptor. World retains the original PREPARING epoch and complete fixture binding digest for exact prepare replay; fixture activation and ACTIVE replay remain unavailable. 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). +The default-off run-owned fixture uses the existing synchronous prepare command after the fixed-server World evidence provider validates the immutable receipt, exact Game Session TLS caller, World recipient pins and current Game Design descriptor. World retains the original PREPARING epoch and complete fixture binding digest for exact prepare replay. Activation and ACTIVE replay for the explicit canonical fixture variant remain closed; activation and ACTIVE replay remain available through the retained predecessor bootstrap. 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: 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 0e4e0a600b..321afef225 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 @@ -16,7 +16,7 @@ The coherent receiving successor for [PR #3196](https://github.com/benhook1013/F 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, but invokes the explicit canonical World owner under controlled peer/certificate context in [RunOwnedFixtureOwnerCompositionCrossServiceTest](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java); that changed candidate has compiled but its combined proof has not yet run. It does not qualify a production canonical World prepare RPC or 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. +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. Fresh cross-service execution `14792` exercised World candidate `4ae539f3e4538b22891477a90ffd3015f534356f` with Game Design source commit `46074cf976759e3fb19cafc0bea7d16e544db555` in [RunOwnedFixtureOwnerCompositionCrossServiceTest](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java); receiving execution `7500` reran that case on World source commit `2807d8b8d76cc8a4f4e86e20d255fcac58bc381e` after redistribution. 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 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 867d16fc4a..85c375e13b 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -8,11 +8,11 @@ This is a non-normative implementation tracker for world runtime and movement. C ### Canonical fixture launch receiving boundary -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 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. Standalone Game Design run 46074 passed 519 fresh unit and 141 fresh native cases. Generation, static, formatting, link, and Markdown checks passed. The cross-service 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 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 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. 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 rebuilt fresh and restarted the same version, then passed WebSocket and Telnet `WORLDS`/`LOGIN`/`PLAY`/`LOOK` and successful original-capability cleanup. Its packaged scripts also force fixture mode off, so this proves only the ordinary default-off baseline, not the enabled fixture flow or canonical admission/first-`OPEN`. -Forward V1042.7 stages only predecessor `PREPARING→ACTIVE`, `PREPARING→FAILED_PRE_ACTIVATION`, `ACTIVE→TERMINATING` and `TERMINATING→TERMINATED`. Both row versions must have all seventeen canonical/provenance/realm/catalog/allocation fields absent and retain the original valid binding, preparing epoch and identity. Exact Game Session peer/certificate and binding checks precede failure/termination effects; the locked row, unresolved-hold refusal, Entity-cleanup failure retention and local finalization transaction remain required. Ordinary failure retains caller REQUIRED transaction participation. Canonical fixture and Human guards remain closed, and published migration bytes are unchanged. The four predecessor transitions and failure/termination owner boundaries are now physically qualified, 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. The staging exception must be retired forward after old writers drain and legitimate cleanup settles; it defines no second runtime target. +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: @@ -81,7 +81,7 @@ 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 source-first correction compares terminal `terminationRequestId`; current proof is pending as recorded above. -- `GR-2.1` / `SF-2.3`: The source-first termination correction rejects a differing terminal `terminationRequestId` before returning the retained snapshot. Its focused owner/socket and physical PostgreSQL proof sources await current execution; exact replay claims remain limited to that retained request identity. See [World Management Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status). +- `GR-2.1` / `SF-2.3`: The source-first termination correction rejects a differing terminal `terminationRequestId` before returning the retained snapshot. Existing `WorldLifecycleCommandServiceImplTest` unit cases cover matching retained `TERMINATED` replay and mismatched-ID rejection. Separately, the controlled predecessor owner and PostgreSQL proof qualifies cleanup-failure retention, rollback, and local finalization. Terminal-identity socket or physical PostgreSQL proof and Temporal retry proof have not newly qualified; exact replay claims remain limited to that retained request identity. Forward V1042.8 terminal affected-unit validation is prepared, with focused SQL proof pending; see the [World runtime and data owner](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status) 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). @@ -92,7 +92,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 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. 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); [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); [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.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); [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/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. | 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 f0be244316..128eb5d956 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 @@ -754,8 +754,18 @@ public WorldInstanceLifecycleSnapshotDto activatePreparedWorldInstance( requireLifecycleEpoch(worldInstance, expectedLifecycleEpoch); } else { 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_ACTIVE.equals(worldInstance.getStatus())) return snapshot(worldInstance); } if (!STATUS_PREPARING.equals(worldInstance.getStatus())) { throw new IllegalArgumentException( 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/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 index 5f5cd42ab2..99e1e2d355 100644 --- 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 @@ -2641,6 +2641,7 @@ private static List remainingVersions() { versions.add("1042.5"); versions.add("1042.6"); versions.add("1042.7"); + versions.add("1042.8"); return List.copyOf(versions); } 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 index 4b0d681cdb..bb3dd65832 100644 --- 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 @@ -14,6 +14,7 @@ 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; @@ -32,10 +33,9 @@ import org.testcontainers.junit.jupiter.Testcontainers; /** - * Exercises V1042.6's two forward owner-guard repairs at the V1042.7 migration frontier against - * native PostgreSQL. The malformed terminal tuples and APPLIED location operations run only through - * test-local predicate probes; they do not create production owner rows or claim Account-authorized - * admission. + * Exercises the V1042.6 and V1042.8 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") @@ -44,13 +44,15 @@ class WorldTerminalAndLocationOwnerGuardsPostgresIntegrationTest { 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"; @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); @Test - void defaultInstallAndForwardUpgradeEnforceCompleteBindingAndSameOperationPlacement() + void defaultInstallAndForwardUpgradeEnforceTerminalUnitsAndOwnerGuards() throws Exception { Path root = repositoryRoot(); String worldLocation = worldMigrations(root); @@ -124,11 +126,30 @@ void defaultInstallAndForwardUpgradeEnforceCompleteBindingAndSameOperationPlacem 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 current = flyway(upgradeSource, upgradeSchema, null, worldLocation, sagaLocation); current.migrate(); current.validate(); - assertThat(latestVersion(upgradeDsl)).isEqualTo("1042.7"); + 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)) @@ -136,17 +157,29 @@ void defaultInstallAndForwardUpgradeEnforceCompleteBindingAndSameOperationPlacem 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(latestVersion(freshDsl)).isEqualTo("1042.7"); + 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(); } finally { dropSchema(upgradeSource, upgradeSchema); @@ -216,6 +249,489 @@ private static void assertTerminalProbeOutcome( } } + 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, + versionId, + "missing epoch", + false, + ""); + assertInvalidTerminalEpoch( + connection, + targetNamespace, + tenantId, + versionId, + localTenantKey, + localVersionKey, + requestId, + commitId, + aggregateId, + versionId, + "null epoch", + true, + "null"); + assertInvalidTerminalEpoch( + connection, + targetNamespace, + tenantId, + versionId, + localTenantKey, + localVersionKey, + requestId, + commitId, + aggregateId, + versionId, + "malformed string epoch", + true, + "\"not-a-counter\""); + assertInvalidTerminalEpoch( + connection, + targetNamespace, + tenantId, + versionId, + localTenantKey, + localVersionKey, + requestId, + commitId, + aggregateId, + versionId, + "fractional epoch", + true, + "4.4"); + assertInvalidTerminalEpoch( + connection, + targetNamespace, + tenantId, + versionId, + localTenantKey, + localVersionKey, + requestId, + commitId, + aggregateId, + versionId, + "negative epoch", + true, + "-1"); + assertInvalidTerminalEpoch( + connection, + targetNamespace, + tenantId, + versionId, + localTenantKey, + localVersionKey, + requestId, + commitId, + aggregateId, + versionId, + "out-of-range epoch", + true, + "9223372036854775808"); + assertInvalidTerminalEpoch( + connection, + targetNamespace, + tenantId, + versionId, + localTenantKey, + localVersionKey, + requestId, + commitId, + aggregateId, + versionId, + "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 { @@ -402,6 +918,42 @@ private static LocationFunctionMetadata locationFunctionMetadata(DSLContext dsl, row.get("public_execute_grants", Long.class) > 0); } + 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()); @@ -422,6 +974,26 @@ private static void assertFunctionMetadataPreserved( 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); @@ -450,6 +1022,14 @@ private static List productionLocationRows(DSLContext dsl, String schema .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 " @@ -512,6 +1092,10 @@ private static String normalizeFunctionSource(String source, String schema) { "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; @@ -704,4 +1288,20 @@ private record LocationFunctionMetadata( 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) {} } 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 8d565c3c38..3508268535 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 @@ -285,6 +285,65 @@ 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}) { + assertThrows( + IllegalArgumentException.class, + () -> service.activatePreparedWorldInstance(42L, 101L, expectedEpoch)); + } + + instance.setLifecycleEpoch(Long.MIN_VALUE); + assertThrows( + IllegalArgumentException.class, + () -> service.activatePreparedWorldInstance(42L, 101L, Long.MAX_VALUE)); + + 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(); From 7c33684ac8666356fc444f2293ab2afa60a62a6f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 21:05:44 +1300 Subject: [PATCH 19/45] Correct terminal guard probe helper calls and formatting --- ...ionOwnerGuardsPostgresIntegrationTest.java | 43 ++++++++----------- 1 file changed, 19 insertions(+), 24 deletions(-) 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 index bb3dd65832..d595e9ce98 100644 --- 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 @@ -52,8 +52,7 @@ class WorldTerminalAndLocationOwnerGuardsPostgresIntegrationTest { new PostgreSQLContainer<>(TestContainerImages.postgres()); @Test - void defaultInstallAndForwardUpgradeEnforceTerminalUnitsAndOwnerGuards() - throws Exception { + void defaultInstallAndForwardUpgradeEnforceTerminalUnitsAndOwnerGuards() throws Exception { Path root = repositoryRoot(); String worldLocation = worldMigrations(root); String sagaLocation = sagaMigrations(root); @@ -137,8 +136,7 @@ void defaultInstallAndForwardUpgradeEnforceTerminalUnitsAndOwnerGuards() through10427.validate(); assertThat(latestVersion(upgradeDsl)).isEqualTo("1042.7"); String predecessorHistory = migrationHistory(upgradeDsl, "1042.7"); - TerminalFunctionMetadata terminalBefore = - terminalFunctionMetadata(upgradeDsl, upgradeSchema); + TerminalFunctionMetadata terminalBefore = terminalFunctionMetadata(upgradeDsl, upgradeSchema); assertThat(terminalBefore.publicExecuteGrant()).isFalse(); assertThat(terminalBefore.securityDefiner()).isTrue(); List terminalRowsBefore = productionTerminalRows(upgradeDsl, upgradeSchema); @@ -157,12 +155,12 @@ void defaultInstallAndForwardUpgradeEnforceTerminalUnitsAndOwnerGuards() LocationFunctionMetadata atCurrentFrontier = locationFunctionMetadata(upgradeDsl, upgradeSchema); assertFunctionMetadataPreserved(after, atCurrentFrontier); - TerminalFunctionMetadata terminalAfter = - terminalFunctionMetadata(upgradeDsl, upgradeSchema); + TerminalFunctionMetadata terminalAfter = terminalFunctionMetadata(upgradeDsl, upgradeSchema); assertTerminalFunctionMetadataPreserved(terminalBefore, terminalAfter); List terminalRowsAfter = productionTerminalRows(upgradeDsl, upgradeSchema); assertThat(terminalRowsAfter).isEqualTo(terminalRowsBefore); - exerciseTerminalAffectedUnitProbe(upgradeSource, upgradeSchema, terminalAfter.functionSource()); + 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); @@ -311,13 +309,7 @@ private static void exerciseTerminalAffectedUnitProbe( owner.executeUpdate(); } insertTerminalProbeIdentity( - connection, - targetNamespace, - tenantId, - versionId, - aggregateId, - aggregateKey, - 4L); + connection, targetNamespace, tenantId, versionId, aggregateId, aggregateKey, 4L); insertTerminalProbeIdentity( connection, targetNamespace, @@ -451,7 +443,8 @@ private static void exerciseTerminalAffectedUnitProbe( commitId, "missing scope type", "[" - + terminalUnitJson(aggregateId, scopeId, true, "\"WORLD_MANAGEMENT\"", false, "", true, "0") + + terminalUnitJson( + aggregateId, scopeId, true, "\"WORLD_MANAGEMENT\"", false, "", true, "0") + "]"); assertTerminalAffectedUnitRejected( connection, @@ -464,7 +457,8 @@ private static void exerciseTerminalAffectedUnitProbe( commitId, "null scope type", "[" - + terminalUnitJson(aggregateId, scopeId, true, "\"WORLD_MANAGEMENT\"", true, "null", true, "0") + + terminalUnitJson( + aggregateId, scopeId, true, "\"WORLD_MANAGEMENT\"", true, "null", true, "0") + "]"); assertTerminalAffectedUnitRejected( connection, @@ -477,7 +471,15 @@ private static void exerciseTerminalAffectedUnitProbe( commitId, "unknown scope type", "[" - + terminalUnitJson(aggregateId, scopeId, true, "\"WORLD_MANAGEMENT\"", true, "\"UNKNOWN\"", true, "0") + + terminalUnitJson( + aggregateId, + scopeId, + true, + "\"WORLD_MANAGEMENT\"", + true, + "\"UNKNOWN\"", + true, + "0") + "]"); assertInvalidTerminalEpoch( @@ -490,7 +492,6 @@ private static void exerciseTerminalAffectedUnitProbe( requestId, commitId, aggregateId, - versionId, "missing epoch", false, ""); @@ -504,7 +505,6 @@ private static void exerciseTerminalAffectedUnitProbe( requestId, commitId, aggregateId, - versionId, "null epoch", true, "null"); @@ -518,7 +518,6 @@ private static void exerciseTerminalAffectedUnitProbe( requestId, commitId, aggregateId, - versionId, "malformed string epoch", true, "\"not-a-counter\""); @@ -532,7 +531,6 @@ private static void exerciseTerminalAffectedUnitProbe( requestId, commitId, aggregateId, - versionId, "fractional epoch", true, "4.4"); @@ -546,7 +544,6 @@ private static void exerciseTerminalAffectedUnitProbe( requestId, commitId, aggregateId, - versionId, "negative epoch", true, "-1"); @@ -560,7 +557,6 @@ private static void exerciseTerminalAffectedUnitProbe( requestId, commitId, aggregateId, - versionId, "out-of-range epoch", true, "9223372036854775808"); @@ -574,7 +570,6 @@ private static void exerciseTerminalAffectedUnitProbe( requestId, commitId, aggregateId, - versionId, "noncanonical decimal string epoch", true, "\"04\""); From e9b5956e842919c0908d6877443baf9b108145e2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 21:15:13 +1300 Subject: [PATCH 20/45] Record qualified World review fixes and rebuilt runtime proof --- .../implementation-tracking/world-runtime-and-movement.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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 85c375e13b..405fb44b8a 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,9 @@ This is a non-normative implementation tracker for world runtime and movement. C ### Canonical fixture launch receiving boundary -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 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. 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 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 rebuilt fresh and restarted the same version, then passed WebSocket and Telnet `WORLDS`/`LOGIN`/`PLAY`/`LOOK` and successful original-capability cleanup. Its packaged scripts also force fixture mode off, so this proves only the ordinary default-off baseline, not the enabled fixture flow or canonical admission/first-`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. @@ -81,7 +81,7 @@ 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 source-first correction compares terminal `terminationRequestId`; current proof is pending as recorded above. -- `GR-2.1` / `SF-2.3`: The source-first termination correction rejects a differing terminal `terminationRequestId` before returning the retained snapshot. Existing `WorldLifecycleCommandServiceImplTest` unit cases cover matching retained `TERMINATED` replay and mismatched-ID rejection. Separately, the controlled predecessor owner and PostgreSQL proof qualifies cleanup-failure retention, rollback, and local finalization. Terminal-identity socket or physical PostgreSQL proof and Temporal retry proof have not newly qualified; exact replay claims remain limited to that retained request identity. Forward V1042.8 terminal affected-unit validation is prepared, with focused SQL proof pending; see the [World runtime and data owner](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status) 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.3`: The source-first termination correction rejects a differing terminal `terminationRequestId` before returning the retained snapshot. Existing `WorldLifecycleCommandServiceImplTest` unit cases cover ordinary activation at the original and same epoch, matching retained `TERMINATED` replay, and mismatched-ID rejection. Separately, the controlled predecessor owner and PostgreSQL proof qualifies cleanup-failure retention, rollback, and local finalization. Terminal-identity socket or physical PostgreSQL proof and Temporal retry proof remain unqualified; exact replay claims remain limited to that retained request identity. 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`. This controlled empty-production-row probe does not qualify nonempty canonical terminal retention or Human authority; broader physical PostgreSQL, socket, and Temporal proof remains open. See the [World runtime and data owner](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status) 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). From eb0cc8ea8a12d33a853db0a1e5eb6213e84dd22a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 21:40:03 +1300 Subject: [PATCH 21/45] fix(world): align terminal retry conflict and review proof --- .../runtime-and-data.md | 4 +-- .../world-creation-workflow.md | 4 +-- design/project-management/ai-observations.md | 32 ++++++++++++++----- ...ame-authoring-publishing-and-activation.md | 2 +- .../world-runtime-and-movement.md | 8 ++--- .../WorldLifecycleCommandServiceImpl.java | 2 +- ...orldLaunchEvidenceMtlsIntegrationTest.java | 4 +++ .../WorldLifecycleCommandServiceImplTest.java | 7 +++- ...rldAuthoredVersionIdentityServiceTest.java | 6 ++-- 9 files changed, 47 insertions(+), 22 deletions(-) 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 458f7b4c57..e5ce491ee5 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -12,10 +12,10 @@ - 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 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; it does not newly qualify terminal-identity socket or physical PostgreSQL proof, or Temporal retry behavior. The [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status) records these proof boundaries 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. This does not close the terminal request-identity mismatch above or the Temporal lost-response gaps below. +- 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. +- 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 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 ba4b40bca7..edd568cc23 100644 --- a/design/architecture/microservices/world-management-service/world-creation-workflow.md +++ b/design/architecture/microservices/world-management-service/world-creation-workflow.md @@ -15,7 +15,7 @@ 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` retry now compares `terminationRequestId` before returning: a different request identity fails with `INVALID_WORLD_INSTANCE_STATE`, 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. This proof does not newly qualify terminal-identity socket or physical PostgreSQL behavior, 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 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. This proof does not newly qualify terminal-identity socket or physical PostgreSQL behavior, 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 default-off run-owned fixture uses the existing synchronous prepare command after the fixed-server World evidence provider validates the immutable receipt, exact Game Session TLS caller, World recipient pins and current Game Design descriptor. World retains the original PREPARING epoch and complete fixture binding digest for exact prepare replay. Activation and ACTIVE replay for the explicit canonical fixture variant remain closed; activation and ACTIVE replay remain available through the retained predecessor bootstrap. 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). @@ -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/project-management/ai-observations.md b/design/project-management/ai-observations.md index ae559ca525..0ac1114afe 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -272,13 +272,15 @@ Entry format: - Current status: the test now waits for the database-owned expiry condition; current physical qualification remains required. - `2026-10-14`: Hold asynchronous recovery until failure-state assertions finish - - Context: the TLS certificate watcher callback-failure test signalled its first attempt before the watcher recorded an unhealthy state. A successful retry could restore health before the test observed that state. + - Context: the TLS certificate watcher callback-failure test signalled its first attempt before the watcher recorded an unhealthy state. + - Observation: a successful retry could restore health before the test observed the unhealthy state. - Expected pattern: gate the successful test callback until the existing unhealthy-state and aggregate-health assertions finish, release the gate in `finally`, then verify retry and recovered health. Preserve the production retry policy and every failure/recovery assertion. - Current status: the test-only latch correction passed the full 486-case Common unit suite and static checks. The separate PostgreSQL refusal and cleanup chronology remains unexplained under the existing local PostgreSQL availability observation; later passing proof does not identify that cause. -- 2026-10-14: Use explicit shell failure propagation for dependent proof and publication steps. - - Observation: a multiline Bash execution continued to stage and commit after an auxiliary Python count assertion failed because the shell did not enable `errexit`. The actual gate passed 11 PostgreSQL cases; the failed assertion used a preliminary count of 10. The committed code remained qualified, but the command sequence did not enforce its intended dependency. - - Guidance: use `set -euo pipefail` or separate sequential tool calls when a proof assertion must succeed before staging, committing or publishing. Read actual result counts before pinning them; an overall shell exit code can otherwise hide an earlier failure. +- `2026-10-14`: Use explicit shell failure propagation for dependent proof and publication steps + - Context: a multiline Bash command coupled a Python result-count assertion to later staging and commit commands. + - Observation: the shell continued after the assertion failed because `errexit` was disabled. The actual gate passed 11 PostgreSQL cases, while the failed assertion used a preliminary count of 10. The committed code remained qualified, but the command sequence did not enforce its intended dependency. + - Expected pattern: use `set -euo pipefail` or separate sequential tool calls when a proof assertion must succeed before staging, committing, or publishing. Read actual result counts before pinning them; an overall shell exit code can otherwise hide an earlier failure. - Current status: the [#3211](https://github.com/benhook1013/FireMUD/pull/3211) result was checked against the actual XML, corrected to 11 passing cases, and subsequent dependent commands use explicit failure propagation. - `2026-10-14`: Review-period bookkeeping must not contend for provider execution locks @@ -328,12 +330,26 @@ Entry format: - Observation: the repeated failures support a higher shared local daemon heap for serialized work; the passing run was mostly up-to-date and does not establish cold-build speedup or a total-memory guarantee. - Qualification: the 3 GiB setting is not a restoration of an earlier default; the shared 1500m setting predates the recent guard since August 28. Worker, test, and code-generation JVM memory remains additional, and the hosted module runner's explicit 2500m setting is unchanged. -- 2026-10-15: Two sequential same-candidate Controller `reviews decide reconcile` operations for #3206 (Hosted and CLI) succeeded after a several-minute silent execution. The slow phase is not isolated; a long-running administrative-looking command is difficult to distinguish from a stall without phase/duration output. Reported to Overseer as nonblocking, alongside the terminology friction that queue inspection uses `reviews stack show` rather than `reviews queue`. Consider progress/duration diagnostics or a guarded shared-evidence operation; no timing, admission or review authority was bypassed. +- `2026-10-15`: Distinguish slow reconciliation from a stall + - Context: two sequential same-candidate Controller `reviews decide reconcile` operations for #3206 (Hosted and CLI) succeeded after a several-minute silent execution. + - Observation: the slow phase is not isolated, so a long-running administrative command is difficult to distinguish from a stall without phase or duration output. Queue inspection also uses `reviews stack show` rather than the expected `reviews queue` terminology. + - Expected pattern: consider phase/duration diagnostics or a guarded shared-evidence operation for long reconciliations. + - Current status: reported to Overseer as nonblocking; no timing, admission, or review authority was bypassed. -- 2026-10-15: Gameplay published the #3210 receiving carry after its runtime/source gate passed but before consuming the separate final proof-note-only documentation session, which was still running. The final documentation result therefore remained pending at publication; the PR/job/Overseer report explicitly retain that limit and no READY claim was made. A yielded session is not completion: dependent mutation must be gated on its consumed terminal exit status, even when earlier runtime proof passed. The pending documentation session subsequently passed in 21 seconds, and Gameplay consumed its exit 0 before recording the final documentation proof. The publication-order mistake remains recorded; a later pass does not change that ordering. +- `2026-10-15`: Keep proof completion separate from a coherent CI checkpoint + - Context: Gameplay published the #3210 receiving carry after its runtime/source gate passed while the separate final proof-note-only documentation session was still running. + - Observation: the final documentation result was pending at publication; the PR/job/Overseer report explicitly retained that limit and made no READY claim. The session later passed in 21 seconds, and Gameplay consumed its exit 0 before recording final documentation proof. The publication-order mistake remains recorded; a later pass does not change that ordering. + - Expected pattern: gate dependent mutation and qualification claims on the consumed terminal exit status. A coherent CI checkpoint may be published with an explicit pending-check limitation; distinguish that pending proof state or an inaccurate qualification report from a safety incident. - 2026-10-15: Preflight native Actions response shapes before publishing trusted callbacks. Completed Validation runs `38662647370` (20 modules) and `38651777538` (zero modules) both returned `pull_requests: []` despite canonical PR/base-SHA/head titles; association-required fixtures would have passed locally while disabling reporting. The optional summary now distinguishes title/SHA attribution from a separately pinned current-ref write fence; this is not historical-ref or required-gate provenance proof. Native webhook execution and partial-rerun shape still need hosted qualification. -- 2026-10-15 follow-up to the #3210 pending-documentation report: Overseer clarified that publishing a coherent CI checkpoint with an explicit pending-check limitation is permitted and is not, by itself, a publication-safety violation. Consume results before claiming qualification; distinguish a pending proof state or inaccurate qualification report from a genuine safety incident. Routine proof completion belongs in the next aggregated milestone. +- `2026-10-15`: Clarify reporting for a checkpoint with pending proof + - Context: follow-up to the #3210 pending-documentation report. + - Observation: Root clarified that publishing a coherent CI checkpoint with an explicit pending-check limitation is permitted and is not, by itself, a publication-safety violation. + - Expected pattern: consume results before claiming qualification; distinguish a pending proof state or inaccurate qualification report from a genuine safety incident. Record routine proof completion in the next aggregated milestone. -- 2026-10-15: Review admission can report PR-wide `PARENT_MOVED` after a focused fix even when the live base, effective parent and latest Hosted parent are unchanged: an older CLI checkpoint retains a different parent and its prior reconciliation binds the preceding child head. On #3206, both new channel requests refused before quota use; compact status identified the historical evidence, and exact reconciliation was initiated. Admission diagnostics should identify the offending channel/checkpoint and reconciliation action. Reported to Overseer; this establishes diagnostic friction, not a policy defect. +- `2026-10-15`: Identify the channel checkpoint behind PR-wide parent movement + - Context: after a focused fix on #3206, review admission reported PR-wide `PARENT_MOVED` even though the live base, effective parent, and latest Hosted parent were unchanged. + - Observation: an older CLI checkpoint retained a different parent and its reconciliation bound the preceding child head. Both new channel requests refused before quota use; compact status identified the historical evidence and exact reconciliation was initiated. + - Expected pattern: admission diagnostics should identify the offending channel/checkpoint and the required reconciliation action. + - Current status: reported to Overseer; this establishes diagnostic friction, not a policy defect. 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 321afef225..e1c73fa752 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,7 +12,7 @@ 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. -### Fixed fixture source and Version reads +### 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). 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 405fb44b8a..7426b93593 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -80,8 +80,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 source-first correction compares terminal `terminationRequestId`; current proof is pending as recorded above. -- `GR-2.1` / `SF-2.3`: The source-first termination correction rejects a differing terminal `terminationRequestId` before returning the retained snapshot. Existing `WorldLifecycleCommandServiceImplTest` unit cases cover ordinary activation at the original and same epoch, matching retained `TERMINATED` replay, and mismatched-ID rejection. Separately, the controlled predecessor owner and PostgreSQL proof qualifies cleanup-failure retention, rollback, and local finalization. Terminal-identity socket or physical PostgreSQL proof and Temporal retry proof remain unqualified; exact replay claims remain limited to that retained request identity. 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`. This controlled empty-production-row probe does not qualify nonempty canonical terminal retention or Human authority; broader physical PostgreSQL, socket, and Temporal proof remains open. See the [World runtime and data owner](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status) and [V1042.8 migration](../../../services/world-management-service/src/main/resources/db/migration/V1042.8__world_terminal_affected_unit_validation.sql). +- `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; live PostgreSQL rollback/crash/concurrency proof is not claimed. The source-first correction compares terminal `terminationRequestId`; terminal-identity socket and physical PostgreSQL proof, 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`: The source-first termination correction rejects a differing terminal `terminationRequestId` before returning the retained snapshot. 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, the controlled predecessor owner and PostgreSQL proof qualifies cleanup-failure retention, rollback, and local finalization. Terminal-identity socket or physical PostgreSQL proof and Temporal retry proof remain unqualified; exact replay claims remain limited to that retained request identity. 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`. This controlled empty-production-row probe does not qualify nonempty canonical terminal retention or Human authority; broader physical PostgreSQL, socket, and Temporal proof remains open. See the [World runtime and data owner](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status) 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). @@ -149,7 +149,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 @@ -181,7 +181,7 @@ 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. 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. 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 128eb5d956..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 @@ -1120,7 +1120,7 @@ private WorldInstance beginOrResumeTermination( if (STATUS_TERMINATED.equals(worldInstance.getStatus())) { if (!terminationRequestId.equals(worldInstance.getTerminationRequestId())) { throw new IllegalArgumentException( - "INVALID_WORLD_INSTANCE_STATE: world instance terminated under a different request id"); + "IDEMPOTENCY_CONFLICT: world instance terminated under a different request id"); } return worldInstance; } 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 f182a90702..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 @@ -319,6 +319,7 @@ public void terminateWorldInstance( .build()); SessionContext.clear(); assertThat(playerContextFailure.hasError()).isTrue(); + assertThat(playerContextFailure.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); assertThat(worldSaves).hasValue(writesAfterPrepare); assertThat(descriptorReads).hasValue(readsAfterPrepare); @@ -402,6 +403,7 @@ public void terminateWorldInstance( .build()); SessionContext.clear(); assertThat(ordinaryCaller.hasError()).isTrue(); + assertThat(ordinaryCaller.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); assertThat(worldSaves).hasValue(writesAfterActivation); assertThat(descriptorReads).hasValue(4); @@ -664,8 +666,10 @@ public void terminateWorldInstance( 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(); 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 3508268535..85d732e23d 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 @@ -605,12 +605,17 @@ void fixtureTerminatedReplayRequiresTheOriginalRequestIdAndDoesNotRepeatEffects( 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().contains("terminated under a different request id")); + 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)); 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 831c656b38..f9a71013a2 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 @@ -436,7 +436,7 @@ void fixtureVersionRejectsChangedRetainedSnapshotOnExactRetryWithoutRemoteOrSql( verify(versionStateClient, times(1)).read(any()); assertThat(transactionManager.transactionStarts).isEqualTo(transactionStartsAfterAcceptance); - for (VersionLifecycleState changedState : + for (VersionLifecycleState retainedState : List.of( VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED)) { @@ -445,9 +445,9 @@ void fixtureVersionRejectsChangedRetainedSnapshotOnExactRetryWithoutRemoteOrSql( originalState.get().request(), source, canonicalVersion, - changedState, + retainedState, evidence.sourceReceipt().launchReadEvidence().versionState().getVersionStateEpoch() - + (changedState == VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED + + (retainedState == VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED ? 1L : 0L)); retained.set(identityReceipt(intake, changed, 101L)); From 0126e6139a344b8ac4c81b4b9ae73f0f9ac0c52d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 21:47:36 +1300 Subject: [PATCH 22/45] docs(world): distinguish predecessor and canonical preparation --- .../world-management-service/world-creation-workflow.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 edd568cc23..7442d8560c 100644 --- a/design/architecture/microservices/world-management-service/world-creation-workflow.md +++ b/design/architecture/microservices/world-management-service/world-creation-workflow.md @@ -17,7 +17,7 @@ The cross-platform workflow placement and adopter-proof requirements are owned b 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. This proof does not newly qualify terminal-identity socket or physical PostgreSQL behavior, 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 default-off run-owned fixture uses the existing synchronous prepare command after the fixed-server World evidence provider validates the immutable receipt, exact Game Session TLS caller, World recipient pins and current Game Design descriptor. World retains the original PREPARING epoch and complete fixture binding digest for exact prepare replay. Activation and ACTIVE replay for the explicit canonical fixture variant remain closed; activation and ACTIVE replay remain available through the retained predecessor bootstrap. 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). +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: From 73ae3f03eb9741bbea760485355d6d7d3b07ac9c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 22:59:21 +1300 Subject: [PATCH 23/45] Fix canonical World client shutdown and savepoint transaction guards --- design/project-management/ai-observations.md | 2 +- ...dCanonicalWorldLaunchEvidenceProvider.java | 5 + ...same_transaction_guard_subtransactions.sql | 70 +++ ...SubtransactionPostgresIntegrationTest.java | 444 ++++++++++++++++++ ...resetResourcesPostgresIntegrationTest.java | 406 +++++++++++++++- ...onicalWorldLaunchEvidenceProviderTest.java | 64 +++ 6 files changed, 982 insertions(+), 9 deletions(-) create mode 100644 services/world-management-service/src/main/resources/db/migration/V1042.9__world_same_transaction_guard_subtransactions.sql create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldSameTransactionGuardSubtransactionPostgresIntegrationTest.java diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 0ac1114afe..10aabea299 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -338,7 +338,7 @@ Entry format: - `2026-10-15`: Keep proof completion separate from a coherent CI checkpoint - Context: Gameplay published the #3210 receiving carry after its runtime/source gate passed while the separate final proof-note-only documentation session was still running. - - Observation: the final documentation result was pending at publication; the PR/job/Overseer report explicitly retained that limit and made no READY claim. The session later passed in 21 seconds, and Gameplay consumed its exit 0 before recording final documentation proof. The publication-order mistake remains recorded; a later pass does not change that ordering. + - Observation: the final documentation result was pending at publication; the PR/job/Overseer report explicitly retained that limit and made no READY claim. The session later passed in 21 seconds, and Gameplay consumed its exit 0 before recording final documentation proof. Root subsequently corrected the initial characterization: publishing a coherent checkpoint with the pending-check limit was permitted and was not a publication-safety violation. The later pass does not change the proof state at publication. - Expected pattern: gate dependent mutation and qualification claims on the consumed terminal exit status. A coherent CI checkpoint may be published with an explicit pending-check limitation; distinguish that pending proof state or an inaccurate qualification report from a safety incident. - 2026-10-15: Preflight native Actions response shapes before publishing trusted callbacks. Completed Validation runs `38662647370` (20 modules) and `38651777538` (zero modules) both returned `pull_requests: []` despite canonical PR/base-SHA/head titles; association-required fixtures would have passed locally while disabling reporting. The optional summary now distinguishes title/SHA attribution from a separately pinned current-ref write fence; this is not historical-ref or required-gate provenance proof. Native webhook execution and partial-rerun shape still need hosted qualification. 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 index 69f9aee50c..df5fff9437 100644 --- 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 @@ -72,6 +72,7 @@ public final class RunOwnedCanonicalWorldLaunchEvidenceProvider { private final GameSessionFixtureClientFactory gameSessionFixtureClientFactory; private final String workloadNamespace; private volatile CanonicalGameInstanceLaunchAssociationClient gameSessionFixtureClient; + private boolean closed; @Autowired public RunOwnedCanonicalWorldLaunchEvidenceProvider( @@ -245,6 +246,9 @@ private static UUID freshFixtureReadRequestId(UUID fixtureOperationId) { } private synchronized CanonicalGameInstanceLaunchAssociationClient gameSessionFixtureClient() { + if (closed) { + throw invalidEvidence(); + } if (gameSessionFixtureClient != null) { return gameSessionFixtureClient; } @@ -272,6 +276,7 @@ private synchronized CanonicalGameInstanceLaunchAssociationClient gameSessionFix @PreDestroy public synchronized void closeGameSessionFixtureClient() { + closed = true; CanonicalGameInstanceLaunchAssociationClient current = gameSessionFixtureClient; gameSessionFixtureClient = null; if (current != null) { 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/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..37599912ec --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldSameTransactionGuardSubtransactionPostgresIntegrationTest.java @@ -0,0 +1,444 @@ +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.fetchOne( + "SELECT count(*) FROM world_design_publication_account_binding WHERE publication_fence = ?", + publicationFence) + .get(0, Long.class)) + .isEqualTo(1L); + assertThat( + dsl.fetchOne( + "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.fetchOne( + "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.fetchOne( + "SELECT count(*) FROM world_design_publication_fence_attempt WHERE publication_fence = ?", + publicationFence) + .get(0, Long.class)) + .isEqualTo(1L); + assertThat( + dsl.fetchOne( + "SELECT count(*) FROM world_design_publication_account_binding WHERE publication_fence = ?", + publicationFence) + .get(0, Long.class)) + .isZero(); + assertThat( + dsl.fetchOne( + "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 index 99e1e2d355..09120f8cff 100644 --- 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 @@ -36,6 +36,7 @@ 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; @@ -713,6 +714,98 @@ void actualOwnerRollbackLeavesNoAllocationTopologyResultOrManifest() { // 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())); + assertThat( + scalarText( + "SELECT p.xmin::text FROM world_canonical_instance_preparation p " + + "WHERE p.world_instance_id = ?", + allocatedFixture.worldInstanceId())) + .isNotEqualTo( + scalarText("SELECT (txid_current() % 4294967296)::text")); + 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 { @@ -967,7 +1060,7 @@ void installed34ThroughParent40ToDefaultFrontierRetainsRowsXminAndStableLegacyUp .isEqualTo(originalRows.get(entry.getKey())); // Create and materialize a controlled schema-3 fixture through the existing World owners at - // the V1041 checkpoint, then prove V1042 retains every stored row image and xmin. + // the V1041 checkpoint, then preserve that real fixture while advancing to V1042.8. var fixtureAssociations = new WorldCanonicalInstanceAssociationRepository( connection, @@ -1026,9 +1119,145 @@ void installed34ThroughParent40ToDefaultFrontierRetainsRowsXminAndStableLegacyUp .get(0, Long.class)) .isEqualTo(1L); - var retainedRowsAtV1042 = new LinkedHashMap<>(allRows(connection)); - retainedRowsAtV1042.remove(HISTORY); - var historyAtV1042 = history(connection); + 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()")) + 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")) + 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( @@ -1049,21 +1278,152 @@ void installed34ThroughParent40ToDefaultFrontierRetainsRowsXminAndStableLegacyUp assertThat(versions(connection).subList(40, resolvedVersionedCount)) .containsExactlyElementsOf(remainingVersions()); assertThat(history(connection).subList(0, 40)).isEqualTo(parentHistory); - assertThat(history(connection).subList(0, 75)).isEqualTo(historyAtV1042); + 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()); 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 retainedRowsAtDefaultFrontier = new LinkedHashMap<>(allRows(connection)); + var retainedRowsAtDefaultFrontier = + new LinkedHashMap<>(allRowsWithoutNewAttemptStamp(connection)); retainedRowsAtDefaultFrontier.remove(HISTORY); assertThat(retainedRowsAtDefaultFrontier) - .as("all retained row values and xmin from V1042 through the default frontier") - .isEqualTo(retainedRowsAtV1042); + .as("all retained row values and xmin from V1042.8 through the V1042.9 repair") + .isEqualTo(retainedRowsAt10428); 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 " @@ -1869,6 +2229,35 @@ private static Map> allRows(DSLContext connection) { return rows; } + private static Map> allRowsWithoutNewAttemptStamp(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 = + table.equals("world_design_publication_fence_attempt") + ? "(to_jsonb(retained) - 'attempt_inserted_full_xid')" + : "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 @@ -2642,6 +3031,7 @@ private static List remainingVersions() { versions.add("1042.6"); versions.add("1042.7"); versions.add("1042.8"); + versions.add("1042.9"); return List.copyOf(versions); } 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 index 58d20d35da..af184c8bdd 100644 --- 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 @@ -7,6 +7,7 @@ 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; @@ -566,6 +567,69 @@ void configuredWorkloadNamespaceIsPassedToFixtureClientFactory() throws Exceptio 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") From a064f183adb8041049ada77722a4c4f78053a542 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 23:02:37 +1300 Subject: [PATCH 24/45] Correct World retained-row fixture snapshot reference --- ...SubtransactionPostgresIntegrationTest.java | 16 ++++++-------- ...resetResourcesPostgresIntegrationTest.java | 22 ++++++++----------- ...onicalWorldLaunchEvidenceProviderTest.java | 7 +----- 3 files changed, 17 insertions(+), 28 deletions(-) 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 index 37599912ec..4b2895cdcc 100644 --- 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 @@ -128,7 +128,8 @@ void childSubtransactionAttemptAcceptsTopLevelAccountBindingAndInventory() { UUID accountOperationId = UUID.randomUUID(); UUID accountFenceId = UUID.randomUUID(); - byte[] accountBytes = "controlled account binding".getBytes(StandardCharsets.UTF_8); + 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, " @@ -139,7 +140,8 @@ void childSubtransactionAttemptAcceptsTopLevelAccountBindingAndInventory() { accountBytes, "sha256:" + sha256(accountBytes)); - byte[] inventoryBytes = "controlled selected inventory".getBytes(StandardCharsets.UTF_8); + 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, " @@ -353,8 +355,7 @@ private WorldAuthoredSourceIntakeReceipt intake(UUID tenantId, String worldSlug) "NEW_GAME_ROW", evidenceDigest); return ownerTransaction() - .execute( - status -> intakeRepository.acceptFresh(NAMESPACE, UUID.randomUUID(), source)); + .execute(status -> intakeRepository.acceptFresh(NAMESPACE, UUID.randomUUID(), source)); } private WorldAuthoredVersionIdentityReceipt identity( @@ -379,8 +380,7 @@ private WorldAuthoredVersionIdentityReceipt identity( 1L); return ownerTransaction() .execute( - status -> - new WorldAuthoredVersionIdentityRepository(dsl).acceptFresh(receipt, state)); + status -> new WorldAuthoredVersionIdentityRepository(dsl).acceptFresh(receipt, state)); } private static WorldDesignPublicationFenceEvidence evidence( @@ -419,9 +419,7 @@ private TransactionTemplate ownerTransaction() { } private static void assertSqlState( - org.assertj.core.api.ThrowableAssert.ThrowingCallable action, - String state, - String message) { + org.assertj.core.api.ThrowableAssert.ThrowingCallable action, String state, String message) { assertThatThrownBy(action) .satisfies( failure -> { 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 index 09120f8cff..9e51d5a4d1 100644 --- 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 @@ -743,10 +743,7 @@ void actualFixtureMaterializationRetainsUnderOwnerSavepoint() { var version = ownerTransaction().execute(status -> versionOwner.acceptFresh(intake, state)); var fixtureAssociations = new WorldCanonicalInstanceAssociationRepository( - dsl, - new WorldCompleteLaunchBindingRepository(dsl), - sourceOwner, - versionOwner); + dsl, new WorldCompleteLaunchBindingRepository(dsl), sourceOwner, versionOwner); var fixtureFence = new WorldDesignPublicationFenceRepository(dsl, sourceOwner); var fixtureRequest = RunOwnedWorldFixtureEvidenceTestFixtures.request(evidence); var allocatedFixture = @@ -782,8 +779,7 @@ void actualFixtureMaterializationRetainsUnderOwnerSavepoint() { "SELECT p.xmin::text FROM world_canonical_instance_preparation p " + "WHERE p.world_instance_id = ?", allocatedFixture.worldInstanceId())) - .isNotEqualTo( - scalarText("SELECT (txid_current() % 4294967296)::text")); + .isNotEqualTo(scalarText("SELECT (txid_current() % 4294967296)::text")); return result; }); assertThat(materialized).isNotNull(); @@ -1296,12 +1292,12 @@ void installed34ThroughParent40ToDefaultFrontierRetainsRowsXminAndStableLegacyUp .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") + 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"); @@ -1486,7 +1482,7 @@ void installed34ThroughParent40ToDefaultFrontierRetainsRowsXminAndStableLegacyUp assertThat(allRows(connection).get("world_instance")) .as( "fixture row remains byte-for-byte and xmin stable after denied lifecycle metadata writes") - .isEqualTo(retainedRowsAtV1042.get("world_instance")); + .isEqualTo(retainedRowsAt10428.get("world_instance")); assertThat(sourceOwner.read("dev", intakeRequest)).contains(intake); assertThat( versionOwner.readByCanonicalVersion( 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 index af184c8bdd..cf7a7382e9 100644 --- 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 @@ -574,12 +574,7 @@ void closingBeforeFirstUsePreventsFixtureClientCreation() throws Exception { RunOwnedCanonicalWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory = mock(); RunOwnedCanonicalWorldLaunchEvidenceProvider provider = provider( - fixture, - gameDesignClient, - null, - fixture.endpoints(), - fixture.tlsProperties(), - factory); + fixture, gameDesignClient, null, fixture.endpoints(), fixture.tlsProperties(), factory); provider.closeGameSessionFixtureClient(); From ec2f60c7e7b62935f5ce0f8a8396a91a64e607c5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 23:06:52 +1300 Subject: [PATCH 25/45] Separate historical and current World migration row snapshots --- ...dWorldFixedPresetResourcesPostgresIntegrationTest.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) 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 index 9e51d5a4d1..4ab0d0840d 100644 --- 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 @@ -1339,12 +1339,14 @@ void installed34ThroughParent40ToDefaultFrontierRetainsRowsXminAndStableLegacyUp assertThat(retainedRows(connection, schema, entry.getKey(), entry.getValue())) .as("all original values and xmin for %s", entry.getKey()) .containsAll(originalRows.get(entry.getKey())); - var retainedRowsAtDefaultFrontier = + var retainedRowsAtDefaultFrontierOriginalColumns = new LinkedHashMap<>(allRowsWithoutNewAttemptStamp(connection)); - retainedRowsAtDefaultFrontier.remove(HISTORY); - assertThat(retainedRowsAtDefaultFrontier) + retainedRowsAtDefaultFrontierOriginalColumns.remove(HISTORY); + assertThat(retainedRowsAtDefaultFrontierOriginalColumns) .as("all retained row values and xmin from V1042.8 through the V1042.9 repair") .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(?)", From 142f7cc69653a02bcbffbdbde1f63403abed3e7a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 23:10:34 +1300 Subject: [PATCH 26/45] Use exact-one-row reads in World transaction guard proof --- ...tionGuardSubtransactionPostgresIntegrationTest.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) 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 index 4b2895cdcc..f1efb64d65 100644 --- 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 @@ -163,13 +163,13 @@ void childSubtransactionAttemptAcceptsTopLevelAccountBindingAndInventory() { }); assertThat( - dsl.fetchOne( + dsl.fetchSingle( "SELECT count(*) FROM world_design_publication_account_binding WHERE publication_fence = ?", publicationFence) .get(0, Long.class)) .isEqualTo(1L); assertThat( - dsl.fetchOne( + dsl.fetchSingle( "SELECT count(*) FROM world_selected_publication_artifact_inventory WHERE publication_fence = ?", publicationFence) .get(0, Long.class)) @@ -181,7 +181,7 @@ void childSubtransactionAttemptAcceptsTopLevelAccountBindingAndInventory() { publicationFence)) .hasMessageContaining("World publication-fence attempt history is immutable"); assertThat( - dsl.fetchOne( + dsl.fetchSingle( "SELECT count(*) FROM world_design_publication_fence_attempt WHERE publication_fence = ?", publicationFence) .get(0, Long.class)) @@ -297,13 +297,13 @@ void callerSuppliedFutureStampIsOverwrittenAndCommittedAttemptCannotBeAttachedLa .as("a late binding fails at the installed SELECT INTO STRICT attempt lookup") .isEqualTo(ownerBeforeLateAttachment); assertThat( - dsl.fetchOne( + dsl.fetchSingle( "SELECT count(*) FROM world_design_publication_fence_attempt WHERE publication_fence = ?", publicationFence) .get(0, Long.class)) .isEqualTo(1L); assertThat( - dsl.fetchOne( + dsl.fetchSingle( "SELECT count(*) FROM world_design_publication_account_binding WHERE publication_fence = ?", publicationFence) .get(0, Long.class)) From 224f72d0d18b4f458a6e555500cb7ec37df8c962 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 23:11:21 +1300 Subject: [PATCH 27/45] Require the retained inventory count row in guard proof --- ...meTransactionGuardSubtransactionPostgresIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 index f1efb64d65..9f69264606 100644 --- 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 @@ -309,7 +309,7 @@ void callerSuppliedFutureStampIsOverwrittenAndCommittedAttemptCannotBeAttachedLa .get(0, Long.class)) .isZero(); assertThat( - dsl.fetchOne( + dsl.fetchSingle( "SELECT count(*) FROM world_selected_publication_artifact_inventory WHERE publication_fence = ?", publicationFence) .get(0, Long.class)) From 8f10af1c9d95fb6ea407872a3312523a8c757d7e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 23:20:42 +1300 Subject: [PATCH 28/45] Record qualified World transaction guard and baseline proof --- .../implementation-tracking/world-runtime-and-movement.md | 4 ++++ 1 file changed, 4 insertions(+) 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 7426b93593..a45d318e68 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -8,6 +8,10 @@ This is a non-normative implementation tracker for world runtime and movement. C ### Canonical fixture launch receiving boundary +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`. From f9ef958467c8a29228c65948ebecef4bd9c3a07e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 00:02:36 +1300 Subject: [PATCH 29/45] Preserve retryable owner reads and retained preparation transaction boundaries --- .../runtime-and-data.md | 12 +- design/project-management/ai-observations.md | 13 +- .../world-runtime-and-movement.md | 4 +- ...dCanonicalWorldLaunchEvidenceProvider.java | 16 + ...orld_initial_location_retention_guards.sql | 9 + ...rld_preparation_full_transaction_stamp.sql | 86 +++ ...SubtransactionPostgresIntegrationTest.java | 593 ++++++++++++++++++ ...resetResourcesPostgresIntegrationTest.java | 135 +++- ...orldLaunchEvidenceMtlsIntegrationTest.java | 0 ...ionOwnerGuardsPostgresIntegrationTest.java | 166 ++++- ...onicalWorldLaunchEvidenceProviderTest.java | 94 +++ .../WorldLifecycleCommandServiceImplTest.java | 2 - 12 files changed, 1099 insertions(+), 31 deletions(-) create mode 100644 services/world-management-service/src/main/resources/db/migration/V1042.10__world_initial_location_retention_guards.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1042.11__world_preparation_full_transaction_stamp.sql create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPreparationStartLocationSubtransactionPostgresIntegrationTest.java rename services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/{ => service/impl}/RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest.java (100%) 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 e5ce491ee5..0972106de0 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -59,10 +59,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. @@ -71,7 +71,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. @@ -124,7 +124,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 @@ -169,7 +169,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/project-management/ai-observations.md b/design/project-management/ai-observations.md index 10aabea299..33473934e6 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -339,14 +339,13 @@ Entry format: - `2026-10-15`: Keep proof completion separate from a coherent CI checkpoint - Context: Gameplay published the #3210 receiving carry after its runtime/source gate passed while the separate final proof-note-only documentation session was still running. - Observation: the final documentation result was pending at publication; the PR/job/Overseer report explicitly retained that limit and made no READY claim. The session later passed in 21 seconds, and Gameplay consumed its exit 0 before recording final documentation proof. Root subsequently corrected the initial characterization: publishing a coherent checkpoint with the pending-check limit was permitted and was not a publication-safety violation. The later pass does not change the proof state at publication. - - Expected pattern: gate dependent mutation and qualification claims on the consumed terminal exit status. A coherent CI checkpoint may be published with an explicit pending-check limitation; distinguish that pending proof state or an inaccurate qualification report from a safety incident. + - Expected pattern: gate dependent mutation and qualification claims on the consumed terminal exit status. A coherent CI checkpoint may be published with an explicit pending-check limitation; distinguish that pending proof state or an inaccurate qualification report from a safety incident. Record routine proof completion in the next aggregated milestone. -- 2026-10-15: Preflight native Actions response shapes before publishing trusted callbacks. Completed Validation runs `38662647370` (20 modules) and `38651777538` (zero modules) both returned `pull_requests: []` despite canonical PR/base-SHA/head titles; association-required fixtures would have passed locally while disabling reporting. The optional summary now distinguishes title/SHA attribution from a separately pinned current-ref write fence; this is not historical-ref or required-gate provenance proof. Native webhook execution and partial-rerun shape still need hosted qualification. - -- `2026-10-15`: Clarify reporting for a checkpoint with pending proof - - Context: follow-up to the #3210 pending-documentation report. - - Observation: Root clarified that publishing a coherent CI checkpoint with an explicit pending-check limitation is permitted and is not, by itself, a publication-safety violation. - - Expected pattern: consume results before claiming qualification; distinguish a pending proof state or inaccurate qualification report from a genuine safety incident. Record routine proof completion in the next aggregated milestone. +- `2026-10-15`: Qualify native Actions callback evidence at the hosted boundary + - Context: completed Validation runs [38662647370](https://github.com/benhook1013/FireMUD/actions/runs/38662647370) and [38651777538](https://github.com/benhook1013/FireMUD/actions/runs/38651777538) covered 20 modules and zero modules respectively, and returned `pull_requests: []` despite canonical PR, base-SHA, and head titles. + - Observation: association-required fixtures would have passed locally while disabling reporting. The optional summary distinguishes title/SHA attribution from a separately pinned current-ref write fence; local fixtures do not prove historical-ref or required-gate provenance, native webhook delivery, or partial-rerun response shapes. + - Expected pattern: preserve that proof limit separately from installed consumer code, and retain the required producer/activation and callback qualification in the [platform operations tracker](implementation-tracking/platform-operations-and-delivery.md). + - Reconsideration trigger: remove after producer activation and hosted webhook plus partial-rerun qualification establish the actual callback boundary. - `2026-10-15`: Identify the channel checkpoint behind PR-wide parent movement - Context: after a focused fix on #3206, review admission reported PR-wide `PARENT_MOVED` even though the live base, effective parent, and latest Hosted parent were unchanged. 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 a45d318e68..d6bce623aa 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for world runtime and movement. C ### Canonical fixture launch receiving boundary +The Hosted 553 repair is prepared with qualification pending. Owner reads preserve retryable gRPC transport statuses while retaining invalid-evidence denial for permanent failures. Forward V1042.10 adds retained-location removal guards; forward V1042.11 stamps new preparations with their server-owned top-level full transaction ID after exact manifest validation, allowing schema-4 selector retention under a savepoint while old NULL-stamped preparations remain ineligible for late attachment. Published predecessor migrations remain unchanged. The new selector probe uses controlled table clones and installed function bodies; it does not establish genuine Account authority or canonical owner activation. Current affected validation and runtime results must be recorded before this repair is described as qualified. + 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. @@ -96,7 +98,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 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); [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/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.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); [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. | 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 index df5fff9437..f9f486f779 100644 --- 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 @@ -1,5 +1,7 @@ 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; @@ -229,6 +231,9 @@ public RunOwnedCanonicalWorldLaunchEvidence requireAuthenticatedEvidence() { if (exception instanceof InvalidRunOwnedCanonicalWorldLaunchEvidenceException invalid) { throw invalid; } + if (isRetryableOwnerReadFailure(stage, exception)) { + throw exception; + } throw invalidEvidence(); } } catch (RuntimeException exception) { @@ -237,6 +242,17 @@ public RunOwnedCanonicalWorldLaunchEvidence requireAuthenticatedEvidence() { } } + 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 { 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..568a114e25 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1042.11__world_preparation_full_transaction_stamp.sql @@ -0,0 +1,86 @@ +-- 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. +ALTER TABLE world_canonical_instance_preparation + ADD COLUMN preparation_inserted_full_xid xid8; + +-- [jooq ignore start] +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/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..5bcc07a4da --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPreparationStartLocationSubtransactionPostgresIntegrationTest.java @@ -0,0 +1,593 @@ +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_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 operationId = 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, + operationId, + 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 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/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java index 4ab0d0840d..62a0731475 100644 --- 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 @@ -774,12 +774,20 @@ void actualFixtureMaterializationRetainsUnderOwnerSavepoint() { fixturePlan, allocatedFixture.worldInstanceId(), allocatedFixture.worldPrivateKeys().gameInstanceId())); - assertThat( - scalarText( - "SELECT p.xmin::text FROM world_canonical_instance_preparation p " - + "WHERE p.world_instance_id = ?", - allocatedFixture.worldInstanceId())) - .isNotEqualTo(scalarText("SELECT (txid_current() % 4294967296)::text")); + 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(); @@ -1114,6 +1122,14 @@ void installed34ThroughParent40ToDefaultFrontierRetainsRowsXminAndStableLegacyUp 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(); @@ -1222,7 +1238,9 @@ void installed34ThroughParent40ToDefaultFrontierRetainsRowsXminAndStableLegacyUp List.of( "world_validate_selected_publication_account_binding()", "world_validate_selected_publication_artifact_inventory()", - "world_retain_preparation_start_location()")) + "world_retain_preparation_start_location()", + "world_guard_preparation_start_location()", + "world_require_preparation_start_location(jsonb,jsonb,uuid)")) sameTransactionFunctionMetadata.put( function, connection @@ -1241,7 +1259,9 @@ void installed34ThroughParent40ToDefaultFrontierRetainsRowsXminAndStableLegacyUp "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_retain_start_location", + "trg_world_preparation_start_location_guard", + "trg_world_preparation_start_location_no_truncate")) sameTransactionTriggerMetadata.put( trigger, connection @@ -1335,15 +1355,96 @@ void installed34ThroughParent40ToDefaultFrontierRetainsRowsXminAndStableLegacyUp .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<>(allRowsWithoutNewAttemptStamp(connection)); + new LinkedHashMap<>(allRowsWithoutNewServerStamps(connection)); retainedRowsAtDefaultFrontierOriginalColumns.remove(HISTORY); assertThat(retainedRowsAtDefaultFrontierOriginalColumns) - .as("all retained row values and xmin from V1042.8 through the V1042.9 repair") + .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); @@ -2227,7 +2328,7 @@ private static Map> allRows(DSLContext connection) { return rows; } - private static Map> allRowsWithoutNewAttemptStamp(DSLContext connection) { + private static Map> allRowsWithoutNewServerStamps(DSLContext connection) { String schema = connection.fetchSingle("SELECT current_schema()").get(0, String.class); assertThat(schema).isNotBlank(); var tables = @@ -2239,9 +2340,13 @@ private static Map> allRowsWithoutNewAttemptStamp(DSLContex Map> rows = new LinkedHashMap<>(); for (String table : tables) { String retainedRow = - table.equals("world_design_publication_fence_attempt") - ? "(to_jsonb(retained) - 'attempt_inserted_full_xid')" - : "to_jsonb(retained)"; + 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 @@ -3030,6 +3135,8 @@ private static List remainingVersions() { versions.add("1042.7"); versions.add("1042.8"); versions.add("1042.9"); + versions.add("1042.10"); + versions.add("1042.11"); return List.copyOf(versions); } diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest.java similarity index 100% rename from services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest.java rename to services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest.java 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 index d595e9ce98..c466e31b91 100644 --- 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 @@ -33,7 +33,8 @@ import org.testcontainers.junit.jupiter.Testcontainers; /** - * Exercises the V1042.6 and V1042.8 forward owner-guard repairs against native PostgreSQL. + * 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. */ @@ -46,6 +47,13 @@ class WorldTerminalAndLocationOwnerGuardsPostgresIntegrationTest { "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 = @@ -142,6 +150,35 @@ void defaultInstallAndForwardUpgradeEnforceTerminalUnitsAndOwnerGuards() throws 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(); @@ -179,6 +216,42 @@ void defaultInstallAndForwardUpgradeEnforceTerminalUnitsAndOwnerGuards() throws .isEqualTo(normalizeSchemaQualifier(terminalAfter.functionSource(), upgradeSchema)); assertThat(productionTerminalRows(freshDsl, freshSchema)).isEmpty(); assertThat(productionLocationRows(freshDsl, freshSchema)).isEmpty(); + + assertThat(latestVersion(upgradeDsl)).isEqualTo("1042.11"); + assertThat(latestVersion(freshDsl)).isEqualTo("1042.11"); + 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); } finally { dropSchema(upgradeSource, upgradeSchema); dropSchema(freshSource, freshSchema); @@ -913,6 +986,94 @@ private static LocationFunctionMetadata locationFunctionMetadata(DSLContext dsl, 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( @@ -1299,4 +1460,7 @@ private record TerminalFunctionMetadata( 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 index cf7a7382e9..acceaa9e4f 100644 --- 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 @@ -13,6 +13,8 @@ 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; @@ -380,6 +382,98 @@ void fixtureOwnerReadFailureIsContentFreeAndLogsTheReadStage(CapturedOutput outp .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 { 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 85d732e23d..b8ee947904 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 @@ -274,8 +274,6 @@ void activatePreparedWorldInstancePromotesPreparingRow() { .thenReturn(Optional.of(instance)); when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(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)); From a5d93c5c4fc74d584b4f6bbefc82281264827edc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 00:04:38 +1300 Subject: [PATCH 30/45] Qualify PostgreSQL-only transaction stamp outside H2 schema interpretation --- ...rld_preparation_full_transaction_stamp.sql | 4 ++- ...SubtransactionPostgresIntegrationTest.java | 30 ++++++++----------- ...resetResourcesPostgresIntegrationTest.java | 18 +++++------ ...ionOwnerGuardsPostgresIntegrationTest.java | 16 +++++----- ...onicalWorldLaunchEvidenceProviderTest.java | 19 ++++-------- 5 files changed, 37 insertions(+), 50 deletions(-) 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 index 568a114e25..1e9f118594 100644 --- 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 @@ -1,9 +1,11 @@ -- 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; --- [jooq ignore start] CREATE FUNCTION world_stamp_preparation_insert_full_xid() RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" 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 index 5bcc07a4da..549b725c27 100644 --- 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 @@ -37,8 +37,8 @@ /** * 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. + * 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( @@ -99,8 +99,7 @@ static void configure(DynamicPropertyRegistry registry) { @Test void installedSchema4GuardAcceptsStampedSavepointPreparationAndRejectsLateOrHistoricalRows() throws Exception { - String installedSchema = - dsl.fetchSingle("SELECT current_schema()").get(0, String.class); + String installedSchema = dsl.fetchSingle("SELECT current_schema()").get(0, String.class); String probeSchema = "world_preparation_guard_" + UUID.randomUUID().toString().replace("-", ""); Fixture fixture = fixture(); try { @@ -120,7 +119,8 @@ void installedSchema4GuardAcceptsStampedSavepointPreparationAndRejectsLateOrHist outer.execute( status -> { savepoint.executeWithoutResult( - nested -> insertPreparation(probeSchema, fixture, 2, fixture.freshInstanceId())); + nested -> + insertPreparation(probeSchema, fixture, 2, fixture.freshInstanceId())); var row = dsl.fetchSingle( "SELECT preparation_inserted_full_xid::text, xmin::text, " @@ -188,8 +188,7 @@ private void copyInstalledFunctions(String installedSchema, String probeSchema) "world_stamp_preparation_insert_full_xid()")) { String definition = scalarText( - "SELECT pg_get_functiondef(to_regprocedure(?))", - installedSchema + "." + signature); + "SELECT pg_get_functiondef(to_regprocedure(?))", installedSchema + "." + signature); definition = definition .replace("\"" + installedSchema + "\"", "\"" + probeSchema + "\"") @@ -229,12 +228,7 @@ private void installProbeTriggers(String probeSchema) { } private void seedHistoricalPreparation(String schema, Fixture fixture) throws Exception { - insertPreparation( - schema, - fixture, - 1, - fixture.historicalInstanceId(), - null); + insertPreparation(schema, fixture, 1, fixture.historicalInstanceId(), null); } private void insertPreparation(String schema, Fixture fixture, long rowId, UUID gameInstanceId) { @@ -277,9 +271,7 @@ private void seedSelectorEvidence(String schema, Fixture fixture) throws Excepti TENANT_KEY, GAME_INSTANCE_KEY); dsl.execute( - "INSERT INTO " - + DSL.name(schema, "room") - + " (id, tenant_id, version_id) VALUES (?, ?, ?)", + "INSERT INTO " + DSL.name(schema, "room") + " (id, tenant_id, version_id) VALUES (?, ?, ?)", TEMPLATE_ROOM_KEY, TENANT_KEY, fixture.localVersionKey()); @@ -429,11 +421,13 @@ private Fixture fixture() throws Exception { UUID captureId = UUID.randomUUID(); UUID roomTemplateId = UUID.randomUUID(); UUID bindingOperationId = UUID.randomUUID(); - byte[] graphBytes = "{\"schemaVersion\":3,\"rows\":[{\"family\":\"ROOM\"}]}".getBytes(StandardCharsets.UTF_8); + 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); + byte[] accountBindingBytes = + "{\"accountBinding\":\"controlled\"}".getBytes(StandardCharsets.UTF_8); String accountBindingDigest = "sha256:" + digestHex(accountBindingBytes); byte[] selectorReceiptBytes = "{\"receipt\":\"controlled\"}".getBytes(StandardCharsets.UTF_8); byte[] appliedResultBytes = 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 index 62a0731475..ce61021b2a 100644 --- 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 @@ -1384,14 +1384,13 @@ void installed34ThroughParent40ToDefaultFrontierRetainsRowsXminAndStableLegacyUp .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)) + 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"); @@ -1413,7 +1412,8 @@ void installed34ThroughParent40ToDefaultFrontierRetainsRowsXminAndStableLegacyUp + "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") + .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"); 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 index c466e31b91..9779d45423 100644 --- 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 @@ -34,9 +34,8 @@ /** * 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. + * 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") @@ -47,7 +46,8 @@ class WorldTerminalAndLocationOwnerGuardsPostgresIntegrationTest { "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_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 = @@ -225,10 +225,10 @@ void defaultInstallAndForwardUpgradeEnforceTerminalUnitsAndOwnerGuards() throws assertLocationRetentionGuards(freshDsl, freshSchema); assertThat( triggerMetadata( - upgradeDsl, - upgradeSchema, - "world_canonical_initial_player_location_operation", - OPERATION_TRUNCATE_TRIGGER)) + upgradeDsl, + upgradeSchema, + "world_canonical_initial_player_location_operation", + OPERATION_TRUNCATE_TRIGGER)) .isEqualTo(operationTruncateBefore); assertSqlState( upgradeSource, 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 index acceaa9e4f..7b303283bf 100644 --- 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 @@ -391,8 +391,7 @@ void retryableGameDesignOwnerReadFailuresArePreservedAndStopBeforeGameSessionRea GameDesignClient gameDesignClient = mock(GameDesignClient.class); StatusRuntimeException failure = Status.fromCode(code).asRuntimeException(); when(gameDesignClient.getLaunchDescriptor(any())).thenThrow(failure); - RunOwnedCanonicalWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory = - mock(); + RunOwnedCanonicalWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory = mock(); RunOwnedCanonicalWorldLaunchEvidenceProvider provider = provider( fixture, @@ -420,8 +419,7 @@ void retryableGameSessionOwnerReadFailuresArePreserved() throws Exception { CanonicalGameInstanceLaunchAssociationClient fixtureClient = mock(); StatusRuntimeException failure = Status.fromCode(code).asRuntimeException(); when(fixtureClient.readFixture(any(), anyString())).thenThrow(failure); - RunOwnedCanonicalWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory = - mock(); + RunOwnedCanonicalWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory = mock(); when(factory.create(any(), any(), any(), anyString())).thenReturn(fixtureClient); RunOwnedCanonicalWorldLaunchEvidenceProvider provider = provider( @@ -440,8 +438,7 @@ void retryableGameSessionOwnerReadFailuresArePreserved() throws Exception { verify(gameDesignClient).getLaunchDescriptor(any()); verify(factory).create(any(), any(), any(), eq("dev")); - verify(fixtureClient) - .readFixture(any(), eq(fixture.gameSessionLeafSha256())); + verify(fixtureClient).readFixture(any(), eq(fixture.gameSessionLeafSha256())); verify(fixtureClient).close(); } } @@ -452,16 +449,10 @@ void nonretryableGameDesignOwnerReadFailureRemainsInvalidEvidence() throws Excep GameDesignClient gameDesignClient = mock(GameDesignClient.class); when(gameDesignClient.getLaunchDescriptor(any())) .thenThrow(Status.PERMISSION_DENIED.asRuntimeException()); - RunOwnedCanonicalWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory = - mock(); + RunOwnedCanonicalWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory = mock(); RunOwnedCanonicalWorldLaunchEvidenceProvider provider = provider( - fixture, - gameDesignClient, - null, - fixture.endpoints(), - fixture.tlsProperties(), - factory); + fixture, gameDesignClient, null, fixture.endpoints(), fixture.tlsProperties(), factory); try (PeerContext ignored = fixture.attachGameSessionPeer()) { assertThatThrownBy(provider::requireAuthenticatedEvidence) From ef4c89bfed4c3515f7fce3bf88c8b6a7aa36afc1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 00:14:14 +1300 Subject: [PATCH 31/45] Give schema-four selector proof its distinct application identity --- ...StartLocationSubtransactionPostgresIntegrationTest.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) 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 index 549b725c27..4c8e9971aa 100644 --- 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 @@ -414,7 +414,8 @@ private void insertStartLocation(String schema, Fixture fixture, UUID gameInstan private Fixture fixture() throws Exception { UUID tenantId = UUID.randomUUID(); UUID versionId = UUID.randomUUID(); - UUID operationId = UUID.randomUUID(); + UUID versionIdentityOperationId = UUID.randomUUID(); + UUID applicationOperationId = UUID.randomUUID(); UUID requestId = UUID.randomUUID(); UUID commitId = UUID.randomUUID(); UUID publicationFence = UUID.randomUUID(); @@ -492,7 +493,8 @@ private Fixture fixture() throws Exception { return new Fixture( tenantId, versionId, - operationId, + versionIdentityOperationId, + applicationOperationId, requestId, commitId, publicationFence, @@ -558,6 +560,7 @@ private record Fixture( UUID tenantId, UUID versionId, UUID versionIdentityOperationId, + UUID applicationOperationId, UUID requestId, UUID commitId, UUID publicationFence, From b24a57c869224ef16295c59e250d29cacb30c99c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 00:20:33 +1300 Subject: [PATCH 32/45] Include retained association row type in isolated selector fixture --- ...rationStartLocationSubtransactionPostgresIntegrationTest.java | 1 + 1 file changed, 1 insertion(+) 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 index 4c8e9971aa..b5b76184c2 100644 --- 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 @@ -64,6 +64,7 @@ class WorldPreparationStartLocationSubtransactionPostgresIntegrationTest { "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"); From da45b3bcadb77324df2f1ec97b0cf8a26c6c2246 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 01:13:38 +1300 Subject: [PATCH 33/45] Bind World graph application and start receipt digests to retained bytes --- .../runtime-and-data.md | 2 +- .../world-creation-workflow.md | 2 +- design/project-management/ai-observations.md | 5 + .../world-runtime-and-movement.md | 10 +- ...graph_application_receipt_byte_digests.sql | 46 ++ ...nReceiptDigestPostgresIntegrationTest.java | 697 ++++++++++++++++++ ...edGraphCapturePostgresIntegrationTest.java | 12 +- ...ionOwnerGuardsPostgresIntegrationTest.java | 5 +- 8 files changed, 767 insertions(+), 12 deletions(-) create mode 100644 services/world-management-service/src/main/resources/db/migration/V1042.12__world_graph_application_receipt_byte_digests.sql create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGraphApplicationReceiptDigestPostgresIntegrationTest.java 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 0972106de0..9f03d721a4 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -11,7 +11,7 @@ - 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 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; it does not newly qualify terminal-identity socket or physical PostgreSQL proof, or Temporal retry behavior. The [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status) records these proof boundaries and the broader lifecycle gaps. +- 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. 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 7442d8560c..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,7 +15,7 @@ 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` 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. This proof does not newly qualify terminal-identity socket or physical PostgreSQL behavior, 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 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 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). diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 33473934e6..2c27d2c2ba 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -352,3 +352,8 @@ Entry format: - Observation: an older CLI checkpoint retained a different parent and its reconciliation bound the preceding child head. Both new channel requests refused before quota use; compact status identified the historical evidence and exact reconciliation was initiated. - Expected pattern: admission diagnostics should identify the offending channel/checkpoint and the required reconciliation action. - Current status: reported to Overseer; this establishes diagnostic friction, not a policy defect. + +- `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. + - Outcome: The helper reported the mistake. Main verified the misplaced and intended files were byte-identical, deleted only the confirmed new duplicate, and preserved the sibling directories. The intended migration and its proof remain under review; no misplaced file was published. + - Expected pattern: Compare every patch target with the pinned worktree path and verify the first written file there before continuing. 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 d6bce623aa..c8163c3236 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -8,7 +8,9 @@ This is a non-normative implementation tracker for world runtime and movement. C ### Canonical fixture launch receiving boundary -The Hosted 553 repair is prepared with qualification pending. Owner reads preserve retryable gRPC transport statuses while retaining invalid-evidence denial for permanent failures. Forward V1042.10 adds retained-location removal guards; forward V1042.11 stamps new preparations with their server-owned top-level full transaction ID after exact manifest validation, allowing schema-4 selector retention under a savepoint while old NULL-stamped preparations remain ineligible for late attachment. Published predecessor migrations remain unchanged. The new selector probe uses controlled table clones and installed function bodies; it does not establish genuine Account authority or canonical owner activation. Current affected validation and runtime results must be recorded before this repair is described as qualified. +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. @@ -86,8 +88,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, RPC/transaction separation, matching retained `TERMINATED` replay, and mismatched-ID rejection; live PostgreSQL rollback/crash/concurrency proof is not claimed. The source-first correction compares terminal `terminationRequestId`; terminal-identity socket and physical PostgreSQL proof, 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`: The source-first termination correction rejects a differing terminal `terminationRequestId` before returning the retained snapshot. 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, the controlled predecessor owner and PostgreSQL proof qualifies cleanup-failure retention, rollback, and local finalization. Terminal-identity socket or physical PostgreSQL proof and Temporal retry proof remain unqualified; exact replay claims remain limited to that retained request identity. 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`. This controlled empty-production-row probe does not qualify nonempty canonical terminal retention or Human authority; broader physical PostgreSQL, socket, and Temporal proof remains open. See the [World runtime and data owner](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status) and [V1042.8 migration](../../../services/world-management-service/src/main/resources/db/migration/V1042.8__world_terminal_affected_unit_validation.sql). +- `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`. This controlled empty-production-row probe does not qualify nonempty canonical terminal retention or 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#implementation-status) 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). @@ -98,7 +100,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 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); [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.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); [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. | 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/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..4041866c9e --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGraphApplicationReceiptDigestPostgresIntegrationTest.java @@ -0,0 +1,697 @@ +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.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 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 forwardMigrationBindsDigestColumnsToRetainedBytesOnFreshAndUpgradedSchemas() + 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"); + + 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 history1012Before = migrationHistory(upgradeDsl, "1012"); + String history1014Before = migrationHistory(upgradeDsl, "1014"); + String history104211Before = migrationHistory(upgradeDsl, "1042.11"); + List applicationRowsBefore = applicationRows(upgradeDsl, upgradeSchema); + List receiptRowsBefore = receiptRows(upgradeDsl, upgradeSchema); + assertThat(applicationRowsBefore).isEmpty(); + assertThat(receiptRowsBefore).isEmpty(); + assertProtectedGuardMetadata( + graphBefore, receiptBefore, graphTriggersBefore, receiptTriggersBefore); + + cloneProbeTables(upgradeDsl, upgradeSchema, probeSchema); + copyInstalledFunctions(upgradeDsl, upgradeSchema, probeSchema); + installProbeTriggers(probeDsl, probeSchema); + 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"); + + Fixture retainedFixture = fixture(); + persistFixture(probeDsl, probeSchema, retainedFixture, Corruption.NONE); + List probeApplicationRowsBefore = applicationRows(probeDsl, probeSchema); + List probeReceiptRowsBefore = receiptRows(probeDsl, probeSchema); + assertThat(probeApplicationRowsBefore).hasSize(1); + assertThat(probeReceiptRowsBefore).hasSize(1); + + 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 probeUpgrade = + 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(); + probeUpgrade.migrate(); + probeUpgrade.validate(); + assertThat(latestVersion(probeDsl)).isEqualTo("1042.12"); + + assertThat( + MigrationVersion.fromVersion(latestVersion(upgradeDsl)) + .compareTo(MigrationVersion.fromVersion("1042.12")) + >= 0) + .isTrue(); + assertThat(latestVersion(freshDsl)).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")).isNotNull(); + assertThat(migrationHistory(freshDsl, "1042.12")).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.APPLICATION_ACCOUNT_DIGEST), + "23514"); + assertSqlState( + () -> persistFixture(probeDsl, probeSchema, fixture(), Corruption.RESULT_DIGEST), "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("encode(sha256(receipt.receipt_bytes), 'hex')"); + assertThat(receipt.source()) + .contains("encode(sha256(NEW.account_binding_bytes), 'hex')") + .contains("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); + } + } + + 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) { + 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(); + String receiptDigest = + corruption == Corruption.RECEIPT_DIGEST + ? wrongDigest(fixture.receiptDigest()) + : fixture.receiptDigest(); + 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, + fixture.receiptBytes()); + + String applicationAccountDigest = + corruption == Corruption.APPLICATION_ACCOUNT_DIGEST + ? wrongDigest(fixture.accountBindingDigest()) + : fixture.accountBindingDigest(); + String resultDigest = + corruption == Corruption.RESULT_DIGEST + ? wrongDigest(fixture.resultDigest()) + : fixture.resultDigest(); + 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, + fixture.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[] receiptBytes = "{\"receipt\":\"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 receiptDigest = digest(receiptBytes); + String graphDigest = digest(graphBytes); + String bindingDigest = "sha256:" + "b".repeat(64); + String bindingJson = bindingJson(tenantId, versionId, roomTemplateId); + long privateKeyBase = NEXT_PRIVATE_KEY_BASE.getAndAdd(10); + 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) + + "\"}"; + byte[] resultBytes = resultJson.getBytes(StandardCharsets.UTF_8); + 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 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 || ':' || 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, + APPLICATION_ACCOUNT_DIGEST, + RESULT_DIGEST + } + + 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 00191008b7..a33ea1e8eb 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 @@ -989,8 +989,8 @@ void historicalGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoin .hasMessageContaining("New canonical graph capture requires selected closure schema 4") .satisfies(exception -> assertThat(sqlState(exception)).isEqualTo("23514")); - // The retained current DTO accepts only schema 3; its altered checkpoint is therefore - // rejected at the current schema-4 boundary before a schema-4 checkpoint comparison. + // The retained current DTO accepts only schemas 2 and 3. Override only the serialized + // freeze-request schema so this controlled SQL probe reaches the schema-4 checkpoint guard. var currentWrongCheckpointCapture = new WorldAuthoredGraphSnapshot.CaptureRequest( capture.targetNamespace(), @@ -1006,6 +1006,10 @@ void historicalGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoin capture.contentDigest(), 3, capture.suppliedOwnedAffectedTuples()); + var currentWrongCheckpointFreezeRequest = + (tools.jackson.databind.node.ObjectNode) + mapper.valueToTree(currentWrongCheckpointCapture); + currentWrongCheckpointFreezeRequest.put("digestSchemaVersion", 4); assertThatThrownBy( () -> insertCanonicalFrozenCandidate( @@ -1013,11 +1017,11 @@ void historicalGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoin plan, currentWrongCheckpointCapture, stored, - mapper.writeValueAsString(currentWrongCheckpointCapture), + mapper.writeValueAsString(currentWrongCheckpointFreezeRequest), identityJson, intakeJson)) .isInstanceOf(org.jooq.exception.DataAccessException.class) - .hasMessageContaining("New canonical graph capture requires selected closure schema 4") + .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") 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 index 9779d45423..5fb15e2cd5 100644 --- 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 @@ -217,8 +217,9 @@ void defaultInstallAndForwardUpgradeEnforceTerminalUnitsAndOwnerGuards() throws assertThat(productionTerminalRows(freshDsl, freshSchema)).isEmpty(); assertThat(productionLocationRows(freshDsl, freshSchema)).isEmpty(); - assertThat(latestVersion(upgradeDsl)).isEqualTo("1042.11"); - assertThat(latestVersion(freshDsl)).isEqualTo("1042.11"); + 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); From 7e729cdd3265ea3c149e60e1e33e489119f686e3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 01:25:06 +1300 Subject: [PATCH 34/45] Normalize PostgreSQL trigger metadata text in digest guard proof --- ...nReceiptDigestPostgresIntegrationTest.java | 47 ++++++++++--------- 1 file changed, 25 insertions(+), 22 deletions(-) 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 index 4041866c9e..ac334a9f25 100644 --- 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 @@ -68,12 +68,7 @@ class WorldGraphApplicationReceiptDigestPostgresIntegrationTest { "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"); + "REGION", "ZONE", "ROOM", "ROOM_EXIT", "GENERATION_RULE", "WORLD_ENTITY_SPAWN_BINDING"); @Container static PostgreSQLContainer postgres = @@ -168,7 +163,7 @@ void forwardMigrationBindsDigestColumnsToRetainedBytesOnFreshAndUpgradedSchemas( assertThat( MigrationVersion.fromVersion(latestVersion(upgradeDsl)) - .compareTo(MigrationVersion.fromVersion("1042.12")) + .compareTo(MigrationVersion.fromVersion("1042.12")) >= 0) .isTrue(); assertThat(latestVersion(freshDsl)).isEqualTo(latestVersion(upgradeDsl)); @@ -223,10 +218,13 @@ void forwardMigrationBindsDigestColumnsToRetainedBytesOnFreshAndUpgradedSchemas( () -> persistFixture(probeDsl, probeSchema, fixture(), Corruption.RECEIPT_DIGEST), "23514"); assertSqlState( - () -> persistFixture(probeDsl, probeSchema, fixture(), Corruption.APPLICATION_ACCOUNT_DIGEST), + () -> + persistFixture( + probeDsl, probeSchema, fixture(), Corruption.APPLICATION_ACCOUNT_DIGEST), "23514"); assertSqlState( - () -> persistFixture(probeDsl, probeSchema, fixture(), Corruption.RESULT_DIGEST), "23514"); + () -> persistFixture(probeDsl, probeSchema, fixture(), Corruption.RESULT_DIGEST), + "23514"); } finally { dropSchema(upgradeSource, upgradeSchema); dropSchema(freshSource, freshSchema); @@ -245,8 +243,10 @@ private static void assertProtectedGuardMetadata( 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")); + 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( @@ -259,8 +259,7 @@ private static void assertFunctionPreservedExceptBody( assertThat(after.configuration()).isEqualTo(before.configuration()); } - private static void assertDigestPredicates( - FunctionMetadata graph, FunctionMetadata receipt) { + 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')") @@ -287,7 +286,8 @@ private static void copyInstalledFunctions( for (String function : PROBE_FUNCTIONS) { String definition = dsl.fetchSingle( - "SELECT pg_get_functiondef(to_regprocedure(?))", sourceSchema + "." + function + "()") + "SELECT pg_get_functiondef(to_regprocedure(?))", + sourceSchema + "." + function + "()") .get(0, String.class); definition = definition @@ -459,10 +459,12 @@ private static Fixture fixture() throws Exception { UUID versionIdentityOperationId = UUID.randomUUID(); UUID revisionId = UUID.randomUUID(); UUID roomTemplateId = UUID.randomUUID(); - byte[] accountBindingBytes = "{\"accountBinding\":\"controlled\"}".getBytes(StandardCharsets.UTF_8); + byte[] accountBindingBytes = + "{\"accountBinding\":\"controlled\"}".getBytes(StandardCharsets.UTF_8); byte[] receiptBytes = "{\"receipt\":\"controlled\"}".getBytes(StandardCharsets.UTF_8); byte[] operationBytes = "{\"operation\":\"controlled\"}".getBytes(StandardCharsets.UTF_8); - byte[] graphBytes = "{\"schemaVersion\":3,\"rows\":[{\"family\":\"ROOM\"}]}".getBytes(StandardCharsets.UTF_8); + byte[] graphBytes = + "{\"schemaVersion\":3,\"rows\":[{\"family\":\"ROOM\"}]}".getBytes(StandardCharsets.UTF_8); String accountBindingDigest = digest(accountBindingBytes); String receiptDigest = digest(receiptBytes); String graphDigest = digest(graphBytes); @@ -522,7 +524,7 @@ private static String bindingJson(UUID tenantId, UUID versionId, UUID roomTempla + "}") .reduce((left, right) -> left + "," + right) .orElseThrow(); - return "{\"revisions\":[{\"owner\":\"WORLD_MANAGEMENT\",\"payload\":{" + return "{\"revisions\":[{\"owner\":\"WORLD_MANAGEMENT\",\"payload\":{" + "\"freshGraphDeclaration\":{\"tenantId\":\"" + tenantId + "\",\"versionId\":\"" @@ -538,8 +540,7 @@ private static String bindingJson(UUID tenantId, UUID versionId, UUID roomTempla + "\"}}}}],\"affectedUnits\":[]}"; } - private static FunctionMetadata functionMetadata( - DSLContext dsl, String schema, String function) { + 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, ''), " @@ -565,7 +566,7 @@ private static FunctionMetadata functionMetadata( 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 || ':' || t.tgdeferrable::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 " @@ -642,8 +643,10 @@ private static DriverManagerDataSource source(String schema) { return source; } - private static void dropSchema(DriverManagerDataSource source, String schema) throws SQLException { - try (var connection = source.getConnection(); var statement = connection.createStatement()) { + 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"); } } From 9cf7359ff95078f9a3084bd98faadd5c69fe0806 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 01:29:32 +1300 Subject: [PATCH 35/45] Record verified World digest guard predicate proof --- .../implementation-tracking/world-runtime-and-movement.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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 c8163c3236..88349a4525 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for world runtime and movement. C ### Canonical fixture launch receiving boundary +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. @@ -100,7 +102,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 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); [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.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); [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. | From edb83757d1b139fae3cca75fbf5b50b4569ed2cf Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 01:42:03 +1300 Subject: [PATCH 36/45] Repair World migration frontier expectations and clarify current guard proof --- .../world-management-service/runtime-and-data.md | 2 +- design/project-management/ai-observations.md | 5 +++-- ...edPresetResourcesPostgresIntegrationTest.java | 1 + .../WorldLifecycleCommandServiceImplTest.java | 16 ++++++++++------ 4 files changed, 15 insertions(+), 9 deletions(-) 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 9f03d721a4..db6352bd64 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -28,7 +28,7 @@ The owner materializes the exact sealed fixed preset into one region, one zone, 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. Published prior SQL remains unchanged, and this validation grants 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. +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; V1042.12 binds stored Account, receipt, and APPLIED-result digests to their exact retained bytes. 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. ### Authored-world source retention diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index c860eded1e..531c662afa 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -83,5 +83,6 @@ Entry format: - `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. - - Outcome: The helper reported the mistake. Main verified the misplaced and intended files were byte-identical, deleted only the confirmed new duplicate, and preserved the sibling directories. The intended migration and its proof remain under review; no misplaced file was published. - - Expected pattern: Compare every patch target with the pinned worktree path and verify the first written file there before continuing. + - 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/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 index ce61021b2a..b07ac1200e 100644 --- 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 @@ -3137,6 +3137,7 @@ private static List remainingVersions() { versions.add("1042.9"); versions.add("1042.10"); versions.add("1042.11"); + versions.add("1042.12"); return List.copyOf(versions); } 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 b8ee947904..412e34c398 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 @@ -326,15 +326,19 @@ void ordinaryActiveReplayRejectsStaleUnrelatedInvalidAndOverflowEpochsWithoutEff .thenReturn(Optional.of(instance)); for (long expectedEpoch : new long[] {1L, 4L, 0L, -1L, Long.MAX_VALUE}) { - assertThrows( - IllegalArgumentException.class, - () -> service.activatePreparedWorldInstance(42L, 101L, expectedEpoch)); + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> service.activatePreparedWorldInstance(42L, 101L, expectedEpoch)); + assertTrue(exception.getMessage().startsWith("WORLD_INSTANCE_LIFECYCLE_STALE:")); } instance.setLifecycleEpoch(Long.MIN_VALUE); - assertThrows( - IllegalArgumentException.class, - () -> service.activatePreparedWorldInstance(42L, 101L, Long.MAX_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()); From e18eadf4a281d3e2ff291363e315bc58157220dc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 01:43:24 +1300 Subject: [PATCH 37/45] Record focused qualification and remaining full World gate obligation --- .../implementation-tracking/world-runtime-and-movement.md | 2 ++ 1 file changed, 2 insertions(+) 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 88349a4525..40a038d8b3 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for world runtime and movement. C ### Canonical fixture launch receiving boundary +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. From 41b9da5d16c8f548e2948aacfade91e42e3fb80b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 01:57:45 +1300 Subject: [PATCH 38/45] Preserve primary World PostgreSQL proof failures across schema cleanup --- ...rminalAndLocationOwnerGuardsPostgresIntegrationTest.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) 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 index 5fb15e2cd5..0ce38dcbe0 100644 --- 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 @@ -71,7 +71,8 @@ void defaultInstallAndForwardUpgradeEnforceTerminalUnitsAndOwnerGuards() throws DSLContext upgradeDsl = DSL.using(upgradeSource, SQLDialect.POSTGRES); DSLContext freshDsl = DSL.using(freshSource, SQLDialect.POSTGRES); - try { + try (AutoCloseable freshSchemaCleanup = () -> dropSchema(freshSource, freshSchema); + AutoCloseable upgradeSchemaCleanup = () -> dropSchema(upgradeSource, upgradeSchema)) { Flyway through10425 = flyway( upgradeSource, @@ -253,9 +254,6 @@ void defaultInstallAndForwardUpgradeEnforceTerminalUnitsAndOwnerGuards() throws assertSqlState( freshSource, "TRUNCATE TABLE \"" + freshSchema + "\".character_location", "55000"); exerciseCharacterLocationDeleteProbe(freshSource, freshSchema); - } finally { - dropSchema(upgradeSource, upgradeSchema); - dropSchema(freshSource, freshSchema); } } From 35fcb6473ec05a0f7301b34dabff5f4c765a1e91 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 02:09:31 +1300 Subject: [PATCH 39/45] Clarify selected capture refusal control and verify all remote identity reads --- ...edGraphCapturePostgresIntegrationTest.java | 28 +++++++++++++++---- ...rldAuthoredVersionIdentityServiceTest.java | 1 + 2 files changed, 24 insertions(+), 5 deletions(-) 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 a33ea1e8eb..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 @@ -938,9 +938,9 @@ void historicalGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoin .getValues(0, String.class)) .isEqualTo(rowsBefore); - // Historical storage proof above is retained as such. Repeat the actual naked-write, - // schema-2 capture, wrong-checkpoint capture, and missing-owner-history denials after the - // complete current World/Saga migration frontier. + // 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(); @@ -989,8 +989,26 @@ void historicalGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoin .hasMessageContaining("New canonical graph capture requires selected closure schema 4") .satisfies(exception -> assertThat(sqlState(exception)).isEqualTo("23514")); - // The retained current DTO accepts only schemas 2 and 3. Override only the serialized - // freeze-request schema so this controlled SQL probe reaches the schema-4 checkpoint guard. + // 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(), 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 f9a71013a2..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 @@ -349,6 +349,7 @@ void fixtureVersionRejectsRemoteStateEpochCanonicalVersionAndRequestSubstitution .isInstanceOf( WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException.class); } + verify(versionStateClient, times(4)).read(any()); verify(repository, never()).acceptFresh(any(), any()); assertThat(transactionManager.startedWith).isNull(); } From 3391fdcfcdcfcac01f705c7ac1c606568240fb3b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 02:13:10 +1300 Subject: [PATCH 40/45] Record final World review controls and rebuilt baseline proof --- .../implementation-tracking/world-runtime-and-movement.md | 4 ++++ 1 file changed, 4 insertions(+) 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 40a038d8b3..f396e5f3ad 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -8,6 +8,10 @@ This is a non-normative implementation tracker for world runtime and movement. C ### Canonical fixture launch receiving boundary +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. From 503f1ccdf2ce19983e4efdc205862a78ceef268d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 02:38:35 +1300 Subject: [PATCH 41/45] Tighten fixture test cleanup and retain canonical proof attribution --- .../game-authoring-publishing-and-activation.md | 2 +- .../implementation-tracking/world-runtime-and-movement.md | 2 ++ .../service/impl/WorldLifecycleCommandServiceImplTest.java | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) 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 e1c73fa752..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 @@ -16,7 +16,7 @@ The coherent receiving successor for [PR #3196](https://github.com/benhook1013/F 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. Fresh cross-service execution `14792` exercised World candidate `4ae539f3e4538b22891477a90ffd3015f534356f` with Game Design source commit `46074cf976759e3fb19cafc0bea7d16e544db555` in [RunOwnedFixtureOwnerCompositionCrossServiceTest](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java); receiving execution `7500` reran that case on World source commit `2807d8b8d76cc8a4f4e86e20d255fcac58bc381e` after redistribution. 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. +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 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 f396e5f3ad..a989975e99 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for world runtime and movement. C ### Canonical fixture launch receiving boundary +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. 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 412e34c398..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 @@ -447,7 +447,7 @@ void fixtureFailureRejectsAmbientTransactionBeforeLoadingOwnerEvidence() { verify(entityManagementClient, never()) .cleanupRuntimeInstance(anyLong(), anyLong(), anyString()); } finally { - TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.clear(); } } From e1d47562ffcc9c682adbad53f9386fbbafbfb941 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 03:40:41 +1300 Subject: [PATCH 42/45] Name fixture owner account argument accurately --- .../RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 index 9410a88a6a..30fa5e7de3 100644 --- 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 @@ -62,7 +62,7 @@ static RunOwnedCanonicalWorldLaunchEvidence create( String worldManagementLeafSha256, String caCertificateSha256, UUID canonicalTenantId, - long capabilityEpoch, + long ownerAccountId, boolean scriptPatchVersionPresent, boolean remapSetIdPresent) { String operationId = @@ -175,7 +175,7 @@ static RunOwnedCanonicalWorldLaunchEvidence create( operationId, 42L, 17L, - capabilityEpoch, + ownerAccountId, "demo", "Demo World", "production", From 5f0082a868709bf0076a18ca7c065431a462235b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 04:16:57 +1300 Subject: [PATCH 43/45] Validate World receipt digests against canonical semantic evidence --- .../runtime-and-data.md | 2 +- .../world-runtime-and-movement.md | 4 + ...start_location_semantic_receipt_digest.sql | 145 +++++++++++ ...resetResourcesPostgresIntegrationTest.java | 1 + ...nReceiptDigestPostgresIntegrationTest.java | 245 +++++++++++++----- 5 files changed, 326 insertions(+), 71 deletions(-) create mode 100644 services/world-management-service/src/main/resources/db/migration/V1042.13__world_start_location_semantic_receipt_digest.sql 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 db6352bd64..d7d3bd0d7c 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -28,7 +28,7 @@ The owner materializes the exact sealed fixed preset into one region, one zone, 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; V1042.12 binds stored Account, receipt, and APPLIED-result digests to their exact retained bytes. 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. +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. ### Authored-world source retention 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 a989975e99..368f392244 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -8,6 +8,10 @@ This is a non-normative implementation tracker for world runtime and movement. C ### Canonical fixture launch receiving boundary +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. New packaged startup/restart, current published-head CI and review-scope reassessment remain pending for this correction. + +The current 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. A forward SQL correction and genuine-producer regression proof are in progress; existing runs keep their stated attribution and do not establish a corrected receipt boundary. + 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. 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/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 index b07ac1200e..ca69804373 100644 --- 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 @@ -3138,6 +3138,7 @@ private static List remainingVersions() { versions.add("1042.10"); versions.add("1042.11"); versions.add("1042.12"); + versions.add("1042.13"); return List.copyOf(versions); } 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 index ac334a9f25..a8e51924cc 100644 --- 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 @@ -18,6 +18,8 @@ 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; @@ -32,10 +34,10 @@ import org.testcontainers.junit.jupiter.Testcontainers; /** - * Proves the forward 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. + * 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") @@ -75,8 +77,7 @@ class WorldGraphApplicationReceiptDigestPostgresIntegrationTest { new PostgreSQLContainer<>(TestContainerImages.postgres()); @Test - void forwardMigrationBindsDigestColumnsToRetainedBytesOnFreshAndUpgradedSchemas() - throws Exception { + void forwardMigrationBindsSemanticReceiptDigestOnFreshAndUpgradedSchemas() throws Exception { Path root = repositoryRoot(); String worldLocation = worldMigrations(root); String sagaLocation = sagaMigrations(root); @@ -102,38 +103,73 @@ void forwardMigrationBindsDigestColumnsToRetainedBytesOnFreshAndUpgradedSchemas( through104211.validate(); assertThat(latestVersion(upgradeDsl)).isEqualTo("1042.11"); - 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 history1012Before = migrationHistory(upgradeDsl, "1012"); String history1014Before = migrationHistory(upgradeDsl, "1014"); String history104211Before = migrationHistory(upgradeDsl, "1042.11"); - List applicationRowsBefore = applicationRows(upgradeDsl, upgradeSchema); - List receiptRowsBefore = receiptRows(upgradeDsl, upgradeSchema); - assertThat(applicationRowsBefore).isEmpty(); - assertThat(receiptRowsBefore).isEmpty(); - assertProtectedGuardMetadata( - graphBefore, receiptBefore, graphTriggersBefore, receiptTriggersBefore); 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"); - - Fixture retainedFixture = fixture(); - persistFixture(probeDsl, probeSchema, retainedFixture, Corruption.NONE); 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(); @@ -145,33 +181,21 @@ void forwardMigrationBindsDigestColumnsToRetainedBytesOnFreshAndUpgradedSchemas( fresh.validate(); assertThat(fresh.info().pending()).isEmpty(); - Flyway probeUpgrade = - 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(); - probeUpgrade.migrate(); - probeUpgrade.validate(); - assertThat(latestVersion(probeDsl)).isEqualTo("1042.12"); + Flyway probeCurrent = flyway(probeSource, probeSchema, null, worldLocation, sagaLocation); + probeCurrent.migrate(); + probeCurrent.validate(); + assertThat(probeCurrent.info().pending()).isEmpty(); - assertThat( - MigrationVersion.fromVersion(latestVersion(upgradeDsl)) - .compareTo(MigrationVersion.fromVersion("1042.12")) - >= 0) - .isTrue(); + 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")).isNotNull(); + 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); @@ -217,6 +241,9 @@ void forwardMigrationBindsDigestColumnsToRetainedBytesOnFreshAndUpgradedSchemas( assertSqlState( () -> persistFixture(probeDsl, probeSchema, fixture(), Corruption.RECEIPT_DIGEST), "23514"); + assertSqlState( + () -> persistFixture(probeDsl, probeSchema, fixture(), Corruption.RECEIPT_FIELD_MISMATCH), + "23514"); assertSqlState( () -> persistFixture( @@ -225,6 +252,11 @@ probeDsl, probeSchema, fixture(), Corruption.APPLICATION_ACCOUNT_DIGEST), 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); @@ -264,10 +296,12 @@ private static void assertDigestPredicates(FunctionMetadata graph, FunctionMetad .contains("encode(sha256(NEW.account_binding_bytes), 'hex')") .contains("encode(sha256(NEW.result_bytes), 'hex')") .contains("encode(sha256(receipt.account_binding_bytes), 'hex')") - .contains("encode(sha256(receipt.receipt_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("encode(sha256(NEW.receipt_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) { @@ -295,6 +329,8 @@ private static void copyInstalledFunctions( .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"); } } @@ -332,7 +368,22 @@ private static void installProbeTriggers(DSLContext dsl, String schema) { } private static void persistFixture( - DSLContext dsl, String schema, Fixture fixture, Corruption corruption) { + 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); @@ -396,10 +447,13 @@ private static void persistFixture( corruption == Corruption.RECEIPT_ACCOUNT_DIGEST ? wrongDigest(fixture.accountBindingDigest()) : fixture.accountBindingDigest(); - String receiptDigest = - corruption == Corruption.RECEIPT_DIGEST - ? wrongDigest(fixture.receiptDigest()) - : fixture.receiptDigest(); + 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 @@ -420,7 +474,13 @@ private static void persistFixture( fixture.roomTemplateId(), fixture.graphDigest(), receiptDigest, - fixture.receiptBytes()); + receiptBytes); + if (bypassReceiptGuard) { + tx.execute( + "ALTER TABLE " + + receiptTable + + " ENABLE TRIGGER trg_world_start_location_receipt_guard"); + } String applicationAccountDigest = corruption == Corruption.APPLICATION_ACCOUNT_DIGEST @@ -428,8 +488,8 @@ private static void persistFixture( : fixture.accountBindingDigest(); String resultDigest = corruption == Corruption.RESULT_DIGEST - ? wrongDigest(fixture.resultDigest()) - : fixture.resultDigest(); + ? wrongDigest(correctResultDigest) + : correctResultDigest; tx.execute( "INSERT INTO " + applicationTable @@ -444,7 +504,7 @@ private static void persistFixture( fixture.operationBytes(), fixture.accountBindingBytes(), applicationAccountDigest, - fixture.resultBytes(), + resultBytes, resultDigest); }); } @@ -461,30 +521,29 @@ private static Fixture fixture() throws Exception { UUID roomTemplateId = UUID.randomUUID(); byte[] accountBindingBytes = "{\"accountBinding\":\"controlled\"}".getBytes(StandardCharsets.UTF_8); - byte[] receiptBytes = "{\"receipt\":\"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 receiptDigest = digest(receiptBytes); 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); - 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) - + "\"}"; - byte[] resultBytes = resultJson.getBytes(StandardCharsets.UTF_8); + byte[] resultBytes = + resultBytes(graphDigest, receiptBytes, receiptDigest, operationBytes, graphBytes); return new Fixture( tenantId, versionId, @@ -512,6 +571,50 @@ private static Fixture fixture() throws Exception { 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() @@ -659,8 +762,10 @@ private enum Corruption { NONE, RECEIPT_ACCOUNT_DIGEST, RECEIPT_DIGEST, + RECEIPT_FIELD_MISMATCH, APPLICATION_ACCOUNT_DIGEST, - RESULT_DIGEST + RESULT_DIGEST, + APPLICATION_RECEIPT_FIELD_MISMATCH } private record FunctionMetadata( From db14513237c09a8b5856f8362a33479c8d90bb59 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 04:49:47 +1300 Subject: [PATCH 44/45] Align World receipt correction status and migration anchors --- .../implementation-tracking/world-runtime-and-movement.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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 368f392244..e8c3e7e166 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,9 @@ This is a non-normative implementation tracker for world runtime and movement. C ### Canonical fixture launch receiving boundary -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. New packaged startup/restart, current published-head CI and review-scope reassessment remain pending for this correction. +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. -The current 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. A forward SQL correction and genuine-producer regression proof are in progress; existing runs keep their stated attribution and do not establish a corrected receipt boundary. +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. @@ -114,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 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); [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.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. | From cc6c6c47eab6e94466afa852df83dd73c51fe3ed Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 05:07:02 +1300 Subject: [PATCH 45/45] Qualify retained World terminal row deployment proof --- .../microservices/world-management-service/runtime-and-data.md | 2 ++ .../implementation-tracking/world-runtime-and-movement.md | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) 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 d7d3bd0d7c..e0ceabade0 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -30,6 +30,8 @@ The SQL read owner permits writable `READ COMMITTED` while materialization verif 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. 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 e8c3e7e166..200ebb8b62 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -103,7 +103,7 @@ 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, 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`. This controlled empty-production-row probe does not qualify nonempty canonical terminal retention or 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#implementation-status) 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.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).