diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index dc3bfb2760..489962950c 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -94,12 +94,18 @@ The separate manually composed, unregistered `EntityRuntimeFamilyCatalogClient` Game Session has a manually composed, unregistered Automation runtime-family catalog client that requires file-backed mTLS, pins the exact same-namespace Automation peer, applies finite size/deadline bounds, and validates complete request/snapshot/catalog evidence. Its [Automation API owner contract](../automation-scripting-service/api-contracts.md#owner-local-runtime-family-catalog-read) and [classification/retention owner contract](../automation-scripting-service/runtime-and-data.md#owner-local-runtime-family-catalog) remain authoritative. A successful source read does not resolve blocking families or non-SQL gaps, enroll Automation, establish FRESH completeness/materialization, authorize an actor, or enable runtime admission, CLOSED aggregation or activation; unavailable evidence is never empty-source or initialized-state proof. +Game Session's own [owner-local runtime-family catalog](./runtime-and-data.md#owner-local-runtime-family-catalog) is instead a manually composed LOCAL SQL capture/independent committed-readback boundary, with a closed typed value and local codec, not a remote client or self-RPC. Its fixed workload namespace and exact retained request/snapshot/epoch/bytes/digests supply as-of Game Session source evidence only; unresolved SQL families and explicit non-SQL gaps remain blocking. It adds no transport, registration, preparation wiring, runtime allocation, manifest, global owner set, pointer mutation or admission authority. The linked data owner defines census, installation-marker, drift, retention and finite-bound rules; [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md) owns the source/proof status and remaining FRESH obligations. + ### Initial `FRESH` playtest lifecycle source preparation [ADR 0137](../../decisions/adr-0137-isolated-playtest-state-modes-and-reset.md) owns playtest initialization modes and isolated lifecycle identity; [ADR 0138](../../decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) owns explicit expiry and grant consequences. The local, unregistered `GameSessionInitialPlaytestLifecycleRepository.prepare` boundary supports only an initial `FRESH` preparation. Its exact request binds a stable `requestId`, `targetNamespace`, `tenantId`, `worldSlug`, `realmSlug`, and explicit future `forkExpiresAt`, plus `sourceCatalogRealmId`, `sourceCatalogRequestId`, `sourceCatalogRevision` fixed at `1`, `sourceIntakeOperationId`, `canonicalVersionId`, `publishedReleaseBundleRef`, and `publishedReleaseBundleDigest`. Game Session locks and validates the retained canonical public-production catalog and its complete published policy evidence against the same tenant/world, distinct target realm, source-intake operation, canonical version, and published release bundle; fixture-only source records are excluded. The target must also be an exact visible, non-public, `ISOLATED` realm policy in that complete immutable Human-published policy set. The retained preparation binds its policy identity, canonical bytes, digest and source revision; a public build or catalog alone cannot authorize an arbitrary private target. A new request allocates a fresh non-nil `playtestLifecycleId` and `playableStateNamespaceId` internally and fixes the initial `playtestStateGeneration` at `1`; none is supplied by the request. The canonical original-request preimage and digest are retained: an exact `requestId` retry returns that original allocation, while changed request content conflicts rather than reallocating or extending expiry. The explicit `forkExpiresAt` is stored with the preparation and checked against the database clock for a new allocation. The preparation remains `PREPARING`; an exact lifecycle read returns `INCOMPLETE` before expiry or `EXPIRED` at/after expiry, and every returned snapshot has `admissionAllowed=false`. The internal `GameSessionCurrentPrivatePlaytestRepository` selects one preparation by explicit expected head revision and expected current lifecycle. A new selection retains an immutable request receipt and advances the scoped head once; historical exact replay returns the original selection rather than choosing a newer preparation. Both selection and current reads qualify the exact retained preparation/private policy; this head is not a player-visible catalog or admission pointer. +A retained non-public catalog projection does not disqualify a new preparation for the same authored selectors; a public-production catalog remains a target conflict. A new preparation/current selection neither changes the durable catalog realm identity and selector nor evolves an immutable catalog row into another lifecycle. The [realm-routing tracker](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md#initial-fresh-lifecycle-preparation) records the separate later-lifecycle catalog and materialization boundary. + +The internal `GameSessionPrivateFreshTargetRepository` can preallocate a private realm identity in the existing canonical realm catalog from one exact retained, unexpired FRESH preparation. Its writable serializable owner transaction locks and requalifies the preparation and original complete Human policy/source, allocates a distinct realm UUID internally, and binds the immutable catalog request/outcome to that preparation’s namespace, lifecycle, generation, policy and build. Exact retry requalifies the retained evidence and preserves the original identity and bytes even after preparation expiry; it creates no new row or admission authority. Concurrent serializable attempts can return PostgreSQL `40001` because an advisory-lock wait cannot refresh the transaction snapshot. The calling owner must roll back and retry its entire transaction in a fresh serializable transaction with the same immutable request and retained preparation; a statement retry or replacement request identity is invalid. An unresolved outcome remains unresolved until exact committed readback, rather than being treated as proof that no other attempt committed. Expiry refuses new allocation and remains checked at commit; changed intent conflicts. The private projection remains non-visible, non-public, `ISOLATED`, revision `1` and `PREPARING`; it is excluded from public collection reads. SQL guards preserve the original public path and recheck the preparation deadline at commit. This identity is an input for later actual owner materialization, not a completed private target, runtime allocation, CLOSED admission pointer, owner manifest, activation or admission. + The standalone, unregistered `CurrentPrivatePlaytestLifecycleReadService` exposes that internal current source only to the exact same-namespace Account workload, without propagated player context. Its bounded closed frame correlates the original read and exact namespace/tenant/world/realm, then returns explicit absence or the immutable selection, lifecycle, expiry, source/build and private-policy provenance as observed by Game Session. Account consumes these as-of facts through its peer-qualified client; they confer no grant or actor authority and protect no later cross-owner commit. `PREPARING` remains invisible to player discovery under ADR 0137. This preparation is not a World lifecycle transition or admission decision. World continues to own the runtime lifecycle state and epoch; that epoch is not allocation authority for the new playtest lifecycle or playable-state namespace. The local boundary does not authenticate or qualify an actor, produce owner manifests, complete preparation, support seeded/snapshot initialization or reset, publish lifecycle changes, register a runtime caller, create a pointer, or admit gameplay. No delivery or successful playtest availability is implied by a stored `PREPARING` row. diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 46d01e8386..2559647338 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -71,6 +71,20 @@ The sections below define the target-state runtime contract. Current implementat - The unregistered created-owner consumer includes V1017/V1020 but omits the separate canonical UUID runtime and creation-protection storage; created-receipt fields supply neither prerequisite. The [owning tracker](../../../project-management/implementation-tracking/player-access-and-session.md#player-created-roster-consumer-preparation) records controlled initial receipt/replay and separate retention-component proof, with current guarded post-issuance supersession through retirement still unrun. Production custody, Account settlement, production PKI, registration, activation and gameplay admission remain unproved. - The current Flyway history also contains the Java/nontransactional `V8__remote_followup_target_instance_effect_identity` migration (`CREATE INDEX CONCURRENTLY`, `canExecuteInTransaction() = false`). This is outside the SQL migration input used by shared jOOQ generation and is not yet inventoried or proved as a narrow exception to the SQL-only persistence lineage. +## Owner-local runtime-family catalog + +Game Session's runtime-family catalog is a manually composed **LOCAL SQL** source boundary, not a remote-owner wrapper or self-RPC. `GameSessionRuntimeFamilyCatalogRepository.capture` binds one non-nil read-request UUID and the exact configured workload namespace to a retained snapshot UUID, positive owner catalog epoch, complete catalog bytes and SHA-256 digests. Workload namespace is deployment configuration, not a playable-state namespace, tenant selector or caller authority. Composition must use a transaction-aware jOOQ data source and transaction manager bound to the same durable primary. `capture` commits the snapshot in its own writable transaction and then performs independent committed readback; `readExact` reconstructs only that exact retained request in a separate read-only transaction. Both refuse ambient SQL transactions or synchronizations, wrong namespaces, missing evidence, changed requests, drift and invalid bytes. Post-commit readback failure can leave the immutable original snapshot retained; it supplies no success and grants no deletion or resampling authority. There is no Spring registration, endpoint, invented workload peer, or player/operator credential in this local call. + +The catalog seals the actual current Game Session PostgreSQL schema, not a historical union of `CREATE TABLE` statements, a prefix exclusion or a static expected-table response. Every installed table, including empty tables, requires an explicit family disposition; named mixed components additionally bind their actual columns. Sorted definition digests cover tables, columns, constraints, indexes, triggers, routines, sequences, views, types, policies and rules, alongside the actual configured Flyway history. View and materialized-view facts bind both the query definition and relation options, including security-invoker, security-barrier and materialized-view storage settings; changing options invalidates the current seal even when the query text is unchanged. Unknown or removed relations/components refuse capture; changed schema definitions, routines, classification or prior/later migration facts invalidate the sealed epoch and previously retained reads. A new epoch requires an explicit monotonic owner installation against the complete current classified schema, not automatic resampling during a read. + +Flyway writes each installing migration's own history row only after its migration transaction. The seal therefore binds distinct stable V1057, V1058 and V1059 installation markers and the actual installed definitions; it excludes only those three installing history rows without inventing or claiming their eventual checksums. After installation, capture/readback additionally require exactly one successful SQL row for each version with its exact installing script in the configured history table. All other prior and later history facts remain part of the seal. Each forward installer seals the next monotonic owner epoch only after all routine replacements: V1058 binds view options, and V1059 narrows the initial-preparation public-target conflict while preserving retained private projections. Earlier migrations and all retained epoch, snapshot and history bytes remain immutable. Requests retained under an older epoch conflict with the current epoch rather than being rewritten or resampled. Other installation and retention obligations remain with the [database migration owner](../../system-architecture-database-migrations.md); the configured history table, rather than an assumed `flyway_schema_history` alias, is itself explicitly classified as retained control evidence. + +Gameplay commands and remote work whose namespace partition or replacement class is unresolved remain `UNKNOWN` and blocking, never implicitly S3. Durable tick/effect recovery, selected-work manifests, remote outcomes, script-pin authority/history and region/timeline provenance remain separate blocking evidence rather than cloned gameplay payload or a FRESH manifest. Input history and reconnect context retain their distinct audit/privacy consequences. `game_manifest` remains unsupported unqualified legacy lineage, not a build or FRESH source. Catalog/pointer, original operator/LOGIN/roster/binding/account/issuer authority, installed Saga control, and their original request, nonce, fence, replay, retirement and hold guards retain their owning consequences. Classification grants neither cleanup authority nor permission to discard uncertain work. The actual V1054–V1056 private preparation and canonical catalog branch are included as retained control/provenance; `PREPARING` is not a private runtime, CLOSED pointer or readiness result. + +Known non-SQL blockers remain explicit: current-pin projections; issuer/account-index custody; legacy queue/cluster scope; region timeline/lease state; session/controller/replay state; and incomplete volatile-stage recovery. They do not enumerate all physical Redis keys or fabricate SQL session, queue, lease or index rows. The [Redis owner](../../system-architecture-redis.md), [session owner](../../system-architecture-session-behavior.md), [replacement contract](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) and [retention contract](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) continue to own those obligations. + +The purpose-specific GCR1/GCE1 local codec retains exact original catalog bytes and rejects incomplete, duplicate, unknown, contradictory, unordered, malformed or oversized values. The catalog bound is 2 MiB with at most 512 families, 16,384 schema facts and 32 non-SQL gaps; all six known gap identifiers remain mandatory, without claiming a complete Redis inventory. Request/evidence frame bounds are 1,024 and 2,101,248 bytes respectively. The immutable epoch and request snapshots have no TTL or cleanup API. These are as-of Game Session owner facts, not protection through a later commit, an owner-enrollment/required-owner set, cross-owner currentness, a FRESH manifest, materialization, runtime allocation, private authorization, pointer mutation, activation or admission. These source facts do not establish completed FRESH capability; detailed proof, status and remaining gaps stay in [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md). + ## Runtime Details - Redis and PostgreSQL hold the meaningful gameplay-session, tick-coordination, and control-plane state needed for takeover. diff --git a/design/architecture/system-architecture-database-migrations.md b/design/architecture/system-architecture-database-migrations.md index 374247acb7..0572b2fba3 100644 --- a/design/architecture/system-architecture-database-migrations.md +++ b/design/architecture/system-architecture-database-migrations.md @@ -51,10 +51,12 @@ Shared migration artifacts use a collision-free versioning convention relative t ### Sealed Runtime-Family Catalog Epochs -The owner-local catalogs for [World](./microservices/world-management-service/api-contracts.md#owner-local-runtime-family-catalog-read), [Entity](./microservices/entity-management-service/api-contracts.md#owner-local-runtime-family-catalog-read), [Automation](./microservices/automation-scripting-service/api-contracts.md#owner-local-runtime-family-catalog-read), and [Social](./microservices/social-groups-service/api-contracts.md#owner-local-runtime-family-catalog-read) seal installed PostgreSQL definitions, classifications and counted Flyway history. Every subsequent owner or adopted shared migration that changes these inputs requires an explicit next owner epoch in its reviewed forward migration batch. End that batch with the owner-local catalog installation and seal after the other definitions are installed; an ordinary new Flyway history row can itself change the catalog even when payload tables are untouched. +The owner-local catalogs for [World](./microservices/world-management-service/api-contracts.md#owner-local-runtime-family-catalog-read), [Entity](./microservices/entity-management-service/api-contracts.md#owner-local-runtime-family-catalog-read), [Automation](./microservices/automation-scripting-service/api-contracts.md#owner-local-runtime-family-catalog-read), [Social](./microservices/social-groups-service/api-contracts.md#owner-local-runtime-family-catalog-read), and [Game Session](./microservices/game-session-service/runtime-and-data.md#owner-local-runtime-family-catalog) seal installed PostgreSQL definitions, classifications and counted Flyway history. Every subsequent owner or adopted shared migration that changes these inputs requires an explicit next owner epoch in its reviewed forward migration batch. End that batch with the owner-local catalog installation and seal after the other definitions are installed; an ordinary new Flyway history row can itself change the catalog even when payload tables are untouched. Keep the census function, catalog-installation history exclusions and successful-installation predicate aligned. A catalog installer's own Flyway row is recorded after its SQL runs, so its exact successful installation must be independently qualified as in World V1047; sealing a snapshot before that row appears without the corresponding owner binding is insufficient. Preserve every prior epoch, snapshot, applied migration and checksum. Never edit history or reseal an old epoch to make a failed read pass. +For an intentional drop or rename of a classified relation, the reviewed forward migration must update the owner-local classification in the same transaction as the DDL. Temporarily remove only the classification immutability trigger needed for that change, replace the affected classification rows, and restore that trigger before sealing the next epoch. Preserve historical snapshots and epochs. The [Game Session catalog owner](./microservices/game-session-service/runtime-and-data.md#owner-local-runtime-family-catalog) provides the concrete census and exact post-SQL installation-marker contract. A new payload table or counted history row also needs the next seal, even when no classification row is removed. Prove fresh bootstrap, upgrade from retained installed history, refusal before the new seal and exact new-epoch readback on disposable PostgreSQL. + PostgreSQL upgrades can change rendered routine, view, constraint, trigger, type or sequence definitions. If the upgraded engine changes sealed bytes, reads remain failed closed until a reviewed forward catalog installation explicitly seals the next epoch against that installed engine and migration history. Prove the upgrade and new-epoch readback on disposable PostgreSQL with retained rows before relying on the new catalog, then reacquire dependent snapshots under their owning contracts. Unavailable or contradictory evidence is not an empty catalog or permission to auto-repair history. ### Objective Compatibility Gates diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 5b63293b6e..31af3e1766 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -54,3 +54,9 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - `2026-11-03` (Pacific/Auckland): Physical issuer retirement lost a fresh Redis connection before mutation. - #3382 substantive Validation run [41474380442](https://github.com/benhook1013/FireMUD/actions/runs/41474380442), Game Session partition 1, passed 85 of 86 physical cases; `retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound` failed at its release step because a newly opened Lettuce connection disconnected before `ACL WHOAMI`. No Redis mutation was dispatched by that attempt. The unchanged complete case passed locally in proof160 (93.841s); this does not establish the remote cause or completed remote improvement from the separately qualified PostgreSQL fixture pool. Source inspection found no intentional in-test shutdown or ACL change. Next: on a natural recurrence, retain Redis container health/logs and the exact turnover iteration alongside connection events; preserve fail-closed handling and the full history-bound proof. Reported to Overseer; no reconnect, blind mutation retry, assertion reduction or production workaround was added. + +- `2026-11-04` (Pacific/Auckland): FireController automatic Hosted selection can remain stuck without a child operation. + - While qualifying #3386, two normal channel-front starts returned `review_busy` although Hosted operation discovery was empty. FireController Worker confirmed an original automatic selection had stayed in `selecting` since 11:36 UTC on 3 November without creating a review operation; childless selections were absent from operation discovery. The original selection and request key are retained, and no duplicate review, queue override or grant was issued. Next: FireController Worker is fixing selector recovery and discovery; verify the installed correction and the original selection’s recovery before treating Hosted progression as restored. + +- `2026-11-04` (Pacific/Auckland): Game Session mapped PostgreSQL connection refused despite healthy container. + - Local #3386 proof423 passed 100 actual cases but failed `CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest` in its existing 60-second JDBC-readiness guard before migration. The captured container was running, not OOM-killed, listening on 5432, and returned `1` from internal `SELECT 1`; Docker reported the expected IPv4/IPv6 port bindings, while JDBC to resolved `127.0.0.1:49634` refused connections. Full failure, container diagnostics and XML are retained. This does not identify the daemon or host forwarding cause. Next: on recurrence capture host-side mapped-port listeners and routing beside the existing bounded container diagnostics before teardown; preserve the original failure and qualify the affected fixture independently. Do not weaken readiness, skip Docker proof or add production retries. diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index a2ffe10a19..d089d75608 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -23,6 +23,12 @@ These links add decision provenance only; they do not upgrade routing or playabl Current-selection CAS is implemented by [`GameSessionCurrentPrivatePlaytestRepository`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCurrentPrivatePlaytestRepository.java) and forward [V1055](../../../services/game-session-service/src/main/resources/db/migration/V1055__current_private_playtest_preparation.sql), with focused executable proof in [`GameSessionCurrentPrivatePlaytestPostgresIntegrationTest`](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCurrentPrivatePlaytestPostgresIntegrationTest.java). The Account-only read is owned by [`CurrentPrivatePlaytestLifecycleReadGrpcService`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CurrentPrivatePlaytestLifecycleReadGrpcService.java) and its [workload guard](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/CurrentPrivatePlaytestLifecycleReadWorkloadGuard.java), with the bounded transport cases in [`CurrentPrivatePlaytestLifecycleReadGrpcServiceIntegrationTest`](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/CurrentPrivatePlaytestLifecycleReadGrpcServiceIntegrationTest.java). These anchors identify the preceding qualified source boundaries and do not extend their proof limits. +The unregistered [private target repository](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionPrivateFreshTargetRepository.java), [typed projection](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalPrivateFreshTargetSnapshot.java) and forward [V1056](../../../services/game-session-service/src/main/resources/db/migration/V1056__private_fresh_catalog_preparation.sql) preallocate a distinct private realm identity in the existing canonical realm catalog from the exact retained preparation; the local boundary and non-authority limits are owned by [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md#initial-fresh-playtest-lifecycle-source-preparation). The expanded lifecycle SQL suite now has twenty cases for original preparation, private allocation/replay/refusal/expiry/commit-guard/public-row preservation and later-lifecycle preparation/selection after allocation. Retained proof190 passed at its original source; receiving proof249 passed the then-sixteen actual PostgreSQL cases, owning generation, selected main/integration static analysis, formatting and documentation checks (2m56). Receiving proof420 passed the then-nineteen lifecycle cases and thirty-two catalog/current-selection/canonical-public PostgreSQL cases, with zero failures, errors or skips and selected enabled analysis, formatting and documentation checks. It proves a self-consistent forged tenant slug is already rejected by the canonical intake trigger, and a stale SERIALIZABLE allocation must roll back and retry the whole owner transaction under the original request to replay unchanged identity, receipt and row/xmin. Published V1056–V1058 and catalog epoch semantics are unchanged; caller retry is a documented manual composition obligation, not an automatically registered production path. Game Session main SpotBugs remains unqualified under the separate JVM investigation. The projection remains non-visible PREPARING with admission denied; there is no private runtime, manifest or CLOSED aggregate. + +Forward V1059 and the corresponding Java qualification query restrict catalog target conflicts to public-production rows, so a retained private projection does not block a later FRESH preparation/current-selection request. V1059 retains the original source/policy guards and prior migrations, aligns exact installation markers and seals the next Game Session catalog epoch. The twentieth lifecycle regression covers allocating a first private target before preparing and explicitly selecting a later lifecycle, with original rows, `xmin`, source evidence and replay retained. Proof 436 reproduced the Java refusal; proof 437 reproduced the separate V1054 database refusal after only the Java correction. Generation 438 and version check 439 pass. Proof 440 passes all twenty lifecycle, ten PostgreSQL/Redis closed-barrier and nine canonical-public cases, plus fifteen catalog cases; its aggregate remains failed because the new upgrade assertion incorrectly included the added epoch in an old-row comparison and current-selection setup failed the existing mapped-JDBC readiness guard. Corrected proof441 passes all sixteen catalog and seven current-selection PostgreSQL cases, with zero failures, errors or skips, and enabled main/integration Checkstyle, integration SpotBugs, formatting and documentation checks (2m34). It proves real V1057→V1058→V1059 upgrades, retained epoch-1/2 rows and snapshots, exact history/checksums, epoch-3 capture/readback and strict installer-marker refusals. Game Session main SpotBugs remains unqualified under the separate JVM investigation. + +This source repair does not implement later-lifecycle catalog evolution. The retained catalog realm UUID and tenant-unique slug remain stable, and immutable preparation-bound revision-1 catalog rows are not rebound or duplicated under another lifecycle. A subsequent preparation/current selection therefore supplies no second catalog allocation, reset, World materialization, CLOSED aggregation or admission proof. The [canonical realm identity contract](../../architecture/system-architecture-multi-tenancy.md) owns that identity/versioning boundary; its unfinished implementation remains part of the private capability work. + ### World owner-local runtime-family catalog prerequisite The private FRESH prerequisite batch now has a concrete World-local catalog producer and Game Session consumer in working source: forward [V1046](../../../services/world-management-service/src/main/resources/db/migration/V1046__world_owner_runtime_family_catalog.sql) and [V1047](../../../services/world-management-service/src/main/resources/db/migration/V1047__world_catalog_snapshot_exact_frames.sql), [World persistence/readback owner](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogRepository.java), [authenticated World read](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcService.java), [shared exact value](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalog.java), [closed codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogCodec.java) and [Game Session client](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/WorldRuntimeFamilyCatalogClient.java). The normative census/classification/retention detail stays with [World Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#owner-local-runtime-family-catalog), and wire/authentication/bounds with [World API Contracts](../../architecture/microservices/world-management-service/api-contracts.md#owner-local-runtime-family-catalog-read). This is an actual database-derived World schema/family source and durable epoch/snapshot prerequisite, not a static expected-table list, global runtime registry, complete owner-epoch set or FRESH manifest. @@ -35,6 +41,14 @@ CLI4 corrections consolidate the four owner values' strict UTF-8, closed JSON, b Remaining batch obligations are the genuine World-owned global enrollment/required-owner-set source, remaining actual owner catalogs/epochs, complete build/lifecycle/namespace/generation-bound FRESH manifest production and immutable authenticated readback, genuine protected private authorization/runtime/materialization, and complete-set aggregation into the existing canonical CLOSED pointer/audit/outcome owner. Current World canonical materialization is still public `SHARED` and original-`StartSession`-only; no private FRESH relabelling is valid. The existing unregistered [canonical CLOSED owner](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java) supplies public initial CLOSED persistence, not the missing private aggregate; the registered legacy routing model described elsewhere remains narrower. No second private pointer authority is added. CLOSED-to-OPEN, private first admission, issuer/custody/PKI qualification, runtime/default registration, operational activation, reset and Unit1B remain held. Capability ratings are unchanged; this source batch does not complete FRESH capability. +### Game Session owner-local runtime-family catalog prerequisite + +Forward [V1057](../../../services/game-session-service/src/main/resources/db/migration/V1057__game_session_owner_runtime_family_catalog.sql), the [local capture/committed-readback repository](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogRepository.java), and closed Common value/codec add the actual Game Session SQL source. The [Game Session data owner](../../architecture/microservices/game-session-service/runtime-and-data.md#owner-local-runtime-family-catalog) defines census, classification, configured history and installation-marker limits, immutable epochs/snapshots, bounds and retention. Focused [value/codec](../../../services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/GameSessionRuntimeFamilyCatalogTest.java), [local composition guards](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogRepositoryTest.java) and [combined GS/Saga PostgreSQL](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java) sources are integrated. Receiving proof251–253 passes seven Common value/codec and three local-guard units plus fourteen actual catalog PostgreSQL cases and the existing sixteen initial-preparation/seven current-selection cases: 47 cases with zero failures, errors or skips. The ten unchanged unit results retain their earlier execution; proof 253 freshly executes the 37 SQL cases and passes selected static analysis, formatting and documentation checks (3m30). Proof 251 retains four test-map compile errors; proof 252 retains the corrected trigger-metadata cast failure, without passing-aggregate credit. Owning generation passes in proof 250. The GS latest-migration fixture pass aligns 47 additional files/63 Flyway builders and one Saga flag. Broader proof 259 retains one public-row preservation assertion failure among 67 GS cases and one Entity setup failure among 20 World cross-service cases; the existing optional maximum-payload case remains skipped. The preservation fixture now compares every original value and xmin, separately requires all nineteen new private columns null and rejects unexpected column additions; proof 260 passes all six affected SQL cases and selected checks (59s). The Entity setup correction is carried from the foreign-catalog parent and its actual coupled case passes again in proof 265 on the combined source. The proof 265 aggregate retains a Game Session harness startup failure: its Spring composition omitted the serviceSchema placeholder after Saga discovery was added. The harness now explicitly provides its actual public fixture schema and both owning migration locations before caller overrides; proof 266 passes the existing actual WebSocket LOOK transcript/metrics case and affected cross-service/test-fixture analysis, formatting and documentation checks (39s). Separate SQL and workload/actor/source fixtures still bound this proof; no whole private issuance/materialization or fresh-image claim follows. The optional maximum-payload case remains unrun. Historical target values and positive assertions are retained, with combined Saga discovery required before later upgrades. Controlled retained fixtures are not genuine private issuance, custody or process-death proof. Class/namespace/recovery gaps and six known non-SQL blockers remain explicit. There is no self-RPC, global owner set, FRESH manifest, private runtime/materialization, pointer mutation, activation, admission or capability-rating upgrade. + +Receiving proof278 qualifies the ordinary foreign-parent carry and forward [V1058](../../../services/game-session-service/src/main/resources/db/migration/V1058__game_session_catalog_view_options.sql) with 74 passing cases and no failures, errors or skips: all five Common catalog codecs (32), three local composition guards, sixteen Game Session catalog PostgreSQL cases, sixteen initial/preallocation cases and seven current-selection cases. It includes actual view-security/materialized-view option drift and genuine V1057 upgrade retention, preserving original epochs, snapshots, history, guards and public-row assertions. Owning generation, selected Common/Game Session analysis, formatting and documentation checks pass (5m); Game Session main SpotBugs remains held and unqualified. The canonical forward-version and mandatory-Docker contracts pass against the corrected foreign parent. These component results retain the existing controlled-source, separate-transport and unregistered boundaries; they do not establish installed external authority or complete FRESH initialization. + +Proof280 passes all seventeen initial/preallocation PostgreSQL cases with the exact committed-allocation retry-after-expiry correction. The original identity, complete row bytes and `xmin` remain unchanged; replay stays non-admissible, a new allocation request is refused after expiry, changed lifecycle intent conflicts, and commit-time expiry guards still apply to new rows. Selected Game Session checks and documentation pass (2m40); main SpotBugs remains held. Proof285 reruns all seventy-five Common/catalog/preparation/current-selection cases on the corrected Social parent with no failures, errors or skips, plus selected checks (2m37). This corrects retained outcome recovery without introducing a runtime or renewing private authority. + ## Capability Status | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/GameSessionRuntimeFamilyCatalog.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/GameSessionRuntimeFamilyCatalog.java new file mode 100644 index 0000000000..c0d0c52f1a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/GameSessionRuntimeFamilyCatalog.java @@ -0,0 +1,402 @@ +package net.firedevops.firemud.common.gamesession; + +import com.google.protobuf.ByteString; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** Exact Game Session SQL source evidence, not enrollment, authorization or a FRESH manifest. */ +public final class GameSessionRuntimeFamilyCatalog { + public static final String OWNER = "game-session-service"; + public static final String SCHEMA = "game-session-runtime-family-catalog/v1"; + public static final int MAX_CATALOG_BYTES = 2 * 1024 * 1024; + public static final int MAX_FAMILIES = 512; + public static final int MAX_FACTS = 16384; + public static final int MAX_NON_SQL_GAPS = 32; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + public enum Role { + RUNTIME_PAYLOAD, + SOURCE, + CONTROL, + AUDIT, + PROVENANCE, + CATALOG + } + + /** UNKNOWN/UNRESOLVED are refusal facts, never implicit S3 or a new replacement class. */ + public enum StateClass { + UNKNOWN, + UNRESOLVED, + NOT_PAYLOAD + } + + public enum FreshDisposition { + STATE_CLASS_UNKNOWN_BLOCKING, + UNSUPPORTED_SOURCE_BLOCKING, + RUNTIME_EVIDENCE_BLOCKING, + SOURCE_ONLY, + CONTROL_ONLY, + AUDIT_ONLY, + PROVENANCE_ONLY, + CATALOG_ONLY + } + + public enum RetentionDisposition { + OWNER_POLICY_RETAINED, + UNRESOLVED_RETAINED, + IMMUTABLE_RETAINED + } + + public enum GapId { + CURRENT_PIN_PROJECTION, + ISSUER_AND_ACCOUNT_INDEX_CUSTODY, + LEGACY_QUEUE_CLUSTER_SCOPE, + REGION_TIMELINE_AND_LEASE, + SESSION_CONTROLLER_AND_REPLAY, + VOLATILE_STAGE_RECOVERY + } + + public enum GapDisposition { + UNRESOLVED_BLOCKING, + UNSUPPORTED_BLOCKING + } + + public enum FactKind { + TABLE, + COLUMN, + CONSTRAINT, + INDEX, + TRIGGER, + ROUTINE, + SEQUENCE, + VIEW, + TYPE, + POLICY, + RULE, + MIGRATION + } + + public record Family( + String familyId, + String relation, + String component, + Role role, + StateClass stateClass, + FreshDisposition freshDisposition, + RetentionDisposition retentionDisposition, + String ownerConsequence) { + public Family { + identifier(relation); + Objects.requireNonNull(component, "component"); + if (!component.isEmpty()) identifier(component); + if (!Objects.equals(familyId, relation + (component.isEmpty() ? "" : "." + component))) + throw new IllegalArgumentException("Family must name its exact installed component"); + Objects.requireNonNull(role, "role"); + Objects.requireNonNull(stateClass, "stateClass"); + Objects.requireNonNull(freshDisposition, "freshDisposition"); + Objects.requireNonNull(retentionDisposition, "retentionDisposition"); + consequence(ownerConsequence); + boolean coherent = + switch (freshDisposition) { + case STATE_CLASS_UNKNOWN_BLOCKING -> + role == Role.RUNTIME_PAYLOAD && stateClass == StateClass.UNKNOWN; + case UNSUPPORTED_SOURCE_BLOCKING -> + role == Role.SOURCE && stateClass == StateClass.UNRESOLVED; + case RUNTIME_EVIDENCE_BLOCKING -> + (role == Role.CONTROL || role == Role.AUDIT || role == Role.PROVENANCE) + && stateClass == StateClass.NOT_PAYLOAD; + case SOURCE_ONLY -> role == Role.SOURCE && stateClass == StateClass.NOT_PAYLOAD; + case CONTROL_ONLY -> role == Role.CONTROL && stateClass == StateClass.NOT_PAYLOAD; + case AUDIT_ONLY -> role == Role.AUDIT && stateClass == StateClass.NOT_PAYLOAD; + case PROVENANCE_ONLY -> role == Role.PROVENANCE && stateClass == StateClass.NOT_PAYLOAD; + case CATALOG_ONLY -> role == Role.CATALOG && stateClass == StateClass.NOT_PAYLOAD; + }; + if (!coherent) throw new IllegalArgumentException("Contradictory Game Session disposition"); + if (role == Role.CATALOG && retentionDisposition != RetentionDisposition.IMMUTABLE_RETAINED) + throw new IllegalArgumentException("Catalog evidence must remain retained and immutable"); + } + } + + /** Known non-SQL limitations only, not an enumeration of physical Redis keys. */ + public record NonSqlGap(GapId id, GapDisposition disposition, String ownerConsequence) { + public NonSqlGap { + Objects.requireNonNull(id, "id"); + Objects.requireNonNull(disposition, "disposition"); + consequence(ownerConsequence); + } + } + + public record SchemaFact(FactKind kind, String identity, String definitionDigest) { + public SchemaFact { + Objects.requireNonNull(kind, "kind"); + if (identity == null + || identity.isBlank() + || identity.length() > 8192 + || identity.codePoints().anyMatch(Character::isISOControl)) + throw new IllegalArgumentException("Invalid schema fact identity"); + requireDigest(definitionDigest); + } + } + + /** + * targetNamespace is fixed WORKLOAD configuration, never playable namespace or caller authority. + */ + public record Request(UUID readRequestId, String targetNamespace) { + public Request { + requireUuid(readRequestId); + requireNamespace(targetNamespace); + } + } + + public record Evidence( + Request request, UUID snapshotId, GameSessionRuntimeFamilyCatalog catalog) { + public Evidence { + Objects.requireNonNull(request, "request"); + requireUuid(snapshotId); + Objects.requireNonNull(catalog, "catalog"); + } + + public String digest() { + return sha256(GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(this)); + } + } + + private final long catalogEpoch; + private final List families; + private final List schemaFacts; + private final List nonSqlGaps; + private final ByteString exactBytes; + + private GameSessionRuntimeFamilyCatalog( + long epoch, + List families, + List facts, + List gaps, + byte[] bytes) { + catalogEpoch = epoch; + this.families = List.copyOf(families); + schemaFacts = List.copyOf(facts); + nonSqlGaps = List.copyOf(gaps); + exactBytes = ByteString.copyFrom(bytes); + } + + public long catalogEpoch() { + return catalogEpoch; + } + + public List families() { + return families; + } + + public List schemaFacts() { + return schemaFacts; + } + + public List nonSqlGaps() { + return nonSqlGaps; + } + + public byte[] exactBytes() { + return exactBytes.toByteArray(); + } + + public String digest() { + return sha256(exactBytes.toByteArray()); + } + + @Override + public boolean equals(Object other) { + return other instanceof GameSessionRuntimeFamilyCatalog catalog + && exactBytes.equals(catalog.exactBytes); + } + + @Override + public int hashCode() { + return exactBytes.hashCode(); + } + + /** Closed parsing preserves original PostgreSQL bytes; shape alone proves no live SQL source. */ + public static GameSessionRuntimeFamilyCatalog fromStored(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_CATALOG_BYTES) + throw new IllegalArgumentException("Game Session catalog exceeds complete-source bound"); + try { + String decoded = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + JsonNode root = JSON.readTree(decoded); + fields( + root, Set.of("schema", "owner", "catalogEpoch", "families", "schemaFacts", "nonSqlGaps")); + if (!SCHEMA.equals(text(root, "schema")) || !OWNER.equals(text(root, "owner"))) + throw new IllegalArgumentException("Unsupported Game Session schema/owner"); + String epochText = text(root, "catalogEpoch"); + if (!epochText.matches("[1-9][0-9]{0,18}")) + throw new IllegalArgumentException("Invalid epoch"); + long epoch = Long.parseLong(epochText); + var families = new ArrayList(); + var facts = new ArrayList(); + var gaps = new ArrayList(); + array(root.get("families"), MAX_FAMILIES); + String previous = ""; + for (JsonNode node : root.get("families")) { + fields( + node, + Set.of( + "familyId", + "relation", + "component", + "role", + "stateClass", + "freshDisposition", + "retentionDisposition", + "ownerConsequence")); + Family family = + new Family( + text(node, "familyId"), + text(node, "relation"), + text(node, "component"), + Role.valueOf(text(node, "role")), + StateClass.valueOf(text(node, "stateClass")), + FreshDisposition.valueOf(text(node, "freshDisposition")), + RetentionDisposition.valueOf(text(node, "retentionDisposition")), + text(node, "ownerConsequence")); + if (previous.compareTo(family.familyId()) >= 0) + throw new IllegalArgumentException("Unordered/duplicate family"); + previous = family.familyId(); + families.add(family); + } + array(root.get("schemaFacts"), MAX_FACTS); + previous = ""; + Set tables = new HashSet<>(); + Set columns = new HashSet<>(); + for (JsonNode node : root.get("schemaFacts")) { + fields(node, Set.of("kind", "identity", "definitionDigest")); + SchemaFact fact = + new SchemaFact( + FactKind.valueOf(text(node, "kind")), + text(node, "identity"), + text(node, "definitionDigest")); + String key = fact.kind().name() + "/" + fact.identity(); + if (previous.compareTo(key) >= 0) + throw new IllegalArgumentException("Unordered/duplicate schema fact"); + previous = key; + if (fact.kind() == FactKind.TABLE) tables.add(fact.identity()); + if (fact.kind() == FactKind.COLUMN) columns.add(fact.identity()); + facts.add(fact); + } + Set declared = new HashSet<>(); + for (Family family : families) { + if (!tables.contains(family.relation())) + throw new IllegalArgumentException("Missing family table"); + if (family.component().isEmpty()) declared.add(family.relation()); + else if (!columns.contains(family.familyId())) + throw new IllegalArgumentException("Missing family component"); + } + if (!tables.equals(declared) || tables.isEmpty()) + throw new IllegalArgumentException("Every installed table needs an explicit disposition"); + array(root.get("nonSqlGaps"), MAX_NON_SQL_GAPS); + previous = ""; + for (JsonNode node : root.get("nonSqlGaps")) { + fields(node, Set.of("id", "disposition", "ownerConsequence")); + NonSqlGap gap = + new NonSqlGap( + GapId.valueOf(text(node, "id")), + GapDisposition.valueOf(text(node, "disposition")), + text(node, "ownerConsequence")); + if (previous.compareTo(gap.id().name()) >= 0) + throw new IllegalArgumentException("Unordered/duplicate non-SQL gap"); + previous = gap.id().name(); + gaps.add(gap); + } + if (!gaps.stream() + .map(NonSqlGap::id) + .collect(java.util.stream.Collectors.toSet()) + .equals(EnumSet.allOf(GapId.class))) + throw new IllegalArgumentException( + "All known Game Session non-SQL limitations must remain explicit"); + return new GameSessionRuntimeFamilyCatalog(epoch, families, facts, gaps, bytes); + } catch (java.io.IOException | tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("Invalid closed Game Session catalog", invalid); + } + } + + static void requireUuid(UUID value) { + if (value == null || value.equals(new UUID(0, 0))) + throw new IllegalArgumentException("Non-nil UUID required"); + } + + static void requireDigest(String value) { + if (value == null || !value.matches("sha256:[0-9a-f]{64}")) + throw new IllegalArgumentException("SHA-256 required"); + } + + public static void requireNamespace(String value) { + if (value == null || !value.matches("[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?")) + throw new IllegalArgumentException("Exact configured workload namespace required"); + } + + public static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 required by Java", impossible); + } + } + + private static void consequence(String value) { + if (value == null + || value.isBlank() + || value.length() > 1024 + || value.codePoints().anyMatch(Character::isISOControl)) + throw new IllegalArgumentException("Bounded explicit owner consequence required"); + } + + private static void identifier(String value) { + if (value == null || !value.matches("[a-z][a-z0-9_]{0,62}")) + throw new IllegalArgumentException("Schema identifier required"); + } + + private static void fields(JsonNode node, Set expected) { + if (node == null || !node.isObject()) + throw new IllegalArgumentException("Closed object required"); + Set actual = new HashSet<>(); + node.propertyNames().forEach(actual::add); + if (!actual.equals(expected)) + throw new IllegalArgumentException("Unknown or missing catalog field"); + } + + private static String text(JsonNode node, String key) { + JsonNode value = node.get(key); + if (value == null || !value.isTextual()) + throw new IllegalArgumentException("Text field required"); + return value.asText(); + } + + private static void array(JsonNode node, int maximum) { + if (node == null || !node.isArray() || node.isEmpty() || node.size() > maximum) + throw new IllegalArgumentException("Complete bounded catalog array required"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/GameSessionRuntimeFamilyCatalogCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/GameSessionRuntimeFamilyCatalogCodec.java new file mode 100644 index 0000000000..32261abf56 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/GameSessionRuntimeFamilyCatalogCodec.java @@ -0,0 +1,128 @@ +package net.firedevops.firemud.common.gamesession; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamesession.GameSessionRuntimeFamilyCatalog.Evidence; +import net.firedevops.firemud.common.gamesession.GameSessionRuntimeFamilyCatalog.Request; + +/** Purpose-specific LOCAL GCR1/GCE1 frames; no proto, self-RPC or compatibility decoder. */ +public final class GameSessionRuntimeFamilyCatalogCodec { + public static final int MAX_REQUEST_BYTES = 1024; + public static final int MAX_EVIDENCE_BYTES = + GameSessionRuntimeFamilyCatalog.MAX_CATALOG_BYTES + 4096; + private static final int REQUEST_V1 = 0x47435231; + private static final int EVIDENCE_V1 = 0x47434531; + + private GameSessionRuntimeFamilyCatalogCodec() {} + + public static byte[] requestBytes(Request request) { + Objects.requireNonNull(request, "request"); + return encode( + out -> { + out.writeInt(REQUEST_V1); + uuid(out, request.readRequestId()); + bytes(out, request.targetNamespace().getBytes(StandardCharsets.US_ASCII)); + }); + } + + public static Request requestFromStored(byte[] bytes) { + try (var in = input(bytes, MAX_REQUEST_BYTES)) { + if (in.readInt() != REQUEST_V1) + throw new IllegalArgumentException("Unsupported local read schema"); + var result = new Request(uuid(in), new String(bytes(in, 63), StandardCharsets.US_ASCII)); + if (in.available() != 0 || !Arrays.equals(bytes, requestBytes(result))) + throw new IllegalArgumentException("Noncanonical Game Session catalog request"); + return result; + } catch (IOException invalid) { + throw new IllegalArgumentException("Incomplete local catalog request", invalid); + } + } + + public static byte[] evidenceBytes(Evidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + byte[] result = + encode( + out -> { + out.writeInt(EVIDENCE_V1); + bytes(out, requestBytes(evidence.request())); + uuid(out, evidence.snapshotId()); + bytes(out, evidence.catalog().digest().getBytes(StandardCharsets.US_ASCII)); + bytes(out, evidence.catalog().exactBytes()); + }); + if (result.length > MAX_EVIDENCE_BYTES) + throw new IllegalArgumentException("Oversized complete catalog evidence"); + return result; + } + + public static Evidence evidenceFromStored(byte[] bytes) { + try (var in = input(bytes, MAX_EVIDENCE_BYTES)) { + if (in.readInt() != EVIDENCE_V1) + throw new IllegalArgumentException("Unsupported local evidence schema"); + Request request = requestFromStored(bytes(in, MAX_REQUEST_BYTES)); + UUID snapshot = uuid(in); + String digest = new String(bytes(in, 71), StandardCharsets.US_ASCII); + var catalog = + GameSessionRuntimeFamilyCatalog.fromStored( + bytes(in, GameSessionRuntimeFamilyCatalog.MAX_CATALOG_BYTES)); + var result = new Evidence(request, snapshot, catalog); + if (in.available() != 0 + || !digest.equals(catalog.digest()) + || !Arrays.equals(bytes, evidenceBytes(result))) + throw new IllegalArgumentException("Changed/noncanonical local catalog evidence"); + return result; + } catch (IOException invalid) { + throw new IllegalArgumentException("Incomplete local catalog evidence", invalid); + } + } + + private static DataInputStream input(byte[] bytes, int maximum) { + if (bytes == null || bytes.length == 0 || bytes.length > maximum) + throw new IllegalArgumentException("Frame bound exceeded"); + return new DataInputStream(new ByteArrayInputStream(bytes)); + } + + private static byte[] bytes(DataInputStream in, int maximum) throws IOException { + int length = in.readInt(); + if (length < 0 || length > maximum || length > in.available()) + throw new IllegalArgumentException("Invalid field bound"); + return in.readNBytes(length); + } + + private static void bytes(DataOutputStream out, byte[] value) throws IOException { + out.writeInt(value.length); + out.write(value); + } + + private static UUID uuid(DataInputStream in) throws IOException { + var value = new UUID(in.readLong(), in.readLong()); + GameSessionRuntimeFamilyCatalog.requireUuid(value); + return value; + } + + private static void uuid(DataOutputStream out, UUID value) throws IOException { + out.writeLong(value.getMostSignificantBits()); + out.writeLong(value.getLeastSignificantBits()); + } + + private interface Encoder { + void write(DataOutputStream out) throws IOException; + } + + private static byte[] encode(Encoder encoder) { + try (var buffer = new ByteArrayOutputStream(); + var out = new DataOutputStream(buffer)) { + encoder.write(out); + out.flush(); + return buffer.toByteArray(); + } catch (IOException impossible) { + throw new IllegalStateException("Memory frame encoding failed", impossible); + } + } +} diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/GameSessionRuntimeFamilyCatalogTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/GameSessionRuntimeFamilyCatalogTest.java new file mode 100644 index 0000000000..8bee859382 --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/GameSessionRuntimeFamilyCatalogTest.java @@ -0,0 +1,276 @@ +package unit.net.firedevops.firemud.common.gamesession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collections; +import java.util.HexFormat; +import java.util.UUID; +import java.util.stream.Collectors; +import net.firedevops.firemud.common.gamesession.GameSessionRuntimeFamilyCatalog; +import net.firedevops.firemud.common.gamesession.GameSessionRuntimeFamilyCatalog.Evidence; +import net.firedevops.firemud.common.gamesession.GameSessionRuntimeFamilyCatalog.GapId; +import net.firedevops.firemud.common.gamesession.GameSessionRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.gamesession.GameSessionRuntimeFamilyCatalogCodec; +import org.junit.jupiter.api.Test; + +/** Controlled local bytes prove shape/framing only, not a complete installed PostgreSQL source. */ +class GameSessionRuntimeFamilyCatalogTest { + private static final String FAMILY = + """ + {"familyId":"gameplay_command","relation":"gameplay_command","component":"","role":"RUNTIME_PAYLOAD", + "stateClass":"UNKNOWN","freshDisposition":"STATE_CLASS_UNKNOWN_BLOCKING", + "retentionDisposition":"UNRESOLVED_RETAINED","ownerConsequence":"Namespace and replacement class unresolved; no clone."} + """; + private static final String FACT = + """ + {"kind":"TABLE","identity":"gameplay_command", + "definitionDigest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"} + """; + private static final String GAPS = + Arrays.stream(GapId.values()) + .map( + id -> + "{\"id\":\"" + + id.name() + + "\",\"disposition\":\"UNRESOLVED_BLOCKING\"," + + "\"ownerConsequence\":\"Controlled known non-SQL gap, not a complete Redis census.\"}") + .collect(Collectors.joining(",")); + private static final String PREFIX = + """ + {"schema":"game-session-runtime-family-catalog/v1","owner":"game-session-service","catalogEpoch":"1", + """; + private static final String CATALOG = + PREFIX + + "\"families\":[" + + FAMILY + + "],\"schemaFacts\":[" + + FACT + + "],\"nonSqlGaps\":[" + + GAPS + + "]}"; + + @Test + void purposeSpecificLocalRequestHasStableFramingAndDigestVector() { + var request = new Request(UUID.fromString("11111111-1111-4111-8111-111111111111"), "test"); + assertThat(HexFormat.of().formatHex(GameSessionRuntimeFamilyCatalogCodec.requestBytes(request))) + .isEqualTo("47435231111111111111411181111111111111110000000474657374"); + assertThat(GameSessionRuntimeFamilyCatalog.sha256("abc".getBytes(StandardCharsets.US_ASCII))) + .isEqualTo("sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); + } + + @Test + void exactRoundTripPreservesOwnerEpochCorrelationBytesDigestsAndImmutableValues() { + byte[] source = CATALOG.getBytes(StandardCharsets.UTF_8); + var catalog = GameSessionRuntimeFamilyCatalog.fromStored(source); + var request = new Request(UUID.randomUUID(), "test"); + var evidence = new Evidence(request, UUID.randomUUID(), catalog); + byte[] requestBytes = GameSessionRuntimeFamilyCatalogCodec.requestBytes(request); + byte[] evidenceBytes = GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(evidence); + assertThat(catalog.catalogEpoch()).isEqualTo(1); + assertThat(catalog.digest()).isEqualTo(GameSessionRuntimeFamilyCatalog.sha256(source)); + assertThat(GameSessionRuntimeFamilyCatalogCodec.requestFromStored(requestBytes)) + .isEqualTo(request); + assertThat(GameSessionRuntimeFamilyCatalogCodec.evidenceFromStored(evidenceBytes)) + .isEqualTo(evidence); + assertThat(evidence.digest()).isEqualTo(GameSessionRuntimeFamilyCatalog.sha256(evidenceBytes)); + assertThat(GameSessionRuntimeFamilyCatalog.fromStored(source)) + .hasSameHashCodeAs(catalog) + .isEqualTo(catalog); + source[0] = 0; + catalog.exactBytes()[0] = 0; + assertThat(catalog.exactBytes()).isEqualTo(CATALOG.getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy(() -> catalog.families().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> catalog.schemaFacts().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> catalog.nonSqlGaps().clear()) + .isInstanceOf(UnsupportedOperationException.class); + var other = new Evidence(new Request(UUID.randomUUID(), "other"), UUID.randomUUID(), catalog); + assertThat(other.digest()).isNotEqualTo(evidence.digest()); + } + + @Test + void closedSchemaRejectsUnknownDuplicateMissingWrongTypedInconsistentAndTrailingContent() { + for (String invalid : + new String[] { + CATALOG.replace("\"owner\":", "\"extra\":true,\"owner\":"), + CATALOG.replace( + "\"catalogEpoch\":\"1\"", "\"catalogEpoch\":\"1\",\"catalogEpoch\":\"1\""), + CATALOG.replace("\"catalogEpoch\":\"1\"", "\"catalogEpoch\":\"0\""), + CATALOG.replace("\"catalogEpoch\":\"1\"", "\"catalogEpoch\":1"), + CATALOG.replace("\"catalogEpoch\":\"1\"", "\"catalogEpoch\":\"01\""), + CATALOG.replace("\"catalogEpoch\":\"1\"", "\"catalogEpoch\":\"9223372036854775808\""), + CATALOG.replace( + "game-session-runtime-family-catalog/v1", "game-session-runtime-family-catalog/v2"), + CATALOG.replace("game-session-service", "world-management-service"), + CATALOG.replace("\"UNKNOWN\"", "\"S3\""), + CATALOG.replace("\"UNKNOWN\"", "\"NOT_PAYLOAD\""), + CATALOG.replace("\"RUNTIME_PAYLOAD\"", "\"SOURCE\""), + CATALOG.replace("UNRESOLVED_RETAINED", "DISPOSABLE"), + CATALOG.replace("CURRENT_PIN_PROJECTION", "REDIS_CENSUS_COMPLETE"), + CATALOG.replace("UNRESOLVED_BLOCKING", "COMPLETE"), + CATALOG.replace( + "\"identity\":\"gameplay_command\"", "\"identity\":\"unknown_empty_table\""), + CATALOG.replace("\"component\":\"\"", "\"component\":\"command_text\""), + CATALOG.replace("\"component\":\"\",", ""), + CATALOG.replace("\"role\":", "\"unexpected\":false,\"role\":"), + CATALOG.replace(FAMILY, FAMILY + "," + FAMILY), + CATALOG.replace(FACT, FACT + "," + FACT), + CATALOG.replace(GAPS, GAPS + "," + GAPS), + CATALOG.replace("Namespace and replacement class unresolved; no clone.", ""), + CATALOG.replace( + "Namespace and replacement class unresolved; no clone.", "forbidden\\ncontrol"), + CATALOG.replace("sha256:" + "a".repeat(64), "sha256:" + "A".repeat(64)), + CATALOG + "{}" + }) { + assertThatThrownBy( + () -> + GameSessionRuntimeFamilyCatalog.fromStored( + invalid.getBytes(StandardCharsets.UTF_8))) + .as(invalid) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void completeFamilyFactAndKnownGapSetsAreBoundedWithoutPartialSuccess() { + String manyFamilies = + CATALOG.replace(FAMILY, String.join(",", Collections.nCopies(513, FAMILY))); + String compactFact = + "{\"kind\":\"TYPE\",\"identity\":\"x\",\"definitionDigest\":\"sha256:" + + "a".repeat(64) + + "\"}"; + String manyFacts = + CATALOG.replace(FACT, String.join(",", Collections.nCopies(16385, compactFact))); + String firstGap = GAPS.substring(0, GAPS.indexOf('}') + 1); + for (String invalid : + new String[] { + manyFamilies, + manyFacts, + CATALOG.replace(GAPS, String.join(",", Collections.nCopies(33, firstGap))), + CATALOG.replace(FAMILY, ""), + CATALOG.replace(FACT, ""), + CATALOG.replace(GAPS, ""), + CATALOG.replace(GAPS, firstGap), + CATALOG.replace("Namespace and replacement class unresolved; no clone.", "x".repeat(1025)) + }) { + assertThatThrownBy( + () -> + GameSessionRuntimeFamilyCatalog.fromStored( + invalid.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + GameSessionRuntimeFamilyCatalog.fromStored( + new byte[GameSessionRuntimeFamilyCatalog.MAX_CATALOG_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> GameSessionRuntimeFamilyCatalog.fromStored(new byte[] {(byte) 0xc3, 0x28})) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void catalogAtTheExactByteBoundRoundTripsWithoutTruncationOrReserialization() { + byte[] original = CATALOG.getBytes(StandardCharsets.UTF_8); + byte[] complete = Arrays.copyOf(original, GameSessionRuntimeFamilyCatalog.MAX_CATALOG_BYTES); + Arrays.fill(complete, original.length, complete.length, (byte) ' '); + var catalog = GameSessionRuntimeFamilyCatalog.fromStored(complete); + var evidence = new Evidence(new Request(UUID.randomUUID(), "test"), UUID.randomUUID(), catalog); + assertThat(catalog.exactBytes()).isEqualTo(complete); + assertThat( + GameSessionRuntimeFamilyCatalogCodec.evidenceFromStored( + GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(evidence))) + .isEqualTo(evidence); + assertThatThrownBy( + () -> + GameSessionRuntimeFamilyCatalog.fromStored( + Arrays.copyOf(complete, complete.length + 1))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void exactOrderedTableAndComponentCoverageCannotOmitOrReorderAFamily() { + String laterFamily = FAMILY.replace("gameplay_command", "remote_followup"); + String laterFact = FACT.replace("gameplay_command", "remote_followup"); + String complete = + CATALOG.replace(FAMILY, FAMILY + "," + laterFamily).replace(FACT, FACT + "," + laterFact); + assertThat( + GameSessionRuntimeFamilyCatalog.fromStored(complete.getBytes(StandardCharsets.UTF_8)) + .families()) + .hasSize(2); + for (String invalid : + new String[] { + complete.replace(FAMILY + "," + laterFamily, laterFamily + "," + FAMILY), + complete.replace(FACT + "," + laterFact, laterFact + "," + FACT), + complete.replace(FAMILY + "," + laterFamily, FAMILY), + complete.replace(FACT + "," + laterFact, FACT), + complete.replace("\"familyId\":\"gameplay_command\"", "\"familyId\":\"other\"") + }) { + assertThatThrownBy( + () -> + GameSessionRuntimeFamilyCatalog.fromStored( + invalid.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void localFramesRejectWrongMagicTruncationTrailingLengthsDigestAndIdentity() { + var evidence = + new Evidence( + new Request(UUID.randomUUID(), "test"), + UUID.randomUUID(), + GameSessionRuntimeFamilyCatalog.fromStored(CATALOG.getBytes(StandardCharsets.UTF_8))); + byte[] frame = GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(evidence); + for (byte[] invalid : + new byte[][] { + Arrays.copyOf(frame, frame.length - 1), + Arrays.copyOf(frame, frame.length + 1), + new byte[GameSessionRuntimeFamilyCatalogCodec.MAX_EVIDENCE_BYTES + 1], + new byte[0] + }) { + assertThatThrownBy(() -> GameSessionRuntimeFamilyCatalogCodec.evidenceFromStored(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + byte[] request = GameSessionRuntimeFamilyCatalogCodec.requestBytes(evidence.request()); + for (int length : new int[] {-1, 64, Integer.MAX_VALUE}) { + byte[] invalid = request.clone(); + ByteBuffer.wrap(invalid).putInt(20, length); + assertThatThrownBy(() -> GameSessionRuntimeFamilyCatalogCodec.requestFromStored(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + for (byte[] invalid : + new byte[][] { + Arrays.copyOf(request, request.length - 1), + Arrays.copyOf(request, request.length + 1), + new byte[1025] + }) { + assertThatThrownBy(() -> GameSessionRuntimeFamilyCatalogCodec.requestFromStored(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + int digestOffset = 4 + 4 + request.length + 16 + 4; + frame[digestOffset + 7] = frame[digestOffset + 7] == 'a' ? (byte) 'b' : (byte) 'a'; + assertThatThrownBy(() -> GameSessionRuntimeFamilyCatalogCodec.evidenceFromStored(frame)) + .isInstanceOf(IllegalArgumentException.class); + frame[0] = 'W'; + request[0] = 'W'; + assertThatThrownBy(() -> GameSessionRuntimeFamilyCatalogCodec.evidenceFromStored(frame)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> GameSessionRuntimeFamilyCatalogCodec.requestFromStored(request)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(new UUID(0, 0), "test")) + .isInstanceOf(IllegalArgumentException.class); + for (String namespace : + new String[] {"", "UPPER", "-test", "test-", "1/sa/game-session-service", "a".repeat(64)}) { + assertThatThrownBy(() -> new Request(UUID.randomUUID(), namespace)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy(() -> new Evidence(evidence.request(), new UUID(0, 0), evidence.catalog())) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalPrivateFreshTargetSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalPrivateFreshTargetSnapshot.java new file mode 100644 index 0000000000..3cf20b374c --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalPrivateFreshTargetSnapshot.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.util.Objects; +import java.util.UUID; + +/** + * Typed internal projection of a private FRESH catalog identity that is still PREPARING. + * + *

This is not a public realm listing, completed World manifest, runtime, or admission target. + */ +public record CanonicalPrivateFreshTargetSnapshot( + String targetNamespace, + UUID tenantId, + String worldSlug, + String realmSlug, + UUID realmId, + String realmDisplayName, + boolean visible, + boolean publicProduction, + String stateScope, + UUID playableStateNamespaceId, + String characterCreationPolicy, + long catalogRevision, + UUID creationRequestId, + String requestDigest, + String receiptDigest, + UUID preparationRequestId, + UUID playtestLifecycleId, + long playtestStateGeneration, + String preparationState, + UUID sourceCatalogRealmId, + UUID targetPolicyId, + String targetPolicyDigest, + UUID canonicalVersionId, + String publishedReleaseBundleRef, + String publishedReleaseBundleDigest) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public CanonicalPrivateFreshTargetSnapshot { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + requireNonNil(tenantId, "tenantId"); + Objects.requireNonNull(worldSlug, "worldSlug"); + Objects.requireNonNull(realmSlug, "realmSlug"); + requireNonNil(realmId, "realmId"); + Objects.requireNonNull(realmDisplayName, "realmDisplayName"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(characterCreationPolicy, "characterCreationPolicy"); + requireNonNil(creationRequestId, "creationRequestId"); + Objects.requireNonNull(requestDigest, "requestDigest"); + Objects.requireNonNull(receiptDigest, "receiptDigest"); + requireNonNil(preparationRequestId, "preparationRequestId"); + requireNonNil(playtestLifecycleId, "playtestLifecycleId"); + Objects.requireNonNull(preparationState, "preparationState"); + requireNonNil(sourceCatalogRealmId, "sourceCatalogRealmId"); + requireNonNil(targetPolicyId, "targetPolicyId"); + Objects.requireNonNull(targetPolicyDigest, "targetPolicyDigest"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + Objects.requireNonNull(publishedReleaseBundleRef, "publishedReleaseBundleRef"); + Objects.requireNonNull(publishedReleaseBundleDigest, "publishedReleaseBundleDigest"); + if (visible + || publicProduction + || !"ISOLATED".equals(stateScope) + || catalogRevision != 1L + || playtestStateGeneration != 1L + || !"PREPARING".equals(preparationState) + || playtestLifecycleId.equals(playableStateNamespaceId) + || realmId.equals(sourceCatalogRealmId) + || realmId.equals(targetPolicyId)) { + throw new IllegalArgumentException( + "Unsupported private FRESH target state; catalog identity must remain non-public and PREPARING"); + } + if (!requestDigest.matches("sha256:[0-9a-f]{64}") + || !receiptDigest.matches("sha256:[0-9a-f]{64}") + || !targetPolicyDigest.matches("sha256:[0-9a-f]{64}") + || !publishedReleaseBundleDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Private FRESH target digests must be lowercase SHA-256"); + } + if (realmDisplayName.isBlank() + || realmDisplayName.codePointCount(0, realmDisplayName.length()) > 128 + || characterCreationPolicy.isBlank() + || publishedReleaseBundleRef.isBlank() + || publishedReleaseBundleRef.length() > 1024) { + throw new IllegalArgumentException("Private FRESH target policy projection is invalid"); + } + } + + public boolean admissionAllowed() { + return false; + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionInitialPlaytestLifecycleRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionInitialPlaytestLifecycleRepository.java index e2dde92894..18ec64c546 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionInitialPlaytestLifecycleRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionInitialPlaytestLifecycleRepository.java @@ -207,12 +207,55 @@ public Optional readExact( return Optional.of(new Snapshot(preparation, state, observedAt)); } + /** + * Locks and requalifies one exact retained preparation for private catalog identity allocation. + * + *

This bounded owner read is only for a caller-owned writable transaction. It does not select + * a lifecycle by slug and refuses a changed source before the catalog owner can allocate an + * identity. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readExactForPrivateCatalogTarget( + UUID preparationRequestId, UUID playtestLifecycleId) { + requireOwnerTransaction(true); + requireNonNil(preparationRequestId, "preparationRequestId"); + requireNonNil(playtestLifecycleId, "playtestLifecycleId"); + Record row = + dsl.fetchOne( + "SELECT * FROM " + + TABLE + + " WHERE request_id = ? AND playtest_lifecycle_id = ? FOR SHARE", + preparationRequestId, + playtestLifecycleId); + if (row == null) return Optional.empty(); + Preparation preparation = preparation(row); + Request request = preparation.request(); + Record sourceLock = + dsl.fetchOne( + "SELECT realm_id FROM game_session_canonical_realm_catalog " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ? FOR SHARE", + request.targetNamespace(), + request.tenantId(), + request.sourceCatalogRealmId()); + if (sourceLock == null || !preparation.source().equals(readSource(request, false))) { + throw new SourceUnavailableException( + "Exact initial playtest source changed before private catalog allocation"); + } + Instant observedAt = databaseNow(); + ReadState state = + observedAt.isBefore(preparation.request().forkExpiresAt()) + ? ReadState.INCOMPLETE + : ReadState.EXPIRED; + return Optional.of(new Snapshot(preparation, state, observedAt)); + } + private SourceReference qualifySource(Request request) { SourceReference source = readSource(request, true); Record target = dsl.fetchOne( "SELECT realm_id FROM game_session_canonical_realm_catalog WHERE target_namespace = ? " - + "AND canonical_tenant_id = ? AND world_slug = ? AND realm_slug = ?", + + "AND canonical_tenant_id = ? AND world_slug = ? AND realm_slug = ? " + + "AND public_production", request.targetNamespace(), request.tenantId(), request.worldSlug(), diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionPrivateFreshTargetRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionPrivateFreshTargetRepository.java new file mode 100644 index 0000000000..533efb7a0d --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionPrivateFreshTargetRepository.java @@ -0,0 +1,735 @@ +package net.firedevops.firemud.gamesession.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayOutputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamesession.dto.CanonicalPrivateFreshTargetSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionInitialPlaytestLifecycleRepository.Preparation; +import net.firedevops.firemud.gamesession.repository.GameSessionInitialPlaytestLifecycleRepository.ReadState; +import net.firedevops.firemud.gamesession.repository.GameSessionInitialPlaytestLifecycleRepository.Snapshot; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Allocates an internal private FRESH realm catalog identity from one exact retained preparation. + * + *

The row remains non-public and PREPARING. This repository creates no World owner data, + * runtime, CLOSED pointer, admission, or player visibility. + */ +public class GameSessionPrivateFreshTargetRepository { + private static final String CATALOG = "game_session_canonical_realm_catalog"; + private static final String REQUEST_SCHEMA = "game-session-private-fresh-catalog-request/v1"; + private static final String RECEIPT_SCHEMA = "game-session-private-fresh-catalog-receipt/v1"; + private static final long INITIAL_CATALOG_REVISION = 1L; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final DSLContext dsl; + private final GameSessionInitialPlaytestLifecycleRepository preparations; + private final GameSessionCanonicalRealmCatalogRepository catalogs; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Fail-fast validation is local; no overridable callback or partially initialized object escapes.") + public GameSessionPrivateFreshTargetRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + this.preparations = new GameSessionInitialPlaytestLifecycleRepository(dsl); + this.catalogs = new GameSessionCanonicalRealmCatalogRepository(dsl); + } + + /** + * Allocates a target realm ID for the exact prepared FRESH lifecycle in the caller's SERIALIZABLE + * owner transaction. Namespace, lifecycle, generation, selectors, and policy come only from the + * locked retained preparation. + * + *

The caller must handle PostgreSQL SQLSTATE 40001 by rolling back and retrying the complete + * owner transaction with this same immutable request. An advisory-lock wait does not refresh a + * SERIALIZABLE snapshot; retrying only this statement or allocating another request is invalid. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Allocation allocate(Request request) { + Objects.requireNonNull(request, "request"); + requireWritableSerializableOwnerTransaction(); + dsl.fetch( + "SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", + "private-fresh-preparation/" + request.preparationRequestId()); + dsl.fetch( + "SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", + "private-fresh-request/" + request.requestId()); + + Record priorRequest = findByCreationRequest(request.requestId()); + if (priorRequest != null + && (!request + .preparationRequestId() + .equals(priorRequest.get("private_preparation_request_id", UUID.class)) + || !request + .playtestLifecycleId() + .equals(priorRequest.get("private_playtest_lifecycle_id", UUID.class)))) { + throw new IdempotencyConflictException( + "Private FRESH target request identity was reused for another preparation or lifecycle"); + } + + Snapshot snapshot = + preparations + .readExactForPrivateCatalogTarget( + request.preparationRequestId(), request.playtestLifecycleId()) + .orElseThrow( + () -> + new PreparationUnavailableException( + "Exact retained FRESH preparation and lifecycle are unavailable")); + Preparation preparation = snapshot.preparation(); + CanonicalRealmCatalogSnapshot sourceCatalog = readExactSourceCatalog(preparation); + IntakeReceipt intake = sourceCatalog.sourceIntakeReceipt(); + byte[] completePolicyEvidence = readCompleteHumanPolicyEvidence(preparation); + byte[] requestPreimage = requestPreimage(request, preparation.requestDigest()); + String requestDigest = digest(requestPreimage); + + if (priorRequest != null) { + return new Allocation( + requireExactRetry(priorRequest, request, preparation, sourceCatalog, requestPreimage), + true); + } + if (snapshot.state() != ReadState.INCOMPLETE) { + throw new PreparationUnavailableException( + "Exact retained FRESH preparation has expired and cannot allocate a catalog identity"); + } + Record priorPreparation = findByPreparation(request.preparationRequestId()); + if (priorPreparation != null) { + throw new IdempotencyConflictException( + "Exact FRESH preparation already has a different private catalog request"); + } + + RealmEntryPolicy policy = preparation.source().targetPolicy().source().policy(); + UUID realmId; + do { + realmId = UUID.randomUUID(); + } while (NIL_UUID.equals(realmId) + || realmId.equals(preparation.request().sourceCatalogRealmId()) + || realmId.equals(preparation.source().targetPolicy().policyId()) + || realmId.equals(preparation.playtestLifecycleId()) + || realmId.equals(preparation.playableStateNamespaceId())); + String receiptDigest = + receiptDigest( + request.requestId(), preparation, sourceCatalog, realmId, requestDigest, policy); + Object[] values = + insertValues( + request, + preparation, + sourceCatalog, + intake, + completePolicyEvidence, + realmId, + requestPreimage, + requestDigest, + receiptDigest, + policy); + String columns = + "target_namespace, canonical_tenant_id, tenant_slug, world_slug, realm_id, realm_slug, " + + "realm_display_name, visible, public_production, state_scope, playable_state_namespace_id, " + + "character_creation_policy, catalog_revision, creation_request_id, request_digest, " + + "receipt_digest, source_intake_operation_id, source_intake_schema_version, " + + "source_intake_request_id, source_intake_request_digest, source_intake_receipt_digest, " + + "source_schema_version, source_registration_request_id, source_operation_id, " + + "source_request_digest, source_world_display_name, source_game_row_id, " + + "source_game_tenant_key, source_provenance_kind, source_evidence_digest, " + + "complete_policy_set_evidence, private_target_request_preimage, " + + "private_preparation_request_id, private_playtest_lifecycle_id, " + + "private_preparation_request_digest, private_state_generation, " + + "private_source_catalog_realm_id, private_source_catalog_request_id, " + + "private_source_catalog_revision, private_source_catalog_receipt_digest, " + + "private_target_policy_id, private_target_policy_digest, " + + "private_target_policy_source_commit_id, private_target_policy_source_revision_id, " + + "private_target_policy_logical_revision_id, private_canonical_version_id, " + + "private_published_release_bundle_ref, private_published_release_bundle_digest, " + + "private_source_policy_set_digest, private_source_policy_carrier_digest"; + String placeholders = String.join(", ", java.util.Collections.nCopies(values.length, "?")); + Record inserted = + dsl.fetchOne( + "INSERT INTO " + + CATALOG + + " (" + + columns + + ") VALUES (" + + placeholders + + ") ON CONFLICT DO NOTHING RETURNING *", + values); + if (inserted != null) { + return new Allocation( + requireExactRetry(inserted, request, preparation, sourceCatalog, requestPreimage), false); + } + Record racedRequest = findByCreationRequest(request.requestId()); + if (racedRequest != null) { + return new Allocation( + requireExactRetry(racedRequest, request, preparation, sourceCatalog, requestPreimage), + true); + } + Record racedPreparation = findByPreparation(request.preparationRequestId()); + if (racedPreparation != null) { + throw new IdempotencyConflictException( + "Exact FRESH preparation already has a different private catalog request"); + } + throw new CatalogConflictException( + "Private FRESH target conflicts with a retained realm selector or namespace identity"); + } + + /** Reads a private preparation-bound projection after its catalog row has committed. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readByPreparation( + UUID preparationRequestId, UUID playtestLifecycleId) { + requireCommittedRead(); + requireNonNil(preparationRequestId, "preparationRequestId"); + requireNonNil(playtestLifecycleId, "playtestLifecycleId"); + Record row = + dsl.fetchOne( + "SELECT * FROM " + + CATALOG + + " WHERE private_preparation_request_id = ? AND private_playtest_lifecycle_id = ?", + preparationRequestId, + playtestLifecycleId); + return row == null ? Optional.empty() : Optional.of(toSnapshot(row)); + } + + private Record findByCreationRequest(UUID requestId) { + List rows = + dsl.fetch( + "SELECT * FROM " + + CATALOG + + " WHERE creation_request_id = ? AND private_preparation_request_id IS NOT NULL", + requestId); + if (rows.size() > 1) { + throw new CatalogConflictException("Private FRESH catalog request identity is ambiguous"); + } + return rows.isEmpty() ? null : rows.getFirst(); + } + + private Record findByPreparation(UUID preparationRequestId) { + List rows = + dsl.fetch( + "SELECT * FROM " + CATALOG + " WHERE private_preparation_request_id = ?", + preparationRequestId); + if (rows.size() > 1) { + throw new CatalogConflictException("FRESH preparation has multiple private catalog targets"); + } + return rows.isEmpty() ? null : rows.getFirst(); + } + + private CanonicalRealmCatalogSnapshot readExactSourceCatalog(Preparation preparation) { + var request = preparation.request(); + CanonicalRealmCatalogSnapshot source = + catalogs.readRetainedInitialPublicProduction( + request.targetNamespace(), + request.tenantId(), + request.sourceCatalogRealmId(), + request.sourceCatalogRequestId(), + request.sourceCatalogRevision()); + var sourceReference = preparation.source(); + if (!source.visible() + || !source.publicProduction() + || !source.tenantId().equals(request.tenantId()) + || !source.worldSlug().equals(request.worldSlug()) + || !source.realmId().equals(sourceReference.catalogRealmId()) + || !source.creationRequestId().equals(sourceReference.catalogRequestId()) + || source.catalogRevision() != sourceReference.catalogRevision() + || !source.receiptDigest().equals(sourceReference.catalogReceiptDigest()) + || !source.sourceIntakeReceipt().operationId().equals(sourceReference.intakeOperationId()) + || !source + .sourceIntakeReceipt() + .receiptDigest() + .equals(sourceReference.intakeReceiptDigest())) { + throw new PreparationUnavailableException( + "Private target source catalog no longer matches its exact FRESH preparation"); + } + return source; + } + + private byte[] readCompleteHumanPolicyEvidence(Preparation preparation) { + var request = preparation.request(); + Record row = + dsl.fetchOne( + "SELECT complete_policy_set_evidence, fixture_policy_request_bytes, " + + "fixture_policy_seal_operation_id, fixture_policy_seal_request_digest, " + + "fixture_policy_seal_evidence_digest FROM " + + CATALOG + + " WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ? FOR SHARE", + request.targetNamespace(), + request.tenantId(), + request.sourceCatalogRealmId()); + byte[] evidence = row == null ? null : row.get("complete_policy_set_evidence", byte[].class); + if (evidence == null + || evidence.length == 0 + || row.get("fixture_policy_request_bytes", byte[].class) != null + || row.get("fixture_policy_seal_operation_id", UUID.class) != null + || row.get("fixture_policy_seal_request_digest", String.class) != null + || row.get("fixture_policy_seal_evidence_digest", String.class) != null + || !digest(evidence).equals(preparation.source().policyCarrierDigest())) { + throw new PreparationUnavailableException( + "Private FRESH target requires its exact retained Human published policy carrier"); + } + return evidence; + } + + private Object[] insertValues( + Request request, + Preparation preparation, + CanonicalRealmCatalogSnapshot sourceCatalog, + IntakeReceipt intake, + byte[] completePolicyEvidence, + UUID realmId, + byte[] requestPreimage, + String requestDigest, + String receiptDigest, + RealmEntryPolicy policy) { + var source = intake.source(); + var preparationRequest = preparation.request(); + var targetPolicy = preparation.source().targetPolicy(); + return new Object[] { + preparationRequest.targetNamespace(), + preparationRequest.tenantId(), + source.tenantSlug(), + preparationRequest.worldSlug(), + realmId, + preparationRequest.realmSlug(), + policy.realmDisplayName(), + false, + false, + RealmEntryPolicy.StateScope.ISOLATED.name(), + preparation.playableStateNamespaceId(), + policy.entryPolicy().name(), + INITIAL_CATALOG_REVISION, + request.requestId(), + requestDigest, + receiptDigest, + intake.operationId(), + 1, + intake.intakeRequestId(), + intake.requestDigest(), + intake.receiptDigest(), + source.schemaVersion(), + source.registrationRequestId(), + source.operationId(), + source.requestDigest(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest(), + completePolicyEvidence, + requestPreimage, + request.preparationRequestId(), + request.playtestLifecycleId(), + preparation.requestDigest(), + preparation.playtestStateGeneration(), + sourceCatalog.realmId(), + sourceCatalog.creationRequestId(), + sourceCatalog.catalogRevision(), + sourceCatalog.receiptDigest(), + targetPolicy.policyId(), + targetPolicy.policyDigest(), + targetPolicy.source().commitId(), + targetPolicy.source().revisionId(), + targetPolicy.source().logicalRevisionId(), + preparation.source().canonicalVersionId(), + preparation.source().publishedReleaseBundleRef(), + preparation.source().publishedReleaseBundleDigest(), + preparation.source().policySetDigest(), + preparation.source().policyCarrierDigest() + }; + } + + private CanonicalPrivateFreshTargetSnapshot requireExactRetry( + Record row, + Request request, + Preparation preparation, + CanonicalRealmCatalogSnapshot sourceCatalog, + byte[] expectedRequestPreimage) { + CanonicalPrivateFreshTargetSnapshot snapshot = toSnapshot(row); + var source = preparation.source(); + var targetPolicy = source.targetPolicy(); + RealmEntryPolicy policy = targetPolicy.source().policy(); + if (!request.requestId().equals(snapshot.creationRequestId()) + || !request.preparationRequestId().equals(snapshot.preparationRequestId()) + || !request.playtestLifecycleId().equals(snapshot.playtestLifecycleId()) + || !Arrays.equals( + expectedRequestPreimage, row.get("private_target_request_preimage", byte[].class)) + || !preparation + .requestDigest() + .equals(row.get("private_preparation_request_digest", String.class)) + || !preparation.request().targetNamespace().equals(snapshot.targetNamespace()) + || !preparation.request().tenantId().equals(snapshot.tenantId()) + || !preparation.request().worldSlug().equals(snapshot.worldSlug()) + || !preparation.request().realmSlug().equals(snapshot.realmSlug()) + || !preparation.playableStateNamespaceId().equals(snapshot.playableStateNamespaceId()) + || preparation.playtestStateGeneration() != snapshot.playtestStateGeneration() + || !policy.realmDisplayName().equals(snapshot.realmDisplayName()) + || !policy.entryPolicy().name().equals(snapshot.characterCreationPolicy()) + || !targetPolicy.policyId().equals(snapshot.targetPolicyId()) + || !targetPolicy.policyDigest().equals(snapshot.targetPolicyDigest()) + || !source.canonicalVersionId().equals(snapshot.canonicalVersionId()) + || !source.publishedReleaseBundleRef().equals(snapshot.publishedReleaseBundleRef()) + || !source.publishedReleaseBundleDigest().equals(snapshot.publishedReleaseBundleDigest()) + || !sourceCatalog.realmId().equals(row.get("private_source_catalog_realm_id", UUID.class)) + || !sourceCatalog + .creationRequestId() + .equals(row.get("private_source_catalog_request_id", UUID.class)) + || sourceCatalog.catalogRevision() != row.get("private_source_catalog_revision", Long.class) + || !sourceCatalog + .receiptDigest() + .equals(row.get("private_source_catalog_receipt_digest", String.class))) { + throw new IdempotencyConflictException( + "Private FRESH catalog request conflicts with its exact retained preparation or outcome"); + } + return snapshot; + } + + private CanonicalPrivateFreshTargetSnapshot toSnapshot(Record row) { + try { + UUID requestId = required(row, "creation_request_id", UUID.class); + UUID preparationRequestId = required(row, "private_preparation_request_id", UUID.class); + UUID lifecycleId = required(row, "private_playtest_lifecycle_id", UUID.class); + String preparationDigest = required(row, "private_preparation_request_digest", String.class); + byte[] requestBytes = required(row, "private_target_request_preimage", byte[].class); + String requestDigest = required(row, "request_digest", String.class); + if (!Arrays.equals( + requestPreimage(requestId, preparationRequestId, lifecycleId, preparationDigest), + requestBytes) + || !digest(requestBytes).equals(requestDigest)) { + throw new InvalidPrivateTargetException( + "Private FRESH catalog request provenance does not match its immutable row"); + } + String receiptDigest = required(row, "receipt_digest", String.class); + if (!receiptDigest(row).equals(receiptDigest)) { + throw new InvalidPrivateTargetException( + "Private FRESH catalog outcome receipt does not match its immutable row"); + } + return new CanonicalPrivateFreshTargetSnapshot( + required(row, "target_namespace", String.class), + required(row, "canonical_tenant_id", UUID.class), + required(row, "world_slug", String.class), + required(row, "realm_slug", String.class), + required(row, "realm_id", UUID.class), + required(row, "realm_display_name", String.class), + Boolean.TRUE.equals(row.get("visible", Boolean.class)), + Boolean.TRUE.equals(row.get("public_production", Boolean.class)), + required(row, "state_scope", String.class), + required(row, "playable_state_namespace_id", UUID.class), + required(row, "character_creation_policy", String.class), + required(row, "catalog_revision", Long.class), + requestId, + requestDigest, + receiptDigest, + preparationRequestId, + lifecycleId, + required(row, "private_state_generation", Long.class), + "PREPARING", + required(row, "private_source_catalog_realm_id", UUID.class), + required(row, "private_target_policy_id", UUID.class), + required(row, "private_target_policy_digest", String.class), + required(row, "private_canonical_version_id", UUID.class), + required(row, "private_published_release_bundle_ref", String.class), + required(row, "private_published_release_bundle_digest", String.class)); + } catch (InvalidPrivateTargetException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidPrivateTargetException( + "Persisted private FRESH catalog target evidence is invalid", exception); + } + } + + private String receiptDigest(Record row) { + return digest( + receiptPreimage( + required(row, "creation_request_id", UUID.class), + required(row, "request_digest", String.class), + required(row, "target_namespace", String.class), + required(row, "canonical_tenant_id", UUID.class), + required(row, "tenant_slug", String.class), + required(row, "world_slug", String.class), + required(row, "realm_id", UUID.class), + required(row, "realm_slug", String.class), + required(row, "realm_display_name", String.class), + Boolean.TRUE.equals(row.get("visible", Boolean.class)), + Boolean.TRUE.equals(row.get("public_production", Boolean.class)), + required(row, "state_scope", String.class), + required(row, "playable_state_namespace_id", UUID.class), + required(row, "character_creation_policy", String.class), + required(row, "catalog_revision", Long.class), + required(row, "private_preparation_request_id", UUID.class), + required(row, "private_playtest_lifecycle_id", UUID.class), + required(row, "private_preparation_request_digest", String.class), + required(row, "private_state_generation", Long.class), + required(row, "private_source_catalog_realm_id", UUID.class), + required(row, "private_source_catalog_request_id", UUID.class), + required(row, "private_source_catalog_revision", Long.class), + required(row, "private_source_catalog_receipt_digest", String.class), + required(row, "private_target_policy_id", UUID.class), + required(row, "private_target_policy_digest", String.class), + required(row, "private_target_policy_source_commit_id", UUID.class), + required(row, "private_target_policy_source_revision_id", UUID.class), + required(row, "private_target_policy_logical_revision_id", String.class), + required(row, "private_canonical_version_id", UUID.class), + required(row, "private_published_release_bundle_ref", String.class), + required(row, "private_published_release_bundle_digest", String.class), + required(row, "private_source_policy_set_digest", String.class), + required(row, "private_source_policy_carrier_digest", String.class), + required(row, "source_intake_operation_id", UUID.class), + required(row, "source_intake_receipt_digest", String.class))); + } + + private static String receiptDigest( + UUID requestId, + Preparation preparation, + CanonicalRealmCatalogSnapshot sourceCatalog, + UUID realmId, + String requestDigest, + RealmEntryPolicy policy) { + IntakeReceipt intake = sourceCatalog.sourceIntakeReceipt(); + var source = intake.source(); + var sourceReference = preparation.source(); + var targetPolicy = sourceReference.targetPolicy(); + return digest( + receiptPreimage( + requestId, + requestDigest, + preparation.request().targetNamespace(), + preparation.request().tenantId(), + source.tenantSlug(), + preparation.request().worldSlug(), + realmId, + preparation.request().realmSlug(), + policy.realmDisplayName(), + false, + false, + RealmEntryPolicy.StateScope.ISOLATED.name(), + preparation.playableStateNamespaceId(), + policy.entryPolicy().name(), + INITIAL_CATALOG_REVISION, + preparation.request().requestId(), + preparation.playtestLifecycleId(), + preparation.requestDigest(), + preparation.playtestStateGeneration(), + sourceCatalog.realmId(), + sourceCatalog.creationRequestId(), + sourceCatalog.catalogRevision(), + sourceCatalog.receiptDigest(), + targetPolicy.policyId(), + targetPolicy.policyDigest(), + targetPolicy.source().commitId(), + targetPolicy.source().revisionId(), + targetPolicy.source().logicalRevisionId(), + sourceReference.canonicalVersionId(), + sourceReference.publishedReleaseBundleRef(), + sourceReference.publishedReleaseBundleDigest(), + sourceReference.policySetDigest(), + sourceReference.policyCarrierDigest(), + intake.operationId(), + intake.receiptDigest())); + } + + private static byte[] receiptPreimage( + UUID requestId, + String requestDigest, + String targetNamespace, + UUID tenantId, + String tenantSlug, + String worldSlug, + UUID realmId, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + String stateScope, + UUID playableStateNamespaceId, + String characterCreationPolicy, + long catalogRevision, + UUID preparationRequestId, + UUID lifecycleId, + String preparationRequestDigest, + long generation, + UUID sourceCatalogRealmId, + UUID sourceCatalogRequestId, + long sourceCatalogRevision, + String sourceCatalogReceiptDigest, + UUID targetPolicyId, + String targetPolicyDigest, + UUID policySourceCommitId, + UUID policySourceRevisionId, + String policyLogicalRevisionId, + UUID canonicalVersionId, + String releaseBundleRef, + String releaseBundleDigest, + String policySetDigest, + String policyCarrierDigest, + UUID sourceIntakeOperationId, + String sourceIntakeReceiptDigest) { + return framed( + RECEIPT_SCHEMA, + requestId.toString(), + requestDigest, + targetNamespace, + tenantId.toString(), + tenantSlug, + worldSlug, + realmId.toString(), + realmSlug, + realmDisplayName, + Boolean.toString(visible), + Boolean.toString(publicProduction), + stateScope, + playableStateNamespaceId.toString(), + characterCreationPolicy, + Long.toString(catalogRevision), + preparationRequestId.toString(), + lifecycleId.toString(), + preparationRequestDigest, + Long.toString(generation), + sourceCatalogRealmId.toString(), + sourceCatalogRequestId.toString(), + Long.toString(sourceCatalogRevision), + sourceCatalogReceiptDigest, + targetPolicyId.toString(), + targetPolicyDigest, + policySourceCommitId.toString(), + policySourceRevisionId.toString(), + policyLogicalRevisionId, + canonicalVersionId.toString(), + releaseBundleRef, + releaseBundleDigest, + policySetDigest, + policyCarrierDigest, + sourceIntakeOperationId.toString(), + sourceIntakeReceiptDigest); + } + + private static byte[] requestPreimage(Request request, String preparationDigest) { + return requestPreimage( + request.requestId(), + request.preparationRequestId(), + request.playtestLifecycleId(), + preparationDigest); + } + + private static byte[] requestPreimage( + UUID requestId, UUID preparationRequestId, UUID lifecycleId, String preparationDigest) { + return framed( + REQUEST_SCHEMA, + requestId.toString(), + preparationRequestId.toString(), + lifecycleId.toString(), + preparationDigest); + } + + private static byte[] framed(String... values) { + var out = new ByteArrayOutputStream(); + for (String value : values) DraftAuthorizationFenceBinding.frame(out, value); + return out.toByteArray(); + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private void requireWritableSerializableOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Private FRESH target allocation requires a writable owner transaction"); + } + dsl.connectionResult( + connection -> { + if (connection.getAutoCommit() + || connection.getTransactionIsolation() != Connection.TRANSACTION_SERIALIZABLE) { + throw new IllegalStateException( + "Private FRESH target allocation requires its owner SERIALIZABLE transaction"); + } + return null; + }); + Record isolationRow = dsl.fetchOne("SHOW transaction_isolation"); + if (isolationRow == null + || !"serializable".equalsIgnoreCase(isolationRow.get(0, String.class).trim())) { + throw new IllegalStateException( + "Private FRESH target allocation requires SERIALIZABLE isolation"); + } + Record readOnlyRow = dsl.fetchOne("SHOW transaction_read_only"); + if (readOnlyRow == null || !"off".equalsIgnoreCase(readOnlyRow.get(0, String.class).trim())) { + throw new IllegalStateException( + "Private FRESH target allocation requires a writable owner transaction"); + } + } + + private static void requireCommittedRead() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Private FRESH target projection requires committed owner readback"); + } + } + + private static T required(Record row, String field, Class type) { + T value = row.get(field, type); + if (value == null) + throw new InvalidPrivateTargetException("Missing private target field " + field); + return value; + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) throw new IllegalArgumentException(name + " must be non-nil"); + } + + public record Request(UUID requestId, UUID preparationRequestId, UUID playtestLifecycleId) { + public Request { + requireNonNil(requestId, "requestId"); + requireNonNil(preparationRequestId, "preparationRequestId"); + requireNonNil(playtestLifecycleId, "playtestLifecycleId"); + } + } + + public record Allocation(CanonicalPrivateFreshTargetSnapshot snapshot, boolean replayed) {} + + public static final class IdempotencyConflictException extends IllegalStateException { + public IdempotencyConflictException(String message) { + super(message); + } + } + + public static final class CatalogConflictException extends IllegalStateException { + public CatalogConflictException(String message) { + super(message); + } + } + + public static final class PreparationUnavailableException extends IllegalStateException { + public PreparationUnavailableException(String message) { + super(message); + } + } + + public static final class InvalidPrivateTargetException extends IllegalStateException { + public InvalidPrivateTargetException(String message) { + super(message); + } + + public InvalidPrivateTargetException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogRepository.java new file mode 100644 index 0000000000..367881b050 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogRepository.java @@ -0,0 +1,166 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamesession.GameSessionRuntimeFamilyCatalog; +import net.firedevops.firemud.common.gamesession.GameSessionRuntimeFamilyCatalog.Evidence; +import net.firedevops.firemud.common.gamesession.GameSessionRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.gamesession.GameSessionRuntimeFamilyCatalogCodec; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Manually composed local SQL capture and independent committed readback. No Spring registration, + * actor/peer fiction, gameplay allocation, private preparation, registry or pointer mutation. + * Dynamic SQL is confined to configured-schema PostgreSQL census and exact BYTEA evidence. The DSL + * must use a TransactionAwareDataSourceProxy over the same durable-primary data source as the + * transaction manager; unrelated or unbound DSL connections are not qualified composition. + */ +public final class GameSessionRuntimeFamilyCatalogRepository { + private final DSLContext dsl; + private final String schema; + private final String namespace; + private final TransactionTemplate capture; + private final TransactionTemplate readback; + + public GameSessionRuntimeFamilyCatalogRepository( + DSLContext dsl, PlatformTransactionManager transactions, String schema, String namespace) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + if (schema == null || !schema.matches("[a-z][a-z0-9_]{0,62}")) + throw new IllegalArgumentException("Fixed owner schema required"); + GameSessionRuntimeFamilyCatalog.requireNamespace(namespace); + this.schema = schema; + this.namespace = namespace; + capture = new TransactionTemplate(Objects.requireNonNull(transactions, "transactions")); + capture.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + capture.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + readback = new TransactionTemplate(transactions); + readback.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + readback.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + readback.setReadOnly(true); + } + + /** + * Commits an exact request snapshot, then independently reads it. Exact concurrent retries + * converge. + */ + public Evidence capture(Request request) { + requireIndependent(request); + byte[] committed = + capture.execute( + status -> { + var catalog = currentCatalog(); + byte[] requestBytes = GameSessionRuntimeFamilyCatalogCodec.requestBytes(request); + var proposed = new Evidence(request, UUID.randomUUID(), catalog); + byte[] evidenceBytes = GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(proposed); + dsl.execute( + "INSERT INTO " + + table("game_session_runtime_family_catalog_snapshot") + + " (read_request_id,target_namespace,request_bytes,request_digest,snapshot_id," + + "catalog_epoch,catalog_digest,evidence_bytes,evidence_digest) VALUES (?,?,?,?,?,?,?,?,?)" + + " ON CONFLICT (read_request_id) DO NOTHING", + request.readRequestId(), + request.targetNamespace(), + requestBytes, + GameSessionRuntimeFamilyCatalog.sha256(requestBytes), + proposed.snapshotId(), + catalog.catalogEpoch(), + catalog.digest(), + evidenceBytes, + proposed.digest()); + return retained(request, catalog); + }); + Evidence result = readExact(request); + if (!Arrays.equals(committed, GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(result))) + throw new CatalogConflictException("Committed Game Session catalog readback changed"); + return result; + } + + /** + * Independent retained primary read. Missing, changed or invalidated evidence never becomes + * empty. + */ + public Evidence readExact(Request request) { + requireIndependent(request); + return readback.execute( + status -> + GameSessionRuntimeFamilyCatalogCodec.evidenceFromStored( + retained(request, currentCatalog()))); + } + + private GameSessionRuntimeFamilyCatalog currentCatalog() { + Record row = + dsl.fetchOne( + "SELECT catalog_epoch,catalog_bytes,catalog_digest," + + schema + + ".gs_runtime_family_catalog_bytes(catalog_epoch) AS current_bytes FROM " + + table("game_session_runtime_family_catalog_epoch") + + " WHERE " + + schema + + ".gs_runtime_family_catalog_installed() ORDER BY catalog_epoch DESC LIMIT 1"); + if (row == null) throw new CatalogConflictException("No durable Game Session catalog epoch"); + byte[] sealed = row.get("catalog_bytes", byte[].class); + if (!Arrays.equals(sealed, row.get("current_bytes", byte[].class))) + throw new CatalogConflictException( + "Game Session schema/classification drift invalidates its epoch"); + var catalog = GameSessionRuntimeFamilyCatalog.fromStored(sealed); + if (catalog.catalogEpoch() != row.get("catalog_epoch", Long.class) + || !catalog.digest().equals(row.get("catalog_digest", String.class))) + throw new CatalogConflictException( + "Game Session catalog epoch/digest binding is inconsistent"); + return catalog; + } + + private byte[] retained(Request request, GameSessionRuntimeFamilyCatalog current) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + table("game_session_runtime_family_catalog_snapshot") + + " WHERE read_request_id=?", + request.readRequestId()); + if (row == null) + throw new CatalogConflictException("Exact Game Session catalog snapshot is absent"); + byte[] bytes = row.get("evidence_bytes", byte[].class); + Evidence result = GameSessionRuntimeFamilyCatalogCodec.evidenceFromStored(bytes); + byte[] requestBytes = GameSessionRuntimeFamilyCatalogCodec.requestBytes(request); + if (!request.equals(result.request()) + || !request.targetNamespace().equals(row.get("target_namespace", String.class)) + || !Arrays.equals(requestBytes, row.get("request_bytes", byte[].class)) + || !GameSessionRuntimeFamilyCatalog.sha256(requestBytes) + .equals(row.get("request_digest", String.class)) + || !result.snapshotId().equals(row.get("snapshot_id", UUID.class)) + || result.catalog().catalogEpoch() != row.get("catalog_epoch", Long.class) + || !result.catalog().digest().equals(row.get("catalog_digest", String.class)) + || !result.digest().equals(row.get("evidence_digest", String.class)) + || !Arrays.equals(current.exactBytes(), result.catalog().exactBytes())) + throw new CatalogConflictException( + "Changed request or invalidated Game Session catalog snapshot"); + return bytes; + } + + private String table(String name) { + return schema + "." + name; + } + + private void requireIndependent(Request request) { + Objects.requireNonNull(request, "request"); + if (!namespace.equals(request.targetNamespace())) + throw new CatalogConflictException("Wrong workload namespace"); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw new IllegalStateException("Catalog evidence requires independent owner transactions"); + } + + public static final class CatalogConflictException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + public CatalogConflictException(String message) { + super(message); + } + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V1056__private_fresh_catalog_preparation.sql b/services/game-session-service/src/main/resources/db/migration/V1056__private_fresh_catalog_preparation.sql new file mode 100644 index 0000000000..8d4e76fd5a --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1056__private_fresh_catalog_preparation.sql @@ -0,0 +1,346 @@ +-- A private FRESH catalog identity is a typed, non-public continuation of one exact retained +-- preparation. It remains PREPARING and creates no runtime or admission authority. +ALTER TABLE game_session_initial_playtest_preparations + ADD CONSTRAINT uq_gs_initial_playtest_private_catalog_binding + UNIQUE (request_id, playtest_lifecycle_id); + +ALTER TABLE game_session_canonical_realm_catalog + ADD COLUMN private_target_request_preimage BYTEA, + ADD COLUMN private_preparation_request_id UUID, + ADD COLUMN private_playtest_lifecycle_id UUID, + ADD COLUMN private_preparation_request_digest VARCHAR(71), + ADD COLUMN private_state_generation BIGINT, + ADD COLUMN private_source_catalog_realm_id UUID, + ADD COLUMN private_source_catalog_request_id UUID, + ADD COLUMN private_source_catalog_revision BIGINT, + ADD COLUMN private_source_catalog_receipt_digest VARCHAR(71), + ADD COLUMN private_target_policy_id UUID, + ADD COLUMN private_target_policy_digest VARCHAR(71), + ADD COLUMN private_target_policy_source_commit_id UUID, + ADD COLUMN private_target_policy_source_revision_id UUID, + ADD COLUMN private_target_policy_logical_revision_id VARCHAR(128), + ADD COLUMN private_canonical_version_id UUID, + ADD COLUMN private_published_release_bundle_ref VARCHAR(4096), + ADD COLUMN private_published_release_bundle_digest VARCHAR(71), + ADD COLUMN private_source_policy_set_digest VARCHAR(71), + ADD COLUMN private_source_policy_carrier_digest VARCHAR(71), + ADD CONSTRAINT fk_gs_private_fresh_catalog_preparation + FOREIGN KEY (private_preparation_request_id, private_playtest_lifecycle_id) + REFERENCES game_session_initial_playtest_preparations (request_id, playtest_lifecycle_id) + ON DELETE RESTRICT, + ADD CONSTRAINT fk_gs_private_fresh_catalog_source_catalog + FOREIGN KEY (target_namespace, private_source_catalog_realm_id) + REFERENCES game_session_canonical_realm_catalog (target_namespace, realm_id) + ON DELETE RESTRICT; + +ALTER TABLE game_session_canonical_realm_catalog + DROP CONSTRAINT chk_gs_canonical_realm_catalog_public_initial; +ALTER TABLE game_session_canonical_realm_catalog + DROP CONSTRAINT chk_gs_canonical_realm_catalog_names; + +ALTER TABLE game_session_canonical_realm_catalog + ADD CONSTRAINT chk_gs_canonical_realm_catalog_public_initial CHECK ( + (visible AND public_production AND private_preparation_request_id IS NULL + AND private_target_request_preimage IS NULL + AND private_playtest_lifecycle_id IS NULL) + OR (NOT visible AND NOT public_production AND state_scope = 'ISOLATED' + AND private_preparation_request_id IS NOT NULL + AND private_target_request_preimage IS NOT NULL + AND private_playtest_lifecycle_id IS NOT NULL) + ), + ADD CONSTRAINT chk_gs_canonical_realm_catalog_names CHECK ( + ( + ((private_preparation_request_id IS NULL + AND char_length(realm_display_name) BETWEEN 1 AND 100 + AND octet_length(realm_display_name) <= 400) + OR (private_preparation_request_id IS NOT NULL + AND char_length(realm_display_name) BETWEEN 1 AND 128 + AND octet_length(realm_display_name) <= 512)) + AND char_length(realm_display_name) BETWEEN 1 AND 128 + AND char_length(source_world_display_name) BETWEEN 1 AND 100 + AND octet_length(source_world_display_name) <= 400 + AND realm_display_name !~ '^[[:space:]]*$' + AND source_world_display_name !~ '^[[:space:]]*$' + ) + ); + +-- [jooq ignore start] +-- PostgreSQL bytea SHA-256 and wire-preimage predicates have no H2 DDL export equivalent. +-- The columns above remain visible to generation; physical PostgreSQL proof owns this check. +ALTER TABLE game_session_canonical_realm_catalog + ADD CONSTRAINT chk_gs_private_fresh_catalog_binding CHECK ( + (private_preparation_request_id IS NULL + AND private_target_request_preimage IS NULL + AND private_playtest_lifecycle_id IS NULL + AND private_preparation_request_digest IS NULL + AND private_state_generation IS NULL + AND private_source_catalog_realm_id IS NULL + AND private_source_catalog_request_id IS NULL + AND private_source_catalog_revision IS NULL + AND private_source_catalog_receipt_digest IS NULL + AND private_target_policy_id IS NULL + AND private_target_policy_digest IS NULL + AND private_target_policy_source_commit_id IS NULL + AND private_target_policy_source_revision_id IS NULL + AND private_target_policy_logical_revision_id IS NULL + AND private_canonical_version_id IS NULL + AND private_published_release_bundle_ref IS NULL + AND private_published_release_bundle_digest IS NULL + AND private_source_policy_set_digest IS NULL + AND private_source_policy_carrier_digest IS NULL) + OR + (private_preparation_request_id IS NOT NULL + AND private_target_request_preimage IS NOT NULL + AND octet_length(private_target_request_preimage) BETWEEN 1 AND 4096 + AND request_digest = 'sha256:' || encode(sha256(private_target_request_preimage), 'hex') + AND private_playtest_lifecycle_id IS NOT NULL + AND private_preparation_request_digest IS NOT NULL + AND private_preparation_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND private_state_generation IS NOT NULL + AND private_state_generation = 1 + AND private_source_catalog_realm_id IS NOT NULL + AND private_source_catalog_realm_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND private_source_catalog_request_id IS NOT NULL + AND private_source_catalog_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND private_source_catalog_revision IS NOT NULL + AND private_source_catalog_revision = 1 + AND private_source_catalog_receipt_digest IS NOT NULL + AND private_source_catalog_receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND private_target_policy_id IS NOT NULL + AND private_target_policy_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND private_target_policy_digest IS NOT NULL + AND private_target_policy_digest ~ '^sha256:[0-9a-f]{64}$' + AND private_target_policy_source_commit_id IS NOT NULL + AND private_target_policy_source_commit_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND private_target_policy_source_revision_id IS NOT NULL + AND private_target_policy_source_revision_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND private_target_policy_logical_revision_id IS NOT NULL + AND char_length(private_target_policy_logical_revision_id) BETWEEN 1 AND 128 + AND private_target_policy_logical_revision_id !~ '^[[:space:]]*$' + AND private_canonical_version_id IS NOT NULL + AND private_canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND private_published_release_bundle_ref IS NOT NULL + AND char_length(private_published_release_bundle_ref) BETWEEN 1 AND 1024 + AND octet_length(private_published_release_bundle_ref) <= 4096 + AND private_published_release_bundle_ref !~ '^[[:space:]]*$' + AND private_published_release_bundle_digest IS NOT NULL + AND private_published_release_bundle_digest ~ '^sha256:[0-9a-f]{64}$' + AND private_source_policy_set_digest IS NOT NULL + AND private_source_policy_set_digest ~ '^sha256:[0-9a-f]{64}$' + AND private_source_policy_carrier_digest IS NOT NULL + AND private_source_policy_carrier_digest ~ '^sha256:[0-9a-f]{64}$' + AND NOT visible AND NOT public_production AND state_scope = 'ISOLATED' + AND catalog_revision = 1 + AND realm_id <> private_source_catalog_realm_id + AND realm_id <> private_target_policy_id + AND realm_id <> private_playtest_lifecycle_id + AND realm_id <> playable_state_namespace_id + AND complete_policy_set_evidence IS NOT NULL + AND fixture_policy_request_bytes IS NULL + AND fixture_policy_seal_operation_id IS NULL + AND fixture_policy_seal_request_digest IS NULL + AND fixture_policy_seal_evidence_digest IS NULL) + ); +-- [jooq ignore stop] + +CREATE UNIQUE INDEX uq_gs_private_fresh_catalog_preparation + ON game_session_canonical_realm_catalog (private_preparation_request_id) + WHERE private_preparation_request_id IS NOT NULL; + +CREATE UNIQUE INDEX uq_gs_private_fresh_catalog_request + ON game_session_canonical_realm_catalog (creation_request_id) + WHERE private_preparation_request_id IS NOT NULL; + +-- [jooq ignore start] +CREATE FUNCTION require_game_session_private_fresh_catalog_target() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + preparation game_session_initial_playtest_preparations%ROWTYPE; + source game_session_canonical_realm_catalog%ROWTYPE; + fields TEXT[]; + item TEXT; + receipt_framed BYTEA := ''::BYTEA; +BEGIN + IF NEW.private_preparation_request_id IS NULL THEN + IF NEW.private_target_request_preimage IS NOT NULL + OR NEW.private_playtest_lifecycle_id IS NOT NULL + OR NEW.private_preparation_request_digest IS NOT NULL + OR NEW.private_state_generation IS NOT NULL + OR NEW.private_source_catalog_realm_id IS NOT NULL + OR NEW.private_source_catalog_request_id IS NOT NULL + OR NEW.private_source_catalog_revision IS NOT NULL + OR NEW.private_source_catalog_receipt_digest IS NOT NULL + OR NEW.private_target_policy_id IS NOT NULL + OR NEW.private_target_policy_digest IS NOT NULL + OR NEW.private_target_policy_source_commit_id IS NOT NULL + OR NEW.private_target_policy_source_revision_id IS NOT NULL + OR NEW.private_target_policy_logical_revision_id IS NOT NULL + OR NEW.private_canonical_version_id IS NOT NULL + OR NEW.private_published_release_bundle_ref IS NOT NULL + OR NEW.private_published_release_bundle_digest IS NOT NULL + OR NEW.private_source_policy_set_digest IS NOT NULL + OR NEW.private_source_policy_carrier_digest IS NOT NULL THEN + RAISE EXCEPTION 'Public canonical catalog row cannot carry private FRESH preparation provenance' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + SELECT * INTO STRICT preparation + FROM game_session_initial_playtest_preparations + WHERE request_id = NEW.private_preparation_request_id + AND playtest_lifecycle_id = NEW.private_playtest_lifecycle_id + FOR SHARE; + IF preparation.initialization_mode <> 'FRESH' + OR preparation.preparation_state <> 'PREPARING' + OR preparation.playtest_state_generation <> 1 + OR preparation.request_digest <> NEW.private_preparation_request_digest + OR preparation.target_namespace <> NEW.target_namespace + OR preparation.canonical_tenant_id <> NEW.canonical_tenant_id + OR preparation.world_slug <> NEW.world_slug + OR preparation.realm_slug <> NEW.realm_slug + OR preparation.playable_state_namespace_id <> NEW.playable_state_namespace_id + OR preparation.target_policy_public_production + OR NOT preparation.target_policy_visible + OR preparation.target_policy_state_scope <> 'ISOLATED' + OR preparation.target_policy_world_slug <> NEW.world_slug + OR preparation.target_policy_realm_slug <> NEW.realm_slug + OR preparation.target_policy_realm_display_name <> NEW.realm_display_name + OR preparation.target_policy_entry_policy <> NEW.character_creation_policy + OR preparation.source_catalog_realm_id <> NEW.private_source_catalog_realm_id + OR preparation.source_catalog_request_id <> NEW.private_source_catalog_request_id + OR preparation.source_catalog_revision <> NEW.private_source_catalog_revision + OR preparation.source_catalog_receipt_digest <> NEW.private_source_catalog_receipt_digest + OR preparation.source_intake_operation_id <> NEW.source_intake_operation_id + OR preparation.source_intake_receipt_digest <> NEW.source_intake_receipt_digest + OR preparation.source_operation_id <> NEW.source_operation_id + OR preparation.source_evidence_digest <> NEW.source_evidence_digest + OR preparation.target_policy_id <> NEW.private_target_policy_id + OR preparation.target_policy_digest <> NEW.private_target_policy_digest + OR preparation.target_policy_source_commit_id <> NEW.private_target_policy_source_commit_id + OR preparation.target_policy_source_revision_id <> NEW.private_target_policy_source_revision_id + OR preparation.target_policy_logical_revision_id <> NEW.private_target_policy_logical_revision_id + OR preparation.canonical_version_id <> NEW.private_canonical_version_id + OR preparation.published_release_bundle_ref <> NEW.private_published_release_bundle_ref + OR preparation.published_release_bundle_digest <> NEW.private_published_release_bundle_digest + OR preparation.source_policy_set_digest <> NEW.private_source_policy_set_digest + OR preparation.source_policy_carrier_digest <> NEW.private_source_policy_carrier_digest + OR NEW.private_target_request_preimage IS DISTINCT FROM ( + int4send(octet_length(convert_to('game-session-private-fresh-catalog-request/v1', 'UTF8'))) + || convert_to('game-session-private-fresh-catalog-request/v1', 'UTF8') + || int4send(octet_length(convert_to(NEW.creation_request_id::TEXT, 'UTF8'))) || convert_to(NEW.creation_request_id::TEXT, 'UTF8') + || int4send(octet_length(convert_to(NEW.private_preparation_request_id::TEXT, 'UTF8'))) || convert_to(NEW.private_preparation_request_id::TEXT, 'UTF8') + || int4send(octet_length(convert_to(NEW.private_playtest_lifecycle_id::TEXT, 'UTF8'))) || convert_to(NEW.private_playtest_lifecycle_id::TEXT, 'UTF8') + || int4send(octet_length(convert_to(NEW.private_preparation_request_digest, 'UTF8'))) || convert_to(NEW.private_preparation_request_digest, 'UTF8')) + OR NEW.realm_id = NEW.private_source_catalog_realm_id + OR NEW.realm_id = NEW.private_target_policy_id + OR NEW.realm_id = NEW.private_playtest_lifecycle_id + OR NEW.realm_id = NEW.playable_state_namespace_id + OR NEW.visible OR NEW.public_production OR NEW.state_scope <> 'ISOLATED' + OR NEW.catalog_revision <> 1 + OR NEW.complete_policy_set_evidence IS NULL + OR NEW.fixture_policy_request_bytes IS NOT NULL + OR NEW.fixture_policy_seal_operation_id IS NOT NULL + OR NEW.fixture_policy_seal_request_digest IS NOT NULL + OR NEW.fixture_policy_seal_evidence_digest IS NOT NULL THEN + RAISE EXCEPTION 'Private FRESH catalog row differs from its exact retained preparation' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO STRICT source + FROM game_session_canonical_realm_catalog + WHERE target_namespace = preparation.target_namespace + AND canonical_tenant_id = preparation.canonical_tenant_id + AND realm_id = preparation.source_catalog_realm_id + FOR SHARE; + IF NOT source.visible OR NOT source.public_production + OR source.complete_policy_set_evidence IS NULL + OR source.fixture_policy_request_bytes IS NOT NULL + OR source.fixture_policy_seal_operation_id IS NOT NULL + OR source.fixture_policy_seal_request_digest IS NOT NULL + OR source.fixture_policy_seal_evidence_digest IS NOT NULL + OR source.creation_request_id <> NEW.private_source_catalog_request_id + OR source.catalog_revision <> NEW.private_source_catalog_revision + OR source.receipt_digest <> NEW.private_source_catalog_receipt_digest + OR source.canonical_tenant_id <> preparation.canonical_tenant_id + OR source.world_slug <> preparation.world_slug + OR source.complete_policy_set_evidence IS DISTINCT FROM NEW.complete_policy_set_evidence + OR source.source_intake_operation_id <> NEW.source_intake_operation_id + OR source.source_intake_schema_version <> NEW.source_intake_schema_version + OR source.source_intake_request_id <> NEW.source_intake_request_id + OR source.source_intake_request_digest <> NEW.source_intake_request_digest + OR source.source_intake_receipt_digest <> NEW.source_intake_receipt_digest + OR source.source_schema_version <> NEW.source_schema_version + OR source.source_registration_request_id <> NEW.source_registration_request_id + OR source.source_operation_id <> NEW.source_operation_id + OR source.source_request_digest <> NEW.source_request_digest + OR source.source_world_display_name <> NEW.source_world_display_name + OR source.source_game_row_id <> NEW.source_game_row_id + OR source.source_game_tenant_key <> NEW.source_game_tenant_key + OR source.source_provenance_kind <> NEW.source_provenance_kind + OR source.source_evidence_digest <> NEW.source_evidence_digest + OR NEW.private_target_policy_source_commit_id = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.private_source_policy_carrier_digest <> 'sha256:' || encode(sha256(source.complete_policy_set_evidence), 'hex') THEN + RAISE EXCEPTION 'Private FRESH catalog source differs from exact retained Human publication evidence' + USING ERRCODE = '23514'; + END IF; + + fields := ARRAY[ + 'game-session-private-fresh-catalog-receipt/v1', NEW.creation_request_id::TEXT, + NEW.request_digest, NEW.target_namespace, NEW.canonical_tenant_id::TEXT, NEW.tenant_slug, + NEW.world_slug, NEW.realm_id::TEXT, NEW.realm_slug, NEW.realm_display_name, + NEW.visible::TEXT, NEW.public_production::TEXT, NEW.state_scope, + NEW.playable_state_namespace_id::TEXT, NEW.character_creation_policy, + NEW.catalog_revision::TEXT, NEW.private_preparation_request_id::TEXT, + NEW.private_playtest_lifecycle_id::TEXT, NEW.private_preparation_request_digest, + NEW.private_state_generation::TEXT, NEW.private_source_catalog_realm_id::TEXT, + NEW.private_source_catalog_request_id::TEXT, NEW.private_source_catalog_revision::TEXT, + NEW.private_source_catalog_receipt_digest, NEW.private_target_policy_id::TEXT, + NEW.private_target_policy_digest, NEW.private_target_policy_source_commit_id::TEXT, + NEW.private_target_policy_source_revision_id::TEXT, + NEW.private_target_policy_logical_revision_id, NEW.private_canonical_version_id::TEXT, + NEW.private_published_release_bundle_ref, NEW.private_published_release_bundle_digest, + NEW.private_source_policy_set_digest, NEW.private_source_policy_carrier_digest, + NEW.source_intake_operation_id::TEXT, NEW.source_intake_receipt_digest]; + FOREACH item IN ARRAY fields LOOP + receipt_framed := receipt_framed || int4send(octet_length(convert_to(item, 'UTF8'))) || convert_to(item, 'UTF8'); + END LOOP; + IF NEW.receipt_digest <> 'sha256:' || encode(sha256(receipt_framed), 'hex') THEN + RAISE EXCEPTION 'Private FRESH catalog receipt digest differs from its persisted outcome' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER game_session_private_fresh_catalog_target_guard + BEFORE INSERT ON game_session_canonical_realm_catalog + FOR EACH ROW EXECUTE FUNCTION require_game_session_private_fresh_catalog_target(); + +CREATE FUNCTION game_session_private_fresh_catalog_commit_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE preparation game_session_initial_playtest_preparations%ROWTYPE; +BEGIN + IF NEW.private_preparation_request_id IS NULL THEN + RETURN NULL; + END IF; + SELECT * INTO STRICT preparation + FROM game_session_initial_playtest_preparations + WHERE request_id = NEW.private_preparation_request_id + AND playtest_lifecycle_id = NEW.private_playtest_lifecycle_id; + IF preparation.fork_expiry_second + preparation.fork_expiry_nano / 1000000000.0 + <= extract(epoch FROM clock_timestamp()) THEN + RAISE EXCEPTION 'Private FRESH catalog preparation expired before final catalog commit' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER game_session_private_fresh_catalog_commit_guard + AFTER INSERT ON game_session_canonical_realm_catalog + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION game_session_private_fresh_catalog_commit_guard(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V1057__game_session_owner_runtime_family_catalog.sql b/services/game-session-service/src/main/resources/db/migration/V1057__game_session_owner_runtime_family_catalog.sql new file mode 100644 index 0000000000..e0aa562aac --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1057__game_session_owner_runtime_family_catalog.sql @@ -0,0 +1,417 @@ +-- Additive local source only. Preserve all payload, original operations, guards and sequences. +CREATE TABLE game_session_runtime_family_classification ( + family_id VARCHAR(127) PRIMARY KEY, + relation_name VARCHAR(63) NOT NULL, + component_name VARCHAR(63) NOT NULL DEFAULT '', + family_role VARCHAR(32) NOT NULL CHECK (family_role IN + ('RUNTIME_PAYLOAD','SOURCE','CONTROL','AUDIT','PROVENANCE','CATALOG')), + state_class VARCHAR(16) NOT NULL CHECK (state_class IN ('UNKNOWN','UNRESOLVED','NOT_PAYLOAD')), + fresh_disposition VARCHAR(48) NOT NULL CHECK (fresh_disposition IN + ('STATE_CLASS_UNKNOWN_BLOCKING','UNSUPPORTED_SOURCE_BLOCKING','RUNTIME_EVIDENCE_BLOCKING', + 'SOURCE_ONLY','CONTROL_ONLY','AUDIT_ONLY','PROVENANCE_ONLY','CATALOG_ONLY')), + retention_disposition VARCHAR(32) NOT NULL CHECK (retention_disposition IN + ('OWNER_POLICY_RETAINED','UNRESOLVED_RETAINED','IMMUTABLE_RETAINED')), + owner_consequence VARCHAR(1024) NOT NULL, + UNIQUE (relation_name, component_name), + CHECK (relation_name ~ '^[a-z][a-z0-9_]{0,62}$'), + CHECK (component_name = '' OR component_name ~ '^[a-z][a-z0-9_]{0,62}$'), + CHECK (family_id = relation_name || CASE WHEN component_name = '' THEN '' ELSE '.' || component_name END), + CHECK ( + (fresh_disposition='STATE_CLASS_UNKNOWN_BLOCKING' AND family_role='RUNTIME_PAYLOAD' AND state_class='UNKNOWN') + OR (fresh_disposition='UNSUPPORTED_SOURCE_BLOCKING' AND family_role='SOURCE' AND state_class='UNRESOLVED') + OR (fresh_disposition='RUNTIME_EVIDENCE_BLOCKING' AND family_role IN ('CONTROL','AUDIT','PROVENANCE') AND state_class='NOT_PAYLOAD') + OR (fresh_disposition='SOURCE_ONLY' AND family_role='SOURCE' AND state_class='NOT_PAYLOAD') + OR (fresh_disposition='CONTROL_ONLY' AND family_role='CONTROL' AND state_class='NOT_PAYLOAD') + OR (fresh_disposition='AUDIT_ONLY' AND family_role='AUDIT' AND state_class='NOT_PAYLOAD') + OR (fresh_disposition='PROVENANCE_ONLY' AND family_role='PROVENANCE' AND state_class='NOT_PAYLOAD') + OR (fresh_disposition='CATALOG_ONLY' AND family_role='CATALOG' AND state_class='NOT_PAYLOAD') + ), + CHECK (family_role <> 'CATALOG' OR retention_disposition='IMMUTABLE_RETAINED') +); + +-- Known limitations only. These rows do not claim an exhaustive Redis key census. +CREATE TABLE game_session_runtime_catalog_non_sql_gap ( + gap_id VARCHAR(48) PRIMARY KEY CHECK (gap_id IN + ('CURRENT_PIN_PROJECTION','ISSUER_AND_ACCOUNT_INDEX_CUSTODY','LEGACY_QUEUE_CLUSTER_SCOPE', + 'REGION_TIMELINE_AND_LEASE','SESSION_CONTROLLER_AND_REPLAY','VOLATILE_STAGE_RECOVERY')), + disposition VARCHAR(32) NOT NULL CHECK (disposition IN ('UNRESOLVED_BLOCKING','UNSUPPORTED_BLOCKING')), + owner_consequence VARCHAR(1024) NOT NULL +); + +CREATE TABLE game_session_runtime_family_catalog_epoch ( + catalog_epoch BIGINT PRIMARY KEY CHECK (catalog_epoch > 0), + catalog_bytes BYTEA NOT NULL CHECK (octet_length(catalog_bytes) BETWEEN 1 AND 2097152), + catalog_digest VARCHAR(71) NOT NULL CHECK (catalog_digest = 'sha256:' || encode(sha256(catalog_bytes), 'hex')), + installed_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); + +CREATE TABLE game_session_runtime_family_catalog_snapshot ( + read_request_id UUID PRIMARY KEY CHECK (read_request_id <> '00000000-0000-0000-0000-000000000000'), + target_namespace VARCHAR(63) NOT NULL CHECK (target_namespace ~ '^[a-z0-9]([-a-z0-9]*[a-z0-9])?$'), + request_bytes BYTEA NOT NULL CHECK (octet_length(request_bytes) BETWEEN 1 AND 1024), + request_digest VARCHAR(71) NOT NULL CHECK (request_digest = 'sha256:' || encode(sha256(request_bytes), 'hex')), + snapshot_id UUID NOT NULL UNIQUE CHECK (snapshot_id <> '00000000-0000-0000-0000-000000000000'), + catalog_epoch BIGINT NOT NULL REFERENCES game_session_runtime_family_catalog_epoch(catalog_epoch), + catalog_digest VARCHAR(71) NOT NULL, + evidence_bytes BYTEA NOT NULL CHECK (octet_length(evidence_bytes) BETWEEN 1 AND 2101248), + evidence_digest VARCHAR(71) NOT NULL CHECK (evidence_digest = 'sha256:' || encode(sha256(evidence_bytes), 'hex')), + retained_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); + +-- POSIX control-character behavior is PostgreSQL-only, not an H2 simulation. +-- [jooq ignore start] +ALTER TABLE game_session_runtime_family_classification ADD CONSTRAINT ck_gs_runtime_family_consequence + CHECK (length(btrim(owner_consequence)) > 0 AND owner_consequence !~ '[[:cntrl:]]'); +ALTER TABLE game_session_runtime_catalog_non_sql_gap ADD CONSTRAINT ck_gs_runtime_gap_consequence + CHECK (length(btrim(owner_consequence)) > 0 AND owner_consequence !~ '[[:cntrl:]]'); +-- [jooq ignore stop] + +-- Explicit current dispositions, not a CREATE-only union or a prefix exclusion. +INSERT INTO game_session_runtime_family_classification + (family_id,relation_name,family_role,state_class,fresh_disposition,retention_disposition,owner_consequence) +VALUES + ('gameplay_command','gameplay_command','RUNTIME_PAYLOAD','UNKNOWN','STATE_CLASS_UNKNOWN_BLOCKING','UNRESOLVED_RETAINED', + 'Admitted command payload mixes original identity, declared effects and replay result. ADR0122 namespace partition/class and complete durable-first recovery are missing; no inherited command or default S3.'), + ('remote_followup','remote_followup','RUNTIME_PAYLOAD','UNKNOWN','STATE_CLASS_UNKNOWN_BLOCKING','UNRESOLVED_RETAINED', + 'Pending remote work and payload retain exact origin/target/effect lineage. Complete namespace/pin/final-effect proof and owner replacement class are unresolved; never clone or discard uncertain work.'), + ('game_manifest','game_manifest','SOURCE','UNRESOLVED','UNSUPPORTED_SOURCE_BLOCKING','UNRESOLVED_RETAINED', + 'Unsupported legacy unqualified version/description rows lack tenant and canonical version lineage. Not build or FRESH authority. Stop old writers and inventory/map retained data before any removal.'); + +INSERT INTO game_session_runtime_family_classification + (family_id,relation_name,family_role,state_class,fresh_disposition,retention_disposition,owner_consequence) +SELECT relation_name,relation_name,family_role,'NOT_PAYLOAD','RUNTIME_EVIDENCE_BLOCKING','UNRESOLVED_RETAINED',consequence +FROM (VALUES + ('game_instances','CONTROL','Concrete execution/status/version row, not durable playable namespace. Stable namespace/scope and genuine private runtime production remain missing; existing public SHARED launch is not private FRESH.'), + ('feature_flag','CONTROL','Tenant runtime overrides remain operator control, not cloned build defaults or player payload. Genuine protected operator mutation and target-scoped applicability remain separate.'), + ('script_pin_operation','CONTROL','Exact atomic pin request/result ledger remains owner authority and retained replay history, never inherited target chronology. Complete bounded rollout history and private runtime binding remain gaps.'), + ('runtime_region_status','CONTROL','Legacy instance/region execution projection is not namespace identity. Retain its epoch/fence and unresolved work; no new timeline or reset inferred from catalog capture.'), + ('game_session_region_runtime_status','CONTROL','Canonical region timeline/executor source retains current runtime and original protected completion guards. Private runtime/source qualification remains absent; do not allocate a region from schema evidence.'), + ('game_session_region_timeline_preparation','PROVENANCE','Original non-admitting timeline initialization and actual lease/readback provenance, including created/preseeded origin, remain retained. INITIALIZING absence never permits a new timeline or private readiness.'), + ('tick_batch','PROVENANCE','Durable batch and selected-work recovery manifest are not FRESH manifests. Namespace and evidence-qualified replay/abandon/re-drive remain incomplete; preserve all nonterminal and restore-reachable lineage under ADR0163.'), + ('tick_effect','PROVENANCE','Original mutation identity and enclosing batch lineage survive reconciliation. No S3 or terminality follows from age, stale fence or technical failure; complete namespace/participant guards remain gaps.'), + ('remote_command_coordinator','CONTROL','Durable result/timeout arbitration and origin/target identity are retained authority, not gameplay initialization. Namespace and complete serialization/late-result compensation proof remain unresolved.'), + ('remote_followup_result','PROVENANCE','Retain original remote result/late-result/replay lineage and terminal immutability. This is not a new playtest result; complete namespace, timeout arbitration and compensation proof remain gaps.'), + ('player_command_history','AUDIT','Private accepted input history is not copied to a playtest. Current per-instance rows lack namespace, policy generation, maximum-age and purge convergence; existing rows remain retained under owning privacy policy.'), + ('resume_transcript_entry','AUDIT','Semantic reconnect context is distinct from input history and credentials. Namespace, durable resume episode/generation and logout invalidation remain incomplete; never clone or infer valid resume from retained text.'), + ('prepared_version_upgrade','CONTROL','Retained version/remap/participant preparation is not complete namespace-qualified owner validation or mapping application. Preserve original outcome; no pointer mutation or cleanup follows.') +) AS dispositions(relation_name,family_role,consequence); + +-- Each authority/control family is deliberately named, including installed Saga and old cohorts. +INSERT INTO game_session_runtime_family_classification + (family_id,relation_name,family_role,state_class,fresh_disposition,retention_disposition,owner_consequence) +SELECT relation_name,relation_name,'CONTROL','NOT_PAYLOAD','CONTROL_ONLY','OWNER_POLICY_RETAINED',consequence +FROM (VALUES + ('player_command_history_retention_sweep_state','Bounded sweep cursor only; preserve policy and holds. Catalog capture grants no cleanup or privacy-erasure authority.'), + ('gameplay_tenant_shared_playable_state_namespace','Retained legacy tenant namespace assignment, not a caller-selected replacement namespace or complete canonical runtime binding.'), + ('gameplay_admission_pointer_identity_backfill_issue','Retained unresolved identity repair issues block qualification; never treat a missing current route as safe removal.'), + ('gameplay_initial_admission_bind_catalog','Original legacy initial-bind catalog provenance and retention guards remain separate from canonical private preparation.'), + ('gameplay_initial_admission_bind_attempt','Original request/digest/hold terminal and replay guards remain unchanged. Absence/PENDING is never abort or private authorization.'), + ('game_session_retained_tenant_association','Original legacy tenant association custody; no tenant allocation or namespace authority is inferred from numeric keys.'), + ('game_session_retained_tenant_association_legal_hold','Retained legal hold is not gameplay state. Existing hold/release predicates cannot be bypassed by per-mode exclusion.'), + ('gameplay_published_realm_catalog_identity','Original published realm identity allocation is control evidence; do not clone or reinterpret it as a private target.'), + ('gameplay_published_tenant_shared_playable_state_namespace','Published shared namespace source remains immutable under its owner; no new namespace or scope is allocated here.'), + ('game_session_canonical_realm_catalog','Unique canonical realm catalog authority. Includes V1056 private PREPARING projection and original public source; no private runtime, manifest or CLOSED readiness is implied.'), + ('game_session_tenant_scope_reservation','Exact private numeric tenant-key reservation and old source guards remain retained. Numeric execution/source keys are not canonical tenant or playable namespace identity.'), + ('game_session_tenant_canonical_claim','Retained canonical-to-private-key claim is owner custody, not caller authority or a runtime initializer.'), + ('game_session_canonical_closed_admission_pointer_request','Immutable original CLOSED request/catalog/audit result belongs to the existing pointer owner. Public initial CLOSED is not private aggregation; no second pointer is introduced.'), + ('game_session_canonical_initial_admission_attempt','Original protected/unprotected admission attempt and terminal guards stay retained; never fabricate Human StartSession or adopt a predecessor as new protection.'), + ('game_session_canonical_initial_admission_intent','Original intent/World hold bytes and Account protection are retained before dispatch. No new actor, hold, credential or admission is issued.'), + ('gameplay_admission_pointer','Existing canonical pointer plus legacy rows remain sole routing authority. Capture never changes pointerVersion/catalogRevision, opens admission or aggregates private evidence.'), + ('game_session_start_session_operator_attempt','Original owner request, nonce, exact actor/reference/redemption and monotonic fence remain retained. Expired or uncertain claim cannot rearm or become FRESH authority.'), + ('game_session_initial_gameplay_login_journal','Original LOGIN request/context/token witness/abandonment/disposal guards remain held. No credential, session, replay authority or live socket custody is copied.'), + ('game_session_canonical_roster_selection','Original account/session/full-target selection, Entity nonce and immutable receipt remain retained. No actor allocation or manifest is inferred from roster attestation.'), + ('game_session_canonical_roster_target_fences','Exact shared reference-admission/retirement fence and captured replay horizons remain authoritative. Age or empty queries never release references.'), + ('game_session_canonical_roster_retirement_transfers','Original retirement/Entity ACK/confirmation lineage survives original removal through existing horizons and holds; catalog evidence grants no disposal.'), + ('game_session_canonical_binding_inventory_clock','Monotonic inventory source revision is not a catalog epoch or permission to create bindings; retain existing lock order and writer exclusion.'), + ('game_session_canonical_binding_generation','Namespace/controller generation allocation is retained authority, not copied sessions or playtestStateGeneration.'), + ('game_session_canonical_gameplay_binding_inventory','Original controller binding/account/full-target and candidate/final receipts remain guarded. No active binding or credentials are cloned.'), + ('game_session_canonical_binding_transition','Original NEW candidate, lease, irreversible abandonment, negative settlement and final receipt remain exact replay evidence, not FRESH initialization.'), + ('game_session_canonical_binding_account_index_obligation','Original cross-slot account repair obligation and acknowledgement remain retained until existing closure/retention predicates hold.'), + ('game_session_canonical_issuer_partition_reservation','Original issuer capacity reservation/fence remains immutable custody; no active session, release or retirement is implied.'), + ('game_session_canonical_binding_issuer_index_obligation','Exact issuer repair/release/retirement obligation remains linked to original binding and current fence. No inherited index membership.'), + ('game_session_canonical_binding_region_bridge_obligation','Original region bridge and created/preseeded source/abort lineage remain retained. No new placement, lease or admitting ACK is fabricated.'), + ('game_session_canonical_binding_legacy_disposition','Explicit held legacy-cohort disposition remains required; empty SQL inventory alone is not complete Redis migration proof.'), + ('game_session_canonical_account_coverage_control','Account-wide control/protection is not payload or Account authority generation. Existing current-operation and no-active-source predicates remain guarded.'), + ('game_session_canonical_account_coverage_operation','Original account coverage operation/fence/cohort and readback remain retained; no release from elapsed time.'), + ('game_session_canonical_account_coverage_snapshot_inventory','Frozen account inventory cohort is original-operation recovery evidence, not current session authority or runtime family enumeration.'), + ('game_session_canonical_account_coverage_snapshot_transition','Frozen original transition cohort retains exact generations and target; no cloned controllers.'), + ('game_session_canonical_account_coverage_snapshot_obligation','Frozen account obligation evidence survives supported replay/restore; no synthetic completion.'), + ('game_session_canonical_account_coverage_snapshot_reservation','Frozen issuer reservation cohort remains protected by original account operation and fence.'), + ('gs_canonical_account_coverage_snapshot_issuer_obligation','Actual V34.2 renamed issuer-obligation cohort retains original operation lineage; old CREATE spelling is not a live table.'), + ('gs_canonical_account_coverage_snapshot_region_obligation','Actual V34.2 renamed region-obligation cohort remains retained; no initial region or private runtime is established.'), + ('game_session_canonical_account_index_acknowledgement','Exact Account-purpose acknowledgement remains distinct from issuer binding-local ACK and final admitting CAS.'), + ('game_session_canonical_legacy_migration_operation','Original durable migration operation/fence phases remain retained; no legacy source adoption, reset or gameplay enablement.'), + ('game_session_canonical_legacy_migration_source_snapshot_entry','Frozen source-key cohort is non-authorizing recovery evidence. No secret values, new authority or complete Redis inventory is inferred.'), + ('game_session_canonical_account_member_repair_control','Cross-slot account member repair ordering/counter remains owner-local control, not Account-owned identity or global admission.'), + ('game_session_canonical_account_member_repair_operation','Original ADD_OR_RETAIN/physical ACK evidence remains linked to candidate; account member write alone never admits gameplay.'), + ('game_session_canonical_account_admission_fence_intent','Original acquisition intent and protected source remain held before any CLOSED install. Historical receipt is not current fence coverage.'), + ('game_session_canonical_account_admission_fence_intent_cohort_ro','Actual PostgreSQL-truncated V1027 cohort table retains original acquisition membership; no fabricated untruncated relation.'), + ('game_session_canonical_account_admission_fence_intent_barrier_t','Actual PostgreSQL-truncated V1027 target table retains REQUIRED targets and original barrier evidence; absence never completes coverage.'), + ('game_session_canonical_tenant_gameplay_tag','Opaque SQL-owned Redis slot mapping is topology only, not tenant authority, playable namespace or permission to read/write keys.'), + ('game_session_canonical_account_closed_barrier_receipt','Exact original CLOSED physical receipt is historical AS-OF evidence, not current protected incarnation or account-wide release authority.'), + ('game_session_canonical_issuer_layout_bootstrap_intent','Original finite issuer layout/cohort intent remains held; it is not installed anchor, current coverage or admission.'), + ('game_session_canonical_issuer_layout_bootstrap_control','Issuer layout source control and exact initial operation remain retained separately from live admission control.'), + ('game_session_canonical_issuer_layout_bootstrap_cohort_row','Frozen issuer cohort binds exact original inventory source; no static or empty registry completeness is inferred.'), + ('game_session_canonical_issuer_partition_build_plan','Original partition plan and layout identity remain immutable recovery evidence; no physical Redis execution or anchor installation.'), + ('game_session_canonical_issuer_partition_build_cohort_row','Partition cohort preserves exact original source row/digest and finite member enumeration, not runtime owner enrollment.'), + ('game_session_canonical_issuer_partition_build_member_work','Original per-member physical work remains pending until native exact readback. No cloned active session or synthetic completion.'), + ('game_session_canonical_issuer_partition_build_blocker','Retained unsupported/unresolved partition member blockers cannot be waived by omission or catalog classification.'), + ('game_session_canonical_issuer_bootstrap_member_op_counter','Monotonic member-operation generation counter remains unchanged; not a playable generation or catalog epoch.'), + ('game_session_canonical_issuer_bootstrap_member_operation','Original schema-v2 bootstrap member bytes and native receipt remain retained; shape-valid data is not current issuer authority.'), + ('game_session_canonical_issuer_bootstrap_partition_proof','Exact finite physical partition proof is retained installation evidence; no later-commit currentness or environment custody is granted.'), + ('game_session_canonical_issuer_bootstrap_coverage_counter','Original coverage allocator remains monotonic and retained; no new issuer coverage is manufactured.'), + ('game_session_canonical_issuer_installed_anchor','Original locally installed issuer anchor requires independent current source/incarnation checks; not a generic authorization capability.'), + ('game_session_canonical_issuer_binding_local_operation','Original ordinary NEW local issuer registration and current membership references remain retained; no default registration or active binding clone.'), + ('game_session_canonical_issuer_binding_local_release_operation','Original exact source-linked terminal release receipt remains separate from physical retirement; catalog capture cannot release capacity.'), + ('game_session_canonical_issuer_partition_mutation_head','Current partition revision/head is an execution fence with original lineage, not a second issuer authority or new catalog epoch.'), + ('game_session_canonical_issuer_partition_mutation','Immutable expected/successor physical partition mutation lineage remains exact under retry and restore.'), + ('game_session_canonical_issuer_binding_local_retirement','Original physical retirement retains exact release, capacity and partition fence; no new retention or cleanup permission.'), + ('game_session_canonical_issuer_bootstrap_supersession','Original stale-bootstrap supersession preserves displaced source and proof; no silent anchor adoption.'), + ('game_session_canonical_issuer_current_local_operation','Current membership reference is separate from retained operations. Removal requires exact existing retirement proof; no history deletion.'), + ('game_session_canonical_issuer_binding_local_ack_gen_counter','Separate binding-local acknowledgement allocator remains exact and monotonic; not Account coverage or lifecycle generation.'), + ('game_session_canonical_issuer_binding_local_acknowledgement','Exact original local ACK binds reservation, anchor, physical field set and currentness; no actor authority or FRESH result.'), + ('game_session_canonical_issuer_admission_epoch_counter','Distinct live issuer barrier epoch allocator remains unchanged; no catalog epoch or reset authority.'), + ('game_session_canonical_issuer_admission_control','Current issuer OPEN/cutoff control requires protected source/incarnation and original operation; schema evidence cannot open or release it.'), + ('game_session_canonical_issuer_admission_operation','Original live issuer cutoff/initial-anchor operation retains exact checkpoint and frozen cohort; no synthetic currentness.'), + ('game_session_canonical_issuer_admission_cohort_row','Exact frozen live-control cohort/digest is original authority evidence, not gameplay payload or global owner registry.'), + ('game_session_canonical_issuer_admission_initializer','Original one-key tenant initializer retains exact OPEN payload before dispatch; preparation alone never proves installation.'), + ('game_session_canonical_issuer_admission_initializer_receipt','Exact original OPEN readback receipt is retained as installation evidence, not current admission or stable-incarnation custody.'), + ('game_session_canonical_issuer_admission_cutoff_target','Frozen REQUIRED/CLOSED cutoff target and original physical postimage remain protected; missing targets never imply completion.'), + ('game_session_canonical_initial_account_barrier_initializer','Original LOGIN-bound INITIAL-only barrier source remains distinct from account-wide acquisition; no token, lease or finalization authority.'), + ('game_session_canonical_initial_account_barrier_target','Original never-dispatched/dispatch-possible/OPEN-installed target retains protected observation and exact readback; no target retargeting.'), + ('game_session_direct_text_authenticated_lobby_scope','Original pre-admission LOGIN-linked lobby scope retains verified witness, not credentials or live transport custody. Capacity and lawful release remain held.'), + ('game_session_direct_text_authenticated_lobby_current','Current lobby UI selection cannot erase older uncertain JOIN originals or authorize tenant admission.'), + ('game_session_direct_text_authenticated_lobby_join','Original frozen JOIN request/reply and uncertain dispatch remain immutable under existing parent abandonment/retention guards.'), + ('game_session_initial_playtest_preparations','V1054 exact FRESH lifecycle/namespace/generation-one policy/build preparation remains PREPARING, non-admissible and retained; not a private runtime or manifest.'), + ('game_session_private_playtest_selections','V1055 immutable selection CAS receipt retains original preparation and head revision; historical exact replay does not select a newer lifecycle.'), + ('game_session_current_private_playtests','V1055 internal current-preparation head is not admission pointer or player catalog. PREPARING remains invisible, never CLOSED or ready.'), + ('saga_instance','Installed adopter-local Saga control state remains under existing owner retention; not gameplay payload, Temporal lifecycle authority or FRESH enrollment.'), + ('saga_step','Installed Saga step/recovery lineage follows its parent and supported retry/restore obligations; no cloning or cleanup permission.') +) AS dispositions(relation_name,consequence); + +INSERT INTO game_session_runtime_family_classification + (family_id,relation_name,family_role,state_class,fresh_disposition,retention_disposition,owner_consequence) +SELECT relation_name,relation_name,family_role,'NOT_PAYLOAD',fresh_disposition,'OWNER_POLICY_RETAINED',consequence +FROM (VALUES + ('game_session_retained_tenant_association_payload','PROVENANCE','PROVENANCE_ONLY','Original retained identity-bearing payload remains under purpose/hold policy; not copied active authority or unbounded retention permission.'), + ('gameplay_published_realm_catalog_snapshot','SOURCE','SOURCE_ONLY','Immutable complete published policy snapshot is source evidence, not runtime initialization or owner manifest.'), + ('gameplay_published_realm_catalog_entry','SOURCE','SOURCE_ONLY','Exact retained published entry keeps original source lineage; no mutable runtime state or private admission is inferred.'), + ('game_session_authored_world_tenant_source_binding','SOURCE','SOURCE_ONLY','Original canonical tenant/world source binding belongs to the authored intake owner, not runtime allocation.'), + ('game_session_authored_world_source_intake','SOURCE','SOURCE_ONLY','Exact authenticated authored-world intake and receipt are retained upstream source evidence, not FRESH actor or materialization authority.'), + ('game_session_canonical_launch_preparation','PROVENANCE','PROVENANCE_ONLY','Retained exact descriptor resolve/readback is evidence-only preparation; no runtime, activation, pointer or admission effects.'), + ('game_session_fresh_tenant_association','PROVENANCE','PROVENANCE_ONLY','Original canonical-to-private tenant key association is retained custody; no tenant, runtime or namespace is allocated by this catalog.'), + ('game_session_canonical_instance_launch','PROVENANCE','PROVENANCE_ONLY','Original complete launch/runtime association remains public SHARED-only. Do not relabel Human StartSession or fixture provenance as private FRESH execution.'), + ('game_session_start_session_template_association_pin','SOURCE','SOURCE_ONLY','Original selected Game Design association pin prevents reselection under retry. It is not a new runtime authority or FRESH source operation.'), + ('game_session_start_session_launch_descriptor_pin','SOURCE','SOURCE_ONLY','Original immutable descriptor outcome remains tied to exact owner claim and association; no private manifest or current authorization.'), + ('gs_original_start_session_authored_actor_core_retention','SOURCE','SOURCE_ONLY','Original public authored-core result remains protected source lineage. No actor creation/assignment or private policy is inferred.'), + ('game_session_canonical_human_runtime_completion','PROVENANCE','PROVENANCE_ONLY','Original protected STARTING-to-RUNNING row versions and Account protection remain immutable provenance, not first OPEN or private runtime creation.'), + ('gameplay_admission_pointer_event','AUDIT','AUDIT_ONLY','Existing append-only pointer/catalog/attempt audit remains unchanged and retained. Source audit history is never cloned into active playtest authority.') +) AS dispositions(relation_name,family_role,fresh_disposition,consequence); + +-- Meaningful mixed components remain separate from whole-table control/recovery disposition. +INSERT INTO game_session_runtime_family_classification + (family_id,relation_name,component_name,family_role,state_class,fresh_disposition,retention_disposition,owner_consequence) +VALUES + ('game_instances.script_patch_version','game_instances','script_patch_version','CONTROL','NOT_PAYLOAD','CONTROL_ONLY','OWNER_POLICY_RETAINED','Game Session exact pin tuple is authority, not Automation observation. UNPINNED requires all tuple fields absent; no pin is generated for census.'), + ('game_instances.owner_account_id','game_instances','owner_account_id','PROVENANCE','NOT_PAYLOAD','PROVENANCE_ONLY','OWNER_POLICY_RETAINED','Legacy numeric owner projection is not Account identity, tenantAdmin authority or private playtest authorization.'), + ('gameplay_command.declared_effects_json','gameplay_command','declared_effects_json','PROVENANCE','NOT_PAYLOAD','RUNTIME_EVIDENCE_BLOCKING','UNRESOLVED_RETAINED','Retained declared-effect snapshot is narrower than complete immutable root/participant/digest and namespace allocation proof; do not manufacture a manifest.'), + ('gameplay_command.command_text','gameplay_command','command_text','RUNTIME_PAYLOAD','UNKNOWN','STATE_CLASS_UNKNOWN_BLOCKING','UNRESOLVED_RETAINED','Diagnostic/accepted command payload and correctness receipt have different ADR0163 minimization predicates; no blanket deletion or inheritance.'), + ('tick_batch.selected_work_manifest_json','tick_batch','selected_work_manifest_json','PROVENANCE','NOT_PAYLOAD','RUNTIME_EVIDENCE_BLOCKING','UNRESOLVED_RETAINED','This selected-work recovery document is not a FRESH mode manifest or shared source snapshot fence.'), + ('remote_followup.read_snapshot_token','remote_followup','read_snapshot_token','PROVENANCE','NOT_PAYLOAD','RUNTIME_EVIDENCE_BLOCKING','UNRESOLVED_RETAINED','Legacy owner read token is not complete handler input/causal-floor authority or cross-owner consistent snapshot.'), + ('game_session_canonical_realm_catalog.private_preparation_request_id','game_session_canonical_realm_catalog','private_preparation_request_id','PROVENANCE','NOT_PAYLOAD','PROVENANCE_ONLY','OWNER_POLICY_RETAINED','Actual V1056 private catalog branch retains exact V1054 preparation, policy/build, new realm UUID and commit-time expiry guard. PREPARING is not runtime/CLOSED.'), + ('game_session_canonical_binding_transition.admission_request_id','game_session_canonical_binding_transition','admission_request_id','CONTROL','NOT_PAYLOAD','CONTROL_ONLY','OWNER_POLICY_RETAINED','Original admission request/nonce/fence remains retained replay authority, not a mode-specific copied payload or new authorization.'); + +INSERT INTO game_session_runtime_family_classification + (family_id,relation_name,family_role,state_class,fresh_disposition,retention_disposition,owner_consequence) +SELECT relation_name,relation_name,'CATALOG','NOT_PAYLOAD','CATALOG_ONLY','IMMUTABLE_RETAINED',consequence +FROM (VALUES + ('game_session_runtime_family_classification','Exact explicit installed dispositions. Unknown class is blocking, not S3, owner enrollment or cleanup permission.'), + ('game_session_runtime_catalog_non_sql_gap','Known non-SQL gaps only, not a complete Redis inventory or fabricated SQL session/tick/lease rows.'), + ('game_session_runtime_family_catalog_epoch','Immutable monotonic local schema/classification/history seal, not a global registry revision or currentness through another commit.'), + ('game_session_runtime_family_catalog_snapshot','Immutable exact request/namespace/snapshot/catalog bytes and digests; no TTL, gameplay allocation, FRESH manifest or actor authority.') +) AS dispositions(relation_name,consequence); + +INSERT INTO game_session_runtime_catalog_non_sql_gap VALUES + ('CURRENT_PIN_PROJECTION','UNRESOLVED_BLOCKING','Redis current runtime/script projections do not replace durable Game Session pin authority; final exact tuple and full remote propagation remain separate. SQL census proves no Redis currentness.'), + ('ISSUER_AND_ACCOUNT_INDEX_CUSTODY','UNRESOLVED_BLOCKING','Manually composed SQL/Redis index, anchor, repair, release and retirement sources remain unregistered. Operational protected incarnation, Account source and complete index coverage/custody are not supplied.'), + ('LEGACY_QUEUE_CLUSTER_SCOPE','UNRESOLVED_BLOCKING','Live gamesession:tick and sessionctx key builders/multi-key scripts lack target tagged cluster-safe owner registration and exact reset/readback proof. This is not a full Redis inventory.'), + ('REGION_TIMELINE_AND_LEASE','UNRESOLVED_BLOCKING','Actual Redis timeline, tick metadata, executor lease and bridge state are outside SQL census. Original INITIALIZING ambiguity remains fenced; missing keys do not authorize reset/reinitialization.'), + ('SESSION_CONTROLLER_AND_REPLAY','UNRESOLVED_BLOCKING','Actual session:game/sessionctx, controller/index, credential and token replay state must not be cloned. Namespace migration, hidden recovery, private expiry and current Account authority remain separately qualified.'), + ('VOLATILE_STAGE_RECOVERY','UNSUPPORTED_BLOCKING','Live queue STAGED/pending Redis-first windows lack complete durable source-claim recovery. Missing batch/effect evidence is not proof of no application, target emptiness or safe S3 discard.'); + +-- PostgreSQL census/guards only; ordinary table DDL remains visible to jOOQ. +-- [jooq ignore start] +INSERT INTO game_session_runtime_family_classification + (family_id,relation_name,family_role,state_class,fresh_disposition,retention_disposition,owner_consequence) +VALUES ('${flyway:table}','${flyway:table}','CONTROL','NOT_PAYLOAD','CONTROL_ONLY','OWNER_POLICY_RETAINED', + 'Actual configured Game Session Flyway history is retained installation evidence, not payload, build authority or runtime enrollment.'); + +CREATE FUNCTION gs_runtime_family_catalog_installed() RETURNS BOOLEAN +LANGUAGE SQL STABLE SET search_path = "${serviceSchema}", pg_catalog AS $$ + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1057__game_session_owner_runtime_family_catalog.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1057'; +$$; + +CREATE FUNCTION gs_runtime_family_catalog_bytes(p_epoch BIGINT) RETURNS BYTEA +LANGUAGE plpgsql STABLE SET search_path = "${serviceSchema}", pg_catalog AS $$ +DECLARE v_families JSONB; v_facts JSONB; v_gaps JSONB; v_bytes BYTEA; +BEGIN + IF p_epoch IS NULL OR p_epoch<=0 THEN + RAISE EXCEPTION 'Positive Game Session catalog epoch required' USING ERRCODE='23514'; + END IF; + IF EXISTS ( + SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE n.nspname='${serviceSchema}' AND c.relkind IN ('r','p','f') + EXCEPT SELECT relation_name FROM game_session_runtime_family_classification WHERE component_name='' + ) OR EXISTS ( + SELECT 1 FROM game_session_runtime_family_classification f + LEFT JOIN pg_namespace n ON n.nspname='${serviceSchema}' + LEFT JOIN pg_class c ON c.relnamespace=n.oid AND c.relname=f.relation_name AND c.relkind IN ('r','p','f') + WHERE c.oid IS NULL OR (f.component_name<>'' AND NOT EXISTS ( + SELECT 1 FROM pg_attribute a WHERE a.attrelid=c.oid AND a.attname=f.component_name + AND a.attnum>0 AND NOT a.attisdropped)) + ) THEN + RAISE EXCEPTION 'Unclassified or changed Game Session schema family' USING ERRCODE='23514'; + END IF; + SELECT jsonb_agg(jsonb_build_object('familyId',family_id,'relation',relation_name,'component',component_name, + 'role',family_role,'stateClass',state_class,'freshDisposition',fresh_disposition, + 'retentionDisposition',retention_disposition,'ownerConsequence',owner_consequence) + ORDER BY family_id COLLATE "C") INTO v_families FROM game_session_runtime_family_classification; + SELECT jsonb_agg(jsonb_build_object('id',gap_id,'disposition',disposition,'ownerConsequence',owner_consequence) + ORDER BY gap_id COLLATE "C") INTO v_gaps FROM game_session_runtime_catalog_non_sql_gap; + + -- Definitions only, not rows, OIDs, sequence positions, statistics or installation timestamps. + WITH relations AS ( + SELECT c.* FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='${serviceSchema}' + ), definitions(kind,identity,definition) AS ( + SELECT 'TABLE',c.relname::TEXT,jsonb_build_array(c.relkind,c.relpersistence, + c.relrowsecurity,c.relforcerowsecurity,c.reloptions,pg_get_partkeydef(c.oid))::TEXT + FROM relations c WHERE c.relkind IN ('r','p','f') + UNION ALL + SELECT 'COLUMN',c.relname||'.'||a.attname,jsonb_build_array(a.attnum, + format_type(a.atttypid,a.atttypmod),a.attnotnull,a.attidentity,a.attgenerated, + pg_get_expr(d.adbin,d.adrelid),co.collname)::TEXT + FROM relations c JOIN pg_attribute a ON a.attrelid=c.oid + LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum + LEFT JOIN pg_collation co ON co.oid=a.attcollation + WHERE c.relkind IN ('r','p','f','v','m') AND a.attnum>0 AND NOT a.attisdropped + UNION ALL + SELECT 'CONSTRAINT',c.relname||'.'||k.conname, + jsonb_build_array(pg_get_constraintdef(k.oid,true),k.convalidated,k.condeferrable,k.condeferred)::TEXT + FROM relations c JOIN pg_constraint k ON k.conrelid=c.oid + UNION ALL + SELECT 'INDEX',c.relname::TEXT,jsonb_build_array(pg_get_indexdef(c.oid),i.indisvalid,i.indisready)::TEXT + FROM relations c JOIN pg_index i ON i.indexrelid=c.oid + UNION ALL + SELECT 'TRIGGER',c.relname||'.'||t.tgname,jsonb_build_array(pg_get_triggerdef(t.oid,true),t.tgenabled)::TEXT + FROM relations c JOIN pg_trigger t ON t.tgrelid=c.oid WHERE NOT t.tgisinternal + UNION ALL + SELECT 'POLICY',c.relname||'.'||p.polname,jsonb_build_array(p.polcmd,p.polpermissive, + (SELECT jsonb_agg(r.rolname ORDER BY r.rolname COLLATE "C") FROM pg_roles r WHERE r.oid=ANY(p.polroles)), + pg_get_expr(p.polqual,p.polrelid),pg_get_expr(p.polwithcheck,p.polrelid))::TEXT + FROM relations c JOIN pg_policy p ON p.polrelid=c.oid + UNION ALL + SELECT 'RULE',c.relname||'.'||r.rulename,pg_get_ruledef(r.oid,true) + FROM relations c JOIN pg_rewrite r ON r.ev_class=c.oid + UNION ALL + SELECT 'ROUTINE',p.proname||'('||pg_get_function_identity_arguments(p.oid)||')',pg_get_functiondef(p.oid) + FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace + WHERE n.nspname='${serviceSchema}' AND p.prokind IN ('f','p') + UNION ALL + SELECT 'SEQUENCE',c.relname::TEXT,(to_jsonb(s)-'seqrelid')::TEXT + FROM relations c JOIN pg_sequence s ON s.seqrelid=c.oid + UNION ALL + SELECT 'VIEW',c.relname::TEXT,pg_get_viewdef(c.oid,true) FROM relations c WHERE c.relkind IN ('v','m') + UNION ALL + SELECT 'TYPE',t.typname::TEXT,jsonb_build_array(t.typtype,t.typnotnull,t.typdefault, + (SELECT jsonb_agg(e.enumlabel ORDER BY e.enumsortorder) FROM pg_enum e WHERE e.enumtypid=t.oid))::TEXT + FROM pg_type t JOIN pg_namespace n ON n.oid=t.typnamespace WHERE n.nspname='${serviceSchema}' + UNION ALL + SELECT 'MIGRATION',installed_rank::TEXT||':'||coalesce(version,'repeatable')||':'||script, + jsonb_build_array(version,type,script,checksum,success)::TEXT + FROM "${flyway:table}" WHERE version IS DISTINCT FROM '1057' + UNION ALL + -- Flyway writes our own history row after this transaction. Bind a stable installation + -- marker and exact installed definitions, NOT an invented own-row checksum. installed() + -- separately requires the later successful exact SQL script. Prior/later rows bind above. + SELECT 'MIGRATION','catalog-installation:1057','V1057__game_session_owner_runtime_family_catalog.sql' + ) + SELECT jsonb_agg(jsonb_build_object('kind',kind,'identity',identity, + 'definitionDigest','sha256:'||encode(sha256(convert_to(definition,'UTF8')),'hex')) + ORDER BY (kind||'/'||identity) COLLATE "C") INTO v_facts FROM definitions; + IF v_families IS NULL OR v_facts IS NULL OR v_gaps IS NULL + OR jsonb_array_length(v_families)>512 OR jsonb_array_length(v_facts)>16384 + OR jsonb_array_length(v_gaps)>32 THEN + RAISE EXCEPTION 'Complete Game Session catalog exceeds source bounds' USING ERRCODE='23514'; + END IF; + v_bytes := convert_to(jsonb_build_object('schema','game-session-runtime-family-catalog/v1', + 'owner','game-session-service','catalogEpoch',p_epoch::TEXT, + 'families',v_families,'schemaFacts',v_facts,'nonSqlGaps',v_gaps)::TEXT,'UTF8'); + IF octet_length(v_bytes)>2097152 THEN + RAISE EXCEPTION 'Complete Game Session catalog exceeds byte bound' USING ERRCODE='23514'; + END IF; + RETURN v_bytes; +END; +$$; + +CREATE FUNCTION gs_runtime_catalog_immutable() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Game Session runtime catalog evidence is immutable' USING ERRCODE='23514'; +END; +$$; +CREATE TRIGGER gs_runtime_classification_retained BEFORE UPDATE OR DELETE OR TRUNCATE +ON game_session_runtime_family_classification FOR EACH STATEMENT EXECUTE FUNCTION gs_runtime_catalog_immutable(); +CREATE TRIGGER gs_runtime_non_sql_gap_retained BEFORE UPDATE OR DELETE OR TRUNCATE +ON game_session_runtime_catalog_non_sql_gap FOR EACH STATEMENT EXECUTE FUNCTION gs_runtime_catalog_immutable(); +CREATE TRIGGER gs_runtime_epoch_retained BEFORE UPDATE OR DELETE OR TRUNCATE +ON game_session_runtime_family_catalog_epoch FOR EACH STATEMENT EXECUTE FUNCTION gs_runtime_catalog_immutable(); +CREATE TRIGGER gs_runtime_snapshot_retained BEFORE UPDATE OR DELETE OR TRUNCATE +ON game_session_runtime_family_catalog_snapshot FOR EACH STATEMENT EXECUTE FUNCTION gs_runtime_catalog_immutable(); + +CREATE FUNCTION gs_runtime_catalog_epoch_guard() RETURNS TRIGGER LANGUAGE plpgsql +SET search_path = "${serviceSchema}", pg_catalog AS $$ +BEGIN + PERFORM pg_advisory_xact_lock(hashtextextended('${serviceSchema}:gs-runtime-catalog-epoch',0)); + IF NEW.catalog_epoch<>coalesce((SELECT max(catalog_epoch) FROM game_session_runtime_family_catalog_epoch),0)+1 + OR NEW.catalog_bytes<>gs_runtime_family_catalog_bytes(NEW.catalog_epoch) THEN + RAISE EXCEPTION 'Game Session epoch must bind the exact classified installed schema' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER gs_runtime_epoch_exact BEFORE INSERT ON game_session_runtime_family_catalog_epoch +FOR EACH ROW EXECUTE FUNCTION gs_runtime_catalog_epoch_guard(); + +CREATE FUNCTION gs_runtime_catalog_snapshot_guard() RETURNS TRIGGER LANGUAGE plpgsql +SET search_path = "${serviceSchema}", pg_catalog AS $$ +DECLARE v_epoch game_session_runtime_family_catalog_epoch%ROWTYPE; v_request BYTEA; v_evidence BYTEA; +BEGIN + SELECT * INTO STRICT v_epoch FROM game_session_runtime_family_catalog_epoch ORDER BY catalog_epoch DESC LIMIT 1; + IF NOT gs_runtime_family_catalog_installed() + OR NEW.catalog_epoch<>v_epoch.catalog_epoch OR NEW.catalog_digest<>v_epoch.catalog_digest + OR gs_runtime_family_catalog_bytes(v_epoch.catalog_epoch)<>v_epoch.catalog_bytes THEN + RAISE EXCEPTION 'Game Session runtime catalog changed; new owner epoch required' USING ERRCODE='23514'; + END IF; + -- Purpose-specific GCR1/GCE1 frames. Owner and epoch are bound inside exact catalog bytes. + v_request := decode('47435231','hex') || uuid_send(NEW.read_request_id) + || int4send(octet_length(convert_to(NEW.target_namespace,'UTF8'))) || convert_to(NEW.target_namespace,'UTF8'); + v_evidence := decode('47434531','hex') || int4send(octet_length(v_request)) || v_request + || uuid_send(NEW.snapshot_id) || int4send(octet_length(convert_to(v_epoch.catalog_digest,'UTF8'))) + || convert_to(v_epoch.catalog_digest,'UTF8') || int4send(octet_length(v_epoch.catalog_bytes)) || v_epoch.catalog_bytes; + IF NEW.request_bytes<>v_request OR NEW.evidence_bytes<>v_evidence THEN + RAISE EXCEPTION 'Game Session snapshot must bind complete exact request and evidence' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER gs_runtime_snapshot_current BEFORE INSERT ON game_session_runtime_family_catalog_snapshot +FOR EACH ROW EXECUTE FUNCTION gs_runtime_catalog_snapshot_guard(); +-- [jooq ignore stop] + +-- PostgreSQL-only seal; deliberately no embedded pg_catalog simulation. +-- [jooq ignore start] +INSERT INTO game_session_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT 1,bytes,'sha256:'||encode(sha256(bytes),'hex') +FROM (SELECT gs_runtime_family_catalog_bytes(1) AS bytes) seal; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V1058__game_session_catalog_view_options.sql b/services/game-session-service/src/main/resources/db/migration/V1058__game_session_catalog_view_options.sql new file mode 100644 index 0000000000..e9f149e95d --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1058__game_session_catalog_view_options.sql @@ -0,0 +1,132 @@ +-- Preserve the published V1057 migration, retained epochs and request evidence. View +-- options affect execution semantics independently of pg_get_viewdef, including security +-- invoker/barrier behavior and materialized-view storage options. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION gs_runtime_family_catalog_installed() RETURNS BOOLEAN +LANGUAGE SQL STABLE SET search_path = "${serviceSchema}", pg_catalog AS $$ + SELECT ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1057__game_session_owner_runtime_family_catalog.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1057' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1058__game_session_catalog_view_options.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1058' + ); +$$; + +CREATE OR REPLACE FUNCTION gs_runtime_family_catalog_bytes(p_epoch BIGINT) RETURNS BYTEA +LANGUAGE plpgsql STABLE SET search_path = "${serviceSchema}", pg_catalog AS $$ +DECLARE v_families JSONB; v_facts JSONB; v_gaps JSONB; v_bytes BYTEA; +BEGIN + IF p_epoch IS NULL OR p_epoch<=0 THEN + RAISE EXCEPTION 'Positive Game Session catalog epoch required' USING ERRCODE='23514'; + END IF; + IF EXISTS ( + SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE n.nspname='${serviceSchema}' AND c.relkind IN ('r','p','f') + EXCEPT SELECT relation_name FROM game_session_runtime_family_classification WHERE component_name='' + ) OR EXISTS ( + SELECT 1 FROM game_session_runtime_family_classification f + LEFT JOIN pg_namespace n ON n.nspname='${serviceSchema}' + LEFT JOIN pg_class c ON c.relnamespace=n.oid AND c.relname=f.relation_name AND c.relkind IN ('r','p','f') + WHERE c.oid IS NULL OR (f.component_name<>'' AND NOT EXISTS ( + SELECT 1 FROM pg_attribute a WHERE a.attrelid=c.oid AND a.attname=f.component_name + AND a.attnum>0 AND NOT a.attisdropped)) + ) THEN + RAISE EXCEPTION 'Unclassified or changed Game Session schema family' USING ERRCODE='23514'; + END IF; + SELECT jsonb_agg(jsonb_build_object('familyId',family_id,'relation',relation_name,'component',component_name, + 'role',family_role,'stateClass',state_class,'freshDisposition',fresh_disposition, + 'retentionDisposition',retention_disposition,'ownerConsequence',owner_consequence) + ORDER BY family_id COLLATE "C") INTO v_families FROM game_session_runtime_family_classification; + SELECT jsonb_agg(jsonb_build_object('id',gap_id,'disposition',disposition,'ownerConsequence',owner_consequence) + ORDER BY gap_id COLLATE "C") INTO v_gaps FROM game_session_runtime_catalog_non_sql_gap; + + -- Definitions only, not rows, OIDs, sequence positions, statistics or installation timestamps. + WITH relations AS ( + SELECT c.* FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='${serviceSchema}' + ), definitions(kind,identity,definition) AS ( + SELECT 'TABLE',c.relname::TEXT,jsonb_build_array(c.relkind,c.relpersistence, + c.relrowsecurity,c.relforcerowsecurity,c.reloptions,pg_get_partkeydef(c.oid))::TEXT + FROM relations c WHERE c.relkind IN ('r','p','f') + UNION ALL + SELECT 'COLUMN',c.relname||'.'||a.attname,jsonb_build_array(a.attnum, + format_type(a.atttypid,a.atttypmod),a.attnotnull,a.attidentity,a.attgenerated, + pg_get_expr(d.adbin,d.adrelid),co.collname)::TEXT + FROM relations c JOIN pg_attribute a ON a.attrelid=c.oid + LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum + LEFT JOIN pg_collation co ON co.oid=a.attcollation + WHERE c.relkind IN ('r','p','f','v','m') AND a.attnum>0 AND NOT a.attisdropped + UNION ALL + SELECT 'CONSTRAINT',c.relname||'.'||k.conname, + jsonb_build_array(pg_get_constraintdef(k.oid,true),k.convalidated,k.condeferrable,k.condeferred)::TEXT + FROM relations c JOIN pg_constraint k ON k.conrelid=c.oid + UNION ALL + SELECT 'INDEX',c.relname::TEXT,jsonb_build_array(pg_get_indexdef(c.oid),i.indisvalid,i.indisready)::TEXT + FROM relations c JOIN pg_index i ON i.indexrelid=c.oid + UNION ALL + SELECT 'TRIGGER',c.relname||'.'||t.tgname,jsonb_build_array(pg_get_triggerdef(t.oid,true),t.tgenabled)::TEXT + FROM relations c JOIN pg_trigger t ON t.tgrelid=c.oid WHERE NOT t.tgisinternal + UNION ALL + SELECT 'POLICY',c.relname||'.'||p.polname,jsonb_build_array(p.polcmd,p.polpermissive, + (SELECT jsonb_agg(r.rolname ORDER BY r.rolname COLLATE "C") FROM pg_roles r WHERE r.oid=ANY(p.polroles)), + pg_get_expr(p.polqual,p.polrelid),pg_get_expr(p.polwithcheck,p.polrelid))::TEXT + FROM relations c JOIN pg_policy p ON p.polrelid=c.oid + UNION ALL + SELECT 'RULE',c.relname||'.'||r.rulename,pg_get_ruledef(r.oid,true) + FROM relations c JOIN pg_rewrite r ON r.ev_class=c.oid + UNION ALL + SELECT 'ROUTINE',p.proname||'('||pg_get_function_identity_arguments(p.oid)||')',pg_get_functiondef(p.oid) + FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace + WHERE n.nspname='${serviceSchema}' AND p.prokind IN ('f','p') + UNION ALL + SELECT 'SEQUENCE',c.relname::TEXT,(to_jsonb(s)-'seqrelid')::TEXT + FROM relations c JOIN pg_sequence s ON s.seqrelid=c.oid + UNION ALL + SELECT 'VIEW',c.relname::TEXT,jsonb_build_array(pg_get_viewdef(c.oid,true),c.reloptions)::TEXT + FROM relations c WHERE c.relkind IN ('v','m') + UNION ALL + SELECT 'TYPE',t.typname::TEXT,jsonb_build_array(t.typtype,t.typnotnull,t.typdefault, + (SELECT jsonb_agg(e.enumlabel ORDER BY e.enumsortorder) FROM pg_enum e WHERE e.enumtypid=t.oid))::TEXT + FROM pg_type t JOIN pg_namespace n ON n.oid=t.typnamespace WHERE n.nspname='${serviceSchema}' + UNION ALL + SELECT 'MIGRATION',installed_rank::TEXT||':'||coalesce(version,'repeatable')||':'||script, + jsonb_build_array(version,type,script,checksum,success)::TEXT + FROM "${flyway:table}" WHERE version IS DISTINCT FROM '1057' AND version IS DISTINCT FROM '1058' + UNION ALL + -- Each installing migration's own row is written after its transaction. Bind distinct + -- stable installation markers, not invented checksums. installed() separately requires + -- both successful exact SQL scripts. All other prior/later rows remain bound above. + SELECT 'MIGRATION','catalog-installation:1057','V1057__game_session_owner_runtime_family_catalog.sql' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1058','V1058__game_session_catalog_view_options.sql' + ) + SELECT jsonb_agg(jsonb_build_object('kind',kind,'identity',identity, + 'definitionDigest','sha256:'||encode(sha256(convert_to(definition,'UTF8')),'hex')) + ORDER BY (kind||'/'||identity) COLLATE "C") INTO v_facts FROM definitions; + IF v_families IS NULL OR v_facts IS NULL OR v_gaps IS NULL + OR jsonb_array_length(v_families)>512 OR jsonb_array_length(v_facts)>16384 + OR jsonb_array_length(v_gaps)>32 THEN + RAISE EXCEPTION 'Complete Game Session catalog exceeds source bounds' USING ERRCODE='23514'; + END IF; + v_bytes := convert_to(jsonb_build_object('schema','game-session-runtime-family-catalog/v1', + 'owner','game-session-service','catalogEpoch',p_epoch::TEXT, + 'families',v_families,'schemaFacts',v_facts,'nonSqlGaps',v_gaps)::TEXT,'UTF8'); + IF octet_length(v_bytes)>2097152 THEN + RAISE EXCEPTION 'Complete Game Session catalog exceeds byte bound' USING ERRCODE='23514'; + END IF; + RETURN v_bytes; +END; +$$; + +-- Seal only after every routine replacement; old epochs and snapshots stay byte-for-byte +-- retained and old requests conflict with this explicitly installed next owner revision. +INSERT INTO game_session_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') +FROM ( + SELECT epoch,gs_runtime_family_catalog_bytes(epoch) AS bytes + FROM (SELECT coalesce(max(catalog_epoch),0)+1 AS epoch + FROM game_session_runtime_family_catalog_epoch) next_epoch +) seal; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V1059__private_lifecycle_preparation_after_catalog_allocation.sql b/services/game-session-service/src/main/resources/db/migration/V1059__private_lifecycle_preparation_after_catalog_allocation.sql new file mode 100644 index 0000000000..bf1055112f --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1059__private_lifecycle_preparation_after_catalog_allocation.sql @@ -0,0 +1,270 @@ +-- A retained private catalog projection is not a public target conflict for a new +-- preparation/current-selection request. Stable realm selectors and immutable catalog +-- rows remain unchanged; later lifecycle catalog evolution is a separate owner boundary. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION game_session_initial_playtest_source_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + source game_session_canonical_realm_catalog%ROWTYPE; + intake game_session_authored_world_source_intake%ROWTYPE; + carrier BYTEA; + payload_bytes BYTEA; + payload TEXT; + policy JSONB; + selected_policy_count INTEGER; + selected_policy_json TEXT; + selected_policy JSONB; + marker TEXT := 'game-design-published-realm-policy-carrier/v1'; + fields TEXT[]; + item TEXT; + framed BYTEA := ''::BYTEA; + fraction TEXT; +BEGIN + IF NEW.fork_expiry_text !~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]{3}|\.[0-9]{6}|\.[0-9]{9})?Z$' + OR extract(epoch FROM regexp_replace(NEW.fork_expiry_text, '\.[0-9]+Z$', 'Z')::TIMESTAMPTZ) <> NEW.fork_expiry_second THEN + RAISE EXCEPTION 'Exact fork expiry text differs from persisted seconds' USING ERRCODE = '23514'; + END IF; + fraction := substring(NEW.fork_expiry_text FROM '\.([0-9]+)Z$'); + IF coalesce(rpad(fraction, 9, '0')::INTEGER, 0) <> NEW.fork_expiry_nano THEN + RAISE EXCEPTION 'Exact fork expiry text differs from persisted nanoseconds' USING ERRCODE = '23514'; + END IF; + fields := ARRAY['game-session-initial-fresh-playtest-request/v1', NEW.request_id::TEXT, + NEW.target_namespace, NEW.canonical_tenant_id::TEXT, NEW.world_slug, NEW.realm_slug, + NEW.source_catalog_realm_id::TEXT, NEW.source_catalog_request_id::TEXT, NEW.source_catalog_revision::TEXT, + NEW.source_intake_operation_id::TEXT, NEW.canonical_version_id::TEXT, NEW.published_release_bundle_ref, + NEW.published_release_bundle_digest, NEW.initialization_mode, NEW.fork_expiry_text]; + FOREACH item IN ARRAY fields LOOP + -- int4send is the four-byte network-order length used by the shared Java frame. + framed := framed || int4send(octet_length(convert_to(item, 'UTF8'))) || convert_to(item, 'UTF8'); + END LOOP; + IF framed <> NEW.request_preimage THEN + RAISE EXCEPTION 'Initial playtest request bytes differ from exact stored intent' USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT source FROM game_session_canonical_realm_catalog + WHERE target_namespace = NEW.target_namespace AND realm_id = NEW.source_catalog_realm_id FOR SHARE; + SELECT * INTO STRICT intake FROM game_session_authored_world_source_intake + WHERE operation_id = NEW.source_intake_operation_id FOR SHARE; + IF NOT source.public_production OR NOT source.visible + OR source.complete_policy_set_evidence IS NULL OR source.fixture_policy_request_bytes IS NOT NULL + OR source.canonical_tenant_id <> NEW.canonical_tenant_id OR source.world_slug <> NEW.world_slug + OR source.realm_slug = NEW.realm_slug + OR source.creation_request_id <> NEW.source_catalog_request_id + OR source.catalog_revision <> NEW.source_catalog_revision + OR source.receipt_digest <> NEW.source_catalog_receipt_digest + OR source.source_intake_operation_id <> NEW.source_intake_operation_id + OR source.source_intake_receipt_digest <> NEW.source_intake_receipt_digest + OR source.source_operation_id <> NEW.source_operation_id + OR source.source_evidence_digest <> NEW.source_evidence_digest + OR intake.receipt_digest <> NEW.source_intake_receipt_digest + OR intake.target_namespace <> NEW.target_namespace OR intake.canonical_tenant_id <> NEW.canonical_tenant_id + OR intake.world_slug <> NEW.world_slug OR intake.source_operation_id <> NEW.source_operation_id + OR intake.source_evidence_digest <> NEW.source_evidence_digest + OR NEW.source_policy_carrier_digest <> 'sha256:' || encode(sha256(source.complete_policy_set_evidence), 'hex') + OR EXISTS (SELECT 1 FROM game_session_canonical_realm_catalog target + WHERE target.target_namespace = NEW.target_namespace AND target.canonical_tenant_id = NEW.canonical_tenant_id + AND target.world_slug = NEW.world_slug AND target.realm_slug = NEW.realm_slug + AND target.public_production) + OR EXISTS (SELECT 1 FROM gameplay_tenant_shared_playable_state_namespace namespace + WHERE namespace.playable_state_namespace_id = NEW.playable_state_namespace_id) + OR EXISTS (SELECT 1 FROM game_session_canonical_realm_catalog catalog + WHERE catalog.playable_state_namespace_id = NEW.playable_state_namespace_id) + OR EXISTS (SELECT 1 FROM gameplay_admission_pointer pointer + WHERE pointer.playable_state_namespace_id = NEW.playable_state_namespace_id) + OR EXISTS (SELECT 1 FROM gameplay_published_tenant_shared_playable_state_namespace namespace + WHERE namespace.playable_state_namespace_id = NEW.playable_state_namespace_id) + OR EXISTS (SELECT 1 FROM gameplay_published_realm_catalog_entry entry + WHERE entry.playable_state_namespace_id = NEW.playable_state_namespace_id) THEN + RAISE EXCEPTION 'Initial playtest requires exact retained canonical public source/build evidence and a fresh private target' USING ERRCODE = '23514'; + END IF; + -- Read only the exact retained shared carrier; Java additionally verifies its closed + -- publication operation/capture/terminal contracts before reaching this guarded insert. + carrier := source.complete_policy_set_evidence; + IF octet_length(carrier) < 8 + octet_length(convert_to(marker, 'UTF8')) THEN + RAISE EXCEPTION 'Retained build source carrier framing is invalid' USING ERRCODE = '23514'; + END IF; + -- The carrier is exactly two shared binary frames: schema marker, then canonical JSON. + -- Derive the actual second-frame bytes and compare both complete length headers exactly. + payload_bytes := substring(carrier FROM 9 + octet_length(convert_to(marker, 'UTF8'))); + IF carrier <> (int4send(octet_length(convert_to(marker, 'UTF8'))) || convert_to(marker, 'UTF8') + || int4send(octet_length(payload_bytes)) || payload_bytes) THEN + RAISE EXCEPTION 'Retained build source carrier framing is invalid' USING ERRCODE = '23514'; + END IF; + payload := convert_from(payload_bytes, 'UTF8'); + policy := payload::JSONB; + IF policy->>'schema' IS DISTINCT FROM marker + OR policy->'target'->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR policy->'target'->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR policy->'target'->>'sourceGameRowId' IS DISTINCT FROM source.source_game_row_id::TEXT + OR policy->'target'->>'sourceGameTenantKey' IS DISTINCT FROM source.source_game_tenant_key + OR policy->'target'->>'sourceProvenanceKind' IS DISTINCT FROM source.source_provenance_kind + OR policy->>'publishedReleaseBundleRef' IS DISTINCT FROM NEW.published_release_bundle_ref + OR policy->>'publishedReleaseBundleDigest' IS DISTINCT FROM NEW.published_release_bundle_digest + OR policy->>'policySetDigest' IS DISTINCT FROM NEW.source_policy_set_digest THEN + RAISE EXCEPTION 'Initial playtest build differs from exact retained published source' USING ERRCODE = '23514'; + END IF; + SELECT count(*), max(policy_item.value->'source'->>'canonicalPolicyJson') + INTO selected_policy_count, selected_policy_json + FROM jsonb_array_elements(policy->'policies') AS policy_item(value) + WHERE policy_item.value->>'policyId' = NEW.target_policy_id::TEXT + AND policy_item.value->>'policyDigest' = NEW.target_policy_digest + AND policy_item.value->'source'->>'commitId' = NEW.target_policy_source_commit_id::TEXT + AND policy_item.value->'source'->>'revisionId' = NEW.target_policy_source_revision_id::TEXT + AND policy_item.value->'source'->>'logicalRevisionId' = NEW.target_policy_logical_revision_id; + IF selected_policy_count <> 1 OR selected_policy_json IS NULL + OR convert_to(selected_policy_json, 'UTF8') IS DISTINCT FROM NEW.target_policy_canonical_json THEN + RAISE EXCEPTION 'Selected private target policy differs from the exact retained published policy set' USING ERRCODE = '23514'; + END IF; + selected_policy := selected_policy_json::JSONB; + IF selected_policy->>'schemaVersion' IS DISTINCT FROM NEW.target_policy_schema_version::TEXT + OR selected_policy->>'worldSlug' IS DISTINCT FROM NEW.target_policy_world_slug + OR selected_policy->>'realmSlug' IS DISTINCT FROM NEW.target_policy_realm_slug + OR selected_policy->>'visible' IS DISTINCT FROM 'true' + OR selected_policy->>'worldDisplayName' IS DISTINCT FROM NEW.target_policy_world_display_name + OR NEW.target_policy_world_display_name IS DISTINCT FROM intake.world_display_name + OR selected_policy->>'publicProduction' IS DISTINCT FROM 'false' + OR selected_policy->>'stateScope' IS DISTINCT FROM NEW.target_policy_state_scope + OR selected_policy->>'realmDisplayName' IS DISTINCT FROM NEW.target_policy_realm_display_name + OR selected_policy->>'entryPolicy' IS DISTINCT FROM NEW.target_policy_entry_policy THEN + RAISE EXCEPTION 'Selected private target policy semantics differ from the exact retained policy bytes' USING ERRCODE = '23514'; + END IF; + IF NEW.fork_expiry_second + NEW.fork_expiry_nano / 1000000000.0 <= extract(epoch FROM clock_timestamp()) THEN + RAISE EXCEPTION 'Initial playtest fork expiry must be future' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION gs_runtime_family_catalog_installed() RETURNS BOOLEAN +LANGUAGE SQL STABLE SET search_path = "${serviceSchema}", pg_catalog AS $$ + SELECT ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1057__game_session_owner_runtime_family_catalog.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1057' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1058__game_session_catalog_view_options.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1058' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1059__private_lifecycle_preparation_after_catalog_allocation.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1059' + ); +$$; + +CREATE OR REPLACE FUNCTION gs_runtime_family_catalog_bytes(p_epoch BIGINT) RETURNS BYTEA +LANGUAGE plpgsql STABLE SET search_path = "${serviceSchema}", pg_catalog AS $$ +DECLARE v_families JSONB; v_facts JSONB; v_gaps JSONB; v_bytes BYTEA; +BEGIN + IF p_epoch IS NULL OR p_epoch<=0 THEN + RAISE EXCEPTION 'Positive Game Session catalog epoch required' USING ERRCODE='23514'; + END IF; + IF EXISTS ( + SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE n.nspname='${serviceSchema}' AND c.relkind IN ('r','p','f') + EXCEPT SELECT relation_name FROM game_session_runtime_family_classification WHERE component_name='' + ) OR EXISTS ( + SELECT 1 FROM game_session_runtime_family_classification f + LEFT JOIN pg_namespace n ON n.nspname='${serviceSchema}' + LEFT JOIN pg_class c ON c.relnamespace=n.oid AND c.relname=f.relation_name AND c.relkind IN ('r','p','f') + WHERE c.oid IS NULL OR (f.component_name<>'' AND NOT EXISTS ( + SELECT 1 FROM pg_attribute a WHERE a.attrelid=c.oid AND a.attname=f.component_name + AND a.attnum>0 AND NOT a.attisdropped)) + ) THEN + RAISE EXCEPTION 'Unclassified or changed Game Session schema family' USING ERRCODE='23514'; + END IF; + SELECT jsonb_agg(jsonb_build_object('familyId',family_id,'relation',relation_name,'component',component_name, + 'role',family_role,'stateClass',state_class,'freshDisposition',fresh_disposition, + 'retentionDisposition',retention_disposition,'ownerConsequence',owner_consequence) + ORDER BY family_id COLLATE "C") INTO v_families FROM game_session_runtime_family_classification; + SELECT jsonb_agg(jsonb_build_object('id',gap_id,'disposition',disposition,'ownerConsequence',owner_consequence) + ORDER BY gap_id COLLATE "C") INTO v_gaps FROM game_session_runtime_catalog_non_sql_gap; + + -- Definitions only, not rows, OIDs, sequence positions, statistics or installation timestamps. + WITH relations AS ( + SELECT c.* FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='${serviceSchema}' + ), definitions(kind,identity,definition) AS ( + SELECT 'TABLE',c.relname::TEXT,jsonb_build_array(c.relkind,c.relpersistence, + c.relrowsecurity,c.relforcerowsecurity,c.reloptions,pg_get_partkeydef(c.oid))::TEXT + FROM relations c WHERE c.relkind IN ('r','p','f') + UNION ALL + SELECT 'COLUMN',c.relname||'.'||a.attname,jsonb_build_array(a.attnum, + format_type(a.atttypid,a.atttypmod),a.attnotnull,a.attidentity,a.attgenerated, + pg_get_expr(d.adbin,d.adrelid),co.collname)::TEXT + FROM relations c JOIN pg_attribute a ON a.attrelid=c.oid + LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum + LEFT JOIN pg_collation co ON co.oid=a.attcollation + WHERE c.relkind IN ('r','p','f','v','m') AND a.attnum>0 AND NOT a.attisdropped + UNION ALL + SELECT 'CONSTRAINT',c.relname||'.'||k.conname, + jsonb_build_array(pg_get_constraintdef(k.oid,true),k.convalidated,k.condeferrable,k.condeferred)::TEXT + FROM relations c JOIN pg_constraint k ON k.conrelid=c.oid + UNION ALL + SELECT 'INDEX',c.relname::TEXT,jsonb_build_array(pg_get_indexdef(c.oid),i.indisvalid,i.indisready)::TEXT + FROM relations c JOIN pg_index i ON i.indexrelid=c.oid + UNION ALL + SELECT 'TRIGGER',c.relname||'.'||t.tgname,jsonb_build_array(pg_get_triggerdef(t.oid,true),t.tgenabled)::TEXT + FROM relations c JOIN pg_trigger t ON t.tgrelid=c.oid WHERE NOT t.tgisinternal + UNION ALL + SELECT 'POLICY',c.relname||'.'||p.polname,jsonb_build_array(p.polcmd,p.polpermissive, + (SELECT jsonb_agg(r.rolname ORDER BY r.rolname COLLATE "C") FROM pg_roles r WHERE r.oid=ANY(p.polroles)), + pg_get_expr(p.polqual,p.polrelid),pg_get_expr(p.polwithcheck,p.polrelid))::TEXT + FROM relations c JOIN pg_policy p ON p.polrelid=c.oid + UNION ALL + SELECT 'RULE',c.relname||'.'||r.rulename,pg_get_ruledef(r.oid,true) + FROM relations c JOIN pg_rewrite r ON r.ev_class=c.oid + UNION ALL + SELECT 'ROUTINE',p.proname||'('||pg_get_function_identity_arguments(p.oid)||')',pg_get_functiondef(p.oid) + FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace + WHERE n.nspname='${serviceSchema}' AND p.prokind IN ('f','p') + UNION ALL + SELECT 'SEQUENCE',c.relname::TEXT,(to_jsonb(s)-'seqrelid')::TEXT + FROM relations c JOIN pg_sequence s ON s.seqrelid=c.oid + UNION ALL + SELECT 'VIEW',c.relname::TEXT,jsonb_build_array(pg_get_viewdef(c.oid,true),c.reloptions)::TEXT + FROM relations c WHERE c.relkind IN ('v','m') + UNION ALL + SELECT 'TYPE',t.typname::TEXT,jsonb_build_array(t.typtype,t.typnotnull,t.typdefault, + (SELECT jsonb_agg(e.enumlabel ORDER BY e.enumsortorder) FROM pg_enum e WHERE e.enumtypid=t.oid))::TEXT + FROM pg_type t JOIN pg_namespace n ON n.oid=t.typnamespace WHERE n.nspname='${serviceSchema}' + UNION ALL + SELECT 'MIGRATION',installed_rank::TEXT||':'||coalesce(version,'repeatable')||':'||script, + jsonb_build_array(version,type,script,checksum,success)::TEXT + FROM "${flyway:table}" WHERE version IS DISTINCT FROM '1057' AND version IS DISTINCT FROM '1058' + AND version IS DISTINCT FROM '1059' + UNION ALL + -- Each installing migration's own row is written after its transaction. Bind distinct + -- stable installation markers, not invented checksums. installed() separately requires + -- all three successful exact SQL scripts. All other prior/later rows remain bound above. + SELECT 'MIGRATION','catalog-installation:1057','V1057__game_session_owner_runtime_family_catalog.sql' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1058','V1058__game_session_catalog_view_options.sql' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1059','V1059__private_lifecycle_preparation_after_catalog_allocation.sql' + ) + SELECT jsonb_agg(jsonb_build_object('kind',kind,'identity',identity, + 'definitionDigest','sha256:'||encode(sha256(convert_to(definition,'UTF8')),'hex')) + ORDER BY (kind||'/'||identity) COLLATE "C") INTO v_facts FROM definitions; + IF v_families IS NULL OR v_facts IS NULL OR v_gaps IS NULL + OR jsonb_array_length(v_families)>512 OR jsonb_array_length(v_facts)>16384 + OR jsonb_array_length(v_gaps)>32 THEN + RAISE EXCEPTION 'Complete Game Session catalog exceeds source bounds' USING ERRCODE='23514'; + END IF; + v_bytes := convert_to(jsonb_build_object('schema','game-session-runtime-family-catalog/v1', + 'owner','game-session-service','catalogEpoch',p_epoch::TEXT, + 'families',v_families,'schemaFacts',v_facts,'nonSqlGaps',v_gaps)::TEXT,'UTF8'); + IF octet_length(v_bytes)>2097152 THEN + RAISE EXCEPTION 'Complete Game Session catalog exceeds byte bound' USING ERRCODE='23514'; + END IF; + RETURN v_bytes; +END; +$$; + +-- Seal only after every routine replacement; old epochs and snapshots stay byte-for-byte +-- retained and old requests conflict with this explicitly installed next owner revision. +INSERT INTO game_session_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') +FROM ( + SELECT epoch,gs_runtime_family_catalog_bytes(epoch) AS bytes + FROM (SELECT coalesce(max(catalog_epoch),0)+1 AS epoch + FROM game_session_runtime_family_catalog_epoch) next_epoch +) seal; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/AccountInitialAdmissionSettlementPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/AccountInitialAdmissionSettlementPostgresIntegrationTest.java index c5c2d4e8db..fbac0a5e5e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/AccountInitialAdmissionSettlementPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/AccountInitialAdmissionSettlementPostgresIntegrationTest.java @@ -383,7 +383,13 @@ private static Flyway migrateDefault(DriverManagerDataSource data) { .dataSource(data) .schemas(data.getSchema()) .defaultSchema(data.getSchema()) - .locations(MIGRATIONS) + .placeholders(java.util.Map.of("serviceSchema", data.getSchema())) + .locations( + MIGRATIONS, + "filesystem:" + + Path.of("../common-saga/src/main/resources/db/migration/saga") + .toAbsolutePath() + .normalize()) .load(); migrations.migrate(); return migrations; diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java index 138f45bf30..c0458cafa3 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java @@ -30,7 +30,6 @@ import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -791,14 +790,7 @@ private static TestSchema newTestSchema(String prefix) { prefix.substring(0, Math.min(prefix.length(), 31)) + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = dataSource(schema); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema(dataSource, schema, MIGRATION_LOCATION, null); DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); return new TestSchema(schema, dsl); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountClosedBarrierRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountClosedBarrierRedisOwnerIntegrationTest.java index 1b141876b5..6e2887d8ca 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountClosedBarrierRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountClosedBarrierRedisOwnerIntegrationTest.java @@ -1366,12 +1366,8 @@ private DSLContext dslForApplication(String applicationName) { private static Flyway flyway( DriverManagerDataSource dataSource, String schema, String migrationTarget) { var configuration = - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION); + CanonicalGameplayIssuerTestFixtures.migrationConfiguration( + dataSource, schema, MIGRATION_LOCATION); if (migrationTarget != null) { configuration.target(MigrationVersion.fromVersion(migrationTarget)); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairRedisOwnerIntegrationTest.java index 97853e6b97..bdd7e88876 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairRedisOwnerIntegrationTest.java @@ -46,7 +46,6 @@ import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountMemberRepairRedisScriptContribution; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -546,14 +545,7 @@ private static void seedSyntheticVerifiedLegacyDisposition(DSLContext dsl) { private static TestSchema newTestSchema(String applicationName) { String schema = "gs_account_member_lock_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = dataSource(schema, applicationName); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema(dataSource, schema, MIGRATION_LOCATION, null); DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); return new TestSchema(schema, dataSource, dsl); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepositoryIntegrationTest.java index bba550617e..83dddafaac 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepositoryIntegrationTest.java @@ -40,7 +40,6 @@ import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -96,14 +95,8 @@ void failsClosedWhenInventoryAbsenceCannotProveLegacyControllerAbsence() { String schema = "gs_binding_inventory_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = dataSource(schema); try { - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, schema, MIGRATION_LOCATION, null); DSLContext dsl = dslForSchema(dataSource, schema); CanonicalGameplayBindingInventoryRepository repository = new CanonicalGameplayBindingInventoryRepository(dsl); @@ -132,14 +125,8 @@ void preparesFirstBindingOnlyBehindVerifiedDispositionAndRetainsNoPriorShape() { String schema = "gs_binding_first_inventory_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = dataSource(schema); try { - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, schema, MIGRATION_LOCATION, null); DSLContext dsl = dslForSchema(dataSource, schema); seedSyntheticVerifiedLegacyDisposition(dsl); CanonicalGameplayBindingInventoryRepository repository = @@ -1088,14 +1075,8 @@ void unresolvedPreparedTransitionFencesASecondTransitionForTheSameController() { String schema = "gs_binding_pending_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = dataSource(schema); try { - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, schema, MIGRATION_LOCATION, null); DSLContext dsl = dslForSchema(dataSource, schema); CanonicalGameplayBindingInventoryRepository repository = new CanonicalGameplayBindingInventoryRepository(dsl); @@ -1132,14 +1113,8 @@ void advancesGenerationAtomicallyAndKeepsPriorControllerActiveUntilExternalCas() String schema = "gs_binding_generation_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = dataSource(schema); try { - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, schema, MIGRATION_LOCATION, null); DSLContext dsl = dslForSchema(dataSource, schema); CanonicalGameplayBindingIdentity prior = identity(sourceSession()); seedActiveSource(dsl, prior); @@ -1371,14 +1346,7 @@ private static TestSchema newTestSchema(String prefix) { private static TestSchema newTestSchema(String prefix, String applicationName) { String schema = prefix + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = dataSource(schema, applicationName); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema(dataSource, schema, MIGRATION_LOCATION, null); return new TestSchema(schema, dataSource, dslForSchema(dataSource, schema)); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java index 8a8c45391d..04f1f08957 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java @@ -8,7 +8,6 @@ import java.sql.DriverManager; import java.util.UUID; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -38,14 +37,8 @@ void legacyRuntimeMutationAndDeletionEvaluateTheTypedCanonicalTenantFence() { String schema = "gs_runtime_fence_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = dataSource(schema); try { - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, schema, MIGRATION_LOCATION, null); DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); var schemaReadback = dsl.fetchOne("SELECT current_schema() AS actual_schema"); @@ -555,15 +548,8 @@ void regionExecutorFenceForwardMigrationRefusesFractionalOverflowAndNonfiniteRet private static void migrateToRegionFencePredecessor( String schema, DriverManagerDataSource dataSource) { - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .target("1044.1") - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, schema, MIGRATION_LOCATION, "1044.1"); } private static java.util.List requiredRegionSourceImages(DSLContext dsl) { @@ -648,15 +634,8 @@ private static void migrate(String schema, DriverManagerDataSource dataSource) { private static void migrate( String schema, DriverManagerDataSource dataSource, String targetVersion) { - var configuration = - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION); - if (targetVersion != null) configuration.target(targetVersion); - configuration.load().migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, schema, MIGRATION_LOCATION, targetVersion); } private static void assertSnapshotObligationIdentifiersCanonicalized( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java index 8d5d608469..6aa935eb68 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java @@ -15,10 +15,10 @@ import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; import net.firedevops.firemud.gamesession.repository.CanonicalGameplayBindingRuntimeTestFixtures; import net.firedevops.firemud.gamesession.repository.CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerTestFixtures; import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionIntentRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.SQLDialect; @@ -221,14 +221,7 @@ private record ReservedIntent( CanonicalInitialAdmissionIntentSnapshot snapshot) {} private static void migrate(String schema, DriverManagerDataSource dataSource) { - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema(dataSource, schema, MIGRATION_LOCATION, null); } private static DriverManagerDataSource dataSource(String schema) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java index 0e3850c7cd..a321933d8e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java @@ -29,8 +29,6 @@ import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; -import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.SQLDialect; @@ -558,15 +556,8 @@ void forwardMigrationRetainsCommittedAndPendingPhysicalMutationLineage() { var intent = new CanonicalGameplayIssuerLayoutBootstrapRepository(dsl) .beginInitialBootstrapIntent(UUID.randomUUID(), descriptor(), source); - Flyway.configure() - .dataSource(schema.dataSource()) - .schemas(schema.schema()) - .defaultSchema(schema.schema()) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .target(MigrationVersion.fromVersion("1038.3")) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + schema.dataSource(), schema.schema(), MIGRATION_LOCATION, "1038.3"); var state = new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( intent.sourceCheckpoint(), stableIncarnation("lineage-migration")); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java index e6573e5652..fecf487e28 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java @@ -25,8 +25,6 @@ import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; -import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; import org.jooq.ExecuteContext; import org.jooq.SQLDialect; @@ -2175,27 +2173,13 @@ private static void migrateThrough1032(TestSchema testSchema) { } private static void migrateThrough1037(TestSchema testSchema) { - Flyway.configure() - .dataSource(testSchema.dataSource()) - .schemas(testSchema.schema()) - .defaultSchema(testSchema.schema()) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .target(MigrationVersion.fromVersion("1037")) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + testSchema.dataSource(), testSchema.schema(), MIGRATION_LOCATION, "1037"); } private static void migrateThrough1038(TestSchema testSchema) { - Flyway.configure() - .dataSource(testSchema.dataSource()) - .schemas(testSchema.schema()) - .defaultSchema(testSchema.schema()) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .target(MigrationVersion.fromVersion("1038")) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + testSchema.dataSource(), testSchema.schema(), MIGRATION_LOCATION, "1038"); } private static void migrateThrough1044_1(TestSchema testSchema) { @@ -2216,26 +2200,12 @@ private static void migrateRemaining(TestSchema testSchema) { private static TestSchema newLegacyIssuerTestSchema(String prefix) { String schema = CanonicalGameplayIssuerTestFixtures.schemaName(prefix); DriverManagerDataSource dataSource = dataSource(schema); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .target(MigrationVersion.fromVersion("1022")) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, schema, MIGRATION_LOCATION, "1022"); DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); establishActualLegacyDisposition(dsl); insertLegacyReservationBeforeIssuerStringConversion(dsl); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema(dataSource, schema, MIGRATION_LOCATION, null); return new TestSchema(schema, dataSource, dsl); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerTestFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerTestFixtures.java index bc2e5ed1a1..2315b6eff4 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerTestFixtures.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerTestFixtures.java @@ -7,6 +7,7 @@ import io.lettuce.core.RedisURI; import java.math.BigInteger; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.Connection; @@ -18,6 +19,7 @@ import java.util.Map; import java.util.Properties; import java.util.UUID; +import javax.sql.DataSource; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.IssuerPreimage; @@ -34,15 +36,38 @@ import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; +import org.flywaydb.core.api.configuration.FluentConfiguration; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.springframework.jdbc.datasource.DriverManagerDataSource; /** Shared actual-owner fixtures for issuer bootstrap and ordinary NEW integration proof. */ -final class CanonicalGameplayIssuerTestFixtures { +public final class CanonicalGameplayIssuerTestFixtures { private CanonicalGameplayIssuerTestFixtures() {} + public static final List PRIVATE_CATALOG_COLUMNS = + List.of( + "private_target_request_preimage", + "private_preparation_request_id", + "private_playtest_lifecycle_id", + "private_preparation_request_digest", + "private_state_generation", + "private_source_catalog_realm_id", + "private_source_catalog_request_id", + "private_source_catalog_revision", + "private_source_catalog_receipt_digest", + "private_target_policy_id", + "private_target_policy_digest", + "private_target_policy_source_commit_id", + "private_target_policy_source_revision_id", + "private_target_policy_logical_revision_id", + "private_canonical_version_id", + "private_published_release_bundle_ref", + "private_published_release_bundle_digest", + "private_source_policy_set_digest", + "private_source_policy_carrier_digest"); + static String schemaName(String prefix) { return prefix + UUID.randomUUID().toString().replace("-", ""); } @@ -94,22 +119,33 @@ protected Connection getConnectionFromDriver(Properties properties) throws SQLEx return configured; } - static void migrateSchema( - DriverManagerDataSource dataSource, - String schema, - String migrationLocation, - String targetVersion) { - var configuration = - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(migrationLocation); + /** + * Migrates one isolated owner schema with shared Saga history and an optional original target. + */ + public static void migrateSchema( + DataSource dataSource, String schema, String migrationLocation, String targetVersion) { + var configuration = migrationConfiguration(dataSource, schema, migrationLocation); if (targetVersion != null) configuration.target(MigrationVersion.fromVersion(targetVersion)); configuration.load().migrate(); } + /** Configures one isolated owner schema with shared Saga history and service migrations. */ + public static FluentConfiguration migrationConfiguration( + DataSource dataSource, String schema, String migrationLocation) { + return Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .placeholders(Map.of("serviceSchema", schema)) + .locations( + migrationLocation, + "filesystem:" + + Path.of("../common-saga/src/main/resources/db/migration/saga") + .toAbsolutePath() + .normalize()); + } + static void dropSchema( DriverManagerDataSource publicDataSource, String schema, String failureMessage) { try (Connection connection = publicDataSource.getConnection()) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationRepositoryIntegrationTest.java index 3d2d976ef8..fe30409062 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationRepositoryIntegrationTest.java @@ -13,7 +13,6 @@ import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -357,14 +356,7 @@ private static CanonicalGameplayLegacyMigrationSourceSnapshot emptyLegacySnapsho } private static void migrate(String schema, DriverManagerDataSource dataSource) { - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema(dataSource, schema, MIGRATION_LOCATION, null); } private static DriverManagerDataSource dataSource(String schema) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwnerIntegrationTest.java index bc29afe19e..4efe44e058 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwnerIntegrationTest.java @@ -31,8 +31,8 @@ import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; import net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewCandidateRedisScriptContribution; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -77,6 +77,11 @@ class CanonicalGameplayOriginalNewCandidateRedisOwnerIntegrationTest { private TestSource source; private CanonicalGameplayOriginalNewCandidateRedisOwner owner; + @org.junit.jupiter.api.BeforeAll + static void awaitMappedPostgresReady() { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); + } + @org.junit.jupiter.api.BeforeEach void setUp() { administrator = createClient(null, null); @@ -819,14 +824,7 @@ private TestSource prepareSource() { dataSource.setUrl(jdbcUrl + (jdbcUrl.contains("?") ? "&" : "?") + "currentSchema=" + schema); dataSource.setUsername(POSTGRES.getUsername()); dataSource.setPassword(POSTGRES.getPassword()); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema(dataSource, schema, MIGRATION_LOCATION, null); DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); var runtime = CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource); seedSyntheticVerifiedLegacyDisposition(dsl); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java index 456651a736..57c04df334 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java @@ -52,7 +52,6 @@ import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; import net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountInitialBarrierRedisScriptContribution; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -1137,14 +1136,8 @@ private Fixture( private static Fixture open() throws Exception { String schema = "gs_incarnation_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = dataSource(schema); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, schema, MIGRATION_LOCATION, null); DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); UUID tenantId = UUID.randomUUID(); var runtime = @@ -1328,14 +1321,8 @@ private static InitialFixture open() throws Exception { private static InitialFixture open(BigInteger sourceControlEpoch) throws Exception { String schema = "gs_initial_incarnation_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = Fixture.dataSource(schema); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, schema, MIGRATION_LOCATION, null); DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); UUID tenantId = UUID.randomUUID(); var runtime = diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index 0af1d18ac7..9da9907574 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -82,7 +82,6 @@ import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRegionResponse; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationResponse; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.SQLDialect; @@ -144,9 +143,9 @@ static void certificates() throws Exception { void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws Exception { PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); ControlledConnectionFailureDataSource dataSource = dataSource(); - Flyway.configure() - .dataSource(dataSource) - .locations( + CanonicalGameplayIssuerTestFixtures.migrationConfiguration( + dataSource, + "public", "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) .load() .migrate(); @@ -1523,14 +1522,10 @@ private static TestSchema newTestSchema(String targetVersion) { private static org.flywaydb.core.api.configuration.FluentConfiguration regionMigrations( DataSource dataSource, String schema) { - return Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations( - "filesystem:" - + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()); + return CanonicalGameplayIssuerTestFixtures.migrationConfiguration( + dataSource, + schema, + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()); } private static void dropSchema(String schema) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java index 9e5f4778a6..f066e1a453 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java @@ -15,7 +15,6 @@ import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.SQLDialect; @@ -67,9 +66,9 @@ void setUpRepository() { dataSource.setUsername(POSTGRES.getUsername()); dataSource.setPassword(POSTGRES.getPassword()); - Flyway.configure() - .dataSource(dataSource) - .locations( + CanonicalGameplayIssuerTestFixtures.migrationConfiguration( + dataSource, + "public", "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) .load() .migrate(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepositoryPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepositoryPostgresIntegrationTest.java index fed8dcb237..f016f12c78 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepositoryPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepositoryPostgresIntegrationTest.java @@ -18,7 +18,6 @@ import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -43,14 +42,8 @@ void serializesFirstAllocationPreservesRestartMappingAndRejectsGlobalCrossVersio String schema = "gs_tenant_tag_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = dataSource(schema); try { - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, schema, MIGRATION_LOCATION, null); DSLContext dsl = dslForSchema(dataSource, schema); UUID tenantA = UUID.randomUUID(); @@ -210,14 +203,8 @@ void barrierTargetAssignmentLocksControlBeforeIntentAndTarget() throws Exception String schema = "gs_tenant_tag_lock_order_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = dataSource(schema); try { - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, schema, MIGRATION_LOCATION, null); DSLContext dsl = dslForSchema(dataSource, schema); UUID tenantId = UUID.randomUUID(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java index 1cbb0782a5..3f733165f8 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java @@ -40,6 +40,7 @@ import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerTestFixtures; import net.firedevops.firemud.gamesession.repository.CanonicalGameplayRosterReferenceRepository; import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; @@ -1275,6 +1276,7 @@ void pre1006CommittedAndAbortedRowsSurviveForwardProtectionMigration() throws Ex String v1011Guard = launchGuardProjection(predecessor, true); migration(predecessor, null).migrate(); migration(predecessor, null).validate(); + assertPrivateCatalogColumnsNull(predecessor, prepared.catalog().creationRequestId()); assertV1013RetentionLaunchForeignKey(predecessor); assertV1040CompletionForeignKeyTriggers(predecessor); assertThat( @@ -1845,6 +1847,10 @@ private record PredecessorAdmission( /** Entire original source, namespace, catalog, runtime, launch and original-pin heap evidence. */ private static String predecessorSourceProjection(Fixture fixture) { + String privateCatalogColumns = + CanonicalGameplayIssuerTestFixtures.PRIVATE_CATALOG_COLUMNS.stream() + .map(column -> "'" + column + "'") + .collect(java.util.stream.Collectors.joining(", ")); return fixture .dsl .fetchSingle( @@ -1855,7 +1861,9 @@ private static String predecessorSourceProjection(Fixture fixture) { + "(SELECT jsonb_agg(jsonb_build_array(xmin::TEXT, to_jsonb(source)) ORDER BY canonical_tenant_id) FROM game_session_tenant_canonical_claim source)," + "(SELECT jsonb_agg(jsonb_build_array(xmin::TEXT, to_jsonb(source)) ORDER BY to_jsonb(source)::TEXT) FROM game_session_tenant_scope_reservation source)," + "(SELECT jsonb_agg(jsonb_build_array(xmin::TEXT, to_jsonb(source)) ORDER BY canonical_tenant_id) FROM gameplay_tenant_shared_playable_state_namespace source)," - + "(SELECT jsonb_agg(jsonb_build_array(xmin::TEXT, to_jsonb(source) - ARRAY['fixture_policy_request_bytes', 'fixture_policy_seal_operation_id', 'fixture_policy_seal_request_digest', 'fixture_policy_seal_evidence_digest']) ORDER BY realm_id) FROM game_session_canonical_realm_catalog source)," + + "(SELECT jsonb_agg(jsonb_build_array(xmin::TEXT, to_jsonb(source) - ARRAY['fixture_policy_request_bytes', 'fixture_policy_seal_operation_id', 'fixture_policy_seal_request_digest', 'fixture_policy_seal_evidence_digest'] - ARRAY[" + + privateCatalogColumns + + "]) ORDER BY realm_id) FROM game_session_canonical_realm_catalog source)," + "(SELECT jsonb_agg(jsonb_build_array(xmin::TEXT, to_jsonb(source)) ORDER BY id) FROM game_instances source)," + "(SELECT jsonb_agg(jsonb_build_array(xmin::TEXT, to_jsonb(source) - ARRAY['fixture_policy_request_bytes', 'fixture_policy_seal_operation_id', 'fixture_policy_seal_request_digest', 'fixture_policy_seal_evidence_digest']) ORDER BY game_instance_id) FROM game_session_canonical_instance_launch source)," + "(SELECT jsonb_agg(jsonb_build_array(xmin::TEXT, to_jsonb(source)) ORDER BY owner_attempt_id) FROM game_session_start_session_operator_attempt source)," @@ -1864,6 +1872,28 @@ private static String predecessorSourceProjection(Fixture fixture) { .get("projection", String.class); } + private static void assertPrivateCatalogColumnsNull(Fixture fixture, UUID creationRequestId) { + String columns = + CanonicalGameplayIssuerTestFixtures.PRIVATE_CATALOG_COLUMNS.stream() + .map(column -> "'" + column + "'") + .collect(java.util.stream.Collectors.joining(", ")); + String nullChecks = + CanonicalGameplayIssuerTestFixtures.PRIVATE_CATALOG_COLUMNS.stream() + .map(column -> "to_jsonb(catalog) -> '" + column + "' = 'null'::jsonb") + .collect(java.util.stream.Collectors.joining(" AND ")); + var row = + fixture.dsl.fetchSingle( + "SELECT jsonb_exists_all(to_jsonb(catalog), ARRAY[" + + columns + + "]) AS has_all_columns, (" + + nullChecks + + ") AS all_null FROM game_session_canonical_realm_catalog catalog " + + "WHERE creation_request_id = ?", + creationRequestId); + assertThat(row.get("has_all_columns", Boolean.class)).isTrue(); + assertThat(row.get("all_null", Boolean.class)).isTrue(); + } + private static void seedPre1006ExpectedClosedTerminal( Fixture fixture, PreparedAdmission prepared, @@ -2391,12 +2421,10 @@ private static String pointerAndAuditProjection(Fixture fixture) { private static Flyway migration(Fixture fixture, String target) { String schema = fixture.dsl.fetchSingle("SELECT current_schema()").get(0, String.class); var configuration = - Flyway.configure() - .dataSource(Objects.requireNonNull(fixture.transactionManager.getDataSource())) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION); + CanonicalGameplayIssuerTestFixtures.migrationConfiguration( + Objects.requireNonNull(fixture.transactionManager.getDataSource()), + schema, + MIGRATION_LOCATION); if (target != null) { configuration.target(MigrationVersion.fromVersion(target)); } @@ -2569,17 +2597,8 @@ private Fixture fixture(String targetVersion) { dataSource.setUsername(postgres.getUsername()); dataSource.setPassword(postgres.getPassword()); dataSource.setSchema(schema); - var migration = - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION); - if (targetVersion != null) { - migration.target(MigrationVersion.fromVersion(targetVersion)); - } - migration.load().migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, schema, MIGRATION_LOCATION, targetVersion); DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); TransactionTemplate transactions = new TransactionTemplate(transactionManager); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ExactScriptPatchBaseMigrationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ExactScriptPatchBaseMigrationIntegrationTest.java index baf8c2b157..1accfc75fd 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ExactScriptPatchBaseMigrationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ExactScriptPatchBaseMigrationIntegrationTest.java @@ -81,7 +81,10 @@ void migrationRetainsLegacyScriptProvenanceWithoutBackfillingMutableRuntimeVersi + "'coord-1', 'followup-1', 'region-a', 1, 'region-b', 1, 'REMOTE_APPLIED', " + "CURRENT_TIMESTAMP, 'legacy-patch', 7, 9)"); - Flyway.configure().dataSource(dataSource).locations(MIGRATION_LOCATION).load().migrate(); + CanonicalGameplayIssuerTestFixtures.migrationConfiguration( + dataSource, "public", MIGRATION_LOCATION) + .load() + .migrate(); var legacyGameplayCommand = dsl.fetchOne( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceScriptPinMigrationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceScriptPinMigrationIntegrationTest.java index 1946c09b67..9f6383ce5f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceScriptPinMigrationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceScriptPinMigrationIntegrationTest.java @@ -5,7 +5,6 @@ import java.nio.file.Path; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.exception.DataAccessException; @@ -29,7 +28,10 @@ class GameInstanceScriptPinMigrationIntegrationTest { @Test void baselineEnforcesCoherentScriptPinTuplesAndUnpinnedMetadata() { DriverManagerDataSource dataSource = dataSource(); - Flyway.configure().dataSource(dataSource).locations(MIGRATION_LOCATION).load().migrate(); + CanonicalGameplayIssuerTestFixtures.migrationConfiguration( + dataSource, "public", MIGRATION_LOCATION) + .load() + .migrate(); DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); dsl.execute( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java index 5b077d0b50..a22292e506 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java @@ -14,6 +14,7 @@ import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerTestFixtures; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; @@ -285,12 +286,19 @@ void historicalCatalogAndAssociationRemainUnchangedWithoutPoisoningFreshDiscover assertThat(retainedCatalogState(fixture, historicalRequest.requestId())) .isEqualTo(catalogBefore); assertThat(retainedAssociationState(fixture, tenant(40))).isEqualTo(associationBefore); + String privateCatalogColumnsNull = + CanonicalGameplayIssuerTestFixtures.PRIVATE_CATALOG_COLUMNS.stream() + .map(column -> column + " IS NULL") + .collect(java.util.stream.Collectors.joining(" AND ")); assertThat( requiredRecord( fixture.dsl, "SELECT complete_policy_set_evidence IS NULL AND fixture_policy_request_bytes IS NULL " + "AND fixture_policy_seal_operation_id IS NULL AND fixture_policy_seal_request_digest IS NULL " - + "AND fixture_policy_seal_evidence_digest IS NULL AS historical " + + "AND fixture_policy_seal_evidence_digest IS NULL " + + "AND " + + privateCatalogColumnsNull + + " AS historical " + "FROM game_session_canonical_realm_catalog WHERE creation_request_id = ?", historicalRequest.requestId()) .get("historical", Boolean.class)) @@ -967,12 +975,8 @@ private Fixture fixture(boolean seedRetainedNumericRows, MigrationVersion target } FluentConfiguration migrationConfiguration = - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION); + CanonicalGameplayIssuerTestFixtures.migrationConfiguration( + dataSource, schema, MIGRATION_LOCATION); if (targetVersion != null) { migrationConfiguration.target(targetVersion); } @@ -993,11 +997,17 @@ private Fixture fixture(boolean seedRetainedNumericRows, MigrationVersion target } private static Record retainedCatalogState(Fixture fixture, UUID requestId) { + String privateCatalogColumnNames = + CanonicalGameplayIssuerTestFixtures.PRIVATE_CATALOG_COLUMNS.stream() + .map(column -> "'" + column + "'") + .collect(java.util.stream.Collectors.joining(", ")); return requiredRecord( fixture.dsl, "SELECT xmin::text AS xmin, (to_jsonb(catalog) - ARRAY['complete_policy_set_evidence', " + "'fixture_policy_request_bytes', 'fixture_policy_seal_operation_id', " - + "'fixture_policy_seal_request_digest', 'fixture_policy_seal_evidence_digest'])::text AS bytes " + + "'fixture_policy_seal_request_digest', 'fixture_policy_seal_evidence_digest', " + + privateCatalogColumnNames + + "])::text AS bytes " + "FROM game_session_canonical_realm_catalog catalog WHERE creation_request_id = ?", requestId); } @@ -1211,14 +1221,8 @@ private record Fixture( net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidence.PublishedSet> publishedSets) { void migrateToLatest() { - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, schema, MIGRATION_LOCATION, null); } IntakeReceipt register(UUID tenantId, String worldSlug, String displayName, String provenance) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java index b5aecb79bb..5b8db5d07b 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java @@ -22,6 +22,7 @@ import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerTestFixtures; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; @@ -31,7 +32,6 @@ import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository; import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.SQLDialect; @@ -541,14 +541,7 @@ private static Fixture fixture(boolean createRealm) { dataSource.setUsername(postgres.getUsername()); dataSource.setPassword(postgres.getPassword()); dataSource.setSchema(schema); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema(dataSource, schema, MIGRATION_LOCATION, null); DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); TransactionTemplate transactions = new TransactionTemplate(transactionManager); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCurrentPrivatePlaytestPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCurrentPrivatePlaytestPostgresIntegrationTest.java index 24f24e6d13..25aae26495 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCurrentPrivatePlaytestPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCurrentPrivatePlaytestPostgresIntegrationTest.java @@ -23,6 +23,7 @@ import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerTestFixtures; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCurrentPrivatePlaytestRepository; @@ -39,7 +40,6 @@ import net.firedevops.firemud.gamesession.repository.GameSessionInitialPlaytestLifecycleRepository.ReadState; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -411,14 +411,11 @@ private Context context(boolean privatePolicy) { dataSource.setUsername(postgres.getUsername()); dataSource.setPassword(postgres.getPassword()); dataSource.setSchema(schema); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .locations( - "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, + schema, + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(), + null); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); TransactionTemplate transaction = diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java index fde64b437f..ea98d13bfd 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java @@ -22,6 +22,7 @@ import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.gamesession.client.GameDesignFreshTenantCreationClient; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerTestFixtures; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldIntakeDigest; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; @@ -32,7 +33,6 @@ import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository.InvalidFreshTenantSourceException; import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -841,14 +841,7 @@ private Fixture fixture() { dataSource.setUsername(postgres.getUsername()); dataSource.setPassword(postgres.getPassword()); dataSource.setSchema(schema); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema(dataSource, schema, MIGRATION_LOCATION, null); DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); TransactionTemplate transactions = new TransactionTemplate(transactionManager); @@ -877,14 +870,7 @@ public Connection getConnection() throws SQLException { dataSource.setUsername(postgres.getUsername()); dataSource.setPassword(postgres.getPassword()); dataSource.setSchema(schema); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema(dataSource, schema, MIGRATION_LOCATION, null); DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); TransactionTemplate transactions = new TransactionTemplate(transactionManager); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantHistoryPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantHistoryPostgresIntegrationTest.java index c56a6bad01..647e436514 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantHistoryPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantHistoryPostgresIntegrationTest.java @@ -14,7 +14,6 @@ import java.util.stream.Collectors; import net.firedevops.firemud.gamesession.client.GameDesignFreshTenantCreationClient; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.exception.DataAccessException; @@ -163,14 +162,11 @@ void originalV25AssociationRetainsItsPhysicalRowsAndCannotGainMissingCreationAut } private static void migrate(DriverManagerDataSource source, String schema, String target) { - var configuration = - Flyway.configure() - .dataSource(source) - .schemas(schema) - .defaultSchema(schema) - .locations("filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath()); - if (target != null) configuration.target(target); - configuration.load().migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + source, + schema, + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath(), + target); } private static Map>> snapshot( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionInitialPlaytestLifecyclePostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionInitialPlaytestLifecyclePostgresIntegrationTest.java index bc5a48b717..5a9ad060c5 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionInitialPlaytestLifecyclePostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionInitialPlaytestLifecyclePostgresIntegrationTest.java @@ -2,10 +2,17 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; +import java.io.ByteArrayOutputStream; import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.SQLException; import java.time.Instant; import java.time.OffsetDateTime; +import java.util.HexFormat; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -14,14 +21,20 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidence; import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalPrivateFreshTargetSnapshot; import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerTestFixtures; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCurrentPrivatePlaytestRepository; import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository; import net.firedevops.firemud.gamesession.repository.GameSessionInitialPlaytestLifecycleRepository; import net.firedevops.firemud.gamesession.repository.GameSessionInitialPlaytestLifecycleRepository.Allocation; @@ -31,10 +44,12 @@ import net.firedevops.firemud.gamesession.repository.GameSessionInitialPlaytestLifecycleRepository.Request; import net.firedevops.firemud.gamesession.repository.GameSessionInitialPlaytestLifecycleRepository.Snapshot; import net.firedevops.firemud.gamesession.repository.GameSessionInitialPlaytestLifecycleRepository.SourceUnavailableException; +import net.firedevops.firemud.gamesession.repository.GameSessionPrivateFreshTargetRepository; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; +import org.awaitility.Awaitility; import org.jooq.DSLContext; +import org.jooq.Field; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.BeforeAll; @@ -42,6 +57,7 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -111,6 +127,15 @@ void retainsPrivateRealmDisplayNameAtCanonicalCodePointAndUtf8Limits() { request.requestId()); assertThat(row.get("characters", Integer.class)).isEqualTo(128); assertThat(row.get("bytes", Integer.class)).isEqualTo(512); + var privateTarget = + context.allocatePrivateTarget( + new GameSessionPrivateFreshTargetRepository.Request( + UUID.randomUUID(), request.requestId(), preparation.playtestLifecycleId())); + assertThat(privateTarget.snapshot().realmDisplayName()).isEqualTo(displayName); + assertThat(privateTarget.snapshot().visible()).isFalse(); + assertThat(privateTarget.snapshot().publicProduction()).isFalse(); + assertThat(context.dsl().fetchCount(DSL.table("gameplay_admission_pointer"))).isZero(); + assertThat(context.dsl().fetchCount(DSL.table("game_instances"))).isZero(); } @Test @@ -205,10 +230,692 @@ void allocatesFreshNonAdmissibleIdentityFromExactRetainedCanonicalSourceAndRepla assertThat(snapshot.admissionAllowed()).isFalse(); assertThat(context.count()).isEqualTo(1); assertThat(context.retainedRows()).usingRecursiveComparison().isEqualTo(retainedBefore); + } + + @Test + void + allocatesPrivateCatalogIdentityFromExactPreparationAndReadsBackWithoutPublicOrRuntimeEffects() { + Context context = context(true); + Request preparationRequest = + context.request(UUID.randomUUID(), "private-playtest", context.now().plusSeconds(3600)); + var preparation = context.prepare(preparationRequest).preparation(); + var publicCatalogBefore = context.publicCatalogRow(); + var namespaceRowsBefore = context.namespaceRows(); + var targetRequest = + new GameSessionPrivateFreshTargetRepository.Request( + UUID.randomUUID(), + preparation.request().requestId(), + preparation.playtestLifecycleId()); + + var allocated = context.allocatePrivateTarget(targetRequest); + CanonicalPrivateFreshTargetSnapshot target = allocated.snapshot(); + assertThat(allocated.replayed()).isFalse(); + assertThat(target.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(target.tenantId()).isEqualTo(preparation.request().tenantId()); + assertThat(target.worldSlug()).isEqualTo(preparation.request().worldSlug()); + assertThat(target.realmSlug()).isEqualTo(preparation.request().realmSlug()); + assertThat(target.sourceCatalogRealmId()).isEqualTo(context.catalog().realmId()); + assertThat(target.realmId()) + .isNotEqualTo(target.sourceCatalogRealmId()) + .isNotEqualTo(preparation.source().targetPolicy().policyId()); + assertThat(target.playableStateNamespaceId()).isEqualTo(preparation.playableStateNamespaceId()); + assertThat(target.playtestLifecycleId()).isEqualTo(preparation.playtestLifecycleId()); + assertThat(target.playtestStateGeneration()).isEqualTo(1); + assertThat(target.catalogRevision()).isEqualTo(1); + assertThat(target.visible()).isFalse(); + assertThat(target.publicProduction()).isFalse(); + assertThat(target.stateScope()).isEqualTo("ISOLATED"); + assertThat(target.preparationState()).isEqualTo("PREPARING"); + assertThat(target.admissionAllowed()).isFalse(); + assertThat(target.realmDisplayName()) + .isEqualTo(preparation.source().targetPolicy().source().policy().realmDisplayName()); + assertThat(target.characterCreationPolicy()) + .isEqualTo(preparation.source().targetPolicy().source().policy().entryPolicy().name()); + assertThat(target.targetPolicyId()).isEqualTo(preparation.source().targetPolicy().policyId()); + assertThat(target.targetPolicyDigest()) + .isEqualTo(preparation.source().targetPolicy().policyDigest()); + assertThat(target.canonicalVersionId()).isEqualTo(preparation.source().canonicalVersionId()); + assertThat(target.publishedReleaseBundleRef()) + .isEqualTo(preparation.source().publishedReleaseBundleRef()); + assertThat(target.publishedReleaseBundleDigest()) + .isEqualTo(preparation.source().publishedReleaseBundleDigest()); + + var independentlyRead = + context + .privateTargets() + .readByPreparation(preparation.request().requestId(), preparation.playtestLifecycleId()) + .orElseThrow(); + assertThat(independentlyRead).isEqualTo(target); + assertThat(context.allocatePrivateTarget(targetRequest)) + .isEqualTo(new GameSessionPrivateFreshTargetRepository.Allocation(target, true)); + assertThat(context.publicCatalogRow()).isEqualTo(publicCatalogBefore); + assertThat(context.namespaceRows()).isEqualTo(namespaceRowsBefore); + assertThat(context.catalogs().readVisiblePublicProductionSnapshots(NAMESPACE)) + .containsExactly(context.catalog()); + assertThat(context.dsl().fetchCount(DSL.table("game_session_canonical_realm_catalog"))) + .isEqualTo(2); + assertThat(context.dsl().fetchCount(DSL.table("gameplay_admission_pointer"))).isZero(); + assertThat(context.dsl().fetchCount(DSL.table("game_instances"))).isZero(); + assertThat(context.dsl().fetchCount(DSL.table("gameplay_published_realm_catalog_entry"))) + .isZero(); + } + + @Test + void laterPreparationAndSelectionRemainAvailableAfterPriorPrivateCatalogAllocation() { + Context context = context(true); + Request firstRequest = + context.request(UUID.randomUUID(), "private-playtest", context.now().plusSeconds(3600)); + var firstPreparation = context.prepare(firstRequest).preparation(); + var selectionRepository = new GameSessionCurrentPrivatePlaytestRepository(context.dsl()); + var scope = + new GameSessionCurrentPrivatePlaytestRepository.Scope( + NAMESPACE, firstRequest.tenantId(), firstRequest.worldSlug(), firstRequest.realmSlug()); + var firstSelectionRequest = + new GameSessionCurrentPrivatePlaytestRepository.Request( + UUID.randomUUID(), + scope, + firstPreparation.request().requestId(), + firstPreparation.playtestLifecycleId(), + null, + null); + var firstSelection = + Objects.requireNonNull( + context + .transaction() + .execute(status -> selectionRepository.select(firstSelectionRequest))); + assertThat(firstSelection.replayed()).isFalse(); + assertThat(firstSelection.receipt().headRevision()).isEqualTo(1L); + var firstPrivateTargetRequest = + new GameSessionPrivateFreshTargetRepository.Request( + UUID.randomUUID(), + firstPreparation.request().requestId(), + firstPreparation.playtestLifecycleId()); + var firstPrivateTarget = context.allocatePrivateTarget(firstPrivateTargetRequest); + assertThat(firstPrivateTarget.replayed()).isFalse(); + + String privateCatalogBefore = privateCatalogRow(context, firstPrivateTargetRequest.requestId()); + String firstPreparationBefore = + retainedRowWithXmin(context, TABLE, "request_id", firstPreparation.request().requestId()); + String firstSelectionBefore = + retainedRowWithXmin( + context, + "game_session_private_playtest_selections", + "request_id", + firstSelectionRequest.requestId()); + byte[] firstPreparationRequestBytes = + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT request_preimage FROM " + TABLE + " WHERE request_id = ?", + firstPreparation.request().requestId())) + .get("request_preimage", byte[].class); + byte[] firstSelectionRequestBytes = + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT request_preimage FROM game_session_private_playtest_selections WHERE request_id = ?", + firstSelectionRequest.requestId())) + .get("request_preimage", byte[].class); + var publicCatalogBefore = context.publicCatalogRow(); + String sourceIntakeBefore = + retainedRowWithXmin( + context, + "game_session_authored_world_source_intake", + "operation_id", + context.catalog().sourceIntakeReceipt().operationId()); + String sourceBindingBefore = + retainedRowWithXmin( + context, + "game_session_authored_world_tenant_source_binding", + "canonical_tenant_id", + context.catalog().tenantId()); + var namespaceRowsBefore = context.namespaceRows(); + + Request laterRequest = + context.request( + UUID.randomUUID(), firstRequest.realmSlug(), context.now().plusSeconds(7200)); + var laterAllocation = context.prepare(laterRequest); + assertThat(laterAllocation.replayed()).isFalse(); + var laterPreparation = laterAllocation.preparation(); + assertThat(laterPreparation.request().realmSlug()).isEqualTo(firstRequest.realmSlug()); + assertThat(laterPreparation.request().requestId()) + .isNotEqualTo(firstPreparation.request().requestId()); + assertThat(laterPreparation.playtestLifecycleId()) + .isNotEqualTo(firstPreparation.playtestLifecycleId()); + assertThat(laterPreparation.playableStateNamespaceId()) + .isNotEqualTo(firstPreparation.playableStateNamespaceId()); + assertThat(laterPreparation.playtestStateGeneration()).isEqualTo(1); + + var replacementSelectionRequest = + new GameSessionCurrentPrivatePlaytestRepository.Request( + UUID.randomUUID(), + scope, + laterPreparation.request().requestId(), + laterPreparation.playtestLifecycleId(), + 1L, + firstPreparation.playtestLifecycleId()); + var replacementSelection = + Objects.requireNonNull( + context + .transaction() + .execute(status -> selectionRepository.select(replacementSelectionRequest))); + assertThat(replacementSelection.replayed()).isFalse(); + assertThat(replacementSelection.receipt().headRevision()).isEqualTo(2L); + String replacementSelectionBeforeReplay = + retainedRowWithXmin( + context, + "game_session_private_playtest_selections", + "request_id", + replacementSelectionRequest.requestId()); + String replacementHeadBeforeReplay = + retainedRowWithXmin( + context, + "game_session_current_private_playtests", + "selection_request_id", + replacementSelectionRequest.requestId()); + var current = + Objects.requireNonNull( + context + .transaction() + .execute( + status -> + selectionRepository + .readCurrent( + NAMESPACE, scope.tenantId(), scope.worldSlug(), scope.realmSlug()) + .orElseThrow())); + assertThat(current.selection()).isEqualTo(replacementSelection.receipt()); + assertThat(current.selectedPrepSnapshot().preparation()).isEqualTo(laterPreparation); + assertThat(current.selectedPrepSnapshot().state()).isEqualTo(ReadState.INCOMPLETE); + assertThat(current.admissionAllowed()).isFalse(); + assertThat(current.selectedPrepSnapshot().admissionAllowed()).isFalse(); + + assertThat(context.prepare(firstRequest)).isEqualTo(new Allocation(firstPreparation, true)); + assertThat(context.read(firstRequest, firstPreparation.playtestLifecycleId()).preparation()) + .isEqualTo(firstPreparation); + var firstSelectionReplay = + Objects.requireNonNull( + context + .transaction() + .execute(status -> selectionRepository.select(firstSelectionRequest))); + assertThat(firstSelectionReplay) + .isEqualTo( + new GameSessionCurrentPrivatePlaytestRepository.SelectionResult( + firstSelection.receipt(), true)); + assertThat(context.allocatePrivateTarget(firstPrivateTargetRequest)) + .isEqualTo( + new GameSessionPrivateFreshTargetRepository.Allocation( + firstPrivateTarget.snapshot(), true)); + assertThat(context.prepare(laterRequest)).isEqualTo(new Allocation(laterPreparation, true)); + + assertThat(context.count()).isEqualTo(2); + assertThat(context.dsl().fetchCount(DSL.table("game_session_private_playtest_selections"))) + .isEqualTo(2); + assertThat( + retainedRowWithXmin( + context, + "game_session_private_playtest_selections", + "request_id", + firstSelectionRequest.requestId())) + .isEqualTo(firstSelectionBefore); + assertThat( + retainedRowWithXmin( + context, + "game_session_private_playtest_selections", + "request_id", + replacementSelectionRequest.requestId())) + .isEqualTo(replacementSelectionBeforeReplay); + assertThat( + retainedRowWithXmin( + context, + "game_session_current_private_playtests", + "selection_request_id", + replacementSelectionRequest.requestId())) + .isEqualTo(replacementHeadBeforeReplay); + assertThat( + retainedRowWithXmin( + context, TABLE, "request_id", firstPreparation.request().requestId())) + .isEqualTo(firstPreparationBefore); + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT request_preimage FROM " + TABLE + " WHERE request_id = ?", + firstPreparation.request().requestId())) + .get("request_preimage", byte[].class)) + .containsExactly(firstPreparationRequestBytes); + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT request_preimage FROM game_session_private_playtest_selections WHERE request_id = ?", + firstSelectionRequest.requestId())) + .get("request_preimage", byte[].class)) + .containsExactly(firstSelectionRequestBytes); + assertThat(privateCatalogRow(context, firstPrivateTargetRequest.requestId())) + .isEqualTo(privateCatalogBefore); + assertThat(context.publicCatalogRow()).isEqualTo(publicCatalogBefore); + assertThat( + retainedRowWithXmin( + context, + "game_session_authored_world_source_intake", + "operation_id", + context.catalog().sourceIntakeReceipt().operationId())) + .isEqualTo(sourceIntakeBefore); + assertThat( + retainedRowWithXmin( + context, + "game_session_authored_world_tenant_source_binding", + "canonical_tenant_id", + context.catalog().tenantId())) + .isEqualTo(sourceBindingBefore); + assertThat(context.namespaceRows()).usingRecursiveComparison().isEqualTo(namespaceRowsBefore); + assertThat(context.dsl().fetchCount(DSL.table("game_session_canonical_realm_catalog"))) + .isEqualTo(2); + assertThat( + context + .dsl() + .fetchSingle( + "SELECT count(*) FROM game_session_canonical_realm_catalog WHERE private_preparation_request_id IS NOT NULL") + .get(0, Long.class)) + .isEqualTo(1L); + assertThat(context.dsl().fetchCount(DSL.table("gameplay_admission_pointer"))).isZero(); + assertThat(context.dsl().fetchCount(DSL.table("game_instances"))).isZero(); + var currentAfterReplay = + Objects.requireNonNull( + context + .transaction() + .execute( + status -> + selectionRepository + .readCurrent( + NAMESPACE, scope.tenantId(), scope.worldSlug(), scope.realmSlug()) + .orElseThrow())); + assertThat(currentAfterReplay.selection()).isEqualTo(replacementSelection.receipt()); + assertThat(currentAfterReplay.admissionAllowed()).isFalse(); + } + + @Test + void privateCatalogRequestRejectsChangedPreparationLifecycleAndSecondRequestForOnePreparation() { + Context context = context(true); + Request preparationRequest = + context.request(UUID.randomUUID(), "private-playtest", context.now().plusSeconds(3600)); + var preparation = context.prepare(preparationRequest).preparation(); + var requestId = UUID.randomUUID(); + var original = + new GameSessionPrivateFreshTargetRepository.Request( + requestId, preparation.request().requestId(), preparation.playtestLifecycleId()); + var allocation = context.allocatePrivateTarget(original); + + assertThatThrownBy( + () -> + context.allocatePrivateTarget( + new GameSessionPrivateFreshTargetRepository.Request( + requestId, UUID.randomUUID(), preparation.playtestLifecycleId()))) + .isInstanceOf(GameSessionPrivateFreshTargetRepository.IdempotencyConflictException.class); + assertThatThrownBy( + () -> + context.allocatePrivateTarget( + new GameSessionPrivateFreshTargetRepository.Request( + requestId, preparation.request().requestId(), UUID.randomUUID()))) + .isInstanceOf(GameSessionPrivateFreshTargetRepository.IdempotencyConflictException.class); + assertThatThrownBy( + () -> + context.allocatePrivateTarget( + new GameSessionPrivateFreshTargetRepository.Request( + UUID.randomUUID(), + preparation.request().requestId(), + preparation.playtestLifecycleId()))) + .isInstanceOf(GameSessionPrivateFreshTargetRepository.IdempotencyConflictException.class); + assertThatThrownBy( + () -> + context.allocatePrivateTarget( + new GameSessionPrivateFreshTargetRepository.Request( + UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()))) + .isInstanceOf( + GameSessionPrivateFreshTargetRepository.PreparationUnavailableException.class); + assertThat(context.allocatePrivateTarget(original).snapshot()).isEqualTo(allocation.snapshot()); + assertThat(context.dsl().fetchCount(DSL.table("game_session_canonical_realm_catalog"))) + .isEqualTo(2); + } + + @Test + void committedPrivateCatalogOutcomeReplaysAfterExpiryWithoutAllocatingOrRenewingAdmission() { + Context context = context(true); + Request preparationRequest = + context.request(UUID.randomUUID(), "private-playtest", context.now().plusSeconds(5)); + var preparation = context.prepare(preparationRequest).preparation(); + var targetRequest = + new GameSessionPrivateFreshTargetRepository.Request( + UUID.randomUUID(), + preparation.request().requestId(), + preparation.playtestLifecycleId()); + var original = context.allocatePrivateTarget(targetRequest); + assertThat(original.replayed()).isFalse(); + String retainedRow = + context + .dsl() + .fetchSingle( + "SELECT to_jsonb(c)::text||':'||xmin::text FROM game_session_canonical_realm_catalog c WHERE creation_request_id=?", + targetRequest.requestId()) + .get(0, String.class); + awaitExpiry(context, preparationRequest.forkExpiresAt()); + assertThat(context.read(preparationRequest, preparation.playtestLifecycleId()).state()) + .isEqualTo(ReadState.EXPIRED); + + var retry = context.allocatePrivateTarget(targetRequest); + assertThat(retry.replayed()).isTrue(); + assertThat(retry.snapshot()).isEqualTo(original.snapshot()); + assertThat(retry.snapshot().admissionAllowed()).isFalse(); + assertThat( + context + .dsl() + .fetchSingle( + "SELECT to_jsonb(c)::text||':'||xmin::text FROM game_session_canonical_realm_catalog c WHERE creation_request_id=?", + targetRequest.requestId()) + .get(0, String.class)) + .isEqualTo(retainedRow); + assertThatThrownBy( + () -> + context.allocatePrivateTarget( + new GameSessionPrivateFreshTargetRepository.Request( + UUID.randomUUID(), + preparation.request().requestId(), + preparation.playtestLifecycleId()))) + .isInstanceOf( + GameSessionPrivateFreshTargetRepository.PreparationUnavailableException.class); + assertThatThrownBy( + () -> + context.allocatePrivateTarget( + new GameSessionPrivateFreshTargetRepository.Request( + targetRequest.requestId(), + preparation.request().requestId(), + UUID.randomUUID()))) + .isInstanceOf(GameSessionPrivateFreshTargetRepository.IdempotencyConflictException.class); + assertThat(context.dsl().fetchCount(DSL.table("game_session_canonical_realm_catalog"))) + .isEqualTo(2); assertThat(context.dsl().fetchCount(DSL.table("gameplay_admission_pointer"))).isZero(); assertThat(context.dsl().fetchCount(DSL.table("game_instances"))).isZero(); } + @Test + void expiredPreparationCannotAllocatePrivateCatalogIdentity() { + Context context = context(true); + Request preparationRequest = + context.request(UUID.randomUUID(), "private-playtest", context.now().plusSeconds(5)); + var preparation = context.prepare(preparationRequest).preparation(); + awaitExpiry(context, preparationRequest.forkExpiresAt()); + + assertThatThrownBy( + () -> + context.allocatePrivateTarget( + new GameSessionPrivateFreshTargetRepository.Request( + UUID.randomUUID(), + preparation.request().requestId(), + preparation.playtestLifecycleId()))) + .isInstanceOf(GameSessionPrivateFreshTargetRepository.PreparationUnavailableException.class) + .hasMessageContaining("expired"); + assertThat(context.dsl().fetchCount(DSL.table("game_session_canonical_realm_catalog"))) + .isEqualTo(1); + } + + @Test + void privateCatalogSqlGuardRejectsReplacementNamespaceAndRollsBackInsert() { + Context context = context(true); + Request preparationRequest = + context.request(UUID.randomUUID(), "private-playtest", context.now().plusSeconds(3600)); + var preparation = context.prepare(preparationRequest).preparation(); + UUID requestId = UUID.randomUUID(); + UUID wrongNamespace = UUID.randomUUID(); + byte[] requestPreimage = + frame( + "game-session-private-fresh-catalog-request/v1", + requestId.toString(), + preparation.request().requestId().toString(), + preparation.playtestLifecycleId().toString(), + preparation.requestDigest()); + String requestDigest = sha256(requestPreimage); + String sql = + """ + INSERT INTO game_session_canonical_realm_catalog ( + target_namespace, canonical_tenant_id, tenant_slug, world_slug, realm_id, realm_slug, + realm_display_name, visible, public_production, state_scope, playable_state_namespace_id, + character_creation_policy, catalog_revision, creation_request_id, request_digest, + receipt_digest, source_intake_operation_id, source_intake_schema_version, + source_intake_request_id, source_intake_request_digest, source_intake_receipt_digest, + source_schema_version, source_registration_request_id, source_operation_id, + source_request_digest, source_world_display_name, source_game_row_id, + source_game_tenant_key, source_provenance_kind, source_evidence_digest, + complete_policy_set_evidence, private_target_request_preimage, + private_preparation_request_id, private_playtest_lifecycle_id, + private_preparation_request_digest, private_state_generation, + private_source_catalog_realm_id, private_source_catalog_request_id, + private_source_catalog_revision, private_source_catalog_receipt_digest, + private_target_policy_id, private_target_policy_digest, + private_target_policy_source_commit_id, private_target_policy_source_revision_id, + private_target_policy_logical_revision_id, private_canonical_version_id, + private_published_release_bundle_ref, private_published_release_bundle_digest, + private_source_policy_set_digest, private_source_policy_carrier_digest) + SELECT p.target_namespace, p.canonical_tenant_id, source.tenant_slug, p.world_slug, + gen_random_uuid(), p.realm_slug, p.target_policy_realm_display_name, false, false, + 'ISOLATED', ?, p.target_policy_entry_policy, 1, ?, ?, + 'sha256:0000000000000000000000000000000000000000000000000000000000000000', + source.source_intake_operation_id, source.source_intake_schema_version, + source.source_intake_request_id, source.source_intake_request_digest, + source.source_intake_receipt_digest, source.source_schema_version, + source.source_registration_request_id, source.source_operation_id, + source.source_request_digest, source.source_world_display_name, source.source_game_row_id, + source.source_game_tenant_key, source.source_provenance_kind, source.source_evidence_digest, + source.complete_policy_set_evidence, ?, p.request_id, p.playtest_lifecycle_id, + p.request_digest, p.playtest_state_generation, p.source_catalog_realm_id, + p.source_catalog_request_id, p.source_catalog_revision, p.source_catalog_receipt_digest, + p.target_policy_id, p.target_policy_digest, p.target_policy_source_commit_id, + p.target_policy_source_revision_id, p.target_policy_logical_revision_id, + p.canonical_version_id, p.published_release_bundle_ref, + p.published_release_bundle_digest, p.source_policy_set_digest, + p.source_policy_carrier_digest + FROM game_session_initial_playtest_preparations p + JOIN game_session_canonical_realm_catalog source + ON source.target_namespace = p.target_namespace + AND source.canonical_tenant_id = p.canonical_tenant_id + AND source.realm_id = p.source_catalog_realm_id + WHERE p.request_id = ? AND p.playtest_lifecycle_id = ? + """; + + assertThatThrownBy( + () -> + context + .serializableTransaction() + .executeWithoutResult( + status -> + context + .dsl() + .execute( + sql, + wrongNamespace, + requestId, + requestDigest, + requestPreimage, + preparation.request().requestId(), + preparation.playtestLifecycleId()))) + .isInstanceOf(RuntimeException.class) + .hasStackTraceContaining( + "Private FRESH catalog row differs from its exact retained preparation"); + // A NULL build reference must not turn the SQL guard and receipt conjunction into UNKNOWN. + // This uses the real guarded INSERT, a matching namespace and the same rolled-back intent. + String nullBuildSql = + sql.replace( + "p.canonical_version_id, p.published_release_bundle_ref,", + "p.canonical_version_id, NULL,"); + assertThat(nullBuildSql).isNotEqualTo(sql); + assertThatThrownBy( + () -> + context + .serializableTransaction() + .executeWithoutResult( + status -> + context + .dsl() + .execute( + nullBuildSql, + preparation.playableStateNamespaceId(), + requestId, + requestDigest, + requestPreimage, + preparation.request().requestId(), + preparation.playtestLifecycleId()))) + .isInstanceOf(RuntimeException.class) + .hasStackTraceContaining("chk_gs_private_fresh_catalog_binding"); + assertThat(context.dsl().fetchCount(DSL.table("game_session_canonical_realm_catalog"))) + .isEqualTo(1); + assertThat(context.dsl().fetchCount(DSL.table("gameplay_admission_pointer"))).isZero(); + } + + @Test + void canonicalIntakeGuardRejectsPrivateForgedTenantSlugWithRecomputedReceipt() { + Context context = context(true); + Request preparationRequest = + context.request(UUID.randomUUID(), "private-playtest", context.now().plusSeconds(3600)); + var preparation = context.prepare(preparationRequest).preparation(); + UUID creationRequestId = UUID.randomUUID(); + var targetRequest = + new GameSessionPrivateFreshTargetRepository.Request( + creationRequestId, + preparation.request().requestId(), + preparation.playtestLifecycleId()); + var publicCatalogBefore = context.publicCatalogRow(); + DetachedCatalogRow rolledBackPrivateRow = + Objects.requireNonNull( + context + .serializableTransaction() + .execute( + status -> { + context.privateTargets().allocate(targetRequest); + var genuine = + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT * FROM game_session_canonical_realm_catalog WHERE creation_request_id = ?", + creationRequestId)); + DetachedCatalogRow detachedValues = + new DetachedCatalogRow( + new LinkedHashMap<>(genuine.intoMap()), + List.copyOf(java.util.Arrays.asList(genuine.fields()))); + status.setRollbackOnly(); + return detachedValues; + })); + assertThat( + context + .privateTargets() + .readByPreparation( + preparation.request().requestId(), preparation.playtestLifecycleId())) + .isEmpty(); + assertThat(context.dsl().fetchCount(DSL.table("game_session_canonical_realm_catalog"))) + .isEqualTo(1); + + String sourceTenantSlug = + context + .dsl() + .fetchSingle( + "SELECT tenant_slug FROM game_session_canonical_realm_catalog WHERE realm_id = ?", + context.catalog().realmId()) + .get(0, String.class); + assertThat(rolledBackPrivateRow.values().get("tenant_slug")).isEqualTo(sourceTenantSlug); + String forgedTenantSlug = "forged-" + sourceTenantSlug; + assertThat(forgedTenantSlug).isNotEqualTo(sourceTenantSlug); + String forgedReceiptDigest = + privateCatalogReceiptDigest(rolledBackPrivateRow.values(), forgedTenantSlug); + assertThat(forgedReceiptDigest) + .startsWith("sha256:") + .isNotEqualTo(rolledBackPrivateRow.values().get("receipt_digest")); + + Map forged = new LinkedHashMap<>(rolledBackPrivateRow.values()); + forged.put("tenant_slug", forgedTenantSlug); + forged.put("receipt_digest", forgedReceiptDigest); + Field[] insertFields = new Field[rolledBackPrivateRow.fields().size()]; + Object[] values = new Object[insertFields.length]; + for (int index = 0; index < insertFields.length; index++) { + Field originalField = rolledBackPrivateRow.fields().get(index); + insertFields[index] = + DSL.field(DSL.name(originalField.getName()), originalField.getDataType()); + values[index] = forged.get(originalField.getName()); + } + Throwable insertFailure = + catchThrowable( + () -> + context + .serializableTransaction() + .executeWithoutResult( + status -> + context + .dsl() + .insertInto( + DSL.table(DSL.name("game_session_canonical_realm_catalog")), + insertFields) + .values(values) + .execute())); + String failureSummary = databaseFailureSummary(insertFailure); + assertThat(insertFailure) + .as("Forged INSERT failure should expose its database cause: %s", failureSummary) + .isNotNull(); + assertThat(sqlStateInCauseChain(insertFailure)) + .as("Expected SQLSTATE 23514; actual database failure: %s", failureSummary) + .isEqualTo("23514"); + assertThat(insertFailure) + .hasStackTraceContaining( + "Canonical realm catalog requires exact committed authored-world intake evidence"); + + assertThat(context.publicCatalogRow()).isEqualTo(publicCatalogBefore); + assertThat( + context + .privateTargets() + .readByPreparation( + preparation.request().requestId(), preparation.playtestLifecycleId())) + .isEmpty(); + assertThat(context.dsl().fetchCount(DSL.table("game_session_canonical_realm_catalog"))) + .isEqualTo(1); + assertThat(context.dsl().fetchCount(DSL.table("gameplay_admission_pointer"))).isZero(); + assertThat(context.dsl().fetchCount(DSL.table("game_instances"))).isZero(); + } + + @Test + void privateCatalogCommitGuardRechecksPreparationExpiry() { + Context context = context(true); + Request preparationRequest = + context.request(UUID.randomUUID(), "private-playtest", context.now().plusSeconds(5)); + var preparation = context.prepare(preparationRequest).preparation(); + var targetRequest = + new GameSessionPrivateFreshTargetRepository.Request( + UUID.randomUUID(), + preparation.request().requestId(), + preparation.playtestLifecycleId()); + + assertThatThrownBy( + () -> + context + .serializableTransaction() + .executeWithoutResult( + status -> { + context.privateTargets().allocate(targetRequest); + awaitExpiry(context, preparationRequest.forkExpiresAt()); + })) + .isInstanceOf(RuntimeException.class) + .hasStackTraceContaining( + "Private FRESH catalog preparation expired before final catalog commit"); + assertThat(context.dsl().fetchCount(DSL.table("game_session_canonical_realm_catalog"))) + .isEqualTo(1); + assertThat( + context + .privateTargets() + .readByPreparation( + preparation.request().requestId(), preparation.playtestLifecycleId())) + .isEmpty(); + } + @Test void changedIntentUnderOneRequestConflictsBeforeSourceLookupOrAllocation() { Context context = context(true); @@ -484,6 +1191,115 @@ void concurrentExactRequestAllocatesOnceAndNewRequestsForSameRealmGetDistinctIde } } + @Test + void staleSerializableSnapshotMustRetryPrivateAllocationInANewOwnerTransaction() + throws Exception { + Context context = context(true); + Request preparationRequest = + context.request(UUID.randomUUID(), "private-playtest", context.now().plusSeconds(3600)); + var preparation = context.prepare(preparationRequest).preparation(); + var targetRequest = + new GameSessionPrivateFreshTargetRepository.Request( + UUID.randomUUID(), + preparation.request().requestId(), + preparation.playtestLifecycleId()); + CountDownLatch firstAllocationHeld = new CountDownLatch(1); + CountDownLatch secondSnapshotEstablished = new CountDownLatch(1); + CountDownLatch releaseFirstAllocation = new CountDownLatch(1); + AtomicInteger secondBackendPid = new AtomicInteger(); + AtomicReference staleFailure = new AtomicReference<>(); + var executor = Executors.newFixedThreadPool(2); + try { + var firstAllocation = + new AtomicReference(); + var first = + executor.submit( + () -> + Objects.requireNonNull( + context + .serializableTransaction() + .execute( + status -> { + var allocated = context.privateTargets().allocate(targetRequest); + firstAllocation.set(allocated); + firstAllocationHeld.countDown(); + await(releaseFirstAllocation); + return allocated; + }))); + await(firstAllocationHeld); + + var second = + executor.submit( + () -> { + try { + context + .serializableTransaction() + .executeWithoutResult( + status -> { + var visibleBeforeCommit = + context + .dsl() + .fetchSingle( + "SELECT count(*) FROM game_session_canonical_realm_catalog WHERE private_preparation_request_id = ?", + preparation.request().requestId()) + .get(0, Long.class); + assertThat(visibleBeforeCommit).isZero(); + secondBackendPid.set( + context + .dsl() + .fetchSingle("SELECT pg_backend_pid()") + .get(0, Integer.class)); + secondSnapshotEstablished.countDown(); + context.privateTargets().allocate(targetRequest); + }); + } catch (Throwable failure) { + staleFailure.set(failure); + } + }); + await(secondSnapshotEstablished); + awaitAdvisoryLockWait(context, secondBackendPid.get()); + releaseFirstAllocation.countDown(); + + first.get(60, TimeUnit.SECONDS); + second.get(60, TimeUnit.SECONDS); + Throwable failure = staleFailure.get(); + assertThat(failure) + .as("stale SERIALIZABLE allocation must refuse with 40001 instead of committing") + .isNotNull(); + assertThat(sqlStateInCauseChain(failure)).isEqualTo("40001"); + + var committed = Objects.requireNonNull(firstAllocation.get()); + String retainedRowBeforeRetry = privateCatalogRow(context, targetRequest.requestId()); + // This is manual caller composition in the test, not automatic production retry behavior. + var freshTransactionRetry = context.allocatePrivateTarget(targetRequest); + assertThat(freshTransactionRetry.replayed()).isTrue(); + assertThat(freshTransactionRetry.snapshot()).isEqualTo(committed.snapshot()); + assertThat(freshTransactionRetry.snapshot().realmId()) + .isEqualTo(committed.snapshot().realmId()); + assertThat(freshTransactionRetry.snapshot().receiptDigest()) + .isEqualTo(committed.snapshot().receiptDigest()); + assertThat(privateCatalogRow(context, targetRequest.requestId())) + .isEqualTo(retainedRowBeforeRetry); + assertThat( + context + .dsl() + .fetchSingle( + "SELECT count(*) FROM game_session_canonical_realm_catalog WHERE private_preparation_request_id = ?", + preparation.request().requestId()) + .get(0, Long.class)) + .isEqualTo(1L); + assertThat(context.dsl().fetchCount(DSL.table("gameplay_admission_pointer"))).isZero(); + assertThat(context.dsl().fetchCount(DSL.table("game_instances"))).isZero(); + } finally { + releaseFirstAllocation.countDown(); + executor.shutdown(); + if (!executor.awaitTermination(30, TimeUnit.SECONDS)) { + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + } + } + @Test void exactReadRejectsWrongLifecycleAndReportsRealExpiryWithoutChangingOriginal() { Context context = context(true); @@ -674,6 +1490,127 @@ private static void await(CountDownLatch latch) { } } + private static void awaitAdvisoryLockWait(Context context, int backendPid) { + Awaitility.await() + .atMost(30, TimeUnit.SECONDS) + .pollInterval(10, TimeUnit.MILLISECONDS) + .untilAsserted( + () -> { + var activity = + context + .dsl() + .fetchOne( + "SELECT wait_event_type, wait_event FROM pg_stat_activity WHERE pid = ?", + backendPid); + assertThat(activity).isNotNull(); + assertThat(activity.get("wait_event_type", String.class)).isEqualTo("Lock"); + assertThat(activity.get("wait_event", String.class)).isEqualTo("advisory"); + }); + } + + private static String privateCatalogRow(Context context, UUID requestId) { + return context + .dsl() + .fetchSingle( + "SELECT to_jsonb(c)::text || ':' || xmin::text FROM game_session_canonical_realm_catalog c WHERE creation_request_id = ?", + requestId) + .get(0, String.class); + } + + private static String retainedRowWithXmin( + Context context, String tableName, String identityColumn, UUID identity) { + return context + .dsl() + .fetchSingle( + "SELECT to_jsonb(retained)::text || ':' || xmin::text FROM " + + tableName + + " retained WHERE " + + identityColumn + + " = ?", + identity) + .get(0, String.class); + } + + private static String privateCatalogReceiptDigest(Map row, String tenantSlug) { + return sha256( + frame( + "game-session-private-fresh-catalog-receipt/v1", + privateCatalogReceiptField(row, "creation_request_id"), + privateCatalogReceiptField(row, "request_digest"), + privateCatalogReceiptField(row, "target_namespace"), + privateCatalogReceiptField(row, "canonical_tenant_id"), + tenantSlug, + privateCatalogReceiptField(row, "world_slug"), + privateCatalogReceiptField(row, "realm_id"), + privateCatalogReceiptField(row, "realm_slug"), + privateCatalogReceiptField(row, "realm_display_name"), + privateCatalogReceiptField(row, "visible"), + privateCatalogReceiptField(row, "public_production"), + privateCatalogReceiptField(row, "state_scope"), + privateCatalogReceiptField(row, "playable_state_namespace_id"), + privateCatalogReceiptField(row, "character_creation_policy"), + privateCatalogReceiptField(row, "catalog_revision"), + privateCatalogReceiptField(row, "private_preparation_request_id"), + privateCatalogReceiptField(row, "private_playtest_lifecycle_id"), + privateCatalogReceiptField(row, "private_preparation_request_digest"), + privateCatalogReceiptField(row, "private_state_generation"), + privateCatalogReceiptField(row, "private_source_catalog_realm_id"), + privateCatalogReceiptField(row, "private_source_catalog_request_id"), + privateCatalogReceiptField(row, "private_source_catalog_revision"), + privateCatalogReceiptField(row, "private_source_catalog_receipt_digest"), + privateCatalogReceiptField(row, "private_target_policy_id"), + privateCatalogReceiptField(row, "private_target_policy_digest"), + privateCatalogReceiptField(row, "private_target_policy_source_commit_id"), + privateCatalogReceiptField(row, "private_target_policy_source_revision_id"), + privateCatalogReceiptField(row, "private_target_policy_logical_revision_id"), + privateCatalogReceiptField(row, "private_canonical_version_id"), + privateCatalogReceiptField(row, "private_published_release_bundle_ref"), + privateCatalogReceiptField(row, "private_published_release_bundle_digest"), + privateCatalogReceiptField(row, "private_source_policy_set_digest"), + privateCatalogReceiptField(row, "private_source_policy_carrier_digest"), + privateCatalogReceiptField(row, "source_intake_operation_id"), + privateCatalogReceiptField(row, "source_intake_receipt_digest"))); + } + + private static String privateCatalogReceiptField(Map row, String field) { + return Objects.requireNonNull(row.get(field), field).toString(); + } + + private static String sqlStateInCauseChain(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sqlException) { + for (SQLException chained = sqlException; + chained != null; + chained = chained.getNextException()) { + if (chained.getSQLState() != null) return chained.getSQLState(); + } + } + } + return null; + } + + private static String databaseFailureSummary(Throwable failure) { + if (failure == null) return ""; + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sqlException) { + for (SQLException chained = sqlException; + chained != null; + chained = chained.getNextException()) { + if (chained.getSQLState() != null) { + return boundedDiagnostic( + chained.getSQLState() + ": " + Objects.toString(chained.getMessage(), "")); + } + } + } + } + return boundedDiagnostic(failure.getClass().getName() + ": " + failure.getMessage()); + } + + private static String boundedDiagnostic(String diagnostic) { + if (diagnostic.length() <= 512) return diagnostic; + return diagnostic.substring(0, 512) + "..."; + } + private static void awaitExpiry(Context context, Instant expiry) { long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15); while (System.nanoTime() < deadline) { @@ -688,6 +1625,21 @@ private static void awaitExpiry(Context context, Instant expiry) { throw new AssertionError("Real database clock did not reach expiry"); } + private static byte[] frame(String... values) { + var out = new ByteArrayOutputStream(); + for (String value : values) DraftAuthorizationFenceBinding.frame(out, value); + return out.toByteArray(); + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + private Context context(boolean withSource) { return context( withSource, @@ -701,20 +1653,30 @@ private Context context(boolean withSource, List privatePolici dataSource.setUsername(postgres.getUsername()); dataSource.setPassword(postgres.getPassword()); dataSource.setSchema(schema); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .locations( - "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, + schema, + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(), + null); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); - TransactionTemplate transaction = - new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + var transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + TransactionTemplate serializableTransaction = new TransactionTemplate(transactionManager); + serializableTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); var repository = new GameSessionInitialPlaytestLifecycleRepository(dsl); - if (!withSource) return new Context(dsl, transaction, repository, null, null); + var catalogs = new GameSessionCanonicalRealmCatalogRepository(dsl); + var privateTargets = new GameSessionPrivateFreshTargetRepository(dsl); + if (!withSource) + return new Context( + dsl, + transaction, + serializableTransaction, + repository, + privateTargets, + catalogs, + null, + null); // These upstream receipts are explicitly stipulated. Every retained GS row is created through // its actual source, fresh association and closed Human canonical catalog owner. UUID tenant = UUID.randomUUID(); @@ -789,12 +1751,19 @@ private Context context(boolean withSource, List privatePolici "generation-1", 3L, privatePolicies); - var catalogs = new GameSessionCanonicalRealmCatalogRepository(dsl); var preparedCatalog = catalogs.prepareInitialPublicProduction(catalogRequest, published); var catalog = Objects.requireNonNull( transaction.execute(status -> catalogs.createInitialPublicProduction(preparedCatalog))); - return new Context(dsl, transaction, repository, catalog, published); + return new Context( + dsl, + transaction, + serializableTransaction, + repository, + privateTargets, + catalogs, + catalog, + published); } private static RealmEntryPolicy privatePolicy( @@ -859,10 +1828,15 @@ private static RealmEntryPolicy privatePolicy( } } + private record DetachedCatalogRow(Map values, List> fields) {} + private record Context( DSLContext dsl, TransactionTemplate transaction, + TransactionTemplate serializableTransaction, GameSessionInitialPlaytestLifecycleRepository repository, + GameSessionPrivateFreshTargetRepository privateTargets, + GameSessionCanonicalRealmCatalogRepository catalogs, CanonicalRealmCatalogSnapshot catalog, RealmPolicyPublishedEvidence.PublishedSet published) { Instant now() { @@ -909,6 +1883,12 @@ Allocation prepare(Request request) { return Objects.requireNonNull(transaction.execute(status -> repository.prepare(request))); } + GameSessionPrivateFreshTargetRepository.Allocation allocatePrivateTarget( + GameSessionPrivateFreshTargetRepository.Request request) { + return Objects.requireNonNull( + serializableTransaction.execute(status -> privateTargets.allocate(request))); + } + GameSessionInitialPlaytestLifecycleRepository.Snapshot read(Request request, UUID lifecycle) { return Objects.requireNonNull( transaction.execute( @@ -933,5 +1913,23 @@ List> retainedRows() { + "UNION ALL SELECT 'namespace', playable_state_namespace_id::TEXT, xmin::TEXT FROM gameplay_tenant_shared_playable_state_namespace ORDER BY 1, 2") .intoMaps(); } + + Map publicCatalogRow() { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT to_jsonb(catalog)::TEXT AS retained_row, xmin::TEXT AS row_version " + + "FROM game_session_canonical_realm_catalog catalog WHERE realm_id = ?", + catalog.realmId())) + .intoMap(); + } + + List> namespaceRows() { + return dsl.fetch( + "SELECT tenant_id, canonical_tenant_id, target_namespace, " + + "playable_state_namespace_id::TEXT AS namespace_id, xmin::TEXT AS row_version " + + "FROM gameplay_tenant_shared_playable_state_namespace " + + "ORDER BY playable_state_namespace_id") + .intoMaps(); + } } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java index 630583af6c..25137b4d5a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java @@ -22,6 +22,7 @@ import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository.LaunchAssociationOwnerReadMismatchException; import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository.OriginalStartSessionAssociation; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerTestFixtures; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalStartingInstanceRepository; @@ -34,7 +35,6 @@ import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionTemplateAssociationRepository; import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -657,14 +657,7 @@ private static Fixture fixture( dataSource.setUsername(postgres.getUsername()); dataSource.setPassword(postgres.getPassword()); dataSource.setSchema(schema); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema(dataSource, schema, MIGRATION_LOCATION, null); DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); TransactionTemplate transactions = new TransactionTemplate(transactionManager); DSLContext dsl = diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest.java index dddeee0095..9a74c5c01f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest.java @@ -21,6 +21,7 @@ import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionLaunchEvidence; import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionLaunchEvidenceTestFixture; import net.firedevops.firemud.gamesession.dto.StartSessionRequest; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerTestFixtures; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository; @@ -32,7 +33,6 @@ import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.SQLDialect; @@ -617,12 +617,18 @@ void forwardHumanPolicyGuardPreservesActualV1011HistoryAndRejectsLegacyCatalogRe insertHistoricalCatalog(fixture, receipt, realmId); migrate(fixture, "1011").load().migrate(); insertHumanLaunch(fixture, receipt, realmId, "retained-human-launch"); - var before = retainedLaunchCatalogRows(fixture); + var columns = + historicalOwnerColumns( + fixture, + java.util.List.of( + "game_session_canonical_realm_catalog", "game_session_canonical_instance_launch")); + var before = originalOwnerRows(fixture, columns); Record triggerBefore = launchTriggerIdentity(fixture); migrate(fixture, null).load().migrate(); - assertThat(retainedLaunchCatalogRows(fixture)).isEqualTo(before); + assertThat(originalOwnerRows(fixture, columns)).isEqualTo(before); + assertPublicCatalogPrivateColumnsRemainNull(fixture, columns); assertThat(launchTriggerIdentity(fixture)).isEqualTo(triggerBefore); assertThat( fixture @@ -636,7 +642,8 @@ void forwardHumanPolicyGuardPreservesActualV1011HistoryAndRejectsLegacyCatalogRe .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasStackTraceContaining( "Launch provenance differs from the exact retained canonical catalog owner"); - assertThat(retainedLaunchCatalogRows(fixture)).isEqualTo(before); + assertThat(originalOwnerRows(fixture, columns)).isEqualTo(before); + assertPublicCatalogPrivateColumnsRemainNull(fixture, columns); } @Test @@ -682,8 +689,8 @@ void forwardHumanPolicyGuardAcceptsCompletePublishedCatalog() { private static java.util.Map> historicalOwnerColumns( Fixture fixture) { - var columns = new java.util.LinkedHashMap>(); - for (String table : + return historicalOwnerColumns( + fixture, java.util.List.of( "game_session_tenant_scope_reservation", "game_session_tenant_canonical_claim", @@ -691,7 +698,13 @@ private static java.util.Map> historicalOwnerColu "game_session_authored_world_tenant_source_binding", "game_session_authored_world_source_intake", "gameplay_tenant_shared_playable_state_namespace", - "game_session_canonical_realm_catalog")) { + "game_session_canonical_realm_catalog")); + } + + private static java.util.Map> historicalOwnerColumns( + Fixture fixture, java.util.List tables) { + var columns = new java.util.LinkedHashMap>(); + for (String table : tables) { columns.put( table, fixture @@ -759,15 +772,23 @@ private static IntakeReceipt registerAndAssociate( return receipt; } - private static java.util.List retainedLaunchCatalogRows(Fixture fixture) { - return fixture + private static void assertPublicCatalogPrivateColumnsRemainNull( + Fixture fixture, java.util.Map> originalColumns) { + var privateColumns = CanonicalGameplayIssuerTestFixtures.PRIVATE_CATALOG_COLUMNS; + var currentColumns = + historicalOwnerColumns(fixture, java.util.List.copyOf(originalColumns.keySet())); + String catalog = "game_session_canonical_realm_catalog"; + var expectedCatalogColumns = new java.util.ArrayList<>(originalColumns.get(catalog)); + expectedCatalogColumns.addAll(privateColumns); + assertThat(currentColumns.get(catalog)) + .containsExactlyInAnyOrderElementsOf(expectedCatalogColumns); + String launch = "game_session_canonical_instance_launch"; + assertThat(currentColumns.get(launch)).containsExactlyElementsOf(originalColumns.get(launch)); + fixture .dsl - .fetch( - "SELECT 'catalog' AS kind, xmin::text AS xmin, to_jsonb(owner_row)::text AS bytes " - + "FROM game_session_canonical_realm_catalog owner_row UNION ALL " - + "SELECT 'launch', xmin::text, to_jsonb(owner_row)::text " - + "FROM game_session_canonical_instance_launch owner_row ORDER BY kind, bytes") - .map(row -> row.get("kind") + "/" + row.get("xmin") + "/" + row.get("bytes")); + .fetch("SELECT " + String.join(", ", privateColumns) + " FROM " + catalog) + .intoMaps() + .forEach(row -> assertThat(row.values()).containsOnlyNulls()); } private static Record launchTriggerIdentity(Fixture fixture) { @@ -1135,12 +1156,8 @@ private static void insertOwnerRow( private static org.flywaydb.core.api.configuration.FluentConfiguration migrate( Fixture fixture, String target) { var configuration = - Flyway.configure() - .dataSource(fixture.dataSource) - .schemas(fixture.schema) - .defaultSchema(fixture.schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION); + CanonicalGameplayIssuerTestFixtures.migrationConfiguration( + fixture.dataSource, fixture.schema, MIGRATION_LOCATION); if (target != null) configuration.target(target); return configuration; } @@ -1329,15 +1346,8 @@ public Connection getConnection() throws SQLException { dataSource.setUsername(postgres.getUsername()); dataSource.setPassword(postgres.getPassword()); dataSource.setSchema(schema); - var migration = - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION); - if (targetVersion != null) migration.target(targetVersion); - migration.load().migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, schema, MIGRATION_LOCATION, targetVersion); DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); TransactionTemplate transactions = new TransactionTemplate(transactionManager); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java new file mode 100644 index 0000000000..96d1b9471d --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -0,0 +1,1086 @@ +package net.firedevops.firemud.gamesession.repository; + +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.util.Collection; +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.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.gamesession.GameSessionRuntimeFamilyCatalog; +import net.firedevops.firemud.common.gamesession.GameSessionRuntimeFamilyCatalog.FactKind; +import net.firedevops.firemud.common.gamesession.GameSessionRuntimeFamilyCatalog.FreshDisposition; +import net.firedevops.firemud.common.gamesession.GameSessionRuntimeFamilyCatalog.GapId; +import net.firedevops.firemud.common.gamesession.GameSessionRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.gamesession.GameSessionRuntimeFamilyCatalog.Role; +import net.firedevops.firemud.common.gamesession.GameSessionRuntimeFamilyCatalog.StateClass; +import net.firedevops.firemud.common.gamesession.GameSessionRuntimeFamilyCatalogCodec; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real combined Game Session/Saga filesystem/PostgreSQL source tests, never an H2 pg_catalog model. + * Populated predecessor identities/bytes are controlled retention fixtures, not genuine private + * issuance, Account/World authority, Redis custody, process-death recovery or whole-FRESH proof. + * Positive tests deliberately do not skip when Docker is absent. Execution is delegated to Main. + */ +@Testcontainers(disabledWithoutDocker = false) +@SuppressWarnings("resource") +class GameSessionRuntimeFamilyCatalogPostgresIntegrationTest { + private static final String MIGRATIONS = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final String SAGA_MIGRATIONS = + "filesystem:" + + Path.of("../common-saga/src/main/resources/db/migration/saga") + .toAbsolutePath() + .normalize(); + private static final String HISTORY = "flyway_schema_history_game_session_service"; + private static final String SNAPSHOTS = "game_session_runtime_family_catalog_snapshot"; + private static final String EPOCHS = "game_session_runtime_family_catalog_epoch"; + private static final String CLASSIFICATIONS = "game_session_runtime_family_classification"; + private static final String GAPS = "game_session_runtime_catalog_non_sql_gap"; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @BeforeAll + static void awaitReady() { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(postgres); + } + + @Test + void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitBlockingGaps() { + try (Fixture f = fixture(null)) { + Map before = f.rows(f.tables()); + var evidence = f.owner().capture(request()); + var catalog = evidence.catalog(); + assertThat(catalog.catalogEpoch()).isEqualTo(3); + assertThat( + catalog.schemaFacts().stream() + .filter(fact -> fact.kind() == FactKind.TABLE) + .map(GameSessionRuntimeFamilyCatalog.SchemaFact::identity) + .toList()) + .containsExactlyInAnyOrderElementsOf(f.tables()); + assertThat(catalog.families().stream().filter(family -> family.component().isEmpty()).count()) + .isEqualTo(f.tables().size()); + for (String name : List.of("gameplay_command", "remote_followup")) { + assertThat(catalog.families()) + .anySatisfy( + family -> { + assertThat(family.familyId()).isEqualTo(name); + assertThat(family.stateClass()).isEqualTo(StateClass.UNKNOWN); + assertThat(family.freshDisposition()) + .isEqualTo(FreshDisposition.STATE_CLASS_UNKNOWN_BLOCKING); + }); + } + assertThat(catalog.families()) + .anySatisfy( + family -> { + assertThat(family.familyId()).isEqualTo("game_manifest"); + assertThat(family.stateClass()).isEqualTo(StateClass.UNRESOLVED); + assertThat(family.freshDisposition()) + .isEqualTo(FreshDisposition.UNSUPPORTED_SOURCE_BLOCKING); + assertThat(family.ownerConsequence()) + .contains("legacy", "tenant", "Not build or FRESH authority"); + }); + for (String name : + List.of( + "tick_batch", + "tick_effect", + "remote_followup_result", + "script_pin_operation", + "game_session_region_runtime_status", + "game_session_region_timeline_preparation")) { + assertThat(catalog.families()) + .anySatisfy( + family -> { + assertThat(family.familyId()).isEqualTo(name); + assertThat(family.freshDisposition()) + .isEqualTo(FreshDisposition.RUNTIME_EVIDENCE_BLOCKING); + }); + } + assertThat(catalog.families()) + .anySatisfy( + family -> { + assertThat(family.familyId()).isEqualTo("player_command_history"); + assertThat(family.role()).isEqualTo(Role.AUDIT); + }); + for (String name : + List.of( + "saga_instance", + "saga_step", + HISTORY, + "gs_canonical_account_coverage_snapshot_issuer_obligation", + "gs_canonical_account_coverage_snapshot_region_obligation", + "game_session_canonical_account_admission_fence_intent_cohort_ro", + "game_session_canonical_account_admission_fence_intent_barrier_t", + "game_instances.script_patch_version", + "gameplay_command.declared_effects_json", + "game_session_canonical_binding_transition.admission_request_id", + "game_session_canonical_realm_catalog.private_preparation_request_id")) { + assertThat(catalog.families()).anyMatch(family -> family.familyId().equals(name)); + } + assertThat(catalog.families()) + .noneMatch( + family -> + family.familyId().equals("redis_session") + || family.familyId().equals("tick_queue") + || family.familyId().equals("issuer_redis_index")); + assertThat(catalog.families()) + .allSatisfy(family -> assertThat(family.ownerConsequence()).isNotBlank()); + assertThat(catalog.nonSqlGaps()) + .extracting(GameSessionRuntimeFamilyCatalog.NonSqlGap::id) + .containsExactly(GapId.values()); + assertThat(catalog.schemaFacts()) + .anyMatch(fact -> fact.kind() == FactKind.ROUTINE) + .anyMatch(fact -> fact.kind() == FactKind.MIGRATION) + .anyMatch(fact -> fact.kind() == FactKind.TRIGGER) + .anyMatch(fact -> fact.kind() == FactKind.SEQUENCE); + assertThat( + catalog.schemaFacts().stream() + .filter(fact -> fact.kind() == FactKind.MIGRATION) + .map(GameSessionRuntimeFamilyCatalog.SchemaFact::identity) + .toList()) + .contains( + "catalog-installation:1057", "catalog-installation:1058", "catalog-installation:1059") + .noneMatch( + identity -> + identity.contains(":1057:") + || identity.contains(":1058:") + || identity.contains(":1059:")); + assertThat( + f.dsl + .fetchSingle( + "SELECT catalog_bytes=gs_runtime_family_catalog_bytes(catalog_epoch) FROM " + + EPOCHS + + " ORDER BY catalog_epoch DESC LIMIT 1") + .get(0, Boolean.class)) + .isTrue(); + before.remove(SNAPSHOTS); + assertThat(f.rows(before.keySet())).isEqualTo(before); + for (String table : + List.of( + "game_instances", + "gameplay_admission_pointer", + "game_session_canonical_realm_catalog", + "game_session_initial_playtest_preparations", + "game_session_private_playtest_selections", + "game_session_current_private_playtests", + "gameplay_command", + "tick_batch", + "tick_effect")) { + assertThat(f.count(table)).as(table).isZero(); + } + } + } + + @Test + void actualConfiguredHistoryIsBoundWithoutHardcodedHistoryAlias() { + for (String history : + List.of("flyway_schema_history_public", "flyway_schema_history_custom_gs")) { + try (Fixture f = fixture(null, history)) { + var evidence = f.owner().capture(request()); + assertThat(evidence.catalog().families()) + .anySatisfy( + family -> { + assertThat(family.familyId()).isEqualTo(history); + assertThat(family.freshDisposition()).isEqualTo(FreshDisposition.CONTROL_ONLY); + }); + assertThat(f.owner().readExact(evidence.request())).isEqualTo(evidence); + assertThat( + f.dsl + .fetchSingle("SELECT to_regclass(?) IS NULL", f.schema + "." + HISTORY) + .get(0, Boolean.class)) + .isTrue(); + } + } + } + + @Test + void exactReplayReconstructionAndIndependentReadbackRetainSnapshotAndRejectChangedNamespace() { + try (Fixture f = fixture(null)) { + Request read = request(); + var original = f.owner().capture(read); + assertThat(f.owner().capture(read)).isEqualTo(original); + assertThat(f.owner().readExact(read)).isEqualTo(original); + assertThat(f.count(SNAPSHOTS)).isEqualTo(1); + var another = f.owner().capture(request()); + assertThat(another.snapshotId()).isNotEqualTo(original.snapshotId()); + assertThat(another.catalog().exactBytes()).isEqualTo(original.catalog().exactBytes()); + assertThat(f.evidence(read)) + .isEqualTo(GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(original)); + assertThat( + f.dsl + .fetchSingle( + "SELECT evidence_digest FROM " + SNAPSHOTS + " WHERE read_request_id=?", + read.readRequestId()) + .get(0, String.class)) + .isEqualTo(original.digest()); + var foreignConfig = + new GameSessionRuntimeFamilyCatalogRepository(f.dsl, f.manager, f.schema, "other"); + assertThatThrownBy(() -> foreignConfig.capture(new Request(read.readRequestId(), "other"))) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().readExact(request())) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThat(f.count(SNAPSHOTS)).isEqualTo(2); + } + } + + @Test + void concurrentExactRetriesConvergeOnOneCommittedSnapshot() throws Exception { + try (Fixture f = fixture(null); + var workers = Executors.newFixedThreadPool(2)) { + Request read = request(); + var start = new CountDownLatch(1); + var first = + workers.submit( + () -> { + start.await(); + return f.owner().capture(read); + }); + var second = + workers.submit( + () -> { + start.await(); + return f.owner().capture(read); + }); + start.countDown(); + var evidence = first.get(30, TimeUnit.SECONDS); + assertThat(second.get(30, TimeUnit.SECONDS)).isEqualTo(evidence); + assertThat(f.owner().readExact(read)).isEqualTo(evidence); + assertThat(f.count(SNAPSHOTS)).isEqualTo(1); + } + } + + @Test + void populatedV1056UpgradePreservesAllOriginalRowsHistorySequencesAndGuards() { + try (Fixture f = fixture("1056")) { + f.populatePredecessor(); + Map before = f.rows(f.tables()); + before.remove(f.history); + for (String table : + List.of( + "game_instances", + "game_manifest", + "gameplay_command", + "player_command_history", + "resume_transcript_entry", + "script_pin_operation", + "tick_batch", + "tick_effect", + "remote_followup", + "remote_followup_result", + "game_session_start_session_operator_attempt", + "game_session_initial_gameplay_login_journal", + "saga_instance", + "saga_step")) { + assertThat(before.get(table)).as(table).isNotEqualTo("[]"); + } + List history = f.historyRows(false); + List sequences = f.sequencePositions(); + Map guards = f.guards(); + Map routines = f.routines(); + String sourceGuard = "game_session_initial_playtest_source_guard()"; + String originalSourceGuard = routines.remove(sourceGuard); + assertThat(originalSourceGuard).isNotNull(); + Map constraints = f.constraints(); + Map indexes = f.indexes(); + migration(f.source, f.schema, f.history, null).migrate(); + assertThat(f.rows(before.keySet())).isEqualTo(before); + assertThat(f.historyRows(true)).isEqualTo(history); + assertThat(f.sequencePositions()).isEqualTo(sequences); + assertThat(f.guards()).containsAllEntriesOf(guards); + Map installedRoutines = f.routines(); + assertThat(installedRoutines).containsAllEntriesOf(routines); + assertThat(installedRoutines.get(sourceGuard)) + .isNotEqualTo(originalSourceGuard) + .contains("target.public_production"); + assertThat(f.constraints()).containsAllEntriesOf(constraints); + assertThat(f.indexes()).containsAllEntriesOf(indexes); + var original = f.owner().capture(request()); + assertThat(f.owner().readExact(original.request())).isEqualTo(original); + migration(f.source, f.schema, f.history, null).migrate(); + migration(f.source, f.schema, f.history, null).validate(); + assertThat(f.owner().capture(original.request())).isEqualTo(original); + assertThat(f.rows(before.keySet())).isEqualTo(before); + assertThat(f.sequencePositions()).isEqualTo(sequences); + // Original authority/replay/hold guards remain effective, not merely present by name. + assertThatThrownBy( + () -> + f.dsl.execute( + "UPDATE game_session_start_session_operator_attempt SET owner_fence=owner_fence+1")) + .hasMessageContaining("immutable"); + assertThatThrownBy( + () -> + f.dsl.execute( + "UPDATE game_session_start_session_operator_attempt SET lease_expires_at=lease_expires_at+interval '1 hour'")) + .hasMessageContaining("immutable"); + assertThatThrownBy( + () -> f.dsl.execute("DELETE FROM game_session_start_session_operator_attempt")) + .hasMessageContaining("immutable"); + assertThatThrownBy( + () -> + f.dsl.execute( + "UPDATE game_session_initial_gameplay_login_journal SET expected_attempt_fence=2")) + .hasMessageContaining("cannot be replaced or reopened"); + assertThatThrownBy( + () -> f.dsl.execute("DELETE FROM game_session_initial_gameplay_login_journal")) + .hasMessageContaining("retention is held"); + assertThatThrownBy( + () -> f.dsl.execute("TRUNCATE game_session_initial_gameplay_login_journal CASCADE")) + .hasMessageContaining("retention is held"); + assertThat(f.rows(before.keySet())).isEqualTo(before); + } + } + + @Test + void genuineV1057AndV1058UpgradesRetainOldEvidenceBeforeSealingEpochThree() { + try (Fixture f = fixture("1057")) { + f.populatePredecessor(); + var original = f.owner().capture(request()); + assertThat(original.catalog().catalogEpoch()).isEqualTo(1); + Map before = f.rows(f.tables()); + before.remove(f.history); + before.remove(EPOCHS); + String originalEpoch = + f.dsl + .fetchSingle( + "SELECT to_jsonb(e)::text||':'||xmin::text FROM " + + EPOCHS + + " e WHERE catalog_epoch=1") + .get(0, String.class); + String originalSnapshot = + f.dsl + .fetchSingle("SELECT to_jsonb(s)::text||':'||xmin::text FROM " + SNAPSHOTS + " s") + .get(0, String.class); + List history = f.historyRows(false); + List sequences = f.sequencePositions(); + Map guards = f.guards(); + Map constraints = f.constraints(); + Map indexes = f.indexes(); + + migration(f.source, f.schema, f.history, "1058").migrate(); + assertThat(f.rows(before.keySet())).isEqualTo(before); + assertThat( + f.dsl + .fetchSingle( + "SELECT to_jsonb(e)::text||':'||xmin::text FROM " + + EPOCHS + + " e WHERE catalog_epoch=1") + .get(0, String.class)) + .isEqualTo(originalEpoch); + assertThat( + f.dsl + .fetchSingle("SELECT to_jsonb(s)::text||':'||xmin::text FROM " + SNAPSHOTS + " s") + .get(0, String.class)) + .isEqualTo(originalSnapshot); + assertThat(f.historyRows(false)).hasSize(history.size() + 1); + assertThat(f.historyRows(false).subList(0, history.size())).isEqualTo(history); + assertThat( + f.dsl + .fetchSingle( + "SELECT script FROM " + f.history + " WHERE version='1058' AND success") + .get(0, String.class)) + .isEqualTo("V1058__game_session_catalog_view_options.sql"); + assertThat(f.sequencePositions()).isEqualTo(sequences); + assertThat(f.guards()).isEqualTo(guards); + assertThat(f.constraints()).isEqualTo(constraints); + assertThat(f.indexes()).isEqualTo(indexes); + assertThatThrownBy(() -> f.owner().readExact(original.request())) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().capture(original.request())) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThat(f.evidence(original.request())) + .isEqualTo(GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(original)); + assertThat(f.count(SNAPSHOTS)).isEqualTo(1); + var current = f.owner().capture(request()); + assertThat(current.catalog().catalogEpoch()).isEqualTo(2); + assertThat(current.catalog().digest()).isNotEqualTo(original.catalog().digest()); + assertThat(f.owner().readExact(current.request())).isEqualTo(current); + assertThat(f.count(EPOCHS)).isEqualTo(2); + assertThat(f.count(SNAPSHOTS)).isEqualTo(2); + migration(f.source, f.schema, f.history, "1058").validate(); + + Map rowsBeforeV1059 = f.rows(f.tables()); + rowsBeforeV1059.remove(f.history); + rowsBeforeV1059.remove(EPOCHS); + List epochsBeforeV1059 = + f.dsl + .fetch( + "SELECT to_jsonb(e)::text||':'||xmin::text FROM " + + EPOCHS + + " e ORDER BY catalog_epoch") + .getValues(0, String.class); + List snapshotsBeforeV1059 = + f.dsl + .fetch( + "SELECT to_jsonb(s)::text||':'||xmin::text FROM " + + SNAPSHOTS + + " s ORDER BY read_request_id") + .getValues(0, String.class); + List historyBeforeV1059 = f.historyRows(false); + byte[] originalEvidence = f.evidence(original.request()); + byte[] currentEvidence = f.evidence(current.request()); + + migration(f.source, f.schema, f.history, null).migrate(); + assertThat(f.rows(rowsBeforeV1059.keySet())).isEqualTo(rowsBeforeV1059); + assertThat( + f.dsl + .fetch( + "SELECT to_jsonb(e)::text||':'||xmin::text FROM " + + EPOCHS + + " e WHERE catalog_epoch IN (1,2) ORDER BY catalog_epoch") + .getValues(0, String.class)) + .isEqualTo(epochsBeforeV1059); + assertThat( + f.dsl + .fetch( + "SELECT to_jsonb(s)::text||':'||xmin::text FROM " + + SNAPSHOTS + + " s ORDER BY read_request_id") + .getValues(0, String.class)) + .isEqualTo(snapshotsBeforeV1059); + List historyAfterV1059 = f.historyRows(false); + assertThat(historyAfterV1059).hasSize(historyBeforeV1059.size() + 1); + assertThat(historyAfterV1059.subList(0, historyBeforeV1059.size())) + .isEqualTo(historyBeforeV1059); + assertThat( + f.dsl + .fetchSingle("SELECT count(*) FROM " + f.history + " WHERE version='1059'") + .get(0, Long.class)) + .isEqualTo(1L); + var installedV1059 = + f.dsl.fetchSingle( + "SELECT type,script,success FROM " + f.history + " WHERE version='1059'"); + assertThat(installedV1059.get("type", String.class)).isEqualTo("SQL"); + assertThat(installedV1059.get("script", String.class)) + .isEqualTo("V1059__private_lifecycle_preparation_after_catalog_allocation.sql"); + assertThat(installedV1059.get("success", Boolean.class)).isTrue(); + assertThat( + f.dsl + .fetchSingle( + "SELECT catalog_bytes=gs_runtime_family_catalog_bytes(catalog_epoch) FROM " + + EPOCHS + + " WHERE catalog_epoch=3") + .get(0, Boolean.class)) + .isTrue(); + assertThat(f.count(EPOCHS)).isEqualTo(3); + assertThat(f.count(SNAPSHOTS)).isEqualTo(2); + assertThatThrownBy(() -> f.owner().readExact(original.request())) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().readExact(current.request())) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThat(f.evidence(original.request())).isEqualTo(originalEvidence); + assertThat(f.evidence(current.request())).isEqualTo(currentEvidence); + + var latest = f.owner().capture(request()); + assertThat(latest.catalog().catalogEpoch()).isEqualTo(3); + assertThat(latest.catalog().digest()).isNotEqualTo(current.catalog().digest()); + assertThat(f.owner().readExact(latest.request())).isEqualTo(latest); + assertThat(f.count(SNAPSHOTS)).isEqualTo(3); + migration(f.source, f.schema, f.history, null).validate(); + } + } + + @Test + void viewOptionsDriftRefusesReadsRetriesAndNewRequestsWithoutChangingRetainedRows() { + for (String change : + List.of( + "ALTER VIEW catalog_probe_view SET (security_invoker=true)", + "ALTER VIEW catalog_probe_view SET (security_barrier=true)", + "ALTER MATERIALIZED VIEW catalog_probe_materialized SET (fillfactor=70)")) { + try (Fixture f = fixture("1056")) { + // Create actual PostgreSQL views before the real catalog migrations install their seals. + f.dsl.execute("CREATE VIEW catalog_probe_view AS SELECT id,description FROM game_manifest"); + f.dsl.execute( + "CREATE MATERIALIZED VIEW catalog_probe_materialized AS SELECT id,description FROM game_manifest WITH NO DATA"); + migration(f.source, f.schema, f.history, null).migrate(); + var original = f.owner().capture(request()); + assertThat(original.catalog().catalogEpoch()).isEqualTo(3); + assertThat(original.catalog().schemaFacts()) + .anyMatch( + fact -> + fact.kind() == FactKind.VIEW && fact.identity().equals("catalog_probe_view")) + .anyMatch( + fact -> + fact.kind() == FactKind.VIEW + && fact.identity().equals("catalog_probe_materialized")); + Map before = f.rows(f.tables()); + var definitions = + f.dsl.fetch( + "SELECT relname,pg_get_viewdef(c.oid,true),reloptions::text FROM pg_class c" + + " JOIN pg_namespace n ON n.oid=c.relnamespace" + + " WHERE n.nspname=? AND c.relkind IN ('v','m') ORDER BY relname", + f.schema); + f.dsl.execute(change); + var changed = + f.dsl.fetch( + "SELECT relname,pg_get_viewdef(c.oid,true),reloptions::text FROM pg_class c" + + " JOIN pg_namespace n ON n.oid=c.relnamespace" + + " WHERE n.nspname=? AND c.relkind IN ('v','m') ORDER BY relname", + f.schema); + assertThat(changed.getValues(0, String.class)) + .isEqualTo(definitions.getValues(0, String.class)); + assertThat(changed.getValues(1, String.class)) + .isEqualTo(definitions.getValues(1, String.class)); + assertThat(changed.getValues(2, String.class)) + .isNotEqualTo(definitions.getValues(2, String.class)); + assertThatThrownBy(() -> f.owner().readExact(original.request())) + .as(change) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().capture(original.request())) + .as(change) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().capture(request())) + .as(change) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + // Includes every epoch, exact snapshot bytes and original installed-history row. + assertThat(f.rows(before.keySet())).isEqualTo(before); + assertThat(f.evidence(original.request())) + .isEqualTo(GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(original)); + assertThat(f.count(SNAPSHOTS)).isEqualTo(1); + assertThat(f.count(EPOCHS)).isEqualTo(3); + } + } + } + + @Test + void unknownEmptyPredecessorRefusesMigrationAtomicallyWithoutHistoryRewrite() { + try (Fixture f = fixture("1056")) { + f.dsl.execute("CREATE TABLE unknown_runtime_family(id BIGINT PRIMARY KEY)"); + List history = f.historyRows(false); + assertThatThrownBy(() -> migration(f.source, f.schema, f.history, null).migrate()) + .hasMessageContaining("Unclassified or changed Game Session schema family"); + assertThat( + f.dsl + .fetchSingle("SELECT to_regclass(?) IS NULL", f.schema + "." + EPOCHS) + .get(0, Boolean.class)) + .isTrue(); + assertThat(f.historyRows(false)).isEqualTo(history); + assertThat(f.count("unknown_runtime_family")).isZero(); + } + } + + @Test + void evenAnEmptyUnknownTableInvalidatesReadbackAndRefusesNewCapture() { + try (Fixture f = fixture(null)) { + var original = f.owner().capture(request()); + f.dsl.execute("CREATE TABLE unknown_runtime_family(id BIGINT PRIMARY KEY)"); + assertThat(f.count("unknown_runtime_family")).isZero(); + assertThatThrownBy(() -> f.owner().readExact(original.request())) + .hasMessageContaining("Unclassified or changed"); + assertThatThrownBy(() -> f.owner().capture(request())) + .hasMessageContaining("Unclassified or changed"); + assertThat(f.evidence(original.request())) + .isEqualTo(GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(original)); + assertThat(f.count(SNAPSHOTS)).isEqualTo(1); + } + } + + @Test + void addDropRenameChangeTableColumnConstraintIndexSequenceOrRoutineCannotReuseOldSeal() { + for (String change : + List.of( + "ALTER TABLE game_manifest ADD COLUMN future_state TEXT", + "ALTER TABLE game_manifest DROP COLUMN description", + "ALTER TABLE game_manifest RENAME COLUMN description TO changed_description", + "ALTER TABLE game_manifest ADD CONSTRAINT catalog_probe CHECK(id>0)", + "ALTER TABLE game_manifest RENAME TO renamed_manifest", + "DROP TABLE game_manifest", + "CREATE INDEX catalog_probe ON game_manifest(version_id)", + "ALTER SEQUENCE game_manifest_id_seq INCREMENT BY 2", + "CREATE FUNCTION future_runtime_writer() RETURNS INTEGER LANGUAGE SQL AS 'SELECT 1'", + "ALTER FUNCTION guard_initial_gameplay_login_journal() RENAME TO renamed_login_guard", + "CREATE OR REPLACE FUNCTION guard_initial_gameplay_login_journal() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN RETURN NEW; END; $$")) { + try (Fixture f = fixture(null)) { + var original = f.owner().capture(request()); + f.dsl.execute(change); + assertThatThrownBy(() -> f.owner().readExact(original.request())) + .as(change) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy(() -> f.owner().capture(request())) + .as(change) + .isInstanceOf(RuntimeException.class); + assertThat(f.evidence(original.request())) + .isEqualTo(GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(original)); + assertThat(f.count(SNAPSHOTS)).isEqualTo(1); + } + } + } + + @Test + void changedClassificationInvalidatesWithoutChangingRetainedEvidence() { + try (Fixture f = fixture(null)) { + var original = f.owner().capture(request()); + f.addComponent(); + assertThatThrownBy(() -> f.owner().readExact(original.request())) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().capture(request())) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThat(f.evidence(original.request())) + .isEqualTo(GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(original)); + } + } + + @Test + void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks() { + try (Fixture f = fixture(null)) { + var original = f.owner().capture(request()); + f.dsl.execute("UPDATE " + f.history + " SET checksum=checksum+1 WHERE version='1'"); + assertThatThrownBy(() -> f.owner().readExact(original.request())) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + } + for (String version : List.of("1057", "1058", "1059")) { + for (String change : + List.of("success=false", "script='wrong_installation.sql'", "type='JDBC'")) { + try (Fixture f = fixture(null)) { + f.dsl.execute("UPDATE " + f.history + " SET " + change + " WHERE version=?", version); + assertThatThrownBy(() -> f.owner().capture(request())) + .hasMessageContaining("No durable Game Session catalog epoch"); + assertThat(f.count(SNAPSHOTS)).isZero(); + } + } + try (Fixture f = fixture(null)) { + f.dsl.execute("DELETE FROM " + f.history + " WHERE version=?", version); + assertThatThrownBy(() -> f.owner().capture(request())) + .hasMessageContaining("No durable Game Session catalog epoch"); + assertThat(f.count(SNAPSHOTS)).isZero(); + } + } + try (Fixture f = fixture(null)) { + var original = f.owner().capture(request()); + f.dsl.execute( + "INSERT INTO " + + f.history + + "(installed_rank,version,description,type,script,checksum,installed_by,execution_time,success)" + + " VALUES(10000,'1060','controlled later migration','SQL','V1060__probe.sql',1,current_user,0,true)"); + assertThatThrownBy(() -> f.owner().readExact(original.request())) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + } + for (String version : List.of("1057", "1058", "1059")) { + try (Fixture f = fixture(null)) { + f.dsl.execute( + "INSERT INTO " + + f.history + + "(installed_rank,version,description,type,script,checksum,installed_by,execution_time,success)" + + " SELECT 10000,version,description,type,script,checksum,installed_by,execution_time,success FROM " + + f.history + + " WHERE version=?", + version); + assertThatThrownBy(() -> f.owner().capture(request())) + .hasMessageContaining("No durable Game Session catalog epoch"); + } + } + } + + @Test + void explicitNewOwnerEpochRetainsButInvalidatesOldRequestsAndRejectsReusedOrSkippedEpochs() { + try (Fixture f = fixture(null)) { + var original = f.owner().capture(request()); + f.addComponent(); + for (long invalid : new long[] {1, 2, 3, 5}) { + assertThatThrownBy(() -> f.installEpoch(invalid)) + .hasMessageContaining("exact classified installed schema"); + } + // Controlled explicit owner revision, not an exposed registry/runtime mutation API. + f.installEpoch(4); + assertThatThrownBy(() -> f.owner().capture(original.request())) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().readExact(original.request())) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThat(f.evidence(original.request())) + .isEqualTo(GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(original)); + var revised = f.owner().capture(request()); + assertThat(revised.catalog().catalogEpoch()).isEqualTo(4); + assertThat(revised.catalog().digest()).isNotEqualTo(original.catalog().digest()); + assertThat(f.count(EPOCHS)).isEqualTo(4); + } + } + + @Test + void metadataEpochAndSnapshotGuardsRefuseMutationStaleBytesAndChangedExactSqlFrames() { + try (Fixture f = fixture(null)) { + var original = f.owner().capture(request()); + for (String table : List.of(CLASSIFICATIONS, GAPS, EPOCHS, SNAPSHOTS)) { + assertThatThrownBy(() -> f.dsl.execute("DELETE FROM " + table)) + .hasMessageContaining("immutable"); + assertThatThrownBy(() -> f.dsl.execute("TRUNCATE " + table + " CASCADE")) + .hasMessageContaining("immutable"); + String column = + table.equals(CLASSIFICATIONS) + ? "family_id" + : table.equals(GAPS) ? "gap_id" : "catalog_epoch"; + assertThatThrownBy(() -> f.dsl.execute("UPDATE " + table + " SET " + column + "=" + column)) + .hasMessageContaining("immutable"); + } + for (String consequence : List.of(" ", "\t")) { + assertThatThrownBy( + () -> + f.dsl.execute( + "INSERT INTO " + + CLASSIFICATIONS + + " VALUES('game_manifest.description','game_manifest','description','SOURCE','UNRESOLVED'," + + "'UNSUPPORTED_SOURCE_BLOCKING','UNRESOLVED_RETAINED',?)", + consequence)) + .hasMessageContaining("ck_gs_runtime_family_consequence"); + } + assertThatThrownBy( + () -> + f.dsl.execute( + "INSERT INTO " + + EPOCHS + + "(catalog_epoch,catalog_bytes,catalog_digest)" + + " SELECT 4,catalog_bytes,catalog_digest FROM " + + EPOCHS + + " WHERE catalog_epoch=3")) + .hasMessageContaining("exact classified installed schema"); + assertThatThrownBy( + () -> + f.dsl.execute( + "INSERT INTO " + + SNAPSHOTS + + "(read_request_id,target_namespace,request_bytes,request_digest,snapshot_id,catalog_epoch,catalog_digest,evidence_bytes,evidence_digest)" + + " SELECT ?,target_namespace,request_bytes,request_digest,?,catalog_epoch,catalog_digest,evidence_bytes,evidence_digest" + + " FROM " + + SNAPSHOTS + + " WHERE read_request_id=?", + UUID.randomUUID(), + UUID.randomUUID(), + original.request().readRequestId())) + .hasMessageContaining("complete exact request and evidence"); + assertThatThrownBy( + () -> + f.dsl.execute( + "INSERT INTO " + + SNAPSHOTS + + "(read_request_id,target_namespace,request_bytes,request_digest,snapshot_id,catalog_epoch,catalog_digest,evidence_bytes,evidence_digest)" + + " SELECT ?,target_namespace,request_bytes,request_digest,?,catalog_epoch,'sha256:'||repeat('0',64),evidence_bytes,evidence_digest" + + " FROM " + + SNAPSHOTS + + " WHERE read_request_id=?", + UUID.randomUUID(), + UUID.randomUUID(), + original.request().readRequestId())) + .hasMessageContaining("new owner epoch required"); + assertThat(f.count(SNAPSHOTS)).isEqualTo(1); + } + } + + @Test + void postCommitDriftFailsReadbackButLeavesTheOriginalSnapshotRetained() { + try (Fixture f = fixture(null)) { + // Controlled inter-transaction race, using real commits; no production callback is added. + var changeAfterFirstCommit = + new PlatformTransactionManager() { + private boolean captured; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + return f.manager.getTransaction(definition); + } + + @Override + public void commit(TransactionStatus status) { + f.manager.commit(status); + if (!captured) { + captured = true; + f.addComponent(); + } + } + + @Override + public void rollback(TransactionStatus status) { + f.manager.rollback(status); + } + }; + var owner = + new GameSessionRuntimeFamilyCatalogRepository( + f.dsl, changeAfterFirstCommit, f.schema, "test"); + Request read = request(); + assertThatThrownBy(() -> owner.capture(read)) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThat(f.count(SNAPSHOTS)).isEqualTo(1); + assertThat( + GameSessionRuntimeFamilyCatalogCodec.evidenceFromStored(f.evidence(read)).request()) + .isEqualTo(read); + assertThatThrownBy(() -> f.owner().readExact(read)) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + } + } + + @Test + void captureUsesIndependentCommittedTransactionsAndRejectsRealAmbientSql() { + try (Fixture f = fixture(null)) { + var evidence = f.owner().capture(request()); + // A new data source/manager/repository has no capture transaction or Java snapshot to reuse. + var independent = source(f.schema); + var independentDsl = + DSL.using(new TransactionAwareDataSourceProxy(independent), SQLDialect.POSTGRES); + var restarted = + new GameSessionRuntimeFamilyCatalogRepository( + independentDsl, new DataSourceTransactionManager(independent), f.schema, "test"); + assertThat(restarted.readExact(evidence.request())).isEqualTo(evidence); + var transaction = new TransactionTemplate(f.manager); + assertThatThrownBy(() -> transaction.execute(status -> f.owner().capture(request()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("independent"); + assertThatThrownBy( + () -> transaction.execute(status -> f.owner().readExact(evidence.request()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("independent"); + assertThat(f.count(SNAPSHOTS)).isEqualTo(1); + } + } + + private static Request request() { + return new Request(UUID.randomUUID(), "test"); + } + + private static Fixture fixture(String target) { + return fixture(target, HISTORY); + } + + private static Flyway migration( + DriverManagerDataSource source, String schema, String history, String target) { + var configuration = + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .table(history) + .locations(MIGRATIONS, SAGA_MIGRATIONS) + .placeholders(Map.of("serviceSchema", schema)); + if (target != null) configuration.target(target); + return configuration.load(); + } + + private static DriverManagerDataSource source(String schema) { + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + return source; + } + + private static Fixture fixture(String target, String history) { + String schema = "gs_catalog_" + UUID.randomUUID().toString().replace("-", ""); + var source = source(schema); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + try { + migration(source, schema, history, target).migrate(); + return new Fixture(schema, history, source, dsl, new DataSourceTransactionManager(source)); + } catch (RuntimeException failed) { + dsl.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + throw failed; + } + } + + private record Fixture( + String schema, + String history, + DriverManagerDataSource source, + DSLContext dsl, + DataSourceTransactionManager manager) + implements AutoCloseable { + GameSessionRuntimeFamilyCatalogRepository owner() { + return new GameSessionRuntimeFamilyCatalogRepository(dsl, manager, schema, "test"); + } + + long count(String table) { + return dsl.fetchSingle("SELECT count(*) FROM " + table).get(0, Long.class); + } + + byte[] evidence(Request request) { + return dsl.fetchSingle( + "SELECT evidence_bytes FROM " + SNAPSHOTS + " WHERE read_request_id=?", + request.readRequestId()) + .get(0, byte[].class); + } + + List tables() { + return dsl.fetch( + "SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace" + + " WHERE n.nspname=? AND c.relkind IN ('r','p','f') ORDER BY c.relname", + schema) + .getValues(0, String.class); + } + + Map rows(Collection tables) { + Map result = new LinkedHashMap<>(); + for (String table : tables) { + result.put( + table, + dsl.fetchSingle( + "SELECT coalesce(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text),'[]'::jsonb)::text FROM " + + table + + " t") + .get(0, String.class)); + } + return result; + } + + List historyRows(boolean excludeCatalogInstalls) { + return dsl.fetch( + "SELECT to_jsonb(h)::text FROM " + + history + + " h" + + (excludeCatalogInstalls + ? " WHERE version IS DISTINCT FROM '1057' AND version IS DISTINCT FROM '1058' AND version IS DISTINCT FROM '1059'" + : "") + + " ORDER BY installed_rank") + .getValues(0, String.class); + } + + List sequencePositions() { + return dsl.fetch( + "SELECT sequencename||':'||coalesce(last_value::text,'unused') FROM pg_sequences" + + " WHERE schemaname=? ORDER BY sequencename", + schema) + .getValues(0, String.class); + } + + Map guards() { + return dsl.fetch( + "SELECT c.relname||'.'||t.tgname,pg_get_triggerdef(t.oid,true)||':'||t.tgenabled::TEXT" + + " 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 ORDER BY c.relname,t.tgname", + schema) + .intoMap(row -> row.get(0, String.class), row -> row.get(1, String.class)); + } + + Map constraints() { + return dsl.fetch( + "SELECT c.relname||'.'||k.conname,pg_get_constraintdef(k.oid,true)||':'||k.convalidated" + + " FROM pg_constraint k JOIN pg_class c ON c.oid=k.conrelid JOIN pg_namespace n ON n.oid=c.relnamespace" + + " WHERE n.nspname=? ORDER BY c.relname,k.conname", + schema) + .intoMap(row -> row.get(0, String.class), row -> row.get(1, String.class)); + } + + Map routines() { + return dsl.fetch( + "SELECT p.proname||'('||pg_get_function_identity_arguments(p.oid)||')',pg_get_functiondef(p.oid)" + + " FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace" + + " WHERE n.nspname=? AND p.prokind IN ('f','p') ORDER BY 1", + schema) + .intoMap(row -> row.get(0, String.class), row -> row.get(1, String.class)); + } + + Map indexes() { + return dsl.fetch( + "SELECT indexname,indexdef FROM pg_indexes WHERE schemaname=? ORDER BY indexname", + schema) + .intoMap(row -> row.get(0, String.class), row -> row.get(1, String.class)); + } + + void addComponent() { + dsl.execute( + "INSERT INTO " + + CLASSIFICATIONS + + " VALUES('game_manifest.description','game_manifest','description','SOURCE','UNRESOLVED'," + + "'UNSUPPORTED_SOURCE_BLOCKING','UNRESOLVED_RETAINED','Controlled component revision; legacy source still blocks FRESH.')"); + } + + void installEpoch(long epoch) { + dsl.execute( + "INSERT INTO " + + EPOCHS + + "(catalog_epoch,catalog_bytes,catalog_digest)" + + " SELECT ?,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM (SELECT gs_runtime_family_catalog_bytes(?) AS bytes) revision", + epoch, + epoch); + } + + void populatePredecessor() { + // SQL fixture values preserve existing bytes; none is passed off as a live authority + // producer. + dsl.execute( + "INSERT INTO game_instances(tenant_id,runtime_version,owner_account_id,status) VALUES(7001,'legacy',9,'STOPPED')"); + dsl.execute( + "INSERT INTO game_manifest(version_id,description) VALUES('unqualified-legacy','retain unresolved lineage')"); + dsl.execute( + "INSERT INTO feature_flag(tenant_id,name,enabled) VALUES(7001,'retained-override',false)"); + dsl.execute( + "INSERT INTO gameplay_command(command_id,tenant_id,game_instance_id,session_id,account_id,character_id,command_name," + + "sanitized_command_text,requires_solo_tick,execution_outcome,gameplay_result,accepted_at,command_text,declared_effects_json)" + + " VALUES('retained-command',7001,1,3,9,7,'LOOK','LOOK',false,'ACCEPTED','PENDING',CURRENT_TIMESTAMP,'LOOK','[]')"); + dsl.execute( + "INSERT INTO player_command_history(tenant_id,game_instance_id,character_id,command_text,accepted_at)" + + " VALUES(7001,1,7,'LOOK',CURRENT_TIMESTAMP)"); + dsl.execute( + "INSERT INTO resume_transcript_entry(tenant_id,game_instance_id,character_id,protocol_text,line_count,byte_size,appended_at)" + + " VALUES(7001,1,7,'retained',1,8,CURRENT_TIMESTAMP)"); + dsl.execute( + "INSERT INTO script_pin_operation(tenant_id,game_instance_id,control_plane_request_id,operation_kind," + + "target_script_patch_version,expected_pin_kind,actor_principal,reason,mutation_digest,outcome,resulting_script_patch_version,resulting_script_pin_epoch)" + + " VALUES(7001,1,'retained-pin','SET','patch','EXPECT_UNPINNED','controlled','retained',?,'COMMITTED','patch',1)", + "a".repeat(64)); + dsl.execute( + "INSERT INTO tick_batch(tick_batch_id,tenant_id,game_instance_id,region_epoch,executor_fence,batch_source,status," + + "requires_solo_tick,command_count,staged_at,selected_work_manifest_json)" + + " VALUES('retained-batch',7001,1,1,'retained-fence','PLAYER','STAGED',false,1,CURRENT_TIMESTAMP,'{}')"); + dsl.execute( + "INSERT INTO tick_effect(effect_id,tick_batch_id,command_id,effect_type,target_aggregate,status,staged_at,effect_key)" + + " VALUES('retained-effect','retained-batch','retained-command','MOVE','actor','STAGED',CURRENT_TIMESTAMP,'retained-effect-key')"); + dsl.execute( + "INSERT INTO remote_followup(followup_id,tenant_id,origin_game_instance_id,origin_region_id,origin_region_epoch," + + "target_game_instance_id,target_region_id,target_region_epoch,due_tick_id,effect_key,status,created_at,updated_at,claim_target_aggregate)" + + " VALUES('retained-followup',7001,1,'origin',1,2,'target',1,4,'retained-remote-effect','PENDING',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,'actor')"); + dsl.execute( + "INSERT INTO remote_followup_result(result_id,tenant_id,coordinator_id,followup_id,origin_region_id,origin_region_epoch," + + "target_region_id,target_region_epoch,outcome,observed_at,origin_game_instance_id,target_game_instance_id)" + + " VALUES('retained-result',7001,'retained-coordinator','retained-followup','origin',1,'target',1,'APPLIED',CURRENT_TIMESTAMP,1,2)"); + dsl.execute( + "INSERT INTO game_session_start_session_operator_attempt(target_namespace,control_plane_request_id,canonical_tenant_id," + + "owner_attempt_id,owner_mutation_id,claim_owner_id,owner_fence,post_authorization_execution_tuple,mutation_digest," + + "authorization_reference_fingerprint,lease_expires_at)" + + " VALUES('test','retained-start',?,?,?,?,nextval('game_session_start_session_operator_owner_fence_seq'),?,?,?,clock_timestamp()+interval '1 hour')", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "controlled-retention-only".getBytes(StandardCharsets.UTF_8), + "b".repeat(64), + "arfp/v1/controlled/" + "c".repeat(64)); + dsl.execute( + "INSERT INTO game_session_initial_gameplay_login_journal(request_id,caller_context_id,expected_attempt_fence) VALUES(?,?,1)", + UUID.randomUUID(), + UUID.randomUUID()); + dsl.execute( + "INSERT INTO game_session_canonical_account_coverage_control(account_id,state,last_operation_fence)" + + " VALUES(?,'NO_ACTIVE_ACCOUNT_WIDE_FLOW',0)", + UUID.randomUUID()); + dsl.execute("INSERT INTO saga_instance(saga_name,state) VALUES('retained','PENDING')"); + dsl.execute( + "INSERT INTO saga_step(instance_id,name,status) VALUES(1,'retained-step','PENDING')"); + } + + @Override + public void close() { + dsl.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest.java index c0d1fd804e..616027f924 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest.java @@ -38,6 +38,7 @@ import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerTestFixtures; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionLaunchDescriptorRepository; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionLaunchDescriptorRepository.PinnedLaunchDescriptorSnapshot; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; @@ -50,7 +51,6 @@ import net.firedevops.firemud.gamesession.service.GameSessionStartSessionLaunchDescriptorContinuationService; import net.firedevops.firemud.gamesession.service.GameSessionStartSessionLaunchDescriptorContinuationService.EvidenceContinuationUnavailableException; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -860,14 +860,7 @@ private static Fixture fixture(Duration ownerClaimLease) { dataSource.setUsername(postgres.getUsername()); dataSource.setPassword(postgres.getPassword()); dataSource.setSchema(schema); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema(dataSource, schema, MIGRATION_LOCATION, null); DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); TransactionTemplate transactions = new TransactionTemplate(transactionManager); DSLContext dsl = diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java index cc18765806..50f925e789 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java @@ -32,6 +32,7 @@ import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerTestFixtures; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionLaunchDescriptorRepository; @@ -124,14 +125,8 @@ void v34_3BaselineUpgradePreservesLegitimateEvidenceAndCreatesContinuationConstr .get(0, String.class)) .isEqualTo("34.3"); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, schema, MIGRATION_LOCATION, null); assertThat( dsl.fetch( @@ -1946,14 +1941,7 @@ private static Fixture fixture(Duration claimLease) { dataSource.setUsername(postgres.getUsername()); dataSource.setPassword(postgres.getPassword()); dataSource.setSchema(schema); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema(dataSource, schema, MIGRATION_LOCATION, null); DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); TransactionTemplate transactions = new TransactionTemplate(transactionManager); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java index 2c85d58f8c..438c20808c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java @@ -58,6 +58,7 @@ import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerTestFixtures; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; @@ -66,7 +67,6 @@ import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionTemplateAssociationRepository; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionTemplateAssociationRepository.PinnedAssociationSnapshot; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -1350,14 +1350,7 @@ private static Fixture fixture(Duration ownerClaimLease) { dataSource.setUsername(postgres.getUsername()); dataSource.setPassword(postgres.getPassword()); dataSource.setSchema(schema); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema(dataSource, schema, MIGRATION_LOCATION, null); var transactions = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionV2QuiescenceMigrationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionV2QuiescenceMigrationIntegrationTest.java index c245a8c13b..930345b105 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionV2QuiescenceMigrationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionV2QuiescenceMigrationIntegrationTest.java @@ -151,13 +151,8 @@ private DSLContext migrateToVersionOne() { } private void migrateExistingSchemaToLatest() { - Flyway.configure() - .dataSource(dataSource(schema)) - .locations(MIGRATION_LOCATION) - .schemas(schema) - .defaultSchema(schema) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource(schema), schema, MIGRATION_LOCATION, null); } private DSLContext adminDsl() { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandAccountUuidMigrationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandAccountUuidMigrationIntegrationTest.java index 3c8e0087ef..aa4a9b53a8 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandAccountUuidMigrationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandAccountUuidMigrationIntegrationTest.java @@ -52,7 +52,10 @@ void migrationRetainsLegacyCommandRowsAndDoesNotInventAccountUuids() { + "FROM gameplay_command AS command_row ORDER BY command_id") .getValues("retained_row", String.class); - Flyway.configure().dataSource(dataSource).locations(MIGRATION_LOCATION).load().migrate(); + CanonicalGameplayIssuerTestFixtures.migrationConfiguration( + dataSource, "public", MIGRATION_LOCATION) + .load() + .migrate(); List migratedRows = dsl.fetch( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java index a628b527c8..ca1ca93f47 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java @@ -21,7 +21,6 @@ import java.util.concurrent.atomic.AtomicBoolean; import net.firedevops.firemud.gamesession.entity.GameplayCommand; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.ExecuteContext; import org.jooq.SQLDialect; @@ -70,9 +69,9 @@ void setUpRepository() { dataSource.setUsername(postgres.getUsername()); dataSource.setPassword(postgres.getPassword()); - Flyway.configure() - .dataSource(dataSource) - .locations( + CanonicalGameplayIssuerTestFixtures.migrationConfiguration( + dataSource, + "public", "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) .load() .migrate(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java index 6d62c22eac..c2e725e1f0 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java @@ -42,12 +42,12 @@ import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult.Disposition; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult.ProofKind; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerTestFixtures; import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository; import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository.JournalConflictException; import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository.JournalUnavailableException; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.exception.DataAccessException; @@ -109,14 +109,11 @@ void migratedIsolatedSchema() { dataSource.setUsername(postgres.getUsername()); dataSource.setPassword(postgres.getPassword()); dataSource.setSchema(schema); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .locations( - "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, + schema, + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(), + null); dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); transactions = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); transactions.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java index 449ce465c6..d59c1941fe 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java @@ -13,7 +13,6 @@ import net.firedevops.firemud.gamesession.service.PlayerCommandHistoryStorageService; import net.firedevops.firemud.gamesession.test.GameplayHistoryTestFixtures; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -54,9 +53,9 @@ void setUpRepository() { // The integration runtime includes other services' db/migration resources; scan this module // only. - Flyway.configure() - .dataSource(dataSource) - .locations( + CanonicalGameplayIssuerTestFixtures.migrationConfiguration( + dataSource, + "public", "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) .load() .migrate(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/RemoteCommandCoordinatorRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/RemoteCommandCoordinatorRepositoryIntegrationTest.java index bea417cf70..631e6512a6 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/RemoteCommandCoordinatorRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/RemoteCommandCoordinatorRepositoryIntegrationTest.java @@ -10,7 +10,6 @@ import net.firedevops.firemud.gamesession.entity.RemoteFollowup; import net.firedevops.firemud.gamesession.entity.RemoteFollowupResult; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -45,9 +44,9 @@ void setUpRepositories() { dataSource.setUsername(postgres.getUsername()); dataSource.setPassword(postgres.getPassword()); - Flyway.configure() - .dataSource(dataSource) - .locations( + CanonicalGameplayIssuerTestFixtures.migrationConfiguration( + dataSource, + "public", "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) .load() .migrate(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepositoryIntegrationTest.java index 7f6e5f64d5..a895f49f5d 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepositoryIntegrationTest.java @@ -47,8 +47,13 @@ void setUpRepository() { Flyway.configure() .dataSource(dataSource) + .placeholders(java.util.Map.of("serviceSchema", "public")) .locations( - "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(), + "filesystem:" + + Path.of("../common-saga/src/main/resources/db/migration/saga") + .toAbsolutePath() + .normalize()) .load() .migrate(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/RuntimeRegionStatusRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/RuntimeRegionStatusRepositoryIntegrationTest.java index 3bcb6f2597..385a0ad345 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/RuntimeRegionStatusRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/RuntimeRegionStatusRepositoryIntegrationTest.java @@ -50,8 +50,13 @@ void setUpRepository() { Flyway.configure() .dataSource(dataSource) + .placeholders(java.util.Map.of("serviceSchema", "public")) .locations( - "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(), + "filesystem:" + + Path.of("../common-saga/src/main/resources/db/migration/saga") + .toAbsolutePath() + .normalize()) .load() .migrate(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ScriptPinOperationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ScriptPinOperationRepositoryIntegrationTest.java index a3541a69fe..d9d0a96a44 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ScriptPinOperationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ScriptPinOperationRepositoryIntegrationTest.java @@ -55,8 +55,13 @@ void setUpRepository() { dataSource.setPassword(postgres.getPassword()); Flyway.configure() .dataSource(dataSource) + .placeholders(java.util.Map.of("serviceSchema", "public")) .locations( - "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(), + "filesystem:" + + Path.of("../common-saga/src/main/resources/db/migration/saga") + .toAbsolutePath() + .normalize()) .load() .migrate(); dsl = DSL.using(dataSource, SQLDialect.POSTGRES); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java index 5b51d6ad24..3ee0e23f3b 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java @@ -33,6 +33,7 @@ import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerTestFixtures; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository; @@ -681,14 +682,7 @@ private Fixture fixture( "canonical_tenant_id", preV24Source.source().canonicalTenantId()); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema(dataSource, schema, MIGRATION_LOCATION, null); GameSessionCanonicalLaunchPreparationRepository preparationRepository = new GameSessionCanonicalLaunchPreparationRepository(transactionalDsl, catalogRepository); GameSessionStartSessionOperatorAttemptRepository attemptRepository = @@ -919,11 +913,21 @@ private static CanonicalRealmCatalogSnapshot seedHistoricalCatalog( private static String historicalProjection( DSLContext dsl, String table, String selector, UUID identity) { + String privateProjection = + "game_session_canonical_realm_catalog".equals(table) + ? " - ARRAY[" + + CanonicalGameplayIssuerTestFixtures.PRIVATE_CATALOG_COLUMNS.stream() + .map(column -> "'" + column + "'") + .collect(java.util.stream.Collectors.joining(",")) + + "]" + : ""; return requiredRecord( dsl, "SELECT xmin::text || '/' || (to_jsonb(owner_row) " + "- 'complete_policy_set_evidence' - 'fixture_policy_request_bytes' - 'fixture_policy_seal_operation_id' " - + "- 'fixture_policy_seal_request_digest' - 'fixture_policy_seal_evidence_digest')::text AS retained " + + "- 'fixture_policy_seal_request_digest' - 'fixture_policy_seal_evidence_digest' " + + privateProjection + + ")::text AS retained " + "FROM " + table + " owner_row WHERE " @@ -1001,6 +1005,18 @@ void requireHistoricalRowsRetained() { preV24Catalog.creationRequestId()) .get("complete_policy_set_evidence", byte[].class)) .isNull(); + assertThat( + requiredRecord( + dsl, + "SELECT " + + CanonicalGameplayIssuerTestFixtures.PRIVATE_CATALOG_COLUMNS.stream() + .map(column -> column + " IS NULL") + .collect(java.util.stream.Collectors.joining(" AND ")) + + " AS private_fields_clear " + + "FROM game_session_canonical_realm_catalog WHERE creation_request_id = ?", + preV24Catalog.creationRequestId()) + .get("private_fields_clear", Boolean.class)) + .isTrue(); assertThatThrownBy( () -> catalogRepository.readByRequest(NAMESPACE, preV24Catalog.creationRequestId())) .isInstanceOf( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest.java index 93b5e15213..d00fab47e8 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest.java @@ -27,6 +27,7 @@ import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.gamesession.client.StartSessionOperatorRedemptionClient; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerTestFixtures; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; @@ -35,7 +36,6 @@ import net.firedevops.firemud.gamesession.service.GameSessionStartSessionOperatorAuthorizationCoordinator; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.SQLDialect; @@ -343,14 +343,7 @@ private static Fixture fixture(Duration claimLease) { dataSource.setUsername(postgres.getUsername()); dataSource.setPassword(postgres.getPassword()); dataSource.setSchema(schema); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema(dataSource, schema, MIGRATION_LOCATION, null); DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); TransactionTemplate transactions = new TransactionTemplate(transactionManager); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerCasPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerCasPostgresIntegrationTest.java index 854ec4d2dd..7fb1eca394 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerCasPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerCasPostgresIntegrationTest.java @@ -51,7 +51,13 @@ void migrateIsolatedContainerSchema() { Flyway flyway = Flyway.configure() .dataSource(dataSource) - .locations(MIGRATION_LOCATION) + .placeholders(java.util.Map.of("serviceSchema", "public")) + .locations( + MIGRATION_LOCATION, + "filesystem:" + + Path.of("../common-saga/src/main/resources/db/migration/saga") + .toAbsolutePath() + .normalize()) .cleanDisabled(false) .load(); flyway.clean(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java index 057567614c..c2c545109b 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java @@ -6,6 +6,7 @@ import java.nio.file.Path; import java.util.Objects; import net.firedevops.firemud.gamesession.entity.GameInstance; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerTestFixtures; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; import net.firedevops.firemud.gamesession.repository.InitialAdmissionBindAttemptRepository; @@ -13,7 +14,6 @@ import net.firedevops.firemud.gamesession.service.impl.DatabaseInitialAdmissionBindOwnerService; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -45,7 +45,8 @@ static void awaitPostgresJdbcReady() { @Test void initialAdmissionLedgerCommitsPointerAuditAndAttemptTogetherAndReadbackFailsClosed() { DriverManagerDataSource dataSource = dataSource(); - Flyway.configure().dataSource(dataSource).locations(MIGRATION_LOCATION).load().migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, "public", MIGRATION_LOCATION, null); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); TransactionTemplate transactionTemplate = diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java index f6e08eca31..599085a1bf 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java @@ -83,11 +83,11 @@ import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult.Disposition; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult.ProofKind; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginJournalSnapshot; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerTestFixtures; import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding.AcknowledgementPolicy; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding.Profile; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.AfterAll; @@ -860,14 +860,11 @@ private InitialGameplayLoginCleanupOwner cleanup( new DriverManagerDataSource( POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); dataSource.setSchema(schema); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .locations( - "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, + schema, + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(), + null); journal = new InitialGameplayLoginCoordinationJournalRepository( DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES)); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java index 2794bc60a2..307f7aae49 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java @@ -10,9 +10,9 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.gamesession.entity.GameInstance; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerTestFixtures; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.exception.DataAccessException; @@ -42,7 +42,8 @@ class RunOwnedInitialLaunchPostgresIntegrationTest { @Test void concurrentExactIdentityAllocationConvergesAndOrdinaryRowsRemainNullable() throws Exception { DriverManagerDataSource dataSource = dataSource(); - Flyway.configure().dataSource(dataSource).locations(MIGRATION_LOCATION).load().migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, "public", MIGRATION_LOCATION, null); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); TransactionTemplate transactions = diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java index e0f920accf..e621041c0e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java @@ -59,6 +59,7 @@ import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerTestFixtures; import net.firedevops.firemud.gamesession.repository.DirectTextAuthenticatedLobbyRepository; import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository; import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; @@ -70,7 +71,6 @@ import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.exception.DataAccessException; @@ -151,7 +151,7 @@ void migratePopulatedOriginalThenComposeInactiveOwner() throws Exception { source.setUsername(postgres.getUsername()); source.setPassword(postgres.getPassword()); source.setSchema(schema); - migration("1051.1").migrate(); + migrate("1051.1"); dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); manager = new DataSourceTransactionManager(source); tx = new TransactionTemplate(manager); @@ -166,7 +166,7 @@ void migratePopulatedOriginalThenComposeInactiveOwner() throws Exception { journal.recordVerifiedResult(original, verified); }); parentBeforeMigration = parentJson(); - migration(null).migrate(); + migrate(null); repository = new DirectTextAuthenticatedLobbyRepository(dsl); account = mock(AccountClient.class); target = target(); @@ -209,17 +209,12 @@ void migratePopulatedOriginalThenComposeInactiveOwner() throws Exception { owner = owner(repository, manager); } - private Flyway migration(String targetVersion) { - var config = - Flyway.configure() - .dataSource(source) - .schemas(schema) - .defaultSchema(schema) - .locations( - "filesystem:" - + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()); - if (targetVersion != null) config.target(targetVersion); - return config.load(); + private void migrate(String targetVersion) { + CanonicalGameplayIssuerTestFixtures.migrateSchema( + source, + schema, + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(), + targetVersion); } @AfterEach diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogRepositoryTest.java new file mode 100644 index 0000000000..371c80c1b0 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogRepositoryTest.java @@ -0,0 +1,70 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.UUID; +import net.firedevops.firemud.common.gamesession.GameSessionRuntimeFamilyCatalog.Request; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** LOCAL composition guards only; physical capture/commit/readback belongs to PostgreSQL tests. */ +class GameSessionRuntimeFamilyCatalogRepositoryTest { + @Test + void captureAndReadbackRejectBothAmbientStatesBeforeSqlOrTransactionCreation() { + DSLContext dsl = mock(DSLContext.class); + var transactions = mock(PlatformTransactionManager.class); + var owner = + new GameSessionRuntimeFamilyCatalogRepository(dsl, transactions, "gs_owner", "test"); + var request = new Request(UUID.randomUUID(), "test"); + for (boolean synchronizationOnly : new boolean[] {false, true}) { + try { + if (synchronizationOnly) TransactionSynchronizationManager.initSynchronization(); + else TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> owner.capture(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("independent owner transactions"); + assertThatThrownBy(() -> owner.readExact(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("independent owner transactions"); + } finally { + TransactionSynchronizationManager.clear(); + } + } + verifyNoInteractions(dsl, transactions); + } + + @Test + void workloadNamespaceIsFixedConfigurationNotCallerSelectedAuthority() { + DSLContext dsl = mock(DSLContext.class); + var transactions = mock(PlatformTransactionManager.class); + var owner = + new GameSessionRuntimeFamilyCatalogRepository(dsl, transactions, "gs_owner", "test"); + var wrong = new Request(UUID.randomUUID(), "other"); + assertThatThrownBy(() -> owner.capture(wrong)) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> owner.readExact(wrong)) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + verifyNoInteractions(dsl, transactions); + } + + @Test + void invalidConfiguredSchemaOrNamespaceCannotReachSql() { + DSLContext dsl = mock(DSLContext.class); + var transactions = mock(PlatformTransactionManager.class); + for (String schema : new String[] {"", "public;select", "MixedCase", "a".repeat(64)}) { + assertThatThrownBy( + () -> + new GameSessionRuntimeFamilyCatalogRepository(dsl, transactions, schema, "test")) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + new GameSessionRuntimeFamilyCatalogRepository(dsl, transactions, "gs_owner", "BAD")) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(dsl, transactions); + } +} diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java index c0b23faec5..16d1d16e46 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java @@ -140,7 +140,13 @@ public static GameSessionHolder startGameSession( props.put("spring.grpc.server.port", "0"); props.put("spring.main.allow-bean-definition-overriding", "true"); props.put("spring.flyway.enabled", "true"); - props.put("spring.flyway.locations", "filesystem:" + gameSessionMigrationDir()); + props.put("spring.flyway.placeholders.serviceSchema", "public"); + props.put( + "spring.flyway.locations", + "filesystem:" + + gameSessionMigrationDir() + + ",filesystem:" + + resolveModuleMigrationDir("common-saga").resolve("saga")); props.put( "spring.autoconfigure.exclude", "org.springframework.boot.grpc.server.autoconfigure.health.GrpcServerHealthAutoConfiguration"); diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedOriginalOwnerFixture.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedOriginalOwnerFixture.java index e9bd406aa4..fc94527ac2 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedOriginalOwnerFixture.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedOriginalOwnerFixture.java @@ -484,7 +484,13 @@ private void migrateTo(String version) { .dataSource(dataSource) .schemas(schema) .defaultSchema(schema) - .locations("filesystem:" + migrations) + .locations( + "filesystem:" + migrations, + "filesystem:" + + migrations + .resolve( + "../../../../../../common-saga/src/main/resources/db/migration/saga") + .normalize()) .placeholders(Map.of("serviceSchema", schema)); if (version != null) migration.target(MigrationVersion.fromVersion(version)); migration diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/AccountAdmissionProtectionCurrentOwnerCompositionCrossServiceTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/AccountAdmissionProtectionCurrentOwnerCompositionCrossServiceTest.java index c3c2b5f9df..70422fba25 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/AccountAdmissionProtectionCurrentOwnerCompositionCrossServiceTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/AccountAdmissionProtectionCurrentOwnerCompositionCrossServiceTest.java @@ -150,8 +150,13 @@ void actualAccountAcquisitionAndExactRetryUseAuthenticatedGsOriginalAndRefuseCha .locations( "filesystem:" + Path.of("../game-session-service/src/main/resources/db/migration") + .toAbsolutePath() + .normalize(), + "filesystem:" + + Path.of("../common-saga/src/main/resources/db/migration/saga") .toAbsolutePath() .normalize()) + .placeholders(java.util.Map.of("serviceSchema", gsData.getSchema())) .load() .migrate(); var dsl = DSL.using(new TransactionAwareDataSourceProxy(gsData), SQLDialect.POSTGRES); diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java index 01975f26b4..4df4d24379 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java @@ -555,7 +555,7 @@ private void compose( proofDirectory.resolve("account"), tenant); var world = database(WORLD, "world-management-service", true); - var gs = database(GS, "game-session-service", false)) { + var gs = database(GS, "game-session-service", true)) { var issuer = new AccountOriginalStartSessionAuthorizationProofFixture( account, proofDirectory.resolve("issuer"), NAMESPACE);