From 247f7ff841c6cabf19a0a476d61e9f1a2e87fd33 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 26 Oct 2026 12:28:35 +1300 Subject: [PATCH 01/34] Prepare pending issuer bootstrap and physical v2 member contracts --- .../game-session-service/api-contracts.md | 2 + .../game-session-service/runtime-and-data.md | 2 +- .../architecture/system-architecture-redis.md | 45 +- .../system-architecture-session-behavior.md | 6 +- .../player-access-and-session.md | 2 + ...calGameplayBindingInventoryRepository.java | 63 ++ ...alGameplayIssuerLayoutBootstrapIntent.java | 363 +++++++ ...meplayIssuerLayoutBootstrapRepository.java | 848 +++++++++++++++ .../CanonicalGameplayIssuerMemberV2Codec.java | 632 +++++++++++ .../CanonicalGameplayIssuerMemberV2Value.java | 279 +++++ .../CanonicalGameplayIssuerRedisKeys.java | 111 ++ ...nonical_issuer_layout_bootstrap_intent.sql | 137 +++ ...losedBarrierRedisOwnerIntegrationTest.java | 89 +- ...strapMigrationPostgresIntegrationTest.java | 220 ++++ ...outBootstrapRepositoryIntegrationTest.java | 989 ++++++++++++++++++ ...lGameplayIssuerMemberV2ValueCodecTest.java | 438 ++++++++ .../CanonicalGameplayIssuerRedisKeysTest.java | 120 +++ 17 files changed, 4309 insertions(+), 37 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapIntent.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerMemberV2Codec.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerMemberV2Value.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerRedisKeys.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V1030__canonical_issuer_layout_bootstrap_intent.sql create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapMigrationPostgresIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerMemberV2ValueCodecTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerRedisKeysTest.java diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 8f133c6770..fbbc34d7b0 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -8,6 +8,8 @@ Target state makes Game Session the authoritative owner of region/tick coordinat ## Implementation Status +The local issuer-index model, codec and key helper carry the selected physical member schema v2; decoding validates shape, not current source, anchor, capacity or incarnation authority. This storage consequence adds no public or internal RPC. Retained physical v1 artifacts are unqualified and have no fallback, and Account acknowledgement schema v2 remains account-only. The separate owner-qualified issuer acknowledgement and final guarded controller CAS remain required before manual NEW consumers can admit; see the [issuer-index owner](../../system-architecture-redis.md#issuer-active-binding-index) and [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components). + The local [canonical NEW admission lease contract](../../system-architecture-session-behavior.md#canonical-public-production-new-admission) now has generated transport carriers and a manually composed `AccountGameplayAdmissionLeaseClient` for Account’s four purpose-specific methods. Its narrow candidate uses the exact Account issuer string at the original string wire tag; shape validation supplies no issuer authority. The [Account API](../account-service/api-contracts.md#canonical-public-production-new-admission-lease-source) owns caller authentication, acquisition, original finalization and read/abort recovery. The prepared Account-only reverse-read proto and closed codec preserve separate current published-target and exact provisional-decision purposes, with their finite transport bounds; this prerequisite does not supply their genuine Game Session owner composition or register a source receiver. The Account receiver’s focused physical-COMMIT and durable-ACK proof uses explicitly controlled reverse responses. These local components do not acknowledge issuer/region obligations or admit a binding; the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) records component proof and remaining composition. The initial-LOGIN PostgreSQL journal and exact original-attempt cleanup owner are unregistered source preparation, with no new Game Session endpoint or legacy LOGIN handler composition. Their unregistered Account client authenticates the exact same-namespace Account mTLS peer and validates the explicit initial delegation profile, signature, original request/context, token hash, claim/projection equality and bounded nonsecret evidence. Its one transient invocation permits at most one transport reload/retry under the unchanged deadline. It also uses the original-request retirement contract. The result retains compact private-token bytes only in process; validation supplies neither current registry authority nor live context installation. Journal snapshots and typed closure fixtures supply no authenticated caller custody or physical Redis closure; the separate Redis adapter remains outside runtime composition. See the [canonical coordination contract](../../system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination) and [implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). 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 c42c989c33..cb7d1b84cf 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,7 +10,7 @@ The service runtime model assumes replaceable workers, not authoritative in-proc The sections below define the target-state runtime contract. Current implementation and proof status is: -- **Local NEW issuer identity:** canonical inventory retains Account's exact issuer string, and typed reads refuse retained UUID issuers rather than relabel them. This storage boundary does not establish issuer ownership, complete coverage, or admission; see [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for migration proof and limits. +- **Local NEW issuer preparation:** canonical inventory retains Account's exact issuer string and refuses retained UUID issuers rather than relabel them. The unregistered SQL owner persists `INITIAL_BOOTSTRAP_INTENT` with a frozen complete issuer cohort and blocks later preparation. Shape-only schema-v2 member model, codec and key-helper sources are present, but do not implement a partition writer or establish authority. There is no installed pointer, partition/capacity operation, separate issuer acknowledgement, issuer barrier/`OPEN`, final CAS or admission. Descriptor and Account checkpoint inputs remain controlled, and operational incarnation, legacy recovery, PKI and activation holds remain; focused receiving proof and its limits are recorded in the tracker. See the [issuer anchor owner](../../system-architecture-redis.md#installed-issuer-anchor-for-ordinary-new) and [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for the physical contract and donor proof attribution. - **Local NEW account-member repair:** the unregistered owner prepares the original binding-local operation, performs one global account-member write and physical readback outside SQL, then accepts its exact acknowledgement in SQL. This supplies `ADD_OR_RETAIN` evidence only; the candidate remains provisional. Account-wide lifecycle writers, remaining index and region acknowledgements, and the guarded final admission CAS remain open. See [Session Behavior](../../system-architecture-session-behavior.md#global-account-active-binding-index) and [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components). diff --git a/design/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index e5c7faedef..73713df21d 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -328,7 +328,7 @@ key: session:game:index:issuer:{issuerIndexLayoutTag}:: type: HASH field: value: { - schemaVersion: 1, + schemaVersion: 2, issuerId, accountId, tenantId, @@ -336,10 +336,43 @@ value: { sessionId, bindingGeneration, issuerAuthGeneration, - issuerIndexLayoutVersion + issuerIndexLayoutVersion, + playableStateNamespaceId, + characterId, + playableStateScope, + runtimeGameInstanceId, + regionId, + regionEpoch, + issuerControlEpoch, + layout: { + partitionCount, partitionCapacity, mappingIdentity, + descriptorBytes, descriptorDigest + }, + reservation: { + reservationId, bindingRef, transitionId, partitionId, + lifecycle, reservationFence, inventoryRevision + }, + anchor: { + issuerCoverageOperationId, operationFence, coverageFence, + issuerInventorySnapshotRevision, sourceCheckpointBytes, + sourceCheckpointDigest, sourceEventBytes, sourceEventDigest + }, + memberOperation: { operationId, operationFence, coverageGeneration }, + incarnation: { + attestorBinding, acceptedAttestationDigest, targetDeploymentEvidence, + coordOpsRoAclDigest, coordRedisConfigObservedDigest + } } ``` +The value is a closed, bounded RFC 8785 canonical JSON object. Except for the literal numeric `schemaVersion: 2`, counters use canonical unsigned decimal strings; every counter is positive except the zero-based `partitionId`. Implementations preserve values beyond binary floating-point precision. UUIDs and identifiers retain their exact canonical spelling, and bytes use canonical padded Base64. `sourceEventBytes` and `sourceEventDigest` are both explicit `null` only when the exact qualified Account checkpoint has no corresponding event. Unknown or duplicate fields, unsupported versions, malformed UTF-8, noncanonical bytes, inconsistent owner/partition/layout references, and resource-bound violations fail closed; parser limits never authorize normalization or truncation. + +The full owner identity, immutable authorized layout descriptor, and Account source bytes must agree with the original reservation and anchor. `anchor.issuerInventorySnapshotRevision` is the complete immutable issuer inventory revision; `reservation.inventoryRevision` is that reservation's durable transition revision, and they are not interchangeable. The anchor operation fence, coverage fence, binding-local member-operation fence and `issuerControlEpoch` retain separate evidence domains. The anchor operation and coverage fences have distinct values; equality between counters from different domains does not merge their authority or imply an ordering. `memberOperation.coverageGeneration` is concrete only after its issuing owner allocates it; a parser, bootstrap preparation, or caller cannot invent it. The value retains the complete stable incarnation binding, including every field of accepted `targetDeploymentEvidence/v1`, not only its digest. Fresh observation nonces, observation times, and signing-key selection are not stable row identity; the protected current-observation owner validates them at each decisive boundary. See [Redis Operations and Access](./system-architecture-redis-ops-access.md) for protected evidence ownership. + +The exact `bindingRef` field identity and canonical partition key remain unchanged. Physical schema-v1 values are retained historical or legacy evidence and never qualify a v2 member, retry, readback, or cleanup. Encountering v1 requires the canonical fenced complete-inventory rebuild or migration; an empty-key assumption, SQL acknowledgement, or hidden second-key witness cannot upgrade it. The same binding under a different anchor, reservation, local operation, issuer-control epoch, or storage incarnation is a conflict, not an idempotent retry. Mutation, exact readback, and cleanup compare the complete v2 value at the one issuer-partition key and permit only the defined original-operation transition. + +Capacity evidence shares that same owned partition HASH and atomic boundary. Reserved versioned capacity-field names must be disjoint from every canonical `bindingRef` field, and capacity values retain the exact anchor, layout, original reservation/member-operation tuple, and incarnation needed for comparison. Capacity counts distinct non-terminal reservations through `RESERVED`, `BOUND`, and `RELEASE_PENDING`; it is not inferred from binding rows or total HASH fields. Separate capacity/readback steps compare the same complete tuples and never use a second key, key absence as initialization authority, or SQL intent as physical evidence. + ### Canonical Issuer Partition Mapping The target `bindingRef` encoding is one exact versioned UTF-8 byte sequence, consistent with the repository's length-prefixed identity convention. For `segment(bytes) = ascii(canonical_decimal_count(byte_length(bytes))) + ":" + bytes`, where the count has no leading zero, the complete binding identity is encoded in this fixed order: @@ -392,6 +425,14 @@ The issuer binding/index CAS must persist and exact-compare the complete binding For a linked issuer recovery edge, edge creation, update, every exact retry, child-result/readback association, and parent-consumption CAS must persist and exact-compare `parentRecoveryOperationId`, `parentLifecycle`, `parentOperationFence`, and `parentCoverageFence` together with the exact child identity, child lifecycle/fences, `linkRevision`, and complete snapshot/layout/cutoff/reservation/capacity proof. Child requests, digests, transitions, readbacks, acknowledgements, and retries remain parent-independent. A standalone issuer operation uses the four exact typed `NOT_APPLICABLE` parent markers and has no parent lifecycle or parent-consumption path. +### Installed Issuer Anchor for Ordinary NEW + +Ordinary binding-local `NEW` may use the global issuer index only under a positively installed, complete issuer-coverage and layout anchor. It binds the exact `{issuerId, issuerCoverageOperationId, operationFence, coverageFence, issuerInventorySnapshotRevision}` and pinned active layout `{issuerIndexLayoutVersion, issuerIndexPartitionCount, issuerIndexPartitionCapacity}`. The account-side `NO_ACTIVE_ACCOUNT_WIDE_FLOW` exception is account-only and says nothing about issuer coverage or layout. + +The issuer owner establishes that anchor only from an authorized immutable layout descriptor, exact current Account source checkpoint, verified legacy disposition, and complete durable issuer inventory including reservations and unresolved obligations. It must build or verify every required partition and reservation, prove local and aggregate capacity, and retain same-attempt readback before guarded publication. An empty physical index, absent or empty inventory result, or conformance-vector count is not initialization authority; unresolved legacy identities remain retained and fenced. Controlled descriptor, source, and incarnation inputs establish only local algorithm behavior, not operational bootstrap authority. + +The physical v2 HASH value above is a projection, not the installed anchor or an issuer binding-local acknowledgement. The separate issuer acknowledgement must be explicitly versioned and bind the complete anchor, exact local transition/reservation, member and capacity readbacks, current control/incarnation evidence, and owner-issued per-transition generation. Neither physical-row parsing nor the account `accountIndexAcknowledgement` schema v2 can manufacture that result; the account acknowledgement and its CLOSED barrier receipt establish no issuer anchor or issuer `INSTALLED`/`OPEN` state. The final tenant-local CAS must positively compare the exact issuer barrier `OPEN` state and owner epoch/incarnation with the original candidate and required Account, issuer, and region evidence; global issuer-index and capacity keys never enter tenant-local Lua. + ### Recovery and Cutoff Scope Authority The permitted scope is part of the evidence contract, not an operator hint. A region- or tenant-scoped preserved-session parent may enumerate only its binding-local snapshot, repair the region-local and tenant-scoped families it owns, and validate a linked child result. It may not map an issuer layout, perform issuer Redis field or reservation-capacity repair, read back issuer partitions for coverage, publish an issuer-partition acknowledgement, or claim global account-index coverage from its narrow snapshot. An issuer-wide child or standalone issuer operation must use a complete authoritative issuer inventory. A standalone operation carries `parentRecoveryOperationId=NOT_APPLICABLE`, `parentLifecycle=NOT_APPLICABLE`, `parentOperationFence=NOT_APPLICABLE`, and `parentCoverageFence=NOT_APPLICABLE`, then uses its own `issuerCoverageOperationId`, `issuerCoverageOperationFence`, distinct `coverageFence`, later `coverageGeneration`, pinned layout, and all finite partitions. A linked child retains the exact parent tuple through its independent edge but does not nest under the parent maintenance lock; the parent owns that lock and the child owns only its operation and coverage fences. An account-wide operation may cover only the untagged account family from a complete account inventory and its own account coverage evidence; it cannot substitute for issuer coverage. A cluster recovery must rebuild or consume complete per-account and per-issuer coverage for the deployment rather than treating a local region, tenant, or aggregate snapshot as global proof. diff --git a/design/architecture/system-architecture-session-behavior.md b/design/architecture/system-architecture-session-behavior.md index c062c09ab9..e5ead30e66 100644 --- a/design/architecture/system-architecture-session-behavior.md +++ b/design/architecture/system-architecture-session-behavior.md @@ -62,6 +62,8 @@ The selected canonical `NEW` path uses Account's purpose-specific `AccountGamepl The binding and issuer-index `issuerId` is the exact Account issuer identifier defined by [JWT and Token Contracts](./system-architecture-jwt-and-token-contracts.md), carried without normalization or a UUID surrogate. Acquisition, finalization and reconciliation compare that identity together with its generation and original source/checkpoint evidence against authenticated current Account owners; generation equality or caller-supplied spelling alone is insufficient. Existing UUID-shaped issuer records without exact original authoritative provenance remain non-admitting and retained for explicit fenced reconciliation. A forward storage conversion preserves their original identity, evidence and cleanup obligations; it never relabels them as the Account issuer or assumes an empty inventory. +The issuer-partition Redis HASH field remains the exact `bindingRef/v1` bytes; schema v2 changes the physical value, not the key, field, or canonical partition mapping. Retained physical schema-v1 values are unqualified legacy evidence and never take a fallback path. A shape-valid v2 row is not the installed issuer anchor or the separate explicitly versioned issuer binding-local acknowledgement; the account `accountIndexAcknowledgement` schema v2 remains account-only. See [Redis Architecture](./system-architecture-redis.md#issuer-active-binding-index) for the physical contract. + The pre-lease published-target read and exact lease-bound `PROVISIONAL` decision read are separate Account-only purposes on the same Game Session service, following the [authentication sequence](./system-architecture-authentication.md#in-band-play-admission-boundary). Game Session independently joins the actual initial World placement to its current runtime-region assignment through the [World owner read](./microservices/world-management-service/api-contracts.md#grpc-apis) and revalidates that source at the binding gate. A guessed region, template-region identity or single-entry map is not placement authority. The candidate remains non-admitting until exact Account `COMMITTED` evidence, actual account-index and issuer-partition acknowledgements, the region bridge acknowledgement and the final tenant-local session/index CAS agree. Only that final CAS admits `PLAY` or `LOOK`. This initial path may refuse existing-controller transfer and resume until their complete protocols are qualified; it does not introduce an ordinary session-save or default-room shortcut. These are the selected target requirements. The current manual source/decision transports, caller verifier and component proof do not establish a complete admitted player binding or default runtime registration. Remaining implementation and proof are recorded in the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md). @@ -178,14 +180,14 @@ Target-state Game Session must also maintain bounded authoritative secondary ind - `session:game:index:account-tenant:{tenantGameplayTag}:` -> active `sessionId` set - `session:game:index:tenant:{tenantGameplayTag}` -> active `sessionId` set - Target-state `session:game:index:realm-grant:{tenantGameplayTag}:` -> active `sessionId` set for private/playtest grant-gated realms, where `grantScopeId` is the exact shared-codec `grant/v1` scope ID for the complete Account-owned tuple; public-production and unscoped bindings have no realm-grant index entry -- `session:game:index:issuer:{issuerIndexLayoutTag}::` -> a bounded Redis hash whose field is the canonical `bindingRef` for one active or provisional binding and whose value is `{schemaVersion: 1, issuerId, accountId, tenantId, gameInstanceId, sessionId, bindingGeneration, issuerAuthGeneration, issuerIndexLayoutVersion}`. `bindingRef` and `partitionId` use the exact [canonical issuer partition mapping](./system-architecture-redis.md#canonical-issuer-partition-mapping): the fixed `bindingRef/v1` UTF-8 length-prefixed bytes, SHA-256, unsigned big-endian normalization, and modulo the positive count pinned by the immutable `issuerIndexLayoutVersion`. Every writer, cutoff, recovery, capacity repair, and migration reuses that mapping and the published vectors; `{issuerIndexLayoutTag}` is the opaque Redis hash tag derived from `(issuerIndexLayoutVersion, issuerId, partitionId)`. The issuer family therefore has a finite, known key set for each issuer and layout and distributes partitions without using wildcard scans. +- `session:game:index:issuer:{issuerIndexLayoutTag}::` -> a bounded Redis hash whose binding-member field is the canonical `bindingRef` and whose member value is the complete [physical issuer-member v2 value](./system-architecture-redis.md#issuer-active-binding-index). `bindingRef` and `partitionId` use the exact [canonical issuer partition mapping](./system-architecture-redis.md#canonical-issuer-partition-mapping): the fixed `bindingRef/v1` UTF-8 length-prefixed bytes, SHA-256, unsigned big-endian normalization, and modulo the positive count pinned by the immutable `issuerIndexLayoutVersion`. Every writer, cutoff, recovery, capacity repair, and migration reuses that mapping and the published vectors; `{issuerIndexLayoutTag}` is the opaque Redis hash tag derived from `(issuerIndexLayoutVersion, issuerId, partitionId)`. The issuer family therefore has a finite, known key set for each issuer and layout and distributes partitions without using wildcard scans. Index contract requirements: - In target state, Game Session is the sole writer for all six index families; Account authority and realm-grant state remain the authorization source, not the indexes. - The shard-local CAS/update flow contains exactly the gameplay session record plus the four tenant-scoped indexes: character, account-tenant, tenant, and realm-grant. All of those keys share `{tenantGameplayTag}`. The initial CAS publishes only the provisional candidate; the final follow-up CAS is the atomic controller boundary for takeover, resume, and tenant/grant-binding decisions inside Redis Cluster, and exact-compares the provisional generation, Account-owned exact-binding admission lease identity, monotonic lease fence, applicable authority cutoff checkpoint, and required follow-up acknowledgements. - The cross-tenant `session:game:index:account:` and issuer-partition indexes are explicitly excluded from that shard-local CAS because they span tenant hash slots or issuer partitions. The untagged account key is also excluded from every tenant-local Lua invocation. Before the tenant-scoped CAS publishes a new binding, Game Session durably commits deterministic account-index and issuer-index repair obligations keyed to that binding transition. The account obligation contains the expected prior generation, candidate `bindingGeneration`, unique transition identity, desired add/remove, and `accountIndexFence`; the issuer obligation also carries its exact reservation identity. The shard-local CAS may publish only a provisional binding with each applicable `accountIndexState=REPAIR_REQUIRED` and `issuerIndexState=REPAIR_REQUIRED`; it is not admissible for gameplay, resume, or takeover. Game Session then performs each separate idempotent single-key index/capacity compare-and-set, reads back the exact generation/fence-qualified member and reservation state, and durably acknowledges each matching account/issuer obligation. The region-lease bridge is another ordered, separately acknowledged follow-up using the validated binding generation and region epoch. Only after all required account, issuer, and region acknowledgements does the final follow-up shard-local CAS exact-compare the provisional generation, set the applicable states to `ACKNOWLEDGED`, and admit the binding at the controller linearization point. This ordered protocol closes the cross-slot and region-bridge crash windows without claiming a cross-store transaction. -- An issuer-index write or removal compares the complete expected `bindingRef`, `bindingGeneration`, `issuerAuthGeneration`, and active `issuerIndexLayoutVersion` before changing the hash field; the same operation also compares the exact reservation owner, transition, partition/layout, lifecycle, fence, and revision. An identical already-applied value is an idempotent success, while a newer or conflicting value is a repair conflict. At the start of an issuer cutoff or recovery, Game Session captures the active layout pointer's version, partition count, and capacity while establishing the operation and coverage fences, then reads exactly that pinned finite partition range and maps every binding through the canonical mapping helper; it does not reread the pointer and mix layouts during the operation. If the pointer no longer matches before acknowledgement, the current operation fails closed or enters the explicit layout-transition workflow, which accounts for the complete pinned old layout and separately built new layout before cutover; neither workflow evaluates a mixed partition set. The operation validates every returned value and reservation, then fences or terminates the referenced bindings through their ordinary binding CAS. Missing Redis responses, unreadable partitions, unresolved reservations or repair obligations, or conflicting field values are unavailable or ambiguous coverage, never an empty result. Recovery rebuilds each partition from the complete durable active-binding and reservation inventory using the same expected-value compare-and-set, canonical mapping, and capacity rules and clears the repair obligation only after every required partition, reservation, and binding acknowledgement is proven. +- An issuer-index write or removal atomically compares the complete expected physical v2 value, including the original anchor and local reservation/member-operation and control/incarnation evidence, before changing the hash field; the same operation also compares the exact reservation owner, transition, partition/layout, lifecycle, fence, and revision. An identical already-applied value is an idempotent success, while a newer or conflicting value is a repair conflict. At the start of an issuer cutoff or recovery, Game Session captures the active layout pointer's version, partition count, and capacity while establishing the operation and coverage fences, then reads exactly that pinned finite partition range and maps every binding through the canonical mapping helper; it does not reread the pointer and mix layouts during the operation. If the pointer no longer matches before acknowledgement, the current operation fails closed or enters the explicit layout-transition workflow, which accounts for the complete pinned old layout and separately built new layout before cutover; neither workflow evaluates a mixed partition set. The operation validates every returned value and reservation, then fences or terminates the referenced bindings through their ordinary binding CAS. Missing Redis responses, unreadable partitions, unresolved reservations or repair obligations, or conflicting field values are unavailable or ambiguous coverage, never an empty result. Recovery rebuilds each partition from the complete durable active-binding and reservation inventory using the same expected-value compare-and-set, canonical mapping, and capacity rules and clears the repair obligation only after every required partition, reservation, and binding acknowledgement is proven. - An issuer-partition acknowledgement is a durable evidence object, not an aggregate flag. For preserved region/tenant recovery it must carry the child-owned `issuerCoverageOperationId` and child lifecycle, the child `issuerCoverageOperationFence`, distinct issuer-wide `coverageFence`, `coverageGeneration`, issuer-wide `inventorySnapshotRevision`, pinned `issuerIndexLayoutVersion`, pinned partition count and capacity, `partitionId`, the exact `issuer/` cutoff checkpoint (`issuerAuthGeneration`, `issuanceFence`, and complete applicable `outboxCheckpoints`), every reservation identity with its owner, transition, lifecycle, fence, and inventory revision, and the capacity tuple `{partitionId, reservationCount, partitionCapacity, aggregateReservationCount, aggregateCapacity}`. The independent parent edge and the parent's consumption record carry the exact linked `parentRecoveryOperationId`, both current lifecycles, parent `operationFence`, distinct `parentCoverageFence`, resolved issuer/scope, and link revision; the child request/digest, transition, partition and reservation readback, acknowledgement, and immutable child result are parent-independent. `coverageGeneration=NOT_YET_ISSUED` remains the pre-coverage value and becomes concrete only after complete finite coverage is proven. For a standalone issuer-wide operation, the operation identity is its own issuer coverage operation identity and still carries its own maintenance fence and coverage fence; all parent fields and account-wide fields are the exact `NOT_APPLICABLE` marker plus `NO_ACTIVE_ACCOUNT_WIDE_FLOW`. The acknowledgement is valid only when all of that evidence comes from the same complete issuer-wide snapshot and operation attempt, with exact readback of the partition and reservation state. Cross-snapshot, cross-attempt, narrow-scope, stale-layout, changed-cutoff, mixed-partition, missing-reservation, or partial-capacity evidence is rejected; no acknowledgement may be assembled from separately read responses or used to authorize a different operation or layout. - Every post-fence transition, readback, acknowledgement, and exact retry proof must persist and exact-compare all four fields `operationFence`, `coverageFence`, `coverageGeneration`, and `inventorySnapshotRevision` from the same durable snapshot and operation attempt. `operationFence` plus `coverageGeneration` is insufficient, and no local or parent fence, later generation, or partial snapshot may substitute for either missing field. - Region-local gameplay binding and the region-lease bridge are intentionally outside that atomic boundary; the bridge has its own ordered request, exact readback, and durable acknowledgement, and its success is consumed only by the follow-up shard-local CAS. The Redis architecture docs define that separate bridge contract. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 01ae7ccded..9fcccc3f51 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,6 +12,8 @@ The Account gameplay-admission lease and the unregistered Game Session receiver The Game Session canonical inventory now retains Account's exact issuer string through the forward V1024→V1025 conversion. R488 passes 19 selected PostgreSQL cases, including populated-row migration preservation, restart, canonical writes, and refusal by the typed reader to reinterpret retained UUID issuers. This proves storage identity conversion only; issuer ownership and admission remain unqualified. +The receiving source includes a pending issuer-bootstrap SQL owner that freezes the complete issuer cohort under the inventory clock, requires actual persisted `VERIFIED` legacy-owner evidence, and blocks later preparation. Descriptor and Account issuer-checkpoint inputs remain controlled. Donor-source R539 recorded 65 focused cases (9 unit and 56 PostgreSQL/Redis, including existing account-member regressions); donor-source R545 recorded 12 cases for the physical schema-v2 shape work. Those remain donor-only attributions. Receiving-parent R548 passes 106 fresh cases (12 unit and 94 PostgreSQL/Redis) on parent `be0e20b`, including the 38-case roster regression, full pending-intent repository/migration coverage and existing account-member owners. jOOQ generation, enabled affected Checkstyle/SpotBugs/formatting and documentation checks pass; all exact test containers are absent. This focused receiving proof does not establish a complete service-suite pass or public runtime admission. Donor proof includes the missing-control refusal, both PostgreSQL-observed prepare/intent lock orders, and populated V1029→V1030 retention/restart. The V1028 retained-row fixture uses controlled historical SQL rows, not an actual pre-migration prepare. The receiving tree has shape-only v2 member model, codec and key-helper sources, but no physical Redis mutation/readback, capacity accounting or separate issuer acknowledgement. The canonical physical schema v2 is selected; retained v1 artifacts remain unqualified with no fallback. No installed pointer, complete partition/capacity proof, issuer acknowledgement, barrier `OPEN`, final CAS or admission is established. Operational source/incarnation custody, legacy recovery, PKI and activation holds remain; see the [issuer anchor owner](../../architecture/system-architecture-redis.md#installed-issuer-anchor-for-ordinary-new). + The unregistered no-active first-NEW member-repair owner composes the original durable operation, the physical one-key global account-member write/readback outside SQL, and separate SQL acceptance. V1026 preserves the operation and completion. R506 freshly passes all 29 selected PostgreSQL/Redis cases, including composed completion, frozen retry/restart, retained prior PRESENT observations, positive control-row requirements, exact member preservation, and malformed-completion refusal. Seven focused unit cases retain R505 attribution; ten shared Redis contract cases retain R500 attribution. This is binding-local `ADD_OR_RETAIN` evidence only: it does not enumerate the account, establish global completeness, or admit the candidate. The account-fence preparation source consists of the durable intent/cohort owner, persisted tenant-tag/key mapping, controlled protected current-observation receiver, one-key CLOSED Redis owner, and immutable historical CLOSED receipt. R515 freshly passes nine focused unit and 37 PostgreSQL/Redis cases for intent, cohort, serialization and controlled signed current observations. R521 freshly passes nine focused unit and 46 PostgreSQL/Redis cases, including actual Redis readback acceptance into immutable per-target V1029 receipts, expiry/current-owner refusal, trigger immutability, and populated V1028→V1029 migration/restart preservation. R523 freshly passes ten native cases, including an actual intent advancing initial control epoch 0 to epoch 1 and closing a controlled prior OPEN epoch 0; prior CLOSED epoch 0 remains a non-mutating refusal. The current-observation signer/channel, prior barrier, clock, and high-water fixtures are controlled local inputs, not operational custody or lifecycle producers. These receipts are historical AS-OF evidence: the account control remains `ACQUISITION_INTENT`, targets remain `REQUIRED`, and there is no `INSTALLED`, OPEN, token, final-CAS, admission, or account-wide-coverage proof. No operational protected attestor, accepted deployment-attestation producer, or fresh protected current-proof source is supplied. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index 5f3a5b9890..c6bef63105 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -56,6 +56,10 @@ public final class CanonicalGameplayBindingInventoryRepository { private static final String GENERATION = "game_session_canonical_binding_generation"; private static final String LEGACY_DISPOSITION = "game_session_canonical_binding_legacy_disposition"; + private static final String ISSUER_BOOTSTRAP_CONTROL = + "game_session_canonical_issuer_layout_bootstrap_control"; + private static final String ISSUER_BOOTSTRAP_INTENT = + "game_session_canonical_issuer_layout_bootstrap_intent"; private final DSLContext dsl; CanonicalGameplayBindingInventoryRepository(DSLContext dsl) { @@ -1491,6 +1495,7 @@ private static void requireSameProvisionalOperation( private static CanonicalGameplayBindingTransitionSnapshot prepareInTransaction( DSLContext transaction, CanonicalGameplayBindingTransitionRequest request) { BigInteger revision = lockInventoryRevision(transaction); + requireNoPendingIssuerLayoutBootstrapIntent(transaction, request.candidate().issuerId()); CanonicalGameplayAccountCoverageEvidence accountCoverageEvidence = lockAccountCoverageEvidence(transaction, request.candidate().accountId()); boolean initialBinding = request.expectedPriorBindingRef() == null; @@ -1604,6 +1609,64 @@ private static CanonicalGameplayBindingTransitionSnapshot prepareInTransaction( return prepared; } + private static void requireNoPendingIssuerLayoutBootstrapIntent( + DSLContext transaction, String issuerId) { + Record control = + transaction.fetchOne( + "SELECT * FROM " + ISSUER_BOOTSTRAP_CONTROL + " WHERE issuer_id = ? FOR UPDATE", + issuerId); + if (control == null) { + Record orphanIntent = + transaction.fetchOne( + "SELECT operation_id FROM " + + ISSUER_BOOTSTRAP_INTENT + + " WHERE issuer_id = ? ORDER BY operation_id LIMIT 1 FOR UPDATE", + issuerId); + if (orphanIntent != null) { + throw conflict("Issuer bootstrap intent exists without its positive current control row"); + } + return; + } + + UUID operationId = control.get("current_operation_id", UUID.class); + String state = control.get("state", String.class); + BigInteger controlEpoch = readBigInteger(control, "control_epoch"); + BigInteger operationFence = readBigInteger(control, "current_operation_fence"); + BigInteger coverageFence = readBigInteger(control, "current_coverage_fence"); + BigInteger lastIssuedFence = readBigInteger(control, "last_issued_fence"); + if (!Objects.equals(issuerId, control.get("issuer_id", String.class)) + || !"INITIAL_BOOTSTRAP_INTENT".equals(state) + || operationId == null + || NIL_UUID.equals(operationId) + || controlEpoch.signum() <= 0 + || operationFence.signum() <= 0 + || coverageFence.signum() <= 0 + || !operationFence.equals(controlEpoch) + || operationFence.equals(coverageFence) + || lastIssuedFence.compareTo(coverageFence) < 0) { + throw conflict("Issuer bootstrap control has a malformed or unsupported current pointer"); + } + + Record intent = + transaction.fetchOne( + "SELECT * FROM " + + ISSUER_BOOTSTRAP_INTENT + + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", + operationId, + issuerId); + if (intent == null + || !operationId.equals(intent.get("operation_id", UUID.class)) + || !Objects.equals(issuerId, intent.get("issuer_id", String.class)) + || !"INITIAL_BOOTSTRAP_INTENT".equals(intent.get("intent_state", String.class)) + || !controlEpoch.equals(readBigInteger(intent, "control_epoch")) + || !operationFence.equals(readBigInteger(intent, "operation_fence")) + || !coverageFence.equals(readBigInteger(intent, "coverage_fence")) + || readBigInteger(intent, "inventory_snapshot_revision").signum() <= 0) { + throw conflict("Issuer bootstrap control does not point to its exact durable intent tuple"); + } + throw conflict("Initial issuer-layout bootstrap intent blocks new binding preparation"); + } + private static void validateRequest(CanonicalGameplayBindingTransitionRequest request) { request.candidate().bindingRef().partitionId(request.candidate().issuerIndexPartitionCount()); if (request.candidateAccountIndexFence().equals(NIL_UUID)) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapIntent.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapIntent.java new file mode 100644 index 0000000000..a4ff731ad2 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapIntent.java @@ -0,0 +1,363 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationDisposition; + +/** + * Immutable SQL read model for the pending initial issuer-layout bootstrap intent. + * + *

This model is deliberately limited to {@link State#INITIAL_BOOTSTRAP_INTENT}. It contains no + * active pointer, installed anchor, issuer coverage acknowledgement, or admission authority. + */ +final class CanonicalGameplayIssuerLayoutBootstrapIntent { + static final String MAPPING_IDENTITY = "bindingRef/v1;sha256-u256-mod/v1"; + + enum State { + INITIAL_BOOTSTRAP_INTENT + } + + enum CohortKind { + BINDING, + UNRESOLVED_LEGACY_BINDING, + TRANSITION, + RESERVATION, + UNRESOLVED_LEGACY_RESERVATION, + ACCOUNT_OBLIGATION, + ISSUER_OBLIGATION, + REGION_OBLIGATION + } + + private final UUID operationId; + private final UUID requestId; + private final String issuerId; + private final BigInteger controlEpoch; + private final BigInteger operationFence; + private final BigInteger coverageFence; + private final BigInteger inventorySnapshotRevision; + private final LayoutDescriptor layoutDescriptor; + private final AccountIssuerSourceCheckpoint sourceCheckpoint; + private final CanonicalGameplayLegacyMigrationDisposition legacyDisposition; + private final State state; + private final List cohortRows; + private final String cohortDigest; + + CanonicalGameplayIssuerLayoutBootstrapIntent( + UUID operationId, + UUID requestId, + String issuerId, + BigInteger controlEpoch, + BigInteger operationFence, + BigInteger coverageFence, + BigInteger inventorySnapshotRevision, + LayoutDescriptor layoutDescriptor, + AccountIssuerSourceCheckpoint sourceCheckpoint, + CanonicalGameplayLegacyMigrationDisposition legacyDisposition, + State state, + List cohortRows, + String cohortDigest) { + this.operationId = requireNonNil(operationId, "operationId"); + this.requestId = requireNonNil(requestId, "requestId"); + if (operationId.equals(requestId)) { + throw new IllegalArgumentException("operationId and requestId must be distinct"); + } + this.issuerId = requireIssuerId(issuerId); + this.controlEpoch = requirePositive(controlEpoch, "controlEpoch"); + this.operationFence = requirePositive(operationFence, "operationFence"); + this.coverageFence = requirePositive(coverageFence, "coverageFence"); + this.inventorySnapshotRevision = + requirePositive(inventorySnapshotRevision, "inventorySnapshotRevision"); + if (!operationFence.equals(controlEpoch) || operationFence.equals(coverageFence)) { + throw new IllegalArgumentException( + "controlEpoch must equal operationFence and coverageFence must be distinct"); + } + this.layoutDescriptor = Objects.requireNonNull(layoutDescriptor, "layoutDescriptor"); + this.sourceCheckpoint = Objects.requireNonNull(sourceCheckpoint, "sourceCheckpoint"); + if (!issuerId.equals(layoutDescriptor.issuerId()) + || !issuerId.equals(sourceCheckpoint.issuerId())) { + throw new IllegalArgumentException("Issuer layout and source checkpoint scopes must match"); + } + this.legacyDisposition = Objects.requireNonNull(legacyDisposition, "legacyDisposition"); + if (legacyDisposition.canonicalInventoryRevision().compareTo(inventorySnapshotRevision) > 0) { + throw new IllegalArgumentException( + "Legacy disposition cannot be newer than the captured issuer inventory"); + } + this.state = Objects.requireNonNull(state, "state"); + if (state != State.INITIAL_BOOTSTRAP_INTENT) { + throw new IllegalArgumentException("Only a pending initial-bootstrap intent is supported"); + } + this.cohortRows = List.copyOf(Objects.requireNonNull(cohortRows, "cohortRows")); + if (this.cohortRows.stream().anyMatch(Objects::isNull)) { + throw new IllegalArgumentException("Issuer cohort rows must not contain null"); + } + for (int index = 0; index < this.cohortRows.size(); index++) { + if (this.cohortRows.get(index).rowOrdinal() != index) { + throw new IllegalArgumentException( + "Issuer cohort row ordinals must be contiguous from zero"); + } + } + this.cohortDigest = requireDigest(cohortDigest, "cohortDigest"); + } + + UUID operationId() { + return operationId; + } + + UUID requestId() { + return requestId; + } + + String issuerId() { + return issuerId; + } + + BigInteger controlEpoch() { + return controlEpoch; + } + + BigInteger operationFence() { + return operationFence; + } + + BigInteger coverageFence() { + return coverageFence; + } + + BigInteger inventorySnapshotRevision() { + return inventorySnapshotRevision; + } + + LayoutDescriptor layoutDescriptor() { + return layoutDescriptor; + } + + AccountIssuerSourceCheckpoint sourceCheckpoint() { + return sourceCheckpoint; + } + + CanonicalGameplayLegacyMigrationDisposition legacyDisposition() { + return legacyDisposition; + } + + State state() { + return state; + } + + List cohortRows() { + return cohortRows; + } + + String cohortDigest() { + return cohortDigest; + } + + static final class LayoutDescriptor { + private final String issuerId; + private final BigInteger layoutVersion; + private final BigInteger partitionCount; + private final BigInteger partitionCapacity; + private final String mappingIdentity; + private final byte[] exactDescriptorBytes; + private final String descriptorDigest; + + LayoutDescriptor( + String issuerId, + BigInteger layoutVersion, + BigInteger partitionCount, + BigInteger partitionCapacity, + String mappingIdentity, + byte[] exactDescriptorBytes, + String descriptorDigest) { + this.issuerId = requireIssuerId(issuerId); + this.layoutVersion = requirePositive(layoutVersion, "layoutVersion"); + this.partitionCount = requirePositive(partitionCount, "partitionCount"); + this.partitionCapacity = requirePositive(partitionCapacity, "partitionCapacity"); + this.mappingIdentity = Objects.requireNonNull(mappingIdentity, "mappingIdentity"); + if (!MAPPING_IDENTITY.equals(mappingIdentity)) { + throw new IllegalArgumentException("Unsupported canonical issuer mapping identity"); + } + this.exactDescriptorBytes = nonEmptyBytes(exactDescriptorBytes, "exactDescriptorBytes"); + this.descriptorDigest = requireDigest(descriptorDigest, "descriptorDigest"); + } + + String issuerId() { + return issuerId; + } + + BigInteger layoutVersion() { + return layoutVersion; + } + + BigInteger partitionCount() { + return partitionCount; + } + + BigInteger partitionCapacity() { + return partitionCapacity; + } + + String mappingIdentity() { + return mappingIdentity; + } + + byte[] exactDescriptorBytes() { + return exactDescriptorBytes.clone(); + } + + String descriptorDigest() { + return descriptorDigest; + } + } + + static final class AccountIssuerSourceCheckpoint { + private final String issuerId; + private final BigInteger issuerAuthGeneration; + private final byte[] exactCheckpointBytes; + private final String checkpointDigest; + private final byte[] latestIssuerEventBytes; + private final String latestIssuerEventDigest; + + AccountIssuerSourceCheckpoint( + String issuerId, + BigInteger issuerAuthGeneration, + byte[] exactCheckpointBytes, + String checkpointDigest, + byte[] latestIssuerEventBytes, + String latestIssuerEventDigest) { + this.issuerId = requireIssuerId(issuerId); + this.issuerAuthGeneration = requirePositive(issuerAuthGeneration, "issuerAuthGeneration"); + this.exactCheckpointBytes = nonEmptyBytes(exactCheckpointBytes, "exactCheckpointBytes"); + this.checkpointDigest = requireDigest(checkpointDigest, "checkpointDigest"); + if ((latestIssuerEventBytes == null) != (latestIssuerEventDigest == null)) { + throw new IllegalArgumentException("Latest issuer event bytes and digest must be paired"); + } + this.latestIssuerEventBytes = + latestIssuerEventBytes == null + ? null + : nonEmptyBytes(latestIssuerEventBytes, "latestIssuerEventBytes"); + this.latestIssuerEventDigest = + latestIssuerEventDigest == null + ? null + : requireDigest(latestIssuerEventDigest, "latestIssuerEventDigest"); + } + + String issuerId() { + return issuerId; + } + + BigInteger issuerAuthGeneration() { + return issuerAuthGeneration; + } + + byte[] exactCheckpointBytes() { + return exactCheckpointBytes.clone(); + } + + String checkpointDigest() { + return checkpointDigest; + } + + byte[] latestIssuerEventBytes() { + return latestIssuerEventBytes == null ? null : latestIssuerEventBytes.clone(); + } + + String latestIssuerEventDigest() { + return latestIssuerEventDigest; + } + } + + static final class CohortRow { + private final long rowOrdinal; + private final CohortKind kind; + private final String sourceKey; + private final BigInteger sourceInventoryRevision; + private final String sourceRowJson; + private final String sourceRowDigest; + + CohortRow( + long rowOrdinal, + CohortKind kind, + String sourceKey, + BigInteger sourceInventoryRevision, + String sourceRowJson, + String sourceRowDigest) { + if (rowOrdinal < 0) throw new IllegalArgumentException("rowOrdinal must not be negative"); + this.rowOrdinal = rowOrdinal; + this.kind = Objects.requireNonNull(kind, "kind"); + this.sourceKey = requireNonBlank(sourceKey, "sourceKey"); + this.sourceInventoryRevision = + requirePositive(sourceInventoryRevision, "sourceInventoryRevision"); + this.sourceRowJson = requireNonBlank(sourceRowJson, "sourceRowJson"); + this.sourceRowDigest = requireDigest(sourceRowDigest, "sourceRowDigest"); + } + + long rowOrdinal() { + return rowOrdinal; + } + + CohortKind kind() { + return kind; + } + + String sourceKey() { + return sourceKey; + } + + BigInteger sourceInventoryRevision() { + return sourceInventoryRevision; + } + + String sourceRowJson() { + return sourceRowJson; + } + + String sourceRowDigest() { + return sourceRowDigest; + } + } + + private static String requireIssuerId(String value) { + Objects.requireNonNull(value, "issuerId"); + if (!GameSessionAccountDelegationProfile.ISSUER.equals(value)) { + throw new IllegalArgumentException("Issuer must be the exact Account environment issuer"); + } + return value; + } + + private static UUID requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(name + " must not be nil"); + } + return value; + } + + private static BigInteger requirePositive(BigInteger value, String name) { + Objects.requireNonNull(value, name); + if (value.signum() <= 0) throw new IllegalArgumentException(name + " must be positive"); + return value; + } + + private static byte[] nonEmptyBytes(byte[] value, String name) { + Objects.requireNonNull(value, name); + if (value.length == 0) throw new IllegalArgumentException(name + " must not be empty"); + return value.clone(); + } + + private static String requireNonBlank(String value, String name) { + Objects.requireNonNull(value, name); + if (value.isBlank()) throw new IllegalArgumentException(name + " must not be blank"); + return value; + } + + private static String requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(name + " must be a canonical SHA-256 digest"); + } + return value; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java new file mode 100644 index 0000000000..5dbd6843b3 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java @@ -0,0 +1,848 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +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.Arrays; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.IssuerEvent; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.SourceEvent; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationDisposition; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Package-private LOCAL SQL owner for a pending initial issuer-layout bootstrap intent. + * + *

The descriptor and Account-source inputs are trusted injected LOCAL collaborators. This owner + * freezes their bytes but does not authenticate or produce either source. It never installs an + * active pointer, issues a coverage acknowledgement, or authorizes ordinary admission. + */ +final class CanonicalGameplayIssuerLayoutBootstrapRepository { + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String INVENTORY_CLOCK = "game_session_canonical_binding_inventory_clock"; + private static final String LEGACY_DISPOSITION = + "game_session_canonical_binding_legacy_disposition"; + private static final String CONTROL = "game_session_canonical_issuer_layout_bootstrap_control"; + private static final String INTENT = "game_session_canonical_issuer_layout_bootstrap_intent"; + private static final String COHORT = "game_session_canonical_issuer_layout_bootstrap_cohort_row"; + private static final String MAPPING_IDENTITY = + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY; + + private static final String COHORT_SQL = + "SELECT source_kind, source_key, source_revision, source_row_json FROM (" + + "SELECT CASE WHEN i.issuer_id = ? THEN 'BINDING'" + + " ELSE 'UNRESOLVED_LEGACY_BINDING' END AS source_kind," + + " encode(i.binding_ref, 'hex') AS source_key, i.inventory_revision AS source_revision," + + " to_jsonb(i)::text AS source_row_json FROM game_session_canonical_gameplay_binding_inventory i" + + " WHERE i.inventory_revision <= ?" + + " UNION ALL SELECT 'TRANSITION' AS source_kind, t.transition_id::text AS source_key," + + " t.inventory_revision AS source_revision, to_jsonb(t)::text AS source_row_json" + + " FROM game_session_canonical_binding_transition t WHERE t.inventory_revision <= ?" + + " UNION ALL SELECT CASE WHEN r.issuer_id = ? THEN 'RESERVATION'" + + " ELSE 'UNRESOLVED_LEGACY_RESERVATION' END AS source_kind," + + " r.reservation_id::text AS source_key, r.inventory_revision AS source_revision," + + " to_jsonb(r)::text AS source_row_json FROM game_session_canonical_issuer_partition_reservation r" + + " WHERE r.inventory_revision <= ?" + + " UNION ALL SELECT 'ACCOUNT_OBLIGATION' AS source_kind," + + " a.transition_id::text || ':' || a.obligation_ordinal::text AS source_key," + + " a.inventory_revision AS source_revision, to_jsonb(a)::text AS source_row_json" + + " FROM game_session_canonical_binding_account_index_obligation a" + + " WHERE a.inventory_revision <= ?" + + " UNION ALL SELECT 'ISSUER_OBLIGATION' AS source_kind," + + " encode(o.binding_ref, 'hex') || ':' || o.transition_id::text AS source_key," + + " o.inventory_revision AS source_revision, to_jsonb(o)::text AS source_row_json" + + " FROM game_session_canonical_binding_issuer_index_obligation o" + + " WHERE o.inventory_revision <= ?" + + " UNION ALL SELECT 'REGION_OBLIGATION' AS source_kind," + + " g.transition_id::text AS source_key, g.inventory_revision AS source_revision," + + " to_jsonb(g)::text AS source_row_json" + + " FROM game_session_canonical_binding_region_bridge_obligation g" + + " WHERE g.inventory_revision <= ?" + + ") captured_cohort" + + " ORDER BY source_kind COLLATE \"C\", source_key COLLATE \"C\""; + + private static final String FUTURE_REVISION_SQL = + "SELECT EXISTS (SELECT 1 FROM game_session_canonical_gameplay_binding_inventory" + + " WHERE inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_transition" + + " WHERE inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_issuer_partition_reservation" + + " WHERE inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_account_index_obligation" + + " WHERE inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_issuer_index_obligation" + + " WHERE inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_region_bridge_obligation" + + " WHERE inventory_revision > ?) AS has_future_revision"; + + private final DSLContext dsl; + + CanonicalGameplayIssuerLayoutBootstrapRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Captures one pending initial-bootstrap intent. Input objects are trusted local collaborators, + * not caller-supplied production authority. + */ + CanonicalGameplayIssuerLayoutBootstrapIntent beginInitialBootstrapIntent( + UUID requestId, + TrustedLayoutDescriptor descriptor, + TrustedAccountIssuerCheckpoint sourceCheckpoint) { + requireNonNil(requestId, "requestId"); + Objects.requireNonNull(descriptor, "descriptor"); + Objects.requireNonNull(sourceCheckpoint, "sourceCheckpoint"); + requireTrustedInputScopes(descriptor, sourceCheckpoint); + requireValidSourceEvent(descriptor.issuerId(), sourceCheckpoint); + requireNoAmbientTransaction(); + + String descriptorDigest = sha256(descriptor.exactBytes()); + String checkpointDigest = sha256(sourceCheckpoint.checkpointBytes()); + String sourceEventDigest = + sourceCheckpoint.latestEventBytes() == null + ? null + : sha256(sourceCheckpoint.latestEventBytes()); + + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + + // This is the same first lock as binding preparation. It serializes the immutable + // inventory cut with every canonical source row that follows this clock. + BigInteger snapshotRevision = lockInventoryRevision(transaction); + Record existingControl = lockControl(transaction, descriptor.issuerId()); + if (existingControl != null) { + UUID currentOperationId = + Objects.requireNonNull( + existingControl.get("current_operation_id", UUID.class), + "issuer bootstrap control operation id"); + Record existingIntent = lockIntent(transaction, currentOperationId); + if (existingIntent == null) { + throw conflict("Issuer bootstrap control lost its original intent row"); + } + CanonicalGameplayIssuerLayoutBootstrapIntent prior = + loadAndRequireCurrent(transaction, existingControl, existingIntent); + if (!prior.requestId().equals(requestId)) { + throw conflict( + "A different initial issuer-layout bootstrap already owns this issuer"); + } + requireSameTrustedInputs( + prior, + descriptor, + sourceCheckpoint, + descriptorDigest, + checkpointDigest, + sourceEventDigest); + return prior; + } + + Record priorIntent = + transaction.fetchOne( + "SELECT operation_id FROM " + INTENT + " WHERE issuer_id = ?", + descriptor.issuerId()); + if (priorIntent != null) { + throw conflict("Issuer bootstrap intent exists without its positive control row"); + } + + CanonicalGameplayLegacyMigrationDisposition legacy = + readVerifiedLegacyDisposition(transaction, snapshotRevision, true); + requireNoFutureInventoryRows(transaction, snapshotRevision); + List sourceRows = captureCohort(transaction, snapshotRevision); + List cohortRows = + freezeCohort(sourceRows); + String cohortDigest = digestCohort(cohortRows); + + UUID operationId = randomNonNilUuid(); + while (operationId.equals(requestId)) operationId = randomNonNilUuid(); + // The only operation in this migration is the initial intent. The first durable epoch + // is positive; operationFence and coverageFence consume distinct ordered values. + BigInteger operationFence = BigInteger.ONE; + BigInteger coverageFence = BigInteger.TWO; + BigInteger controlEpoch = operationFence; + + insertIntent( + transaction, + operationId, + requestId, + descriptor, + descriptorDigest, + sourceCheckpoint, + checkpointDigest, + sourceEventDigest, + snapshotRevision, + controlEpoch, + operationFence, + coverageFence, + legacy, + cohortRows, + cohortDigest); + insertCohort(transaction, operationId, descriptor.issuerId(), cohortRows); + insertControl( + transaction, + descriptor.issuerId(), + operationId, + controlEpoch, + operationFence, + coverageFence); + + Record savedControl = lockControl(transaction, descriptor.issuerId()); + Record savedIntent = lockIntent(transaction, operationId); + if (savedControl == null || savedIntent == null) { + throw conflict("Persisted initial issuer-bootstrap intent is incomplete"); + } + return loadAndRequireCurrent(transaction, savedControl, savedIntent); + }); + } + + /** Reads the exact persisted pending intent and its frozen cohort by owner-allocated ID. */ + CanonicalGameplayIssuerLayoutBootstrapIntent readCurrentInitialBootstrapIntent(UUID operationId) { + requireNonNil(operationId, "operationId"); + requireNoAmbientTransaction(); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + Record intent = + transaction.fetchOne( + "SELECT * FROM " + INTENT + " WHERE operation_id = ?", operationId); + if (intent == null) throw conflict("Exact initial issuer-bootstrap intent is missing"); + String issuerId = Objects.requireNonNull(intent.get("issuer_id", String.class)); + Record control = readControl(transaction, issuerId); + if (control == null) { + throw conflict("Initial issuer-bootstrap intent lost its positive control row"); + } + return loadAndRequireCurrent(transaction, control, intent); + }); + } + + private static void requireTrustedInputScopes( + TrustedLayoutDescriptor descriptor, TrustedAccountIssuerCheckpoint checkpoint) { + if (!GameSessionAccountDelegationProfile.ISSUER.equals(descriptor.issuerId()) + || !descriptor.issuerId().equals(checkpoint.issuerId()) + || !CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY.equals( + descriptor.mappingIdentity())) { + throw conflict("Trusted issuer descriptor and checkpoint must use the exact Account issuer"); + } + } + + private static void requireValidSourceEvent( + String issuerId, TrustedAccountIssuerCheckpoint checkpoint) { + byte[] eventBytes = checkpoint.latestEventBytes(); + if (eventBytes == null) return; + final String eventJson; + try { + eventJson = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(eventBytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw conflict("Controlled Account issuer source event is not exact UTF-8"); + } + final SourceEvent parsed; + try { + parsed = AccountAuthoritySourceEventV1Codec.verify(eventJson); + } catch (RuntimeException malformed) { + throw conflict("Controlled Account issuer source event is not codec-verified"); + } + if (!(parsed instanceof IssuerEvent event) + || !event.issuerId().equals(issuerId) + || !new BigInteger(event.issuerAuthGeneration()).equals(checkpoint.issuerAuthGeneration()) + || !Arrays.equals(event.canonicalJsonUtf8(), eventBytes)) { + throw conflict("Controlled Account issuer event differs from its exact checkpoint scope"); + } + } + + private static void requireSameTrustedInputs( + CanonicalGameplayIssuerLayoutBootstrapIntent prior, + TrustedLayoutDescriptor descriptor, + TrustedAccountIssuerCheckpoint checkpoint, + String descriptorDigest, + String checkpointDigest, + String sourceEventDigest) { + var storedLayout = prior.layoutDescriptor(); + var storedSource = prior.sourceCheckpoint(); + if (!storedLayout.issuerId().equals(descriptor.issuerId()) + || !storedLayout.layoutVersion().equals(descriptor.layoutVersion()) + || !storedLayout.partitionCount().equals(descriptor.partitionCount()) + || !storedLayout.partitionCapacity().equals(descriptor.partitionCapacity()) + || !storedLayout.mappingIdentity().equals(descriptor.mappingIdentity()) + || !Arrays.equals(storedLayout.exactDescriptorBytes(), descriptor.exactBytes()) + || !storedLayout.descriptorDigest().equals(descriptorDigest) + || !storedSource.issuerId().equals(checkpoint.issuerId()) + || !storedSource.issuerAuthGeneration().equals(checkpoint.issuerAuthGeneration()) + || !Arrays.equals(storedSource.exactCheckpointBytes(), checkpoint.checkpointBytes()) + || !storedSource.checkpointDigest().equals(checkpointDigest) + || !Arrays.equals(storedSource.latestIssuerEventBytes(), checkpoint.latestEventBytes()) + || !Objects.equals(storedSource.latestIssuerEventDigest(), sourceEventDigest)) { + throw conflict("Initial issuer-bootstrap retry changed its original trusted inputs"); + } + } + + private static CanonicalGameplayIssuerLayoutBootstrapIntent loadAndRequireCurrent( + DSLContext transaction, Record control, Record intent) { + String issuerId = Objects.requireNonNull(intent.get("issuer_id", String.class)); + UUID operationId = Objects.requireNonNull(intent.get("operation_id", UUID.class)); + UUID requestId = Objects.requireNonNull(intent.get("request_id", UUID.class)); + BigInteger controlEpoch = readBigInteger(intent, "control_epoch"); + BigInteger operationFence = readBigInteger(intent, "operation_fence"); + BigInteger coverageFence = readBigInteger(intent, "coverage_fence"); + BigInteger snapshotRevision = readBigInteger(intent, "inventory_snapshot_revision"); + + if (!issuerId.equals(control.get("issuer_id", String.class)) + || !"INITIAL_BOOTSTRAP_INTENT".equals(control.get("state", String.class)) + || !operationId.equals(control.get("current_operation_id", UUID.class)) + || !controlEpoch.equals(readBigInteger(control, "control_epoch")) + || !operationFence.equals(readBigInteger(control, "current_operation_fence")) + || !coverageFence.equals(readBigInteger(control, "current_coverage_fence")) + || !operationFence.equals(controlEpoch) + || operationFence.equals(coverageFence) + || !"INITIAL_BOOTSTRAP_INTENT".equals(intent.get("intent_state", String.class))) { + throw conflict("Initial issuer-bootstrap control and immutable intent differ"); + } + + byte[] descriptorBytes = + Objects.requireNonNull(intent.get("layout_descriptor_bytes", byte[].class)); + String descriptorDigest = + Objects.requireNonNull(intent.get("layout_descriptor_digest", String.class)); + if (!sha256(descriptorBytes).equals(descriptorDigest)) { + throw conflict("Stored issuer layout descriptor digest is invalid"); + } + var descriptor = + new CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor( + issuerId, + readBigInteger(intent, "layout_version"), + readBigInteger(intent, "partition_count"), + readBigInteger(intent, "partition_capacity"), + Objects.requireNonNull(intent.get("mapping_identity", String.class)), + descriptorBytes, + descriptorDigest); + + byte[] checkpointBytes = + Objects.requireNonNull(intent.get("source_checkpoint_bytes", byte[].class)); + String checkpointDigest = + Objects.requireNonNull(intent.get("source_checkpoint_digest", String.class)); + byte[] eventBytes = intent.get("source_event_bytes", byte[].class); + String eventDigest = intent.get("source_event_digest", String.class); + if (!sha256(checkpointBytes).equals(checkpointDigest) + || ((eventBytes == null) != (eventDigest == null)) + || (eventBytes != null && !sha256(eventBytes).equals(eventDigest))) { + throw conflict("Stored Account issuer checkpoint digest is invalid"); + } + var sourceCheckpoint = + new CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint( + issuerId, + readBigInteger(intent, "issuer_auth_generation"), + checkpointBytes, + checkpointDigest, + eventBytes, + eventDigest); + if (eventBytes != null) { + requireValidSourceEvent( + issuerId, + new TrustedAccountIssuerCheckpoint( + issuerId, sourceCheckpoint.issuerAuthGeneration(), checkpointBytes, eventBytes)); + } + + CanonicalGameplayLegacyMigrationDisposition legacy = persistedLegacyDisposition(intent); + CanonicalGameplayLegacyMigrationDisposition currentLegacy = + readVerifiedLegacyDisposition(transaction, snapshotRevision, false); + if (!legacy.equals(currentLegacy)) { + throw conflict("Verified legacy disposition changed after initial issuer intent capture"); + } + + List cohortRows = + transaction + .fetch( + "SELECT * FROM " + COHORT + " WHERE operation_id = ? ORDER BY row_ordinal", + operationId) + .map( + row -> { + String sourceJson = + Objects.requireNonNull(row.get("source_row_json", String.class)); + String sourceDigest = + Objects.requireNonNull(row.get("source_row_digest", String.class)); + if (!sha256(sourceJson.getBytes(StandardCharsets.UTF_8)).equals(sourceDigest)) { + throw conflict("Stored issuer cohort source-row digest is invalid"); + } + return new CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow( + Objects.requireNonNull(row.get("row_ordinal", Long.class)), + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.valueOf( + Objects.requireNonNull(row.get("source_kind", String.class))), + Objects.requireNonNull(row.get("source_key", String.class)), + readBigInteger(row, "source_inventory_revision"), + sourceJson, + sourceDigest); + }); + if (cohortRows.stream() + .anyMatch(row -> row.sourceInventoryRevision().compareTo(snapshotRevision) > 0) + || cohortRows.size() != readLong(intent, "cohort_row_count")) { + throw conflict("Stored issuer cohort is incomplete or newer than its snapshot"); + } + for (int index = 0; index < cohortRows.size(); index++) { + if (cohortRows.get(index).rowOrdinal() != index) { + throw conflict("Stored issuer cohort row ordinals are not contiguous from zero"); + } + } + String cohortDigest = digestCohort(cohortRows); + if (!cohortDigest.equals(intent.get("cohort_digest", String.class))) { + throw conflict("Stored issuer cohort digest does not match its immutable row set"); + } + + return new CanonicalGameplayIssuerLayoutBootstrapIntent( + operationId, + requestId, + issuerId, + controlEpoch, + operationFence, + coverageFence, + snapshotRevision, + descriptor, + sourceCheckpoint, + legacy, + CanonicalGameplayIssuerLayoutBootstrapIntent.State.INITIAL_BOOTSTRAP_INTENT, + cohortRows, + cohortDigest); + } + + private static CanonicalGameplayLegacyMigrationDisposition persistedLegacyDisposition( + Record intent) { + return new CanonicalGameplayLegacyMigrationDisposition( + Objects.requireNonNull(intent.get("legacy_cohort_id", UUID.class)), + Objects.requireNonNull(intent.get("legacy_owner_operation_id", UUID.class)), + Objects.requireNonNull(intent.get("legacy_writer_fence", UUID.class)), + readBigInteger(intent, "legacy_source_snapshot_revision"), + readBigInteger(intent, "legacy_canonical_inventory_revision"), + readBigInteger(intent, "legacy_namespace_index_readback_revision"), + Objects.requireNonNull(intent.get("legacy_evidence_digest", String.class))); + } + + private static CanonicalGameplayLegacyMigrationDisposition readVerifiedLegacyDisposition( + DSLContext transaction, BigInteger snapshotRevision, boolean lockForShare) { + Record row = + transaction.fetchOne( + "SELECT * FROM " + + LEGACY_DISPOSITION + + " WHERE singleton_id = 1" + + (lockForShare ? " FOR SHARE" : "")); + if (row == null || !"VERIFIED".equals(row.get("disposition_state", String.class))) { + throw conflict("Initial issuer bootstrap requires the actual VERIFIED legacy disposition"); + } + final CanonicalGameplayLegacyMigrationDisposition disposition; + try { + disposition = + new CanonicalGameplayLegacyMigrationDisposition( + row.get("cohort_id", UUID.class), + row.get("owner_operation_id", UUID.class), + row.get("legacy_writer_fence", UUID.class), + readBigInteger(row, "source_snapshot_revision"), + readBigInteger(row, "canonical_inventory_revision"), + readBigInteger(row, "namespace_index_readback_revision"), + row.get("evidence_digest", String.class)); + } catch (RuntimeException malformed) { + throw conflict("Actual VERIFIED legacy disposition is incomplete or malformed"); + } + if (disposition.canonicalInventoryRevision().compareTo(snapshotRevision) > 0) { + throw conflict("VERIFIED legacy disposition is newer than the locked issuer inventory"); + } + return disposition; + } + + private static List captureCohort( + DSLContext transaction, BigInteger snapshotRevision) { + requireNoFutureInventoryRows(transaction, snapshotRevision); + return transaction + .fetch( + COHORT_SQL, + ISSUER, + decimal(snapshotRevision), + decimal(snapshotRevision), + ISSUER, + decimal(snapshotRevision), + decimal(snapshotRevision), + decimal(snapshotRevision), + decimal(snapshotRevision)) + .map( + row -> + new CohortSourceRow( + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.valueOf( + Objects.requireNonNull(row.get("source_kind", String.class))), + Objects.requireNonNull(row.get("source_key", String.class)), + readBigInteger(row, "source_revision"), + Objects.requireNonNull(row.get("source_row_json", String.class)))); + } + + private static List freezeCohort( + List sourceRows) { + List sorted = + sourceRows.stream() + .sorted( + Comparator.comparing((CohortSourceRow row) -> row.kind().name()) + .thenComparing(CohortSourceRow::sourceKey)) + .toList(); + List result = new ArrayList<>(); + for (int index = 0; index < sorted.size(); index++) { + CohortSourceRow row = sorted.get(index); + result.add( + new CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow( + index, + row.kind(), + row.sourceKey(), + row.sourceInventoryRevision(), + row.sourceRowJson(), + sha256(row.sourceRowJson().getBytes(StandardCharsets.UTF_8)))); + } + return List.copyOf(result); + } + + private static String digestCohort( + List rows) { + MessageDigest digest = sha256Digest(); + rows.stream() + .sorted( + Comparator.comparingLong( + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::rowOrdinal)) + .forEach( + row -> { + updateFramed( + digest, Long.toString(row.rowOrdinal()).getBytes(StandardCharsets.US_ASCII)); + updateFramed(digest, row.kind().name().getBytes(StandardCharsets.UTF_8)); + updateFramed(digest, row.sourceKey().getBytes(StandardCharsets.UTF_8)); + updateFramed( + digest, + row.sourceInventoryRevision().toString().getBytes(StandardCharsets.US_ASCII)); + updateFramed(digest, row.sourceRowDigest().getBytes(StandardCharsets.US_ASCII)); + }); + return "sha256:" + HexFormat.of().formatHex(digest.digest()); + } + + private static void updateFramed(MessageDigest digest, byte[] value) { + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(value.length).array()); + digest.update(value); + } + + private static void insertIntent( + DSLContext transaction, + UUID operationId, + UUID requestId, + TrustedLayoutDescriptor descriptor, + String descriptorDigest, + TrustedAccountIssuerCheckpoint sourceCheckpoint, + String checkpointDigest, + String sourceEventDigest, + BigInteger snapshotRevision, + BigInteger controlEpoch, + BigInteger operationFence, + BigInteger coverageFence, + CanonicalGameplayLegacyMigrationDisposition legacy, + List cohortRows, + String cohortDigest) { + transaction.execute( + "INSERT INTO " + + INTENT + + " (operation_id, request_id, issuer_id, control_epoch, operation_fence," + + " coverage_fence, inventory_snapshot_revision, layout_version, partition_count," + + " partition_capacity, mapping_identity, layout_descriptor_bytes," + + " layout_descriptor_digest, issuer_auth_generation, source_checkpoint_bytes," + + " source_checkpoint_digest, source_event_bytes, source_event_digest," + + " legacy_cohort_id, legacy_owner_operation_id, legacy_writer_fence," + + " legacy_source_snapshot_revision, legacy_canonical_inventory_revision," + + " legacy_namespace_index_readback_revision, legacy_evidence_digest," + + " cohort_row_count, cohort_digest, intent_state)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ", + operationId, + requestId, + descriptor.issuerId(), + decimal(controlEpoch), + decimal(operationFence), + decimal(coverageFence), + decimal(snapshotRevision), + decimal(descriptor.layoutVersion()), + decimal(descriptor.partitionCount()), + decimal(descriptor.partitionCapacity()), + descriptor.mappingIdentity(), + descriptor.exactBytes(), + descriptorDigest, + decimal(sourceCheckpoint.issuerAuthGeneration()), + sourceCheckpoint.checkpointBytes(), + checkpointDigest, + sourceCheckpoint.latestEventBytes(), + sourceEventDigest, + legacy.cohortId(), + legacy.ownerOperationId(), + legacy.legacyWriterFence(), + decimal(legacy.sourceSnapshotRevision()), + decimal(legacy.canonicalInventoryRevision()), + decimal(legacy.namespaceIndexReadbackRevision()), + legacy.evidenceDigest(), + (long) cohortRows.size(), + cohortDigest, + CanonicalGameplayIssuerLayoutBootstrapIntent.State.INITIAL_BOOTSTRAP_INTENT.name()); + } + + private static void insertCohort( + DSLContext transaction, + UUID operationId, + String issuerId, + List rows) { + for (CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow row : rows) { + transaction.execute( + "INSERT INTO " + + COHORT + + " (operation_id, issuer_id, row_ordinal, source_kind, source_key," + + " source_inventory_revision, source_row_json, source_row_digest)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + operationId, + issuerId, + row.rowOrdinal(), + row.kind().name(), + row.sourceKey(), + decimal(row.sourceInventoryRevision()), + row.sourceRowJson(), + row.sourceRowDigest()); + } + } + + private static void insertControl( + DSLContext transaction, + String issuerId, + UUID operationId, + BigInteger controlEpoch, + BigInteger operationFence, + BigInteger coverageFence) { + transaction.execute( + "INSERT INTO " + + CONTROL + + " (issuer_id, state, control_epoch, last_issued_fence, current_operation_id," + + " current_operation_fence, current_coverage_fence)" + + " VALUES (?, 'INITIAL_BOOTSTRAP_INTENT', ?, ?, ?, ?, ?)", + issuerId, + decimal(controlEpoch), + decimal(coverageFence), + operationId, + decimal(operationFence), + decimal(coverageFence)); + } + + private static BigInteger lockInventoryRevision(DSLContext transaction) { + return readBigInteger( + Objects.requireNonNull( + transaction.fetchOne( + "SELECT inventory_revision FROM " + + INVENTORY_CLOCK + + " WHERE singleton_id = 1 FOR UPDATE"), + "canonical inventory clock row must exist"), + "inventory_revision"); + } + + private static Record lockControl(DSLContext transaction, String issuerId) { + return transaction.fetchOne( + "SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", issuerId); + } + + private static Record readControl(DSLContext transaction, String issuerId) { + return transaction.fetchOne("SELECT * FROM " + CONTROL + " WHERE issuer_id = ?", issuerId); + } + + private static Record lockIntent(DSLContext transaction, UUID operationId) { + return transaction.fetchOne( + "SELECT * FROM " + INTENT + " WHERE operation_id = ? FOR UPDATE", operationId); + } + + private static void requireNoFutureInventoryRows( + DSLContext transaction, BigInteger snapshotRevision) { + Record row = + Objects.requireNonNull( + transaction.fetchOne( + FUTURE_REVISION_SQL, + decimal(snapshotRevision), + decimal(snapshotRevision), + decimal(snapshotRevision), + decimal(snapshotRevision), + decimal(snapshotRevision), + decimal(snapshotRevision)), + "future inventory revision query must return one row"); + if (Boolean.TRUE.equals(row.get("has_future_revision", Boolean.class))) { + throw conflict("Issuer bootstrap cannot omit durable rows newer than the inventory clock"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw conflict("Issuer bootstrap owner cannot join an ambient transaction"); + } + } + + private static String sha256(byte[] bytes) { + return "sha256:" + HexFormat.of().formatHex(sha256Digest().digest(bytes)); + } + + private static MessageDigest sha256Digest() { + try { + return MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("JVM does not provide SHA-256", impossible); + } + } + + private static BigInteger readBigInteger(Record row, String field) { + BigDecimal value = Objects.requireNonNull(row.get(field, BigDecimal.class), field); + return value.toBigIntegerExact(); + } + + private static long readLong(Record row, String field) { + return Objects.requireNonNull(row.get(field, Long.class), field); + } + + private static BigDecimal decimal(BigInteger value) { + return new BigDecimal(value); + } + + private static UUID requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException(name + " must not be nil"); + return value; + } + + private static UUID randomNonNilUuid() { + UUID value; + do { + value = UUID.randomUUID(); + } while (value.equals(new UUID(0L, 0L))); + return value; + } + + private static IllegalStateException conflict(String message) { + return new IllegalStateException(message); + } + + private record CohortSourceRow( + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind kind, + String sourceKey, + BigInteger sourceInventoryRevision, + String sourceRowJson) {} + + /** Shape-only trusted descriptor input; this code does not authenticate its authority. */ + static final class TrustedLayoutDescriptor { + private final String issuerId; + private final BigInteger layoutVersion; + private final BigInteger partitionCount; + private final BigInteger partitionCapacity; + private final String mappingIdentity; + private final byte[] exactBytes; + + TrustedLayoutDescriptor( + String issuerId, + BigInteger layoutVersion, + BigInteger partitionCount, + BigInteger partitionCapacity, + String mappingIdentity, + byte[] exactBytes) { + this.issuerId = Objects.requireNonNull(issuerId, "issuerId"); + this.layoutVersion = Objects.requireNonNull(layoutVersion, "layoutVersion"); + this.partitionCount = Objects.requireNonNull(partitionCount, "partitionCount"); + this.partitionCapacity = Objects.requireNonNull(partitionCapacity, "partitionCapacity"); + this.mappingIdentity = Objects.requireNonNull(mappingIdentity, "mappingIdentity"); + this.exactBytes = cloneNonEmpty(exactBytes, "exactBytes"); + if (layoutVersion.signum() <= 0 + || partitionCount.signum() <= 0 + || partitionCapacity.signum() <= 0 + || !CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY.equals( + mappingIdentity)) { + throw new IllegalArgumentException("Trusted layout descriptor is malformed"); + } + } + + String issuerId() { + return issuerId; + } + + BigInteger layoutVersion() { + return layoutVersion; + } + + BigInteger partitionCount() { + return partitionCount; + } + + BigInteger partitionCapacity() { + return partitionCapacity; + } + + String mappingIdentity() { + return mappingIdentity; + } + + byte[] exactBytes() { + return exactBytes.clone(); + } + } + + /** + * Shape-only trusted Account-current-source input. Checkpoint bytes are retained exactly; when a + * latest event is supplied, the existing Account event codec verifies it before persistence. + */ + static final class TrustedAccountIssuerCheckpoint { + private final String issuerId; + private final BigInteger issuerAuthGeneration; + private final byte[] checkpointBytes; + private final byte[] latestEventBytes; + + TrustedAccountIssuerCheckpoint( + String issuerId, + BigInteger issuerAuthGeneration, + byte[] checkpointBytes, + byte[] latestEventBytes) { + this.issuerId = Objects.requireNonNull(issuerId, "issuerId"); + this.issuerAuthGeneration = + Objects.requireNonNull(issuerAuthGeneration, "issuerAuthGeneration"); + this.checkpointBytes = cloneNonEmpty(checkpointBytes, "checkpointBytes"); + this.latestEventBytes = + latestEventBytes == null ? null : cloneNonEmpty(latestEventBytes, "latestEventBytes"); + if (issuerAuthGeneration.signum() <= 0) { + throw new IllegalArgumentException("issuerAuthGeneration must be positive"); + } + } + + String issuerId() { + return issuerId; + } + + BigInteger issuerAuthGeneration() { + return issuerAuthGeneration; + } + + byte[] checkpointBytes() { + return checkpointBytes.clone(); + } + + byte[] latestEventBytes() { + return latestEventBytes == null ? null : latestEventBytes.clone(); + } + } + + private static byte[] cloneNonEmpty(byte[] value, String name) { + Objects.requireNonNull(value, name); + if (value.length == 0) throw new IllegalArgumentException(name + " must not be empty"); + return value.clone(); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerMemberV2Codec.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerMemberV2Codec.java new file mode 100644 index 0000000000..ab6de9d6dd --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerMemberV2Codec.java @@ -0,0 +1,632 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadConstraints; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +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.Arrays; +import java.util.Base64; +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 java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; + +/** Closed, bounded canonical JSON codec for the shape-only schema-2 issuer member value. */ +final class CanonicalGameplayIssuerMemberV2Codec { + static final int MAX_VALUE_BYTES = 64 * 1024; + static final int MAX_COUNTER_DIGITS = 256; + + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); + private static final Pattern NON_NEGATIVE_DECIMAL = Pattern.compile("(?:0|[1-9][0-9]*)"); + private static final JsonFactory JSON_FACTORY = + JsonFactory.builder() + .streamReadConstraints( + StreamReadConstraints.builder() + .maxNestingDepth(8) + .maxStringLength(MAX_VALUE_BYTES) + .maxNumberLength(8) + .build()) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + private static final ObjectMapper JSON = + new ObjectMapper(JSON_FACTORY).enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + + private static final Set ROOT_FIELDS = + Set.of( + "schemaVersion", + "issuerId", + "accountId", + "tenantId", + "gameInstanceId", + "sessionId", + "bindingGeneration", + "issuerAuthGeneration", + "issuerIndexLayoutVersion", + "playableStateNamespaceId", + "characterId", + "playableStateScope", + "runtimeGameInstanceId", + "regionId", + "regionEpoch", + "issuerControlEpoch", + "layout", + "reservation", + "anchor", + "memberOperation", + "incarnation"); + private static final Set LAYOUT_FIELDS = + Set.of( + "partitionCount", + "partitionCapacity", + "mappingIdentity", + "descriptorBytes", + "descriptorDigest"); + private static final Set RESERVATION_FIELDS = + Set.of( + "reservationId", + "bindingRef", + "transitionId", + "partitionId", + "lifecycle", + "reservationFence", + "inventoryRevision"); + private static final Set ANCHOR_FIELDS = + Set.of( + "issuerCoverageOperationId", + "operationFence", + "coverageFence", + "issuerInventorySnapshotRevision", + "sourceCheckpointBytes", + "sourceCheckpointDigest", + "sourceEventBytes", + "sourceEventDigest"); + private static final Set MEMBER_OPERATION_FIELDS = + Set.of("operationId", "operationFence", "coverageGeneration"); + private static final Set INCARNATION_FIELDS = + Set.of( + "attestorBinding", + "acceptedAttestationDigest", + "targetDeploymentEvidence", + "coordOpsRoAclDigest", + "coordRedisConfigObservedDigest"); + private static final Set TARGET_DEPLOYMENT_EVIDENCE_FIELDS = + Set.of( + "deploymentIdentity", + "deploymentGeneration", + "canonicalNodeSet", + "redisBuildIdentity", + "luaScriptRegistryVersion", + "luaScriptRegistryDigest", + "startupState", + "bootGeneration", + "startupGeneration", + "storageGeneration", + "aofGeneration"); + + private CanonicalGameplayIssuerMemberV2Codec() {} + + static byte[] encode(CanonicalGameplayIssuerMemberV2Value value) { + Objects.requireNonNull(value, "value"); + try { + requireCounterLimit(value.bindingGeneration(), "bindingGeneration", false); + CanonicalGameplayBindingIdentity owner = value.owner(); + requireCounterLimit(owner.issuerAuthGeneration(), "issuerAuthGeneration", false); + requireCounterLimit(owner.issuerIndexLayoutVersion(), "issuerIndexLayoutVersion", false); + requireCounterLimit(owner.regionEpoch(), "regionEpoch", false); + requireCounterLimit(value.issuerControlEpoch(), "issuerControlEpoch", false); + requireCounterLimit(value.layoutDescriptor().partitionCount(), "partitionCount", false); + requireCounterLimit(value.layoutDescriptor().partitionCapacity(), "partitionCapacity", false); + requireCounterLimit(value.reservation().partitionId(), "partitionId", true); + requireCounterLimit(value.reservation().inventoryRevision(), "inventoryRevision", false); + requireCounterLimit(value.anchor().operationFence(), "anchor.operationFence", false); + requireCounterLimit(value.anchor().coverageFence(), "anchor.coverageFence", false); + requireCounterLimit( + value.anchor().issuerInventorySnapshotRevision(), + "issuerInventorySnapshotRevision", + false); + requireCounterLimit( + value.memberOperation().operationFence(), "memberOperation.operationFence", false); + requireCounterLimit( + value.memberOperation().coverageGeneration(), + "memberOperation.coverageGeneration", + false); + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(toJson(value))); + if (bytes.length > MAX_VALUE_BYTES) { + throw invalid("issuer member value exceeds the local 64 KiB resource limit"); + } + return bytes; + } catch (IOException failure) { + throw new IllegalArgumentException("Could not encode canonical issuer member value", failure); + } + } + + static CanonicalGameplayIssuerMemberV2Value decode(byte[] encoded) { + Objects.requireNonNull(encoded, "encoded"); + if (encoded.length == 0 || encoded.length > MAX_VALUE_BYTES) { + throw invalid("issuer member value is empty or exceeds the local 64 KiB resource limit"); + } + String json = decodeUtf8(encoded); + try { + JsonNode parsed = JSON.readTree(json); + ObjectNode root = requireObject(parsed, "issuer member value"); + JsonNode schemaVersion = root.get("schemaVersion"); + if (schemaVersion != null + && schemaVersion.isIntegralNumber() + && schemaVersion.canConvertToInt() + && schemaVersion.intValue() == 1) { + throw invalid("schema-1 issuer member is unqualified legacy evidence"); + } + requireFields(root, ROOT_FIELDS, "issuer member value"); + if (!root.path("schemaVersion").isIntegralNumber() + || !root.path("schemaVersion").canConvertToInt() + || root.path("schemaVersion").intValue() + != CanonicalGameplayIssuerMemberV2Value.SCHEMA_VERSION) { + throw invalid("schemaVersion must be the JSON integer 2"); + } + + String issuerId = text(root, "issuerId"); + UUID accountId = uuid(root, "accountId"); + UUID tenantId = uuid(root, "tenantId"); + UUID gameInstanceId = uuid(root, "gameInstanceId"); + String sessionId = text(root, "sessionId"); + BigInteger bindingGeneration = positive(root, "bindingGeneration"); + BigInteger issuerAuthGeneration = positive(root, "issuerAuthGeneration"); + BigInteger issuerIndexLayoutVersion = positive(root, "issuerIndexLayoutVersion"); + UUID playableStateNamespaceId = uuid(root, "playableStateNamespaceId"); + UUID characterId = uuid(root, "characterId"); + String playableStateScope = text(root, "playableStateScope"); + long runtimeGameInstanceId = positiveLong(root, "runtimeGameInstanceId"); + UUID regionId = uuid(root, "regionId"); + BigInteger regionEpoch = positive(root, "regionEpoch"); + BigInteger issuerControlEpoch = positive(root, "issuerControlEpoch"); + + ObjectNode layoutObject = nestedObject(root, "layout", LAYOUT_FIELDS); + BigInteger partitionCount = positive(layoutObject, "partitionCount"); + BigInteger partitionCapacity = positive(layoutObject, "partitionCapacity"); + String mappingIdentity = text(layoutObject, "mappingIdentity"); + byte[] descriptorBytes = base64(layoutObject, "descriptorBytes"); + String descriptorDigest = text(layoutObject, "descriptorDigest"); + CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor layoutDescriptor = + new CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor( + issuerId, + issuerIndexLayoutVersion, + partitionCount, + partitionCapacity, + mappingIdentity, + descriptorBytes, + descriptorDigest); + + ObjectNode reservationObject = nestedObject(root, "reservation", RESERVATION_FIELDS); + UUID reservationId = uuid(reservationObject, "reservationId"); + String bindingRef = text(reservationObject, "bindingRef"); + UUID transitionId = uuid(reservationObject, "transitionId"); + BigInteger partitionId = nonNegative(reservationObject, "partitionId"); + CanonicalIssuerPartitionReservation.Lifecycle lifecycle = + enumValue( + CanonicalIssuerPartitionReservation.Lifecycle.class, + text(reservationObject, "lifecycle"), + "reservation lifecycle"); + UUID reservationFence = uuid(reservationObject, "reservationFence"); + BigInteger inventoryRevision = positive(reservationObject, "inventoryRevision"); + + ObjectNode anchorObject = nestedObject(root, "anchor", ANCHOR_FIELDS); + UUID issuerCoverageOperationId = uuid(anchorObject, "issuerCoverageOperationId"); + BigInteger anchorOperationFence = positive(anchorObject, "operationFence"); + BigInteger coverageFence = positive(anchorObject, "coverageFence"); + BigInteger issuerInventorySnapshotRevision = + positive(anchorObject, "issuerInventorySnapshotRevision"); + byte[] sourceCheckpointBytes = base64(anchorObject, "sourceCheckpointBytes"); + String sourceCheckpointDigest = text(anchorObject, "sourceCheckpointDigest"); + byte[] sourceEventBytes = nullableBase64(anchorObject, "sourceEventBytes"); + String sourceEventDigest = nullableText(anchorObject, "sourceEventDigest"); + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint sourceCheckpoint = + new CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint( + issuerId, + issuerAuthGeneration, + sourceCheckpointBytes, + sourceCheckpointDigest, + sourceEventBytes, + sourceEventDigest); + + ObjectNode operationObject = nestedObject(root, "memberOperation", MEMBER_OPERATION_FIELDS); + CanonicalGameplayIssuerMemberV2Value.LocalMemberOperation memberOperation = + new CanonicalGameplayIssuerMemberV2Value.LocalMemberOperation( + uuid(operationObject, "operationId"), + positive(operationObject, "operationFence"), + positive(operationObject, "coverageGeneration")); + + ObjectNode incarnationObject = nestedObject(root, "incarnation", INCARNATION_FIELDS); + ObjectNode deploymentObject = + nestedObject( + incarnationObject, "targetDeploymentEvidence", TARGET_DEPLOYMENT_EVIDENCE_FIELDS); + CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + targetDeploymentEvidence = + new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + text(deploymentObject, "deploymentIdentity"), + text(deploymentObject, "deploymentGeneration"), + stringArray(deploymentObject, "canonicalNodeSet"), + text(deploymentObject, "redisBuildIdentity"), + text(deploymentObject, "luaScriptRegistryVersion"), + text(deploymentObject, "luaScriptRegistryDigest"), + text(deploymentObject, "startupState"), + text(deploymentObject, "bootGeneration"), + text(deploymentObject, "startupGeneration"), + text(deploymentObject, "storageGeneration"), + text(deploymentObject, "aofGeneration")); + CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation = + new CanonicalGameplayIssuerMemberV2Value.Incarnation( + text(incarnationObject, "attestorBinding"), + text(incarnationObject, "acceptedAttestationDigest"), + targetDeploymentEvidence, + text(incarnationObject, "coordOpsRoAclDigest"), + text(incarnationObject, "coordRedisConfigObservedDigest")); + + CanonicalGameplayBindingIdentity owner = + new CanonicalGameplayBindingIdentity( + accountId, + tenantId, + playableStateNamespaceId, + characterId, + playableStateScope, + gameInstanceId, + runtimeGameInstanceId, + sessionId, + regionId, + regionEpoch, + issuerId, + issuerAuthGeneration, + issuerIndexLayoutVersion, + partitionCount, + partitionCapacity); + String expectedBindingRef = new String(owner.bindingRef().bytes(), StandardCharsets.UTF_8); + if (!expectedBindingRef.equals(bindingRef)) { + throw invalid("reservation bindingRef must match the exact canonical binding identity"); + } + CanonicalIssuerPartitionReservation reservation = + new CanonicalIssuerPartitionReservation( + reservationId, + owner, + bindingGeneration, + transitionId, + partitionId, + lifecycle, + reservationFence, + issuerCoverageOperationId, + anchorOperationFence, + coverageFence, + issuerInventorySnapshotRevision, + inventoryRevision); + CanonicalGameplayIssuerMemberV2Value value = + new CanonicalGameplayIssuerMemberV2Value( + owner, + bindingGeneration, + reservation, + new CanonicalGameplayIssuerMemberV2Value.Anchor( + issuerCoverageOperationId, + anchorOperationFence, + coverageFence, + issuerInventorySnapshotRevision), + memberOperation, + issuerControlEpoch, + layoutDescriptor, + sourceCheckpoint, + incarnation); + + if (!Arrays.equals(encoded, encode(value))) { + throw invalid("issuer member JSON must exactly match its canonical emitted bytes"); + } + return value; + } catch (IOException | RuntimeException failure) { + if (failure instanceof IllegalArgumentException invalid) { + throw invalid; + } + throw new IllegalArgumentException("Invalid canonical issuer member value", failure); + } + } + + private static ObjectNode toJson(CanonicalGameplayIssuerMemberV2Value value) { + CanonicalGameplayBindingIdentity owner = value.owner(); + CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor layout = value.layoutDescriptor(); + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint source = + value.sourceCheckpoint(); + CanonicalIssuerPartitionReservation reservation = value.reservation(); + CanonicalGameplayIssuerMemberV2Value.Anchor anchor = value.anchor(); + CanonicalGameplayIssuerMemberV2Value.LocalMemberOperation operation = value.memberOperation(); + CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation = value.incarnation(); + + ObjectNode root = JSON.createObjectNode(); + root.put("schemaVersion", CanonicalGameplayIssuerMemberV2Value.SCHEMA_VERSION); + root.put("issuerId", owner.issuerId()); + root.put("accountId", owner.accountId().toString()); + root.put("tenantId", owner.tenantId().toString()); + root.put("gameInstanceId", owner.gameInstanceId().toString()); + root.put("sessionId", owner.sessionId()); + root.put("bindingGeneration", value.bindingGeneration().toString()); + root.put("issuerAuthGeneration", owner.issuerAuthGeneration().toString()); + root.put("issuerIndexLayoutVersion", owner.issuerIndexLayoutVersion().toString()); + root.put("playableStateNamespaceId", owner.playableStateNamespaceId().toString()); + root.put("characterId", owner.characterId().toString()); + root.put("playableStateScope", owner.playableStateScope()); + root.put("runtimeGameInstanceId", Long.toString(owner.runtimeGameInstanceId())); + root.put("regionId", owner.regionId().toString()); + root.put("regionEpoch", owner.regionEpoch().toString()); + root.put("issuerControlEpoch", value.issuerControlEpoch().toString()); + + ObjectNode layoutObject = root.putObject("layout"); + layoutObject.put("partitionCount", layout.partitionCount().toString()); + layoutObject.put("partitionCapacity", layout.partitionCapacity().toString()); + layoutObject.put("mappingIdentity", layout.mappingIdentity()); + layoutObject.put( + "descriptorBytes", Base64.getEncoder().encodeToString(layout.exactDescriptorBytes())); + layoutObject.put("descriptorDigest", layout.descriptorDigest()); + + ObjectNode reservationObject = root.putObject("reservation"); + reservationObject.put("reservationId", reservation.reservationId().toString()); + reservationObject.put( + "bindingRef", new String(owner.bindingRef().bytes(), StandardCharsets.UTF_8)); + reservationObject.put("transitionId", reservation.transitionId().toString()); + reservationObject.put("partitionId", reservation.partitionId().toString()); + reservationObject.put("lifecycle", reservation.lifecycle().name()); + reservationObject.put("reservationFence", reservation.reservationFence().toString()); + reservationObject.put("inventoryRevision", reservation.inventoryRevision().toString()); + + ObjectNode anchorObject = root.putObject("anchor"); + anchorObject.put("issuerCoverageOperationId", anchor.issuerCoverageOperationId().toString()); + anchorObject.put("operationFence", anchor.operationFence().toString()); + anchorObject.put("coverageFence", anchor.coverageFence().toString()); + anchorObject.put( + "issuerInventorySnapshotRevision", anchor.issuerInventorySnapshotRevision().toString()); + anchorObject.put( + "sourceCheckpointBytes", Base64.getEncoder().encodeToString(source.exactCheckpointBytes())); + anchorObject.put("sourceCheckpointDigest", source.checkpointDigest()); + putNullableBase64(anchorObject, "sourceEventBytes", source.latestIssuerEventBytes()); + putNullableText(anchorObject, "sourceEventDigest", source.latestIssuerEventDigest()); + + ObjectNode operationObject = root.putObject("memberOperation"); + operationObject.put("operationId", operation.operationId().toString()); + operationObject.put("operationFence", operation.operationFence().toString()); + operationObject.put("coverageGeneration", operation.coverageGeneration().toString()); + + ObjectNode incarnationObject = root.putObject("incarnation"); + incarnationObject.put("attestorBinding", incarnation.attestorBinding()); + incarnationObject.put("acceptedAttestationDigest", incarnation.acceptedAttestationDigest()); + CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence deployment = + incarnation.targetDeploymentEvidence(); + ObjectNode deploymentObject = incarnationObject.putObject("targetDeploymentEvidence"); + deploymentObject.put("deploymentIdentity", deployment.deploymentIdentity()); + deploymentObject.put("deploymentGeneration", deployment.deploymentGeneration()); + ArrayNode nodeSet = deploymentObject.putArray("canonicalNodeSet"); + deployment.canonicalNodeSet().forEach(nodeSet::add); + deploymentObject.put("redisBuildIdentity", deployment.redisBuildIdentity()); + deploymentObject.put("luaScriptRegistryVersion", deployment.luaScriptRegistryVersion()); + deploymentObject.put("luaScriptRegistryDigest", deployment.luaScriptRegistryDigest()); + deploymentObject.put("startupState", deployment.startupState()); + deploymentObject.put("bootGeneration", deployment.bootGeneration()); + deploymentObject.put("startupGeneration", deployment.startupGeneration()); + deploymentObject.put("storageGeneration", deployment.storageGeneration()); + deploymentObject.put("aofGeneration", deployment.aofGeneration()); + incarnationObject.put("coordOpsRoAclDigest", incarnation.coordOpsRoAclDigest()); + incarnationObject.put( + "coordRedisConfigObservedDigest", incarnation.coordRedisConfigObservedDigest()); + return root; + } + + private static ObjectNode nestedObject(ObjectNode parent, String name, Set fields) { + ObjectNode child = requireObject(parent.get(name), name); + requireFields(child, fields, name); + return child; + } + + private static ObjectNode requireObject(JsonNode node, String name) { + if (!(node instanceof ObjectNode object)) { + throw invalid(name + " must be an object"); + } + return object; + } + + private static void requireFields(ObjectNode object, Set required, String name) { + Set actual = new HashSet<>(); + object.fieldNames().forEachRemaining(actual::add); + if (!actual.equals(required)) { + throw invalid(name + " must contain exactly its required fields"); + } + } + + private static String text(ObjectNode object, String name) { + JsonNode node = object.get(name); + if (node == null || !node.isTextual()) { + throw invalid(name + " must be a JSON string"); + } + return node.textValue(); + } + + private static String nullableText(ObjectNode object, String name) { + JsonNode node = object.get(name); + if (node == null) { + throw invalid(name + " is required"); + } + if (node.isNull()) { + return null; + } + if (!node.isTextual()) { + throw invalid(name + " must be a JSON string or explicit null"); + } + return node.textValue(); + } + + private static UUID uuid(ObjectNode object, String name) { + String value = text(object, name); + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value)) { + throw invalid(name + " must use canonical lowercase UUID text"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + if (malformed instanceof CodecException) { + throw malformed; + } + throw new IllegalArgumentException(name + " must use canonical UUID text", malformed); + } + } + + private static BigInteger positive(ObjectNode object, String name) { + return decimal(text(object, name), name, true); + } + + private static BigInteger nonNegative(ObjectNode object, String name) { + return decimal(text(object, name), name, false); + } + + private static BigInteger decimal(String value, String name, boolean positive) { + Pattern grammar = positive ? POSITIVE_DECIMAL : NON_NEGATIVE_DECIMAL; + if (value.length() > MAX_COUNTER_DIGITS || !grammar.matcher(value).matches()) { + throw invalid(name + " must be a canonical unsigned decimal string within the local limit"); + } + return new BigInteger(value); + } + + private static void requireCounterLimit(BigInteger value, String name, boolean allowZero) { + int digitCount = value.toString().length(); + if (digitCount > MAX_COUNTER_DIGITS) { + throw invalid(name + " exceeds the local 256-digit resource limit"); + } + if (value.signum() < 0 || (!allowZero && value.signum() == 0)) { + throw invalid(name + " is outside its canonical unsigned decimal range"); + } + } + + private static long positiveLong(ObjectNode object, String name) { + BigInteger value = positive(object, name); + try { + return value.longValueExact(); + } catch (ArithmeticException tooLarge) { + throw invalid(name + " exceeds its owner model's positive long range"); + } + } + + private static byte[] base64(ObjectNode object, String name) { + String text = text(object, name); + return decodeCanonicalBase64(text, name); + } + + private static byte[] nullableBase64(ObjectNode object, String name) { + String text = nullableText(object, name); + return text == null ? null : decodeCanonicalBase64(text, name); + } + + private static byte[] decodeCanonicalBase64(String value, String name) { + try { + byte[] decoded = Base64.getDecoder().decode(value); + if (!Base64.getEncoder().encodeToString(decoded).equals(value)) { + throw invalid(name + " must use canonical padded Base64"); + } + return decoded; + } catch (IllegalArgumentException malformed) { + if (malformed instanceof CodecException) { + throw malformed; + } + throw new IllegalArgumentException(name + " must use canonical padded Base64", malformed); + } + } + + private static List stringArray(ObjectNode object, String name) { + JsonNode node = object.get(name); + if (!(node instanceof ArrayNode array)) { + throw invalid(name + " must be an array of strings"); + } + List values = new ArrayList<>(array.size()); + for (JsonNode item : array) { + if (!item.isTextual()) { + throw invalid(name + " must contain only JSON strings"); + } + values.add(item.textValue()); + } + return List.copyOf(values); + } + + private static > E enumValue(Class type, String value, String name) { + try { + E parsed = Enum.valueOf(type, value); + if (!parsed.name().equals(value)) { + throw invalid(name + " must use its exact canonical name"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + if (malformed instanceof CodecException) { + throw malformed; + } + throw new IllegalArgumentException(name + " is unsupported", malformed); + } + } + + private static void putNullableBase64(ObjectNode object, String name, byte[] value) { + if (value == null) { + object.putNull(name); + } else { + object.put(name, Base64.getEncoder().encodeToString(value)); + } + } + + private static void putNullableText(ObjectNode object, String name, String value) { + if (value == null) { + object.putNull(name); + } else { + object.put(name, value); + } + } + + private static String decodeUtf8(byte[] encoded) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(encoded)) + .toString(); + } catch (CharacterCodingException malformed) { + throw new IllegalArgumentException("Issuer member JSON must be valid UTF-8", malformed); + } + } + + static String sha256(byte[] bytes) { + Objects.requireNonNull(bytes, "bytes"); + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("JVM does not provide SHA-256", impossible); + } + } + + private static IllegalArgumentException invalid(String message) { + return new CodecException(message); + } + + private static final class CodecException extends IllegalArgumentException { + private static final long serialVersionUID = 1L; + + private CodecException(String message) { + super(message); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerMemberV2Value.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerMemberV2Value.java new file mode 100644 index 0000000000..32f9b0d1cb --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerMemberV2Value.java @@ -0,0 +1,279 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; + +/** + * Immutable shape-only carrier for the complete schema-2 issuer partition member value. + * + *

Construction and decoding validate retained evidence and tuple consistency. They do not + * establish trusted ownership, currentness, issuer coverage, or admission authority. + */ +final class CanonicalGameplayIssuerMemberV2Value { + static final int SCHEMA_VERSION = 2; + + private final CanonicalGameplayBindingIdentity owner; + private final BigInteger bindingGeneration; + private final CanonicalIssuerPartitionReservation reservation; + private final Anchor anchor; + private final LocalMemberOperation memberOperation; + private final BigInteger issuerControlEpoch; + private final CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor layoutDescriptor; + private final CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint + sourceCheckpoint; + private final Incarnation incarnation; + + CanonicalGameplayIssuerMemberV2Value( + CanonicalGameplayBindingIdentity owner, + BigInteger bindingGeneration, + CanonicalIssuerPartitionReservation reservation, + Anchor anchor, + LocalMemberOperation memberOperation, + BigInteger issuerControlEpoch, + CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor layoutDescriptor, + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint sourceCheckpoint, + Incarnation incarnation) { + this.owner = Objects.requireNonNull(owner, "owner"); + this.bindingGeneration = requirePositive(bindingGeneration, "bindingGeneration"); + this.reservation = Objects.requireNonNull(reservation, "reservation"); + this.anchor = Objects.requireNonNull(anchor, "anchor"); + this.memberOperation = Objects.requireNonNull(memberOperation, "memberOperation"); + this.issuerControlEpoch = requirePositive(issuerControlEpoch, "issuerControlEpoch"); + this.layoutDescriptor = Objects.requireNonNull(layoutDescriptor, "layoutDescriptor"); + this.sourceCheckpoint = Objects.requireNonNull(sourceCheckpoint, "sourceCheckpoint"); + this.incarnation = Objects.requireNonNull(incarnation, "incarnation"); + + if (!owner.issuerId().equals(layoutDescriptor.issuerId()) + || !owner.issuerId().equals(sourceCheckpoint.issuerId())) { + throw new IllegalArgumentException("Issuer member, layout, and source scopes must match"); + } + if (!owner.issuerIndexLayoutVersion().equals(layoutDescriptor.layoutVersion()) + || !owner.issuerIndexPartitionCount().equals(layoutDescriptor.partitionCount()) + || !owner.issuerIndexPartitionCapacity().equals(layoutDescriptor.partitionCapacity())) { + throw new IllegalArgumentException("Issuer member must retain its exact pinned layout"); + } + if (!owner.issuerAuthGeneration().equals(sourceCheckpoint.issuerAuthGeneration())) { + throw new IllegalArgumentException( + "Account issuer source generation must match binding issuerAuthGeneration"); + } + if (!reservation.owner().equals(owner) + || !reservation.bindingGeneration().equals(bindingGeneration) + || !reservation + .partitionId() + .equals(owner.bindingRef().partitionId(owner.issuerIndexPartitionCount()))) { + throw new IllegalArgumentException( + "Issuer reservation must retain the exact binding owner, generation, and partition"); + } + if (!anchor.issuerCoverageOperationId().equals(reservation.issuerCoverageOperationId()) + || !anchor.operationFence().equals(reservation.issuerCoverageOperationFence()) + || !anchor.coverageFence().equals(reservation.coverageFence()) + || !anchor + .issuerInventorySnapshotRevision() + .equals(reservation.inventorySnapshotRevision())) { + throw new IllegalArgumentException( + "Issuer reservation must retain the complete installed anchor tuple"); + } + requireDigestMatches( + layoutDescriptor.exactDescriptorBytes(), layoutDescriptor.descriptorDigest(), "descriptor"); + requireDigestMatches( + sourceCheckpoint.exactCheckpointBytes(), + sourceCheckpoint.checkpointDigest(), + "source checkpoint"); + byte[] sourceEventBytes = sourceCheckpoint.latestIssuerEventBytes(); + if (sourceEventBytes != null) { + requireDigestMatches( + sourceEventBytes, sourceCheckpoint.latestIssuerEventDigest(), "source event"); + } + } + + CanonicalGameplayBindingIdentity owner() { + return owner; + } + + BigInteger bindingGeneration() { + return bindingGeneration; + } + + CanonicalIssuerPartitionReservation reservation() { + return reservation; + } + + Anchor anchor() { + return anchor; + } + + LocalMemberOperation memberOperation() { + return memberOperation; + } + + BigInteger issuerControlEpoch() { + return issuerControlEpoch; + } + + CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor layoutDescriptor() { + return layoutDescriptor; + } + + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint sourceCheckpoint() { + return sourceCheckpoint; + } + + Incarnation incarnation() { + return incarnation; + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof CanonicalGameplayIssuerMemberV2Value value)) { + return false; + } + return owner.equals(value.owner) + && bindingGeneration.equals(value.bindingGeneration) + && reservation.equals(value.reservation) + && anchor.equals(value.anchor) + && memberOperation.equals(value.memberOperation) + && issuerControlEpoch.equals(value.issuerControlEpoch) + && sameLayout(layoutDescriptor, value.layoutDescriptor) + && sameSourceCheckpoint(sourceCheckpoint, value.sourceCheckpoint) + && incarnation.equals(value.incarnation); + } + + @Override + public int hashCode() { + int result = + Objects.hash( + owner, bindingGeneration, reservation, anchor, memberOperation, issuerControlEpoch); + result = 31 * result + layoutHashCode(layoutDescriptor); + result = 31 * result + sourceCheckpointHashCode(sourceCheckpoint); + return 31 * result + incarnation.hashCode(); + } + + private static boolean sameLayout( + CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor left, + CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor right) { + return left.issuerId().equals(right.issuerId()) + && left.layoutVersion().equals(right.layoutVersion()) + && left.partitionCount().equals(right.partitionCount()) + && left.partitionCapacity().equals(right.partitionCapacity()) + && left.mappingIdentity().equals(right.mappingIdentity()) + && Arrays.equals(left.exactDescriptorBytes(), right.exactDescriptorBytes()) + && left.descriptorDigest().equals(right.descriptorDigest()); + } + + private static int layoutHashCode( + CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor layout) { + int result = + Objects.hash( + layout.issuerId(), + layout.layoutVersion(), + layout.partitionCount(), + layout.partitionCapacity(), + layout.mappingIdentity(), + layout.descriptorDigest()); + return 31 * result + Arrays.hashCode(layout.exactDescriptorBytes()); + } + + private static boolean sameSourceCheckpoint( + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint left, + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint right) { + return left.issuerId().equals(right.issuerId()) + && left.issuerAuthGeneration().equals(right.issuerAuthGeneration()) + && Arrays.equals(left.exactCheckpointBytes(), right.exactCheckpointBytes()) + && left.checkpointDigest().equals(right.checkpointDigest()) + && Arrays.equals(left.latestIssuerEventBytes(), right.latestIssuerEventBytes()) + && Objects.equals(left.latestIssuerEventDigest(), right.latestIssuerEventDigest()); + } + + private static int sourceCheckpointHashCode( + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint source) { + int result = + Objects.hash( + source.issuerId(), + source.issuerAuthGeneration(), + source.checkpointDigest(), + source.latestIssuerEventDigest()); + result = 31 * result + Arrays.hashCode(source.exactCheckpointBytes()); + return 31 * result + Arrays.hashCode(source.latestIssuerEventBytes()); + } + + record Anchor( + UUID issuerCoverageOperationId, + BigInteger operationFence, + BigInteger coverageFence, + BigInteger issuerInventorySnapshotRevision) { + Anchor { + requireNonNil(issuerCoverageOperationId, "issuerCoverageOperationId"); + requirePositive(operationFence, "operationFence"); + requirePositive(coverageFence, "coverageFence"); + requirePositive(issuerInventorySnapshotRevision, "issuerInventorySnapshotRevision"); + if (operationFence.equals(coverageFence)) { + throw new IllegalArgumentException("Issuer operationFence and coverageFence are distinct"); + } + } + } + + record LocalMemberOperation( + UUID operationId, BigInteger operationFence, BigInteger coverageGeneration) { + LocalMemberOperation { + requireNonNil(operationId, "operationId"); + requirePositive(operationFence, "member operationFence"); + requirePositive(coverageGeneration, "coverageGeneration"); + } + } + + record Incarnation( + String attestorBinding, + String acceptedAttestationDigest, + CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + targetDeploymentEvidence, + String coordOpsRoAclDigest, + String coordRedisConfigObservedDigest) { + Incarnation { + requireNonBlank(attestorBinding, "attestorBinding"); + requireDigest(acceptedAttestationDigest, "acceptedAttestationDigest"); + Objects.requireNonNull(targetDeploymentEvidence, "targetDeploymentEvidence"); + requireDigest(coordOpsRoAclDigest, "coordOpsRoAclDigest"); + requireDigest(coordRedisConfigObservedDigest, "coordRedisConfigObservedDigest"); + } + } + + private static BigInteger requirePositive(BigInteger value, String name) { + Objects.requireNonNull(value, name); + if (value.signum() <= 0) { + throw new IllegalArgumentException(name + " must be positive"); + } + return value; + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(name + " must not be nil"); + } + } + + private static void requireNonBlank(String value, String name) { + Objects.requireNonNull(value, name); + if (value.isBlank()) { + throw new IllegalArgumentException(name + " must not be blank"); + } + } + + private static void requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(name + " must be canonical SHA-256"); + } + } + + private static void requireDigestMatches(byte[] bytes, String digest, String name) { + requireDigest(digest, name + " digest"); + if (!CanonicalGameplayIssuerMemberV2Codec.sha256(bytes).equals(digest)) { + throw new IllegalArgumentException(name + " digest does not match its exact bytes"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerRedisKeys.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerRedisKeys.java new file mode 100644 index 0000000000..de72fffb46 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerRedisKeys.java @@ -0,0 +1,111 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; + +/** Canonical key construction for one issuer layout partition. */ +final class CanonicalGameplayIssuerRedisKeys { + private static final String KEY_PREFIX = "session:game:index:issuer:"; + private static final String TAG_DOMAIN = "issuer-layout-tag/v1"; + + private CanonicalGameplayIssuerRedisKeys() {} + + static String forMember(CanonicalGameplayIssuerMemberV2Value value) { + Objects.requireNonNull(value, "value"); + return forPartition(value.layoutDescriptor(), value.reservation().partitionId()); + } + + /** Builds the canonical physical key for an explicit pinned layout partition. */ + static String forPartition( + CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor layout, + BigInteger partitionId) { + validateLayout(layout); + Objects.requireNonNull(partitionId, "partitionId"); + if (partitionId.signum() < 0 || partitionId.compareTo(layout.partitionCount()) >= 0) { + throw new IllegalArgumentException("partitionId must be within the pinned issuer layout"); + } + String canonicalPartitionId = partitionId.toString(); + String tag = + "il-v1-" + + HexFormat.of() + .formatHex( + sha256( + framed( + TAG_DOMAIN, + layout.layoutVersion().toString(), + layout.issuerId(), + canonicalPartitionId))); + return KEY_PREFIX + "{" + tag + "}:" + layout.issuerId() + ":" + canonicalPartitionId; + } + + /** Verifies the existing canonical bindingRef mapping before constructing its partition key. */ + static String forBindingReference( + CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor layout, + CanonicalGameplayBindingRef bindingRef, + BigInteger partitionId) { + validateLayout(layout); + Objects.requireNonNull(bindingRef, "bindingRef"); + Objects.requireNonNull(partitionId, "partitionId"); + if (!bindingRef.partitionId(layout.partitionCount()).equals(partitionId)) { + throw new IllegalArgumentException( + "partitionId does not match the canonical bindingRef mapping"); + } + return forPartition(layout, partitionId); + } + + static String layoutTag( + CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor layout, + BigInteger partitionId) { + String key = forPartition(layout, partitionId); + int tagStart = KEY_PREFIX.length() + 1; + int tagEnd = key.indexOf('}', tagStart); + return key.substring(tagStart, tagEnd); + } + + private static void validateLayout( + CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor layout) { + Objects.requireNonNull(layout, "layout"); + if (!CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY.equals( + layout.mappingIdentity())) { + throw new IllegalArgumentException("Unsupported canonical issuer mapping identity"); + } + if (!GameSessionAccountDelegationProfile.ISSUER.equals(layout.issuerId())) { + throw new IllegalArgumentException("Unsupported Account issuer identity"); + } + if (layout.layoutVersion().signum() <= 0 + || layout.partitionCount().signum() <= 0 + || layout.partitionCapacity().signum() <= 0) { + throw new IllegalArgumentException("Pinned issuer layout counters must be positive"); + } + if (!CanonicalGameplayIssuerMemberV2Codec.sha256(layout.exactDescriptorBytes()) + .equals(layout.descriptorDigest())) { + throw new IllegalArgumentException("Pinned issuer layout descriptor digest does not match"); + } + } + + private static byte[] framed(String... values) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (String value : values) { + byte[] encoded = value.getBytes(StandardCharsets.UTF_8); + output.writeBytes(Integer.toString(encoded.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(encoded); + } + return output.toByteArray(); + } + + private static byte[] sha256(byte[] bytes) { + try { + return MessageDigest.getInstance("SHA-256").digest(bytes); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("JVM does not provide SHA-256", impossible); + } + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V1030__canonical_issuer_layout_bootstrap_intent.sql b/services/game-session-service/src/main/resources/db/migration/V1030__canonical_issuer_layout_bootstrap_intent.sql new file mode 100644 index 0000000000..19f77a36bc --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1030__canonical_issuer_layout_bootstrap_intent.sql @@ -0,0 +1,137 @@ +-- This migration persists only a pending, issuer-scoped initial-layout bootstrap intent and its +-- immutable durable SQL cohort. It does not publish an active layout pointer, installed anchor, +-- issuer coverage acknowledgement, barrier state, or admission authority. +CREATE TABLE game_session_canonical_issuer_layout_bootstrap_intent ( + operation_id uuid NOT NULL, + request_id uuid NOT NULL, + issuer_id character varying(64) NOT NULL, + control_epoch numeric NOT NULL, + operation_fence numeric NOT NULL, + coverage_fence numeric NOT NULL, + inventory_snapshot_revision numeric NOT NULL, + layout_version numeric NOT NULL, + partition_count numeric NOT NULL, + partition_capacity numeric NOT NULL, + mapping_identity character varying(96) NOT NULL, + layout_descriptor_bytes bytea NOT NULL, + layout_descriptor_digest character varying(71) NOT NULL, + issuer_auth_generation numeric NOT NULL, + source_checkpoint_bytes bytea NOT NULL, + source_checkpoint_digest character varying(71) NOT NULL, + source_event_bytes bytea, + source_event_digest character varying(71), + legacy_cohort_id uuid NOT NULL, + legacy_owner_operation_id uuid NOT NULL, + legacy_writer_fence uuid NOT NULL, + legacy_source_snapshot_revision numeric NOT NULL, + legacy_canonical_inventory_revision numeric NOT NULL, + legacy_namespace_index_readback_revision numeric NOT NULL, + legacy_evidence_digest character varying(71) NOT NULL, + cohort_row_count bigint NOT NULL, + cohort_digest character varying(71) NOT NULL, + intent_state character varying(32) NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_issuer_layout_bootstrap_intent PRIMARY KEY (operation_id), + CONSTRAINT uq_gs_issuer_layout_bootstrap_intent_operation_issuer_pair + UNIQUE (operation_id, issuer_id), + CONSTRAINT uq_gs_issuer_layout_bootstrap_intent_operation_issuer + UNIQUE (operation_id, issuer_id, control_epoch, operation_fence, coverage_fence), + CONSTRAINT uq_gs_issuer_layout_bootstrap_intent_request + UNIQUE (issuer_id, request_id), + CONSTRAINT uq_gs_issuer_layout_bootstrap_intent_fence + UNIQUE (issuer_id, operation_fence), + CONSTRAINT chk_gs_issuer_layout_bootstrap_intent CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND operation_id <> request_id + AND issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND control_epoch > 0 + AND operation_fence = control_epoch + AND coverage_fence > 0 + AND coverage_fence <> operation_fence + AND inventory_snapshot_revision > 0 + AND layout_version > 0 + AND partition_count > 0 + AND partition_capacity > 0 + AND mapping_identity = 'bindingRef/v1;sha256-u256-mod/v1' + AND octet_length(layout_descriptor_bytes) > 0 + AND layout_descriptor_digest ~ '^sha256:[0-9a-f]{64}$' + AND issuer_auth_generation > 0 + AND octet_length(source_checkpoint_bytes) > 0 + AND source_checkpoint_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((source_event_bytes IS NULL AND source_event_digest IS NULL) + OR (source_event_bytes IS NOT NULL + AND octet_length(source_event_bytes) > 0 + AND source_event_digest IS NOT NULL + AND source_event_digest ~ '^sha256:[0-9a-f]{64}$')) + AND legacy_cohort_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND legacy_owner_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND legacy_writer_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND legacy_source_snapshot_revision > 0 + AND legacy_canonical_inventory_revision > 0 + AND legacy_canonical_inventory_revision <= inventory_snapshot_revision + AND legacy_namespace_index_readback_revision > 0 + AND legacy_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND cohort_row_count >= 0 + AND cohort_digest ~ '^sha256:[0-9a-f]{64}$' + AND intent_state = 'INITIAL_BOOTSTRAP_INTENT') +); + +CREATE TABLE game_session_canonical_issuer_layout_bootstrap_control ( + issuer_id character varying(64) NOT NULL, + state character varying(32) NOT NULL, + control_epoch numeric NOT NULL, + last_issued_fence numeric NOT NULL, + current_operation_id uuid NOT NULL, + current_operation_fence numeric NOT NULL, + current_coverage_fence numeric NOT NULL, + updated_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_issuer_layout_bootstrap_control PRIMARY KEY (issuer_id), + CONSTRAINT fk_gs_issuer_layout_bootstrap_control_intent + FOREIGN KEY ( + current_operation_id, issuer_id, control_epoch, + current_operation_fence, current_coverage_fence) + REFERENCES game_session_canonical_issuer_layout_bootstrap_intent ( + operation_id, issuer_id, control_epoch, operation_fence, coverage_fence), + CONSTRAINT chk_gs_issuer_layout_bootstrap_control CHECK ( + issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND state = 'INITIAL_BOOTSTRAP_INTENT' + AND control_epoch > 0 + AND last_issued_fence >= current_coverage_fence + AND current_operation_fence = control_epoch + AND current_operation_fence > 0 + AND current_coverage_fence > 0 + AND current_coverage_fence <> current_operation_fence) +); + +CREATE TABLE game_session_canonical_issuer_layout_bootstrap_cohort_row ( + operation_id uuid NOT NULL, + issuer_id character varying(64) NOT NULL, + row_ordinal bigint NOT NULL, + source_kind character varying(40) NOT NULL, + source_key text NOT NULL, + source_inventory_revision numeric NOT NULL, + source_row_json text NOT NULL, + source_row_digest character varying(71) NOT NULL, + CONSTRAINT pk_gs_issuer_layout_bootstrap_cohort_row + PRIMARY KEY (operation_id, row_ordinal), + -- [jooq ignore start] + CONSTRAINT uq_gs_issuer_layout_bootstrap_cohort_source + UNIQUE (operation_id, source_kind, source_key), + -- [jooq ignore stop] + CONSTRAINT fk_gs_issuer_layout_bootstrap_cohort_intent + FOREIGN KEY (operation_id, issuer_id) + REFERENCES game_session_canonical_issuer_layout_bootstrap_intent + (operation_id, issuer_id), + CONSTRAINT chk_gs_issuer_layout_bootstrap_cohort_row CHECK ( + row_ordinal >= 0 + AND issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND source_kind IN ( + 'BINDING', 'UNRESOLVED_LEGACY_BINDING', 'TRANSITION', 'RESERVATION', + 'UNRESOLVED_LEGACY_RESERVATION', 'ACCOUNT_OBLIGATION', 'ISSUER_OBLIGATION', + 'REGION_OBLIGATION') + AND length(source_key) > 0 + AND source_inventory_revision > 0 + AND length(source_row_json) > 1 + AND source_row_digest ~ '^sha256:[0-9a-f]{64}$') +); 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 403da6ae17..bf1a65ca90 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 @@ -933,43 +933,59 @@ static Fixture open(java.math.BigInteger lastOperationFence, String migrationTar DriverManagerDataSource dataSource = dataSource(schema); flyway(dataSource, schema, migrationTarget).migrate(); DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); - UUID tenantId = UUID.randomUUID(); + CanonicalGameplayBindingIdentity retainedIdentity = + "1028".equals(migrationTarget) + ? CanonicalGameplayBindingInventoryRepositoryIntegrationTest.identity( + UUID.randomUUID().toString()) + : null; + UUID tenantId = retainedIdentity == null ? UUID.randomUUID() : retainedIdentity.tenantId(); var runtime = CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource, tenantId); CanonicalGameplayBindingInventoryRepositoryIntegrationTest .seedSyntheticVerifiedLegacyDisposition(dsl); - UUID accountId = UUID.randomUUID(); - UUID transitionId = UUID.randomUUID(); - CanonicalGameplayBindingIdentity identity = - new CanonicalGameplayBindingIdentity( - accountId, - runtime.canonicalTenantId(), - runtime.playableStateNamespaceId(), - UUID.randomUUID(), - "SHARED", - runtime.gameInstanceUuid(), - runtime.gameInstanceId(), - UUID.randomUUID().toString(), - UUID.randomUUID(), - java.math.BigInteger.ONE, - GameSessionAccountDelegationProfile.ISSUER, - java.math.BigInteger.ONE, - java.math.BigInteger.ONE, - java.math.BigInteger.valueOf(16), - java.math.BigInteger.valueOf(32)); - CanonicalIssuerReservationFenceEvidence reservation = - new CanonicalIssuerReservationFenceEvidence( - UUID.randomUUID(), - UUID.randomUUID(), - UUID.randomUUID(), - java.math.BigInteger.ONE, - java.math.BigInteger.ONE, - java.math.BigInteger.ONE); - new CanonicalGameplayBindingInventoryRepository(dsl) - .prepare( - new CanonicalGameplayBindingTransitionRequest( - transitionId, UUID.randomUUID(), identity, reservation, null, null)); + UUID accountId; + if (retainedIdentity != null) { + // This V1028-only fixture reuses the existing canonical historical-source SQL helper. + // It is retained storage for this migration test, not a live prepare-owner or admission + // proof. V1028 predates the V1030 issuer-intent guard read by current prepare(). + accountId = retainedIdentity.accountId(); + CanonicalGameplayBindingInventoryRepositoryIntegrationTest.seedActiveSource( + dsl, retainedIdentity); + seedNoActiveAccountCoverageControl(dsl, accountId); + } else { + accountId = UUID.randomUUID(); + UUID transitionId = UUID.randomUUID(); + CanonicalGameplayBindingIdentity identity = + new CanonicalGameplayBindingIdentity( + accountId, + runtime.canonicalTenantId(), + runtime.playableStateNamespaceId(), + UUID.randomUUID(), + "SHARED", + runtime.gameInstanceUuid(), + runtime.gameInstanceId(), + UUID.randomUUID().toString(), + UUID.randomUUID(), + java.math.BigInteger.ONE, + GameSessionAccountDelegationProfile.ISSUER, + java.math.BigInteger.ONE, + java.math.BigInteger.ONE, + java.math.BigInteger.valueOf(16), + java.math.BigInteger.valueOf(32)); + CanonicalIssuerReservationFenceEvidence reservation = + new CanonicalIssuerReservationFenceEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + java.math.BigInteger.ONE, + java.math.BigInteger.ONE, + java.math.BigInteger.ONE); + new CanonicalGameplayBindingInventoryRepository(dsl) + .prepare( + new CanonicalGameplayBindingTransitionRequest( + transitionId, UUID.randomUUID(), identity, reservation, null, null)); + } dsl.execute( "UPDATE game_session_canonical_account_coverage_control SET last_operation_fence = ?" + " WHERE account_id = ? AND state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW'", @@ -1002,6 +1018,15 @@ static Fixture open(java.math.BigInteger lastOperationFence, String migrationTar schema, dataSource, dsl, intent, runtime.targetNamespace(), keyPair, evidence); } + private static void seedNoActiveAccountCoverageControl(DSLContext dsl, UUID accountId) { + // Controlled retained-row input only; this is not owner-produced no-active authority. + dsl.execute( + "INSERT INTO game_session_canonical_account_coverage_control " + + "(account_id, state, last_operation_fence) " + + "VALUES (?, 'NO_ACTIVE_ACCOUNT_WIDE_FLOW', 0)", + accountId); + } + private void migrateTo(String migrationTarget) { flyway(dataSource, schema, migrationTarget).migrate(); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapMigrationPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapMigrationPostgresIntegrationTest.java new file mode 100644 index 0000000000..a794c3db47 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapMigrationPostgresIntegrationTest.java @@ -0,0 +1,220 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.nio.file.Path; +import java.sql.Connection; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL retention proof for adding the pending issuer-bootstrap intent schema. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayIssuerLayoutBootstrapMigrationPostgresIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final UUID CONTROLLED_ACCOUNT_ID = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final List RETAINED_TABLES = + List.of( + "game_session_canonical_binding_inventory_clock", + "game_session_canonical_binding_legacy_disposition", + "game_session_canonical_account_coverage_control"); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void addingIssuerBootstrapIntentTablesPreservesExistingRowsAndMetadataAcrossRestart() + throws Exception { + String schema = "gs_issuer_layout_v1030_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + try { + Flyway v1029 = flyway(dataSource, schema, MigrationVersion.fromVersion("1029")); + v1029.migrate(); + v1029.validate(); + assertThat( + dsl.fetchSingle( + "SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1") + .get(0, String.class)) + .isEqualTo("1029"); + + seedControlledRetainedAccountControl(dsl); + Map> rowsBefore = rowSnapshots(dsl); + List historyBefore = historySnapshot(dsl); + Map constraintsBefore = constraintSnapshot(dsl); + Map indexesBefore = indexSnapshot(dsl); + assertThat(rowsBefore.get("game_session_canonical_binding_inventory_clock")).hasSize(1); + assertThat(rowsBefore.get("game_session_canonical_binding_legacy_disposition")).hasSize(1); + assertThat(rowsBefore.get("game_session_canonical_account_coverage_control")).hasSize(1); + assertThat( + dsl.fetchSingle( + "SELECT disposition_state FROM game_session_canonical_binding_legacy_disposition " + + "WHERE singleton_id = 1") + .get(0, String.class)) + .isEqualTo("REQUIRED"); + + Flyway v1030 = flyway(dataSource, schema, MigrationVersion.fromVersion("1030")); + v1030.migrate(); + v1030.validate(); + + List historyAfterMigration = historySnapshot(dsl); + assertThat(historyAfterMigration).hasSize(historyBefore.size() + 1); + assertThat(historyAfterMigration.subList(0, historyBefore.size())) + .containsExactlyElementsOf(historyBefore); + assertThat( + dsl.fetchSingle("SELECT script FROM flyway_schema_history WHERE version = '1030'") + .get(0, String.class)) + .isEqualTo("V1030__canonical_issuer_layout_bootstrap_intent.sql"); + assertThat(rowSnapshots(dsl)).isEqualTo(rowsBefore); + assertThat(constraintSnapshot(dsl)).containsAllEntriesOf(constraintsBefore); + assertThat(indexSnapshot(dsl)).containsAllEntriesOf(indexesBefore); + assertNewBootstrapTablesAreEmpty(dsl); + + Map> rowsAfterMigration = rowSnapshots(dsl); + Map constraintsAfterMigration = constraintSnapshot(dsl); + Map indexesAfterMigration = indexSnapshot(dsl); + Flyway restarted = flyway(dataSource, schema, MigrationVersion.fromVersion("1030")); + restarted.migrate(); + restarted.validate(); + + assertThat(historySnapshot(dsl)).containsExactlyElementsOf(historyAfterMigration); + assertThat(rowSnapshots(dsl)).isEqualTo(rowsAfterMigration); + assertThat(constraintSnapshot(dsl)).isEqualTo(constraintsAfterMigration); + assertThat(indexSnapshot(dsl)).isEqualTo(indexesAfterMigration); + assertNewBootstrapTablesAreEmpty(dsl); + } finally { + dropSchema(schema); + } + } + + private static void seedControlledRetainedAccountControl(DSLContext dsl) { + // Controlled legal SQL row used only to prove V1030 retention. It is not owner-produced + // no-active authority and does not represent an issuer bootstrap or gameplay admission. + dsl.execute( + "INSERT INTO game_session_canonical_account_coverage_control " + + "(account_id, state, last_operation_fence) " + + "VALUES (?, 'NO_ACTIVE_ACCOUNT_WIDE_FLOW', 0)", + CONTROLLED_ACCOUNT_ID); + } + + private static Map> rowSnapshots(DSLContext dsl) { + Map> snapshots = new LinkedHashMap<>(); + for (String table : RETAINED_TABLES) { + List rows = new ArrayList<>(); + for (var row : + dsl.fetch( + "SELECT to_jsonb(retained_row)::text AS row_json FROM " + + table + + " retained_row ORDER BY to_jsonb(retained_row)::text")) { + rows.add(row.get("row_json", String.class)); + } + snapshots.put(table, List.copyOf(rows)); + } + return Map.copyOf(snapshots); + } + + private static List historySnapshot(DSLContext dsl) { + return dsl.fetch( + "SELECT to_jsonb(history_row)::text AS row_json FROM flyway_schema_history history_row " + + "ORDER BY installed_rank") + .getValues("row_json", String.class); + } + + private static Map constraintSnapshot(DSLContext dsl) { + Map constraints = new LinkedHashMap<>(); + for (var row : + dsl.fetch( + "SELECT relation.relname AS relation_name, constraint_row.conname AS constraint_name, " + + "constraint_row.contype::text AS constraint_type, constraint_row.convalidated, " + + "pg_get_constraintdef(constraint_row.oid, true) AS definition " + + "FROM pg_constraint constraint_row " + + "JOIN pg_class relation ON relation.oid = constraint_row.conrelid " + + "WHERE constraint_row.connamespace = current_schema()::regnamespace " + + "ORDER BY relation.relname, constraint_row.conname")) { + String key = + row.get("relation_name", String.class) + "." + row.get("constraint_name", String.class); + String value = + row.get("constraint_type", String.class) + + "|" + + row.get("convalidated", Boolean.class) + + "|" + + row.get("definition", String.class); + constraints.put(key, value); + } + return Map.copyOf(constraints); + } + + private static Map indexSnapshot(DSLContext dsl) { + Map indexes = new LinkedHashMap<>(); + for (var row : + dsl.fetch( + "SELECT tablename, indexname, indexdef FROM pg_indexes " + + "WHERE schemaname = current_schema() ORDER BY tablename, indexname")) { + indexes.put( + row.get("tablename", String.class) + "." + row.get("indexname", String.class), + row.get("indexdef", String.class)); + } + return Map.copyOf(indexes); + } + + private static void assertNewBootstrapTablesAreEmpty(DSLContext dsl) { + assertThat(dsl.fetchCount(DSL.table("game_session_canonical_issuer_layout_bootstrap_control"))) + .isZero(); + assertThat(dsl.fetchCount(DSL.table("game_session_canonical_issuer_layout_bootstrap_intent"))) + .isZero(); + assertThat( + dsl.fetchCount(DSL.table("game_session_canonical_issuer_layout_bootstrap_cohort_row"))) + .isZero(); + } + + private static Flyway flyway( + DriverManagerDataSource dataSource, String schema, MigrationVersion target) { + return Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(target) + .load(); + } + + private static DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + String jdbcUrl = postgres.getJdbcUrl(); + String separator = jdbcUrl.contains("?") ? "&" : "?"; + dataSource.setUrl(jdbcUrl + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } + + private static void dropSchema(String schema) { + try (Connection connection = + java.sql.DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + var statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } catch (Exception failure) { + throw new IllegalStateException("Failed to dispose issuer-layout migration schema", failure); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java new file mode 100644 index 0000000000..a466b5a8cc --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java @@ -0,0 +1,989 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.EnumSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; +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; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final UUID ACCOUNT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID NAMESPACE_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID GAME_INSTANCE_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID REGION_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID PREPARED_CHARACTER_ID = + UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID BLOCKED_CHARACTER_ID = + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final BigInteger LAYOUT_VERSION = BigInteger.valueOf(3); + private static final BigInteger PARTITION_COUNT = BigInteger.valueOf(16); + private static final BigInteger PARTITION_CAPACITY = BigInteger.valueOf(32); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void absenceAndRequiredLegacyDispositionCannotCreateAnIntent() { + TestSchema testSchema = newTestSchema("gs_issuer_boot_legacy_"); + try { + var owner = new CanonicalGameplayIssuerLayoutBootstrapRepository(testSchema.dsl()); + var descriptor = descriptor(LAYOUT_VERSION, PARTITION_COUNT, PARTITION_CAPACITY); + var source = sourceCheckpoint(BigInteger.valueOf(7)); + UUID requestId = UUID.randomUUID(); + + assertThatThrownBy(() -> owner.beginInitialBootstrapIntent(requestId, descriptor, source)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("actual VERIFIED legacy disposition"); + assertThat( + countRows(testSchema.dsl(), "game_session_canonical_issuer_layout_bootstrap_intent")) + .isZero(); + assertThat( + countRows(testSchema.dsl(), "game_session_canonical_issuer_layout_bootstrap_control")) + .isZero(); + + testSchema + .dsl() + .execute( + "DELETE FROM game_session_canonical_binding_legacy_disposition WHERE singleton_id = 1"); + assertThatThrownBy( + () -> owner.beginInitialBootstrapIntent(UUID.randomUUID(), descriptor, source)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("actual VERIFIED legacy disposition"); + assertThat( + countRows(testSchema.dsl(), "game_session_canonical_issuer_layout_bootstrap_intent")) + .isZero(); + } finally { + dropSchema(testSchema.schema()); + } + } + + @Test + void pendingIntentFreezesActualInventoryAndExactInputsAcrossRetryAndRestart() { + TestSchema testSchema = newTestSchema("gs_issuer_boot_retry_"); + try { + establishActualLegacyDisposition(testSchema.dsl()); + var inventory = new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); + var prepared = prepareActualBinding(inventory); + UUID reservationOnlyId = UUID.randomUUID(); + insertReservationOnly( + testSchema.dsl(), prepared.candidate(), prepared.inventoryRevision(), reservationOnlyId); + + var owner = new CanonicalGameplayIssuerLayoutBootstrapRepository(testSchema.dsl()); + UUID requestId = UUID.randomUUID(); + var descriptor = descriptor(LAYOUT_VERSION, PARTITION_COUNT, PARTITION_CAPACITY); + var source = sourceCheckpoint(BigInteger.valueOf(7)); + var intent = owner.beginInitialBootstrapIntent(requestId, descriptor, source); + + assertThat(intent.state()) + .isEqualTo(CanonicalGameplayIssuerLayoutBootstrapIntent.State.INITIAL_BOOTSTRAP_INTENT); + assertThat(intent.operationFence()).isPositive(); + assertThat(intent.coverageFence()).isPositive().isNotEqualTo(intent.operationFence()); + assertThat(intent.inventorySnapshotRevision()).isEqualTo(prepared.inventoryRevision()); + assertThat(intent.sourceCheckpoint().issuerId()).isEqualTo(ISSUER); + assertThat(intent.sourceCheckpoint().issuerAuthGeneration()).isEqualTo(BigInteger.valueOf(7)); + assertThat(intent.cohortRows()) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::kind) + .contains( + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.BINDING, + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.TRANSITION, + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.RESERVATION, + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.ACCOUNT_OBLIGATION, + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.ISSUER_OBLIGATION, + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.REGION_OBLIGATION); + assertThat(intent.cohortRows()) + .filteredOn( + row -> + row.kind() == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.RESERVATION) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceKey) + .contains(reservationOnlyId.toString()); + + var exactRetry = owner.beginInitialBootstrapIntent(requestId, descriptor, source); + var restartedRead = + new CanonicalGameplayIssuerLayoutBootstrapRepository(testSchema.dsl()) + .readCurrentInitialBootstrapIntent(intent.operationId()); + assertThat(exactRetry.operationId()).isEqualTo(intent.operationId()); + assertThat(exactRetry.operationFence()).isEqualTo(intent.operationFence()); + assertThat(exactRetry.coverageFence()).isEqualTo(intent.coverageFence()); + assertThat(exactRetry.cohortDigest()).isEqualTo(intent.cohortDigest()); + assertThat(restartedRead.operationId()).isEqualTo(intent.operationId()); + assertThat(restartedRead.cohortDigest()).isEqualTo(intent.cohortDigest()); + assertThat(restartedRead.cohortRows()) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceRowDigest) + .containsExactlyElementsOf( + intent.cohortRows().stream() + .map(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceRowDigest) + .toList()); + + var changedDescriptor = descriptor(LAYOUT_VERSION, PARTITION_COUNT, BigInteger.valueOf(33)); + assertThatThrownBy( + () -> owner.beginInitialBootstrapIntent(requestId, changedDescriptor, source)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("changed its original trusted inputs"); + var changedSource = sourceCheckpoint(BigInteger.valueOf(8)); + assertThatThrownBy( + () -> owner.beginInitialBootstrapIntent(requestId, descriptor, changedSource)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("changed its original trusted inputs"); + var malformedSource = + new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint( + ISSUER, + BigInteger.valueOf(7), + source.checkpointBytes(), + "{".getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy( + () -> owner.beginInitialBootstrapIntent(requestId, descriptor, malformedSource)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not codec-verified"); + assertThat(owner.readCurrentInitialBootstrapIntent(intent.operationId()).cohortDigest()) + .isEqualTo(intent.cohortDigest()); + assertThat( + countRows(testSchema.dsl(), "game_session_canonical_issuer_layout_bootstrap_control")) + .isEqualTo(1); + } finally { + dropSchema(testSchema.schema()); + } + } + + @Test + void pendingIntentBlocksLaterPreparationWithoutChangingInventoryOrItsCohort() { + TestSchema testSchema = newTestSchema("gs_issuer_boot_blocks_new_"); + try { + establishActualLegacyDisposition(testSchema.dsl()); + var inventory = new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); + prepareActualBinding(inventory); + + var owner = new CanonicalGameplayIssuerLayoutBootstrapRepository(testSchema.dsl()); + UUID requestId = UUID.randomUUID(); + var descriptor = descriptor(LAYOUT_VERSION, PARTITION_COUNT, PARTITION_CAPACITY); + var source = sourceCheckpoint(BigInteger.valueOf(7)); + var originalIntent = owner.beginInitialBootstrapIntent(requestId, descriptor, source); + List originalCohortRowDigests = + originalIntent.cohortRows().stream() + .map(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceRowDigest) + .toList(); + BigInteger originalInventoryRevision = currentInventoryRevision(testSchema.dsl()); + int bindingCount = + countRows(testSchema.dsl(), "game_session_canonical_gameplay_binding_inventory"); + int transitionCount = + countRows(testSchema.dsl(), "game_session_canonical_binding_transition"); + int reservationCount = + countRows(testSchema.dsl(), "game_session_canonical_issuer_partition_reservation"); + int generationCount = + countRows(testSchema.dsl(), "game_session_canonical_binding_generation"); + + assertThatThrownBy(() -> prepareActualBinding(inventory, BLOCKED_CHARACTER_ID)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining( + "Initial issuer-layout bootstrap intent blocks new binding preparation"); + + assertThat(currentInventoryRevision(testSchema.dsl())).isEqualTo(originalInventoryRevision); + assertThat(countRows(testSchema.dsl(), "game_session_canonical_gameplay_binding_inventory")) + .isEqualTo(bindingCount); + assertThat(countRows(testSchema.dsl(), "game_session_canonical_binding_transition")) + .isEqualTo(transitionCount); + assertThat(countRows(testSchema.dsl(), "game_session_canonical_issuer_partition_reservation")) + .isEqualTo(reservationCount); + assertThat(countRows(testSchema.dsl(), "game_session_canonical_binding_generation")) + .isEqualTo(generationCount); + + var exactRetry = owner.beginInitialBootstrapIntent(requestId, descriptor, source); + var currentIntent = owner.readCurrentInitialBootstrapIntent(originalIntent.operationId()); + assertThat(exactRetry.operationId()).isEqualTo(originalIntent.operationId()); + assertThat(exactRetry.operationFence()).isEqualTo(originalIntent.operationFence()); + assertThat(exactRetry.coverageFence()).isEqualTo(originalIntent.coverageFence()); + assertThat(exactRetry.cohortDigest()).isEqualTo(originalIntent.cohortDigest()); + assertThat(currentIntent.cohortRows()) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceRowDigest) + .containsExactlyElementsOf(originalCohortRowDigests); + } finally { + dropSchema(testSchema.schema()); + } + } + + @Test + void orphanedPendingIntentBlocksPreparationWithoutChangingItsFrozenSources() { + TestSchema testSchema = newTestSchema("gs_issuer_boot_orphan_"); + try { + establishActualLegacyDisposition(testSchema.dsl()); + var inventory = new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); + prepareActualBinding(inventory); + var owner = new CanonicalGameplayIssuerLayoutBootstrapRepository(testSchema.dsl()); + var intent = + owner.beginInitialBootstrapIntent( + UUID.randomUUID(), + descriptor(LAYOUT_VERSION, PARTITION_COUNT, PARTITION_CAPACITY), + sourceCheckpoint(BigInteger.valueOf(7))); + + List intentBefore = + rowImages(testSchema.dsl(), "game_session_canonical_issuer_layout_bootstrap_intent"); + List cohortBefore = + rowImages(testSchema.dsl(), "game_session_canonical_issuer_layout_bootstrap_cohort_row"); + List inventoryBefore = + rowImages(testSchema.dsl(), "game_session_canonical_gameplay_binding_inventory"); + List generationBefore = + rowImages(testSchema.dsl(), "game_session_canonical_binding_generation"); + List transitionBefore = + rowImages(testSchema.dsl(), "game_session_canonical_binding_transition"); + List reservationBefore = + rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_reservation"); + List accountObligationBefore = + rowImages(testSchema.dsl(), "game_session_canonical_binding_account_index_obligation"); + List issuerObligationBefore = + rowImages(testSchema.dsl(), "game_session_canonical_binding_issuer_index_obligation"); + List regionObligationBefore = + rowImages(testSchema.dsl(), "game_session_canonical_binding_region_bridge_obligation"); + List accountControlBefore = + rowImages(testSchema.dsl(), "game_session_canonical_account_coverage_control"); + BigInteger inventoryRevisionBefore = currentInventoryRevision(testSchema.dsl()); + + testSchema + .dsl() + .execute( + "DELETE FROM game_session_canonical_issuer_layout_bootstrap_control " + + "WHERE issuer_id = ?", + ISSUER); + + assertThatThrownBy(() -> prepareActualBinding(inventory, BLOCKED_CHARACTER_ID)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining( + "Issuer bootstrap intent exists without its positive current control row"); + + assertThat( + countRows(testSchema.dsl(), "game_session_canonical_issuer_layout_bootstrap_control")) + .isZero(); + assertThat( + rowImages(testSchema.dsl(), "game_session_canonical_issuer_layout_bootstrap_intent")) + .containsExactlyElementsOf(intentBefore); + assertThat( + rowImages( + testSchema.dsl(), "game_session_canonical_issuer_layout_bootstrap_cohort_row")) + .containsExactlyElementsOf(cohortBefore); + assertThat(rowImages(testSchema.dsl(), "game_session_canonical_gameplay_binding_inventory")) + .containsExactlyElementsOf(inventoryBefore); + assertThat(rowImages(testSchema.dsl(), "game_session_canonical_binding_generation")) + .containsExactlyElementsOf(generationBefore); + assertThat(rowImages(testSchema.dsl(), "game_session_canonical_binding_transition")) + .containsExactlyElementsOf(transitionBefore); + assertThat(rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_reservation")) + .containsExactlyElementsOf(reservationBefore); + assertThat( + rowImages( + testSchema.dsl(), "game_session_canonical_binding_account_index_obligation")) + .containsExactlyElementsOf(accountObligationBefore); + assertThat( + rowImages(testSchema.dsl(), "game_session_canonical_binding_issuer_index_obligation")) + .containsExactlyElementsOf(issuerObligationBefore); + assertThat( + rowImages( + testSchema.dsl(), "game_session_canonical_binding_region_bridge_obligation")) + .containsExactlyElementsOf(regionObligationBefore); + assertThat(rowImages(testSchema.dsl(), "game_session_canonical_account_coverage_control")) + .containsExactlyElementsOf(accountControlBefore); + assertThat(currentInventoryRevision(testSchema.dsl())).isEqualTo(inventoryRevisionBefore); + assertThat(intent.state()) + .isEqualTo(CanonicalGameplayIssuerLayoutBootstrapIntent.State.INITIAL_BOOTSTRAP_INTENT); + } finally { + dropSchema(testSchema.schema()); + } + } + + @Test + void preparationQueuedBeforeBootstrapIntentIsCapturedByTheIntent() throws Exception { + TestSchema testSchema = newTestSchema("gs_issuer_boot_order_prep_"); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + establishActualLegacyDisposition(testSchema.dsl()); + var inventory = new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); + var owner = new CanonicalGameplayIssuerLayoutBootstrapRepository(testSchema.dsl()); + UUID requestId = UUID.randomUUID(); + var descriptor = descriptor(LAYOUT_VERSION, PARTITION_COUNT, PARTITION_CAPACITY); + var source = sourceCheckpoint(BigInteger.valueOf(7)); + CountDownLatch prepareStarted = new CountDownLatch(1); + CountDownLatch intentStarted = new CountDownLatch(1); + + try (Connection blocker = testSchema.dataSource().getConnection()) { + blocker.setAutoCommit(false); + DSL.using(blocker, SQLDialect.POSTGRES) + .fetchSingle( + "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock" + + " WHERE singleton_id = 1 FOR UPDATE"); + + Future preparedFuture = + executor.submit( + () -> { + prepareStarted.countDown(); + return prepareActualBinding(inventory); + }); + assertThat(prepareStarted.await(10, TimeUnit.SECONDS)).isTrue(); + awaitInventoryClockWaiters(testSchema, 1); + + Future intentFuture = + executor.submit( + () -> { + intentStarted.countDown(); + return owner.beginInitialBootstrapIntent(requestId, descriptor, source); + }); + assertThat(intentStarted.await(10, TimeUnit.SECONDS)).isTrue(); + awaitInventoryClockWaiters(testSchema, 2); + + blocker.commit(); + CanonicalGameplayBindingTransitionSnapshot prepared = + preparedFuture.get(30, TimeUnit.SECONDS); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = + intentFuture.get(30, TimeUnit.SECONDS); + assertCapturedPreparationCohort(intent, prepared); + } + } finally { + executor.shutdownNow(); + dropSchema(testSchema.schema()); + } + } + + @Test + void bootstrapIntentQueuedBeforePreparationLeavesNoAllocatedRows() throws Exception { + TestSchema testSchema = newTestSchema("gs_issuer_boot_order_intent_"); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + establishActualLegacyDisposition(testSchema.dsl()); + var inventory = new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); + CanonicalGameplayBindingTransitionSnapshot retainedPreparation = + prepareActualBinding(inventory); + var owner = new CanonicalGameplayIssuerLayoutBootstrapRepository(testSchema.dsl()); + UUID requestId = UUID.randomUUID(); + var descriptor = descriptor(LAYOUT_VERSION, PARTITION_COUNT, PARTITION_CAPACITY); + var source = sourceCheckpoint(BigInteger.valueOf(7)); + int bindingCount = + countRows(testSchema.dsl(), "game_session_canonical_gameplay_binding_inventory"); + int generationCount = + countRows(testSchema.dsl(), "game_session_canonical_binding_generation"); + int transitionCount = + countRows(testSchema.dsl(), "game_session_canonical_binding_transition"); + int reservationCount = + countRows(testSchema.dsl(), "game_session_canonical_issuer_partition_reservation"); + int accountObligationCount = + countRows(testSchema.dsl(), "game_session_canonical_binding_account_index_obligation"); + int issuerObligationCount = + countRows(testSchema.dsl(), "game_session_canonical_binding_issuer_index_obligation"); + int regionObligationCount = + countRows(testSchema.dsl(), "game_session_canonical_binding_region_bridge_obligation"); + int accountControlCount = + countRows(testSchema.dsl(), "game_session_canonical_account_coverage_control"); + CountDownLatch intentStarted = new CountDownLatch(1); + CountDownLatch prepareStarted = new CountDownLatch(1); + + try (Connection blocker = testSchema.dataSource().getConnection()) { + blocker.setAutoCommit(false); + DSL.using(blocker, SQLDialect.POSTGRES) + .fetchSingle( + "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock" + + " WHERE singleton_id = 1 FOR UPDATE"); + + Future intentFuture = + executor.submit( + () -> { + intentStarted.countDown(); + return owner.beginInitialBootstrapIntent(requestId, descriptor, source); + }); + assertThat(intentStarted.await(10, TimeUnit.SECONDS)).isTrue(); + awaitInventoryClockWaiters(testSchema, 1); + + Future prepareFuture = + executor.submit( + () -> { + prepareStarted.countDown(); + try { + return new PreparationAttempt( + prepareActualBinding(inventory, BLOCKED_CHARACTER_ID), null); + } catch (RuntimeException failure) { + return new PreparationAttempt(null, failure); + } + }); + assertThat(prepareStarted.await(10, TimeUnit.SECONDS)).isTrue(); + awaitInventoryClockWaiters(testSchema, 2); + + blocker.commit(); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = + intentFuture.get(30, TimeUnit.SECONDS); + PreparationAttempt preparation = prepareFuture.get(30, TimeUnit.SECONDS); + assertThat(preparation.transition()).isNull(); + assertThat(preparation.failure()) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining( + "Initial issuer-layout bootstrap intent blocks new binding preparation"); + assertCapturedPreparationCohort(intent, retainedPreparation); + assertThat(currentInventoryRevision(testSchema.dsl())) + .isEqualTo(retainedPreparation.inventoryRevision()) + .isEqualTo(intent.inventorySnapshotRevision()); + assertThat(countRows(testSchema.dsl(), "game_session_canonical_gameplay_binding_inventory")) + .isEqualTo(bindingCount); + assertThat(countRows(testSchema.dsl(), "game_session_canonical_binding_generation")) + .isEqualTo(generationCount); + assertThat(countRows(testSchema.dsl(), "game_session_canonical_binding_transition")) + .isEqualTo(transitionCount); + assertThat( + countRows(testSchema.dsl(), "game_session_canonical_issuer_partition_reservation")) + .isEqualTo(reservationCount); + assertThat( + countRows( + testSchema.dsl(), "game_session_canonical_binding_account_index_obligation")) + .isEqualTo(accountObligationCount); + assertThat( + countRows( + testSchema.dsl(), "game_session_canonical_binding_issuer_index_obligation")) + .isEqualTo(issuerObligationCount); + assertThat( + countRows( + testSchema.dsl(), "game_session_canonical_binding_region_bridge_obligation")) + .isEqualTo(regionObligationCount); + assertThat(countRows(testSchema.dsl(), "game_session_canonical_account_coverage_control")) + .isEqualTo(accountControlCount); + var retry = owner.beginInitialBootstrapIntent(requestId, descriptor, source); + assertThat(retry.operationId()).isEqualTo(intent.operationId()); + assertThat(retry.cohortDigest()).isEqualTo(intent.cohortDigest()); + } + } finally { + executor.shutdownNow(); + dropSchema(testSchema.schema()); + } + } + + @Test + void shiftedStoredCohortOrdinalIsRejectedWithoutChangingPendingIntentHeader() { + TestSchema testSchema = newTestSchema("gs_issuer_boot_ordinal_"); + try { + establishActualLegacyDisposition(testSchema.dsl()); + var inventory = new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); + prepareActualBinding(inventory); + var owner = new CanonicalGameplayIssuerLayoutBootstrapRepository(testSchema.dsl()); + var intent = + owner.beginInitialBootstrapIntent( + UUID.randomUUID(), + descriptor(LAYOUT_VERSION, PARTITION_COUNT, PARTITION_CAPACITY), + sourceCheckpoint(BigInteger.valueOf(7))); + assertThat(intent.cohortRows()).isNotEmpty(); + + testSchema + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_layout_bootstrap_cohort_row " + + "SET row_ordinal = row_ordinal + 1000 " + + "WHERE operation_id = ? AND row_ordinal = 0", + intent.operationId()); + + assertThatThrownBy(() -> owner.readCurrentInitialBootstrapIntent(intent.operationId())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("row ordinals are not contiguous from zero"); + assertThat( + testSchema + .dsl() + .fetchSingle( + "SELECT cohort_digest, intent_state FROM " + + "game_session_canonical_issuer_layout_bootstrap_intent " + + "WHERE operation_id = ?", + intent.operationId()) + .get("cohort_digest", String.class)) + .isEqualTo(intent.cohortDigest()); + assertThat( + testSchema + .dsl() + .fetchSingle( + "SELECT intent_state FROM " + + "game_session_canonical_issuer_layout_bootstrap_intent " + + "WHERE operation_id = ?", + intent.operationId()) + .get("intent_state", String.class)) + .isEqualTo("INITIAL_BOOTSTRAP_INTENT"); + assertThat( + testSchema + .dsl() + .fetchSingle( + "SELECT state FROM game_session_canonical_issuer_layout_bootstrap_control " + + "WHERE issuer_id = ?", + ISSUER) + .get("state", String.class)) + .isEqualTo("INITIAL_BOOTSTRAP_INTENT"); + } finally { + dropSchema(testSchema.schema()); + } + } + + @Test + void concurrentDifferentBootstrapRequestsSerializeToOneImmutableIntent() throws Exception { + TestSchema testSchema = newTestSchema("gs_issuer_boot_race_"); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + establishActualLegacyDisposition(testSchema.dsl()); + var inventory = new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); + prepareActualBinding(inventory); + var descriptor = descriptor(LAYOUT_VERSION, PARTITION_COUNT, PARTITION_CAPACITY); + var source = sourceCheckpoint(BigInteger.valueOf(7)); + var ready = new CountDownLatch(2); + var start = new CountDownLatch(1); + Future first = + executor.submit( + () -> attempt(testSchema.dsl(), UUID.randomUUID(), descriptor, source, ready, start)); + Future second = + executor.submit( + () -> attempt(testSchema.dsl(), UUID.randomUUID(), descriptor, source, ready, start)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + Attempt left = first.get(20, TimeUnit.SECONDS); + Attempt right = second.get(20, TimeUnit.SECONDS); + assertThat(List.of(left, right).stream().filter(attempt -> attempt.intent() != null).count()) + .isEqualTo(1L); + assertThat(List.of(left, right).stream().filter(attempt -> attempt.failure() != null).count()) + .isEqualTo(1L); + Attempt failed = left.failure() == null ? right : left; + assertThat(failed.failure()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("different initial issuer-layout bootstrap"); + assertThat( + countRows(testSchema.dsl(), "game_session_canonical_issuer_layout_bootstrap_intent")) + .isEqualTo(1); + assertThat( + countRows(testSchema.dsl(), "game_session_canonical_issuer_layout_bootstrap_control")) + .isEqualTo(1); + } finally { + executor.shutdownNow(); + dropSchema(testSchema.schema()); + } + } + + private static Attempt attempt( + DSLContext dsl, + UUID requestId, + CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor descriptor, + CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint source, + CountDownLatch ready, + CountDownLatch start) { + ready.countDown(); + try { + if (!start.await(10, TimeUnit.SECONDS)) { + return new Attempt(null, new IllegalStateException("test start gate timed out")); + } + var intent = + new CanonicalGameplayIssuerLayoutBootstrapRepository(dsl) + .beginInitialBootstrapIntent(requestId, descriptor, source); + return new Attempt(intent, null); + } catch (RuntimeException failure) { + return new Attempt(null, failure); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + return new Attempt( + null, new IllegalStateException("test worker was interrupted", interrupted)); + } + } + + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor + descriptor(BigInteger version, BigInteger count, BigInteger capacity) { + String encoded = + "issuer-layout-descriptor/v1|" + + ISSUER + + "|" + + version + + "|" + + count + + "|" + + capacity + + "|" + + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY; + return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor( + ISSUER, + version, + count, + capacity, + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY, + encoded.getBytes(StandardCharsets.UTF_8)); + } + + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + sourceCheckpoint(BigInteger issuerGeneration) { + long sequence = issuerGeneration.longValueExact() - 1L; + var event = + AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + UUID.randomUUID().toString(), + UUID.randomUUID().toString(), + AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + ISSUER, + Long.toString(sequence), + ISSUER, + issuerGeneration.toString(), + issuerGeneration.toString(), + "ISSUER_SECURITY_CHANGE")); + byte[] eventBytes = event.canonicalJsonUtf8(); + return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint( + ISSUER, issuerGeneration, eventBytes, eventBytes); + } + + private static CanonicalGameplayBindingTransitionSnapshot prepareActualBinding( + CanonicalGameplayBindingInventoryRepository inventory) { + return prepareActualBinding(inventory, PREPARED_CHARACTER_ID); + } + + private static CanonicalGameplayBindingTransitionSnapshot prepareActualBinding( + CanonicalGameplayBindingInventoryRepository inventory, UUID characterId) { + UUID transitionId = UUID.randomUUID(); + UUID reservationId = UUID.randomUUID(); + UUID reservationFence = UUID.randomUUID(); + UUID issuerCoverageOperationId = UUID.randomUUID(); + var candidate = + new CanonicalGameplayBindingIdentity( + ACCOUNT_ID, + TENANT_ID, + NAMESPACE_ID, + characterId, + "SHARED", + GAME_INSTANCE_ID, + 23L, + UUID.fromString("77777777-7777-4777-8777-777777777777").toString(), + REGION_ID, + BigInteger.valueOf(12), + ISSUER, + BigInteger.valueOf(7), + LAYOUT_VERSION, + PARTITION_COUNT, + PARTITION_CAPACITY); + var reservation = + new CanonicalIssuerReservationFenceEvidence( + reservationId, + reservationFence, + issuerCoverageOperationId, + BigInteger.ONE, + BigInteger.TWO, + BigInteger.ONE); + return inventory.prepare( + new CanonicalGameplayBindingTransitionRequest( + transitionId, UUID.randomUUID(), candidate, reservation, null, null)); + } + + private static void insertReservationOnly( + DSLContext dsl, + CanonicalGameplayBindingIdentity template, + BigInteger revision, + UUID reservationId) { + UUID characterId = UUID.fromString("88888888-8888-4888-8888-888888888888"); + UUID transitionId = UUID.randomUUID(); + UUID fence = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String sessionId = UUID.fromString("99999999-9999-4999-8999-999999999999").toString(); + var bindingRef = + net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef.of( + template.tenantId().toString(), template.gameInstanceId().toString(), sessionId); + BigInteger partitionId = bindingRef.partitionId(template.issuerIndexPartitionCount()); + dsl.execute( + "INSERT INTO game_session_canonical_issuer_partition_reservation" + + " (reservation_id, binding_ref, account_id, tenant_id, game_instance_id," + + " runtime_game_instance_id, session_id, binding_generation, transition_id, issuer_id," + + " issuer_auth_generation, playable_state_namespace_id, character_id," + + " playable_state_scope, region_id, region_epoch, partition_id," + + " issuer_index_layout_version, issuer_index_partition_count," + + " issuer_index_partition_capacity, lifecycle, reservation_fence," + + " issuer_coverage_operation_id, issuer_coverage_operation_fence, coverage_fence," + + " inventory_snapshot_revision, inventory_revision)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + + " 'RESERVED', ?, ?, ?, ?, ?, ?)", + reservationId, + bindingRef.bytes(), + template.accountId(), + template.tenantId(), + template.gameInstanceId(), + template.runtimeGameInstanceId(), + sessionId, + BigDecimal.valueOf(1), + transitionId, + ISSUER, + new BigDecimal(template.issuerAuthGeneration()), + template.playableStateNamespaceId(), + characterId, + template.playableStateScope(), + template.regionId(), + new BigDecimal(template.regionEpoch()), + new BigDecimal(partitionId), + new BigDecimal(template.issuerIndexLayoutVersion()), + new BigDecimal(template.issuerIndexPartitionCount()), + new BigDecimal(template.issuerIndexPartitionCapacity()), + fence, + operationId, + BigDecimal.ONE, + BigDecimal.TWO, + new BigDecimal(revision), + new BigDecimal(revision)); + } + + private static void establishActualLegacyDisposition(DSLContext dsl) { + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); + UUID cohortId = UUID.randomUUID(); + UUID writerFence = UUID.randomUUID(); + var storageIdentity = + new CanonicalGameplayLegacyMigrationStorageIdentity( + "controlled-cluster-uid", + "controlled-namespace-uid", + "controlled-producer-pod-uid", + "controlled-container-id", + "controlled-node-uid", + "123456789", + 42L, + "controlled-postgres-volume-uid", + "controlled-redis-run-id", + "controlled-redis-volume-uid"); + var fencedCohort = + new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { + @Override + public UUID cohortId() { + return cohortId; + } + + @Override + public UUID legacyWriterFence() { + return writerFence; + } + + @Override + public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + return storageIdentity; + } + + @Override + public void requireStillFenced( + CanonicalGameplayLegacyMigrationStorageIdentity expectedIdentity) { + if (!storageIdentity.equals(expectedIdentity)) { + throw new IllegalStateException("Controlled fixture storage identity changed"); + } + } + }; + var owner = + new CanonicalGameplayLegacyMigrationOwner( + migration, + inventory, + () -> fencedCohort, + ignored -> + new CanonicalGameplayLegacyMigrationSourceSnapshot( + EnumSet.of( + Family.TENANT_SESSION_CONTEXT, + Family.SESSION_ALIAS_CONTEXT, + Family.GAMEPLAY_IDENTITY_CONTEXT, + Family.GAMEPLAY_NAME_CONTEXT, + Family.MOVEMENT_EFFECT, + Family.DURABLE_EFFECT), + List.of()), + new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { + @Override + public void rebuildExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignoredCohort, + CanonicalGameplayLegacyMigrationSourceSnapshot source, + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot + canonical) { + assertThat(canonical.bindings()).isEmpty(); + assertThat(canonical.reservations()).isEmpty(); + } + + @Override + public CanonicalGameplayLegacyMigrationReadback readBackExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignoredCohort, + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot + canonical) { + assertThat(canonical.bindings()).isEmpty(); + return new CanonicalGameplayLegacyMigrationReadback( + List.of(), List.of(), List.of(), List.of()); + } + }); + assertThat(owner.migrate().state()) + .isEqualTo(CanonicalGameplayLegacyMigrationOperation.State.VERIFIED); + } + + private static TestSchema newTestSchema(String prefix) { + String schema = prefix + 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(); + return new TestSchema(schema, dataSource, DSL.using(dataSource, SQLDialect.POSTGRES)); + } + + private static DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + String jdbcUrl = postgres.getJdbcUrl(); + String separator = jdbcUrl.contains("?") ? "&" : "?"; + dataSource.setUrl(jdbcUrl + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } + + private static void dropSchema(String schema) { + try (Connection connection = dataSource("public").getConnection()) { + DSL.using(connection, SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } catch (SQLException failure) { + throw new IllegalStateException( + "Could not drop the owned issuer-bootstrap test schema", failure); + } + } + + private static int countRows(DSLContext dsl, String tableName) { + return dsl.fetchCount(DSL.table(tableName)); + } + + private static BigInteger currentInventoryRevision(DSLContext dsl) { + BigDecimal revision = + Objects.requireNonNull( + dsl.fetchSingle( + "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock" + + " WHERE singleton_id = 1") + .get("inventory_revision", BigDecimal.class), + "inventory clock row must exist"); + return revision.toBigIntegerExact(); + } + + private static void assertCapturedPreparationCohort( + CanonicalGameplayIssuerLayoutBootstrapIntent intent, + CanonicalGameplayBindingTransitionSnapshot prepared) { + String bindingRefHex = HexFormat.of().formatHex(prepared.bindingRef().bytes()); + String transitionId = prepared.transitionId().toString(); + assertThat(intent.inventorySnapshotRevision()).isEqualTo(prepared.inventoryRevision()); + assertThat(intent.cohortRows()).hasSize(6); + assertThat(intent.cohortRows()) + .allSatisfy( + row -> + assertThat(row.sourceInventoryRevision()).isEqualTo(prepared.inventoryRevision())); + assertThat(intent.cohortRows()) + .filteredOn( + row -> row.kind() == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.BINDING) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceKey) + .containsExactly(bindingRefHex); + assertThat(intent.cohortRows()) + .filteredOn( + row -> row.kind() == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.TRANSITION) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceKey) + .containsExactly(transitionId); + assertThat(intent.cohortRows()) + .filteredOn( + row -> + row.kind() == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.RESERVATION) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceKey) + .containsExactly(prepared.issuerReservationId().toString()); + assertThat(intent.cohortRows()) + .filteredOn( + row -> + row.kind() + == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.ACCOUNT_OBLIGATION) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceKey) + .containsExactly(transitionId + ":0"); + assertThat(intent.cohortRows()) + .filteredOn( + row -> + row.kind() + == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.ISSUER_OBLIGATION) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceKey) + .containsExactly(bindingRefHex + ":" + transitionId); + assertThat(intent.cohortRows()) + .filteredOn( + row -> + row.kind() + == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.REGION_OBLIGATION) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceKey) + .containsExactly(transitionId); + } + + private static List rowImages(DSLContext dsl, String tableName) { + return dsl.fetch( + "SELECT to_jsonb(retained_row)::text AS row_image FROM " + + tableName + + " retained_row ORDER BY to_jsonb(retained_row)::text") + .getValues("row_image", String.class); + } + + private static void awaitInventoryClockWaiters(TestSchema testSchema, long expectedWaiters) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(20); + long observedWaiters = 0; + do { + observedWaiters = + Objects.requireNonNull( + testSchema + .dsl() + .fetchSingle( + "SELECT count(DISTINCT activity.pid) AS waiting_count " + + "FROM pg_stat_activity activity " + + "JOIN pg_locks relation_lock ON relation_lock.pid = activity.pid " + + "WHERE activity.wait_event_type = 'Lock' " + + "AND activity.query LIKE '%SELECT inventory_revision FROM " + + "game_session_canonical_binding_inventory_clock%' " + + "AND relation_lock.relation = to_regclass(?) " + + "AND relation_lock.mode = 'RowShareLock' AND relation_lock.granted", + testSchema.schema() + ".game_session_canonical_binding_inventory_clock") + .get("waiting_count", Long.class), + "PostgreSQL lock waiter count"); + if (observedWaiters == expectedWaiters) return; + if (observedWaiters > expectedWaiters) { + throw new AssertionError( + "Observed more inventory-clock waiters than the controlled queue: " + observedWaiters); + } + Thread.onSpinWait(); + Thread.yield(); + } while (System.nanoTime() < deadline); + throw new AssertionError( + "Timed out waiting for " + + expectedWaiters + + " PostgreSQL inventory-clock waiters; observed " + + observedWaiters); + } + + private record TestSchema(String schema, DriverManagerDataSource dataSource, DSLContext dsl) {} + + private record Attempt( + CanonicalGameplayIssuerLayoutBootstrapIntent intent, RuntimeException failure) {} + + private record PreparationAttempt( + CanonicalGameplayBindingTransitionSnapshot transition, RuntimeException failure) {} +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerMemberV2ValueCodecTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerMemberV2ValueCodecTest.java new file mode 100644 index 0000000000..e9e9f042d2 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerMemberV2ValueCodecTest.java @@ -0,0 +1,438 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +import org.junit.jupiter.api.Test; + +class CanonicalGameplayIssuerMemberV2ValueCodecTest { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final BigInteger LARGE = new BigInteger("9007199254740997"); + + @Test + void roundTripsCompleteTupleAndCountersBeyondJavaScriptSafeInteger() { + CanonicalGameplayIssuerMemberV2Value value = fixture(); + + byte[] encoded = CanonicalGameplayIssuerMemberV2Codec.encode(value); + CanonicalGameplayIssuerMemberV2Value decoded = + CanonicalGameplayIssuerMemberV2Codec.decode(encoded); + + assertThat(decoded).isEqualTo(value); + assertThat(decoded.bindingGeneration()).isEqualTo(LARGE); + assertThat(decoded.anchor().issuerInventorySnapshotRevision()) + .isEqualTo(LARGE.add(BigInteger.valueOf(12))); + assertThat(decoded.memberOperation().coverageGeneration()) + .isEqualTo(LARGE.add(BigInteger.valueOf(20))); + assertThat(new String(encoded, StandardCharsets.UTF_8)).contains("\"schemaVersion\":2"); + } + + @Test + void encoderRefusesCountersBeyondTheLocalReaderLimit() { + CanonicalGameplayIssuerMemberV2Value original = fixture(); + BigInteger oversizedFence = + new BigInteger("1".repeat(CanonicalGameplayIssuerMemberV2Codec.MAX_COUNTER_DIGITS + 1)); + CanonicalGameplayIssuerMemberV2Value.LocalMemberOperation operation = + new CanonicalGameplayIssuerMemberV2Value.LocalMemberOperation( + original.memberOperation().operationId(), + oversizedFence, + original.memberOperation().coverageGeneration()); + CanonicalGameplayIssuerMemberV2Value value = withMemberOperation(original, operation); + + assertThatThrownBy(() -> CanonicalGameplayIssuerMemberV2Codec.encode(value)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("256-digit"); + assertThat(value).isEqualTo(withMemberOperation(original, operation)); + assertThat(value.hashCode()).isEqualTo(withMemberOperation(original, operation).hashCode()); + } + + @Test + void equalityAndHashCodeDoNotDependOnTheCodecByteLimit() { + CanonicalGameplayIssuerMemberV2Value original = fixture(); + byte[] oversizedDescriptor = new byte[CanonicalGameplayIssuerMemberV2Codec.MAX_VALUE_BYTES + 1]; + var leftLayout = + new CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor( + original.owner().issuerId(), + original.owner().issuerIndexLayoutVersion(), + original.owner().issuerIndexPartitionCount(), + original.owner().issuerIndexPartitionCapacity(), + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY, + oversizedDescriptor, + CanonicalGameplayIssuerMemberV2Codec.sha256(oversizedDescriptor)); + var rightLayout = + new CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor( + original.owner().issuerId(), + original.owner().issuerIndexLayoutVersion(), + original.owner().issuerIndexPartitionCount(), + original.owner().issuerIndexPartitionCapacity(), + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY, + oversizedDescriptor.clone(), + CanonicalGameplayIssuerMemberV2Codec.sha256(oversizedDescriptor)); + CanonicalGameplayIssuerMemberV2Value left = withLayout(original, leftLayout); + CanonicalGameplayIssuerMemberV2Value right = withLayout(original, rightLayout); + + assertThatThrownBy(() -> CanonicalGameplayIssuerMemberV2Codec.encode(left)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("64 KiB"); + assertThat(left).isEqualTo(right); + assertThat(left.hashCode()).isEqualTo(right.hashCode()); + assertThat(left).isNotEqualTo(original); + } + + @Test + void sameBindingWithDifferentConsistentAnchorOrReservationRemainsSeparateAfterDecode() { + CanonicalGameplayIssuerMemberV2Value original = fixture(); + CanonicalGameplayIssuerMemberV2Value.Anchor changedAnchor = + new CanonicalGameplayIssuerMemberV2Value.Anchor( + original.anchor().issuerCoverageOperationId(), + original.anchor().operationFence(), + original.anchor().coverageFence(), + original.anchor().issuerInventorySnapshotRevision().add(BigInteger.ONE)); + CanonicalIssuerPartitionReservation changedReservation = + new CanonicalIssuerPartitionReservation( + original.reservation().reservationId(), + original.owner(), + original.bindingGeneration(), + original.reservation().transitionId(), + original.reservation().partitionId(), + original.reservation().lifecycle(), + original.reservation().reservationFence(), + changedAnchor.issuerCoverageOperationId(), + changedAnchor.operationFence(), + changedAnchor.coverageFence(), + changedAnchor.issuerInventorySnapshotRevision(), + original.reservation().inventoryRevision()); + CanonicalGameplayIssuerMemberV2Value anotherAnchor = + copy(original, changedReservation, changedAnchor); + CanonicalIssuerPartitionReservation changedLifecycle = + new CanonicalIssuerPartitionReservation( + original.reservation().reservationId(), + original.owner(), + original.bindingGeneration(), + original.reservation().transitionId(), + original.reservation().partitionId(), + CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING, + original.reservation().reservationFence(), + original.reservation().issuerCoverageOperationId(), + original.reservation().issuerCoverageOperationFence(), + original.reservation().coverageFence(), + original.reservation().inventorySnapshotRevision(), + original.reservation().inventoryRevision()); + CanonicalGameplayIssuerMemberV2Value anotherReservation = + copy(original, changedLifecycle, original.anchor()); + + assertThat(anotherAnchor.owner()).isEqualTo(original.owner()); + assertThat(anotherAnchor).isNotEqualTo(original); + assertThat(anotherReservation).isNotEqualTo(original); + byte[] anotherAnchorBytes = CanonicalGameplayIssuerMemberV2Codec.encode(anotherAnchor); + assertThat(anotherAnchorBytes) + .isNotEqualTo(CanonicalGameplayIssuerMemberV2Codec.encode(original)); + assertThat(CanonicalGameplayIssuerMemberV2Codec.decode(anotherAnchorBytes)) + .isEqualTo(anotherAnchor) + .isNotEqualTo(original); + } + + @Test + void allRetainedByteAccessorsAreDefensiveCopies() { + CanonicalGameplayIssuerMemberV2Value value = fixture(); + byte[] descriptor = value.layoutDescriptor().exactDescriptorBytes(); + byte[] checkpoint = value.sourceCheckpoint().exactCheckpointBytes(); + byte[] sourceEvent = value.sourceCheckpoint().latestIssuerEventBytes(); + byte descriptorFirst = descriptor[0]; + byte checkpointFirst = checkpoint[0]; + byte sourceEventFirst = sourceEvent[0]; + + descriptor[0] = (byte) (descriptor[0] ^ 0x7f); + checkpoint[0] = (byte) (checkpoint[0] ^ 0x7f); + sourceEvent[0] = (byte) (sourceEvent[0] ^ 0x7f); + + assertThat(value.layoutDescriptor().exactDescriptorBytes()[0]).isEqualTo(descriptorFirst); + assertThat(value.sourceCheckpoint().exactCheckpointBytes()[0]).isEqualTo(checkpointFirst); + assertThat(value.sourceCheckpoint().latestIssuerEventBytes()[0]).isEqualTo(sourceEventFirst); + } + + @Test + void nullableSourceEventFieldsAreBothEncodedAsExplicitNull() { + CanonicalGameplayIssuerMemberV2Value original = fixture(); + byte[] checkpointBytes = "checkpoint-without-event".getBytes(StandardCharsets.UTF_8); + var source = + new CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint( + original.owner().issuerId(), + original.owner().issuerAuthGeneration(), + checkpointBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(checkpointBytes), + null, + null); + CanonicalGameplayIssuerMemberV2Value value = + new CanonicalGameplayIssuerMemberV2Value( + original.owner(), + original.bindingGeneration(), + original.reservation(), + original.anchor(), + original.memberOperation(), + original.issuerControlEpoch(), + original.layoutDescriptor(), + source, + original.incarnation()); + + byte[] encoded = CanonicalGameplayIssuerMemberV2Codec.encode(value); + CanonicalGameplayIssuerMemberV2Value decoded = + CanonicalGameplayIssuerMemberV2Codec.decode(encoded); + + assertThat(new String(encoded, StandardCharsets.UTF_8)) + .contains("\"sourceEventBytes\":null", "\"sourceEventDigest\":null"); + assertThat(decoded.sourceCheckpoint().latestIssuerEventBytes()).isNull(); + assertThat(decoded.sourceCheckpoint().latestIssuerEventDigest()).isNull(); + } + + @Test + void rejectsLegacyUnknownDuplicateNoncanonicalAndMalformedInputs() throws Exception { + byte[] canonical = CanonicalGameplayIssuerMemberV2Codec.encode(fixture()); + ObjectNode root = (ObjectNode) JSON.readTree(canonical); + + ObjectNode schemaOne = root.deepCopy(); + schemaOne.put("schemaVersion", 1); + assertRejected(canonical(schemaOne)); + + ObjectNode extraField = root.deepCopy(); + extraField.put("extra", "not permitted"); + assertRejected(canonical(extraField)); + + String duplicate = + new String(canonical, StandardCharsets.UTF_8) + .replace("\"schemaVersion\":2", "\"schemaVersion\":2,\"schemaVersion\":2"); + assertRejected(duplicate.getBytes(StandardCharsets.UTF_8)); + + ObjectNode leadingZero = root.deepCopy(); + leadingZero.put("bindingGeneration", "01"); + assertRejected(canonical(leadingZero)); + + ObjectNode oversizedCounter = root.deepCopy(); + oversizedCounter.put( + "bindingGeneration", + "1".repeat(CanonicalGameplayIssuerMemberV2Codec.MAX_COUNTER_DIGITS + 1)); + assertRejected(canonical(oversizedCounter)); + + byte[] malformedUtf8 = new byte[] {'{', '"', (byte) 0xc3, '"', '}', (byte) 0x80}; + assertRejected(malformedUtf8); + assertRejected( + "[".repeat(12).concat("0").concat("]".repeat(12)).getBytes(StandardCharsets.UTF_8)); + assertRejected( + Arrays.copyOf(canonical, CanonicalGameplayIssuerMemberV2Codec.MAX_VALUE_BYTES + 1)); + assertRejected( + (new String(canonical, StandardCharsets.UTF_8) + " ").getBytes(StandardCharsets.UTF_8)); + assertRejected( + (new String(canonical, StandardCharsets.UTF_8) + "{}").getBytes(StandardCharsets.UTF_8)); + + ObjectNode unpaddedBytes = root.deepCopy(); + ObjectNode layout = (ObjectNode) unpaddedBytes.get("layout"); + layout.put("descriptorBytes", "YQ"); + assertRejected(canonical(unpaddedBytes)); + + ObjectNode mismatchedDigest = root.deepCopy(); + ((ObjectNode) mismatchedDigest.get("layout")).put("descriptorDigest", digest("other")); + assertRejected(canonical(mismatchedDigest)); + } + + @Test + void constructorRejectsAnAnchorThatDoesNotMatchItsReservation() { + CanonicalGameplayIssuerMemberV2Value original = fixture(); + CanonicalGameplayIssuerMemberV2Value.Anchor mismatchedAnchor = + new CanonicalGameplayIssuerMemberV2Value.Anchor( + original.anchor().issuerCoverageOperationId(), + original.anchor().operationFence(), + original.anchor().coverageFence().add(BigInteger.ONE), + original.anchor().issuerInventorySnapshotRevision()); + + assertThatThrownBy( + () -> + new CanonicalGameplayIssuerMemberV2Value( + original.owner(), + original.bindingGeneration(), + original.reservation(), + mismatchedAnchor, + original.memberOperation(), + original.issuerControlEpoch(), + original.layoutDescriptor(), + original.sourceCheckpoint(), + original.incarnation())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("complete installed anchor tuple"); + } + + static CanonicalGameplayIssuerMemberV2Value fixture() { + CanonicalGameplayBindingIdentity owner = + new CanonicalGameplayBindingIdentity( + uuid(1), + uuid(2), + uuid(3), + uuid(4), + "SHARED", + uuid(5), + 420L, + uuid(6).toString(), + uuid(7), + LARGE.add(BigInteger.valueOf(5)), + GameSessionAccountDelegationProfile.ISSUER, + LARGE.add(BigInteger.valueOf(6)), + BigInteger.valueOf(9), + BigInteger.valueOf(16), + BigInteger.valueOf(128)); + byte[] descriptorBytes = "issuer-layout-descriptor".getBytes(StandardCharsets.UTF_8); + CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor layout = + new CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor( + owner.issuerId(), + owner.issuerIndexLayoutVersion(), + owner.issuerIndexPartitionCount(), + owner.issuerIndexPartitionCapacity(), + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY, + descriptorBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(descriptorBytes)); + byte[] checkpointBytes = "account-issuer-checkpoint".getBytes(StandardCharsets.UTF_8); + byte[] sourceEventBytes = "account-issuer-source-event".getBytes(StandardCharsets.UTF_8); + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint source = + new CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint( + owner.issuerId(), + owner.issuerAuthGeneration(), + checkpointBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(checkpointBytes), + sourceEventBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(sourceEventBytes)); + CanonicalGameplayIssuerMemberV2Value.Anchor anchor = + new CanonicalGameplayIssuerMemberV2Value.Anchor( + uuid(20), + LARGE.add(BigInteger.valueOf(10)), + LARGE.add(BigInteger.valueOf(11)), + LARGE.add(BigInteger.valueOf(12))); + UUID transitionId = uuid(30); + CanonicalGameplayIssuerMemberV2Value.LocalMemberOperation operation = + new CanonicalGameplayIssuerMemberV2Value.LocalMemberOperation( + uuid(33), LARGE.add(BigInteger.valueOf(13)), LARGE.add(BigInteger.valueOf(20))); + CanonicalIssuerPartitionReservation reservation = + new CanonicalIssuerPartitionReservation( + uuid(31), + owner, + LARGE, + transitionId, + owner.bindingRef().partitionId(owner.issuerIndexPartitionCount()), + CanonicalIssuerPartitionReservation.Lifecycle.BOUND, + uuid(32), + anchor.issuerCoverageOperationId(), + anchor.operationFence(), + anchor.coverageFence(), + anchor.issuerInventorySnapshotRevision(), + LARGE.add(BigInteger.valueOf(14))); + CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence deployment = + new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "coordination-prod", + "deployment-21", + List.of("coord-a", "coord-b"), + "redis-build-7", + "lua-registry-4", + digest("lua-registry"), + "READY", + "boot-13", + "startup-8", + "storage-5", + "aof-3"); + CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation = + new CanonicalGameplayIssuerMemberV2Value.Incarnation( + "workload=gamesession;namespace=game-session", + digest("attestation"), + deployment, + digest("coord-ops-ro-acl"), + digest("coord-redis-config")); + return new CanonicalGameplayIssuerMemberV2Value( + owner, + LARGE, + reservation, + anchor, + operation, + LARGE.add(BigInteger.valueOf(15)), + layout, + source, + incarnation); + } + + private static CanonicalGameplayIssuerMemberV2Value copy( + CanonicalGameplayIssuerMemberV2Value original, + CanonicalIssuerPartitionReservation reservation, + CanonicalGameplayIssuerMemberV2Value.Anchor anchor) { + return new CanonicalGameplayIssuerMemberV2Value( + original.owner(), + original.bindingGeneration(), + reservation, + anchor, + original.memberOperation(), + original.issuerControlEpoch(), + original.layoutDescriptor(), + original.sourceCheckpoint(), + original.incarnation()); + } + + private static CanonicalGameplayIssuerMemberV2Value withMemberOperation( + CanonicalGameplayIssuerMemberV2Value original, + CanonicalGameplayIssuerMemberV2Value.LocalMemberOperation memberOperation) { + return new CanonicalGameplayIssuerMemberV2Value( + original.owner(), + original.bindingGeneration(), + original.reservation(), + original.anchor(), + memberOperation, + original.issuerControlEpoch(), + original.layoutDescriptor(), + original.sourceCheckpoint(), + original.incarnation()); + } + + private static CanonicalGameplayIssuerMemberV2Value withLayout( + CanonicalGameplayIssuerMemberV2Value original, + CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor layoutDescriptor) { + return new CanonicalGameplayIssuerMemberV2Value( + original.owner(), + original.bindingGeneration(), + original.reservation(), + original.anchor(), + original.memberOperation(), + original.issuerControlEpoch(), + layoutDescriptor, + original.sourceCheckpoint(), + original.incarnation()); + } + + private static byte[] canonical(ObjectNode object) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(object)); + } + + private static void assertRejected(byte[] encoded) { + assertThatThrownBy(() -> CanonicalGameplayIssuerMemberV2Codec.decode(encoded)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static UUID uuid(long suffix) { + return UUID.fromString(String.format("00000000-0000-0000-0000-%012d", suffix)); + } + + private static String digest(String input) { + try { + return "sha256:" + + java.util.HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(input.getBytes(StandardCharsets.UTF_8))); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerRedisKeysTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerRedisKeysTest.java new file mode 100644 index 0000000000..1dad8f16eb --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerRedisKeysTest.java @@ -0,0 +1,120 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; +import org.junit.jupiter.api.Test; + +class CanonicalGameplayIssuerRedisKeysTest { + @Test + void bindingRefVectorsUseThePublishedUnsignedSha256Mapping() { + var countOne = layout(BigInteger.ONE, BigInteger.ONE); + var countSixteen = layout(BigInteger.ONE, BigInteger.valueOf(16)); + CanonicalGameplayBindingRef ascii = + CanonicalGameplayBindingRef.of("tenant-01", "instance-01", "session-01"); + CanonicalGameplayBindingRef delimiter = + CanonicalGameplayBindingRef.of("tenant/01", "game:01", "session|01"); + + assertThat(new String(ascii.bytes(), StandardCharsets.UTF_8)) + .isEqualTo("13:bindingRef/v19:tenant-0111:instance-0110:session-01"); + assertThat(sha256(ascii.bytes())) + .isEqualTo("43f08f503d85155c8bbc4501f14f496f7b35fa334b875382da86831251722565"); + assertThat(ascii.partitionId(BigInteger.ONE)).isEqualTo(BigInteger.ZERO); + assertThat(ascii.partitionId(BigInteger.valueOf(16))).isEqualTo(BigInteger.valueOf(5)); + assertThat(sha256(delimiter.bytes())) + .isEqualTo("89e8ba42d8f2fc0525c5b7ac2363528c1cbe7d00fc968b7ff95118da3443413a"); + assertThat(delimiter.partitionId(BigInteger.valueOf(16))).isEqualTo(BigInteger.TEN); + assertThat( + CanonicalGameplayIssuerRedisKeys.forBindingReference(countOne, ascii, BigInteger.ZERO)) + .endsWith(":" + GameSessionAccountDelegationProfile.ISSUER + ":0"); + assertThat( + CanonicalGameplayIssuerRedisKeys.forBindingReference( + countSixteen, ascii, BigInteger.valueOf(5))) + .endsWith(":" + GameSessionAccountDelegationProfile.ISSUER + ":5"); + assertThat( + CanonicalGameplayIssuerRedisKeys.forBindingReference( + countSixteen, delimiter, BigInteger.TEN)) + .endsWith(":" + GameSessionAccountDelegationProfile.ISSUER + ":10"); + } + + @Test + void keyTagPinsLayoutVersionIssuerAndPartitionWithoutTenantMixing() { + var versionOne = layout(BigInteger.ONE, BigInteger.valueOf(16)); + var versionTwo = layout(BigInteger.TWO, BigInteger.valueOf(16)); + String firstPartition = + CanonicalGameplayIssuerRedisKeys.forPartition(versionOne, BigInteger.ZERO); + String otherPartition = + CanonicalGameplayIssuerRedisKeys.forPartition(versionOne, BigInteger.ONE); + String otherVersion = + CanonicalGameplayIssuerRedisKeys.forPartition(versionTwo, BigInteger.ZERO); + + assertThat(firstPartition) + .startsWith("session:game:index:issuer:{il-v1-") + .endsWith(":" + GameSessionAccountDelegationProfile.ISSUER + ":0"); + assertThat(firstPartition).doesNotContain("tenant"); + assertThat(CanonicalGameplayIssuerRedisKeys.layoutTag(versionOne, BigInteger.ZERO)) + .matches("il-v1-[0-9a-f]{64}") + .isNotEqualTo(CanonicalGameplayIssuerRedisKeys.layoutTag(versionOne, BigInteger.ONE)) + .isNotEqualTo(CanonicalGameplayIssuerRedisKeys.layoutTag(versionTwo, BigInteger.ZERO)); + assertThat(otherPartition).isNotEqualTo(firstPartition); + assertThat(otherVersion).isNotEqualTo(firstPartition); + } + + @Test + void memberKeyUsesItsPinnedLayoutAndReservationPartition() { + CanonicalGameplayIssuerMemberV2Value member = + CanonicalGameplayIssuerMemberV2ValueCodecTest.fixture(); + + assertThat(CanonicalGameplayIssuerRedisKeys.forMember(member)) + .isEqualTo( + CanonicalGameplayIssuerRedisKeys.forPartition( + member.layoutDescriptor(), member.reservation().partitionId())); + assertThat(CanonicalGameplayIssuerRedisKeys.forMember(member)) + .doesNotContain(member.owner().tenantId().toString()); + } + + @Test + void rejectsMismatchedOrOutOfLayoutPartitions() { + var layout = layout(BigInteger.ONE, BigInteger.valueOf(16)); + CanonicalGameplayBindingRef bindingRef = + CanonicalGameplayBindingRef.of("tenant-01", "instance-01", "session-01"); + + assertThatThrownBy( + () -> + CanonicalGameplayIssuerRedisKeys.forBindingReference( + layout, bindingRef, BigInteger.valueOf(6))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> CanonicalGameplayIssuerRedisKeys.forPartition(layout, BigInteger.valueOf(16))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> CanonicalGameplayIssuerRedisKeys.forPartition(layout, BigInteger.valueOf(-1))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor layout( + BigInteger version, BigInteger count) { + byte[] bytes = ("layout-v" + version).getBytes(StandardCharsets.UTF_8); + return new CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor( + GameSessionAccountDelegationProfile.ISSUER, + version, + count, + BigInteger.valueOf(32), + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY, + bytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(bytes)); + } + + private static String sha256(byte[] bytes) { + try { + return java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } +} From 57846ef3bf4e7e202a70414eecfb3edd060dc8ee Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:09:52 +1300 Subject: [PATCH 02/34] Preserve original issuer reservation coverage independently of bootstrap anchor --- .../architecture/system-architecture-redis.md | 10 +- .../system-architecture-session-behavior.md | 2 +- .../player-access-and-session.md | 2 +- .../CanonicalGameplayIssuerMemberV2Codec.java | 39 ++++- .../CanonicalGameplayIssuerMemberV2Value.java | 10 +- ...outBootstrapRepositoryIntegrationTest.java | 145 +++++++++++++++++ ...lGameplayIssuerMemberV2ValueCodecTest.java | 152 ++++++++++++------ 7 files changed, 293 insertions(+), 67 deletions(-) diff --git a/design/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index 73713df21d..048d94c86c 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -350,7 +350,9 @@ value: { }, reservation: { reservationId, bindingRef, transitionId, partitionId, - lifecycle, reservationFence, inventoryRevision + lifecycle, reservationFence, inventoryRevision, + issuerCoverageOperationId, issuerCoverageOperationFence, + coverageFence, inventorySnapshotRevision }, anchor: { issuerCoverageOperationId, operationFence, coverageFence, @@ -367,7 +369,9 @@ value: { The value is a closed, bounded RFC 8785 canonical JSON object. Except for the literal numeric `schemaVersion: 2`, counters use canonical unsigned decimal strings; every counter is positive except the zero-based `partitionId`. Implementations preserve values beyond binary floating-point precision. UUIDs and identifiers retain their exact canonical spelling, and bytes use canonical padded Base64. `sourceEventBytes` and `sourceEventDigest` are both explicit `null` only when the exact qualified Account checkpoint has no corresponding event. Unknown or duplicate fields, unsupported versions, malformed UTF-8, noncanonical bytes, inconsistent owner/partition/layout references, and resource-bound violations fail closed; parser limits never authorize normalization or truncation. -The full owner identity, immutable authorized layout descriptor, and Account source bytes must agree with the original reservation and anchor. `anchor.issuerInventorySnapshotRevision` is the complete immutable issuer inventory revision; `reservation.inventoryRevision` is that reservation's durable transition revision, and they are not interchangeable. The anchor operation fence, coverage fence, binding-local member-operation fence and `issuerControlEpoch` retain separate evidence domains. The anchor operation and coverage fences have distinct values; equality between counters from different domains does not merge their authority or imply an ordering. `memberOperation.coverageGeneration` is concrete only after its issuing owner allocates it; a parser, bootstrap preparation, or caller cannot invent it. The value retains the complete stable incarnation binding, including every field of accepted `targetDeploymentEvidence/v1`, not only its digest. Fresh observation nonces, observation times, and signing-key selection are not stable row identity; the protected current-observation owner validates them at each decisive boundary. See [Redis Operations and Access](./system-architecture-redis-ops-access.md) for protected evidence ownership. +The value preserves two distinct issuer-coverage tuples. `reservation.issuerCoverageOperationId`, `issuerCoverageOperationFence`, `coverageFence`, and `inventorySnapshotRevision` are copied unchanged from the original durable reservation. The four fields under `anchor` identify the issuer coverage anchor carried by this v2 value; they are not a replacement for or reconstruction of the original reservation tuple. No equality between those tuples is required. `anchor.issuerInventorySnapshotRevision` is the complete immutable issuer inventory revision; `reservation.inventoryRevision` is that reservation's durable transition revision, and they are not interchangeable. The full owner identity, immutable authorized layout descriptor, and Account source bytes must match the exact binding and anchor evidence; the reservation must independently match its original durable source. Before a physical bootstrap write, the owner proves that this original reservation belongs to the frozen complete issuer cohort and links it to the exact bootstrap operation and fences. Shape parsing alone grants no authority. + +Mutation, retry, readback, and cleanup preserve and exact-compare both complete coverage tuples, the original reservation identity, owner, transition, layout, partition, lifecycle, fence and revision, and the local member-operation linkage. Same binding identity with different original reservation provenance, anchor, or operation linkage is a conflict. The owner never reconstructs the original tuple from the anchor, rewrites or re-anchors the original SQL reservation, or invents a member generation. The anchor operation fence, coverage fence, binding-local member-operation fence and `issuerControlEpoch` retain separate evidence domains. The anchor operation and coverage fences retain their distinct values. Equality between counters from different domains does not merge their authority or imply an ordering. `memberOperation.coverageGeneration` is concrete only after its issuing owner allocates it; a parser, bootstrap preparation, or caller cannot invent it. The value retains the complete stable incarnation binding, including every field of accepted `targetDeploymentEvidence/v1`, not only its digest. Fresh observation nonces, observation times, and signing-key selection are not stable row identity; the protected current-observation owner validates them at each decisive boundary. See [Redis Operations and Access](./system-architecture-redis-ops-access.md) for protected evidence ownership. The exact `bindingRef` field identity and canonical partition key remain unchanged. Physical schema-v1 values are retained historical or legacy evidence and never qualify a v2 member, retry, readback, or cleanup. Encountering v1 requires the canonical fenced complete-inventory rebuild or migration; an empty-key assumption, SQL acknowledgement, or hidden second-key witness cannot upgrade it. The same binding under a different anchor, reservation, local operation, issuer-control epoch, or storage incarnation is a conflict, not an idempotent retry. Mutation, exact readback, and cleanup compare the complete v2 value at the one issuer-partition key and permit only the defined original-operation transition. @@ -431,7 +435,7 @@ Ordinary binding-local `NEW` may use the global issuer index only under a positi The issuer owner establishes that anchor only from an authorized immutable layout descriptor, exact current Account source checkpoint, verified legacy disposition, and complete durable issuer inventory including reservations and unresolved obligations. It must build or verify every required partition and reservation, prove local and aggregate capacity, and retain same-attempt readback before guarded publication. An empty physical index, absent or empty inventory result, or conformance-vector count is not initialization authority; unresolved legacy identities remain retained and fenced. Controlled descriptor, source, and incarnation inputs establish only local algorithm behavior, not operational bootstrap authority. -The physical v2 HASH value above is a projection, not the installed anchor or an issuer binding-local acknowledgement. The separate issuer acknowledgement must be explicitly versioned and bind the complete anchor, exact local transition/reservation, member and capacity readbacks, current control/incarnation evidence, and owner-issued per-transition generation. Neither physical-row parsing nor the account `accountIndexAcknowledgement` schema v2 can manufacture that result; the account acknowledgement and its CLOSED barrier receipt establish no issuer anchor or issuer `INSTALLED`/`OPEN` state. The final tenant-local CAS must positively compare the exact issuer barrier `OPEN` state and owner epoch/incarnation with the original candidate and required Account, issuer, and region evidence; global issuer-index and capacity keys never enter tenant-local Lua. +The physical v2 HASH value above is a projection, not the installed anchor or an issuer binding-local acknowledgement. Its anchor tuple and preserved original reservation tuple remain separate even when a bootstrap operation links both to the same frozen cohort. The separate issuer acknowledgement must be explicitly versioned and bind the complete anchor, exact local transition/reservation, member and capacity readbacks, current control/incarnation evidence, and owner-issued per-transition generation. Neither physical-row parsing nor the account `accountIndexAcknowledgement` schema v2 can manufacture that result; the account acknowledgement and its CLOSED barrier receipt establish no issuer anchor or issuer `INSTALLED`/`OPEN` state. The final tenant-local CAS must positively compare the exact issuer barrier `OPEN` state and owner epoch/incarnation with the original candidate and required Account, issuer, and region evidence; global issuer-index and capacity keys never enter tenant-local Lua. ### Recovery and Cutoff Scope Authority diff --git a/design/architecture/system-architecture-session-behavior.md b/design/architecture/system-architecture-session-behavior.md index e5ead30e66..f77ee5453f 100644 --- a/design/architecture/system-architecture-session-behavior.md +++ b/design/architecture/system-architecture-session-behavior.md @@ -187,7 +187,7 @@ Index contract requirements: - In target state, Game Session is the sole writer for all six index families; Account authority and realm-grant state remain the authorization source, not the indexes. - The shard-local CAS/update flow contains exactly the gameplay session record plus the four tenant-scoped indexes: character, account-tenant, tenant, and realm-grant. All of those keys share `{tenantGameplayTag}`. The initial CAS publishes only the provisional candidate; the final follow-up CAS is the atomic controller boundary for takeover, resume, and tenant/grant-binding decisions inside Redis Cluster, and exact-compares the provisional generation, Account-owned exact-binding admission lease identity, monotonic lease fence, applicable authority cutoff checkpoint, and required follow-up acknowledgements. - The cross-tenant `session:game:index:account:` and issuer-partition indexes are explicitly excluded from that shard-local CAS because they span tenant hash slots or issuer partitions. The untagged account key is also excluded from every tenant-local Lua invocation. Before the tenant-scoped CAS publishes a new binding, Game Session durably commits deterministic account-index and issuer-index repair obligations keyed to that binding transition. The account obligation contains the expected prior generation, candidate `bindingGeneration`, unique transition identity, desired add/remove, and `accountIndexFence`; the issuer obligation also carries its exact reservation identity. The shard-local CAS may publish only a provisional binding with each applicable `accountIndexState=REPAIR_REQUIRED` and `issuerIndexState=REPAIR_REQUIRED`; it is not admissible for gameplay, resume, or takeover. Game Session then performs each separate idempotent single-key index/capacity compare-and-set, reads back the exact generation/fence-qualified member and reservation state, and durably acknowledges each matching account/issuer obligation. The region-lease bridge is another ordered, separately acknowledged follow-up using the validated binding generation and region epoch. Only after all required account, issuer, and region acknowledgements does the final follow-up shard-local CAS exact-compare the provisional generation, set the applicable states to `ACKNOWLEDGED`, and admit the binding at the controller linearization point. This ordered protocol closes the cross-slot and region-bridge crash windows without claiming a cross-store transaction. -- An issuer-index write or removal atomically compares the complete expected physical v2 value, including the original anchor and local reservation/member-operation and control/incarnation evidence, before changing the hash field; the same operation also compares the exact reservation owner, transition, partition/layout, lifecycle, fence, and revision. An identical already-applied value is an idempotent success, while a newer or conflicting value is a repair conflict. At the start of an issuer cutoff or recovery, Game Session captures the active layout pointer's version, partition count, and capacity while establishing the operation and coverage fences, then reads exactly that pinned finite partition range and maps every binding through the canonical mapping helper; it does not reread the pointer and mix layouts during the operation. If the pointer no longer matches before acknowledgement, the current operation fails closed or enters the explicit layout-transition workflow, which accounts for the complete pinned old layout and separately built new layout before cutover; neither workflow evaluates a mixed partition set. The operation validates every returned value and reservation, then fences or terminates the referenced bindings through their ordinary binding CAS. Missing Redis responses, unreadable partitions, unresolved reservations or repair obligations, or conflicting field values are unavailable or ambiguous coverage, never an empty result. Recovery rebuilds each partition from the complete durable active-binding and reservation inventory using the same expected-value compare-and-set, canonical mapping, and capacity rules and clears the repair obligation only after every required partition, reservation, and binding acknowledgement is proven. +- An issuer-index write or removal atomically compares the complete expected physical v2 value, including its anchor tuple, the independently preserved original reservation coverage tuple, and local member-operation and control/incarnation evidence, before changing the hash field. The operation also compares the exact original reservation owner, transition, partition/layout, lifecycle, reservation fence and revision; the original reservation tuple is not reconstructed from or required to equal the anchor tuple. For bootstrap, the owner must prove that the original reservation belongs to the frozen complete cohort and is linked to the exact bootstrap operation and fences. An identical already-applied value is an idempotent success, while a newer or conflicting value is a repair conflict. At the start of an issuer cutoff or recovery, Game Session captures the active layout pointer's version, partition count, and capacity while establishing the operation and coverage fences, then reads exactly that pinned finite partition range and maps every binding through the canonical mapping helper; it does not reread the pointer and mix layouts during the operation. If the pointer no longer matches before acknowledgement, the current operation fails closed or enters the explicit layout-transition workflow, which accounts for the complete pinned old layout and separately built new layout before cutover; neither workflow evaluates a mixed partition set. The operation validates every returned value and reservation, then fences or terminates the referenced bindings through their ordinary binding CAS. Missing Redis responses, unreadable partitions, unresolved reservations or repair obligations, or conflicting field values are unavailable or ambiguous coverage, never an empty result. Recovery rebuilds each partition from the complete durable active-binding and reservation inventory using the same expected-value compare-and-set, canonical mapping, and capacity rules and clears the repair obligation only after every required partition, reservation, and binding acknowledgement is proven. - An issuer-partition acknowledgement is a durable evidence object, not an aggregate flag. For preserved region/tenant recovery it must carry the child-owned `issuerCoverageOperationId` and child lifecycle, the child `issuerCoverageOperationFence`, distinct issuer-wide `coverageFence`, `coverageGeneration`, issuer-wide `inventorySnapshotRevision`, pinned `issuerIndexLayoutVersion`, pinned partition count and capacity, `partitionId`, the exact `issuer/` cutoff checkpoint (`issuerAuthGeneration`, `issuanceFence`, and complete applicable `outboxCheckpoints`), every reservation identity with its owner, transition, lifecycle, fence, and inventory revision, and the capacity tuple `{partitionId, reservationCount, partitionCapacity, aggregateReservationCount, aggregateCapacity}`. The independent parent edge and the parent's consumption record carry the exact linked `parentRecoveryOperationId`, both current lifecycles, parent `operationFence`, distinct `parentCoverageFence`, resolved issuer/scope, and link revision; the child request/digest, transition, partition and reservation readback, acknowledgement, and immutable child result are parent-independent. `coverageGeneration=NOT_YET_ISSUED` remains the pre-coverage value and becomes concrete only after complete finite coverage is proven. For a standalone issuer-wide operation, the operation identity is its own issuer coverage operation identity and still carries its own maintenance fence and coverage fence; all parent fields and account-wide fields are the exact `NOT_APPLICABLE` marker plus `NO_ACTIVE_ACCOUNT_WIDE_FLOW`. The acknowledgement is valid only when all of that evidence comes from the same complete issuer-wide snapshot and operation attempt, with exact readback of the partition and reservation state. Cross-snapshot, cross-attempt, narrow-scope, stale-layout, changed-cutoff, mixed-partition, missing-reservation, or partial-capacity evidence is rejected; no acknowledgement may be assembled from separately read responses or used to authorize a different operation or layout. - Every post-fence transition, readback, acknowledgement, and exact retry proof must persist and exact-compare all four fields `operationFence`, `coverageFence`, `coverageGeneration`, and `inventorySnapshotRevision` from the same durable snapshot and operation attempt. `operationFence` plus `coverageGeneration` is insufficient, and no local or parent fence, later generation, or partial snapshot may substitute for either missing field. - Region-local gameplay binding and the region-lease bridge are intentionally outside that atomic boundary; the bridge has its own ordered request, exact readback, and durable acknowledgement, and its success is consumed only by the follow-up shard-local CAS. The Redis architecture docs define that separate bridge contract. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 9fcccc3f51..34da43788e 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,7 +12,7 @@ The Account gameplay-admission lease and the unregistered Game Session receiver The Game Session canonical inventory now retains Account's exact issuer string through the forward V1024→V1025 conversion. R488 passes 19 selected PostgreSQL cases, including populated-row migration preservation, restart, canonical writes, and refusal by the typed reader to reinterpret retained UUID issuers. This proves storage identity conversion only; issuer ownership and admission remain unqualified. -The receiving source includes a pending issuer-bootstrap SQL owner that freezes the complete issuer cohort under the inventory clock, requires actual persisted `VERIFIED` legacy-owner evidence, and blocks later preparation. Descriptor and Account issuer-checkpoint inputs remain controlled. Donor-source R539 recorded 65 focused cases (9 unit and 56 PostgreSQL/Redis, including existing account-member regressions); donor-source R545 recorded 12 cases for the physical schema-v2 shape work. Those remain donor-only attributions. Receiving-parent R548 passes 106 fresh cases (12 unit and 94 PostgreSQL/Redis) on parent `be0e20b`, including the 38-case roster regression, full pending-intent repository/migration coverage and existing account-member owners. jOOQ generation, enabled affected Checkstyle/SpotBugs/formatting and documentation checks pass; all exact test containers are absent. This focused receiving proof does not establish a complete service-suite pass or public runtime admission. Donor proof includes the missing-control refusal, both PostgreSQL-observed prepare/intent lock orders, and populated V1029→V1030 retention/restart. The V1028 retained-row fixture uses controlled historical SQL rows, not an actual pre-migration prepare. The receiving tree has shape-only v2 member model, codec and key-helper sources, but no physical Redis mutation/readback, capacity accounting or separate issuer acknowledgement. The canonical physical schema v2 is selected; retained v1 artifacts remain unqualified with no fallback. No installed pointer, complete partition/capacity proof, issuer acknowledgement, barrier `OPEN`, final CAS or admission is established. Operational source/incarnation custody, legacy recovery, PKI and activation holds remain; see the [issuer anchor owner](../../architecture/system-architecture-redis.md#installed-issuer-anchor-for-ordinary-new). +The receiving source includes a pending issuer-bootstrap SQL owner that freezes the complete issuer cohort under the inventory clock, requires actual persisted `VERIFIED` legacy-owner evidence, and blocks later preparation. Descriptor and Account issuer-checkpoint inputs remain controlled. Donor-source R539 recorded 65 focused cases (9 unit and 56 PostgreSQL/Redis, including existing account-member regressions); donor-source R545 recorded 12 cases for the physical schema-v2 shape work. Those remain donor-only attributions. Receiving-parent R548 passes 106 fresh cases (12 unit and 94 PostgreSQL/Redis) on parent `be0e20b`, including the 38-case roster regression, full pending-intent repository/migration coverage and existing account-member owners. jOOQ generation, enabled affected Checkstyle/SpotBugs/formatting and documentation checks pass; all exact test containers are absent. This focused receiving proof does not establish a complete service-suite pass or public runtime admission. Donor proof includes the missing-control refusal, both PostgreSQL-observed prepare/intent lock orders, and populated V1029→V1030 retention/restart. The V1028 retained-row fixture uses controlled historical SQL rows, not an actual pre-migration prepare. The receiving tree has shape-only v2 member model, codec and key-helper sources, but no physical Redis mutation/readback, capacity accounting or separate issuer acknowledgement. The canonical physical schema v2 preserves the original reservation coverage tuple separately from the anchor tuple; R551 passes 21 fresh focused cases (12 unit and nine PostgreSQL), including an actual populated reservation with distinct original coverage and new bootstrap anchor, preserved source rows and cohort, independent physical identities and closed malformed-field refusal. Enabled affected Checkstyle/SpotBugs/formatting and documentation checks pass; all exact test containers are absent. This is representation proof with controlled member-operation and incarnation inputs, not an installed anchor or qualified physical write. Retained v1 artifacts remain unqualified with no fallback. No installed pointer, complete partition/capacity proof, issuer acknowledgement, barrier `OPEN`, final CAS or admission is established. Operational source/incarnation custody, legacy recovery, PKI and activation holds remain; see the [issuer anchor owner](../../architecture/system-architecture-redis.md#installed-issuer-anchor-for-ordinary-new). The unregistered no-active first-NEW member-repair owner composes the original durable operation, the physical one-key global account-member write/readback outside SQL, and separate SQL acceptance. V1026 preserves the operation and completion. R506 freshly passes all 29 selected PostgreSQL/Redis cases, including composed completion, frozen retry/restart, retained prior PRESENT observations, positive control-row requirements, exact member preservation, and malformed-completion refusal. Seven focused unit cases retain R505 attribution; ten shared Redis contract cases retain R500 attribution. This is binding-local `ADD_OR_RETAIN` evidence only: it does not enumerate the account, establish global completeness, or admit the candidate. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerMemberV2Codec.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerMemberV2Codec.java index ab6de9d6dd..d8c0dccc78 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerMemberV2Codec.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerMemberV2Codec.java @@ -88,6 +88,10 @@ final class CanonicalGameplayIssuerMemberV2Codec { "partitionId", "lifecycle", "reservationFence", + "issuerCoverageOperationId", + "issuerCoverageOperationFence", + "coverageFence", + "inventorySnapshotRevision", "inventoryRevision"); private static final Set ANCHOR_FIELDS = Set.of( @@ -136,6 +140,15 @@ static byte[] encode(CanonicalGameplayIssuerMemberV2Value value) { requireCounterLimit(value.layoutDescriptor().partitionCount(), "partitionCount", false); requireCounterLimit(value.layoutDescriptor().partitionCapacity(), "partitionCapacity", false); requireCounterLimit(value.reservation().partitionId(), "partitionId", true); + requireCounterLimit( + value.reservation().issuerCoverageOperationFence(), + "reservation.issuerCoverageOperationFence", + false); + requireCounterLimit(value.reservation().coverageFence(), "reservation.coverageFence", false); + requireCounterLimit( + value.reservation().inventorySnapshotRevision(), + "reservation.inventorySnapshotRevision", + false); requireCounterLimit(value.reservation().inventoryRevision(), "inventoryRevision", false); requireCounterLimit(value.anchor().operationFence(), "anchor.operationFence", false); requireCounterLimit(value.anchor().coverageFence(), "anchor.coverageFence", false); @@ -226,12 +239,19 @@ static CanonicalGameplayIssuerMemberV2Value decode(byte[] encoded) { text(reservationObject, "lifecycle"), "reservation lifecycle"); UUID reservationFence = uuid(reservationObject, "reservationFence"); + UUID reservationIssuerCoverageOperationId = + uuid(reservationObject, "issuerCoverageOperationId"); + BigInteger reservationIssuerCoverageOperationFence = + positive(reservationObject, "issuerCoverageOperationFence"); + BigInteger reservationCoverageFence = positive(reservationObject, "coverageFence"); + BigInteger reservationInventorySnapshotRevision = + positive(reservationObject, "inventorySnapshotRevision"); BigInteger inventoryRevision = positive(reservationObject, "inventoryRevision"); ObjectNode anchorObject = nestedObject(root, "anchor", ANCHOR_FIELDS); UUID issuerCoverageOperationId = uuid(anchorObject, "issuerCoverageOperationId"); BigInteger anchorOperationFence = positive(anchorObject, "operationFence"); - BigInteger coverageFence = positive(anchorObject, "coverageFence"); + BigInteger anchorCoverageFence = positive(anchorObject, "coverageFence"); BigInteger issuerInventorySnapshotRevision = positive(anchorObject, "issuerInventorySnapshotRevision"); byte[] sourceCheckpointBytes = base64(anchorObject, "sourceCheckpointBytes"); @@ -310,10 +330,10 @@ static CanonicalGameplayIssuerMemberV2Value decode(byte[] encoded) { partitionId, lifecycle, reservationFence, - issuerCoverageOperationId, - anchorOperationFence, - coverageFence, - issuerInventorySnapshotRevision, + reservationIssuerCoverageOperationId, + reservationIssuerCoverageOperationFence, + reservationCoverageFence, + reservationInventorySnapshotRevision, inventoryRevision); CanonicalGameplayIssuerMemberV2Value value = new CanonicalGameplayIssuerMemberV2Value( @@ -323,7 +343,7 @@ static CanonicalGameplayIssuerMemberV2Value decode(byte[] encoded) { new CanonicalGameplayIssuerMemberV2Value.Anchor( issuerCoverageOperationId, anchorOperationFence, - coverageFence, + anchorCoverageFence, issuerInventorySnapshotRevision), memberOperation, issuerControlEpoch, @@ -387,6 +407,13 @@ private static ObjectNode toJson(CanonicalGameplayIssuerMemberV2Value value) { reservationObject.put("partitionId", reservation.partitionId().toString()); reservationObject.put("lifecycle", reservation.lifecycle().name()); reservationObject.put("reservationFence", reservation.reservationFence().toString()); + reservationObject.put( + "issuerCoverageOperationId", reservation.issuerCoverageOperationId().toString()); + reservationObject.put( + "issuerCoverageOperationFence", reservation.issuerCoverageOperationFence().toString()); + reservationObject.put("coverageFence", reservation.coverageFence().toString()); + reservationObject.put( + "inventorySnapshotRevision", reservation.inventorySnapshotRevision().toString()); reservationObject.put("inventoryRevision", reservation.inventoryRevision().toString()); ObjectNode anchorObject = root.putObject("anchor"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerMemberV2Value.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerMemberV2Value.java index 32f9b0d1cb..121965ed2c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerMemberV2Value.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerMemberV2Value.java @@ -68,15 +68,7 @@ final class CanonicalGameplayIssuerMemberV2Value { throw new IllegalArgumentException( "Issuer reservation must retain the exact binding owner, generation, and partition"); } - if (!anchor.issuerCoverageOperationId().equals(reservation.issuerCoverageOperationId()) - || !anchor.operationFence().equals(reservation.issuerCoverageOperationFence()) - || !anchor.coverageFence().equals(reservation.coverageFence()) - || !anchor - .issuerInventorySnapshotRevision() - .equals(reservation.inventorySnapshotRevision())) { - throw new IllegalArgumentException( - "Issuer reservation must retain the complete installed anchor tuple"); - } + // The reservation's original coverage tuple is independent from the newly pinned anchor. requireDigestMatches( layoutDescriptor.exactDescriptorBytes(), layoutDescriptor.descriptorDigest(), "descriptor"); requireDigestMatches( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java index a466b5a8cc..519462ba52 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java @@ -28,6 +28,7 @@ import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; @@ -186,6 +187,119 @@ void pendingIntentFreezesActualInventoryAndExactInputsAcrossRetryAndRestart() { } } + @Test + void shapeOnlyMemberRoundTripPreservesPopulatedReservationTupleBesideBootstrapAnchor() { + TestSchema testSchema = newTestSchema("gs_issuer_boot_member_shape_"); + try { + establishActualLegacyDisposition(testSchema.dsl()); + var inventory = new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); + var prepared = prepareActualBinding(inventory); + List reservationRowsBefore = + rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_reservation"); + var durableReservationRow = + testSchema + .dsl() + .fetchSingle( + "SELECT * FROM game_session_canonical_issuer_partition_reservation" + + " WHERE reservation_id = ?", + prepared.issuerReservationId()); + byte[] originalBindingRefBytes = durableReservationRow.get("binding_ref", byte[].class); + var originalReservation = + new CanonicalIssuerPartitionReservation( + prepared.issuerReservationId(), + prepared.candidate(), + decimal(durableReservationRow.get("binding_generation", BigDecimal.class)), + durableReservationRow.get("transition_id", UUID.class), + decimal(durableReservationRow.get("partition_id", BigDecimal.class)), + CanonicalIssuerPartitionReservation.Lifecycle.valueOf( + durableReservationRow.get("lifecycle", String.class)), + durableReservationRow.get("reservation_fence", UUID.class), + durableReservationRow.get("issuer_coverage_operation_id", UUID.class), + decimal( + durableReservationRow.get("issuer_coverage_operation_fence", BigDecimal.class)), + decimal(durableReservationRow.get("coverage_fence", BigDecimal.class)), + decimal(durableReservationRow.get("inventory_snapshot_revision", BigDecimal.class)), + decimal(durableReservationRow.get("inventory_revision", BigDecimal.class))); + + var bootstrapOwner = new CanonicalGameplayIssuerLayoutBootstrapRepository(testSchema.dsl()); + var intent = + bootstrapOwner.beginInitialBootstrapIntent( + UUID.randomUUID(), + descriptor(LAYOUT_VERSION, PARTITION_COUNT, PARTITION_CAPACITY), + sourceCheckpoint(BigInteger.valueOf(7))); + assertThat(intent.state()) + .isEqualTo(CanonicalGameplayIssuerLayoutBootstrapIntent.State.INITIAL_BOOTSTRAP_INTENT); + var anchor = + new CanonicalGameplayIssuerMemberV2Value.Anchor( + intent.operationId(), + intent.operationFence(), + intent.coverageFence(), + intent.inventorySnapshotRevision()); + assertThat( + new CanonicalGameplayIssuerMemberV2Value.Anchor( + originalReservation.issuerCoverageOperationId(), + originalReservation.issuerCoverageOperationFence(), + originalReservation.coverageFence(), + originalReservation.inventorySnapshotRevision())) + .isNotEqualTo(anchor); + + // These member-operation and incarnation values are explicit shape fixtures; they do not + // advance bootstrap state or establish trusted issuer, Redis, or admission evidence. + var controlledMemberOperation = + new CanonicalGameplayIssuerMemberV2Value.LocalMemberOperation( + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + BigInteger.valueOf(101), + BigInteger.valueOf(102)); + var controlledIncarnation = controlledIncarnationForShapeOnly(); + var value = + new CanonicalGameplayIssuerMemberV2Value( + prepared.candidate(), + prepared.bindingGeneration(), + originalReservation, + anchor, + controlledMemberOperation, + intent.controlEpoch(), + intent.layoutDescriptor(), + intent.sourceCheckpoint(), + controlledIncarnation); + + byte[] encoded = CanonicalGameplayIssuerMemberV2Codec.encode(value); + CanonicalGameplayIssuerMemberV2Value decoded = + CanonicalGameplayIssuerMemberV2Codec.decode(encoded); + assertThat(decoded).isEqualTo(value); + assertThat(decoded.reservation()).isEqualTo(originalReservation); + assertThat(decoded.reservation().owner().bindingRef().bytes()) + .containsExactly(originalBindingRefBytes); + assertThat(decoded.anchor()).isEqualTo(anchor); + assertThat(decoded.memberOperation()).isEqualTo(controlledMemberOperation); + assertThat(decoded.incarnation()).isEqualTo(controlledIncarnation); + + var reservationCohortRow = + intent.cohortRows().stream() + .filter( + row -> + row.kind() + == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.RESERVATION) + .findFirst() + .orElseThrow(); + assertThat(reservationCohortRow.sourceKey()) + .isEqualTo(prepared.issuerReservationId().toString()); + var frozenReadback = bootstrapOwner.readCurrentInitialBootstrapIntent(intent.operationId()); + assertThat(frozenReadback.state()) + .isEqualTo(CanonicalGameplayIssuerLayoutBootstrapIntent.State.INITIAL_BOOTSTRAP_INTENT); + assertThat(frozenReadback.cohortRows()) + .filteredOn( + row -> + row.kind() == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.RESERVATION) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceRowDigest) + .containsExactly(reservationCohortRow.sourceRowDigest()); + assertThat(rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_reservation")) + .containsExactlyElementsOf(reservationRowsBefore); + } finally { + dropSchema(testSchema.schema()); + } + } + @Test void pendingIntentBlocksLaterPreparationWithoutChangingInventoryOrItsCohort() { TestSchema testSchema = newTestSchema("gs_issuer_boot_blocks_new_"); @@ -875,6 +989,37 @@ private static int countRows(DSLContext dsl, String tableName) { return dsl.fetchCount(DSL.table(tableName)); } + private static BigInteger decimal(BigDecimal value) { + return Objects.requireNonNull(value, "durable reservation counter").toBigIntegerExact(); + } + + private static CanonicalGameplayIssuerMemberV2Value.Incarnation + controlledIncarnationForShapeOnly() { + var deployment = + new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "coordination-controlled", + "deployment-controlled", + List.of("coord-controlled-a", "coord-controlled-b"), + "redis-controlled", + "lua-registry-controlled", + digest("lua-registry-controlled"), + "READY", + "boot-controlled", + "startup-controlled", + "storage-controlled", + "aof-controlled"); + return new CanonicalGameplayIssuerMemberV2Value.Incarnation( + "controlled-shape-only-workload", + digest("attestation-controlled"), + deployment, + digest("coord-ops-ro-acl-controlled"), + digest("coord-redis-config-controlled")); + } + + private static String digest(String value) { + return CanonicalGameplayIssuerMemberV2Codec.sha256(value.getBytes(StandardCharsets.UTF_8)); + } + private static BigInteger currentInventoryRevision(DSLContext dsl) { BigDecimal revision = Objects.requireNonNull( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerMemberV2ValueCodecTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerMemberV2ValueCodecTest.java index e9e9f042d2..7020dd217d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerMemberV2ValueCodecTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerMemberV2ValueCodecTest.java @@ -22,7 +22,7 @@ class CanonicalGameplayIssuerMemberV2ValueCodecTest { private static final BigInteger LARGE = new BigInteger("9007199254740997"); @Test - void roundTripsCompleteTupleAndCountersBeyondJavaScriptSafeInteger() { + void roundTripsCompleteTupleAndCountersBeyondJavaScriptSafeInteger() throws Exception { CanonicalGameplayIssuerMemberV2Value value = fixture(); byte[] encoded = CanonicalGameplayIssuerMemberV2Codec.encode(value); @@ -33,9 +33,20 @@ void roundTripsCompleteTupleAndCountersBeyondJavaScriptSafeInteger() { assertThat(decoded.bindingGeneration()).isEqualTo(LARGE); assertThat(decoded.anchor().issuerInventorySnapshotRevision()) .isEqualTo(LARGE.add(BigInteger.valueOf(12))); + assertThat(decoded.reservation().issuerCoverageOperationId()).isEqualTo(uuid(21)); + assertThat(decoded.reservation().issuerCoverageOperationFence()) + .isEqualTo(LARGE.add(BigInteger.valueOf(15))); + assertThat(decoded.reservation().coverageFence()).isEqualTo(LARGE.add(BigInteger.valueOf(16))); + assertThat(decoded.reservation().inventorySnapshotRevision()) + .isEqualTo(LARGE.add(BigInteger.valueOf(17))); assertThat(decoded.memberOperation().coverageGeneration()) .isEqualTo(LARGE.add(BigInteger.valueOf(20))); assertThat(new String(encoded, StandardCharsets.UTF_8)).contains("\"schemaVersion\":2"); + ObjectNode encodedRoot = (ObjectNode) JSON.readTree(encoded); + assertThat(encodedRoot.path("reservation").path("coverageFence").textValue()) + .isEqualTo(LARGE.add(BigInteger.valueOf(16)).toString()); + assertThat(encodedRoot.path("anchor").path("coverageFence").textValue()) + .isEqualTo(LARGE.add(BigInteger.valueOf(11)).toString()); } @Test @@ -91,15 +102,16 @@ void equalityAndHashCodeDoNotDependOnTheCodecByteLimit() { } @Test - void sameBindingWithDifferentConsistentAnchorOrReservationRemainsSeparateAfterDecode() { + void originalReservationAnchorAndMemberOperationTuplesRemainDistinctPhysicalIdentity() + throws Exception { CanonicalGameplayIssuerMemberV2Value original = fixture(); CanonicalGameplayIssuerMemberV2Value.Anchor changedAnchor = new CanonicalGameplayIssuerMemberV2Value.Anchor( - original.anchor().issuerCoverageOperationId(), - original.anchor().operationFence(), - original.anchor().coverageFence(), + uuid(34), + original.anchor().operationFence().add(BigInteger.ONE), + original.anchor().coverageFence().add(BigInteger.ONE), original.anchor().issuerInventorySnapshotRevision().add(BigInteger.ONE)); - CanonicalIssuerPartitionReservation changedReservation = + CanonicalIssuerPartitionReservation changedOriginalReservation = new CanonicalIssuerPartitionReservation( original.reservation().reservationId(), original.owner(), @@ -108,13 +120,22 @@ void sameBindingWithDifferentConsistentAnchorOrReservationRemainsSeparateAfterDe original.reservation().partitionId(), original.reservation().lifecycle(), original.reservation().reservationFence(), - changedAnchor.issuerCoverageOperationId(), - changedAnchor.operationFence(), - changedAnchor.coverageFence(), - changedAnchor.issuerInventorySnapshotRevision(), + uuid(35), + original.reservation().issuerCoverageOperationFence().add(BigInteger.ONE), + original.reservation().coverageFence().add(BigInteger.ONE), + original.reservation().inventorySnapshotRevision().add(BigInteger.ONE), original.reservation().inventoryRevision()); + CanonicalGameplayIssuerMemberV2Value anotherOriginalReservation = + withReservation(original, changedOriginalReservation); CanonicalGameplayIssuerMemberV2Value anotherAnchor = - copy(original, changedReservation, changedAnchor); + copy(original, original.reservation(), changedAnchor); + CanonicalGameplayIssuerMemberV2Value anotherMemberOperation = + withMemberOperation( + original, + new CanonicalGameplayIssuerMemberV2Value.LocalMemberOperation( + uuid(36), + original.memberOperation().operationFence().add(BigInteger.ONE), + original.memberOperation().coverageGeneration().add(BigInteger.ONE))); CanonicalIssuerPartitionReservation changedLifecycle = new CanonicalIssuerPartitionReservation( original.reservation().reservationId(), @@ -132,15 +153,24 @@ void sameBindingWithDifferentConsistentAnchorOrReservationRemainsSeparateAfterDe CanonicalGameplayIssuerMemberV2Value anotherReservation = copy(original, changedLifecycle, original.anchor()); - assertThat(anotherAnchor.owner()).isEqualTo(original.owner()); - assertThat(anotherAnchor).isNotEqualTo(original); - assertThat(anotherReservation).isNotEqualTo(original); - byte[] anotherAnchorBytes = CanonicalGameplayIssuerMemberV2Codec.encode(anotherAnchor); - assertThat(anotherAnchorBytes) - .isNotEqualTo(CanonicalGameplayIssuerMemberV2Codec.encode(original)); - assertThat(CanonicalGameplayIssuerMemberV2Codec.decode(anotherAnchorBytes)) - .isEqualTo(anotherAnchor) - .isNotEqualTo(original); + byte[] originalBytes = CanonicalGameplayIssuerMemberV2Codec.encode(original); + for (CanonicalGameplayIssuerMemberV2Value changed : + List.of( + anotherOriginalReservation, + anotherAnchor, + anotherMemberOperation, + anotherReservation)) { + byte[] changedBytes = CanonicalGameplayIssuerMemberV2Codec.encode(changed); + assertThat(changed).isNotEqualTo(original); + assertThat(changedBytes).isNotEqualTo(originalBytes); + CanonicalGameplayIssuerMemberV2Value decoded = + CanonicalGameplayIssuerMemberV2Codec.decode(changedBytes); + assertThat(decoded).isEqualTo(changed).isNotEqualTo(original); + assertThat(decoded.hashCode()).isEqualTo(changed.hashCode()); + } + assertThat(anotherOriginalReservation.anchor()).isEqualTo(original.anchor()); + assertThat(anotherAnchor.reservation()).isEqualTo(original.reservation()); + assertThat(anotherMemberOperation.reservation()).isEqualTo(original.reservation()); } @Test @@ -209,10 +239,32 @@ void rejectsLegacyUnknownDuplicateNoncanonicalAndMalformedInputs() throws Except extraField.put("extra", "not permitted"); assertRejected(canonical(extraField)); + ObjectNode missingOriginalCoverageField = root.deepCopy(); + ((ObjectNode) missingOriginalCoverageField.get("reservation")).remove("coverageFence"); + assertRejected(canonical(missingOriginalCoverageField)); + + ObjectNode unknownOriginalCoverageField = root.deepCopy(); + ((ObjectNode) unknownOriginalCoverageField.get("reservation")) + .put("unrecognizedCoverageEvidence", "not permitted"); + assertRejected(canonical(unknownOriginalCoverageField)); + + ObjectNode malformedOriginalCoverageField = root.deepCopy(); + ((ObjectNode) malformedOriginalCoverageField.get("reservation")) + .put("inventorySnapshotRevision", "01"); + assertRejected(canonical(malformedOriginalCoverageField)); + String duplicate = new String(canonical, StandardCharsets.UTF_8) .replace("\"schemaVersion\":2", "\"schemaVersion\":2,\"schemaVersion\":2"); assertRejected(duplicate.getBytes(StandardCharsets.UTF_8)); + String originalFence = + "\"issuerCoverageOperationFence\":\"" + + fixture().reservation().issuerCoverageOperationFence() + + "\""; + String duplicateOriginalReservationField = + new String(canonical, StandardCharsets.UTF_8) + .replace(originalFence, originalFence + "," + originalFence); + assertRejected(duplicateOriginalReservationField.getBytes(StandardCharsets.UTF_8)); ObjectNode leadingZero = root.deepCopy(); leadingZero.put("bindingGeneration", "01"); @@ -246,29 +298,20 @@ void rejectsLegacyUnknownDuplicateNoncanonicalAndMalformedInputs() throws Except } @Test - void constructorRejectsAnAnchorThatDoesNotMatchItsReservation() { - CanonicalGameplayIssuerMemberV2Value original = fixture(); - CanonicalGameplayIssuerMemberV2Value.Anchor mismatchedAnchor = - new CanonicalGameplayIssuerMemberV2Value.Anchor( - original.anchor().issuerCoverageOperationId(), - original.anchor().operationFence(), - original.anchor().coverageFence().add(BigInteger.ONE), - original.anchor().issuerInventorySnapshotRevision()); - - assertThatThrownBy( - () -> - new CanonicalGameplayIssuerMemberV2Value( - original.owner(), - original.bindingGeneration(), - original.reservation(), - mismatchedAnchor, - original.memberOperation(), - original.issuerControlEpoch(), - original.layoutDescriptor(), - original.sourceCheckpoint(), - original.incarnation())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("complete installed anchor tuple"); + void constructorAcceptsDistinctValidOriginalReservationAndNewAnchorTuples() { + CanonicalGameplayIssuerMemberV2Value value = fixture(); + + assertThat(value.reservation().issuerCoverageOperationId()) + .isNotEqualTo(value.anchor().issuerCoverageOperationId()); + assertThat(value.reservation().issuerCoverageOperationFence()) + .isNotEqualTo(value.anchor().operationFence()); + assertThat(value.reservation().coverageFence()).isNotEqualTo(value.anchor().coverageFence()); + assertThat(value.reservation().inventorySnapshotRevision()) + .isNotEqualTo(value.anchor().issuerInventorySnapshotRevision()); + assertThat( + CanonicalGameplayIssuerMemberV2Codec.decode( + CanonicalGameplayIssuerMemberV2Codec.encode(value))) + .isEqualTo(value); } static CanonicalGameplayIssuerMemberV2Value fixture() { @@ -328,10 +371,10 @@ static CanonicalGameplayIssuerMemberV2Value fixture() { owner.bindingRef().partitionId(owner.issuerIndexPartitionCount()), CanonicalIssuerPartitionReservation.Lifecycle.BOUND, uuid(32), - anchor.issuerCoverageOperationId(), - anchor.operationFence(), - anchor.coverageFence(), - anchor.issuerInventorySnapshotRevision(), + uuid(21), + LARGE.add(BigInteger.valueOf(15)), + LARGE.add(BigInteger.valueOf(16)), + LARGE.add(BigInteger.valueOf(17)), LARGE.add(BigInteger.valueOf(14))); CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence deployment = new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( @@ -396,6 +439,21 @@ private static CanonicalGameplayIssuerMemberV2Value withMemberOperation( original.incarnation()); } + private static CanonicalGameplayIssuerMemberV2Value withReservation( + CanonicalGameplayIssuerMemberV2Value original, + CanonicalIssuerPartitionReservation reservation) { + return new CanonicalGameplayIssuerMemberV2Value( + original.owner(), + original.bindingGeneration(), + reservation, + original.anchor(), + original.memberOperation(), + original.issuerControlEpoch(), + original.layoutDescriptor(), + original.sourceCheckpoint(), + original.incarnation()); + } + private static CanonicalGameplayIssuerMemberV2Value withLayout( CanonicalGameplayIssuerMemberV2Value original, CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor layoutDescriptor) { From a9b6f886cdcf88f188d79d0e38d50d1f3a253e01 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:40:18 +1300 Subject: [PATCH 03/34] Prepare immutable issuer partition build plans from frozen bootstrap cohorts --- ...nicalGameplayIssuerPartitionBuildPlan.java | 305 +++ ...ameplayIssuerPartitionBuildRepository.java | 1809 +++++++++++++++++ ..._canonical_issuer_partition_build_plan.sql | 265 +++ ...rtitionBuildRepositoryIntegrationTest.java | 1339 ++++++++++++ 4 files changed, 3718 insertions(+) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildPlan.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V1031__canonical_issuer_partition_build_plan.sql create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildPlan.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildPlan.java new file mode 100644 index 0000000000..49c66a7c67 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildPlan.java @@ -0,0 +1,305 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.util.List; +import java.util.Objects; +import java.util.UUID; + +/** + * Immutable preparation artifact for building the initial issuer partitions from the exact + * persisted bootstrap intent and cohort. + * + *

This plan is not an installed anchor, a physical member write, a coverage acknowledgement, or + * admission evidence. Its operation IDs and UUID fences identify preparation work only. + */ +final class CanonicalGameplayIssuerPartitionBuildPlan { + enum State { + PREPARED, + BLOCKED + } + + enum CoverageGenerationState { + NOT_YET_ISSUED + } + + enum BlockerCode { + UNRESOLVED_LEGACY_BINDING, + UNRESOLVED_LEGACY_RESERVATION, + UNREPRESENTABLE_BINDING, + UNREPRESENTABLE_RESERVATION, + UNREPRESENTABLE_SOURCE, + MISSING_RESERVATION, + CONFLICTING_RESERVATION_LINK, + PARTITION_CAPACITY_EXCEEDED, + AGGREGATE_CAPACITY_EXCEEDED + } + + private final UUID buildOperationId; + private final UUID buildPreparationFenceId; + private final CanonicalGameplayIssuerLayoutBootstrapIntent bootstrapIntent; + private final List cohortRows; + private final List memberWorks; + private final List blockers; + private final String planDigest; + + CanonicalGameplayIssuerPartitionBuildPlan( + UUID buildOperationId, + UUID buildPreparationFenceId, + CanonicalGameplayIssuerLayoutBootstrapIntent bootstrapIntent, + List cohortRows, + List memberWorks, + List blockers, + String planDigest) { + this.buildOperationId = requireNonNil(buildOperationId, "buildOperationId"); + this.buildPreparationFenceId = + requireNonNil(buildPreparationFenceId, "buildPreparationFenceId"); + this.bootstrapIntent = Objects.requireNonNull(bootstrapIntent, "bootstrapIntent"); + if (buildOperationId.equals(bootstrapIntent.operationId()) + || buildOperationId.equals(buildPreparationFenceId) + || buildOperationId.equals(bootstrapIntent.requestId()) + || buildPreparationFenceId.equals(bootstrapIntent.operationId()) + || buildPreparationFenceId.equals(bootstrapIntent.requestId())) { + throw new IllegalArgumentException("Build preparation identity must be separate from intent"); + } + this.cohortRows = List.copyOf(Objects.requireNonNull(cohortRows, "cohortRows")); + this.memberWorks = List.copyOf(Objects.requireNonNull(memberWorks, "memberWorks")); + this.blockers = List.copyOf(Objects.requireNonNull(blockers, "blockers")); + if (this.cohortRows.stream().anyMatch(Objects::isNull) + || this.memberWorks.stream().anyMatch(Objects::isNull) + || this.blockers.stream().anyMatch(Objects::isNull)) { + throw new IllegalArgumentException("Build plan collections must not contain null"); + } + if (this.cohortRows.size() != bootstrapIntent.cohortRows().size()) { + throw new IllegalArgumentException("Build plan must retain the complete bootstrap cohort"); + } + for (int index = 0; index < this.cohortRows.size(); index++) { + requireSameCohortRow(this.cohortRows.get(index), bootstrapIntent.cohortRows().get(index)); + } + for (int index = 0; index < this.memberWorks.size(); index++) { + MemberWork work = this.memberWorks.get(index); + if (work.workOrdinal() != index) { + throw new IllegalArgumentException("Member work ordinals must be contiguous from zero"); + } + work.requireAnchor(bootstrapIntent); + } + for (int index = 0; index < this.blockers.size(); index++) { + Blocker blocker = this.blockers.get(index); + if (blocker.blockerOrdinal() != index) { + throw new IllegalArgumentException("Blocker ordinals must be contiguous from zero"); + } + if (blocker.sourceRowOrdinal() >= this.cohortRows.size() + || !blocker + .sourceRowDigest() + .equals(this.cohortRows.get((int) blocker.sourceRowOrdinal()).sourceRowDigest())) { + throw new IllegalArgumentException("Build blocker must link to its exact cohort row"); + } + } + this.planDigest = requireDigest(planDigest, "planDigest"); + } + + UUID buildOperationId() { + return buildOperationId; + } + + UUID buildPreparationFenceId() { + return buildPreparationFenceId; + } + + CanonicalGameplayIssuerLayoutBootstrapIntent bootstrapIntent() { + return bootstrapIntent; + } + + List cohortRows() { + return cohortRows; + } + + List memberWorks() { + return memberWorks; + } + + List blockers() { + return blockers; + } + + State state() { + return blockers.isEmpty() ? State.PREPARED : State.BLOCKED; + } + + CoverageGenerationState coverageGenerationState() { + return CoverageGenerationState.NOT_YET_ISSUED; + } + + /** The pending preparation stage deliberately has no owner-issued coverage generation. */ + BigInteger coverageGeneration() { + return null; + } + + String planDigest() { + return planDigest; + } + + private static void requireSameCohortRow( + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow actual, + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow expected) { + if (actual.rowOrdinal() != expected.rowOrdinal() + || actual.kind() != expected.kind() + || !actual.sourceKey().equals(expected.sourceKey()) + || !actual.sourceInventoryRevision().equals(expected.sourceInventoryRevision()) + || !actual.sourceRowJson().equals(expected.sourceRowJson()) + || !actual.sourceRowDigest().equals(expected.sourceRowDigest())) { + throw new IllegalArgumentException("Build plan changed a frozen bootstrap cohort row"); + } + } + + private static UUID requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(name + " must not be nil"); + } + return value; + } + + private static String requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(name + " must be a canonical SHA-256 digest"); + } + return value; + } + + record MemberWork( + long workOrdinal, + UUID memberOperationId, + UUID memberPreparationFenceId, + long reservationSourceRowOrdinal, + String reservationSourceRowDigest, + Long bindingSourceRowOrdinal, + String bindingSourceRowDigest, + UUID reservationId, + byte[] bindingRef, + UUID transitionId, + String reservationLifecycle, + UUID reservationFence, + BigInteger originalPartitionId, + BigInteger originalLayoutVersion, + BigInteger originalPartitionCount, + BigInteger originalPartitionCapacity, + UUID originalIssuerCoverageOperationId, + BigInteger originalIssuerCoverageOperationFence, + BigInteger originalCoverageFence, + BigInteger originalInventorySnapshotRevision, + BigInteger plannedPartitionId, + UUID plannedAnchorOperationId, + BigInteger plannedAnchorOperationFence, + BigInteger plannedAnchorCoverageFence, + BigInteger plannedAnchorInventorySnapshotRevision) { + MemberWork { + requireNonNegative(workOrdinal, "workOrdinal"); + requireNonNil(memberOperationId, "memberOperationId"); + requireNonNil(memberPreparationFenceId, "memberPreparationFenceId"); + requireNonNegative(reservationSourceRowOrdinal, "reservationSourceRowOrdinal"); + requireDigest(reservationSourceRowDigest, "reservationSourceRowDigest"); + if ((bindingSourceRowOrdinal == null) != (bindingSourceRowDigest == null)) { + throw new IllegalArgumentException("Binding cohort link must include its exact digest"); + } + if (bindingSourceRowOrdinal != null) { + requireNonNegative(bindingSourceRowOrdinal, "bindingSourceRowOrdinal"); + requireDigest(bindingSourceRowDigest, "bindingSourceRowDigest"); + } + requireNonNil(reservationId, "reservationId"); + bindingRef = Objects.requireNonNull(bindingRef, "bindingRef").clone(); + if (bindingRef.length == 0) + throw new IllegalArgumentException("bindingRef must not be empty"); + requireNonNil(transitionId, "transitionId"); + Objects.requireNonNull(reservationLifecycle, "reservationLifecycle"); + if (!List.of("RESERVED", "BOUND", "RELEASE_PENDING", "RELEASED") + .contains(reservationLifecycle)) { + throw new IllegalArgumentException("Unsupported original reservation lifecycle"); + } + requireNonNil(reservationFence, "reservationFence"); + requireNonNegative(originalPartitionId, "originalPartitionId"); + requirePositive(originalLayoutVersion, "originalLayoutVersion"); + requirePositive(originalPartitionCount, "originalPartitionCount"); + requirePositive(originalPartitionCapacity, "originalPartitionCapacity"); + if (originalPartitionId.compareTo(originalPartitionCount) >= 0) { + throw new IllegalArgumentException("Original partition is outside the original layout"); + } + requireNonNil(originalIssuerCoverageOperationId, "originalIssuerCoverageOperationId"); + requirePositive(originalIssuerCoverageOperationFence, "originalIssuerCoverageOperationFence"); + requirePositive(originalCoverageFence, "originalCoverageFence"); + requirePositive(originalInventorySnapshotRevision, "originalInventorySnapshotRevision"); + requireNonNegative(plannedPartitionId, "plannedPartitionId"); + requireNonNil(plannedAnchorOperationId, "plannedAnchorOperationId"); + requirePositive(plannedAnchorOperationFence, "plannedAnchorOperationFence"); + requirePositive(plannedAnchorCoverageFence, "plannedAnchorCoverageFence"); + requirePositive( + plannedAnchorInventorySnapshotRevision, "plannedAnchorInventorySnapshotRevision"); + } + + @Override + public byte[] bindingRef() { + return bindingRef.clone(); + } + + boolean countsTowardCapacity() { + return !reservationLifecycle.equals("RELEASED"); + } + + private void requireAnchor(CanonicalGameplayIssuerLayoutBootstrapIntent intent) { + if (!plannedAnchorOperationId.equals(intent.operationId()) + || !plannedAnchorOperationFence.equals(intent.operationFence()) + || !plannedAnchorCoverageFence.equals(intent.coverageFence()) + || !plannedAnchorInventorySnapshotRevision.equals(intent.inventorySnapshotRevision()) + || plannedPartitionId.compareTo(intent.layoutDescriptor().partitionCount()) >= 0) { + throw new IllegalArgumentException( + "Planned reservation work differs from the exact pending bootstrap layout tuple"); + } + if (memberOperationId.equals(transitionId) + || memberOperationId.equals(memberPreparationFenceId) + || memberPreparationFenceId.equals(reservationFence)) { + throw new IllegalArgumentException( + "Member preparation identity must remain separate from reservation provenance"); + } + } + + private static void requireNonNegative(long value, String name) { + if (value < 0L) throw new IllegalArgumentException(name + " must be non-negative"); + } + + private static void requireNonNegative(BigInteger value, String name) { + Objects.requireNonNull(value, name); + if (value.signum() < 0) throw new IllegalArgumentException(name + " must be non-negative"); + } + + private static void requirePositive(BigInteger value, String name) { + Objects.requireNonNull(value, name); + if (value.signum() <= 0) throw new IllegalArgumentException(name + " must be positive"); + } + + private static UUID requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException(name + " must not be nil"); + return value; + } + + private static String requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(name + " must be a canonical SHA-256 digest"); + } + return value; + } + } + + record Blocker( + long blockerOrdinal, long sourceRowOrdinal, String sourceRowDigest, BlockerCode code) { + Blocker { + if (blockerOrdinal < 0L || sourceRowOrdinal < 0L) { + throw new IllegalArgumentException("Blocker ordinals must be non-negative"); + } + requireDigest(sourceRowDigest, "sourceRowDigest"); + Objects.requireNonNull(code, "code"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java new file mode 100644 index 0000000000..e0a6aaa612 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java @@ -0,0 +1,1809 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +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.Arrays; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.IssuerEvent; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationDisposition; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Game Session-owned preparation owner for the first physical issuer-partition build. + * + *

It consumes only the exact persisted pending V1030 bootstrap operation and its complete + * cohort. It does not write Redis, publish an active pointer, install an anchor, issue coverage, or + * authorize ordinary admission. + */ +final class CanonicalGameplayIssuerPartitionBuildRepository { + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String INVENTORY_CLOCK = "game_session_canonical_binding_inventory_clock"; + private static final String LEGACY_DISPOSITION = + "game_session_canonical_binding_legacy_disposition"; + private static final String BOOTSTRAP_CONTROL = + "game_session_canonical_issuer_layout_bootstrap_control"; + private static final String BOOTSTRAP_INTENT = + "game_session_canonical_issuer_layout_bootstrap_intent"; + private static final String BOOTSTRAP_COHORT = + "game_session_canonical_issuer_layout_bootstrap_cohort_row"; + private static final String BUILD_PLAN = "game_session_canonical_issuer_partition_build_plan"; + private static final String BUILD_COHORT = + "game_session_canonical_issuer_partition_build_cohort_row"; + private static final String MEMBER_WORK = + "game_session_canonical_issuer_partition_build_member_work"; + private static final String BUILD_BLOCKER = + "game_session_canonical_issuer_partition_build_blocker"; + private static final String MAPPING_IDENTITY = + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final ObjectMapper JSON = new ObjectMapper(); + + private static final String COHORT_SQL = + "SELECT source_kind, source_key, source_revision, source_row_json FROM (" + + "SELECT CASE WHEN i.issuer_id = ? THEN 'BINDING'" + + " ELSE 'UNRESOLVED_LEGACY_BINDING' END AS source_kind," + + " encode(i.binding_ref, 'hex') AS source_key, i.inventory_revision AS source_revision," + + " to_jsonb(i)::text AS source_row_json FROM game_session_canonical_gameplay_binding_inventory i" + + " WHERE i.inventory_revision <= ?" + + " UNION ALL SELECT 'TRANSITION' AS source_kind, t.transition_id::text AS source_key," + + " t.inventory_revision AS source_revision, to_jsonb(t)::text AS source_row_json" + + " FROM game_session_canonical_binding_transition t WHERE t.inventory_revision <= ?" + + " UNION ALL SELECT CASE WHEN r.issuer_id = ? THEN 'RESERVATION'" + + " ELSE 'UNRESOLVED_LEGACY_RESERVATION' END AS source_kind," + + " r.reservation_id::text AS source_key, r.inventory_revision AS source_revision," + + " to_jsonb(r)::text AS source_row_json FROM game_session_canonical_issuer_partition_reservation r" + + " WHERE r.inventory_revision <= ?" + + " UNION ALL SELECT 'ACCOUNT_OBLIGATION' AS source_kind," + + " a.transition_id::text || ':' || a.obligation_ordinal::text AS source_key," + + " a.inventory_revision AS source_revision, to_jsonb(a)::text AS source_row_json" + + " FROM game_session_canonical_binding_account_index_obligation a" + + " WHERE a.inventory_revision <= ?" + + " UNION ALL SELECT 'ISSUER_OBLIGATION' AS source_kind," + + " encode(o.binding_ref, 'hex') || ':' || o.transition_id::text AS source_key," + + " o.inventory_revision AS source_revision, to_jsonb(o)::text AS source_row_json" + + " FROM game_session_canonical_binding_issuer_index_obligation o" + + " WHERE o.inventory_revision <= ?" + + " UNION ALL SELECT 'REGION_OBLIGATION' AS source_kind," + + " g.transition_id::text AS source_key, g.inventory_revision AS source_revision," + + " to_jsonb(g)::text AS source_row_json" + + " FROM game_session_canonical_binding_region_bridge_obligation g" + + " WHERE g.inventory_revision <= ?" + + ") captured_cohort ORDER BY source_kind COLLATE \"C\", source_key COLLATE \"C\""; + + private static final String FUTURE_REVISION_SQL = + "SELECT EXISTS (SELECT 1 FROM game_session_canonical_gameplay_binding_inventory" + + " WHERE inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_transition" + + " WHERE inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_issuer_partition_reservation" + + " WHERE inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_account_index_obligation" + + " WHERE inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_issuer_index_obligation" + + " WHERE inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_region_bridge_obligation" + + " WHERE inventory_revision > ?) AS has_future_revision"; + + private final DSLContext dsl; + + CanonicalGameplayIssuerPartitionBuildRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Prepares or resumes the immutable plan for one exact pending bootstrap operation/request pair. + * No caller-provided layout or member list is accepted. + */ + CanonicalGameplayIssuerPartitionBuildPlan prepareInitialBuildPlan( + UUID bootstrapOperationId, UUID bootstrapRequestId) { + requireNonNil(bootstrapOperationId, "bootstrapOperationId"); + requireNonNil(bootstrapRequestId, "bootstrapRequestId"); + if (bootstrapOperationId.equals(bootstrapRequestId)) { + throw conflict("Bootstrap operation and request identities must be distinct"); + } + requireNoAmbientTransaction(); + return dsl.transactionResult( + configuration -> + prepareInTransaction( + DSL.using(configuration), bootstrapOperationId, bootstrapRequestId)); + } + + private CanonicalGameplayIssuerPartitionBuildPlan prepareInTransaction( + DSLContext transaction, UUID bootstrapOperationId, UUID bootstrapRequestId) { + // Keep the same serialization order as V1030 and ordinary inventory preparation. + BigInteger currentInventoryRevision = lockInventoryRevision(transaction); + Record control = lockControl(transaction, ISSUER); + if (control == null) { + Record orphan = + transaction.fetchOne( + "SELECT operation_id FROM " + BOOTSTRAP_INTENT + " WHERE issuer_id = ?", ISSUER); + if (orphan != null) { + throw conflict("Pending issuer-bootstrap intent lost its positive current control row"); + } + throw conflict("Exact pending issuer-bootstrap control row is missing"); + } + Record intentRow = lockIntent(transaction, bootstrapOperationId); + if (intentRow == null) { + throw conflict("Exact pending issuer-bootstrap operation is missing"); + } + CanonicalGameplayIssuerLayoutBootstrapIntent intent = + loadAndRequireCurrentIntent( + transaction, + control, + intentRow, + bootstrapOperationId, + bootstrapRequestId, + currentInventoryRevision); + + List currentRows = + captureCurrentCohort(transaction, intent.inventorySnapshotRevision()); + requireSameCohort(intent.cohortRows(), currentRows); + DerivedPlan derived = derivePlan(intent, currentRows); + + Record existing = + transaction.fetchOne( + "SELECT * FROM " + BUILD_PLAN + " WHERE bootstrap_operation_id = ? FOR UPDATE", + bootstrapOperationId); + if (existing != null) { + return loadAndRequireExactPlan(transaction, intent, currentRows, derived, existing); + } + + Set reservedIdentities = collectSourceIdentities(intent, derived); + UUID buildOperationId = nextUniqueUuid(reservedIdentities); + UUID buildPreparationFenceId = nextUniqueUuid(reservedIdentities); + List memberWorks = + new ArrayList<>(derived.reservations().size()); + for (int index = 0; index < derived.reservations().size(); index++) { + PlannedReservation planned = derived.reservations().get(index); + memberWorks.add( + toMemberWork( + planned, + index, + nextUniqueUuid(reservedIdentities), + nextUniqueUuid(reservedIdentities), + intent)); + } + List blockers = + toBlockers(derived.blockers(), intent.cohortRows()); + String digest = + digestPlan( + buildOperationId, + buildPreparationFenceId, + intent, + intent.cohortRows(), + memberWorks, + blockers); + CanonicalGameplayIssuerPartitionBuildPlan plan = + new CanonicalGameplayIssuerPartitionBuildPlan( + buildOperationId, + buildPreparationFenceId, + intent, + intent.cohortRows(), + memberWorks, + blockers, + digest); + insertPlan(transaction, plan); + return loadAndRequireExactPlan( + transaction, + intent, + currentRows, + derived, + Objects.requireNonNull( + transaction.fetchOne( + "SELECT * FROM " + BUILD_PLAN + " WHERE bootstrap_operation_id = ? FOR UPDATE", + bootstrapOperationId), + "saved issuer partition build plan must be readable")); + } + + private static CanonicalGameplayIssuerLayoutBootstrapIntent loadAndRequireCurrentIntent( + DSLContext transaction, + Record control, + Record intent, + UUID expectedOperationId, + UUID expectedRequestId, + BigInteger currentInventoryRevision) { + UUID operationId = requireNonNil(intent.get("operation_id", UUID.class), "operation_id"); + UUID requestId = requireNonNil(intent.get("request_id", UUID.class), "request_id"); + String issuerId = Objects.requireNonNull(intent.get("issuer_id", String.class), "issuer_id"); + BigInteger controlEpoch = readBigInteger(intent, "control_epoch"); + BigInteger operationFence = readBigInteger(intent, "operation_fence"); + BigInteger coverageFence = readBigInteger(intent, "coverage_fence"); + BigInteger snapshotRevision = readBigInteger(intent, "inventory_snapshot_revision"); + BigInteger controlLastFence = readBigInteger(control, "last_issued_fence"); + if (!operationId.equals(expectedOperationId) + || !requestId.equals(expectedRequestId) + || !ISSUER.equals(issuerId) + || !issuerId.equals(control.get("issuer_id", String.class)) + || !"INITIAL_BOOTSTRAP_INTENT".equals(control.get("state", String.class)) + || !operationId.equals(control.get("current_operation_id", UUID.class)) + || !controlEpoch.equals(readBigInteger(control, "control_epoch")) + || !operationFence.equals(readBigInteger(control, "current_operation_fence")) + || !coverageFence.equals(readBigInteger(control, "current_coverage_fence")) + || !operationFence.equals(controlEpoch) + || operationFence.equals(coverageFence) + || controlLastFence.compareTo(coverageFence) < 0 + || !"INITIAL_BOOTSTRAP_INTENT".equals(intent.get("intent_state", String.class))) { + throw conflict("Pending bootstrap request or exact current control tuple changed"); + } + if (!snapshotRevision.equals(currentInventoryRevision)) { + throw conflict("Canonical issuer inventory advanced after its pending bootstrap snapshot"); + } + + byte[] descriptorBytes = requireBytes(intent, "layout_descriptor_bytes"); + String descriptorDigest = requireText(intent, "layout_descriptor_digest"); + if (!sha256(descriptorBytes).equals(descriptorDigest)) { + throw conflict("Persisted bootstrap layout descriptor digest is invalid"); + } + String mappingIdentity = requireText(intent, "mapping_identity"); + if (!MAPPING_IDENTITY.equals(mappingIdentity)) { + throw conflict("Persisted bootstrap layout uses an unsupported canonical mapping"); + } + CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor descriptor; + try { + descriptor = + new CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor( + issuerId, + readBigInteger(intent, "layout_version"), + readBigInteger(intent, "partition_count"), + readBigInteger(intent, "partition_capacity"), + mappingIdentity, + descriptorBytes, + descriptorDigest); + } catch (RuntimeException malformed) { + throw conflict("Persisted bootstrap layout descriptor is malformed"); + } + + byte[] checkpointBytes = requireBytes(intent, "source_checkpoint_bytes"); + String checkpointDigest = requireText(intent, "source_checkpoint_digest"); + byte[] eventBytes = intent.get("source_event_bytes", byte[].class); + String eventDigest = intent.get("source_event_digest", String.class); + if (!sha256(checkpointBytes).equals(checkpointDigest) + || ((eventBytes == null) != (eventDigest == null)) + || (eventBytes != null && !sha256(eventBytes).equals(eventDigest))) { + throw conflict("Persisted Account issuer source checkpoint digest is invalid"); + } + BigInteger issuerGeneration = readBigInteger(intent, "issuer_auth_generation"); + if (eventBytes != null) requireValidSourceEvent(issuerId, issuerGeneration, eventBytes); + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint checkpoint; + try { + checkpoint = + new CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint( + issuerId, + issuerGeneration, + checkpointBytes, + checkpointDigest, + eventBytes, + eventDigest); + } catch (RuntimeException malformed) { + throw conflict("Persisted Account issuer source checkpoint is malformed"); + } + + CanonicalGameplayLegacyMigrationDisposition storedLegacy; + CanonicalGameplayLegacyMigrationDisposition currentLegacy; + try { + storedLegacy = persistedLegacyDisposition(intent); + currentLegacy = readCurrentLegacyDisposition(transaction, snapshotRevision); + } catch (RuntimeException malformed) { + throw conflict("Current verified legacy disposition is missing or malformed"); + } + if (!storedLegacy.equals(currentLegacy)) { + throw conflict("Verified legacy disposition changed after pending bootstrap capture"); + } + + List rows = readStoredCohort(transaction, operationId); + long expectedCount = requireLong(intent, "cohort_row_count"); + String expectedDigest = requireText(intent, "cohort_digest"); + List cohortRows = + rows.stream().map(IssuerCohortSourceRow::cohortRow).toList(); + if (cohortRows.size() != expectedCount + || !digestCohortRows(cohortRows).equals(expectedDigest) + || cohortRows.stream() + .anyMatch(row -> row.sourceInventoryRevision().compareTo(snapshotRevision) > 0)) { + throw conflict("Persisted bootstrap cohort is incomplete or its exact digest changed"); + } + + return new CanonicalGameplayIssuerLayoutBootstrapIntent( + operationId, + requestId, + issuerId, + controlEpoch, + operationFence, + coverageFence, + snapshotRevision, + descriptor, + checkpoint, + storedLegacy, + CanonicalGameplayIssuerLayoutBootstrapIntent.State.INITIAL_BOOTSTRAP_INTENT, + cohortRows, + expectedDigest); + } + + private static List readStoredCohort( + DSLContext transaction, UUID operationId) { + return transaction + .fetch( + "SELECT * FROM " + BOOTSTRAP_COHORT + " WHERE operation_id = ? ORDER BY row_ordinal", + operationId) + .map( + row -> { + String sourceJson = requireText(row, "source_row_json"); + String digest = requireText(row, "source_row_digest"); + if (!sha256(sourceJson.getBytes(StandardCharsets.UTF_8)).equals(digest)) { + throw conflict("Frozen bootstrap cohort contains a changed source-row digest"); + } + if (!operationId.equals(row.get("operation_id", UUID.class)) + || !ISSUER.equals(row.get("issuer_id", String.class))) { + throw conflict("Frozen bootstrap cohort row lost its exact owner linkage"); + } + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow cohortRow; + try { + cohortRow = + new CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow( + requireLong(row, "row_ordinal"), + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.valueOf( + requireText(row, "source_kind")), + requireText(row, "source_key"), + readBigInteger(row, "source_inventory_revision"), + sourceJson, + digest); + } catch (RuntimeException malformed) { + throw conflict("Frozen bootstrap cohort row is malformed"); + } + return new IssuerCohortSourceRow(cohortRow); + }); + } + + private static CanonicalGameplayLegacyMigrationDisposition persistedLegacyDisposition( + Record row) { + return new CanonicalGameplayLegacyMigrationDisposition( + requireNonNil(row.get("legacy_cohort_id", UUID.class), "legacy_cohort_id"), + requireNonNil( + row.get("legacy_owner_operation_id", UUID.class), "legacy_owner_operation_id"), + requireNonNil(row.get("legacy_writer_fence", UUID.class), "legacy_writer_fence"), + readBigInteger(row, "legacy_source_snapshot_revision"), + readBigInteger(row, "legacy_canonical_inventory_revision"), + readBigInteger(row, "legacy_namespace_index_readback_revision"), + requireText(row, "legacy_evidence_digest")); + } + + private static CanonicalGameplayLegacyMigrationDisposition readCurrentLegacyDisposition( + DSLContext transaction, BigInteger snapshotRevision) { + Record row = + transaction.fetchOne( + "SELECT * FROM " + LEGACY_DISPOSITION + " WHERE singleton_id = 1 FOR SHARE"); + if (row == null || !"VERIFIED".equals(row.get("disposition_state", String.class))) { + throw conflict("Initial issuer build requires the actual VERIFIED legacy disposition"); + } + CanonicalGameplayLegacyMigrationDisposition current = + new CanonicalGameplayLegacyMigrationDisposition( + row.get("cohort_id", UUID.class), + row.get("owner_operation_id", UUID.class), + row.get("legacy_writer_fence", UUID.class), + readBigInteger(row, "source_snapshot_revision"), + readBigInteger(row, "canonical_inventory_revision"), + readBigInteger(row, "namespace_index_readback_revision"), + row.get("evidence_digest", String.class)); + if (current.canonicalInventoryRevision().compareTo(snapshotRevision) > 0) { + throw conflict("Verified legacy disposition is newer than the frozen inventory snapshot"); + } + return current; + } + + private static List captureCurrentCohort( + DSLContext transaction, BigInteger snapshotRevision) { + requireNoFutureRows(transaction, snapshotRevision); + return transaction + .fetch( + COHORT_SQL, + ISSUER, + decimal(snapshotRevision), + decimal(snapshotRevision), + ISSUER, + decimal(snapshotRevision), + decimal(snapshotRevision), + decimal(snapshotRevision), + decimal(snapshotRevision)) + .map( + row -> { + String sourceJson = requireText(row, "source_row_json"); + String sourceKey = requireText(row, "source_key"); + BigInteger sourceRevision = readBigInteger(row, "source_revision"); + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind kind; + try { + kind = + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.valueOf( + requireText(row, "source_kind")); + } catch (RuntimeException malformed) { + throw conflict("Current issuer inventory contains an unsupported source family"); + } + if (sourceRevision.compareTo(snapshotRevision) > 0) { + throw conflict( + "Current issuer inventory source is newer than its bootstrap snapshot"); + } + return new IssuerCohortSourceRow( + new CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow( + 0L, + kind, + sourceKey, + sourceRevision, + sourceJson, + sha256(sourceJson.getBytes(StandardCharsets.UTF_8)))); + }); + } + + private static void requireSameCohort( + List frozen, + List current) { + List sorted = + current.stream() + .sorted( + Comparator.comparing((IssuerCohortSourceRow row) -> row.cohortRow().kind().name()) + .thenComparing(row -> row.cohortRow().sourceKey())) + .toList(); + if (frozen.size() != sorted.size()) { + throw conflict( + "Current source inventory no longer equals its complete frozen bootstrap cohort"); + } + for (int index = 0; index < frozen.size(); index++) { + var expected = frozen.get(index); + var row = sorted.get(index).cohortRow(); + if (expected.rowOrdinal() != index + || expected.kind() != row.kind() + || !expected.sourceKey().equals(row.sourceKey()) + || !expected.sourceInventoryRevision().equals(row.sourceInventoryRevision()) + || !expected.sourceRowJson().equals(row.sourceRowJson()) + || !expected.sourceRowDigest().equals(row.sourceRowDigest())) { + throw conflict("Current source row differs from its exact original bootstrap cohort entry"); + } + } + } + + private static DerivedPlan derivePlan( + CanonicalGameplayIssuerLayoutBootstrapIntent intent, + List currentRows) { + List cohortRows = + currentRows.stream() + .sorted( + Comparator.comparing((IssuerCohortSourceRow row) -> row.cohortRow().kind().name()) + .thenComparing(row -> row.cohortRow().sourceKey())) + .map( + row -> { + var source = row.cohortRow(); + return new CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow( + currentRows.indexOf(row), + source.kind(), + source.sourceKey(), + source.sourceInventoryRevision(), + source.sourceRowJson(), + source.sourceRowDigest()); + }) + .toList(); + List blockers = new ArrayList<>(); + Map reservations = new HashMap<>(); + Map> bindings = new HashMap<>(); + Map byOrdinal = new HashMap<>(); + for (var row : cohortRows) byOrdinal.put(row.rowOrdinal(), row); + + for (var row : cohortRows) { + switch (row.kind()) { + case UNRESOLVED_LEGACY_BINDING -> + blockers.add( + new PlanBlocker( + row.rowOrdinal(), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode + .UNRESOLVED_LEGACY_BINDING)); + case UNRESOLVED_LEGACY_RESERVATION -> + blockers.add( + new PlanBlocker( + row.rowOrdinal(), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode + .UNRESOLVED_LEGACY_RESERVATION)); + case RESERVATION -> { + try { + ReservationSource parsed = parseReservation(row); + if (reservations.putIfAbsent(parsed.reservationId(), parsed) != null) { + blockers.add( + new PlanBlocker( + row.rowOrdinal(), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode + .UNREPRESENTABLE_RESERVATION)); + } + } catch (RuntimeException malformed) { + blockers.add( + new PlanBlocker( + row.rowOrdinal(), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode + .UNREPRESENTABLE_RESERVATION)); + } + } + case BINDING -> { + try { + BindingSource parsed = parseBinding(row); + bindings + .computeIfAbsent(parsed.reservationId(), ignored -> new ArrayList<>()) + .add(parsed); + } catch (RuntimeException malformed) { + blockers.add( + new PlanBlocker( + row.rowOrdinal(), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode.UNREPRESENTABLE_BINDING)); + } + } + default -> { + // Transition and obligation rows remain in the exact cohort artifact and plan digest. + } + } + } + + Map bindingOrdinalByReservation = new HashMap<>(); + for (var entry : bindings.entrySet()) { + List rows = entry.getValue(); + if (rows.size() != 1) { + rows.forEach( + row -> + blockers.add( + new PlanBlocker( + row.rowOrdinal(), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode + .CONFLICTING_RESERVATION_LINK))); + continue; + } + BindingSource binding = rows.get(0); + ReservationSource reservation = reservations.get(entry.getKey()); + if (reservation == null) { + blockers.add( + new PlanBlocker( + binding.rowOrdinal(), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode.MISSING_RESERVATION)); + } else if (!binding.matches(reservation)) { + blockers.add( + new PlanBlocker( + reservation.rowOrdinal(), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode + .CONFLICTING_RESERVATION_LINK)); + blockers.add( + new PlanBlocker( + binding.rowOrdinal(), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode + .CONFLICTING_RESERVATION_LINK)); + } else { + bindingOrdinalByReservation.put(entry.getKey(), binding.rowOrdinal()); + } + } + + List initialLayoutReservations = new ArrayList<>(); + for (ReservationSource reservation : + reservations.values().stream() + .sorted(Comparator.comparingLong(ReservationSource::rowOrdinal)) + .toList()) { + if (matchesInitialLayout(reservation, intent)) { + initialLayoutReservations.add(reservation); + } else { + blockers.add( + new PlanBlocker( + reservation.rowOrdinal(), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode + .CONFLICTING_RESERVATION_LINK)); + } + } + + List planned = + initialLayoutReservations.stream() + .map( + reservation -> { + Long bindingOrdinal = + bindingOrdinalByReservation.get(reservation.reservationId()); + String bindingDigest = + bindingOrdinal == null + ? null + : byOrdinal.get(bindingOrdinal).sourceRowDigest(); + BigInteger partitionId; + try { + partitionId = + CanonicalGameplayBindingRef.fromExactBytes(reservation.bindingRef()) + .partitionId(intent.layoutDescriptor().partitionCount()); + } catch (RuntimeException malformed) { + blockers.add( + new PlanBlocker( + reservation.rowOrdinal(), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode + .UNREPRESENTABLE_RESERVATION)); + return null; + } + return new PlannedReservation( + reservation, bindingOrdinal, bindingDigest, partitionId); + }) + .filter(Objects::nonNull) + .toList(); + requireIssuerSourceLinks( + cohortRows, reservations, bindingOrdinalByReservation, bindings, blockers); + Map> countedByPartition = new HashMap<>(); + List countedReservations = + planned.stream() + .filter(item -> !item.reservation().lifecycle().equals("RELEASED")) + .toList(); + for (PlannedReservation item : countedReservations) { + countedByPartition + .computeIfAbsent(item.plannedPartitionId(), ignored -> new ArrayList<>()) + .add(item); + } + for (List partitionReservations : countedByPartition.values()) { + if (BigInteger.valueOf(partitionReservations.size()) + .compareTo(intent.layoutDescriptor().partitionCapacity()) + > 0) { + partitionReservations.forEach( + item -> + blockers.add( + new PlanBlocker( + item.reservation().rowOrdinal(), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode + .PARTITION_CAPACITY_EXCEEDED))); + } + } + BigInteger aggregateCapacity = + intent + .layoutDescriptor() + .partitionCount() + .multiply(intent.layoutDescriptor().partitionCapacity()); + if (BigInteger.valueOf(countedReservations.size()).compareTo(aggregateCapacity) > 0) { + countedReservations.forEach( + item -> + blockers.add( + new PlanBlocker( + item.reservation().rowOrdinal(), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode + .AGGREGATE_CAPACITY_EXCEEDED))); + } + blockers.sort( + Comparator.comparingLong(PlanBlocker::sourceRowOrdinal) + .thenComparing(blocker -> blocker.code().name())); + return new DerivedPlan(planned, blockers); + } + + /** Initial bootstrap adopts its frozen layout; it does not migrate reservations to a new one. */ + private static boolean matchesInitialLayout( + ReservationSource reservation, CanonicalGameplayIssuerLayoutBootstrapIntent intent) { + var layout = intent.layoutDescriptor(); + if (!reservation.layoutVersion().equals(layout.layoutVersion()) + || !reservation.partitionCount().equals(layout.partitionCount()) + || !reservation.partitionCapacity().equals(layout.partitionCapacity())) { + return false; + } + try { + BigInteger originalCanonicalPartition = + CanonicalGameplayBindingRef.fromExactBytes(reservation.bindingRef()) + .partitionId(reservation.partitionCount()); + return originalCanonicalPartition.equals(reservation.partitionId()); + } catch (RuntimeException malformed) { + return false; + } + } + + private static ReservationSource parseReservation( + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow row) { + JsonNode json = parseObject(row.sourceRowJson()); + UUID reservationId = uuid(json, "reservation_id"); + if (!reservationId.toString().equals(row.sourceKey())) { + throw conflict("Reservation cohort key differs from its original SQL row"); + } + String issuerId = text(json, "issuer_id"); + if (!ISSUER.equals(issuerId)) + throw conflict("Reservation does not use the exact Account issuer"); + byte[] bindingRef = bytea(json, "binding_ref"); + CanonicalGameplayBindingRef.fromExactBytes(bindingRef); + String tenantId = text(json, "tenant_id"); + String gameInstanceId = text(json, "game_instance_id"); + String sessionId = text(json, "session_id"); + if (!Arrays.equals( + bindingRef, CanonicalGameplayBindingRef.of(tenantId, gameInstanceId, sessionId).bytes())) { + throw conflict("Reservation owner identifiers do not match its original bindingRef bytes"); + } + String lifecycle = text(json, "lifecycle"); + if (!List.of("RESERVED", "BOUND", "RELEASE_PENDING", "RELEASED").contains(lifecycle)) { + throw conflict("Reservation lifecycle is not representable by the canonical owner"); + } + BigInteger sourceRevision = integer(json, "inventory_revision"); + if (!sourceRevision.equals(row.sourceInventoryRevision())) { + throw conflict("Reservation cohort revision differs from its original SQL row"); + } + BigInteger partitionId = integer(json, "partition_id"); + BigInteger layoutVersion = integer(json, "issuer_index_layout_version"); + BigInteger partitionCount = integer(json, "issuer_index_partition_count"); + BigInteger partitionCapacity = integer(json, "issuer_index_partition_capacity"); + if (partitionId.signum() < 0 + || layoutVersion.signum() <= 0 + || partitionCount.signum() <= 0 + || partitionCapacity.signum() <= 0 + || partitionId.compareTo(partitionCount) >= 0) { + throw conflict("Original reservation layout or partition is malformed"); + } + BigInteger originalSnapshot = integer(json, "inventory_snapshot_revision"); + BigInteger originalOperationFence = integer(json, "issuer_coverage_operation_fence"); + BigInteger originalCoverageFence = integer(json, "coverage_fence"); + if (originalSnapshot.signum() <= 0 + || originalOperationFence.signum() <= 0 + || originalCoverageFence.signum() <= 0) { + throw conflict("Original reservation coverage tuple is malformed"); + } + return new ReservationSource( + row.rowOrdinal(), + row.sourceRowDigest(), + reservationId, + bindingRef, + uuid(json, "transition_id"), + uuid(json, "reservation_fence"), + lifecycle, + partitionId, + layoutVersion, + partitionCount, + partitionCapacity, + uuid(json, "issuer_coverage_operation_id"), + originalOperationFence, + originalCoverageFence, + originalSnapshot, + integer(json, "binding_generation"), + text(json, "account_id"), + tenantId, + text(json, "playable_state_namespace_id"), + text(json, "character_id"), + text(json, "playable_state_scope"), + gameInstanceId, + integer(json, "runtime_game_instance_id"), + sessionId, + text(json, "region_id"), + integer(json, "region_epoch"), + issuerId, + integer(json, "issuer_auth_generation")); + } + + private static BindingSource parseBinding( + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow row) { + JsonNode json = parseObject(row.sourceRowJson()); + byte[] bindingRef = bytea(json, "binding_ref"); + CanonicalGameplayBindingRef.fromExactBytes(bindingRef); + if (!HexFormat.of().formatHex(bindingRef).equals(row.sourceKey())) { + throw conflict("Binding cohort key differs from its original SQL row"); + } + String issuerId = text(json, "issuer_id"); + if (!ISSUER.equals(issuerId)) { + throw conflict("Binding source does not use the exact Account issuer"); + } + return new BindingSource( + row.rowOrdinal(), + row.sourceRowDigest(), + uuid(json, "issuer_reservation_id"), + bindingRef, + uuid(json, "transition_id"), + text(json, "account_id"), + text(json, "tenant_id"), + text(json, "playable_state_namespace_id"), + text(json, "character_id"), + text(json, "playable_state_scope"), + text(json, "game_instance_id"), + integer(json, "runtime_game_instance_id"), + text(json, "session_id"), + text(json, "region_id"), + integer(json, "region_epoch"), + issuerId, + integer(json, "issuer_auth_generation"), + integer(json, "issuer_index_layout_version"), + integer(json, "issuer_index_partition_count"), + integer(json, "issuer_index_partition_capacity"), + integer(json, "issuer_partition_id"), + integer(json, "binding_generation")); + } + + private static CanonicalGameplayIssuerPartitionBuildPlan.MemberWork toMemberWork( + PlannedReservation planned, + int ordinal, + UUID memberOperationId, + UUID memberPreparationFenceId, + CanonicalGameplayIssuerLayoutBootstrapIntent intent) { + ReservationSource reservation = planned.reservation(); + return new CanonicalGameplayIssuerPartitionBuildPlan.MemberWork( + ordinal, + memberOperationId, + memberPreparationFenceId, + reservation.rowOrdinal(), + reservation.sourceRowDigest(), + planned.bindingSourceRowOrdinal(), + planned.bindingSourceRowDigest(), + reservation.reservationId(), + reservation.bindingRef(), + reservation.transitionId(), + reservation.lifecycle(), + reservation.reservationFence(), + reservation.partitionId(), + reservation.layoutVersion(), + reservation.partitionCount(), + reservation.partitionCapacity(), + reservation.coverageOperationId(), + reservation.coverageOperationFence(), + reservation.coverageFence(), + reservation.inventorySnapshotRevision(), + planned.plannedPartitionId(), + intent.operationId(), + intent.operationFence(), + intent.coverageFence(), + intent.inventorySnapshotRevision()); + } + + private static List toBlockers( + List blockers, + List cohort) { + return java.util.stream.IntStream.range(0, blockers.size()) + .mapToObj( + index -> { + PlanBlocker blocker = blockers.get(index); + return new CanonicalGameplayIssuerPartitionBuildPlan.Blocker( + index, + blocker.sourceRowOrdinal(), + cohort.get((int) blocker.sourceRowOrdinal()).sourceRowDigest(), + blocker.code()); + }) + .toList(); + } + + private static void requireIssuerSourceLinks( + List cohortRows, + Map reservations, + Map bindingOrdinalByReservation, + Map> bindings, + List blockers) { + for (var row : cohortRows) { + if (row.kind() != CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.TRANSITION + && row.kind() + != CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.ISSUER_OBLIGATION) { + continue; + } + try { + JsonNode json = parseObject(row.sourceRowJson()); + UUID transitionId = uuid(json, "transition_id"); + boolean transitionRow = + row.kind() == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.TRANSITION; + UUID reservationId = uuid(json, transitionRow ? "issuer_reservation_id" : "reservation_id"); + byte[] bindingRef = bytea(json, transitionRow ? "candidate_binding_ref" : "binding_ref"); + BigInteger bindingGeneration = + integer(json, transitionRow ? "candidate_binding_generation" : "binding_generation"); + ReservationSource reservation = reservations.get(reservationId); + List matchingBindings = bindings.get(reservationId); + Long linkedBindingOrdinal = bindingOrdinalByReservation.get(reservationId); + if (reservation == null + || !reservation.transitionId().equals(transitionId) + || !Arrays.equals(reservation.bindingRef(), bindingRef) + || !reservation.bindingGeneration().equals(bindingGeneration) + || matchingBindings == null + || matchingBindings.size() != 1 + || linkedBindingOrdinal == null + || !matchingBindings.get(0).matches(reservation)) { + blockers.add( + new PlanBlocker( + row.rowOrdinal(), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode + .CONFLICTING_RESERVATION_LINK)); + } + if (transitionRow && !row.sourceKey().equals(transitionId.toString())) { + blockers.add( + new PlanBlocker( + row.rowOrdinal(), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode.UNREPRESENTABLE_SOURCE)); + } + if (!transitionRow) { + String expectedKey = HexFormat.of().formatHex(bindingRef) + ":" + transitionId; + if (!row.sourceKey().equals(expectedKey)) { + blockers.add( + new PlanBlocker( + row.rowOrdinal(), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode.UNREPRESENTABLE_SOURCE)); + } + } + } catch (RuntimeException malformed) { + blockers.add( + new PlanBlocker( + row.rowOrdinal(), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode.UNREPRESENTABLE_SOURCE)); + } + } + } + + private static Set collectSourceIdentities( + CanonicalGameplayIssuerLayoutBootstrapIntent intent, DerivedPlan derived) { + Set result = new HashSet<>(); + result.add(intent.operationId()); + result.add(intent.requestId()); + for (var reservation : derived.reservations()) { + result.add(reservation.reservation().reservationId()); + result.add(reservation.reservation().transitionId()); + result.add(reservation.reservation().reservationFence()); + result.add(reservation.reservation().coverageOperationId()); + } + for (var row : intent.cohortRows()) { + try { + result.add(UUID.fromString(row.sourceKey())); + } catch (IllegalArgumentException ignored) { + // Binding and issuer-obligation source keys are exact byte encodings, not UUIDs. + } + } + return result; + } + + private static UUID nextUniqueUuid(Set reserved) { + UUID candidate; + do { + candidate = UUID.randomUUID(); + } while (candidate.equals(NIL_UUID) || !reserved.add(candidate)); + return candidate; + } + + private static void insertPlan( + DSLContext transaction, CanonicalGameplayIssuerPartitionBuildPlan plan) { + var intent = plan.bootstrapIntent(); + var descriptor = intent.layoutDescriptor(); + transaction.execute( + "INSERT INTO " + + BUILD_PLAN + + " (build_operation_id, build_preparation_fence_id, bootstrap_operation_id," + + " bootstrap_request_id, issuer_id, control_epoch, bootstrap_operation_fence," + + " bootstrap_coverage_fence, issuer_inventory_snapshot_revision, layout_version," + + " partition_count, partition_capacity, mapping_identity, layout_descriptor_bytes," + + " layout_descriptor_digest, cohort_row_count, cohort_digest, member_work_count," + + " blocker_count, plan_state, coverage_generation_state, coverage_generation, plan_digest)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?)", + plan.buildOperationId(), + plan.buildPreparationFenceId(), + intent.operationId(), + intent.requestId(), + intent.issuerId(), + decimal(intent.controlEpoch()), + decimal(intent.operationFence()), + decimal(intent.coverageFence()), + decimal(intent.inventorySnapshotRevision()), + decimal(descriptor.layoutVersion()), + decimal(descriptor.partitionCount()), + decimal(descriptor.partitionCapacity()), + descriptor.mappingIdentity(), + descriptor.exactDescriptorBytes(), + descriptor.descriptorDigest(), + (long) plan.cohortRows().size(), + intent.cohortDigest(), + (long) plan.memberWorks().size(), + (long) plan.blockers().size(), + plan.state().name(), + plan.coverageGenerationState().name(), + plan.planDigest()); + for (var row : plan.cohortRows()) { + transaction.execute( + "INSERT INTO " + + BUILD_COHORT + + " (build_operation_id, source_operation_id, issuer_id, source_row_ordinal," + + " source_kind, source_key, source_inventory_revision, source_row_json, source_row_digest)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + plan.buildOperationId(), + intent.operationId(), + intent.issuerId(), + row.rowOrdinal(), + row.kind().name(), + row.sourceKey(), + decimal(row.sourceInventoryRevision()), + row.sourceRowJson(), + row.sourceRowDigest()); + } + for (var work : plan.memberWorks()) insertMemberWork(transaction, plan, work); + for (var blocker : plan.blockers()) insertBlocker(transaction, plan, blocker); + } + + private static void insertMemberWork( + DSLContext transaction, + CanonicalGameplayIssuerPartitionBuildPlan plan, + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work) { + var intent = plan.bootstrapIntent(); + transaction.execute( + "INSERT INTO " + + MEMBER_WORK + + " (build_operation_id, bootstrap_operation_id, issuer_id, work_ordinal," + + " member_operation_id, member_preparation_fence_id, reservation_id," + + " reservation_source_row_ordinal, reservation_source_row_digest," + + " binding_source_row_ordinal, binding_source_row_digest, binding_ref, transition_id," + + " reservation_lifecycle, reservation_fence, original_partition_id," + + " original_layout_version, original_partition_count, original_partition_capacity," + + " original_issuer_coverage_operation_id, original_issuer_coverage_operation_fence," + + " original_coverage_fence, original_inventory_snapshot_revision, planned_partition_id," + + " planned_anchor_operation_id, planned_anchor_operation_fence," + + " planned_anchor_coverage_fence, planned_anchor_inventory_snapshot_revision," + + " counts_toward_capacity) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + plan.buildOperationId(), + intent.operationId(), + intent.issuerId(), + work.workOrdinal(), + work.memberOperationId(), + work.memberPreparationFenceId(), + work.reservationId(), + work.reservationSourceRowOrdinal(), + work.reservationSourceRowDigest(), + work.bindingSourceRowOrdinal(), + work.bindingSourceRowDigest(), + work.bindingRef(), + work.transitionId(), + work.reservationLifecycle(), + work.reservationFence(), + decimal(work.originalPartitionId()), + decimal(work.originalLayoutVersion()), + decimal(work.originalPartitionCount()), + decimal(work.originalPartitionCapacity()), + work.originalIssuerCoverageOperationId(), + decimal(work.originalIssuerCoverageOperationFence()), + decimal(work.originalCoverageFence()), + decimal(work.originalInventorySnapshotRevision()), + decimal(work.plannedPartitionId()), + work.plannedAnchorOperationId(), + decimal(work.plannedAnchorOperationFence()), + decimal(work.plannedAnchorCoverageFence()), + decimal(work.plannedAnchorInventorySnapshotRevision()), + work.countsTowardCapacity()); + } + + private static void insertBlocker( + DSLContext transaction, + CanonicalGameplayIssuerPartitionBuildPlan plan, + CanonicalGameplayIssuerPartitionBuildPlan.Blocker blocker) { + transaction.execute( + "INSERT INTO " + + BUILD_BLOCKER + + " (build_operation_id, blocker_ordinal, source_row_ordinal, source_row_digest, blocker_code)" + + " VALUES (?, ?, ?, ?, ?)", + plan.buildOperationId(), + blocker.blockerOrdinal(), + blocker.sourceRowOrdinal(), + blocker.sourceRowDigest(), + blocker.code().name()); + } + + private static CanonicalGameplayIssuerPartitionBuildPlan loadAndRequireExactPlan( + DSLContext transaction, + CanonicalGameplayIssuerLayoutBootstrapIntent intent, + List currentRows, + DerivedPlan derived, + Record header) { + UUID buildOperationId = + requireNonNil(header.get("build_operation_id", UUID.class), "build_operation_id"); + UUID buildFence = + requireNonNil( + header.get("build_preparation_fence_id", UUID.class), "build_preparation_fence_id"); + var descriptor = intent.layoutDescriptor(); + if (!Objects.equals(intent.operationId(), header.get("bootstrap_operation_id", UUID.class)) + || !Objects.equals(intent.requestId(), header.get("bootstrap_request_id", UUID.class)) + || !Objects.equals(intent.issuerId(), header.get("issuer_id", String.class)) + || !intent.controlEpoch().equals(readBigInteger(header, "control_epoch")) + || !intent.operationFence().equals(readBigInteger(header, "bootstrap_operation_fence")) + || !intent.coverageFence().equals(readBigInteger(header, "bootstrap_coverage_fence")) + || !intent + .inventorySnapshotRevision() + .equals(readBigInteger(header, "issuer_inventory_snapshot_revision")) + || !descriptor.layoutVersion().equals(readBigInteger(header, "layout_version")) + || !descriptor.partitionCount().equals(readBigInteger(header, "partition_count")) + || !descriptor.partitionCapacity().equals(readBigInteger(header, "partition_capacity")) + || !descriptor.mappingIdentity().equals(header.get("mapping_identity", String.class)) + || !Arrays.equals( + descriptor.exactDescriptorBytes(), header.get("layout_descriptor_bytes", byte[].class)) + || !descriptor + .descriptorDigest() + .equals(header.get("layout_descriptor_digest", String.class)) + || !"NOT_YET_ISSUED".equals(header.get("coverage_generation_state", String.class)) + || header.get("coverage_generation", BigDecimal.class) != null) { + throw conflict( + "Persisted build plan changed its exact pending bootstrap layout or anchor link"); + } + + List planRows = + transaction + .fetch( + "SELECT * FROM " + + BUILD_COHORT + + " WHERE build_operation_id = ? ORDER BY source_row_ordinal", + buildOperationId) + .map( + row -> { + String raw = requireText(row, "source_row_json"); + String digest = requireText(row, "source_row_digest"); + if (!sha256(raw.getBytes(StandardCharsets.UTF_8)).equals(digest) + || !intent.operationId().equals(row.get("source_operation_id", UUID.class)) + || !intent.issuerId().equals(row.get("issuer_id", String.class))) { + throw conflict("Build plan cohort row lost its exact bootstrap source link"); + } + return new IssuerCohortSourceRow( + new CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow( + requireLong(row, "source_row_ordinal"), + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.valueOf( + requireText(row, "source_kind")), + requireText(row, "source_key"), + readBigInteger(row, "source_inventory_revision"), + raw, + digest)); + }); + requireSameCohort(intent.cohortRows(), planRows); + if (!intent.cohortDigest().equals(header.get("cohort_digest", String.class)) + || planRows.size() != requireLong(header, "cohort_row_count")) { + throw conflict("Build plan no longer retains the complete original cohort"); + } + + List work = + transaction + .fetch( + "SELECT * FROM " + + MEMBER_WORK + + " WHERE build_operation_id = ? ORDER BY work_ordinal", + buildOperationId) + .map( + row -> { + if (!intent.operationId().equals(row.get("bootstrap_operation_id", UUID.class)) + || !intent.issuerId().equals(row.get("issuer_id", String.class))) { + throw conflict("Member work lost its exact bootstrap plan linkage"); + } + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork memberWork = + toMemberWork(row); + Boolean counted = row.get("counts_toward_capacity", Boolean.class); + if (!Objects.equals(counted, memberWork.countsTowardCapacity())) { + throw conflict( + "Member work capacity classification differs from its lifecycle"); + } + return memberWork; + }); + if (work.size() != requireLong(header, "member_work_count") + || work.size() != derived.reservations().size()) { + throw conflict("Build plan member work is incomplete or contains unplanned reservations"); + } + for (int index = 0; index < work.size(); index++) { + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork actual = work.get(index); + PlannedReservation expected = derived.reservations().get(index); + if (!sameWorkMapping(actual, expected, intent, index)) { + throw conflict("Build plan member work differs from its exact frozen reservation source"); + } + } + + List blockers = + transaction + .fetch( + "SELECT * FROM " + + BUILD_BLOCKER + + " WHERE build_operation_id = ? ORDER BY blocker_ordinal", + buildOperationId) + .map( + row -> + new CanonicalGameplayIssuerPartitionBuildPlan.Blocker( + requireLong(row, "blocker_ordinal"), + requireLong(row, "source_row_ordinal"), + requireText(row, "source_row_digest"), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode.valueOf( + requireText(row, "blocker_code")))); + List expectedBlockers = + toBlockers(derived.blockers(), intent.cohortRows()); + if (!sameBlockers(blockers, expectedBlockers) + || blockers.size() != requireLong(header, "blocker_count")) { + throw conflict("Build plan blocker set changed or omitted an unresolved cohort source"); + } + String expectedState = blockers.isEmpty() ? "PREPARED" : "BLOCKED"; + if (!expectedState.equals(header.get("plan_state", String.class))) { + throw conflict("Build plan state does not reflect its complete blocker set"); + } + requireUniquePreparationIdentities(buildOperationId, buildFence, intent, work); + String computedDigest = + digestPlan( + buildOperationId, + buildFence, + intent, + planRows.stream().map(IssuerCohortSourceRow::cohortRow).toList(), + work, + blockers); + String storedDigest = requireText(header, "plan_digest"); + if (!computedDigest.equals(storedDigest)) { + throw conflict( + "Persisted immutable build-plan digest does not match its source and work set"); + } + return new CanonicalGameplayIssuerPartitionBuildPlan( + buildOperationId, + buildFence, + intent, + planRows.stream().map(IssuerCohortSourceRow::cohortRow).toList(), + work, + blockers, + storedDigest); + } + + private static CanonicalGameplayIssuerPartitionBuildPlan.MemberWork toMemberWork(Record row) { + return new CanonicalGameplayIssuerPartitionBuildPlan.MemberWork( + requireLong(row, "work_ordinal"), + requireNonNil(row.get("member_operation_id", UUID.class), "member_operation_id"), + requireNonNil( + row.get("member_preparation_fence_id", UUID.class), "member_preparation_fence_id"), + requireLong(row, "reservation_source_row_ordinal"), + requireText(row, "reservation_source_row_digest"), + row.get("binding_source_row_ordinal", Long.class), + row.get("binding_source_row_digest", String.class), + requireNonNil(row.get("reservation_id", UUID.class), "reservation_id"), + requireBytes(row, "binding_ref"), + requireNonNil(row.get("transition_id", UUID.class), "transition_id"), + requireText(row, "reservation_lifecycle"), + requireNonNil(row.get("reservation_fence", UUID.class), "reservation_fence"), + readBigInteger(row, "original_partition_id"), + readBigInteger(row, "original_layout_version"), + readBigInteger(row, "original_partition_count"), + readBigInteger(row, "original_partition_capacity"), + requireNonNil( + row.get("original_issuer_coverage_operation_id", UUID.class), + "original_issuer_coverage_operation_id"), + readBigInteger(row, "original_issuer_coverage_operation_fence"), + readBigInteger(row, "original_coverage_fence"), + readBigInteger(row, "original_inventory_snapshot_revision"), + readBigInteger(row, "planned_partition_id"), + requireNonNil( + row.get("planned_anchor_operation_id", UUID.class), "planned_anchor_operation_id"), + readBigInteger(row, "planned_anchor_operation_fence"), + readBigInteger(row, "planned_anchor_coverage_fence"), + readBigInteger(row, "planned_anchor_inventory_snapshot_revision")); + } + + private static boolean sameWorkMapping( + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork actual, + PlannedReservation expected, + CanonicalGameplayIssuerLayoutBootstrapIntent intent, + int ordinal) { + ReservationSource reservation = expected.reservation(); + return actual.workOrdinal() == ordinal + && actual.reservationSourceRowOrdinal() == reservation.rowOrdinal() + && actual.reservationSourceRowDigest().equals(reservation.sourceRowDigest()) + && Objects.equals(actual.bindingSourceRowOrdinal(), expected.bindingSourceRowOrdinal()) + && Objects.equals(actual.bindingSourceRowDigest(), expected.bindingSourceRowDigest()) + && actual.reservationId().equals(reservation.reservationId()) + && Arrays.equals(actual.bindingRef(), reservation.bindingRef()) + && actual.transitionId().equals(reservation.transitionId()) + && actual.reservationLifecycle().equals(reservation.lifecycle()) + && actual.reservationFence().equals(reservation.reservationFence()) + && actual.originalPartitionId().equals(reservation.partitionId()) + && actual.originalLayoutVersion().equals(reservation.layoutVersion()) + && actual.originalPartitionCount().equals(reservation.partitionCount()) + && actual.originalPartitionCapacity().equals(reservation.partitionCapacity()) + && actual.originalIssuerCoverageOperationId().equals(reservation.coverageOperationId()) + && actual + .originalIssuerCoverageOperationFence() + .equals(reservation.coverageOperationFence()) + && actual.originalCoverageFence().equals(reservation.coverageFence()) + && actual + .originalInventorySnapshotRevision() + .equals(reservation.inventorySnapshotRevision()) + && actual.plannedPartitionId().equals(expected.plannedPartitionId()) + && actual.plannedAnchorOperationId().equals(intent.operationId()) + && actual.plannedAnchorOperationFence().equals(intent.operationFence()) + && actual.plannedAnchorCoverageFence().equals(intent.coverageFence()) + && actual + .plannedAnchorInventorySnapshotRevision() + .equals(intent.inventorySnapshotRevision()); + } + + private static boolean sameBlockers( + List left, + List right) { + if (left.size() != right.size()) return false; + for (int index = 0; index < left.size(); index++) { + var a = left.get(index); + var b = right.get(index); + if (a.blockerOrdinal() != b.blockerOrdinal() + || a.sourceRowOrdinal() != b.sourceRowOrdinal() + || !a.sourceRowDigest().equals(b.sourceRowDigest()) + || a.code() != b.code()) return false; + } + return true; + } + + private static void requireUniquePreparationIdentities( + UUID buildOperationId, + UUID buildFence, + CanonicalGameplayIssuerLayoutBootstrapIntent intent, + List work) { + Set originalIdentities = new HashSet<>(); + originalIdentities.add(intent.operationId()); + if (!originalIdentities.add(intent.requestId())) { + throw conflict("Original bootstrap operation and request identities overlap"); + } + for (var row : intent.cohortRows()) { + try { + UUID parsed = UUID.fromString(row.sourceKey()); + if (parsed.toString().equals(row.sourceKey())) originalIdentities.add(parsed); + } catch (IllegalArgumentException ignored) { + // Non-UUID source keys are retained byte-for-byte by the cohort artifact. + } + } + for (var item : work) { + originalIdentities.add(item.reservationId()); + originalIdentities.add(item.transitionId()); + originalIdentities.add(item.reservationFence()); + originalIdentities.add(item.originalIssuerCoverageOperationId()); + } + + Set preparationIdentities = new HashSet<>(); + if (!isNewPreparationIdentity(buildOperationId, originalIdentities, preparationIdentities) + || !isNewPreparationIdentity(buildFence, originalIdentities, preparationIdentities)) { + throw conflict("Build preparation identity collides with original source provenance"); + } + for (var item : work) { + if (!isNewPreparationIdentity( + item.memberOperationId(), originalIdentities, preparationIdentities) + || !isNewPreparationIdentity( + item.memberPreparationFenceId(), originalIdentities, preparationIdentities)) { + throw conflict("Member preparation identity collides with an original source identity"); + } + if (item.memberOperationId().equals(item.transitionId()) + || item.memberOperationId().equals(item.reservationId()) + || item.memberPreparationFenceId().equals(item.reservationFence())) { + throw conflict("Member preparation identity reused original reservation provenance"); + } + } + } + + private static boolean isNewPreparationIdentity( + UUID candidate, Set originalIdentities, Set preparationIdentities) { + return !originalIdentities.contains(candidate) && preparationIdentities.add(candidate); + } + + private static String digestPlan( + UUID buildOperationId, + UUID buildFence, + CanonicalGameplayIssuerLayoutBootstrapIntent intent, + List cohort, + List work, + List blockers) { + MessageDigest digest = sha256Digest(); + frame(digest, buildOperationId.toString()); + frame(digest, buildFence.toString()); + frame(digest, intent.operationId().toString()); + frame(digest, intent.requestId().toString()); + frame(digest, intent.issuerId()); + frame(digest, intent.controlEpoch().toString()); + frame(digest, intent.operationFence().toString()); + frame(digest, intent.coverageFence().toString()); + frame(digest, intent.inventorySnapshotRevision().toString()); + var layout = intent.layoutDescriptor(); + frame(digest, layout.layoutVersion().toString()); + frame(digest, layout.partitionCount().toString()); + frame(digest, layout.partitionCapacity().toString()); + frame(digest, layout.mappingIdentity()); + frame(digest, layout.exactDescriptorBytes()); + frame(digest, layout.descriptorDigest()); + var source = intent.sourceCheckpoint(); + frame(digest, source.issuerId()); + frame(digest, source.issuerAuthGeneration().toString()); + frame(digest, source.exactCheckpointBytes()); + frame(digest, source.checkpointDigest()); + nullableFrame(digest, source.latestIssuerEventBytes()); + nullableFrame(digest, source.latestIssuerEventDigest()); + var legacy = intent.legacyDisposition(); + frame(digest, legacy.cohortId().toString()); + frame(digest, legacy.ownerOperationId().toString()); + frame(digest, legacy.legacyWriterFence().toString()); + frame(digest, legacy.sourceSnapshotRevision().toString()); + frame(digest, legacy.canonicalInventoryRevision().toString()); + frame(digest, legacy.namespaceIndexReadbackRevision().toString()); + frame(digest, legacy.evidenceDigest()); + frame(digest, blockers.isEmpty() ? "PREPARED" : "BLOCKED"); + frame( + digest, + CanonicalGameplayIssuerPartitionBuildPlan.CoverageGenerationState.NOT_YET_ISSUED.name()); + for (var row : cohort) { + frame(digest, Long.toString(row.rowOrdinal())); + frame(digest, row.kind().name()); + frame(digest, row.sourceKey()); + frame(digest, row.sourceInventoryRevision().toString()); + frame(digest, row.sourceRowJson()); + frame(digest, row.sourceRowDigest()); + } + for (var item : work) { + frame(digest, Long.toString(item.workOrdinal())); + frame(digest, item.memberOperationId().toString()); + frame(digest, item.memberPreparationFenceId().toString()); + frame(digest, Long.toString(item.reservationSourceRowOrdinal())); + frame(digest, item.reservationSourceRowDigest()); + nullableFrame( + digest, + item.bindingSourceRowOrdinal() == null + ? null + : item.bindingSourceRowOrdinal().toString()); + nullableFrame(digest, item.bindingSourceRowDigest()); + frame(digest, item.reservationId().toString()); + frame(digest, item.bindingRef()); + frame(digest, item.transitionId().toString()); + frame(digest, item.reservationLifecycle()); + frame(digest, item.reservationFence().toString()); + frame(digest, item.originalPartitionId().toString()); + frame(digest, item.originalLayoutVersion().toString()); + frame(digest, item.originalPartitionCount().toString()); + frame(digest, item.originalPartitionCapacity().toString()); + frame(digest, item.originalIssuerCoverageOperationId().toString()); + frame(digest, item.originalIssuerCoverageOperationFence().toString()); + frame(digest, item.originalCoverageFence().toString()); + frame(digest, item.originalInventorySnapshotRevision().toString()); + frame(digest, item.plannedPartitionId().toString()); + frame(digest, item.plannedAnchorOperationId().toString()); + frame(digest, item.plannedAnchorOperationFence().toString()); + frame(digest, item.plannedAnchorCoverageFence().toString()); + frame(digest, item.plannedAnchorInventorySnapshotRevision().toString()); + frame(digest, Boolean.toString(item.countsTowardCapacity())); + } + for (var blocker : blockers) { + frame(digest, Long.toString(blocker.blockerOrdinal())); + frame(digest, Long.toString(blocker.sourceRowOrdinal())); + frame(digest, blocker.sourceRowDigest()); + frame(digest, blocker.code().name()); + } + return "sha256:" + HexFormat.of().formatHex(digest.digest()); + } + + private static void frame(MessageDigest digest, String value) { + frame(digest, value.getBytes(StandardCharsets.UTF_8)); + } + + private static void frame(MessageDigest digest, byte[] value) { + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(value.length).array()); + digest.update(value); + } + + private static void nullableFrame(MessageDigest digest, String value) { + if (value == null) { + frame(digest, new byte[] {0}); + } else { + frame(digest, new byte[] {1}); + frame(digest, value); + } + } + + private static void nullableFrame(MessageDigest digest, byte[] value) { + if (value == null) { + frame(digest, new byte[] {0}); + } else { + frame(digest, new byte[] {1}); + frame(digest, value); + } + } + + private static String digestCohortRows( + List rows) { + MessageDigest digest = sha256Digest(); + rows.stream() + .sorted( + Comparator.comparingLong( + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::rowOrdinal)) + .forEach( + row -> { + frame(digest, Long.toString(row.rowOrdinal())); + frame(digest, row.kind().name()); + frame(digest, row.sourceKey()); + frame(digest, row.sourceInventoryRevision().toString()); + frame(digest, row.sourceRowDigest()); + }); + return "sha256:" + HexFormat.of().formatHex(digest.digest()); + } + + private static void requireNoFutureRows(DSLContext transaction, BigInteger revision) { + Record row = + Objects.requireNonNull( + transaction.fetchOne( + FUTURE_REVISION_SQL, + decimal(revision), + decimal(revision), + decimal(revision), + decimal(revision), + decimal(revision), + decimal(revision)), + "future inventory query must return one row"); + if (Boolean.TRUE.equals(row.get("has_future_revision", Boolean.class))) { + throw conflict("Current issuer inventory has durable rows beyond its locked clock"); + } + } + + private static BigInteger lockInventoryRevision(DSLContext transaction) { + Record row = + transaction.fetchOne( + "SELECT inventory_revision FROM " + + INVENTORY_CLOCK + + " WHERE singleton_id = 1 FOR UPDATE"); + if (row == null) throw conflict("Canonical binding inventory clock row is missing"); + return readBigInteger(row, "inventory_revision"); + } + + private static Record lockControl(DSLContext transaction, String issuerId) { + return transaction.fetchOne( + "SELECT * FROM " + BOOTSTRAP_CONTROL + " WHERE issuer_id = ? FOR UPDATE", issuerId); + } + + private static Record lockIntent(DSLContext transaction, UUID operationId) { + return transaction.fetchOne( + "SELECT * FROM " + + BOOTSTRAP_INTENT + + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", + operationId, + ISSUER); + } + + private static void requireValidSourceEvent( + String issuerId, BigInteger generation, byte[] eventBytes) { + final String eventJson; + try { + eventJson = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(eventBytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw conflict("Persisted Account issuer source event is not exact UTF-8"); + } + final AccountAuthoritySourceEventV1Codec.SourceEvent parsed; + try { + parsed = AccountAuthoritySourceEventV1Codec.verify(eventJson); + } catch (RuntimeException malformed) { + throw conflict("Persisted Account issuer source event is not codec-verified"); + } + if (!(parsed instanceof IssuerEvent event) + || !event.issuerId().equals(issuerId) + || !new BigInteger(event.issuerAuthGeneration()).equals(generation) + || !Arrays.equals(event.canonicalJsonUtf8(), eventBytes)) { + throw conflict("Persisted Account issuer source event differs from its exact checkpoint"); + } + } + + private static JsonNode parseObject(String raw) { + try { + JsonNode result = JSON.readTree(raw); + if (result == null || !result.isObject()) + throw conflict("Cohort source row is not a JSON object"); + return result; + } catch (JsonProcessingException malformed) { + throw conflict("Cohort source row JSON is malformed"); + } + } + + private static String text(JsonNode json, String field) { + JsonNode value = json.get(field); + if (value == null || value.isNull() || !value.isValueNode()) { + throw conflict("Cohort source row is missing scalar field " + field); + } + return value.asText(); + } + + private static BigInteger integer(JsonNode json, String field) { + JsonNode value = json.get(field); + if (value == null || value.isNull() || (!value.isNumber() && !value.isTextual())) { + throw conflict("Cohort source row is missing integer field " + field); + } + try { + return value.isNumber() + ? value.decimalValue().toBigIntegerExact() + : new BigInteger(value.textValue()); + } catch (RuntimeException malformed) { + throw conflict("Cohort source row integer field is malformed: " + field); + } + } + + private static UUID uuid(JsonNode json, String field) { + String value = text(json, field); + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(NIL_UUID)) { + throw new IllegalArgumentException("noncanonical UUID"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw conflict("Cohort source row UUID field is malformed: " + field); + } + } + + private static byte[] bytea(JsonNode json, String field) { + String value = text(json, field); + if (!value.startsWith("\\x") || (value.length() & 1) != 0) { + throw conflict("Cohort source row bytea field is not PostgreSQL hex text: " + field); + } + try { + return HexFormat.of().parseHex(value.substring(2)); + } catch (IllegalArgumentException malformed) { + throw conflict("Cohort source row bytea field is malformed: " + field); + } + } + + private static BigInteger readBigInteger(Record row, String field) { + BigDecimal value = row.get(field, BigDecimal.class); + if (value == null) throw conflict("Persisted field is missing: " + field); + try { + return value.toBigIntegerExact(); + } catch (ArithmeticException malformed) { + throw conflict("Persisted numeric field is not an integer: " + field); + } + } + + private static long requireLong(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null) throw conflict("Persisted field is missing: " + field); + return value; + } + + private static String requireText(Record row, String field) { + String value = row.get(field, String.class); + if (value == null) throw conflict("Persisted field is missing: " + field); + return value; + } + + private static byte[] requireBytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + if (value == null || value.length == 0) + throw conflict("Persisted byte field is missing: " + field); + return value; + } + + private static BigDecimal decimal(BigInteger value) { + return new BigDecimal(value); + } + + private static String sha256(byte[] bytes) { + return "sha256:" + HexFormat.of().formatHex(sha256Digest().digest(bytes)); + } + + private static MessageDigest sha256Digest() { + try { + return MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("JVM does not provide SHA-256", impossible); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw conflict("Issuer partition build owner cannot join an ambient transaction"); + } + } + + private static UUID requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(NIL_UUID)) throw conflict(name + " must not be nil"); + return value; + } + + private static void requireNonNegative(BigInteger value, String name) { + if (value.signum() < 0) throw conflict(name + " must be non-negative"); + } + + private static IllegalStateException conflict(String message) { + return new IllegalStateException(message); + } + + private record IssuerCohortSourceRow( + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow cohortRow) {} + + private record PlanBlocker( + long sourceRowOrdinal, CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode code) {} + + private record DerivedPlan(List reservations, List blockers) {} + + private record PlannedReservation( + ReservationSource reservation, + Long bindingSourceRowOrdinal, + String bindingSourceRowDigest, + BigInteger plannedPartitionId) {} + + private record ReservationSource( + long rowOrdinal, + String sourceRowDigest, + UUID reservationId, + byte[] bindingRef, + UUID transitionId, + UUID reservationFence, + String lifecycle, + BigInteger partitionId, + BigInteger layoutVersion, + BigInteger partitionCount, + BigInteger partitionCapacity, + UUID coverageOperationId, + BigInteger coverageOperationFence, + BigInteger coverageFence, + BigInteger inventorySnapshotRevision, + BigInteger bindingGeneration, + String accountId, + String tenantId, + String namespaceId, + String characterId, + String playableStateScope, + String gameInstanceId, + BigInteger runtimeGameInstanceId, + String sessionId, + String regionId, + BigInteger regionEpoch, + String issuerId, + BigInteger issuerAuthGeneration) { + ReservationSource { + bindingRef = bindingRef.clone(); + } + + @Override + public byte[] bindingRef() { + return bindingRef.clone(); + } + } + + private record BindingSource( + long rowOrdinal, + String sourceRowDigest, + UUID reservationId, + byte[] bindingRef, + UUID transitionId, + String accountId, + String tenantId, + String namespaceId, + String characterId, + String playableStateScope, + String gameInstanceId, + BigInteger runtimeGameInstanceId, + String sessionId, + String regionId, + BigInteger regionEpoch, + String issuerId, + BigInteger issuerAuthGeneration, + BigInteger layoutVersion, + BigInteger partitionCount, + BigInteger partitionCapacity, + BigInteger partitionId, + BigInteger bindingGeneration) { + BindingSource { + bindingRef = bindingRef.clone(); + } + + @Override + public byte[] bindingRef() { + return bindingRef.clone(); + } + + boolean matches(ReservationSource reservation) { + return reservationId.equals(reservation.reservationId()) + && Arrays.equals(bindingRef, reservation.bindingRef()) + && transitionId.equals(reservation.transitionId()) + && accountId.equals(reservation.accountId()) + && tenantId.equals(reservation.tenantId()) + && namespaceId.equals(reservation.namespaceId()) + && characterId.equals(reservation.characterId()) + && playableStateScope.equals(reservation.playableStateScope()) + && gameInstanceId.equals(reservation.gameInstanceId()) + && runtimeGameInstanceId.equals(reservation.runtimeGameInstanceId()) + && sessionId.equals(reservation.sessionId()) + && regionId.equals(reservation.regionId()) + && regionEpoch.equals(reservation.regionEpoch()) + && issuerId.equals(reservation.issuerId()) + && issuerAuthGeneration.equals(reservation.issuerAuthGeneration()) + && bindingGeneration.equals(reservation.bindingGeneration()) + && layoutVersion.equals(reservation.layoutVersion()) + && partitionCount.equals(reservation.partitionCount()) + && partitionCapacity.equals(reservation.partitionCapacity()) + && partitionId.equals(reservation.partitionId()); + } + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V1031__canonical_issuer_partition_build_plan.sql b/services/game-session-service/src/main/resources/db/migration/V1031__canonical_issuer_partition_build_plan.sql new file mode 100644 index 0000000000..7cbd5e3604 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1031__canonical_issuer_partition_build_plan.sql @@ -0,0 +1,265 @@ +-- Immutable preparation records for a local initial issuer partition build. These records link to +-- the exact pending V1030 bootstrap intent and its complete frozen cohort. They do not publish a +-- layout pointer, install an anchor, acknowledge coverage, or authorize admission. +CREATE TABLE game_session_canonical_issuer_partition_build_plan ( + build_operation_id uuid NOT NULL, + build_preparation_fence_id uuid NOT NULL, + bootstrap_operation_id uuid NOT NULL, + bootstrap_request_id uuid NOT NULL, + issuer_id character varying(64) NOT NULL, + control_epoch numeric NOT NULL, + bootstrap_operation_fence numeric NOT NULL, + bootstrap_coverage_fence numeric NOT NULL, + issuer_inventory_snapshot_revision numeric NOT NULL, + layout_version numeric NOT NULL, + partition_count numeric NOT NULL, + partition_capacity numeric NOT NULL, + mapping_identity character varying(96) NOT NULL, + layout_descriptor_bytes bytea NOT NULL, + layout_descriptor_digest character varying(71) NOT NULL, + cohort_row_count bigint NOT NULL, + cohort_digest character varying(71) NOT NULL, + member_work_count bigint NOT NULL, + blocker_count bigint NOT NULL, + plan_state character varying(16) NOT NULL, + coverage_generation_state character varying(24) NOT NULL, + coverage_generation numeric, + plan_digest character varying(71) NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_issuer_partition_build_plan PRIMARY KEY (build_operation_id), + CONSTRAINT uq_gs_issuer_partition_build_plan_bootstrap UNIQUE (bootstrap_operation_id), + CONSTRAINT uq_gs_issuer_partition_build_plan_anchor_link UNIQUE ( + build_operation_id, bootstrap_operation_id, issuer_id, + bootstrap_operation_fence, bootstrap_coverage_fence, + issuer_inventory_snapshot_revision), + CONSTRAINT fk_gs_issuer_partition_build_plan_intent FOREIGN KEY ( + bootstrap_operation_id, issuer_id) + REFERENCES game_session_canonical_issuer_layout_bootstrap_intent + (operation_id, issuer_id), + CONSTRAINT chk_gs_issuer_partition_build_plan CHECK ( + build_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND build_preparation_fence_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND bootstrap_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND bootstrap_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND build_operation_id <> bootstrap_operation_id + AND build_operation_id <> bootstrap_request_id + AND build_operation_id <> build_preparation_fence_id + AND build_preparation_fence_id <> bootstrap_operation_id + AND build_preparation_fence_id <> bootstrap_request_id + AND issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND control_epoch > 0 + AND bootstrap_operation_fence = control_epoch + AND bootstrap_coverage_fence > 0 + AND bootstrap_coverage_fence <> bootstrap_operation_fence + AND issuer_inventory_snapshot_revision > 0 + AND layout_version > 0 + AND partition_count > 0 + AND partition_capacity > 0 + AND mapping_identity = 'bindingRef/v1;sha256-u256-mod/v1' + AND octet_length(layout_descriptor_bytes) > 0 + AND layout_descriptor_digest ~ '^sha256:[0-9a-f]{64}$' + AND cohort_row_count >= 0 + AND cohort_digest ~ '^sha256:[0-9a-f]{64}$' + AND member_work_count >= 0 + AND blocker_count >= 0 + AND ((plan_state = 'PREPARED' AND blocker_count = 0) + OR (plan_state = 'BLOCKED' AND blocker_count > 0)) + AND coverage_generation_state = 'NOT_YET_ISSUED' + AND coverage_generation IS NULL + AND plan_digest ~ '^sha256:[0-9a-f]{64}$') +); + +CREATE TABLE game_session_canonical_issuer_partition_build_cohort_row ( + build_operation_id uuid NOT NULL, + source_operation_id uuid NOT NULL, + issuer_id character varying(64) NOT NULL, + source_row_ordinal bigint NOT NULL, + source_kind character varying(40) NOT NULL, + source_key text NOT NULL, + source_inventory_revision numeric NOT NULL, + source_row_json text NOT NULL, + source_row_digest character varying(71) NOT NULL, + CONSTRAINT pk_gs_issuer_partition_build_cohort_row + PRIMARY KEY (build_operation_id, source_row_ordinal), + CONSTRAINT fk_gs_issuer_partition_build_cohort_plan FOREIGN KEY (build_operation_id) + REFERENCES game_session_canonical_issuer_partition_build_plan (build_operation_id), + CONSTRAINT fk_gs_issuer_partition_build_cohort_intent FOREIGN KEY ( + source_operation_id, issuer_id) + REFERENCES game_session_canonical_issuer_layout_bootstrap_intent + (operation_id, issuer_id), + CONSTRAINT chk_gs_issuer_partition_build_cohort_row CHECK ( + source_row_ordinal >= 0 + AND issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND source_kind IN ( + 'BINDING', 'UNRESOLVED_LEGACY_BINDING', 'TRANSITION', 'RESERVATION', + 'UNRESOLVED_LEGACY_RESERVATION', 'ACCOUNT_OBLIGATION', 'ISSUER_OBLIGATION', + 'REGION_OBLIGATION') + AND length(source_key) > 0 + AND source_inventory_revision > 0 + AND length(source_row_json) > 1 + AND source_row_digest ~ '^sha256:[0-9a-f]{64}$') +); + +-- jOOQ's H2 DDL simulation cannot index PostgreSQL TEXT; retain this exact PostgreSQL key guard. +-- [jooq ignore start] +ALTER TABLE game_session_canonical_issuer_partition_build_cohort_row + ADD CONSTRAINT uq_gs_issuer_partition_build_cohort_source + UNIQUE (build_operation_id, source_kind, source_key); +-- [jooq ignore stop] + +CREATE TABLE game_session_canonical_issuer_partition_build_member_work ( + build_operation_id uuid NOT NULL, + bootstrap_operation_id uuid NOT NULL, + issuer_id character varying(64) NOT NULL, + work_ordinal bigint NOT NULL, + member_operation_id uuid NOT NULL, + member_preparation_fence_id uuid NOT NULL, + reservation_id uuid NOT NULL, + reservation_source_row_ordinal bigint NOT NULL, + reservation_source_row_digest character varying(71) NOT NULL, + binding_source_row_ordinal bigint, + binding_source_row_digest character varying(71), + binding_ref bytea NOT NULL, + transition_id uuid NOT NULL, + reservation_lifecycle character varying(24) NOT NULL, + reservation_fence uuid NOT NULL, + original_partition_id numeric NOT NULL, + original_layout_version numeric NOT NULL, + original_partition_count numeric NOT NULL, + original_partition_capacity numeric NOT NULL, + original_issuer_coverage_operation_id uuid NOT NULL, + original_issuer_coverage_operation_fence numeric NOT NULL, + original_coverage_fence numeric NOT NULL, + original_inventory_snapshot_revision numeric NOT NULL, + planned_partition_id numeric NOT NULL, + planned_anchor_operation_id uuid NOT NULL, + planned_anchor_operation_fence numeric NOT NULL, + planned_anchor_coverage_fence numeric NOT NULL, + planned_anchor_inventory_snapshot_revision numeric NOT NULL, + counts_toward_capacity boolean NOT NULL, + CONSTRAINT pk_gs_issuer_partition_build_member_work + PRIMARY KEY (build_operation_id, work_ordinal), + CONSTRAINT uq_gs_issuer_partition_build_member_operation + UNIQUE (build_operation_id, member_operation_id), + CONSTRAINT uq_gs_issuer_partition_build_member_fence + UNIQUE (build_operation_id, member_preparation_fence_id), + CONSTRAINT uq_gs_issuer_partition_build_member_reservation + UNIQUE (build_operation_id, reservation_id), + CONSTRAINT fk_gs_issuer_partition_build_member_plan FOREIGN KEY (build_operation_id) + REFERENCES game_session_canonical_issuer_partition_build_plan (build_operation_id), + CONSTRAINT fk_gs_issuer_partition_build_member_reservation_source FOREIGN KEY ( + build_operation_id, reservation_source_row_ordinal) + REFERENCES game_session_canonical_issuer_partition_build_cohort_row + (build_operation_id, source_row_ordinal), + CONSTRAINT fk_gs_issuer_partition_build_member_binding_source FOREIGN KEY ( + build_operation_id, binding_source_row_ordinal) + REFERENCES game_session_canonical_issuer_partition_build_cohort_row + (build_operation_id, source_row_ordinal), + CONSTRAINT fk_gs_issuer_partition_build_member_anchor_link FOREIGN KEY ( + build_operation_id, planned_anchor_operation_id, issuer_id, + planned_anchor_operation_fence, planned_anchor_coverage_fence, + planned_anchor_inventory_snapshot_revision) + REFERENCES game_session_canonical_issuer_partition_build_plan ( + build_operation_id, bootstrap_operation_id, issuer_id, + bootstrap_operation_fence, bootstrap_coverage_fence, + issuer_inventory_snapshot_revision), + CONSTRAINT chk_gs_issuer_partition_build_member_work CHECK ( + work_ordinal >= 0 + AND member_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND member_preparation_fence_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND reservation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND member_operation_id <> build_operation_id + AND member_operation_id <> bootstrap_operation_id + AND member_operation_id <> member_preparation_fence_id + AND member_preparation_fence_id <> build_operation_id + AND member_preparation_fence_id <> bootstrap_operation_id + AND (binding_source_row_ordinal IS NULL) = (binding_source_row_digest IS NULL) + AND octet_length(binding_ref) > 0 + AND transition_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND reservation_lifecycle IN ('RESERVED', 'BOUND', 'RELEASE_PENDING', 'RELEASED') + AND reservation_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND original_partition_id >= 0 + AND original_layout_version > 0 + AND original_partition_count > 0 + AND original_partition_id < original_partition_count + AND original_partition_capacity > 0 + AND original_issuer_coverage_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND original_issuer_coverage_operation_fence > 0 + AND original_coverage_fence > 0 + AND original_inventory_snapshot_revision > 0 + AND planned_partition_id >= 0 + AND planned_anchor_operation_id = bootstrap_operation_id + AND planned_anchor_operation_fence > 0 + AND planned_anchor_coverage_fence > 0 + AND planned_anchor_inventory_snapshot_revision > 0 + AND counts_toward_capacity = (reservation_lifecycle <> 'RELEASED') + AND reservation_source_row_digest ~ '^sha256:[0-9a-f]{64}$' + AND (binding_source_row_digest IS NULL + OR binding_source_row_digest ~ '^sha256:[0-9a-f]{64}$')) +); + +CREATE TABLE game_session_canonical_issuer_partition_build_blocker ( + build_operation_id uuid NOT NULL, + blocker_ordinal bigint NOT NULL, + source_row_ordinal bigint NOT NULL, + source_row_digest character varying(71) NOT NULL, + blocker_code character varying(48) NOT NULL, + CONSTRAINT pk_gs_issuer_partition_build_blocker + PRIMARY KEY (build_operation_id, blocker_ordinal), + CONSTRAINT fk_gs_issuer_partition_build_blocker_plan FOREIGN KEY (build_operation_id) + REFERENCES game_session_canonical_issuer_partition_build_plan (build_operation_id), + CONSTRAINT fk_gs_issuer_partition_build_blocker_source FOREIGN KEY ( + build_operation_id, source_row_ordinal) + REFERENCES game_session_canonical_issuer_partition_build_cohort_row + (build_operation_id, source_row_ordinal), + CONSTRAINT chk_gs_issuer_partition_build_blocker CHECK ( + blocker_ordinal >= 0 + AND source_row_digest ~ '^sha256:[0-9a-f]{64}$' + AND blocker_code IN ( + 'UNRESOLVED_LEGACY_BINDING', 'UNRESOLVED_LEGACY_RESERVATION', + 'UNREPRESENTABLE_BINDING', 'UNREPRESENTABLE_RESERVATION', 'UNREPRESENTABLE_SOURCE', + 'MISSING_RESERVATION', 'CONFLICTING_RESERVATION_LINK', + 'PARTITION_CAPACITY_EXCEEDED', 'AGGREGATE_CAPACITY_EXCEEDED')) +); + +-- jOOQ's H2 DDL parser cannot represent PostgreSQL PL/pgSQL trigger functions. Keep the +-- immutable guards in the real migration; the focused PostgreSQL integration proof executes them. +-- [jooq ignore start] +CREATE FUNCTION game_session_reject_issuer_partition_build_artifact_change() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'issuer partition build preparation artifacts are immutable' + USING ERRCODE = 'check_violation'; +END; +$$; + +CREATE TRIGGER trg_gs_issuer_partition_build_plan_immutable + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_partition_build_plan + FOR EACH ROW EXECUTE FUNCTION game_session_reject_issuer_partition_build_artifact_change(); + +CREATE TRIGGER trg_gs_issuer_partition_build_cohort_immutable + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_partition_build_cohort_row + FOR EACH ROW EXECUTE FUNCTION game_session_reject_issuer_partition_build_artifact_change(); + +CREATE TRIGGER trg_gs_issuer_partition_build_work_immutable + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_partition_build_member_work + FOR EACH ROW EXECUTE FUNCTION game_session_reject_issuer_partition_build_artifact_change(); + +CREATE TRIGGER trg_gs_issuer_partition_build_blocker_immutable + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_partition_build_blocker + FOR EACH ROW EXECUTE FUNCTION game_session_reject_issuer_partition_build_artifact_change(); +CREATE TRIGGER trg_gs_issuer_partition_build_plan_no_truncate + BEFORE TRUNCATE ON game_session_canonical_issuer_partition_build_plan + FOR EACH STATEMENT EXECUTE FUNCTION game_session_reject_issuer_partition_build_artifact_change(); +CREATE TRIGGER trg_gs_issuer_partition_build_cohort_no_truncate + BEFORE TRUNCATE ON game_session_canonical_issuer_partition_build_cohort_row + FOR EACH STATEMENT EXECUTE FUNCTION game_session_reject_issuer_partition_build_artifact_change(); +CREATE TRIGGER trg_gs_issuer_partition_build_work_no_truncate + BEFORE TRUNCATE ON game_session_canonical_issuer_partition_build_member_work + FOR EACH STATEMENT EXECUTE FUNCTION game_session_reject_issuer_partition_build_artifact_change(); +CREATE TRIGGER trg_gs_issuer_partition_build_blocker_no_truncate + BEFORE TRUNCATE ON game_session_canonical_issuer_partition_build_blocker + FOR EACH STATEMENT EXECUTE FUNCTION game_session_reject_issuer_partition_build_artifact_change(); +-- [jooq ignore stop] 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 new file mode 100644 index 0000000000..c8bcc5c681 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java @@ -0,0 +1,1339 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.EnumSet; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; +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.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final UUID ACCOUNT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID NAMESPACE_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID GAME_INSTANCE_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID REGION_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID CHARACTER_ID = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final BigInteger LAYOUT_VERSION = BigInteger.valueOf(3); + private static final BigInteger PARTITION_COUNT = BigInteger.valueOf(16); + private static final BigInteger PARTITION_CAPACITY = BigInteger.valueOf(32); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void populatedPendingIntentRetainsCompleteCohortAndBothCoverageTuplesAcrossConcurrentRetry() + throws Exception { + TestSchema testSchema = newTestSchemaAtVersion("gs_issuer_build_retry_", "1030"); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + establishActualLegacyDisposition(testSchema.dsl()); + var inventory = new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); + var prepared = prepareActualBinding(inventory); + UUID reservationOnlyId = UUID.randomUUID(); + insertReservationOnly( + testSchema.dsl(), + prepared.candidate(), + prepared.inventoryRevision(), + reservationOnlyId, + BigInteger.valueOf(17), + BigInteger.valueOf(19)); + + var bootstrapOwner = new CanonicalGameplayIssuerLayoutBootstrapRepository(testSchema.dsl()); + UUID requestId = UUID.randomUUID(); + var intent = + bootstrapOwner.beginInitialBootstrapIntent( + requestId, + descriptor(LAYOUT_VERSION, PARTITION_COUNT, PARTITION_CAPACITY), + sourceCheckpoint(BigInteger.valueOf(7))); + List bindingRowsBefore = + rowImages(testSchema.dsl(), "game_session_canonical_gameplay_binding_inventory"); + List reservationRowsBefore = + rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_reservation"); + List intentRowsBefore = + rowImages(testSchema.dsl(), "game_session_canonical_issuer_layout_bootstrap_intent"); + List controlRowsBefore = + rowImages(testSchema.dsl(), "game_session_canonical_issuer_layout_bootstrap_control"); + List cohortRowsBefore = + rowImages(testSchema.dsl(), "game_session_canonical_issuer_layout_bootstrap_cohort_row"); + List transitionRowsBefore = + rowImages(testSchema.dsl(), "game_session_canonical_binding_transition"); + List accountObligationsBefore = + rowImages(testSchema.dsl(), "game_session_canonical_binding_account_index_obligation"); + List issuerObligationsBefore = + rowImages(testSchema.dsl(), "game_session_canonical_binding_issuer_index_obligation"); + List regionObligationsBefore = + rowImages(testSchema.dsl(), "game_session_canonical_binding_region_bridge_obligation"); + List inventoryClockBefore = + rowImages(testSchema.dsl(), "game_session_canonical_binding_inventory_clock"); + List migrationHistoryBefore = rowImages(testSchema.dsl(), "flyway_schema_history"); + migrateRemaining(testSchema); + + var ready = new CountDownLatch(2); + var start = new CountDownLatch(1); + var first = + executor.submit( + () -> prepareAtGate(testSchema.dsl(), intent.operationId(), requestId, ready, start)); + var second = + executor.submit( + () -> prepareAtGate(testSchema.dsl(), intent.operationId(), requestId, ready, start)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + var firstPlan = first.get(30, TimeUnit.SECONDS); + var secondPlan = second.get(30, TimeUnit.SECONDS); + + assertThat(firstPlan.state()) + .isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED); + assertThat(firstPlan.coverageGenerationState()) + .isEqualTo( + CanonicalGameplayIssuerPartitionBuildPlan.CoverageGenerationState.NOT_YET_ISSUED); + assertThat(firstPlan.coverageGeneration()).isNull(); + assertThat(firstPlan.cohortRows()) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::rowOrdinal) + .containsExactlyElementsOf( + intent.cohortRows().stream() + .map(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::rowOrdinal) + .toList()); + assertThat(firstPlan.cohortRows()) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceRowDigest) + .containsExactlyElementsOf( + intent.cohortRows().stream() + .map(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceRowDigest) + .toList()); + assertThat(firstPlan.memberWorks()).hasSize(2); + assertThat(firstPlan.memberWorks()) + .extracting(CanonicalGameplayIssuerPartitionBuildPlan.MemberWork::reservationId) + .containsExactlyInAnyOrder(prepared.issuerReservationId(), reservationOnlyId); + var reservationOnlyWork = + firstPlan.memberWorks().stream() + .filter(work -> work.reservationId().equals(reservationOnlyId)) + .findFirst() + .orElseThrow(); + assertThat(reservationOnlyWork.bindingSourceRowOrdinal()).isNull(); + assertThat(reservationOnlyWork.bindingSourceRowDigest()).isNull(); + assertThat(reservationOnlyWork.originalIssuerCoverageOperationId()) + .isNotEqualTo(reservationOnlyWork.plannedAnchorOperationId()); + assertThat(reservationOnlyWork.originalIssuerCoverageOperationFence()) + .isEqualTo(BigInteger.valueOf(17)); + assertThat(reservationOnlyWork.originalCoverageFence()).isEqualTo(BigInteger.valueOf(19)); + assertThat(reservationOnlyWork.originalInventorySnapshotRevision()) + .isEqualTo(intent.inventorySnapshotRevision()); + assertThat(reservationOnlyWork.plannedAnchorOperationId()).isEqualTo(intent.operationId()); + assertThat(reservationOnlyWork.plannedAnchorOperationFence()) + .isEqualTo(intent.operationFence()); + assertThat(reservationOnlyWork.plannedAnchorCoverageFence()) + .isEqualTo(intent.coverageFence()); + assertThat(reservationOnlyWork.plannedAnchorInventorySnapshotRevision()) + .isEqualTo(intent.inventorySnapshotRevision()); + assertThat(reservationOnlyWork.plannedPartitionId()) + .isEqualTo( + CanonicalGameplayBindingRef.fromExactBytes(reservationOnlyWork.bindingRef()) + .partitionId(PARTITION_COUNT)); + assertThat(firstPlan.memberWorks()) + .extracting(CanonicalGameplayIssuerPartitionBuildPlan.MemberWork::memberOperationId) + .doesNotContain(prepared.transitionId()); + assertThat(firstPlan.memberWorks()) + .extracting(CanonicalGameplayIssuerPartitionBuildPlan.MemberWork::memberOperationId) + .doesNotHaveDuplicates(); + assertThat(firstPlan.memberWorks()) + .extracting( + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork::memberPreparationFenceId) + .doesNotHaveDuplicates(); + assertThat(secondPlan.buildOperationId()).isEqualTo(firstPlan.buildOperationId()); + assertThat(secondPlan.buildPreparationFenceId()) + .isEqualTo(firstPlan.buildPreparationFenceId()); + assertThat(secondPlan.planDigest()).isEqualTo(firstPlan.planDigest()); + assertThat(secondPlan.memberWorks()) + .extracting(CanonicalGameplayIssuerPartitionBuildPlan.MemberWork::memberOperationId) + .containsExactlyElementsOf( + firstPlan.memberWorks().stream() + .map(CanonicalGameplayIssuerPartitionBuildPlan.MemberWork::memberOperationId) + .toList()); + var restarted = + new CanonicalGameplayIssuerPartitionBuildRepository(testSchema.dsl()) + .prepareInitialBuildPlan(intent.operationId(), requestId); + assertThat(restarted.planDigest()).isEqualTo(firstPlan.planDigest()); + assertThat(restarted.memberWorks()) + .extracting( + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork::memberPreparationFenceId) + .containsExactlyElementsOf( + firstPlan.memberWorks().stream() + .map( + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork + ::memberPreparationFenceId) + .toList()); + assertThat(rowImages(testSchema.dsl(), "game_session_canonical_gameplay_binding_inventory")) + .containsExactlyElementsOf(bindingRowsBefore); + assertThat(rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_reservation")) + .containsExactlyElementsOf(reservationRowsBefore); + assertThat( + rowImages(testSchema.dsl(), "game_session_canonical_issuer_layout_bootstrap_intent")) + .containsExactlyElementsOf(intentRowsBefore); + assertThat( + rowImages(testSchema.dsl(), "game_session_canonical_issuer_layout_bootstrap_control")) + .containsExactlyElementsOf(controlRowsBefore); + assertThat( + rowImages( + testSchema.dsl(), "game_session_canonical_issuer_layout_bootstrap_cohort_row")) + .containsExactlyElementsOf(cohortRowsBefore); + assertThat(rowImages(testSchema.dsl(), "game_session_canonical_binding_transition")) + .containsExactlyElementsOf(transitionRowsBefore); + assertThat( + rowImages( + testSchema.dsl(), "game_session_canonical_binding_account_index_obligation")) + .containsExactlyElementsOf(accountObligationsBefore); + assertThat( + rowImages(testSchema.dsl(), "game_session_canonical_binding_issuer_index_obligation")) + .containsExactlyElementsOf(issuerObligationsBefore); + assertThat( + rowImages( + testSchema.dsl(), "game_session_canonical_binding_region_bridge_obligation")) + .containsExactlyElementsOf(regionObligationsBefore); + assertThat(rowImages(testSchema.dsl(), "game_session_canonical_binding_inventory_clock")) + .containsExactlyElementsOf(inventoryClockBefore); + List migrationHistoryAfter = rowImages(testSchema.dsl(), "flyway_schema_history"); + assertThat(migrationHistoryAfter) + .hasSize(migrationHistoryBefore.size() + 1) + .containsAll(migrationHistoryBefore); + } finally { + executor.shutdownNow(); + dropSchema(testSchema.schema()); + } + } + + @Test + void exactOwnerRejectsMissingWrongRequestMissingControlAndChangedFrozenSources() { + TestSchema testSchema = newTestSchema("gs_issuer_build_intent_fence_"); + try { + var fixture = pendingFixture(testSchema); + var owner = new CanonicalGameplayIssuerPartitionBuildRepository(testSchema.dsl()); + assertThatThrownBy( + () -> owner.prepareInitialBuildPlan(UUID.randomUUID(), fixture.requestId())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Exact pending issuer-bootstrap operation is missing"); + assertThatThrownBy( + () -> + owner.prepareInitialBuildPlan(fixture.intent().operationId(), UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("request or exact current control tuple changed"); + + testSchema + .dsl() + .execute( + "DELETE FROM game_session_canonical_issuer_layout_bootstrap_control WHERE issuer_id = ?", + ISSUER); + assertThatThrownBy( + () -> + owner.prepareInitialBuildPlan( + fixture.intent().operationId(), fixture.requestId())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("lost its positive current control row"); + } finally { + dropSchema(testSchema.schema()); + } + } + + @Test + void immutableBuildArtifactsRejectTruncateAndRetainTheirCompletePostimage() { + TestSchema testSchema = newTestSchema("gs_issuer_build_immutable_"); + try { + var fixture = + pendingLayoutFixture( + testSchema, + LAYOUT_VERSION.add(BigInteger.ONE), + PARTITION_COUNT, + PARTITION_CAPACITY, + false); + var owner = new CanonicalGameplayIssuerPartitionBuildRepository(testSchema.dsl()); + var plan = owner.prepareInitialBuildPlan(fixture.intent().operationId(), fixture.requestId()); + assertThat(plan.state()).isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.BLOCKED); + + List planBefore = + rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_build_plan"); + List cohortBefore = + rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_build_cohort_row"); + List workBefore = + rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_build_member_work"); + List blockersBefore = + rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_build_blocker"); + assertThat(planBefore).hasSize(1); + assertThat(cohortBefore).isNotEmpty(); + assertThat(workBefore).isNotEmpty(); + assertThat(blockersBefore).isNotEmpty(); + + assertThatThrownBy( + () -> + testSchema + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_partition_build_plan" + + " SET created_at = created_at + INTERVAL '1 second'")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("issuer partition build preparation artifacts are immutable"); + + assertThatThrownBy( + () -> + testSchema + .dsl() + .execute( + "TRUNCATE TABLE" + + " game_session_canonical_issuer_partition_build_plan," + + " game_session_canonical_issuer_partition_build_cohort_row," + + " game_session_canonical_issuer_partition_build_member_work," + + " game_session_canonical_issuer_partition_build_blocker")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("issuer partition build preparation artifacts are immutable"); + + assertThat(rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_build_plan")) + .containsExactlyElementsOf(planBefore); + assertThat( + rowImages( + testSchema.dsl(), "game_session_canonical_issuer_partition_build_cohort_row")) + .containsExactlyElementsOf(cohortBefore); + assertThat( + rowImages( + testSchema.dsl(), "game_session_canonical_issuer_partition_build_member_work")) + .containsExactlyElementsOf(workBefore); + assertThat( + rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_build_blocker")) + .containsExactlyElementsOf(blockersBefore); + } finally { + dropSchema(testSchema.schema()); + } + } + + @Test + void changedLayoutCohortOrSourceCannotResumeAnOriginalPlan() { + TestSchema layoutSchema = newTestSchema("gs_issuer_build_layout_drift_"); + try { + var fixture = pendingFixture(layoutSchema); + var owner = new CanonicalGameplayIssuerPartitionBuildRepository(layoutSchema.dsl()); + owner.prepareInitialBuildPlan(fixture.intent().operationId(), fixture.requestId()); + layoutSchema + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_layout_bootstrap_intent" + + " SET layout_version = layout_version + 1 WHERE operation_id = ?", + fixture.intent().operationId()); + assertThatThrownBy( + () -> + owner.prepareInitialBuildPlan( + fixture.intent().operationId(), fixture.requestId())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact pending bootstrap layout or anchor link"); + } finally { + dropSchema(layoutSchema.schema()); + } + + TestSchema cohortSchema = newTestSchema("gs_issuer_build_cohort_drift_"); + try { + var fixture = pendingFixture(cohortSchema); + cohortSchema + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_layout_bootstrap_cohort_row" + + " SET source_row_digest = ? WHERE operation_id = ? AND row_ordinal = 0", + "sha256:" + "0".repeat(64), + fixture.intent().operationId()); + assertThatThrownBy( + () -> + new CanonicalGameplayIssuerPartitionBuildRepository(cohortSchema.dsl()) + .prepareInitialBuildPlan(fixture.intent().operationId(), fixture.requestId())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("changed source-row digest"); + } finally { + dropSchema(cohortSchema.schema()); + } + + TestSchema sourceSchema = newTestSchema("gs_issuer_build_source_drift_"); + try { + var fixture = pendingFixture(sourceSchema); + sourceSchema + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_partition_reservation" + + " SET lifecycle = 'BOUND' WHERE reservation_id = ?", + fixture.reservationId()); + assertThatThrownBy( + () -> + new CanonicalGameplayIssuerPartitionBuildRepository(sourceSchema.dsl()) + .prepareInitialBuildPlan(fixture.intent().operationId(), fixture.requestId())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Current source row differs"); + } finally { + dropSchema(sourceSchema.schema()); + } + + TestSchema checkpointSchema = newTestSchema("gs_build_checkpoint_drift_"); + try { + var fixture = pendingFixture(checkpointSchema); + checkpointSchema + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_layout_bootstrap_intent" + + " SET source_checkpoint_bytes = convert_to('{}', 'UTF8') WHERE operation_id = ?", + fixture.intent().operationId()); + assertThatThrownBy( + () -> + new CanonicalGameplayIssuerPartitionBuildRepository(checkpointSchema.dsl()) + .prepareInitialBuildPlan(fixture.intent().operationId(), fixture.requestId())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source checkpoint digest is invalid"); + } finally { + dropSchema(checkpointSchema.schema()); + } + } + + @Test + void retainedLegacyReservationProducesACompleteBlockedPlan() { + TestSchema testSchema = newLegacyIssuerTestSchema("gs_issuer_build_legacy_"); + try { + UUID requestId = UUID.randomUUID(); + var intent = + new CanonicalGameplayIssuerLayoutBootstrapRepository(testSchema.dsl()) + .beginInitialBootstrapIntent( + requestId, + descriptor(LAYOUT_VERSION, PARTITION_COUNT, PARTITION_CAPACITY), + sourceCheckpoint(BigInteger.valueOf(7))); + var plan = + new CanonicalGameplayIssuerPartitionBuildRepository(testSchema.dsl()) + .prepareInitialBuildPlan(intent.operationId(), requestId); + + assertThat(plan.state()).isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.BLOCKED); + assertThat(plan.coverageGenerationState()) + .isEqualTo( + CanonicalGameplayIssuerPartitionBuildPlan.CoverageGenerationState.NOT_YET_ISSUED); + assertThat(plan.coverageGeneration()).isNull(); + assertThat(plan.cohortRows()) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::kind) + .contains( + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind + .UNRESOLVED_LEGACY_RESERVATION); + assertThat(plan.memberWorks()).isEmpty(); + assertThat(plan.blockers()) + .extracting(CanonicalGameplayIssuerPartitionBuildPlan.Blocker::code) + .containsExactly( + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode.UNRESOLVED_LEGACY_RESERVATION); + var retry = + new CanonicalGameplayIssuerPartitionBuildRepository(testSchema.dsl()) + .prepareInitialBuildPlan(intent.operationId(), requestId); + assertThat(retry.buildOperationId()).isEqualTo(plan.buildOperationId()); + assertThat(retry.planDigest()).isEqualTo(plan.planDigest()); + assertThat(retry.blockers()).containsExactlyElementsOf(plan.blockers()); + } finally { + dropSchema(testSchema.schema()); + } + } + + @Test + void initialBootstrapBlocksReservationsFromAnotherLayoutOrNoncanonicalOriginalPartition() { + TestSchema layoutSchema = newTestSchema("gs_issuer_build_layout_init_"); + try { + var fixture = + pendingLayoutFixture( + layoutSchema, + LAYOUT_VERSION.add(BigInteger.ONE), + PARTITION_COUNT, + PARTITION_CAPACITY, + false); + var owner = new CanonicalGameplayIssuerPartitionBuildRepository(layoutSchema.dsl()); + var plan = owner.prepareInitialBuildPlan(fixture.intent().operationId(), fixture.requestId()); + assertBlockedInitialReservation(owner, plan, fixture); + } finally { + dropSchema(layoutSchema.schema()); + } + + TestSchema mappingSchema = newTestSchema("gs_issuer_build_mapping_init_"); + try { + var fixture = + pendingLayoutFixture( + mappingSchema, LAYOUT_VERSION, PARTITION_COUNT, PARTITION_CAPACITY, true); + var owner = new CanonicalGameplayIssuerPartitionBuildRepository(mappingSchema.dsl()); + var plan = owner.prepareInitialBuildPlan(fixture.intent().operationId(), fixture.requestId()); + assertBlockedInitialReservation(owner, plan, fixture); + } finally { + dropSchema(mappingSchema.schema()); + } + } + + @Test + void initialBootstrapCountsNonterminalReservationCapacityAndExcludesReleasedRows() { + TestSchema testSchema = newTestSchema("gs_build_capacity_"); + BigInteger partitionCount = BigInteger.TWO; + BigInteger partitionCapacity = BigInteger.ONE; + BigInteger originalOperationFence = BigInteger.valueOf(17); + BigInteger originalCoverageFence = BigInteger.valueOf(19); + try { + establishActualLegacyDisposition(testSchema.dsl()); + var prepared = + prepareActualBinding( + new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()), + LAYOUT_VERSION, + partitionCount, + partitionCapacity, + originalOperationFence, + originalCoverageFence); + BigInteger overCapacityPartition = + CanonicalGameplayBindingRef.of( + prepared.candidate().tenantId().toString(), + prepared.candidate().gameInstanceId().toString(), + prepared.candidate().sessionId()) + .partitionId(partitionCount); + BigInteger otherPartition = + overCapacityPartition.equals(BigInteger.ZERO) ? BigInteger.ONE : BigInteger.ZERO; + List capacitySessionIds = + new java.util.ArrayList<>(List.of(UUID.fromString(prepared.candidate().sessionId()))); + testSchema + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_partition_reservation" + + " SET lifecycle = 'BOUND' WHERE reservation_id = ?", + prepared.issuerReservationId()); + + UUID reservedReservationId = UUID.randomUUID(); + UUID reservedSessionId = + sessionUuidForPartition( + prepared.candidate(), partitionCount, overCapacityPartition, capacitySessionIds); + capacitySessionIds.add(reservedSessionId); + insertReservationOnly( + testSchema.dsl(), + prepared.candidate(), + prepared.inventoryRevision(), + reservedReservationId, + originalOperationFence, + originalCoverageFence, + LAYOUT_VERSION, + partitionCount, + partitionCapacity, + false, + "RESERVED", + reservedSessionId); + UUID releasePendingReservationId = UUID.randomUUID(); + UUID releasePendingSessionId = + sessionUuidForPartition( + prepared.candidate(), partitionCount, otherPartition, capacitySessionIds); + capacitySessionIds.add(releasePendingSessionId); + insertReservationOnly( + testSchema.dsl(), + prepared.candidate(), + prepared.inventoryRevision(), + releasePendingReservationId, + originalOperationFence, + originalCoverageFence, + LAYOUT_VERSION, + partitionCount, + partitionCapacity, + false, + "RELEASE_PENDING", + releasePendingSessionId); + UUID releasedReservationId = UUID.randomUUID(); + UUID releasedSessionId = + sessionUuidForPartition( + prepared.candidate(), partitionCount, overCapacityPartition, capacitySessionIds); + insertReservationOnly( + testSchema.dsl(), + prepared.candidate(), + prepared.inventoryRevision(), + releasedReservationId, + originalOperationFence, + originalCoverageFence, + LAYOUT_VERSION, + partitionCount, + partitionCapacity, + false, + "RELEASED", + releasedSessionId); + + UUID requestId = UUID.randomUUID(); + var intent = + new CanonicalGameplayIssuerLayoutBootstrapRepository(testSchema.dsl()) + .beginInitialBootstrapIntent( + requestId, + descriptor(LAYOUT_VERSION, partitionCount, partitionCapacity), + sourceCheckpoint(BigInteger.valueOf(7))); + List reservationsBeforePlan = + rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_reservation"); + var owner = new CanonicalGameplayIssuerPartitionBuildRepository(testSchema.dsl()); + var plan = owner.prepareInitialBuildPlan(intent.operationId(), requestId); + + assertThat(plan.state()).isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.BLOCKED); + assertThat(plan.coverageGenerationState()) + .isEqualTo( + CanonicalGameplayIssuerPartitionBuildPlan.CoverageGenerationState.NOT_YET_ISSUED); + assertThat(plan.coverageGeneration()).isNull(); + assertThat(plan.cohortRows()) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::rowOrdinal) + .containsExactlyElementsOf( + intent.cohortRows().stream() + .map(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::rowOrdinal) + .toList()); + assertThat(plan.cohortRows()) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::kind) + .containsExactlyElementsOf( + intent.cohortRows().stream() + .map(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::kind) + .toList()); + assertThat(plan.cohortRows()) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceKey) + .containsExactlyElementsOf( + intent.cohortRows().stream() + .map(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceKey) + .toList()); + assertThat(plan.cohortRows()) + .extracting( + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceInventoryRevision) + .containsExactlyElementsOf( + intent.cohortRows().stream() + .map( + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow + ::sourceInventoryRevision) + .toList()); + assertThat(plan.cohortRows()) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceRowJson) + .containsExactlyElementsOf( + intent.cohortRows().stream() + .map(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceRowJson) + .toList()); + assertThat(plan.cohortRows()) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceRowDigest) + .containsExactlyElementsOf( + intent.cohortRows().stream() + .map(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceRowDigest) + .toList()); + + assertThat(plan.memberWorks()).hasSize(4); + assertThat(plan.memberWorks()) + .extracting(CanonicalGameplayIssuerPartitionBuildPlan.MemberWork::reservationLifecycle) + .containsExactlyInAnyOrder("BOUND", "RESERVED", "RELEASE_PENDING", "RELEASED"); + assertThat(plan.memberWorks()) + .allSatisfy( + work -> { + assertThat(work.originalPartitionId()) + .isEqualTo( + CanonicalGameplayBindingRef.fromExactBytes(work.bindingRef()) + .partitionId(partitionCount)); + assertThat(work.originalLayoutVersion()).isEqualTo(LAYOUT_VERSION); + assertThat(work.originalPartitionCount()).isEqualTo(partitionCount); + assertThat(work.originalPartitionCapacity()).isEqualTo(partitionCapacity); + assertThat(work.originalIssuerCoverageOperationId()) + .isNotEqualTo(work.plannedAnchorOperationId()); + assertThat(work.originalIssuerCoverageOperationFence()) + .isEqualTo(originalOperationFence) + .isNotEqualTo(intent.operationFence()); + assertThat(work.originalCoverageFence()) + .isEqualTo(originalCoverageFence) + .isNotEqualTo(intent.coverageFence()); + if (work.reservationId().equals(prepared.issuerReservationId())) { + assertThat(work.originalInventorySnapshotRevision()).isEqualTo(BigInteger.ONE); + } else { + assertThat(work.originalInventorySnapshotRevision()) + .isEqualTo(intent.inventorySnapshotRevision()); + } + assertThat(work.plannedPartitionId()).isEqualTo(work.originalPartitionId()); + assertThat(work.plannedAnchorOperationId()).isEqualTo(intent.operationId()); + assertThat(work.plannedAnchorOperationFence()).isEqualTo(intent.operationFence()); + assertThat(work.plannedAnchorCoverageFence()).isEqualTo(intent.coverageFence()); + assertThat(work.plannedAnchorInventorySnapshotRevision()) + .isEqualTo(intent.inventorySnapshotRevision()); + }); + assertThat(plan.memberWorks()) + .filteredOn(CanonicalGameplayIssuerPartitionBuildPlan.MemberWork::countsTowardCapacity) + .hasSize(3); + var releasedWork = + plan.memberWorks().stream() + .filter(work -> work.reservationId().equals(releasedReservationId)) + .findFirst() + .orElseThrow(); + var reservedWork = + plan.memberWorks().stream() + .filter(work -> work.reservationId().equals(reservedReservationId)) + .findFirst() + .orElseThrow(); + var releasePendingWork = + plan.memberWorks().stream() + .filter(work -> work.reservationId().equals(releasePendingReservationId)) + .findFirst() + .orElseThrow(); + var boundWork = + plan.memberWorks().stream() + .filter(work -> work.reservationId().equals(prepared.issuerReservationId())) + .findFirst() + .orElseThrow(); + assertThat(releasedWork.reservationLifecycle()).isEqualTo("RELEASED"); + assertThat(releasedWork.countsTowardCapacity()).isFalse(); + assertThat(releasedWork.originalPartitionId()).isEqualTo(overCapacityPartition); + assertThat(reservedWork.reservationLifecycle()).isEqualTo("RESERVED"); + assertThat(reservedWork.countsTowardCapacity()).isTrue(); + assertThat(reservedWork.originalPartitionId()).isEqualTo(overCapacityPartition); + assertThat(releasePendingWork.reservationLifecycle()).isEqualTo("RELEASE_PENDING"); + assertThat(releasePendingWork.countsTowardCapacity()).isTrue(); + assertThat(releasePendingWork.originalPartitionId()).isEqualTo(otherPartition); + assertThat(boundWork.reservationLifecycle()).isEqualTo("BOUND"); + assertThat(boundWork.countsTowardCapacity()).isTrue(); + assertThat(boundWork.originalPartitionId()).isEqualTo(overCapacityPartition); + + assertThat(plan.blockers()).hasSize(5); + assertThat(plan.blockers()) + .extracting(CanonicalGameplayIssuerPartitionBuildPlan.Blocker::code) + .containsOnly( + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode.PARTITION_CAPACITY_EXCEEDED, + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode.AGGREGATE_CAPACITY_EXCEEDED); + for (var work : + plan.memberWorks().stream() + .filter(CanonicalGameplayIssuerPartitionBuildPlan.MemberWork::countsTowardCapacity) + .toList()) { + var workBlockerCodes = + plan.blockers().stream() + .filter(blocker -> blocker.sourceRowOrdinal() == work.reservationSourceRowOrdinal()) + .map(CanonicalGameplayIssuerPartitionBuildPlan.Blocker::code) + .toList(); + if (work.reservationId().equals(releasePendingWork.reservationId())) { + assertThat(workBlockerCodes) + .containsExactly( + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode + .AGGREGATE_CAPACITY_EXCEEDED); + } else { + assertThat(workBlockerCodes) + .containsExactlyInAnyOrder( + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode.PARTITION_CAPACITY_EXCEEDED, + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode + .AGGREGATE_CAPACITY_EXCEEDED); + } + } + assertThat(plan.blockers()) + .noneMatch( + blocker -> blocker.sourceRowOrdinal() == releasedWork.reservationSourceRowOrdinal()); + + assertThat(rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_build_plan")) + .hasSize(1); + assertThat( + rowImages( + testSchema.dsl(), "game_session_canonical_issuer_partition_build_cohort_row")) + .hasSize(intent.cohortRows().size()); + assertThat( + rowImages( + testSchema.dsl(), "game_session_canonical_issuer_partition_build_member_work")) + .hasSize(4); + assertThat( + rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_build_blocker")) + .hasSize(5); + assertThat(rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_reservation")) + .containsExactlyElementsOf(reservationsBeforePlan); + + var retry = owner.prepareInitialBuildPlan(intent.operationId(), requestId); + assertThat(retry.buildOperationId()).isEqualTo(plan.buildOperationId()); + assertThat(retry.planDigest()).isEqualTo(plan.planDigest()); + assertThat(retry.blockers()).containsExactlyElementsOf(plan.blockers()); + assertThat(retry.memberWorks()) + .extracting(CanonicalGameplayIssuerPartitionBuildPlan.MemberWork::memberOperationId) + .containsExactlyElementsOf( + plan.memberWorks().stream() + .map(CanonicalGameplayIssuerPartitionBuildPlan.MemberWork::memberOperationId) + .toList()); + } finally { + dropSchema(testSchema.schema()); + } + } + + private static void assertBlockedInitialReservation( + CanonicalGameplayIssuerPartitionBuildRepository owner, + CanonicalGameplayIssuerPartitionBuildPlan plan, + LayoutFixture fixture) { + assertThat(plan.state()).isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.BLOCKED); + assertThat(plan.coverageGenerationState()) + .isEqualTo( + CanonicalGameplayIssuerPartitionBuildPlan.CoverageGenerationState.NOT_YET_ISSUED); + assertThat(plan.coverageGeneration()).isNull(); + var originalReservation = + fixture.intent().cohortRows().stream() + .filter( + row -> + row.kind() + == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.RESERVATION + && row.sourceKey().equals(fixture.extraReservationId().toString())) + .findFirst() + .orElseThrow(); + var retainedReservation = + plan.cohortRows().stream() + .filter(row -> row.rowOrdinal() == originalReservation.rowOrdinal()) + .findFirst() + .orElseThrow(); + assertThat(retainedReservation.sourceRowJson()).isEqualTo(originalReservation.sourceRowJson()); + assertThat(retainedReservation.sourceRowDigest()) + .isEqualTo(originalReservation.sourceRowDigest()); + assertThat(plan.blockers()) + .anySatisfy( + blocker -> { + assertThat(blocker.sourceRowOrdinal()).isEqualTo(originalReservation.rowOrdinal()); + assertThat(blocker.code()) + .isEqualTo( + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode + .CONFLICTING_RESERVATION_LINK); + }); + assertThat(plan.memberWorks()) + .extracting(CanonicalGameplayIssuerPartitionBuildPlan.MemberWork::reservationId) + .contains(fixture.bindingReservationId()) + .doesNotContain(fixture.extraReservationId()); + var retry = owner.prepareInitialBuildPlan(fixture.intent().operationId(), fixture.requestId()); + assertThat(retry.buildOperationId()).isEqualTo(plan.buildOperationId()); + assertThat(retry.planDigest()).isEqualTo(plan.planDigest()); + assertThat(retry.blockers()).containsExactlyElementsOf(plan.blockers()); + } + + private static CanonicalGameplayIssuerPartitionBuildPlan prepareAtGate( + DSLContext dsl, UUID operationId, UUID requestId, CountDownLatch ready, CountDownLatch start) + throws InterruptedException { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) + throw new IllegalStateException("test start gate timed out"); + return new CanonicalGameplayIssuerPartitionBuildRepository(dsl) + .prepareInitialBuildPlan(operationId, requestId); + } + + private static Fixture pendingFixture(TestSchema testSchema) { + establishActualLegacyDisposition(testSchema.dsl()); + var prepared = + prepareActualBinding(new CanonicalGameplayBindingInventoryRepository(testSchema.dsl())); + UUID requestId = UUID.randomUUID(); + var intent = + new CanonicalGameplayIssuerLayoutBootstrapRepository(testSchema.dsl()) + .beginInitialBootstrapIntent( + requestId, + descriptor(LAYOUT_VERSION, PARTITION_COUNT, PARTITION_CAPACITY), + sourceCheckpoint(BigInteger.valueOf(7))); + return new Fixture(intent, requestId, prepared.issuerReservationId()); + } + + private static LayoutFixture pendingLayoutFixture( + TestSchema testSchema, + BigInteger reservationLayoutVersion, + BigInteger reservationPartitionCount, + BigInteger reservationPartitionCapacity, + boolean wrongOriginalPartition) { + establishActualLegacyDisposition(testSchema.dsl()); + var prepared = + prepareActualBinding(new CanonicalGameplayBindingInventoryRepository(testSchema.dsl())); + UUID extraReservationId = UUID.randomUUID(); + insertReservationOnly( + testSchema.dsl(), + prepared.candidate(), + prepared.inventoryRevision(), + extraReservationId, + BigInteger.valueOf(17), + BigInteger.valueOf(19), + reservationLayoutVersion, + reservationPartitionCount, + reservationPartitionCapacity, + wrongOriginalPartition); + UUID requestId = UUID.randomUUID(); + var intent = + new CanonicalGameplayIssuerLayoutBootstrapRepository(testSchema.dsl()) + .beginInitialBootstrapIntent( + requestId, + descriptor(LAYOUT_VERSION, PARTITION_COUNT, PARTITION_CAPACITY), + sourceCheckpoint(BigInteger.valueOf(7))); + return new LayoutFixture(intent, requestId, prepared.issuerReservationId(), extraReservationId); + } + + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor + descriptor(BigInteger version, BigInteger count, BigInteger capacity) { + String encoded = + "issuer-layout-descriptor/v1|" + + ISSUER + + "|" + + version + + "|" + + count + + "|" + + capacity + + "|" + + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY; + return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor( + ISSUER, + version, + count, + capacity, + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY, + encoded.getBytes(StandardCharsets.UTF_8)); + } + + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + sourceCheckpoint(BigInteger issuerGeneration) { + long sequence = issuerGeneration.longValueExact() - 1L; + var event = + AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + UUID.randomUUID().toString(), + UUID.randomUUID().toString(), + AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + ISSUER, + Long.toString(sequence), + ISSUER, + issuerGeneration.toString(), + issuerGeneration.toString(), + "ISSUER_SECURITY_CHANGE")); + byte[] eventBytes = event.canonicalJsonUtf8(); + return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint( + ISSUER, issuerGeneration, eventBytes, eventBytes); + } + + private static CanonicalGameplayBindingTransitionSnapshot prepareActualBinding( + CanonicalGameplayBindingInventoryRepository inventory) { + return prepareActualBinding( + inventory, + LAYOUT_VERSION, + PARTITION_COUNT, + PARTITION_CAPACITY, + BigInteger.ONE, + BigInteger.TWO); + } + + private static CanonicalGameplayBindingTransitionSnapshot prepareActualBinding( + CanonicalGameplayBindingInventoryRepository inventory, + BigInteger layoutVersion, + BigInteger partitionCount, + BigInteger partitionCapacity, + BigInteger originalOperationFence, + BigInteger originalCoverageFence) { + UUID transitionId = UUID.randomUUID(); + UUID reservationId = UUID.randomUUID(); + UUID reservationFence = UUID.randomUUID(); + UUID issuerCoverageOperationId = UUID.randomUUID(); + var candidate = + new CanonicalGameplayBindingIdentity( + ACCOUNT_ID, + TENANT_ID, + NAMESPACE_ID, + CHARACTER_ID, + "SHARED", + GAME_INSTANCE_ID, + 23L, + UUID.fromString("77777777-7777-4777-8777-777777777777").toString(), + REGION_ID, + BigInteger.valueOf(12), + ISSUER, + BigInteger.valueOf(7), + layoutVersion, + partitionCount, + partitionCapacity); + var reservation = + new CanonicalIssuerReservationFenceEvidence( + reservationId, + reservationFence, + issuerCoverageOperationId, + originalOperationFence, + originalCoverageFence, + BigInteger.ONE); + return inventory.prepare( + new CanonicalGameplayBindingTransitionRequest( + transitionId, UUID.randomUUID(), candidate, reservation, null, null)); + } + + private static UUID sessionUuidForPartition( + CanonicalGameplayBindingIdentity template, + BigInteger partitionCount, + BigInteger partitionId, + List excludedSessionIds) { + for (int candidate = 1; candidate <= 10_000; candidate++) { + UUID sessionUuid = + UUID.nameUUIDFromBytes( + ("issuer-build-capacity-session-" + candidate).getBytes(StandardCharsets.UTF_8)); + if (excludedSessionIds.contains(sessionUuid)) continue; + byte[] bindingRef = + CanonicalGameplayBindingRef.of( + template.tenantId().toString(), + template.gameInstanceId().toString(), + sessionUuid.toString()) + .bytes(); + if (CanonicalGameplayBindingRef.fromExactBytes(bindingRef) + .partitionId(partitionCount) + .equals(partitionId)) { + return sessionUuid; + } + } + throw new IllegalStateException("Could not prepare a fixture binding in the target partition"); + } + + private static void insertReservationOnly( + DSLContext dsl, + CanonicalGameplayBindingIdentity template, + BigInteger revision, + UUID reservationId, + BigInteger originalOperationFence, + BigInteger originalCoverageFence) { + insertReservationOnly( + dsl, + template, + revision, + reservationId, + originalOperationFence, + originalCoverageFence, + template.issuerIndexLayoutVersion(), + template.issuerIndexPartitionCount(), + template.issuerIndexPartitionCapacity(), + false); + } + + private static void insertReservationOnly( + DSLContext dsl, + CanonicalGameplayBindingIdentity template, + BigInteger revision, + UUID reservationId, + BigInteger originalOperationFence, + BigInteger originalCoverageFence, + BigInteger layoutVersion, + BigInteger partitionCount, + BigInteger partitionCapacity, + boolean wrongOriginalPartition) { + insertReservationOnly( + dsl, + template, + revision, + reservationId, + originalOperationFence, + originalCoverageFence, + layoutVersion, + partitionCount, + partitionCapacity, + wrongOriginalPartition, + "RESERVED", + UUID.fromString("99999999-9999-4999-8999-999999999999")); + } + + private static void insertReservationOnly( + DSLContext dsl, + CanonicalGameplayBindingIdentity template, + BigInteger revision, + UUID reservationId, + BigInteger originalOperationFence, + BigInteger originalCoverageFence, + BigInteger layoutVersion, + BigInteger partitionCount, + BigInteger partitionCapacity, + boolean wrongOriginalPartition, + String lifecycle, + UUID sessionUuid) { + UUID characterId = UUID.fromString("88888888-8888-4888-8888-888888888888"); + UUID transitionId = UUID.randomUUID(); + UUID fence = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String sessionId = sessionUuid.toString(); + var bindingRef = + CanonicalGameplayBindingRef.of( + template.tenantId().toString(), template.gameInstanceId().toString(), sessionId); + BigInteger canonicalOriginalPartition = bindingRef.partitionId(partitionCount); + BigInteger partitionId = + wrongOriginalPartition + ? canonicalOriginalPartition.add(BigInteger.ONE).mod(partitionCount) + : canonicalOriginalPartition; + dsl.execute( + "INSERT INTO game_session_canonical_issuer_partition_reservation" + + " (reservation_id, binding_ref, account_id, tenant_id, game_instance_id," + + " runtime_game_instance_id, session_id, binding_generation, transition_id, issuer_id," + + " issuer_auth_generation, playable_state_namespace_id, character_id," + + " playable_state_scope, region_id, region_epoch, partition_id," + + " issuer_index_layout_version, issuer_index_partition_count," + + " issuer_index_partition_capacity, lifecycle, reservation_fence," + + " issuer_coverage_operation_id, issuer_coverage_operation_fence, coverage_fence," + + " inventory_snapshot_revision, inventory_revision)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + + " ?, ?, ?, ?, ?, ?, ?)", + reservationId, + bindingRef.bytes(), + template.accountId(), + template.tenantId(), + template.gameInstanceId(), + template.runtimeGameInstanceId(), + sessionId, + BigDecimal.ONE, + transitionId, + ISSUER, + new BigDecimal(template.issuerAuthGeneration()), + template.playableStateNamespaceId(), + characterId, + template.playableStateScope(), + template.regionId(), + new BigDecimal(template.regionEpoch()), + new BigDecimal(partitionId), + new BigDecimal(layoutVersion), + new BigDecimal(partitionCount), + new BigDecimal(partitionCapacity), + lifecycle, + fence, + operationId, + new BigDecimal(originalOperationFence), + new BigDecimal(originalCoverageFence), + new BigDecimal(revision), + new BigDecimal(revision)); + } + + private static void establishActualLegacyDisposition(DSLContext dsl) { + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); + UUID cohortId = UUID.randomUUID(); + UUID writerFence = UUID.randomUUID(); + var storageIdentity = + new CanonicalGameplayLegacyMigrationStorageIdentity( + "controlled-cluster-uid", + "controlled-namespace-uid", + "controlled-producer-pod-uid", + "controlled-container-id", + "controlled-node-uid", + "123456789", + 42L, + "controlled-postgres-volume-uid", + "controlled-redis-run-id", + "controlled-redis-volume-uid"); + var fencedCohort = + new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { + @Override + public UUID cohortId() { + return cohortId; + } + + @Override + public UUID legacyWriterFence() { + return writerFence; + } + + @Override + public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + return storageIdentity; + } + + @Override + public void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity expected) { + if (!storageIdentity.equals(expected)) { + throw new IllegalStateException("Controlled fixture storage identity changed"); + } + } + }; + var owner = + new CanonicalGameplayLegacyMigrationOwner( + migration, + inventory, + () -> fencedCohort, + ignored -> + new CanonicalGameplayLegacyMigrationSourceSnapshot( + EnumSet.of( + Family.TENANT_SESSION_CONTEXT, + Family.SESSION_ALIAS_CONTEXT, + Family.GAMEPLAY_IDENTITY_CONTEXT, + Family.GAMEPLAY_NAME_CONTEXT, + Family.MOVEMENT_EFFECT, + Family.DURABLE_EFFECT), + List.of()), + new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { + @Override + public void rebuildExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + CanonicalGameplayLegacyMigrationSourceSnapshot source, + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot + canonical) { + assertThat(canonical.bindings()).isEmpty(); + assertThat(canonical.reservations()).isEmpty(); + } + + @Override + public CanonicalGameplayLegacyMigrationReadback readBackExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot + canonical) { + assertThat(canonical.bindings()).isEmpty(); + return new CanonicalGameplayLegacyMigrationReadback( + List.of(), List.of(), List.of(), List.of()); + } + }); + assertThat(owner.migrate().state()) + .isEqualTo(CanonicalGameplayLegacyMigrationOperation.State.VERIFIED); + } + + private static TestSchema newTestSchema(String prefix) { + return newTestSchemaAtVersion(prefix, null); + } + + private static TestSchema newTestSchemaAtVersion(String prefix, String version) { + String schema = prefix + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION); + if (version != null) configuration.target(MigrationVersion.fromVersion(version)); + configuration.load().migrate(); + return new TestSchema(schema, dataSource, DSL.using(dataSource, SQLDialect.POSTGRES)); + } + + private static void migrateRemaining(TestSchema testSchema) { + Flyway.configure() + .dataSource(testSchema.dataSource()) + .schemas(testSchema.schema()) + .defaultSchema(testSchema.schema()) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + } + + private static TestSchema newLegacyIssuerTestSchema(String prefix) { + String schema = prefix + UUID.randomUUID().toString().replace("-", ""); + 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(); + 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(); + return new TestSchema(schema, dataSource, dsl); + } + + private static void insertLegacyReservationBeforeIssuerStringConversion(DSLContext dsl) { + UUID reservationId = UUID.randomUUID(); + UUID transitionId = UUID.randomUUID(); + UUID reservationFence = UUID.randomUUID(); + UUID oldIssuerId = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + String sessionId = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb").toString(); + var bindingRef = + CanonicalGameplayBindingRef.of( + TENANT_ID.toString(), GAME_INSTANCE_ID.toString(), sessionId); + BigInteger partitionId = bindingRef.partitionId(PARTITION_COUNT); + dsl.execute( + "INSERT INTO game_session_canonical_issuer_partition_reservation" + + " (reservation_id, binding_ref, account_id, tenant_id, game_instance_id," + + " runtime_game_instance_id, session_id, binding_generation, transition_id, issuer_id," + + " issuer_auth_generation, playable_state_namespace_id, character_id," + + " playable_state_scope, region_id, region_epoch, partition_id," + + " issuer_index_layout_version, issuer_index_partition_count," + + " issuer_index_partition_capacity, lifecycle, reservation_fence," + + " issuer_coverage_operation_id, issuer_coverage_operation_fence, coverage_fence," + + " inventory_snapshot_revision, inventory_revision)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + + " 'RESERVED', ?, ?, ?, ?, ?, ?)", + reservationId, + bindingRef.bytes(), + ACCOUNT_ID, + TENANT_ID, + GAME_INSTANCE_ID, + 23L, + sessionId, + BigDecimal.ONE, + transitionId, + oldIssuerId, + BigDecimal.valueOf(7), + NAMESPACE_ID, + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + "SHARED", + REGION_ID, + BigDecimal.valueOf(12), + new BigDecimal(partitionId), + new BigDecimal(LAYOUT_VERSION), + new BigDecimal(PARTITION_COUNT), + new BigDecimal(PARTITION_CAPACITY), + reservationFence, + UUID.randomUUID(), + BigDecimal.ONE, + BigDecimal.TWO, + BigDecimal.ONE, + BigDecimal.ONE); + dsl.execute( + "UPDATE game_session_canonical_binding_inventory_clock" + + " SET inventory_revision = 1 WHERE singleton_id = 1 AND inventory_revision = 0"); + } + + private static DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + String jdbcUrl = postgres.getJdbcUrl(); + String separator = jdbcUrl.contains("?") ? "&" : "?"; + dataSource.setUrl(jdbcUrl + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } + + private static List rowImages(DSLContext dsl, String tableName) { + return dsl.fetch( + "SELECT to_jsonb(retained_row)::text AS row_image FROM " + + tableName + + " retained_row ORDER BY to_jsonb(retained_row)::text") + .getValues("row_image", String.class); + } + + private static void dropSchema(String schema) { + try (Connection connection = dataSource("public").getConnection()) { + DSL.using(connection, SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } catch (SQLException failure) { + throw new IllegalStateException("Could not drop the owned issuer-build test schema", failure); + } + } + + private record Fixture( + CanonicalGameplayIssuerLayoutBootstrapIntent intent, UUID requestId, UUID reservationId) {} + + private record LayoutFixture( + CanonicalGameplayIssuerLayoutBootstrapIntent intent, + UUID requestId, + UUID bindingReservationId, + UUID extraReservationId) {} + + private record TestSchema(String schema, DriverManagerDataSource dataSource, DSLContext dsl) {} +} From 9fb188ce46b52daf9a6dd97fb798bc041b7c8353 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 26 Oct 2026 15:28:31 +1300 Subject: [PATCH 04/34] Checkpoint local issuer member issuance and partition projection integration --- .../system-architecture-redis-lua-patterns.md | 1 + .../architecture/system-architecture-redis.md | 6 +- .../player-access-and-session.md | 2 + .../contracts/RedisScriptDescriptor.java | 1 + ...ameplayIssuerBootstrapMemberOperation.java | 239 ++++ ...uerBootstrapMemberOperationRepository.java | 745 +++++++++++ ...IssuerBootstrapPartitionPhysicalCodec.java | 442 +++++++ ...layIssuerBootstrapPartitionRedisOwner.java | 447 +++++++ ...lGameplayIssuerBootstrapPartitionWork.java | 98 ++ ...ameplayIssuerPartitionBuildRepository.java | 186 +++ ...strapPartitionRedisScriptContribution.java | 52 + ...ical_issuer_bootstrap_member_operation.sql | 254 ++++ ...ssion-issuer-bootstrap-partition-build.lua | 315 +++++ ...sion-issuer-bootstrap-partition-build.json | 39 + ...berOperationRepositoryIntegrationTest.java | 952 ++++++++++++++ ...rapPartitionRedisOwnerIntegrationTest.java | 1145 +++++++++++++++++ ...rtitionBuildRepositoryIntegrationTest.java | 78 +- 17 files changed, 4995 insertions(+), 7 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperation.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwner.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionWork.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V1032__canonical_issuer_bootstrap_member_operation.sql create mode 100644 services/game-session-service/src/main/resources/redis/lua/game-session-issuer-bootstrap-partition-build.lua create mode 100644 services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-bootstrap-partition-build.json create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java diff --git a/design/architecture/system-architecture-redis-lua-patterns.md b/design/architecture/system-architecture-redis-lua-patterns.md index 0c7d2e0852..66bde4194d 100644 --- a/design/architecture/system-architecture-redis-lua-patterns.md +++ b/design/architecture/system-architecture-redis-lua-patterns.md @@ -35,6 +35,7 @@ Every coordination script belongs to a **script category** that constrains which | Timers and retries | `timer:{tenantRegionTag}`, `retry:{tenantRegionTag}` | Shard-local scripts operating on keys that share the same `{tenantRegionTag}`; no cross-slot operations. | | Gameplay session CAS / bindings | `session:game:{tenantGameplayTag}::`, tenant-tagged `session:game:index:*:{tenantGameplayTag}:*`, and `session:game:account-admission:{tenantGameplayTag}::` | Gameplay session CAS/update scripts may be shard-local multi-key scripts where all gameplay-session keys share `{tenantGameplayTag}`. The final binding CAS checks the exact account-qualified barrier in that slot. These scripts do not operate on Account auth-token registry keys, tick keys, or the untagged global account index/control key in the same invocation. | | Cross-tenant gameplay-session account index | `session:game:index:account:` | This global account index cannot share every tenant gameplay slot and is never included in a shard-local gameplay CAS/Lua invocation. Game Session updates it through a separate idempotent write after the owning gameplay-session mutation and reconciles it from authoritative session bindings. Account-wide revocation uses the index as a discovery projection but verifies and mutates each tenant-local binding through its owning shard-local contract; missing or stale index entries are repaired rather than treated as authorization truth. | +| Issuer gameplay-session index | `session:game:index:issuer:{issuerIndexLayoutTag}::` | `SESSION_ISSUER_INDEX` operations touch exactly one pinned issuer-layout partition HASH. Binding members and versioned reservation-capacity metadata share that one key and atomic boundary; full original reservation, anchor, local operation and incarnation evidence is compared. These invocations never mix issuer partitions with tenant gameplay, account, region or replay keys. | | Account auth-token registry | `session:auth:token:` | Account-owned issued-token registry operations are single-key operations for the exact token hash. The exact-token registry record is mandatory validity and per-token-revocation authority: a cryptographically valid JWT without a matching permitted record is denied, and Lua must not invent validity from absence or from a generation alone. Durable issuer/account/tenant/membership authority generations advance in Account Service; Redis entries project/read through those durable generations for validation, while Lua may enforce the stored record state but never becomes the authority for generation advancement. This is not part of gameplay session CAS. | | Gateway replay admission | `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:` | The `gateway-connect-token-replay-consume/v1` descriptor is the only three-key descriptor in this category: it runs only on Coordination Redis and receives readiness/fence, replay, and deny keys in that order. The literal `{gateway-connect-token-replay-v1}` hash tag is required on all three keys so Redis Cluster executes the atomic operation in one slot; the readiness value carries `replayAdmissionFence`. The separate `gateway-connect-token-browser-revoke/v1` descriptor is a one-key deny-marker mutation using only `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:` with the same literal tag; it is not part of this three-key key order. The current generic Cache-bound writer's only untagged output is the replay marker; it has no deny-marker, readiness, or replay-fence writer. That old replay key is migration-only drift and is not a valid descriptor shape. | | Session-to-region bridge | `tick:{tenantRegionTag}:session-binding:` plus `tick-executor-lease:{tenantRegionTag}` | Region-lease scripts only. They update region-authoritative gameplay bindings using caller-supplied `sessionId` / `binding_generation` and never read `session:game:*` directly inside Lua. | diff --git a/design/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index 048d94c86c..d1a17addc8 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -369,14 +369,16 @@ value: { The value is a closed, bounded RFC 8785 canonical JSON object. Except for the literal numeric `schemaVersion: 2`, counters use canonical unsigned decimal strings; every counter is positive except the zero-based `partitionId`. Implementations preserve values beyond binary floating-point precision. UUIDs and identifiers retain their exact canonical spelling, and bytes use canonical padded Base64. `sourceEventBytes` and `sourceEventDigest` are both explicit `null` only when the exact qualified Account checkpoint has no corresponding event. Unknown or duplicate fields, unsupported versions, malformed UTF-8, noncanonical bytes, inconsistent owner/partition/layout references, and resource-bound violations fail closed; parser limits never authorize normalization or truncation. -The value preserves two distinct issuer-coverage tuples. `reservation.issuerCoverageOperationId`, `issuerCoverageOperationFence`, `coverageFence`, and `inventorySnapshotRevision` are copied unchanged from the original durable reservation. The four fields under `anchor` identify the issuer coverage anchor carried by this v2 value; they are not a replacement for or reconstruction of the original reservation tuple. No equality between those tuples is required. `anchor.issuerInventorySnapshotRevision` is the complete immutable issuer inventory revision; `reservation.inventoryRevision` is that reservation's durable transition revision, and they are not interchangeable. The full owner identity, immutable authorized layout descriptor, and Account source bytes must match the exact binding and anchor evidence; the reservation must independently match its original durable source. Before a physical bootstrap write, the owner proves that this original reservation belongs to the frozen complete issuer cohort and links it to the exact bootstrap operation and fences. Shape parsing alone grants no authority. +The value preserves two distinct issuer-coverage tuples. `reservation.issuerCoverageOperationId`, `issuerCoverageOperationFence`, `coverageFence`, and `inventorySnapshotRevision` are copied unchanged from the original durable reservation. The four coverage-tuple fields under `anchor` (`issuerCoverageOperationId`, `operationFence`, `coverageFence`, and `issuerInventorySnapshotRevision`) identify the issuer coverage anchor carried by this v2 value. Together with the anchor's exact Account source fields, they are independent from the original reservation tuple and never replace or reconstruct it. No equality between those tuples is required. `anchor.issuerInventorySnapshotRevision` is the complete immutable issuer inventory revision; `reservation.inventoryRevision` is that reservation's durable transition revision, and they are not interchangeable. The full owner identity, immutable authorized layout descriptor, and Account source bytes must match the exact binding and anchor evidence; the reservation must independently match its original durable source. Before a physical bootstrap write, the owner proves that this original reservation belongs to the frozen complete issuer cohort and links it to the exact bootstrap operation and fences. Shape parsing alone grants no authority. -Mutation, retry, readback, and cleanup preserve and exact-compare both complete coverage tuples, the original reservation identity, owner, transition, layout, partition, lifecycle, fence and revision, and the local member-operation linkage. Same binding identity with different original reservation provenance, anchor, or operation linkage is a conflict. The owner never reconstructs the original tuple from the anchor, rewrites or re-anchors the original SQL reservation, or invents a member generation. The anchor operation fence, coverage fence, binding-local member-operation fence and `issuerControlEpoch` retain separate evidence domains. The anchor operation and coverage fences retain their distinct values. Equality between counters from different domains does not merge their authority or imply an ordering. `memberOperation.coverageGeneration` is concrete only after its issuing owner allocates it; a parser, bootstrap preparation, or caller cannot invent it. The value retains the complete stable incarnation binding, including every field of accepted `targetDeploymentEvidence/v1`, not only its digest. Fresh observation nonces, observation times, and signing-key selection are not stable row identity; the protected current-observation owner validates them at each decisive boundary. See [Redis Operations and Access](./system-architecture-redis-ops-access.md) for protected evidence ownership. +Mutation, retry, readback, and cleanup preserve and exact-compare both complete coverage tuples, the original reservation identity, owner, transition, layout, partition, lifecycle, fence and revision, and the local member-operation linkage. Same binding identity with different original reservation provenance, anchor, or operation linkage is a conflict. The owner never reconstructs the original tuple from the anchor, rewrites or re-anchors the original SQL reservation, or invents a member generation. The anchor operation fence, coverage fence, binding-local member-operation fence and `issuerControlEpoch` retain separate evidence domains. The anchor operation and coverage fences retain their distinct values. Equality between counters from different domains does not merge their authority or imply an ordering. `memberOperation.coverageGeneration` is concrete only after its issuing owner allocates it; a parser, bootstrap preparation, or caller cannot invent it. The local SQL owner issues and persists this member-operation identity before the physical member write; allocation alone proves neither readback nor completion. It is distinct from the issuer-wide acknowledgement generation, which remains `NOT_YET_ISSUED` until complete finite physical coverage is proven. The value retains the complete stable incarnation binding, including every field of accepted `targetDeploymentEvidence/v1`, not only its digest. Fresh observation nonces, observation times, and signing-key selection are not stable row identity; the protected current-observation owner validates them at each decisive boundary. See [Redis Operations and Access](./system-architecture-redis-ops-access.md) for protected evidence ownership. The exact `bindingRef` field identity and canonical partition key remain unchanged. Physical schema-v1 values are retained historical or legacy evidence and never qualify a v2 member, retry, readback, or cleanup. Encountering v1 requires the canonical fenced complete-inventory rebuild or migration; an empty-key assumption, SQL acknowledgement, or hidden second-key witness cannot upgrade it. The same binding under a different anchor, reservation, local operation, issuer-control epoch, or storage incarnation is a conflict, not an idempotent retry. Mutation, exact readback, and cleanup compare the complete v2 value at the one issuer-partition key and permit only the defined original-operation transition. Capacity evidence shares that same owned partition HASH and atomic boundary. Reserved versioned capacity-field names must be disjoint from every canonical `bindingRef` field, and capacity values retain the exact anchor, layout, original reservation/member-operation tuple, and incarnation needed for comparison. Capacity counts distinct non-terminal reservations through `RESERVED`, `BOUND`, and `RELEASE_PENDING`; it is not inferred from binding rows or total HASH fields. Separate capacity/readback steps compare the same complete tuples and never use a second key, key absence as initialization authority, or SQL intent as physical evidence. +The versioned reserved field `!issuer-partition-bootstrap/v1` retains the exact common bootstrap/layout/source/incarnation context, and `!issuer-reservation-capacity/v1:` retains the complete schema-v2 value for that original reservation and issued local operation. Both names are disjoint from the length-prefixed `bindingRef/v1` field grammar. A partition build compares the complete existing field set before mutation and refuses unknown, legacy, conflicting, expiring or partially decoded state without rewriting it. Full member and reservation values retain their original provenance; a header digest never replaces them. Complete per-partition readback remains a separate input to the later finite issuer-wide coverage proof, and its frozen aggregate expectation is not proof that other partitions have been built. + ### Canonical Issuer Partition Mapping The target `bindingRef` encoding is one exact versioned UTF-8 byte sequence, consistent with the repository's length-prefixed identity convention. For `segment(bytes) = ascii(canonical_decimal_count(byte_length(bytes))) + ":" + bytes`, where the count has no leading zero, the complete binding identity is encoded in this fixed order: diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 34da43788e..b853f059ba 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -18,6 +18,8 @@ The unregistered no-active first-NEW member-repair owner composes the original d The account-fence preparation source consists of the durable intent/cohort owner, persisted tenant-tag/key mapping, controlled protected current-observation receiver, one-key CLOSED Redis owner, and immutable historical CLOSED receipt. R515 freshly passes nine focused unit and 37 PostgreSQL/Redis cases for intent, cohort, serialization and controlled signed current observations. R521 freshly passes nine focused unit and 46 PostgreSQL/Redis cases, including actual Redis readback acceptance into immutable per-target V1029 receipts, expiry/current-owner refusal, trigger immutability, and populated V1028→V1029 migration/restart preservation. R523 freshly passes ten native cases, including an actual intent advancing initial control epoch 0 to epoch 1 and closing a controlled prior OPEN epoch 0; prior CLOSED epoch 0 remains a non-mutating refusal. The current-observation signer/channel, prior barrier, clock, and high-water fixtures are controlled local inputs, not operational custody or lifecycle producers. These receipts are historical AS-OF evidence: the account control remains `ACQUISITION_INTENT`, targets remain `REQUIRED`, and there is no `INSTALLED`, OPEN, token, final-CAS, admission, or account-wide-coverage proof. No operational protected attestor, accepted deployment-attestation producer, or fresh protected current-proof source is supplied. +The local issuer build-plan checkpoint at `a9b6f886cdcf88f188d79d0e38d50d1f3a253e01` retains the complete V1030 cohort and original reservation provenance in immutable V1031 plan/work/blocker rows. R569 freshly passes seven PostgreSQL cases, including concurrent original retry, restart, source/control/layout refusal, old reservation versus new anchor tuples, row and TRUNCATE guards, and per-partition/aggregate nonterminal reservation bounds with RELEASED exclusion. Enabled main and integration static analysis and formatting pass through R567/R569; the exact R569 container is independently confirmed absent. Earlier failed attempts remain retained. This qualifies preparation-time counting and retained storage only. Actual issuer-local operation issuance, physical single-key capacity/member write/readback, complete finite acknowledgement, installed anchor and ordinary NEW consumption remain unqualified until their separately constructed owners and composition pass proof; no unpublished work counts as reviewable green runway. + ### Player-created roster consumer preparation The unregistered Game Session composition consumes the independently resolved current published source through Entity's distinct created-roster and selected-character reads, preserving full original creation terminals, frozen menu/actor choice and the typed original-operation receipt/recovery/retirement branch. The [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#player-created-roster-and-selected-character) owns the created evidence contract; [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md#player-created-original-roster-storage) records its local storage consequences. V1020 receipt storage does not include the separate canonical UUID runtime or creation-protection owners and supplies no Account protection or admission authority. diff --git a/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java index 9ff5ae2fbd..a5eeacb300 100644 --- a/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java +++ b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java @@ -141,6 +141,7 @@ public enum ScriptCategory { TIMER_QUEUE, SESSION_CAS, SESSION_ACCOUNT_INDEX, + SESSION_ISSUER_INDEX, SESSION_TO_REGION_BRIDGE, MAINTENANCE, CACHE, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperation.java new file mode 100644 index 0000000000..85dba352fb --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperation.java @@ -0,0 +1,239 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; + +/** + * Immutable SQL-issued identity and exact v2 member value for one initial-bootstrap work item. + * + *

{@link Status#PENDING_PHYSICAL_PROOF} is preparation for the next physical owner. The local + * member generation in this record is not an issuer-wide coverage acknowledgement or proof that a + * Redis member was written. + */ +final class CanonicalGameplayIssuerBootstrapMemberOperation { + enum Status { + PENDING_PHYSICAL_PROOF + } + + private final UUID operationId; + private final java.math.BigInteger operationFence; + private final java.math.BigInteger localMemberGeneration; + private final UUID bootstrapOperationId; + private final UUID bootstrapRequestId; + private final UUID buildOperationId; + private final String buildPlanDigest; + private final long workOrdinal; + private final UUID preparationOperationId; + private final UUID preparationFenceId; + private final long reservationSourceRowOrdinal; + private final String reservationSourceRowDigest; + private final CanonicalGameplayIssuerMemberV2Value memberValue; + private final CanonicalGameplayBindingInventoryEntry.Lifecycle bindingLifecycle; + private final boolean expectedBindingPresent; + private final boolean countsTowardCapacity; + private final byte[] exactMemberValueBytes; + private final String memberValueDigest; + private final Status status; + + CanonicalGameplayIssuerBootstrapMemberOperation( + UUID operationId, + java.math.BigInteger operationFence, + java.math.BigInteger localMemberGeneration, + UUID bootstrapOperationId, + UUID bootstrapRequestId, + UUID buildOperationId, + String buildPlanDigest, + long workOrdinal, + UUID preparationOperationId, + UUID preparationFenceId, + long reservationSourceRowOrdinal, + String reservationSourceRowDigest, + CanonicalGameplayIssuerMemberV2Value memberValue, + CanonicalGameplayBindingInventoryEntry.Lifecycle bindingLifecycle, + boolean expectedBindingPresent, + boolean countsTowardCapacity, + byte[] exactMemberValueBytes, + String memberValueDigest, + Status status) { + this.operationId = requireNonNil(operationId, "operationId"); + this.operationFence = requirePositive(operationFence, "operationFence"); + this.localMemberGeneration = requirePositive(localMemberGeneration, "localMemberGeneration"); + this.bootstrapOperationId = requireNonNil(bootstrapOperationId, "bootstrapOperationId"); + this.bootstrapRequestId = requireNonNil(bootstrapRequestId, "bootstrapRequestId"); + this.buildOperationId = requireNonNil(buildOperationId, "buildOperationId"); + this.buildPlanDigest = requireDigest(buildPlanDigest, "buildPlanDigest"); + this.workOrdinal = requireNonNegative(workOrdinal, "workOrdinal"); + this.preparationOperationId = requireNonNil(preparationOperationId, "preparationOperationId"); + this.preparationFenceId = requireNonNil(preparationFenceId, "preparationFenceId"); + this.reservationSourceRowOrdinal = + requireNonNegative(reservationSourceRowOrdinal, "reservationSourceRowOrdinal"); + this.reservationSourceRowDigest = + requireDigest(reservationSourceRowDigest, "reservationSourceRowDigest"); + this.memberValue = Objects.requireNonNull(memberValue, "memberValue"); + this.bindingLifecycle = bindingLifecycle; + this.expectedBindingPresent = expectedBindingPresent; + this.countsTowardCapacity = countsTowardCapacity; + this.exactMemberValueBytes = + Objects.requireNonNull(exactMemberValueBytes, "exactMemberValueBytes").clone(); + if (this.exactMemberValueBytes.length == 0 + || this.exactMemberValueBytes.length + > CanonicalGameplayIssuerMemberV2Codec.MAX_VALUE_BYTES) { + throw new IllegalArgumentException( + "Exact issuer member value bytes are outside the local limit"); + } + this.memberValueDigest = requireDigest(memberValueDigest, "memberValueDigest"); + this.status = Objects.requireNonNull(status, "status"); + if (bootstrapOperationId.equals(bootstrapRequestId) + || buildOperationId.equals(bootstrapOperationId) + || buildOperationId.equals(bootstrapRequestId) + || operationId.equals(bootstrapOperationId) + || operationId.equals(bootstrapRequestId) + || operationId.equals(buildOperationId) + || operationId.equals(preparationOperationId) + || operationId.equals(preparationFenceId) + || localMemberGeneration.compareTo(operationFence) <= 0) { + throw new IllegalArgumentException( + "Issued local member identity must be distinct from preparation"); + } + if (!operationId.equals(memberValue.memberOperation().operationId()) + || !operationFence.equals(memberValue.memberOperation().operationFence()) + || !localMemberGeneration.equals(memberValue.memberOperation().coverageGeneration()) + || !bootstrapOperationId.equals(memberValue.anchor().issuerCoverageOperationId()) + || !Arrays.equals( + this.exactMemberValueBytes, CanonicalGameplayIssuerMemberV2Codec.encode(memberValue)) + || !memberValueDigest.equals( + CanonicalGameplayIssuerMemberV2Codec.sha256(this.exactMemberValueBytes))) { + throw new IllegalArgumentException( + "Issued operation fields differ from its exact schema-v2 member value"); + } + CanonicalIssuerPartitionReservation originalReservation = memberValue.reservation(); + boolean lifecycleCounts = + originalReservation.lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED; + boolean lifecycleHasBinding = + bindingLifecycle == CanonicalGameplayBindingInventoryEntry.Lifecycle.ACTIVE + || bindingLifecycle == CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL; + if (countsTowardCapacity != lifecycleCounts + || expectedBindingPresent != lifecycleHasBinding + || (expectedBindingPresent && bindingLifecycle == null)) { + throw new IllegalArgumentException( + "Physical binding and capacity actions must match the frozen SQL source lifecycle"); + } + CanonicalGameplayIssuerMemberV2Value decoded = + CanonicalGameplayIssuerMemberV2Codec.decode(this.exactMemberValueBytes); + if (!memberValue.equals(decoded)) { + throw new IllegalArgumentException( + "Exact schema-v2 member bytes decode to a different value"); + } + } + + UUID operationId() { + return operationId; + } + + BigInteger operationFence() { + return operationFence; + } + + BigInteger localMemberGeneration() { + return localMemberGeneration; + } + + UUID bootstrapOperationId() { + return bootstrapOperationId; + } + + UUID bootstrapRequestId() { + return bootstrapRequestId; + } + + UUID buildOperationId() { + return buildOperationId; + } + + String buildPlanDigest() { + return buildPlanDigest; + } + + long workOrdinal() { + return workOrdinal; + } + + UUID preparationOperationId() { + return preparationOperationId; + } + + UUID preparationFenceId() { + return preparationFenceId; + } + + long reservationSourceRowOrdinal() { + return reservationSourceRowOrdinal; + } + + String reservationSourceRowDigest() { + return reservationSourceRowDigest; + } + + CanonicalGameplayIssuerMemberV2Value memberValue() { + return memberValue; + } + + /** Full closed v2 value the physical owner must compare; not a coverage acknowledgement. */ + CanonicalGameplayIssuerMemberV2Value expectedMemberValue() { + return memberValue; + } + + CanonicalGameplayBindingInventoryEntry.Lifecycle bindingLifecycle() { + return bindingLifecycle; + } + + boolean expectedBindingPresent() { + return expectedBindingPresent; + } + + boolean countsTowardCapacity() { + return countsTowardCapacity; + } + + byte[] exactMemberValueBytes() { + return exactMemberValueBytes.clone(); + } + + String memberValueDigest() { + return memberValueDigest; + } + + Status status() { + return status; + } + + private static UUID requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException(name + " must not be nil"); + return value; + } + + private static BigInteger requirePositive(BigInteger value, String name) { + Objects.requireNonNull(value, name); + if (value.signum() <= 0) throw new IllegalArgumentException(name + " must be positive"); + return value; + } + + private static long requireNonNegative(long value, String name) { + if (value < 0) throw new IllegalArgumentException(name + " must not be negative"); + return value; + } + + private static String requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(name + " must be canonical SHA-256"); + } + return value; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepository.java new file mode 100644 index 0000000000..1ac5aa5d38 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepository.java @@ -0,0 +1,745 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Local SQL owner for issuing one immutable member operation from an exact prepared initial + * bootstrap work item. It does not execute physical Redis work or record proof completion. + */ +final class CanonicalGameplayIssuerBootstrapMemberOperationRepository { + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String COUNTER = "game_session_canonical_issuer_bootstrap_member_op_counter"; + private static final String OPERATION = + "game_session_canonical_issuer_bootstrap_member_operation"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final DSLContext dsl; + + CanonicalGameplayIssuerBootstrapMemberOperationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Begins or resumes one exact planned member work item. The current Account checkpoint and stable + * storage-incarnation inputs are explicitly controlled local collaborators: this method checks + * them against the persisted bootstrap tuple but does not authenticate their authority. + */ + CanonicalGameplayIssuerBootstrapMemberOperation beginOrResumePendingPhysicalProof( + UUID bootstrapOperationId, + UUID bootstrapRequestId, + long workOrdinal, + CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + currentAccountCheckpoint, + TrustedStableIncarnation stableIncarnation) { + requireNonNil(bootstrapOperationId, "bootstrapOperationId"); + requireNonNil(bootstrapRequestId, "bootstrapRequestId"); + if (workOrdinal < 0) throw new IllegalArgumentException("workOrdinal must not be negative"); + Objects.requireNonNull(currentAccountCheckpoint, "currentAccountCheckpoint"); + Objects.requireNonNull(stableIncarnation, "stableIncarnation"); + requireNoAmbientTransaction(); + return dsl.transactionResult( + configuration -> + beginOrResumeInTransaction( + org.jooq.impl.DSL.using(configuration), + bootstrapOperationId, + bootstrapRequestId, + workOrdinal, + currentAccountCheckpoint, + stableIncarnation)); + } + + /** + * Qualifies and issues the complete member-operation set for one exact partition in one SQL + * transaction. The partition id selects from the persisted plan; no member list is accepted. + */ + CanonicalGameplayIssuerBootstrapPartitionWork preparePartitionWork( + UUID bootstrapOperationId, + UUID bootstrapRequestId, + BigInteger partitionId, + CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + currentAccountCheckpoint, + TrustedStableIncarnation stableIncarnation) { + requireNonNil(bootstrapOperationId, "bootstrapOperationId"); + requireNonNil(bootstrapRequestId, "bootstrapRequestId"); + Objects.requireNonNull(partitionId, "partitionId"); + Objects.requireNonNull(currentAccountCheckpoint, "currentAccountCheckpoint"); + Objects.requireNonNull(stableIncarnation, "stableIncarnation"); + requireNoAmbientTransaction(); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + CanonicalGameplayIssuerPartitionBuildRepository buildRepository = + new CanonicalGameplayIssuerPartitionBuildRepository(transaction); + CanonicalGameplayIssuerPartitionBuildPlan plan = + buildRepository.readPreparedPlanInTransaction( + transaction, bootstrapOperationId, bootstrapRequestId); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); + if (partitionId.signum() < 0 + || partitionId.compareTo(intent.layoutDescriptor().partitionCount()) >= 0) { + throw conflict("Requested partition is outside the exact prepared bootstrap layout"); + } + requireCurrentAccountCheckpoint(currentAccountCheckpoint, intent.sourceCheckpoint()); + CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation = stableIncarnation.value(); + List operations = new ArrayList<>(); + for (CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work : plan.memberWorks()) { + if (!work.plannedPartitionId().equals(partitionId)) continue; + CanonicalGameplayIssuerPartitionBuildRepository.PreparedMemberWork prepared = + buildRepository.readPreparedMemberWorkFromVerifiedPlan(plan, work.workOrdinal()); + operations.add( + beginOrResumePreparedInTransaction( + transaction, prepared, currentAccountCheckpoint, incarnation)); + } + return new CanonicalGameplayIssuerBootstrapPartitionWork( + plan, partitionId, operations, incarnation); + }); + } + + private static CanonicalGameplayIssuerBootstrapMemberOperation beginOrResumeInTransaction( + DSLContext transaction, + UUID bootstrapOperationId, + UUID bootstrapRequestId, + long workOrdinal, + CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + currentAccountCheckpoint, + TrustedStableIncarnation stableIncarnation) { + CanonicalGameplayIssuerPartitionBuildRepository.PreparedMemberWork prepared = + new CanonicalGameplayIssuerPartitionBuildRepository(transaction) + .readPreparedMemberWorkInTransaction( + transaction, bootstrapOperationId, bootstrapRequestId, workOrdinal); + return beginOrResumePreparedInTransaction( + transaction, prepared, currentAccountCheckpoint, stableIncarnation.value()); + } + + private static CanonicalGameplayIssuerBootstrapMemberOperation beginOrResumePreparedInTransaction( + DSLContext transaction, + CanonicalGameplayIssuerPartitionBuildRepository.PreparedMemberWork prepared, + CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + currentAccountCheckpoint, + CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation) { + CanonicalGameplayIssuerPartitionBuildPlan plan = prepared.plan(); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work = prepared.work(); + requireCurrentAccountCheckpoint(currentAccountCheckpoint, intent.sourceCheckpoint()); + + Record existing = + transaction.fetchOne( + "SELECT * FROM " + + OPERATION + + " WHERE issuer_id = ? AND bootstrap_operation_id = ? AND work_ordinal = ? FOR UPDATE", + ISSUER, + intent.operationId(), + work.workOrdinal()); + if (existing != null) { + return loadAndRequireExactOperation(existing, prepared, incarnation); + } + + IssuedCounters counters = allocateLocalCounters(transaction, prepared); + UUID operationId = nextOperationId(transaction, prepared); + CanonicalGameplayIssuerMemberV2Value memberValue = + createMemberValue( + prepared, operationId, counters.operationFence(), counters.generation(), incarnation); + byte[] memberValueBytes = CanonicalGameplayIssuerMemberV2Codec.encode(memberValue); + String memberValueDigest = CanonicalGameplayIssuerMemberV2Codec.sha256(memberValueBytes); + insertOperation( + transaction, prepared, operationId, counters, memberValueBytes, memberValueDigest); + Record saved = + transaction.fetchOne( + "SELECT * FROM " + + OPERATION + + " WHERE issuer_id = ? AND bootstrap_operation_id = ? AND work_ordinal = ? FOR UPDATE", + ISSUER, + intent.operationId(), + work.workOrdinal()); + if (saved == null) throw conflict("Persisted bootstrap member operation is unreadable"); + CanonicalGameplayIssuerBootstrapMemberOperation result = + loadAndRequireExactOperation(saved, prepared, incarnation); + if (!result.operationId().equals(operationId) + || !result.operationFence().equals(counters.operationFence()) + || !result.localMemberGeneration().equals(counters.generation()) + || !Arrays.equals(result.exactMemberValueBytes(), memberValueBytes)) { + throw conflict("Persisted member operation differs from the SQL owner-issued value"); + } + return result; + } + + private static void requireCurrentAccountCheckpoint( + CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint current, + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint persisted) { + if (!ISSUER.equals(current.issuerId()) + || !ISSUER.equals(persisted.issuerId()) + || !current.issuerAuthGeneration().equals(persisted.issuerAuthGeneration()) + || !Arrays.equals(current.checkpointBytes(), persisted.exactCheckpointBytes()) + || !Arrays.equals(current.latestEventBytes(), persisted.latestIssuerEventBytes())) { + throw conflict( + "Controlled current Account checkpoint differs from the exact pending bootstrap source"); + } + } + + private static CanonicalGameplayIssuerBootstrapMemberOperation loadAndRequireExactOperation( + Record row, + CanonicalGameplayIssuerPartitionBuildRepository.PreparedMemberWork prepared, + CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation) { + CanonicalGameplayIssuerPartitionBuildPlan plan = prepared.plan(); + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work = prepared.work(); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); + CanonicalIssuerPartitionReservation original = prepared.originalReservation(); + byte[] bytes = requireBytes(row, "member_value_bytes"); + String digest = requireText(row, "member_value_digest"); + if (!digest.equals(CanonicalGameplayIssuerMemberV2Codec.sha256(bytes))) { + throw conflict("Persisted pending member value digest differs from its exact bytes"); + } + CanonicalGameplayIssuerMemberV2Value value; + try { + value = CanonicalGameplayIssuerMemberV2Codec.decode(bytes); + } catch (RuntimeException malformed) { + throw conflict("Persisted pending member value is not canonical schema v2"); + } + UUID operationId = requireUuid(row, "member_operation_id"); + BigInteger operationFence = readPositive(row, "operation_fence"); + BigInteger generation = readPositive(row, "local_member_generation"); + UUID bootstrapOperationId = requireUuid(row, "bootstrap_operation_id"); + UUID bootstrapRequestId = requireUuid(row, "bootstrap_request_id"); + UUID buildOperationId = requireUuid(row, "build_operation_id"); + String planDigest = requireText(row, "build_plan_digest"); + long workOrdinal = requireNonNegativeLong(row, "work_ordinal"); + UUID preparationOperationId = requireUuid(row, "preparation_operation_id"); + UUID preparationFenceId = requireUuid(row, "preparation_fence_id"); + long sourceOrdinal = requireNonNegativeLong(row, "reservation_source_row_ordinal"); + String sourceDigest = requireText(row, "reservation_source_row_digest"); + Long bindingSourceOrdinal = row.get("binding_source_row_ordinal", Long.class); + String bindingSourceDigest = row.get("binding_source_row_digest", String.class); + String bindingLifecycleText = row.get("binding_lifecycle", String.class); + CanonicalGameplayBindingInventoryEntry.Lifecycle bindingLifecycle = null; + if (bindingLifecycleText != null) { + try { + bindingLifecycle = + CanonicalGameplayBindingInventoryEntry.Lifecycle.valueOf(bindingLifecycleText); + } catch (RuntimeException malformed) { + throw conflict("Persisted pending operation has an unsupported binding lifecycle"); + } + } + boolean expectedBindingPresent = + Objects.requireNonNull(row.get("expected_binding_present", Boolean.class)); + boolean countsTowardCapacity = + Objects.requireNonNull(row.get("counts_toward_capacity", Boolean.class)); + String status = requireText(row, "member_status"); + BindingAction action = bindingAction(prepared); + + requireSameRowLinkage( + row, + prepared, + plan, + work, + original, + intent, + operationId, + operationFence, + generation, + bootstrapOperationId, + bootstrapRequestId, + buildOperationId, + planDigest, + workOrdinal, + preparationOperationId, + preparationFenceId, + sourceOrdinal, + sourceDigest, + bindingSourceOrdinal, + bindingSourceDigest, + bindingLifecycleText, + action, + expectedBindingPresent, + countsTowardCapacity, + status, + value); + CanonicalGameplayIssuerMemberV2Value expectedValue = + createMemberValue(prepared, operationId, operationFence, generation, incarnation); + if (!expectedValue.equals(value) + || !Arrays.equals(bytes, CanonicalGameplayIssuerMemberV2Codec.encode(expectedValue))) { + throw conflict("Pending member operation retry changed an exact schema-v2 field or tuple"); + } + try { + return new CanonicalGameplayIssuerBootstrapMemberOperation( + operationId, + operationFence, + generation, + bootstrapOperationId, + bootstrapRequestId, + buildOperationId, + planDigest, + workOrdinal, + preparationOperationId, + preparationFenceId, + sourceOrdinal, + sourceDigest, + value, + bindingLifecycle, + expectedBindingPresent, + countsTowardCapacity, + bytes, + digest, + CanonicalGameplayIssuerBootstrapMemberOperation.Status.valueOf(status)); + } catch (RuntimeException malformed) { + throw conflict("Persisted bootstrap member operation metadata is malformed"); + } + } + + private static void requireSameRowLinkage( + Record row, + CanonicalGameplayIssuerPartitionBuildRepository.PreparedMemberWork prepared, + CanonicalGameplayIssuerPartitionBuildPlan plan, + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work, + CanonicalIssuerPartitionReservation original, + CanonicalGameplayIssuerLayoutBootstrapIntent intent, + UUID operationId, + BigInteger operationFence, + BigInteger generation, + UUID bootstrapOperationId, + UUID bootstrapRequestId, + UUID buildOperationId, + String planDigest, + long workOrdinal, + UUID preparationOperationId, + UUID preparationFenceId, + long sourceOrdinal, + String sourceDigest, + Long bindingSourceOrdinal, + String bindingSourceDigest, + String bindingLifecycle, + BindingAction action, + boolean expectedBindingPresent, + boolean countsTowardCapacity, + String status, + CanonicalGameplayIssuerMemberV2Value value) { + if (!ISSUER.equals(requireText(row, "issuer_id")) + || !bootstrapOperationId.equals(intent.operationId()) + || !bootstrapRequestId.equals(intent.requestId()) + || !buildOperationId.equals(plan.buildOperationId()) + || !planDigest.equals(plan.planDigest()) + || workOrdinal != work.workOrdinal() + || !preparationOperationId.equals(work.memberOperationId()) + || !preparationFenceId.equals(work.memberPreparationFenceId()) + || sourceOrdinal != work.reservationSourceRowOrdinal() + || !sourceDigest.equals(work.reservationSourceRowDigest()) + || !Objects.equals(bindingSourceOrdinal, work.bindingSourceRowOrdinal()) + || !Objects.equals(bindingSourceDigest, work.bindingSourceRowDigest()) + || !Objects.equals( + bindingLifecycle, + prepared.bindingLifecycle() == null ? null : prepared.bindingLifecycle().name()) + || expectedBindingPresent != action.expectedBindingPresent() + || countsTowardCapacity != work.countsTowardCapacity() + || !original.lifecycle().name().equals(requireText(row, "reservation_lifecycle")) + || !original.reservationId().equals(row.get("reservation_id", UUID.class)) + || !original + .issuerCoverageOperationId() + .equals(row.get("original_issuer_coverage_operation_id", UUID.class)) + || !original + .issuerCoverageOperationFence() + .equals(readPositive(row, "original_issuer_coverage_operation_fence")) + || !original.coverageFence().equals(readPositive(row, "original_coverage_fence")) + || !original + .inventorySnapshotRevision() + .equals(readPositive(row, "original_inventory_snapshot_revision")) + || !intent.operationId().equals(row.get("bootstrap_anchor_operation_id", UUID.class)) + || !intent.operationFence().equals(readPositive(row, "bootstrap_anchor_operation_fence")) + || !intent.coverageFence().equals(readPositive(row, "bootstrap_anchor_coverage_fence")) + || !intent + .inventorySnapshotRevision() + .equals(readPositive(row, "bootstrap_anchor_inventory_snapshot_revision")) + || !"PENDING_PHYSICAL_PROOF".equals(status) + || row.get("member_schema_version", Short.class) == null + || row.get("member_schema_version", Short.class) + != CanonicalGameplayIssuerMemberV2Value.SCHEMA_VERSION + || !operationId.equals(value.memberOperation().operationId()) + || !operationFence.equals(value.memberOperation().operationFence()) + || !generation.equals(value.memberOperation().coverageGeneration())) { + throw conflict("Persisted member operation linkage differs from its exact prepared work"); + } + } + + private static CanonicalGameplayIssuerMemberV2Value createMemberValue( + CanonicalGameplayIssuerPartitionBuildRepository.PreparedMemberWork prepared, + UUID operationId, + BigInteger operationFence, + BigInteger generation, + CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation) { + CanonicalGameplayIssuerPartitionBuildPlan plan = prepared.plan(); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); + return new CanonicalGameplayIssuerMemberV2Value( + prepared.originalReservation().owner(), + prepared.originalReservation().bindingGeneration(), + prepared.originalReservation(), + new CanonicalGameplayIssuerMemberV2Value.Anchor( + intent.operationId(), + intent.operationFence(), + intent.coverageFence(), + intent.inventorySnapshotRevision()), + new CanonicalGameplayIssuerMemberV2Value.LocalMemberOperation( + operationId, operationFence, generation), + intent.controlEpoch(), + intent.layoutDescriptor(), + intent.sourceCheckpoint(), + incarnation); + } + + private static BindingAction bindingAction( + CanonicalGameplayIssuerPartitionBuildRepository.PreparedMemberWork prepared) { + CanonicalIssuerPartitionReservation.Lifecycle reservationLifecycle = + prepared.originalReservation().lifecycle(); + CanonicalGameplayBindingInventoryEntry.Lifecycle bindingLifecycle = prepared.bindingLifecycle(); + if (bindingLifecycle == null) { + if (reservationLifecycle == CanonicalIssuerPartitionReservation.Lifecycle.RESERVED + || reservationLifecycle == CanonicalIssuerPartitionReservation.Lifecycle.RELEASED) { + return new BindingAction(false); + } + throw conflict( + "A BOUND or RELEASE_PENDING reservation without a linked binding cannot qualify physical work"); + } + return switch (bindingLifecycle) { + case CANDIDATE_PREPARED -> { + if (reservationLifecycle != CanonicalIssuerPartitionReservation.Lifecycle.RESERVED) { + throw conflict("CANDIDATE_PREPARED binding must retain its exact RESERVED reservation"); + } + yield new BindingAction(false); + } + case PROVISIONAL -> { + if (reservationLifecycle != CanonicalIssuerPartitionReservation.Lifecycle.RESERVED) { + throw conflict("PROVISIONAL binding must retain its exact RESERVED reservation"); + } + yield new BindingAction(true); + } + case ACTIVE -> { + if (reservationLifecycle != CanonicalIssuerPartitionReservation.Lifecycle.BOUND + && reservationLifecycle + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING) { + throw conflict( + "ACTIVE binding must retain its exact BOUND or RELEASE_PENDING reservation"); + } + yield new BindingAction(true); + } + case TERMINAL -> { + if (reservationLifecycle != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED) { + throw conflict("TERMINAL binding must retain its exact RELEASED reservation"); + } + yield new BindingAction(false); + } + case TERMINAL_UNRESOLVED -> + throw conflict("TERMINAL_UNRESOLVED source cannot qualify initial physical member work"); + }; + } + + private static IssuedCounters allocateLocalCounters( + DSLContext transaction, + CanonicalGameplayIssuerPartitionBuildRepository.PreparedMemberWork prepared) { + Record counter = + transaction.fetchOne( + "SELECT * FROM " + COUNTER + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (counter == null) { + Record priorOperation = + transaction.fetchOne( + "SELECT 1 FROM " + OPERATION + " WHERE issuer_id = ? LIMIT 1", ISSUER); + if (priorOperation != null) { + throw conflict("Issuer-local member-operation counter is missing after prior issuance"); + } + transaction.execute( + "INSERT INTO " + + COUNTER + + " (issuer_id, last_issued_operation_fence, last_issued_member_generation, counter_version)" + + " VALUES (?, 0, 0, 0) ON CONFLICT (issuer_id) DO NOTHING", + ISSUER); + counter = + transaction.fetchOne( + "SELECT * FROM " + COUNTER + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (counter == null) + throw conflict("Issuer-local member-operation counter could not initialize"); + } + BigInteger previousFence = readNonNegative(counter, "last_issued_operation_fence"); + BigInteger previousGeneration = readNonNegative(counter, "last_issued_member_generation"); + long previousVersion = Objects.requireNonNull(counter.get("counter_version", Long.class)); + if (previousVersion < 0 + || (previousVersion == 0 + && (previousFence.signum() != 0 || previousGeneration.signum() != 0)) + || (previousVersion > 0 + && (!previousFence.add(BigInteger.ONE).equals(previousGeneration) + || previousFence.signum() <= 0))) { + throw conflict("Issuer-local member-operation counter state is malformed"); + } + + CanonicalGameplayIssuerPartitionBuildPlan plan = prepared.plan(); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); + CanonicalIssuerPartitionReservation original = prepared.originalReservation(); + BigInteger qualifiedSeed = + max( + intent.controlEpoch(), + intent.operationFence(), + intent.coverageFence(), + intent.inventorySnapshotRevision(), + original.issuerCoverageOperationFence(), + original.coverageFence(), + original.inventorySnapshotRevision(), + original.inventoryRevision(), + previousFence, + previousGeneration); + BigInteger newFence = qualifiedSeed.add(BigInteger.ONE); + BigInteger newGeneration = newFence.add(BigInteger.ONE); + requireCounterLimit(newFence, "operationFence"); + requireCounterLimit(newGeneration, "localMemberGeneration"); + long nextVersion; + try { + nextVersion = Math.addExact(previousVersion, 1L); + } catch (ArithmeticException overflow) { + throw conflict("Issuer-local member-operation counter version is exhausted"); + } + Record updated = + transaction.fetchOne( + "UPDATE " + + COUNTER + + " SET last_issued_operation_fence = ?, last_issued_member_generation = ?, counter_version = ?" + + " WHERE issuer_id = ? AND last_issued_operation_fence = ?" + + " AND last_issued_member_generation = ? AND counter_version = ?" + + " RETURNING issuer_id", + decimal(newFence), + decimal(newGeneration), + nextVersion, + ISSUER, + decimal(previousFence), + decimal(previousGeneration), + previousVersion); + if (updated == null) + throw conflict("Issuer-local member-operation counter compare-and-set lost"); + return new IssuedCounters(newFence, newGeneration); + } + + private static UUID nextOperationId( + DSLContext transaction, + CanonicalGameplayIssuerPartitionBuildRepository.PreparedMemberWork prepared) { + Set reserved = new HashSet<>(); + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work = prepared.work(); + CanonicalIssuerPartitionReservation original = prepared.originalReservation(); + CanonicalGameplayBindingIdentity owner = original.owner(); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = prepared.plan().bootstrapIntent(); + reserved.add(NIL_UUID); + reserved.add(intent.operationId()); + reserved.add(intent.requestId()); + reserved.add(prepared.plan().buildOperationId()); + reserved.add(work.memberOperationId()); + reserved.add(work.memberPreparationFenceId()); + reserved.add(original.reservationId()); + reserved.add(original.transitionId()); + reserved.add(original.reservationFence()); + reserved.add(original.issuerCoverageOperationId()); + reserved.add(owner.accountId()); + reserved.add(owner.tenantId()); + reserved.add(owner.playableStateNamespaceId()); + reserved.add(owner.characterId()); + reserved.add(owner.gameInstanceId()); + reserved.add(owner.regionId()); + reserved.add(UUID.fromString(owner.sessionId())); + while (true) { + UUID candidate = UUID.randomUUID(); + if (reserved.contains(candidate)) continue; + Record collision = + transaction.fetchOne( + "SELECT 1 FROM " + OPERATION + " WHERE member_operation_id = ?", candidate); + if (collision == null) return candidate; + } + } + + private static void insertOperation( + DSLContext transaction, + CanonicalGameplayIssuerPartitionBuildRepository.PreparedMemberWork prepared, + UUID operationId, + IssuedCounters counters, + byte[] bytes, + String digest) { + CanonicalGameplayIssuerPartitionBuildPlan plan = prepared.plan(); + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work = prepared.work(); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); + CanonicalIssuerPartitionReservation original = prepared.originalReservation(); + BindingAction action = bindingAction(prepared); + transaction.execute( + "INSERT INTO " + + OPERATION + + " (member_operation_id, issuer_id, bootstrap_operation_id, bootstrap_request_id," + + " build_operation_id, build_plan_digest, work_ordinal, preparation_operation_id," + + " preparation_fence_id, reservation_source_row_ordinal, reservation_source_row_digest," + + " binding_source_row_ordinal, binding_source_row_digest, binding_lifecycle," + + " reservation_id, reservation_lifecycle, expected_binding_present, counts_toward_capacity," + + " original_issuer_coverage_operation_id," + + " original_issuer_coverage_operation_fence, original_coverage_fence," + + " original_inventory_snapshot_revision, bootstrap_anchor_operation_id," + + " bootstrap_anchor_operation_fence, bootstrap_anchor_coverage_fence," + + " bootstrap_anchor_inventory_snapshot_revision, operation_fence," + + " local_member_generation, member_status, member_schema_version, member_value_bytes," + + " member_value_digest)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + + " 'PENDING_PHYSICAL_PROOF', 2, ?, ?)", + operationId, + ISSUER, + intent.operationId(), + intent.requestId(), + plan.buildOperationId(), + plan.planDigest(), + work.workOrdinal(), + work.memberOperationId(), + work.memberPreparationFenceId(), + work.reservationSourceRowOrdinal(), + work.reservationSourceRowDigest(), + work.bindingSourceRowOrdinal(), + work.bindingSourceRowDigest(), + prepared.bindingLifecycle() == null ? null : prepared.bindingLifecycle().name(), + original.reservationId(), + original.lifecycle().name(), + action.expectedBindingPresent(), + work.countsTowardCapacity(), + original.issuerCoverageOperationId(), + decimal(original.issuerCoverageOperationFence()), + decimal(original.coverageFence()), + decimal(original.inventorySnapshotRevision()), + intent.operationId(), + decimal(intent.operationFence()), + decimal(intent.coverageFence()), + decimal(intent.inventorySnapshotRevision()), + decimal(counters.operationFence()), + decimal(counters.generation()), + bytes, + digest); + } + + private static BigInteger max(BigInteger... values) { + BigInteger greatest = BigInteger.ZERO; + for (BigInteger value : values) { + if (value.compareTo(greatest) > 0) greatest = value; + } + return greatest; + } + + private static BigInteger readPositive(Record row, String field) { + BigInteger value = readNonNegative(row, field); + if (value.signum() <= 0) throw conflict(field + " must be positive"); + return value; + } + + private static BigInteger readNonNegative(Record row, String field) { + BigDecimal value = row.get(field, BigDecimal.class); + if (value == null) throw conflict(field + " is missing"); + try { + BigInteger integer = value.toBigIntegerExact(); + if (integer.signum() < 0) throw conflict(field + " must not be negative"); + requireCounterLimit(integer, field); + return integer; + } catch (ArithmeticException malformed) { + throw conflict(field + " must be an exact integer"); + } + } + + private static long requireNonNegativeLong(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null || value < 0) throw conflict(field + " must be a non-negative bigint"); + return value; + } + + private static String requireText(Record row, String field) { + String value = row.get(field, String.class); + if (value == null) throw conflict(field + " is missing"); + return value; + } + + private static byte[] requireBytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + if (value == null || value.length == 0) throw conflict(field + " is missing"); + return value; + } + + private static BigDecimal decimal(BigInteger value) { + return new BigDecimal(value); + } + + private static void requireCounterLimit(BigInteger value, String name) { + if (value.signum() < 0 + || value.toString().length() > CanonicalGameplayIssuerMemberV2Codec.MAX_COUNTER_DIGITS) { + throw conflict(name + " is outside the canonical unsigned local counter range"); + } + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(NIL_UUID)) throw new IllegalArgumentException(name + " must not be nil"); + } + + private static UUID requireUuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null || NIL_UUID.equals(value)) throw conflict(field + " must be a non-nil UUID"); + return value; + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw conflict("Issuer bootstrap member operation owner cannot join an ambient transaction"); + } + } + + private static IllegalStateException conflict(String message) { + return new IllegalStateException(message); + } + + private record BindingAction(boolean expectedBindingPresent) {} + + private record IssuedCounters(BigInteger operationFence, BigInteger generation) {} + + /** + * Shape-only controlled local input for a stable coordination-storage incarnation. Its name + * describes the required consumer input, not an authenticated attestation or production source. + */ + static final class TrustedStableIncarnation { + private final String attestorBinding; + private final String acceptedAttestationDigest; + private final CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + targetDeploymentEvidence; + private final String coordOpsRoAclDigest; + private final String coordRedisConfigObservedDigest; + + TrustedStableIncarnation( + String attestorBinding, + String acceptedAttestationDigest, + CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + targetDeploymentEvidence, + String coordOpsRoAclDigest, + String coordRedisConfigObservedDigest) { + this.attestorBinding = Objects.requireNonNull(attestorBinding, "attestorBinding"); + this.acceptedAttestationDigest = + Objects.requireNonNull(acceptedAttestationDigest, "acceptedAttestationDigest"); + this.targetDeploymentEvidence = + Objects.requireNonNull(targetDeploymentEvidence, "targetDeploymentEvidence"); + this.coordOpsRoAclDigest = Objects.requireNonNull(coordOpsRoAclDigest, "coordOpsRoAclDigest"); + this.coordRedisConfigObservedDigest = + Objects.requireNonNull(coordRedisConfigObservedDigest, "coordRedisConfigObservedDigest"); + // Reuse the v2 typed carrier's closed local shape validation without claiming custody. + value(); + } + + private CanonicalGameplayIssuerMemberV2Value.Incarnation value() { + return new CanonicalGameplayIssuerMemberV2Value.Incarnation( + attestorBinding, + acceptedAttestationDigest, + targetDeploymentEvidence, + coordOpsRoAclDigest, + coordRedisConfigObservedDigest); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.java new file mode 100644 index 0000000000..5ec07768b3 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.java @@ -0,0 +1,442 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadConstraints; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; + +/** Narrow canonical metadata and exact field-set codec for one initial-bootstrap issuer partition. */ +final class CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec { + static final String METADATA_FIELD = "!issuer-partition-bootstrap/v1"; + static final String RESERVATION_FIELD_PREFIX = "!issuer-reservation-capacity/v1:"; + static final int MAX_MEMBER_OPERATIONS = 256; + static final int MAX_HASH_FIELDS = 1 + 2 * MAX_MEMBER_OPERATIONS; + static final int MAX_BINDING_REF_BYTES = 6_144; + static final int MAX_VALUE_BYTES = CanonicalGameplayIssuerMemberV2Codec.MAX_VALUE_BYTES; + static final int MAX_METADATA_BYTES = 64 * 1024; + static final int MAX_TOTAL_HASH_BYTES = 16 * 1024 * 1024; + + private static final JsonFactory JSON_FACTORY = + JsonFactory.builder() + .streamReadConstraints( + StreamReadConstraints.builder() + .maxNestingDepth(8) + .maxStringLength(MAX_VALUE_BYTES) + .maxNumberLength(8) + .build()) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + private static final ObjectMapper JSON = + new ObjectMapper(JSON_FACTORY).enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + + private CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec() {} + + static PhysicalFieldSet expectedFields(CanonicalGameplayIssuerBootstrapPartitionWork work) { + Objects.requireNonNull(work, "work"); + validatePreparedWork(work); + CanonicalGameplayIssuerPartitionBuildPlan plan = work.buildPlan(); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); + BigInteger plannedAggregateCapacityCount = + BigInteger.valueOf( + plan.memberWorks().stream() + .filter(CanonicalGameplayIssuerPartitionBuildPlan.MemberWork::countsTowardCapacity) + .count()); + long partitionCount = work.memberOperations().size(); + long partitionCapacityCount = + work.memberOperations().stream() + .filter(CanonicalGameplayIssuerBootstrapMemberOperation::countsTowardCapacity) + .count(); + + byte[] metadata = encodeMetadata(work, plannedAggregateCapacityCount, partitionCapacityCount); + if (metadata.length == 0 || metadata.length > MAX_METADATA_BYTES) { + throw invalid("Issuer bootstrap partition metadata exceeds its resource limit"); + } + + Map fields = new LinkedHashMap<>(); + putUnique(fields, METADATA_FIELD, metadata); + Set reservations = new HashSet<>(); + Set bindings = new HashSet<>(); + int bindingCount = 0; + long totalBytes = METADATA_FIELD.getBytes(StandardCharsets.US_ASCII).length + metadata.length; + for (CanonicalGameplayIssuerBootstrapMemberOperation operation : work.memberOperations()) { + CanonicalGameplayIssuerMemberV2Value value = operation.expectedMemberValue(); + byte[] valueBytes = operation.exactMemberValueBytes(); + if (valueBytes.length == 0 || valueBytes.length > MAX_VALUE_BYTES) { + throw invalid("Exact SQL-issued v2 member exceeds its resource limit"); + } + CanonicalGameplayIssuerMemberV2Value decoded = CanonicalGameplayIssuerMemberV2Codec.decode(valueBytes); + if (!decoded.equals(value) + || !Arrays.equals(valueBytes, CanonicalGameplayIssuerMemberV2Codec.encode(decoded))) { + throw invalid("SQL-issued v2 member bytes do not round-trip exactly"); + } + UUID reservationId = value.reservation().reservationId(); + if (!reservations.add(reservationId)) throw invalid("Duplicate partition reservation identity"); + + byte[] bindingRefBytes = value.owner().bindingRef().bytes(); + if (bindingRefBytes.length == 0 || bindingRefBytes.length > MAX_BINDING_REF_BYTES) { + throw invalid("Canonical bindingRef exceeds its resource limit"); + } + CanonicalGameplayBindingRef exactBindingRef = + CanonicalGameplayBindingRef.fromExactBytes(bindingRefBytes); + String bindingField = strictUtf8(bindingRefBytes); + if (!Arrays.equals(bindingRefBytes, bindingField.getBytes(StandardCharsets.UTF_8)) + || !exactBindingRef.equals(value.owner().bindingRef()) + || !bindings.add(bindingField)) { + throw invalid("Binding field identity is malformed or duplicated"); + } + String capacityField = reservationField(reservationId); + if (operation.expectedBindingPresent()) { + putUnique(fields, bindingField, valueBytes); + bindingCount++; + } + putUnique(fields, capacityField, valueBytes); + totalBytes += + bindingField.getBytes(StandardCharsets.UTF_8).length + + capacityField.getBytes(StandardCharsets.US_ASCII).length + + (operation.expectedBindingPresent() ? valueBytes.length : 0L) + + valueBytes.length; + } + if (fields.size() > MAX_HASH_FIELDS || totalBytes > MAX_TOTAL_HASH_BYTES) { + throw invalid("Issuer bootstrap partition field set exceeds its bounded resource limits"); + } + if (BigInteger.valueOf(partitionCapacityCount) + .compareTo(intent.layoutDescriptor().partitionCapacity()) > 0) { + throw invalid("Prepared issuer partition exceeds its exact finite capacity"); + } + long aggregateCapacity = + plan.memberWorks().stream() + .filter(CanonicalGameplayIssuerPartitionBuildPlan.MemberWork::countsTowardCapacity) + .count(); + BigInteger aggregateBound = + intent.layoutDescriptor().partitionCount().multiply(intent.layoutDescriptor().partitionCapacity()); + if (BigInteger.valueOf(aggregateCapacity).compareTo(aggregateBound) > 0) { + throw invalid("Prepared issuer aggregate capacity exceeds its exact finite layout bound"); + } + return new PhysicalFieldSet( + fields, + metadata, + reservations.size(), + bindingCount, + Math.toIntExact(partitionCapacityCount), + BigInteger.valueOf(aggregateCapacity), + partitionCount); + } + + static byte[] encodeMetadata(CanonicalGameplayIssuerBootstrapPartitionWork work) { + PhysicalFieldSet fields = expectedFields(work); + return fields.metadataBytes(); + } + + static void requireExactMetadata(byte[] encoded, byte[] expected) { + Objects.requireNonNull(encoded, "encoded"); + Objects.requireNonNull(expected, "expected"); + if (encoded.length == 0 || encoded.length > MAX_METADATA_BYTES) { + throw invalid("Stored bootstrap metadata is outside the bounded format"); + } + try { + JsonNode decoded = JSON.readTree(strictUtf8(encoded)); + if (!(decoded instanceof ObjectNode root)) throw invalid("Bootstrap metadata must be an object"); + requireExactFields( + root, + Set.of( + "schemaVersion", + "issuerId", + "partitionId", + "layoutTag", + "bootstrap", + "build", + "layout", + "anchor", + "issuerControlEpoch", + "incarnation", + "plannedAggregateCapacityCount", + "plannedPartitionReservationCount", + "plannedPartitionCapacityCount"), + "bootstrap metadata"); + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + if (!Arrays.equals(canonical, encoded) || !Arrays.equals(encoded, expected)) { + throw invalid("Stored bootstrap metadata is noncanonical or belongs to different work"); + } + } catch (IOException failure) { + throw new IllegalArgumentException("Stored bootstrap metadata is invalid", failure); + } + } + + static String reservationField(UUID reservationId) { + Objects.requireNonNull(reservationId, "reservationId"); + String canonical = reservationId.toString(); + if (!UUID.fromString(canonical).toString().equals(canonical) + || reservationId.equals(new UUID(0L, 0L))) { + throw invalid("Reservation identity must be canonical and nonnil"); + } + return RESERVATION_FIELD_PREFIX + canonical; + } + + private static void validatePreparedWork(CanonicalGameplayIssuerBootstrapPartitionWork work) { + CanonicalGameplayIssuerPartitionBuildPlan plan = work.buildPlan(); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); + if (plan.state() != CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED + || !plan.blockers().isEmpty() + || work.memberOperations().size() > MAX_MEMBER_OPERATIONS + || work.memberOperations().size() + != plan.memberWorks().stream() + .filter(member -> member.plannedPartitionId().equals(work.partitionId())) + .count()) { + throw invalid("Physical partition requires the exact complete positive SQL preparation"); + } + Set reservationIds = new HashSet<>(); + Set memberOperationIds = new HashSet<>(); + Set issuedOperationIds = new HashSet<>(); + Set issuedOperationFences = new HashSet<>(); + Set issuedGenerations = new HashSet<>(); + for (int index = 0; index < plan.memberWorks().size(); index++) { + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork member = plan.memberWorks().get(index); + CanonicalGameplayBindingRef reference = + CanonicalGameplayBindingRef.fromExactBytes(member.bindingRef()); + if (member.workOrdinal() != index + || !member.plannedPartitionId().equals(reference.partitionId(intent.layoutDescriptor().partitionCount())) + || !reservationIds.add(member.reservationId()) + || !memberOperationIds.add(member.memberOperationId())) { + throw invalid("Prepared issuer plan has a duplicate or mis-mapped cohort member"); + } + } + for (CanonicalGameplayIssuerBootstrapMemberOperation operation : work.memberOperations()) { + CanonicalGameplayIssuerMemberV2Value value = operation.expectedMemberValue(); + if (operation.workOrdinal() >= plan.memberWorks().size()) { + throw invalid("SQL-issued member ordinal is outside the exact persisted plan"); + } + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork planned = + plan.memberWorks().get(Math.toIntExact(operation.workOrdinal())); + var reservation = value.reservation(); + var memberRef = value.owner().bindingRef(); + if (operation.status() + != CanonicalGameplayIssuerBootstrapMemberOperation.Status.PENDING_PHYSICAL_PROOF + || !operation.bootstrapOperationId().equals(intent.operationId()) + || !operation.bootstrapRequestId().equals(intent.requestId()) + || !operation.buildOperationId().equals(plan.buildOperationId()) + || !operation.buildPlanDigest().equals(plan.planDigest()) + || operation.reservationSourceRowOrdinal() != planned.reservationSourceRowOrdinal() + || !operation.reservationSourceRowDigest().equals(planned.reservationSourceRowDigest()) + || !operation.preparationOperationId().equals(planned.memberOperationId()) + || !operation.preparationFenceId().equals(planned.memberPreparationFenceId()) + || !reservation.reservationId().equals(planned.reservationId()) + || !reservation.transitionId().equals(planned.transitionId()) + || !reservation.reservationFence().equals(planned.reservationFence()) + || !reservation.lifecycle().name().equals(planned.reservationLifecycle()) + || !reservation.partitionId().equals(planned.plannedPartitionId()) + || !reservation.partitionId().equals(planned.originalPartitionId()) + || !reservation.issuerCoverageOperationId().equals(planned.originalIssuerCoverageOperationId()) + || !reservation.issuerCoverageOperationFence().equals(planned.originalIssuerCoverageOperationFence()) + || !reservation.coverageFence().equals(planned.originalCoverageFence()) + || !reservation.inventorySnapshotRevision().equals(planned.originalInventorySnapshotRevision()) + || !value.owner().issuerIndexLayoutVersion().equals(planned.originalLayoutVersion()) + || !value.owner().issuerIndexPartitionCount().equals(planned.originalPartitionCount()) + || !value.owner().issuerIndexPartitionCapacity().equals(planned.originalPartitionCapacity()) + || !Arrays.equals(memberRef.bytes(), planned.bindingRef()) + || !value.incarnation().equals(work.incarnation()) + || !value.anchor().issuerCoverageOperationId().equals(intent.operationId()) + || !value.anchor().operationFence().equals(intent.operationFence()) + || !value.anchor().coverageFence().equals(intent.coverageFence()) + || !value.anchor().issuerInventorySnapshotRevision().equals(intent.inventorySnapshotRevision()) + || !value.layoutDescriptor().descriptorDigest().equals(intent.layoutDescriptor().descriptorDigest()) + || !sameLayout(value.layoutDescriptor(), intent.layoutDescriptor()) + || !sameCheckpoint(value.sourceCheckpoint(), intent.sourceCheckpoint()) + || !value.issuerControlEpoch().equals(intent.controlEpoch()) + || !issuedOperationIds.add(operation.operationId()) + || !issuedOperationFences.add(operation.operationFence()) + || !issuedGenerations.add(operation.localMemberGeneration()) + || operation.countsTowardCapacity() + != (value.reservation().lifecycle() + != net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation.Lifecycle.RELEASED) + || operation.expectedBindingPresent() + != (planned.bindingSourceRowOrdinal() != null)) { + throw invalid("SQL-issued member differs from the complete frozen preparation tuple"); + } + } + } + + private static boolean sameLayout( + CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor actual, + CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor expected) { + return actual.issuerId().equals(expected.issuerId()) + && actual.layoutVersion().equals(expected.layoutVersion()) + && actual.partitionCount().equals(expected.partitionCount()) + && actual.partitionCapacity().equals(expected.partitionCapacity()) + && actual.mappingIdentity().equals(expected.mappingIdentity()) + && actual.descriptorDigest().equals(expected.descriptorDigest()) + && Arrays.equals(actual.exactDescriptorBytes(), expected.exactDescriptorBytes()); + } + + private static boolean sameCheckpoint( + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint actual, + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint expected) { + return actual.issuerId().equals(expected.issuerId()) + && actual.issuerAuthGeneration().equals(expected.issuerAuthGeneration()) + && actual.checkpointDigest().equals(expected.checkpointDigest()) + && Arrays.equals(actual.exactCheckpointBytes(), expected.exactCheckpointBytes()) + && Objects.equals(actual.latestIssuerEventDigest(), expected.latestIssuerEventDigest()) + && Arrays.equals(actual.latestIssuerEventBytes(), expected.latestIssuerEventBytes()); + } + + private static byte[] encodeMetadata( + CanonicalGameplayIssuerBootstrapPartitionWork work, + BigInteger plannedAggregateCapacityCount, + long plannedPartitionCapacityCount) { + var intent = work.buildPlan().bootstrapIntent(); + var layout = intent.layoutDescriptor(); + var source = intent.sourceCheckpoint(); + var incarnation = work.incarnation(); + var deployment = incarnation.targetDeploymentEvidence(); + try { + ObjectNode root = JSON.createObjectNode(); + root.put("schemaVersion", 1); + root.put("issuerId", intent.issuerId()); + root.put("partitionId", work.partitionId().toString()); + root.put("layoutTag", CanonicalGameplayIssuerRedisKeys.layoutTag(layout, work.partitionId())); + ObjectNode bootstrap = root.putObject("bootstrap"); + bootstrap.put("operationId", intent.operationId().toString()); + bootstrap.put("requestId", intent.requestId().toString()); + bootstrap.put("controlEpoch", intent.controlEpoch().toString()); + bootstrap.put("operationFence", intent.operationFence().toString()); + bootstrap.put("coverageFence", intent.coverageFence().toString()); + bootstrap.put("issuerInventorySnapshotRevision", intent.inventorySnapshotRevision().toString()); + bootstrap.put("cohortDigest", intent.cohortDigest()); + ObjectNode build = root.putObject("build"); + build.put("operationId", work.buildPlan().buildOperationId().toString()); + build.put("planDigest", work.buildPlan().planDigest()); + ObjectNode layoutObject = root.putObject("layout"); + layoutObject.put("version", layout.layoutVersion().toString()); + layoutObject.put("partitionCount", layout.partitionCount().toString()); + layoutObject.put("partitionCapacity", layout.partitionCapacity().toString()); + layoutObject.put("mappingIdentity", layout.mappingIdentity()); + layoutObject.put("descriptorBytes", Base64.getEncoder().encodeToString(layout.exactDescriptorBytes())); + layoutObject.put("descriptorDigest", layout.descriptorDigest()); + ObjectNode anchor = root.putObject("anchor"); + anchor.put("issuerCoverageOperationId", intent.operationId().toString()); + anchor.put("operationFence", intent.operationFence().toString()); + anchor.put("coverageFence", intent.coverageFence().toString()); + anchor.put("issuerInventorySnapshotRevision", intent.inventorySnapshotRevision().toString()); + anchor.put("issuerAuthGeneration", source.issuerAuthGeneration().toString()); + anchor.put("sourceCheckpointBytes", Base64.getEncoder().encodeToString(source.exactCheckpointBytes())); + anchor.put("sourceCheckpointDigest", source.checkpointDigest()); + putNullableBase64(anchor, "sourceEventBytes", source.latestIssuerEventBytes()); + putNullableText(anchor, "sourceEventDigest", source.latestIssuerEventDigest()); + root.put("issuerControlEpoch", intent.controlEpoch().toString()); + ObjectNode incarnationObject = root.putObject("incarnation"); + incarnationObject.put("attestorBinding", incarnation.attestorBinding()); + incarnationObject.put("acceptedAttestationDigest", incarnation.acceptedAttestationDigest()); + ObjectNode deploymentObject = incarnationObject.putObject("targetDeploymentEvidence"); + deploymentObject.put("deploymentIdentity", deployment.deploymentIdentity()); + deploymentObject.put("deploymentGeneration", deployment.deploymentGeneration()); + ArrayNode nodeSet = deploymentObject.putArray("canonicalNodeSet"); + deployment.canonicalNodeSet().forEach(nodeSet::add); + deploymentObject.put("redisBuildIdentity", deployment.redisBuildIdentity()); + deploymentObject.put("luaScriptRegistryVersion", deployment.luaScriptRegistryVersion()); + deploymentObject.put("luaScriptRegistryDigest", deployment.luaScriptRegistryDigest()); + deploymentObject.put("startupState", deployment.startupState()); + deploymentObject.put("bootGeneration", deployment.bootGeneration()); + deploymentObject.put("startupGeneration", deployment.startupGeneration()); + deploymentObject.put("storageGeneration", deployment.storageGeneration()); + deploymentObject.put("aofGeneration", deployment.aofGeneration()); + incarnationObject.put("coordOpsRoAclDigest", incarnation.coordOpsRoAclDigest()); + incarnationObject.put("coordRedisConfigObservedDigest", incarnation.coordRedisConfigObservedDigest()); + root.put("plannedAggregateCapacityCount", plannedAggregateCapacityCount.toString()); + root.put("plannedPartitionReservationCount", Integer.toString(work.memberOperations().size())); + root.put("plannedPartitionCapacityCount", Long.toString(plannedPartitionCapacityCount)); + byte[] encoded = + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + if (encoded.length > MAX_METADATA_BYTES) throw invalid("Bootstrap metadata exceeds its resource limit"); + return encoded; + } catch (IOException failure) { + throw new IllegalArgumentException("Could not encode canonical bootstrap metadata", failure); + } + } + + private static void putNullableBase64(ObjectNode object, String name, byte[] bytes) { + if (bytes == null) object.putNull(name); + else object.put(name, Base64.getEncoder().encodeToString(bytes)); + } + + private static void putNullableText(ObjectNode object, String name, String value) { + if (value == null) object.putNull(name); + else object.put(name, value); + } + + private static void putUnique(Map fields, String field, byte[] value) { + if (field == null || field.isEmpty() || field.getBytes(StandardCharsets.UTF_8).length > MAX_BINDING_REF_BYTES + || fields.putIfAbsent(field, value.clone()) != null) { + throw invalid("Issuer bootstrap field identity is reserved, oversized, or duplicated"); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw new IllegalArgumentException("Issuer bootstrap field is not canonical UTF-8", malformed); + } + } + + private static void requireExactFields(ObjectNode object, Set expected, String name) { + Set actual = new HashSet<>(); + object.fieldNames().forEachRemaining(actual::add); + if (!actual.equals(expected)) throw invalid(name + " has missing or unknown fields"); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + record PhysicalFieldSet( + Map fields, + byte[] metadataBytes, + int reservationCount, + int bindingCount, + int countedReservationCount, + BigInteger plannedAggregateCapacityCount, + long partitionReservationCount) { + PhysicalFieldSet { + Map copied = new LinkedHashMap<>(); + fields.forEach((field, value) -> copied.put(field, value.clone())); + fields = Map.copyOf(copied); + metadataBytes = metadataBytes.clone(); + } + + @Override + public Map fields() { + Map copied = new LinkedHashMap<>(); + fields.forEach((field, value) -> copied.put(field, value.clone())); + return Map.copyOf(copied); + } + + @Override + public byte[] metadataBytes() { + return metadataBytes.clone(); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwner.java new file mode 100644 index 0000000000..caff08a9d8 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwner.java @@ -0,0 +1,447 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisFuture; +import io.lettuce.core.RedisClient; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.async.RedisAsyncCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Projects one exact prepared bootstrap partition to its canonical single Coordination Redis hash. + * The result is physical readback evidence only; this owner does not install an anchor or admit. + */ +public final class CanonicalGameplayIssuerBootstrapPartitionRedisOwner { + private static final String PRINCIPAL = "gamesession_coord_app"; + private static final String KEY_PREFIX = "session:game:index:issuer:"; + private static final int MAX_SCRIPT_BYTES = 128 * 1024; + private static final long COMMAND_TIMEOUT_MILLIS = 5_000; + private static final List EXPECTED_KEYS = + List.of( + new RedisScriptDescriptor.KeySpec( + "issuerPartition", + KEY_PREFIX, + RedisScriptDescriptor.HashTagDeclaration.REQUIRED)); + private static final List EXPECTED_ARGUMENTS = + List.of( + new RedisScriptDescriptor.ArgumentSpec("issuerId"), + new RedisScriptDescriptor.ArgumentSpec("partitionId"), + new RedisScriptDescriptor.ArgumentSpec("partitionCount"), + new RedisScriptDescriptor.ArgumentSpec("partitionCapacity"), + new RedisScriptDescriptor.ArgumentSpec("exactBootstrapMetadata"), + new RedisScriptDescriptor.ArgumentSpec("memberOperationCount"), + new RedisScriptDescriptor.ArgumentSpec("repeatedBindingRefMemberCapacityFieldBindingPresence")); + private static final List EXPECTED_OUTCOMES = + List.of( + new RedisScriptDescriptor.OutcomeSpec( + "PARTITION_BUILT", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "PARTITION_REPLAY", + RedisScriptDescriptor.OutcomeCategory.REPLAY, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "TYPE_TTL_OR_FIELDSET_REFUSED", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "INVALID_ARGUMENTS_OR_CAPACITY", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING)); + + private final RedisClient redisClient; + private final RedisScriptCatalog catalog; + private final CurrentIssuerStateSource currentStateSource; + + /** The Redis client, manual owner contribution catalog, and protected local source are explicit. */ + public CanonicalGameplayIssuerBootstrapPartitionRedisOwner( + RedisClient redisClient, + RedisScriptCatalog catalog, + CurrentIssuerStateSource currentStateSource) { + this.redisClient = Objects.requireNonNull(redisClient, "Configured Redis client is required"); + this.catalog = Objects.requireNonNull(catalog, "Manual Redis script catalog is required"); + this.currentStateSource = + Objects.requireNonNull(currentStateSource, "Fresh current issuer source is required"); + } + + /** + * Writes or exactly replays the complete physical field set, then reads it back on a separate + * connection. Fresh controlled current source checks bracket the remote phase; source or Redis + * uncertainty returns no readback capability. + */ + public Readback buildAndRead(CanonicalGameplayIssuerBootstrapPartitionWork work) { + Objects.requireNonNull(work, "Prepared issuer partition work is required"); + try { + requireNoAmbientTransaction(); + var physical = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.expectedFields(work); + requireFreshCurrentState(work); + RedisScriptDescriptor descriptor = requireDescriptor(); + byte[] script = scriptSource(descriptor); + byte[] key = exactPartitionKey(work); + byte[][] arguments = scriptArguments(work, physical); + long mutationResult = writeOneKey(script, key, arguments); + if (mutationResult != 1L && mutationResult != 2L) throw unavailable(); + PhysicalReadback observed = readExactPhysicalState(key, physical); + requireFreshCurrentState(work); + return new Readback(work, observed, physical.plannedAggregateCapacityCount()); + } catch (RuntimeException failure) { + if (failure instanceof IllegalStateException state + && state.getMessage() != null + && state.getMessage().contains("partition projection is unavailable")) { + throw state; + } + throw unavailable(failure); + } + } + + private long writeOneKey( + byte[] script, byte[] key, byte[][] arguments) { + requireNoAmbientTransaction(); + try (StatefulRedisConnection connection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(connection); + requirePrincipal(await(commands.aclWhoami())); + String loadedSha = await(commands.scriptLoad(script)); + if (!digest("SHA-1", script).equals(loadedSha)) throw unavailable(); + Long reply = + await( + commands.evalsha( + loadedSha, + ScriptOutputType.INTEGER, + new byte[][] {key}, + arguments)); + if (reply == null) throw unavailable(); + return reply; + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private PhysicalReadback readExactPhysicalState( + byte[] key, CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.PhysicalFieldSet expected) { + requireNoAmbientTransaction(); + try (StatefulRedisConnection connection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(connection); + requirePrincipal(await(commands.aclWhoami())); + if (!"hash".equals(await(commands.type(key))) + || !Long.valueOf(-1L).equals(await(commands.pttl(key)))) { + throw unavailable(); + } + Long length = await(commands.hlen(key)); + if (length == null + || length < 0 + || length > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_HASH_FIELDS) { + throw unavailable(); + } + Map raw = await(commands.hgetall(key)); + if (raw == null || raw.size() != length) throw unavailable(); + long totalBytes = 0; + Map actual = new HashMap<>(); + for (Map.Entry entry : raw.entrySet()) { + byte[] field = Objects.requireNonNull(entry.getKey(), "Redis field"); + byte[] value = Objects.requireNonNull(entry.getValue(), "Redis value"); + totalBytes += (long) field.length + value.length; + if (totalBytes > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_TOTAL_HASH_BYTES) { + throw unavailable(); + } + String encodedField = Base64.getEncoder().encodeToString(field); + if (actual.putIfAbsent(encodedField, value.clone()) != null) throw unavailable(); + } + Map expectedFields = expected.fields(); + if (actual.size() != expectedFields.size()) throw unavailable(); + for (Map.Entry entry : expectedFields.entrySet()) { + byte[] redisField = entry.getKey().getBytes(StandardCharsets.UTF_8); + byte[] observed = actual.get(Base64.getEncoder().encodeToString(redisField)); + if (!Arrays.equals(entry.getValue(), observed)) throw unavailable(); + } + byte[] metadata = actual.get( + Base64.getEncoder() + .encodeToString( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.METADATA_FIELD + .getBytes(StandardCharsets.US_ASCII))); + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.requireExactMetadata( + metadata, expected.metadataBytes()); + + int capacityCount = 0; + int bindingCount = 0; + for (Map.Entry entry : expectedFields.entrySet()) { + String field = entry.getKey(); + if (field.startsWith( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.RESERVATION_FIELD_PREFIX)) { + CanonicalGameplayIssuerMemberV2Value decoded = + CanonicalGameplayIssuerMemberV2Codec.decode(actual.get( + Base64.getEncoder().encodeToString(field.getBytes(StandardCharsets.US_ASCII)))); + if (!decoded.equals(CanonicalGameplayIssuerMemberV2Codec.decode(entry.getValue()))) { + throw unavailable(); + } + if (decoded.reservation().lifecycle() + != net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation.Lifecycle.RELEASED) { + capacityCount++; + } + } else if (!field.equals( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.METADATA_FIELD)) { + CanonicalGameplayIssuerMemberV2Codec.decode(actual.get( + Base64.getEncoder().encodeToString(field.getBytes(StandardCharsets.UTF_8)))); + bindingCount++; + } + } + if (capacityCount != expected.countedReservationCount() + || bindingCount != expected.bindingCount() + || expected.reservationCount() != expected.partitionReservationCount()) { + throw unavailable(); + } + return new PhysicalReadback(expectedFields.size(), capacityCount, bindingCount); + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private void requireFreshCurrentState(CanonicalGameplayIssuerBootstrapPartitionWork work) { + requireNoAmbientTransaction(); + CurrentIssuerState current = currentStateSource.readFreshCurrentState(); + requireNoAmbientTransaction(); + if (current == null + || !sameCheckpoint( + current.accountCheckpoint(), work.buildPlan().bootstrapIntent().sourceCheckpoint()) + || !current.incarnation().equals(work.incarnation())) { + throw unavailable(); + } + } + + private RedisScriptDescriptor requireDescriptor() { + try { + RedisScriptDescriptor descriptor = + catalog.require(CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.SCRIPT_ID); + if (!CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.SCRIPT_ID + .equals(descriptor.scriptId()) + || !CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.RESOURCE_PATH + .equals(descriptor.resourcePath()) + || !"game-session-service".equals(descriptor.owner()) + || !PRINCIPAL.equals(descriptor.principal()) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || !EXPECTED_KEYS.equals(descriptor.keys()) + || !EXPECTED_ARGUMENTS.equals(descriptor.arguments()) + || descriptor.category() != RedisScriptDescriptor.ScriptCategory.SESSION_ISSUER_INDEX + || !EXPECTED_OUTCOMES.equals(descriptor.outcomes()) + || descriptor.resetSensitivity() != RedisScriptDescriptor.ResetSensitivity.CLUSTER + || descriptor.lossClass() + != RedisScriptDescriptor.LossClass.EMPTY_REDIS_COLD_START_OR_RESET + || descriptor.compatibilityLevel() + != RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET + || !descriptor + .supportedCoexistence() + .equals(List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "v2"))) + || descriptor.legacyPayloadShape() != null) { + throw unavailable(); + } + return descriptor; + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private static byte[] scriptSource(RedisScriptDescriptor descriptor) { + try (InputStream input = + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.class + .getClassLoader() + .getResourceAsStream(descriptor.resourcePath())) { + if (input == null) throw unavailable(); + byte[] bytes = input.readNBytes(MAX_SCRIPT_BYTES + 1); + if (bytes.length == 0 + || bytes.length > MAX_SCRIPT_BYTES + || !descriptor.sha256().equals(digest("SHA-256", bytes))) { + throw unavailable(); + } + return bytes; + } catch (IOException | RuntimeException failure) { + throw unavailable(failure); + } + } + + private static byte[] exactPartitionKey(CanonicalGameplayIssuerBootstrapPartitionWork work) { + String key = + CanonicalGameplayIssuerRedisKeys.forPartition( + work.buildPlan().bootstrapIntent().layoutDescriptor(), work.partitionId()); + if (!key.startsWith(KEY_PREFIX) || key.length() > 512) throw unavailable(); + return key.getBytes(StandardCharsets.US_ASCII); + } + + private static byte[][] scriptArguments( + CanonicalGameplayIssuerBootstrapPartitionWork work, + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.PhysicalFieldSet physical) { + var intent = work.buildPlan().bootstrapIntent(); + byte[][] arguments = new byte[6 + work.memberOperations().size() * 4][]; + arguments[0] = ascii(intent.issuerId()); + arguments[1] = ascii(work.partitionId().toString()); + arguments[2] = ascii(intent.layoutDescriptor().partitionCount().toString()); + arguments[3] = ascii(intent.layoutDescriptor().partitionCapacity().toString()); + arguments[4] = physical.metadataBytes(); + arguments[5] = ascii(Integer.toString(work.memberOperations().size())); + int position = 6; + for (CanonicalGameplayIssuerBootstrapMemberOperation operation : work.memberOperations()) { + CanonicalGameplayIssuerMemberV2Value value = operation.expectedMemberValue(); + arguments[position++] = value.owner().bindingRef().bytes(); + byte[] exactValue = operation.exactMemberValueBytes(); + arguments[position++] = exactValue; + arguments[position++] = + ascii( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + value.reservation().reservationId())); + arguments[position++] = ascii(operation.expectedBindingPresent() ? "1" : "0"); + } + return arguments; + } + + private static boolean sameCheckpoint( + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint current, + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint expected) { + return current != null + && expected != null + && current.issuerId().equals(expected.issuerId()) + && current.issuerAuthGeneration().equals(expected.issuerAuthGeneration()) + && Arrays.equals(current.exactCheckpointBytes(), expected.exactCheckpointBytes()) + && current.checkpointDigest().equals(expected.checkpointDigest()) + && Arrays.equals(current.latestIssuerEventBytes(), expected.latestIssuerEventBytes()) + && Objects.equals(current.latestIssuerEventDigest(), expected.latestIssuerEventDigest()); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static RedisAsyncCommands requireCommands( + StatefulRedisConnection connection) { + if (connection == null || !connection.isOpen()) throw unavailable(); + return connection.async(); + } + + private static void requirePrincipal(String principal) { + if (!PRINCIPAL.equals(principal)) throw unavailable(); + } + + private static T await(RedisFuture future) { + try { + return future.get(COMMAND_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + future.cancel(true); + throw unavailable(interrupted); + } catch (ExecutionException | TimeoutException | RuntimeException failure) { + future.cancel(true); + throw unavailable(failure); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + } + + private static String digest(String algorithm, byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(bytes)); + } catch (Exception failure) { + throw unavailable(failure); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Issuer bootstrap partition projection is unavailable"); + } + + private static IllegalStateException unavailable(Throwable cause) { + return new IllegalStateException("Issuer bootstrap partition projection is unavailable", cause); + } + + /** Fresh, trusted local read collaborator. No default implementation derives authority from work. */ + @FunctionalInterface + public interface CurrentIssuerStateSource { + CurrentIssuerState readFreshCurrentState(); + } + + /** One current exact Account checkpoint and stable incarnation observation from the collaborator. */ + public record CurrentIssuerState( + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint accountCheckpoint, + CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation) { + public CurrentIssuerState { + Objects.requireNonNull(accountCheckpoint, "accountCheckpoint"); + Objects.requireNonNull(incarnation, "incarnation"); + } + } + + private record PhysicalReadback(int fieldCount, int countedReservationCount, int bindingCount) {} + + /** Exact physical partition readback; it carries no global aggregate, acknowledgement, or OPEN authority. */ + public static final class Readback { + private final CanonicalGameplayIssuerBootstrapPartitionWork work; + private final int physicalFieldCount; + private final int physicalReservationCount; + private final int physicalBindingCount; + private final int physicalCountedCapacityCount; + private final BigInteger plannedAggregateCapacityCount; + + private Readback( + CanonicalGameplayIssuerBootstrapPartitionWork work, + PhysicalReadback observed, + BigInteger plannedAggregateCapacityCount) { + this.work = Objects.requireNonNull(work, "work"); + this.physicalFieldCount = observed.fieldCount(); + this.physicalReservationCount = work.memberOperations().size(); + this.physicalBindingCount = observed.bindingCount(); + this.physicalCountedCapacityCount = observed.countedReservationCount(); + this.plannedAggregateCapacityCount = Objects.requireNonNull(plannedAggregateCapacityCount); + if (observed.fieldCount() != 1 + physicalReservationCount + physicalBindingCount + || BigInteger.valueOf(observed.countedReservationCount()) + .compareTo( + work.buildPlan().bootstrapIntent().layoutDescriptor().partitionCapacity()) + > 0) { + throw unavailable(); + } + } + + public int physicalFieldCount() { + return physicalFieldCount; + } + + public int physicalPartitionReservationCount() { + return physicalReservationCount; + } + + public int physicalBindingCount() { + return physicalBindingCount; + } + + public int physicalCountedCapacityCount() { + return physicalCountedCapacityCount; + } + + /** Frozen complete-plan capacity count, distinct from this one partition's physical count. */ + public BigInteger plannedAggregateCapacityCount() { + return plannedAggregateCapacityCount; + } + + public CanonicalGameplayIssuerBootstrapPartitionWork work() { + return work; + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionWork.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionWork.java new file mode 100644 index 0000000000..050b7d6c55 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionWork.java @@ -0,0 +1,98 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.util.List; +import java.util.Objects; + +/** + * Read-only output of the local SQL owner for one exact partition in a prepared initial bootstrap. + * + *

Its members are SQL-issued operations still pending physical proof. An empty partition has an + * empty member list and does not receive a fabricated member generation. + */ +final class CanonicalGameplayIssuerBootstrapPartitionWork { + private final CanonicalGameplayIssuerPartitionBuildPlan buildPlan; + private final BigInteger partitionId; + private final List memberOperations; + private final CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation; + + CanonicalGameplayIssuerBootstrapPartitionWork( + CanonicalGameplayIssuerPartitionBuildPlan buildPlan, + BigInteger partitionId, + List memberOperations, + CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation) { + this.buildPlan = Objects.requireNonNull(buildPlan, "buildPlan"); + if (buildPlan.state() != CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED) { + throw new IllegalArgumentException("Partition work requires the exact PREPARED build plan"); + } + this.partitionId = Objects.requireNonNull(partitionId, "partitionId"); + if (partitionId.signum() < 0 + || partitionId.compareTo(buildPlan.bootstrapIntent().layoutDescriptor().partitionCount()) + >= 0) { + throw new IllegalArgumentException("partitionId is outside the exact bootstrap layout"); + } + this.memberOperations = + List.copyOf(Objects.requireNonNull(memberOperations, "memberOperations")); + if (this.memberOperations.stream().anyMatch(Objects::isNull)) { + throw new IllegalArgumentException("memberOperations must not contain null"); + } + this.incarnation = Objects.requireNonNull(incarnation, "incarnation"); + List expectedWork = + buildPlan.memberWorks().stream() + .filter(work -> work.plannedPartitionId().equals(partitionId)) + .toList(); + if (expectedWork.size() != this.memberOperations.size()) { + throw new IllegalArgumentException( + "Partition work must contain every exact prepared member operation for its partition"); + } + for (int index = 0; index < expectedWork.size(); index++) { + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work = expectedWork.get(index); + CanonicalGameplayIssuerBootstrapMemberOperation operation = this.memberOperations.get(index); + CanonicalGameplayIssuerMemberV2Value value = operation.expectedMemberValue(); + if (operation.status() + != CanonicalGameplayIssuerBootstrapMemberOperation.Status.PENDING_PHYSICAL_PROOF + || operation.workOrdinal() != work.workOrdinal() + || !operation.buildOperationId().equals(buildPlan.buildOperationId()) + || !operation.buildPlanDigest().equals(buildPlan.planDigest()) + || !operation.preparationOperationId().equals(work.memberOperationId()) + || !operation.preparationFenceId().equals(work.memberPreparationFenceId()) + || operation.reservationSourceRowOrdinal() != work.reservationSourceRowOrdinal() + || !operation.reservationSourceRowDigest().equals(work.reservationSourceRowDigest()) + || !operation.bootstrapOperationId().equals(buildPlan.bootstrapIntent().operationId()) + || !operation.bootstrapRequestId().equals(buildPlan.bootstrapIntent().requestId()) + || !value.reservation().reservationId().equals(work.reservationId()) + || !value.reservation().transitionId().equals(work.transitionId()) + || !value.reservation().partitionId().equals(partitionId) + || !value + .anchor() + .issuerCoverageOperationId() + .equals(buildPlan.bootstrapIntent().operationId()) + || !value.anchor().operationFence().equals(buildPlan.bootstrapIntent().operationFence()) + || !value.anchor().coverageFence().equals(buildPlan.bootstrapIntent().coverageFence()) + || !value + .anchor() + .issuerInventorySnapshotRevision() + .equals(buildPlan.bootstrapIntent().inventorySnapshotRevision()) + || !incarnation.equals(value.incarnation())) { + throw new IllegalArgumentException( + "Partition operation differs from its exact planned source or incarnation"); + } + } + } + + CanonicalGameplayIssuerPartitionBuildPlan buildPlan() { + return buildPlan; + } + + BigInteger partitionId() { + return partitionId; + } + + List memberOperations() { + return memberOperations; + } + + CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation() { + return incarnation; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java index e0a6aaa612..5bc8b97bc4 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java @@ -25,8 +25,11 @@ import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.IssuerEvent; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationDisposition; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.impl.DSL; @@ -219,6 +222,169 @@ private CanonicalGameplayIssuerPartitionBuildPlan prepareInTransaction( "saved issuer partition build plan must be readable")); } + /** + * Reads one exact work item from an already persisted complete PREPARED plan using the caller's + * transaction. This deliberately repeats the same locks and exact source/plan checks as plan + * preparation; it does not open a nested transaction or create a missing plan. + */ + PreparedMemberWork readPreparedMemberWorkInTransaction( + DSLContext transaction, + UUID bootstrapOperationId, + UUID bootstrapRequestId, + long workOrdinal) { + return readPreparedMemberWorkFromVerifiedPlan( + readPreparedPlanInTransaction(transaction, bootstrapOperationId, bootstrapRequestId), + workOrdinal); + } + + /** Loads and locks the already persisted complete PREPARED plan and its current sources. */ + CanonicalGameplayIssuerPartitionBuildPlan readPreparedPlanInTransaction( + DSLContext transaction, UUID bootstrapOperationId, UUID bootstrapRequestId) { + requireNonNil(bootstrapOperationId, "bootstrapOperationId"); + requireNonNil(bootstrapRequestId, "bootstrapRequestId"); + if (bootstrapOperationId.equals(bootstrapRequestId)) { + throw conflict("Bootstrap operation and request identities must be distinct"); + } + BigInteger currentInventoryRevision = lockInventoryRevision(transaction); + Record control = lockControl(transaction, ISSUER); + if (control == null) { + Record orphan = + transaction.fetchOne( + "SELECT operation_id FROM " + BOOTSTRAP_INTENT + " WHERE issuer_id = ?", ISSUER); + if (orphan != null) { + throw conflict("Pending issuer-bootstrap intent lost its positive current control row"); + } + throw conflict("Exact pending issuer-bootstrap control row is missing"); + } + Record intentRow = lockIntent(transaction, bootstrapOperationId); + if (intentRow == null) throw conflict("Exact pending issuer-bootstrap operation is missing"); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = + loadAndRequireCurrentIntent( + transaction, + control, + intentRow, + bootstrapOperationId, + bootstrapRequestId, + currentInventoryRevision); + List currentRows = + captureCurrentCohort(transaction, intent.inventorySnapshotRevision()); + requireSameCohort(intent.cohortRows(), currentRows); + DerivedPlan derived = derivePlan(intent, currentRows); + Record buildPlanRow = + transaction.fetchOne( + "SELECT * FROM " + BUILD_PLAN + " WHERE bootstrap_operation_id = ? FOR UPDATE", + bootstrapOperationId); + if (buildPlanRow == null) { + throw conflict("Exact complete issuer partition build plan is missing"); + } + CanonicalGameplayIssuerPartitionBuildPlan plan = + loadAndRequireExactPlan(transaction, intent, currentRows, derived, buildPlanRow); + if (plan.state() != CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED) { + throw conflict("Blocked issuer partition build plan cannot issue member operations"); + } + return plan; + } + + /** Extracts typed source only from a plan returned by {@link #readPreparedPlanInTransaction}. */ + PreparedMemberWork readPreparedMemberWorkFromVerifiedPlan( + CanonicalGameplayIssuerPartitionBuildPlan plan, long workOrdinal) { + Objects.requireNonNull(plan, "plan"); + if (plan.state() != CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED) { + throw conflict("Blocked issuer partition build plan cannot issue member operations"); + } + if (workOrdinal < 0) throw conflict("Member work ordinal must not be negative"); + if (workOrdinal >= plan.memberWorks().size()) { + throw conflict("Member work ordinal is outside the exact prepared plan"); + } + CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work = + plan.memberWorks().get(Math.toIntExact(workOrdinal)); + int sourceIndex = Math.toIntExact(work.reservationSourceRowOrdinal()); + if (sourceIndex >= intent.cohortRows().size()) { + throw conflict("Prepared member work lost its exact reservation cohort row"); + } + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow sourceRow = + intent.cohortRows().get(sourceIndex); + if (sourceRow.kind() != CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.RESERVATION + || !sourceRow.sourceRowDigest().equals(work.reservationSourceRowDigest())) { + throw conflict("Prepared member work no longer links to its exact original reservation"); + } + ReservationSource source = parseReservation(sourceRow); + CanonicalGameplayBindingIdentity owner = + new CanonicalGameplayBindingIdentity( + UUID.fromString(source.accountId()), + UUID.fromString(source.tenantId()), + UUID.fromString(source.namespaceId()), + UUID.fromString(source.characterId()), + source.playableStateScope(), + UUID.fromString(source.gameInstanceId()), + source.runtimeGameInstanceId().longValueExact(), + source.sessionId(), + UUID.fromString(source.regionId()), + source.regionEpoch(), + source.issuerId(), + source.issuerAuthGeneration(), + source.layoutVersion(), + source.partitionCount(), + source.partitionCapacity()); + CanonicalIssuerPartitionReservation reservation = + new CanonicalIssuerPartitionReservation( + source.reservationId(), + owner, + source.bindingGeneration(), + source.transitionId(), + source.partitionId(), + CanonicalIssuerPartitionReservation.Lifecycle.valueOf(source.lifecycle()), + source.reservationFence(), + source.coverageOperationId(), + source.coverageOperationFence(), + source.coverageFence(), + source.inventorySnapshotRevision(), + sourceRow.sourceInventoryRevision()); + if (!work.reservationId().equals(reservation.reservationId()) + || !Arrays.equals(work.bindingRef(), owner.bindingRef().bytes()) + || !work.transitionId().equals(reservation.transitionId()) + || !work.reservationLifecycle().equals(reservation.lifecycle().name()) + || !work.reservationFence().equals(reservation.reservationFence()) + || !work.originalPartitionId().equals(reservation.partitionId()) + || !work.originalLayoutVersion().equals(reservation.owner().issuerIndexLayoutVersion()) + || !work.originalPartitionCount().equals(reservation.owner().issuerIndexPartitionCount()) + || !work.originalPartitionCapacity() + .equals(reservation.owner().issuerIndexPartitionCapacity()) + || !work.originalIssuerCoverageOperationId().equals(reservation.issuerCoverageOperationId()) + || !work.originalIssuerCoverageOperationFence() + .equals(reservation.issuerCoverageOperationFence()) + || !work.originalCoverageFence().equals(reservation.coverageFence()) + || !work.originalInventorySnapshotRevision() + .equals(reservation.inventorySnapshotRevision())) { + throw conflict("Prepared member work differs from its exact typed original reservation"); + } + CanonicalGameplayBindingInventoryEntry.Lifecycle bindingLifecycle = null; + if (work.bindingSourceRowOrdinal() != null) { + int bindingIndex = Math.toIntExact(work.bindingSourceRowOrdinal()); + if (bindingIndex >= intent.cohortRows().size()) { + throw conflict("Prepared member work lost its exact binding cohort row"); + } + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow bindingRow = + intent.cohortRows().get(bindingIndex); + if (bindingRow.kind() != CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.BINDING + || !bindingRow.sourceRowDigest().equals(work.bindingSourceRowDigest())) { + throw conflict("Prepared member work no longer links to its exact binding cohort row"); + } + BindingSource binding = parseBinding(bindingRow); + if (!binding.matches(source)) { + throw conflict("Prepared member work binding differs from the exact original reservation"); + } + try { + bindingLifecycle = + CanonicalGameplayBindingInventoryEntry.Lifecycle.valueOf(binding.lifecycle()); + } catch (RuntimeException malformed) { + throw conflict("Prepared member work has an unsupported binding lifecycle"); + } + } + return new PreparedMemberWork(plan, work, reservation, bindingLifecycle); + } + private static CanonicalGameplayIssuerLayoutBootstrapIntent loadAndRequireCurrentIntent( DSLContext transaction, Record control, @@ -792,6 +958,12 @@ private static BindingSource parseBinding( if (!ISSUER.equals(issuerId)) { throw conflict("Binding source does not use the exact Account issuer"); } + String lifecycle = text(json, "lifecycle"); + try { + CanonicalGameplayBindingInventoryEntry.Lifecycle.valueOf(lifecycle); + } catch (RuntimeException malformed) { + throw conflict("Binding source uses an unsupported lifecycle"); + } return new BindingSource( row.rowOrdinal(), row.sourceRowDigest(), @@ -814,6 +986,7 @@ private static BindingSource parseBinding( integer(json, "issuer_index_partition_count"), integer(json, "issuer_index_partition_capacity"), integer(json, "issuer_partition_id"), + lifecycle, integer(json, "binding_generation")); } @@ -1773,6 +1946,7 @@ private record BindingSource( BigInteger partitionCount, BigInteger partitionCapacity, BigInteger partitionId, + String lifecycle, BigInteger bindingGeneration) { BindingSource { bindingRef = bindingRef.clone(); @@ -1806,4 +1980,16 @@ boolean matches(ReservationSource reservation) { && partitionId.equals(reservation.partitionId()); } } + + record PreparedMemberWork( + CanonicalGameplayIssuerPartitionBuildPlan plan, + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work, + CanonicalIssuerPartitionReservation originalReservation, + CanonicalGameplayBindingInventoryEntry.Lifecycle bindingLifecycle) { + PreparedMemberWork { + Objects.requireNonNull(plan, "plan"); + Objects.requireNonNull(work, "work"); + Objects.requireNonNull(originalReservation, "originalReservation"); + } + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.java new file mode 100644 index 0000000000..7b3eecd8c2 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.java @@ -0,0 +1,52 @@ +package net.firedevops.firemud.gamesession.service; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Collection; +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Passive manual-catalog contribution for the local issuer-bootstrap partition builder. */ +public final class CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution + implements RedisScriptContribution { + public static final String SCRIPT_ID = "game-session.issuer-bootstrap-partition-build.v1"; + public static final String RESOURCE_PATH = + "redis/lua/game-session-issuer-bootstrap-partition-build.lua"; + private static final String DESCRIPTOR_PATH = + "/redis/scripts/game-session-issuer-bootstrap-partition-build.json"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @Override + public String ownerId() { + return "game-session-service"; + } + + @Override + public Collection descriptors() { + try (InputStream input = getClass().getResourceAsStream(DESCRIPTOR_PATH)) { + if (input == null) throw unavailable(); + byte[] bytes = input.readNBytes(16 * 1024 + 1); + if (bytes.length == 0 || bytes.length > 16 * 1024) throw unavailable(); + RedisScriptDescriptor descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); + if (!ownerId().equals(descriptor.owner()) || !SCRIPT_ID.equals(descriptor.scriptId())) { + throw unavailable(); + } + return List.of(descriptor); + } catch (IOException | RuntimeException failure) { + throw unavailable(); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Issuer bootstrap partition Redis descriptor is unavailable"); + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V1032__canonical_issuer_bootstrap_member_operation.sql b/services/game-session-service/src/main/resources/db/migration/V1032__canonical_issuer_bootstrap_member_operation.sql new file mode 100644 index 0000000000..3e4198b460 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1032__canonical_issuer_bootstrap_member_operation.sql @@ -0,0 +1,254 @@ +-- A persisted local SQL-issued operation for one exact work item in the current complete +-- PREPARED initial-bootstrap plan. This is still pending physical proof: it installs no pointer, +-- records no Redis result, and issues no issuer-wide coverage acknowledgement. +-- The local numeric generation is an operation identity, not global coverage evidence. + +ALTER TABLE game_session_canonical_issuer_partition_build_plan + ADD CONSTRAINT uq_gs_issuer_partition_build_plan_digest_link + UNIQUE (build_operation_id, bootstrap_operation_id, bootstrap_request_id, issuer_id, plan_digest); + +ALTER TABLE game_session_canonical_issuer_layout_bootstrap_intent + ADD CONSTRAINT uq_gs_issuer_bootstrap_intent_request_link + UNIQUE (operation_id, issuer_id, request_id); + +ALTER TABLE game_session_canonical_issuer_partition_build_cohort_row + ADD CONSTRAINT uq_gs_issuer_partition_build_cohort_digest_link + UNIQUE (build_operation_id, source_row_ordinal, source_row_digest); + +ALTER TABLE game_session_canonical_issuer_partition_build_member_work + ADD CONSTRAINT uq_gs_issuer_partition_build_member_operation_link UNIQUE ( + build_operation_id, bootstrap_operation_id, issuer_id, work_ordinal, + member_operation_id, member_preparation_fence_id, + reservation_source_row_ordinal, reservation_source_row_digest, + reservation_id, + original_issuer_coverage_operation_id, original_issuer_coverage_operation_fence, + original_coverage_fence, original_inventory_snapshot_revision, + planned_anchor_operation_id, planned_anchor_operation_fence, + planned_anchor_coverage_fence, planned_anchor_inventory_snapshot_revision); + +ALTER TABLE game_session_canonical_issuer_partition_build_member_work + ADD CONSTRAINT uq_gs_issuer_partition_build_binding_link UNIQUE ( + build_operation_id, bootstrap_operation_id, issuer_id, work_ordinal, + binding_source_row_ordinal, binding_source_row_digest); + +CREATE TABLE game_session_canonical_issuer_bootstrap_member_op_counter ( + issuer_id character varying(64) NOT NULL, + last_issued_operation_fence numeric NOT NULL, + last_issued_member_generation numeric NOT NULL, + counter_version bigint NOT NULL, + CONSTRAINT pk_gs_issuer_bootstrap_member_op_counter PRIMARY KEY (issuer_id), + CONSTRAINT chk_gs_issuer_bootstrap_member_op_counter CHECK ( + issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND counter_version >= 0 + AND last_issued_operation_fence >= 0 + AND last_issued_member_generation >= 0 + AND last_issued_operation_fence = floor(last_issued_operation_fence) + AND last_issued_member_generation = floor(last_issued_member_generation) + AND length(CAST(last_issued_operation_fence AS varchar)) <= 256 + AND length(CAST(last_issued_member_generation AS varchar)) <= 256 + AND ((counter_version = 0 + AND last_issued_operation_fence = 0 + AND last_issued_member_generation = 0) + OR (counter_version > 0 + AND last_issued_operation_fence > 0 + AND last_issued_member_generation = last_issued_operation_fence + 1)) + ) +); + +CREATE TABLE game_session_canonical_issuer_bootstrap_member_operation ( + member_operation_id uuid NOT NULL, + issuer_id character varying(64) NOT NULL, + bootstrap_operation_id uuid NOT NULL, + bootstrap_request_id uuid NOT NULL, + build_operation_id uuid NOT NULL, + build_plan_digest character varying(71) NOT NULL, + work_ordinal bigint NOT NULL, + preparation_operation_id uuid NOT NULL, + preparation_fence_id uuid NOT NULL, + reservation_source_row_ordinal bigint NOT NULL, + reservation_source_row_digest character varying(71) NOT NULL, + binding_source_row_ordinal bigint, + binding_source_row_digest character varying(71), + binding_lifecycle character varying(24), + reservation_id uuid NOT NULL, + reservation_lifecycle character varying(24) NOT NULL, + expected_binding_present boolean NOT NULL, + counts_toward_capacity boolean NOT NULL, + original_issuer_coverage_operation_id uuid NOT NULL, + original_issuer_coverage_operation_fence numeric NOT NULL, + original_coverage_fence numeric NOT NULL, + original_inventory_snapshot_revision numeric NOT NULL, + bootstrap_anchor_operation_id uuid NOT NULL, + bootstrap_anchor_operation_fence numeric NOT NULL, + bootstrap_anchor_coverage_fence numeric NOT NULL, + bootstrap_anchor_inventory_snapshot_revision numeric NOT NULL, + operation_fence numeric NOT NULL, + local_member_generation numeric NOT NULL, + member_status character varying(32) NOT NULL, + member_schema_version smallint NOT NULL, + member_value_bytes bytea NOT NULL, + member_value_digest character varying(71) NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_issuer_bootstrap_member_operation PRIMARY KEY (member_operation_id), + CONSTRAINT uq_gs_issuer_bootstrap_member_operation_work + UNIQUE (issuer_id, bootstrap_operation_id, work_ordinal), + CONSTRAINT uq_gs_issuer_bootstrap_member_operation_fence + UNIQUE (issuer_id, operation_fence), + CONSTRAINT uq_gs_issuer_bootstrap_member_operation_generation + UNIQUE (issuer_id, local_member_generation), + CONSTRAINT fk_gs_issuer_bootstrap_member_operation_intent + FOREIGN KEY (bootstrap_operation_id, issuer_id) + REFERENCES game_session_canonical_issuer_layout_bootstrap_intent (operation_id, issuer_id), + CONSTRAINT fk_gs_issuer_bootstrap_member_operation_request + FOREIGN KEY (bootstrap_operation_id, issuer_id, bootstrap_request_id) + REFERENCES game_session_canonical_issuer_layout_bootstrap_intent (operation_id, issuer_id, request_id), + CONSTRAINT fk_gs_issuer_bootstrap_member_operation_plan + FOREIGN KEY (build_operation_id, bootstrap_operation_id, bootstrap_request_id, + issuer_id, build_plan_digest) + REFERENCES game_session_canonical_issuer_partition_build_plan + (build_operation_id, bootstrap_operation_id, bootstrap_request_id, issuer_id, plan_digest), + CONSTRAINT fk_gs_issuer_bootstrap_member_operation_work + FOREIGN KEY ( + build_operation_id, bootstrap_operation_id, issuer_id, work_ordinal, + preparation_operation_id, preparation_fence_id, + reservation_source_row_ordinal, reservation_source_row_digest, reservation_id, + original_issuer_coverage_operation_id, original_issuer_coverage_operation_fence, + original_coverage_fence, original_inventory_snapshot_revision, + bootstrap_anchor_operation_id, bootstrap_anchor_operation_fence, + bootstrap_anchor_coverage_fence, bootstrap_anchor_inventory_snapshot_revision) + REFERENCES game_session_canonical_issuer_partition_build_member_work ( + build_operation_id, bootstrap_operation_id, issuer_id, work_ordinal, + member_operation_id, member_preparation_fence_id, + reservation_source_row_ordinal, reservation_source_row_digest, reservation_id, + original_issuer_coverage_operation_id, original_issuer_coverage_operation_fence, + original_coverage_fence, original_inventory_snapshot_revision, + planned_anchor_operation_id, planned_anchor_operation_fence, + planned_anchor_coverage_fence, planned_anchor_inventory_snapshot_revision), + CONSTRAINT fk_gs_issuer_bootstrap_member_operation_binding_work + FOREIGN KEY (build_operation_id, bootstrap_operation_id, issuer_id, work_ordinal, + binding_source_row_ordinal, binding_source_row_digest) + REFERENCES game_session_canonical_issuer_partition_build_member_work ( + build_operation_id, bootstrap_operation_id, issuer_id, work_ordinal, + binding_source_row_ordinal, binding_source_row_digest), + CONSTRAINT fk_gs_issuer_bootstrap_member_operation_source + FOREIGN KEY (build_operation_id, reservation_source_row_ordinal, + reservation_source_row_digest) + REFERENCES game_session_canonical_issuer_partition_build_cohort_row + (build_operation_id, source_row_ordinal, source_row_digest), + CONSTRAINT fk_gs_issuer_bootstrap_member_operation_binding_source + FOREIGN KEY (build_operation_id, binding_source_row_ordinal, + binding_source_row_digest) + REFERENCES game_session_canonical_issuer_partition_build_cohort_row + (build_operation_id, source_row_ordinal, source_row_digest), + CONSTRAINT fk_gs_issuer_bootstrap_member_operation_anchor + FOREIGN KEY (build_operation_id, bootstrap_operation_id, issuer_id, + bootstrap_anchor_operation_fence, bootstrap_anchor_coverage_fence, + bootstrap_anchor_inventory_snapshot_revision) + REFERENCES game_session_canonical_issuer_partition_build_plan + (build_operation_id, bootstrap_operation_id, issuer_id, + bootstrap_operation_fence, bootstrap_coverage_fence, + issuer_inventory_snapshot_revision), + CONSTRAINT chk_gs_issuer_bootstrap_member_operation CHECK ( + member_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND bootstrap_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND bootstrap_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND build_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND preparation_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND preparation_fence_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND reservation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND original_issuer_coverage_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND bootstrap_anchor_operation_id = bootstrap_operation_id + AND member_operation_id <> bootstrap_operation_id + AND member_operation_id <> bootstrap_request_id + AND member_operation_id <> build_operation_id + AND member_operation_id <> preparation_operation_id + AND member_operation_id <> preparation_fence_id + AND reservation_lifecycle IN ('RESERVED', 'BOUND', 'RELEASE_PENDING', 'RELEASED') + AND ((binding_source_row_ordinal IS NULL + AND binding_source_row_digest IS NULL + AND binding_lifecycle IS NULL + AND expected_binding_present = FALSE + AND reservation_lifecycle IN ('RESERVED', 'RELEASED')) + OR (binding_source_row_ordinal IS NOT NULL + AND binding_source_row_ordinal >= 0 + AND binding_source_row_digest IS NOT NULL + AND binding_source_row_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((binding_lifecycle = 'CANDIDATE_PREPARED' + AND reservation_lifecycle = 'RESERVED' + AND expected_binding_present = FALSE) + OR (binding_lifecycle = 'PROVISIONAL' + AND reservation_lifecycle = 'RESERVED' + AND expected_binding_present = TRUE) + OR (binding_lifecycle = 'ACTIVE' + AND reservation_lifecycle IN ('BOUND', 'RELEASE_PENDING') + AND expected_binding_present = TRUE) + OR (binding_lifecycle = 'TERMINAL' + AND reservation_lifecycle = 'RELEASED' + AND expected_binding_present = FALSE)))) + AND operation_fence > 0 + AND local_member_generation > operation_fence + AND original_issuer_coverage_operation_fence > 0 + AND original_coverage_fence > 0 + AND original_inventory_snapshot_revision > 0 + AND bootstrap_anchor_operation_fence > 0 + AND bootstrap_anchor_coverage_fence > 0 + AND bootstrap_anchor_inventory_snapshot_revision > 0 + AND member_status = 'PENDING_PHYSICAL_PROOF' + AND member_schema_version = 2 + AND counts_toward_capacity = (reservation_lifecycle <> 'RELEASED') + AND octet_length(member_value_bytes) BETWEEN 1 AND 65536 + AND build_plan_digest ~ '^sha256:[0-9a-f]{64}$' + AND reservation_source_row_digest ~ '^sha256:[0-9a-f]{64}$' + AND member_value_digest ~ '^sha256:[0-9a-f]{64}$' + AND work_ordinal >= 0 + AND reservation_source_row_ordinal >= 0) +); + +-- jOOQ's H2 DDL parser does not model PostgreSQL trigger functions. The deployed PostgreSQL +-- migration retains these immutable-artifact and monotonic compare-and-set guards. +-- [jooq ignore start] +CREATE FUNCTION game_session_reject_issuer_bootstrap_member_operation_change() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'issuer bootstrap member operation artifacts are immutable' + USING ERRCODE = 'check_violation'; +END; +$$; + +CREATE TRIGGER trg_gs_issuer_bootstrap_member_operation_immutable + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_bootstrap_member_operation + FOR EACH ROW EXECUTE FUNCTION game_session_reject_issuer_bootstrap_member_operation_change(); +CREATE TRIGGER trg_gs_issuer_bootstrap_member_operation_no_truncate + BEFORE TRUNCATE ON game_session_canonical_issuer_bootstrap_member_operation + FOR EACH STATEMENT EXECUTE FUNCTION game_session_reject_issuer_bootstrap_member_operation_change(); + +CREATE FUNCTION game_session_guard_issuer_bootstrap_member_operation_counter() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'issuer bootstrap member operation counters cannot be deleted' + USING ERRCODE = 'check_violation'; + END IF; + IF NEW.issuer_id IS DISTINCT FROM OLD.issuer_id + OR NEW.counter_version <> OLD.counter_version + 1 + OR NEW.last_issued_operation_fence <= OLD.last_issued_operation_fence + OR NEW.last_issued_member_generation <= OLD.last_issued_member_generation + OR NEW.last_issued_member_generation <> NEW.last_issued_operation_fence + 1 THEN + RAISE EXCEPTION 'issuer bootstrap member operation counter CAS must advance both local domains' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_gs_issuer_bootstrap_member_operation_counter_guard + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_bootstrap_member_op_counter + FOR EACH ROW EXECUTE FUNCTION game_session_guard_issuer_bootstrap_member_operation_counter(); +CREATE TRIGGER trg_gs_issuer_bootstrap_member_operation_counter_no_truncate + BEFORE TRUNCATE ON game_session_canonical_issuer_bootstrap_member_op_counter + FOR EACH STATEMENT EXECUTE FUNCTION game_session_reject_issuer_bootstrap_member_operation_change(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-bootstrap-partition-build.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-bootstrap-partition-build.lua new file mode 100644 index 0000000000..c24d1a83af --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-bootstrap-partition-build.lua @@ -0,0 +1,315 @@ +-- Build/retain one exact partition from complete positive SQL-issued bootstrap work. +-- KEYS[1] is the only issuer partition hash. ARGV[7..] repeats +-- bindingRef bytes, full schema-v2 value, reservation capacity field, expected binding presence. +local keyPrefix = 'session:game:index:issuer:' +local metadataField = '!issuer-partition-bootstrap/v1' +local capacityPrefix = '!issuer-reservation-capacity/v1:' +local maxDecimalBytes = 256 +local maxMemberOperations = 256 +local maxBindingRefBytes = 6144 +local maxMemberValueBytes = 65536 +local maxMetadataBytes = 65536 +local maxHashFields = 513 +local maxHashBytes = 16777216 + +local function uuid(value) + return type(value) == 'string' and #value == 36 + and string.match(value, '^%x%x%x%x%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x$') + and value == string.lower(value) + and value ~= '00000000-0000-0000-0000-000000000000' +end + +local function positive(value) + return type(value) == 'string' and #value > 0 and #value <= maxDecimalBytes + and string.match(value, '^[1-9][0-9]*$') ~= nil +end + +local function nonnegative(value) + return value == '0' or positive(value) +end + +local function digest(value) + return type(value) == 'string' and #value == 71 + and string.match(value, '^sha256:[0-9a-f]+$') ~= nil +end + +local function greaterDecimal(left, right) + if #left ~= #right then return #left > #right end + return left > right +end + +local function readSegment(bytes, offset) + local start = offset + while offset <= #bytes do + local char = string.byte(bytes, offset) + if char < 48 or char > 57 then break end + offset = offset + 1 + end + if offset == start or offset > #bytes or string.byte(bytes, offset) ~= 58 then return nil end + if offset - start > 1 and string.byte(bytes, start) == 48 then return nil end + local lengthText = string.sub(bytes, start, offset - 1) + if #lengthText > 5 then return nil end + local length = tonumber(lengthText) + if not length or length > maxBindingRefBytes or offset + length > #bytes then return nil end + local valueStart = offset + 1 + local valueEnd = offset + length + return string.sub(bytes, valueStart, valueEnd), valueEnd + 1 +end + +local function canonicalBindingRef(bytes, member) + if type(bytes) ~= 'string' or #bytes == 0 or #bytes > maxBindingRefBytes then return false end + local domain, offset = readSegment(bytes, 1) + if domain ~= 'bindingRef/v1' or not offset then return false end + local tenant, afterTenant = readSegment(bytes, offset) + if not tenant or not afterTenant then return false end + local instance, afterInstance = readSegment(bytes, afterTenant) + if not instance or not afterInstance then return false end + local session, afterSession = readSegment(bytes, afterInstance) + if not tenant or not instance or not session or not afterSession or afterSession ~= #bytes + 1 then + return false + end + return uuid(tenant) and uuid(instance) and uuid(session) + and tenant == member.tenantId and instance == member.gameInstanceId and session == member.sessionId +end + +local function sameIncarnation(left, right) + if type(left) ~= 'table' or type(right) ~= 'table' + or left.attestorBinding ~= right.attestorBinding + or left.acceptedAttestationDigest ~= right.acceptedAttestationDigest + or left.coordOpsRoAclDigest ~= right.coordOpsRoAclDigest + or left.coordRedisConfigObservedDigest ~= right.coordRedisConfigObservedDigest then return false end + local a = left.targetDeploymentEvidence + local b = right.targetDeploymentEvidence + if type(a) ~= 'table' or type(b) ~= 'table' + or a.deploymentIdentity ~= b.deploymentIdentity + or a.deploymentGeneration ~= b.deploymentGeneration + or a.redisBuildIdentity ~= b.redisBuildIdentity + or a.luaScriptRegistryVersion ~= b.luaScriptRegistryVersion + or a.luaScriptRegistryDigest ~= b.luaScriptRegistryDigest + or a.startupState ~= b.startupState + or a.bootGeneration ~= b.bootGeneration + or a.startupGeneration ~= b.startupGeneration + or a.storageGeneration ~= b.storageGeneration + or a.aofGeneration ~= b.aofGeneration + or type(a.canonicalNodeSet) ~= 'table' + or type(b.canonicalNodeSet) ~= 'table' + or #a.canonicalNodeSet ~= #b.canonicalNodeSet then return false end + for index = 1, #a.canonicalNodeSet do + if a.canonicalNodeSet[index] ~= b.canonicalNodeSet[index] then return false end + end + return true +end + +local function metadataMatchesMember(metadata, member, partitionId) + local layout = metadata.layout + local anchor = metadata.anchor + return type(layout) == 'table' and type(anchor) == 'table' + and member.schemaVersion == 2 + and member.issuerId == metadata.issuerId + and member.issuerId == ARGV[1] + and member.issuerAuthGeneration == anchor.issuerAuthGeneration + and member.issuerControlEpoch == metadata.issuerControlEpoch + and member.issuerIndexLayoutVersion == layout.version + and member.layout.partitionCount == layout.partitionCount + and member.layout.partitionCapacity == layout.partitionCapacity + and member.layout.mappingIdentity == layout.mappingIdentity + and member.layout.descriptorBytes == layout.descriptorBytes + and member.layout.descriptorDigest == layout.descriptorDigest + and member.reservation.partitionId == partitionId + and member.anchor.issuerCoverageOperationId == anchor.issuerCoverageOperationId + and member.anchor.operationFence == anchor.operationFence + and member.anchor.coverageFence == anchor.coverageFence + and member.anchor.issuerInventorySnapshotRevision == anchor.issuerInventorySnapshotRevision + and member.anchor.sourceCheckpointBytes == anchor.sourceCheckpointBytes + and member.anchor.sourceCheckpointDigest == anchor.sourceCheckpointDigest + and member.anchor.sourceEventBytes == anchor.sourceEventBytes + and member.anchor.sourceEventDigest == anchor.sourceEventDigest + and member.anchor.issuerCoverageOperationId == metadata.bootstrap.operationId + and member.anchor.operationFence == metadata.bootstrap.operationFence + and member.anchor.coverageFence == metadata.bootstrap.coverageFence + and member.anchor.issuerInventorySnapshotRevision == metadata.bootstrap.issuerInventorySnapshotRevision + and sameIncarnation(member.incarnation, metadata.incarnation) +end + +if #KEYS ~= 1 or #ARGV < 6 then return -2 end +if type(KEYS[1]) ~= 'string' or #KEYS[1] > 512 or string.sub(KEYS[1], 1, #keyPrefix) ~= keyPrefix then + return -2 +end + +local issuerId = ARGV[1] +local partitionId = ARGV[2] +local partitionCount = ARGV[3] +local partitionCapacity = ARGV[4] +local metadataBytes = ARGV[5] +local memberCountText = ARGV[6] +if issuerId ~= 'firemud-account-service' or not nonnegative(partitionId) + or not positive(partitionCount) or not positive(partitionCapacity) + or not nonnegative(memberCountText) then return -2 end +local memberCount = tonumber(memberCountText) +if not memberCount or memberCount > maxMemberOperations + or #ARGV ~= 6 + memberCount * 4 then return -2 end +if #metadataBytes == 0 or #metadataBytes > maxMetadataBytes then return -2 end + +local metadataOk, metadata = pcall(cjson.decode, metadataBytes) +if not metadataOk or type(metadata) ~= 'table' or metadata.schemaVersion ~= 1 + or metadata.issuerId ~= issuerId or metadata.partitionId ~= partitionId + or type(metadata.layoutTag) ~= 'string' or #metadata.layoutTag ~= 70 + or not string.match(metadata.layoutTag, '^il%-v1%-%x+$') + or type(metadata.bootstrap) ~= 'table' or type(metadata.build) ~= 'table' + or type(metadata.layout) ~= 'table' or type(metadata.anchor) ~= 'table' + or type(metadata.incarnation) ~= 'table' + or metadata.layout.partitionCount ~= partitionCount + or metadata.layout.partitionCapacity ~= partitionCapacity + or not positive(metadata.layout.version) + or metadata.layout.mappingIdentity ~= 'bindingRef/v1;sha256-u256-mod/v1' + or metadata.anchor.issuerCoverageOperationId ~= metadata.bootstrap.operationId + or metadata.anchor.operationFence ~= metadata.bootstrap.operationFence + or metadata.anchor.coverageFence ~= metadata.bootstrap.coverageFence + or metadata.anchor.issuerInventorySnapshotRevision ~= metadata.bootstrap.issuerInventorySnapshotRevision + or metadata.issuerControlEpoch ~= metadata.bootstrap.controlEpoch + or not uuid(metadata.bootstrap.operationId) or not uuid(metadata.bootstrap.requestId) + or not uuid(metadata.build.operationId) + or not positive(metadata.bootstrap.operationFence) + or not positive(metadata.bootstrap.coverageFence) + or metadata.bootstrap.operationFence == metadata.bootstrap.coverageFence + or not positive(metadata.bootstrap.issuerInventorySnapshotRevision) + or not positive(metadata.issuerControlEpoch) + or not digest(metadata.bootstrap.cohortDigest) + or not digest(metadata.build.planDigest) + or not nonnegative(metadata.plannedAggregateCapacityCount) + or not nonnegative(metadata.plannedPartitionReservationCount) + or not nonnegative(metadata.plannedPartitionCapacityCount) + or metadata.plannedPartitionReservationCount ~= memberCountText then return -2 end + +local expectedKey = + keyPrefix .. '{' .. metadata.layoutTag .. '}:' .. issuerId .. ':' .. partitionId +if KEYS[1] ~= expectedKey then return -2 end +if not greaterDecimal(partitionCount, partitionId) then return -2 end + +local expected = {} +local expectedCount = 0 +local totalExpectedBytes = #metadataField + #metadataBytes +local function putExpected(field, value) + if type(field) ~= 'string' or #field == 0 or expected[field] ~= nil then return false end + expected[field] = value + expectedCount = expectedCount + 1 + totalExpectedBytes = totalExpectedBytes + #field + #value + return totalExpectedBytes <= maxHashBytes and expectedCount <= maxHashFields +end +if not putExpected(metadataField, metadataBytes) then return -2 end + +local seenReservations = {} +local seenBindings = {} +local seenMemberOperations = {} +local actualCapacityCount = 0 +local actualBindingCount = 0 +local totalArgumentBytes = #metadataBytes +for index = 0, memberCount - 1 do + local offset = 7 + index * 4 + local bindingRef = ARGV[offset] + local memberBytes = ARGV[offset + 1] + local capacityField = ARGV[offset + 2] + local bindingPresent = ARGV[offset + 3] + if bindingPresent ~= '0' and bindingPresent ~= '1' then return -2 end + if type(memberBytes) ~= 'string' or #memberBytes == 0 or #memberBytes > maxMemberValueBytes then return -2 end + totalArgumentBytes = totalArgumentBytes + #bindingRef + #memberBytes + #capacityField + if totalArgumentBytes > maxHashBytes then return -2 end + local decodedOk, member = pcall(cjson.decode, memberBytes) + if not decodedOk or type(member) ~= 'table' or type(member.reservation) ~= 'table' + or type(member.layout) ~= 'table' or type(member.anchor) ~= 'table' + or type(member.incarnation) ~= 'table' + or not metadataMatchesMember(metadata, member, partitionId) + or not canonicalBindingRef(bindingRef, member) then return -2 end + local lifecycle = member.reservation.lifecycle + if lifecycle ~= 'RESERVED' and lifecycle ~= 'BOUND' + and lifecycle ~= 'RELEASE_PENDING' and lifecycle ~= 'RELEASED' then return -2 end + local reservationId = member.reservation.reservationId + if not uuid(reservationId) or seenReservations[reservationId] + or not uuid(member.reservation.transitionId) + or not uuid(member.reservation.reservationFence) + or not uuid(member.reservation.issuerCoverageOperationId) + or not positive(member.reservation.issuerCoverageOperationFence) + or not positive(member.reservation.coverageFence) + or not positive(member.reservation.inventorySnapshotRevision) + or not positive(member.reservation.inventoryRevision) + or not uuid(member.accountId) or not uuid(member.tenantId) + or not uuid(member.playableStateNamespaceId) or not uuid(member.characterId) + or not uuid(member.gameInstanceId) or not uuid(member.regionId) + or not positive(member.bindingGeneration) or not positive(member.issuerAuthGeneration) + or not positive(member.issuerIndexLayoutVersion) or not positive(member.regionEpoch) + or not positive(member.issuerControlEpoch) + or not positive(member.runtimeGameInstanceId) + or not digest(member.layout.descriptorDigest) + or not digest(member.anchor.sourceCheckpointDigest) + or (member.anchor.sourceEventDigest ~= cjson.null and not digest(member.anchor.sourceEventDigest)) then + return -2 + end + seenReservations[reservationId] = true + if seenBindings[bindingRef] then return -2 end + seenBindings[bindingRef] = true + if member.reservation.bindingRef ~= bindingRef + or member.reservation.reservationId == nil + or member.reservation.partitionId ~= partitionId + or member.reservation.issuerCoverageOperationId == nil + or member.reservation.issuerCoverageOperationFence == nil + or member.reservation.coverageFence == nil + or member.reservation.inventorySnapshotRevision == nil + or member.memberOperation == nil + or not uuid(member.memberOperation.operationId) + or seenMemberOperations[member.memberOperation.operationId] + or not positive(member.memberOperation.operationFence) + or not positive(member.memberOperation.coverageGeneration) then return -2 end + seenMemberOperations[member.memberOperation.operationId] = true + local expectedCapacityField = capacityPrefix .. reservationId + if capacityField ~= expectedCapacityField + or not putExpected(capacityField, memberBytes) then return -2 end + if lifecycle ~= 'RELEASED' then actualCapacityCount = actualCapacityCount + 1 end + if bindingPresent == '1' then + if string.sub(bindingRef, 1, 1) == '!' or not putExpected(bindingRef, memberBytes) then return -2 end + actualBindingCount = actualBindingCount + 1 + end +end + +if greaterDecimal(tostring(actualCapacityCount), partitionCapacity) + or tostring(actualCapacityCount) ~= metadata.plannedPartitionCapacityCount + or actualBindingCount > memberCount then return -2 end +if memberCount > 0 and metadata.plannedPartitionCapacityCount ~= tostring(actualCapacityCount) then return -2 end + +-- Validate TYPE, persistence and every current field before the first mutation. +local kind = redis.call('TYPE', KEYS[1]).ok +local ttl = redis.call('PTTL', KEYS[1]) +if kind == 'none' then + if ttl ~= -2 then return -1 end +elseif kind == 'hash' then + if ttl ~= -1 then return -1 end +else + return -1 +end +local currentLength = redis.call('HLEN', KEYS[1]) +if currentLength < 0 or currentLength > maxHashFields or currentLength > expectedCount then return -1 end +local current = redis.call('HGETALL', KEYS[1]) +if #current ~= currentLength * 2 then return -1 end +local totalCurrentBytes = 0 +local present = {} +for index = 1, #current, 2 do + local field = current[index] + local value = current[index + 1] + totalCurrentBytes = totalCurrentBytes + #field + #value + if totalCurrentBytes > maxHashBytes or expected[field] == nil or expected[field] ~= value then + return -1 + end + if present[field] then return -1 end + present[field] = true +end + +if currentLength == expectedCount then return 2 end +local missing = {} +for field, value in pairs(expected) do + if not present[field] then + missing[#missing + 1] = field + missing[#missing + 1] = value + end +end +if #missing == 0 or #missing % 2 ~= 0 then return -1 end +redis.call('HSET', KEYS[1], unpack(missing)) +return 1 diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-bootstrap-partition-build.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-bootstrap-partition-build.json new file mode 100644 index 0000000000..07c21f9b6b --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-bootstrap-partition-build.json @@ -0,0 +1,39 @@ +{ + "scriptId": "game-session.issuer-bootstrap-partition-build.v1", + "resourcePath": "redis/lua/game-session-issuer-bootstrap-partition-build.lua", + "sha256": "526383d905b93ef2a8026f6b4ac659b601c40257b874652b8c3b89b637b84531", + "owner": "game-session-service", + "principal": "gamesession_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "issuerPartition", + "ownedPrefix": "session:game:index:issuer:", + "hashTagDeclaration": "REQUIRED" + } + ], + "arguments": [ + {"name": "issuerId"}, + {"name": "partitionId"}, + {"name": "partitionCount"}, + {"name": "partitionCapacity"}, + {"name": "exactBootstrapMetadata"}, + {"name": "memberOperationCount"}, + {"name": "repeatedBindingRefMemberCapacityFieldBindingPresence"} + ], + "category": "SESSION_ISSUER_INDEX", + "outcomes": [ + {"code": "PARTITION_BUILT", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "PARTITION_REPLAY", "category": "REPLAY", "effect": "NON_MUTATING"}, + {"code": "TYPE_TTL_OR_FIELDSET_REFUSED", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, + {"code": "INVALID_ARGUMENTS_OR_CAPACITY", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} + ], + "resetSensitivity": "CLUSTER", + "lossClass": "EMPTY_REDIS_COLD_START_OR_RESET", + "tailLossBehavior": "This local one-partition bootstrap projection is reset-sensitive physical evidence only. The SQL owner must supply a complete positive prepared cohort and the exact member-operation set for this partition. Missing, partial, malformed, legacy, foreign, or mismatched state remains unqualified unless the exact complete field set is written and read back under fresh controlled current-source and incarnation checks. This single partition readback is not complete issuer coverage, an installed anchor, an acknowledgement, barrier OPEN, or admission authority.", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [ + {"callerVersion": "v1", "payloadVersion": "v2"} + ], + "legacyPayloadShape": null +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java new file mode 100644 index 0000000000..f9aa136284 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java @@ -0,0 +1,952 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.util.EnumSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; +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.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL proof for the SQL-issued pending initial-bootstrap member-operation boundary. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final UUID ACCOUNT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID NAMESPACE_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID GAME_INSTANCE_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID REGION_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID CHARACTER_ID = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final BigInteger LAYOUT_VERSION = BigInteger.valueOf(3); + private static final BigInteger PARTITION_COUNT = BigInteger.valueOf(16); + private static final BigInteger PARTITION_CAPACITY = BigInteger.valueOf(32); + private static final List RETAINED_TABLES = + List.of( + "game_session_canonical_binding_inventory_clock", + "game_session_canonical_binding_legacy_disposition", + "game_session_canonical_gameplay_binding_inventory", + "game_session_canonical_issuer_partition_reservation", + "game_session_canonical_issuer_layout_bootstrap_intent", + "game_session_canonical_issuer_layout_bootstrap_control", + "game_session_canonical_issuer_layout_bootstrap_cohort_row", + "game_session_canonical_issuer_partition_build_plan", + "game_session_canonical_issuer_partition_build_cohort_row", + "game_session_canonical_issuer_partition_build_member_work", + "game_session_canonical_issuer_partition_build_blocker"); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void actualPreparedPlanIssuesExactPendingV2OperationAndPreservesV1031RowsAcrossRestart() + throws Exception { + Fixture fixture = + pendingFixture( + "gs_bootstrap_member_issue_", PARTITION_CAPACITY, LAYOUT_VERSION, false, true); + try { + assertThat(fixture.plan().state()) + .isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED); + Map> retainedBefore = rowSnapshots(fixture.testSchema().dsl()); + List historyBefore = historySnapshot(fixture.testSchema().dsl()); + migrateRemaining(fixture.testSchema()); + + assertThat(rowSnapshots(fixture.testSchema().dsl())).isEqualTo(retainedBefore); + List historyAfterMigration = historySnapshot(fixture.testSchema().dsl()); + assertThat(historyAfterMigration).hasSize(historyBefore.size() + 1); + assertThat(historyAfterMigration.subList(0, historyBefore.size())) + .containsExactlyElementsOf(historyBefore); + assertThat( + fixture + .testSchema() + .dsl() + .fetchSingle("SELECT script FROM flyway_schema_history WHERE version = '1032'") + .get(0, String.class)) + .isEqualTo("V1032__canonical_issuer_bootstrap_member_operation.sql"); + assertThat( + fixture + .testSchema() + .dsl() + .fetchSingle( + "SELECT count(*) FROM game_session_canonical_issuer_bootstrap_member_operation") + .get(0, Long.class)) + .isZero(); + + var owner = + new CanonicalGameplayIssuerBootstrapMemberOperationRepository(fixture.testSchema().dsl()); + var operation = + owner.beginOrResumePendingPhysicalProof( + fixture.intent().operationId(), + fixture.requestId(), + 0, + fixture.currentAccountCheckpoint(), + stableIncarnation("stable-a")); + var value = operation.expectedMemberValue(); + assertThat(operation.status()) + .isEqualTo(CanonicalGameplayIssuerBootstrapMemberOperation.Status.PENDING_PHYSICAL_PROOF); + assertThat(operation.operationId()) + .isNotEqualTo(fixture.plan().memberWorks().getFirst().memberOperationId()) + .isNotEqualTo(fixture.plan().memberWorks().getFirst().memberPreparationFenceId()); + assertThat(operation.operationFence()).isGreaterThan(value.anchor().coverageFence()); + assertThat(operation.localMemberGeneration()).isGreaterThan(operation.operationFence()); + assertThat(value.memberOperation().coverageGeneration()) + .isEqualTo(operation.localMemberGeneration()); + assertThat(value.anchor().issuerCoverageOperationId()) + .isEqualTo(fixture.intent().operationId()); + assertThat(value.anchor().operationFence()).isEqualTo(fixture.intent().operationFence()); + assertThat(value.anchor().coverageFence()).isEqualTo(fixture.intent().coverageFence()); + assertThat(value.anchor().issuerInventorySnapshotRevision()) + .isEqualTo(fixture.intent().inventorySnapshotRevision()); + assertThat(value.reservation().issuerCoverageOperationId()) + .isNotEqualTo(value.anchor().issuerCoverageOperationId()); + assertThat(value.reservation().issuerCoverageOperationFence()) + .isEqualTo(BigInteger.valueOf(17)); + assertThat(value.reservation().coverageFence()).isEqualTo(BigInteger.valueOf(19)); + var originalReservationRow = + fixture + .testSchema() + .dsl() + .fetchOne( + "SELECT issuer_coverage_operation_id, issuer_coverage_operation_fence," + + " coverage_fence, inventory_snapshot_revision" + + " FROM game_session_canonical_issuer_partition_reservation" + + " WHERE reservation_id = ?", + fixture.preparedBinding().issuerReservationId()); + assertThat(originalReservationRow).isNotNull(); + assertThat(value.reservation().issuerCoverageOperationId()) + .isEqualTo(originalReservationRow.get("issuer_coverage_operation_id", UUID.class)); + assertThat(value.reservation().issuerCoverageOperationFence()) + .isEqualTo( + originalReservationRow + .get("issuer_coverage_operation_fence", BigDecimal.class) + .toBigIntegerExact()); + assertThat(value.reservation().coverageFence()) + .isEqualTo( + originalReservationRow.get("coverage_fence", BigDecimal.class).toBigIntegerExact()); + assertThat(value.reservation().inventorySnapshotRevision()) + .isEqualTo( + originalReservationRow + .get("inventory_snapshot_revision", BigDecimal.class) + .toBigIntegerExact()); + assertThat(operation.bindingLifecycle()) + .isEqualTo(CanonicalGameplayBindingInventoryEntry.Lifecycle.CANDIDATE_PREPARED); + assertThat(operation.expectedBindingPresent()).isFalse(); + assertThat(operation.countsTowardCapacity()).isTrue(); + assertThat(CanonicalGameplayIssuerMemberV2Codec.decode(operation.exactMemberValueBytes())) + .isEqualTo(value); + + var restarted = + new CanonicalGameplayIssuerBootstrapMemberOperationRepository(fixture.testSchema().dsl()) + .beginOrResumePendingPhysicalProof( + fixture.intent().operationId(), + fixture.requestId(), + 0, + fixture.currentAccountCheckpoint(), + stableIncarnation("stable-a")); + assertThat(restarted.operationId()).isEqualTo(operation.operationId()); + assertThat(restarted.operationFence()).isEqualTo(operation.operationFence()); + assertThat(restarted.localMemberGeneration()).isEqualTo(operation.localMemberGeneration()); + assertThat(restarted.exactMemberValueBytes()) + .containsExactly(operation.exactMemberValueBytes()); + assertThat(rowSnapshots(fixture.testSchema().dsl())).isEqualTo(retainedBefore); + + assertThatThrownBy( + () -> + owner.beginOrResumePendingPhysicalProof( + fixture.intent().operationId(), + fixture.requestId(), + 0, + fixture.currentAccountCheckpoint(), + stableIncarnation("changed-incarnation"))) + .isInstanceOf(IllegalStateException.class); + assertThat( + rowImages( + fixture.testSchema().dsl(), + "game_session_canonical_issuer_bootstrap_member_operation")) + .hasSize(1); + + assertThatThrownBy( + () -> + fixture + .testSchema() + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_bootstrap_member_operation" + + " SET member_status = 'PHYSICAL_PROOF_COMPLETE' WHERE member_operation_id = ?", + operation.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + fixture + .testSchema() + .dsl() + .execute( + "DELETE FROM game_session_canonical_issuer_bootstrap_member_operation" + + " WHERE member_operation_id = ?", + operation.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + fixture + .testSchema() + .dsl() + .execute("TRUNCATE game_session_canonical_issuer_bootstrap_member_operation")) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + fixture + .testSchema() + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_bootstrap_member_op_counter" + + " SET last_issued_operation_fence = last_issued_operation_fence + 1" + + " WHERE issuer_id = ?", + ISSUER)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + fixture + .testSchema() + .dsl() + .execute( + "DELETE FROM game_session_canonical_issuer_bootstrap_member_op_counter" + + " WHERE issuer_id = ?", + ISSUER)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + fixture + .testSchema() + .dsl() + .execute( + "TRUNCATE game_session_canonical_issuer_bootstrap_member_op_counter")) + .isInstanceOf(DataAccessException.class); + assertThat( + rowImages( + fixture.testSchema().dsl(), + "game_session_canonical_issuer_bootstrap_member_operation")) + .hasSize(1); + assertThat( + fixture + .testSchema() + .dsl() + .fetchSingle( + "SELECT counter_version FROM game_session_canonical_issuer_bootstrap_member_op_counter" + + " WHERE issuer_id = ?", + ISSUER) + .get(0, Long.class)) + .isEqualTo(1L); + assertThat(historySnapshot(fixture.testSchema().dsl())) + .containsExactlyElementsOf(historyAfterMigration); + } finally { + dropSchema(fixture.testSchema().schema()); + } + } + + @Test + void groupedPartitionWorkIssuesAllExactOperationsConcurrentlyAndLeavesEmptyPartitionsUnallocated() + throws Exception { + Fixture fixture = + pendingFixture( + "gs_bootstrap_member_group_", PARTITION_CAPACITY, LAYOUT_VERSION, true, true); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + assertThat(fixture.plan().state()) + .isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED); + assertThat(fixture.plan().memberWorks()).hasSize(2); + migrateRemaining(fixture.testSchema()); + + var ready = new CountDownLatch(2); + var start = new CountDownLatch(1); + var first = executor.submit(() -> preparePartitionAtGate(fixture, ready, start)); + var second = executor.submit(() -> preparePartitionAtGate(fixture, ready, start)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + var firstWork = first.get(30, TimeUnit.SECONDS); + var secondWork = second.get(30, TimeUnit.SECONDS); + + assertThat(firstWork.buildPlan().planDigest()).isEqualTo(fixture.plan().planDigest()); + assertThat(firstWork.partitionId()).isEqualTo(fixture.partitionId()); + assertThat(firstWork.memberOperations()).hasSize(2); + assertThat(secondWork.memberOperations()) + .extracting(CanonicalGameplayIssuerBootstrapMemberOperation::operationId) + .containsExactlyElementsOf( + firstWork.memberOperations().stream() + .map(CanonicalGameplayIssuerBootstrapMemberOperation::operationId) + .toList()); + assertThat(firstWork.memberOperations()) + .extracting(CanonicalGameplayIssuerBootstrapMemberOperation::operationId) + .doesNotHaveDuplicates(); + assertThat(firstWork.memberOperations()) + .extracting(CanonicalGameplayIssuerBootstrapMemberOperation::expectedBindingPresent) + .containsOnly(false); + assertThat(firstWork.memberOperations().get(1).operationFence()) + .isGreaterThan(firstWork.memberOperations().getFirst().operationFence()); + assertThat(firstWork.memberOperations().get(1).localMemberGeneration()) + .isGreaterThan(firstWork.memberOperations().getFirst().localMemberGeneration()); + for (var operation : firstWork.memberOperations()) { + assertThat(operation.expectedMemberValue().reservation().partitionId()) + .isEqualTo(firstWork.partitionId()); + assertThat(operation.status()) + .isEqualTo( + CanonicalGameplayIssuerBootstrapMemberOperation.Status.PENDING_PHYSICAL_PROOF); + } + assertThat( + fixture + .testSchema() + .dsl() + .fetchSingle( + "SELECT counter_version FROM game_session_canonical_issuer_bootstrap_member_op_counter" + + " WHERE issuer_id = ?", + ISSUER) + .get(0, Long.class)) + .isEqualTo(2L); + + BigInteger emptyPartition = fixture.partitionId().add(BigInteger.ONE).mod(PARTITION_COUNT); + var empty = + new CanonicalGameplayIssuerBootstrapMemberOperationRepository(fixture.testSchema().dsl()) + .preparePartitionWork( + fixture.intent().operationId(), + fixture.requestId(), + emptyPartition, + fixture.currentAccountCheckpoint(), + stableIncarnation("stable-a")); + assertThat(empty.buildPlan().planDigest()).isEqualTo(fixture.plan().planDigest()); + assertThat(empty.partitionId()).isEqualTo(emptyPartition); + assertThat(empty.memberOperations()).isEmpty(); + assertThat( + fixture + .testSchema() + .dsl() + .fetchSingle( + "SELECT counter_version FROM game_session_canonical_issuer_bootstrap_member_op_counter" + + " WHERE issuer_id = ?", + ISSUER) + .get(0, Long.class)) + .isEqualTo(2L); + } finally { + executor.shutdownNow(); + dropSchema(fixture.testSchema().schema()); + } + } + + @Test + void wrongRequestCheckpointAndChangedFrozenSourceRefuseWithoutAllocatingCounters() { + Fixture fixture = + pendingFixture( + "gs_bootstrap_member_refusal_", PARTITION_CAPACITY, LAYOUT_VERSION, false, true); + try { + migrateRemaining(fixture.testSchema()); + var owner = + new CanonicalGameplayIssuerBootstrapMemberOperationRepository(fixture.testSchema().dsl()); + assertThatThrownBy( + () -> + owner.preparePartitionWork( + fixture.intent().operationId(), + UUID.randomUUID(), + fixture.partitionId(), + fixture.currentAccountCheckpoint(), + stableIncarnation("stable-a"))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + owner.preparePartitionWork( + fixture.intent().operationId(), + fixture.requestId(), + fixture.partitionId(), + sourceCheckpoint(BigInteger.valueOf(8)), + stableIncarnation("stable-a"))) + .isInstanceOf(IllegalStateException.class); + assertThat( + fixture + .testSchema() + .dsl() + .fetchSingle( + "SELECT count(*) FROM game_session_canonical_issuer_bootstrap_member_op_counter") + .get(0, Long.class)) + .isZero(); + + fixture + .testSchema() + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_partition_reservation" + + " SET coverage_fence = coverage_fence + 1 WHERE reservation_id = ?", + fixture.preparedBinding().issuerReservationId()); + assertThatThrownBy( + () -> + owner.preparePartitionWork( + fixture.intent().operationId(), + fixture.requestId(), + fixture.partitionId(), + fixture.currentAccountCheckpoint(), + stableIncarnation("stable-a"))) + .isInstanceOf(IllegalStateException.class); + assertThat( + rowImages( + fixture.testSchema().dsl(), + "game_session_canonical_issuer_bootstrap_member_operation")) + .isEmpty(); + assertThat( + fixture + .testSchema() + .dsl() + .fetchSingle( + "SELECT count(*) FROM game_session_canonical_issuer_bootstrap_member_op_counter") + .get(0, Long.class)) + .isZero(); + } finally { + dropSchema(fixture.testSchema().schema()); + } + } + + @Test + void missingPlanMissingControlAndBlockedLayoutRefuseWithoutMemberOperation() { + Fixture missingPlan = + pendingFixture( + "gs_bootstrap_member_no_plan_", PARTITION_CAPACITY, LAYOUT_VERSION, false, false); + try { + migrateRemaining(missingPlan.testSchema()); + assertThatThrownBy( + () -> + new CanonicalGameplayIssuerBootstrapMemberOperationRepository( + missingPlan.testSchema().dsl()) + .preparePartitionWork( + missingPlan.intent().operationId(), + missingPlan.requestId(), + missingPlan.partitionId(), + missingPlan.currentAccountCheckpoint(), + stableIncarnation("stable-a"))) + .isInstanceOf(IllegalStateException.class); + assertNoIssuedRows(missingPlan.testSchema().dsl()); + } finally { + dropSchema(missingPlan.testSchema().schema()); + } + + Fixture missingControl = + pendingFixture( + "gs_bootstrap_member_no_control_", PARTITION_CAPACITY, LAYOUT_VERSION, false, true); + try { + migrateRemaining(missingControl.testSchema()); + missingControl + .testSchema() + .dsl() + .execute( + "ALTER TABLE game_session_canonical_issuer_layout_bootstrap_control" + + " DROP CONSTRAINT fk_gs_issuer_layout_bootstrap_control_intent"); + missingControl + .testSchema() + .dsl() + .execute( + "DELETE FROM game_session_canonical_issuer_layout_bootstrap_control WHERE issuer_id = ?", + ISSUER); + assertThatThrownBy( + () -> + new CanonicalGameplayIssuerBootstrapMemberOperationRepository( + missingControl.testSchema().dsl()) + .preparePartitionWork( + missingControl.intent().operationId(), + missingControl.requestId(), + missingControl.partitionId(), + missingControl.currentAccountCheckpoint(), + stableIncarnation("stable-a"))) + .isInstanceOf(IllegalStateException.class); + assertNoIssuedRows(missingControl.testSchema().dsl()); + } finally { + dropSchema(missingControl.testSchema().schema()); + } + + Fixture blockedLayout = + pendingFixture( + "gs_bootstrap_member_bad_layout_", + PARTITION_CAPACITY, + LAYOUT_VERSION.add(BigInteger.ONE), + false, + true); + try { + assertThat(blockedLayout.plan().state()) + .isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.BLOCKED); + migrateRemaining(blockedLayout.testSchema()); + assertThatThrownBy( + () -> + new CanonicalGameplayIssuerBootstrapMemberOperationRepository( + blockedLayout.testSchema().dsl()) + .preparePartitionWork( + blockedLayout.intent().operationId(), + blockedLayout.requestId(), + blockedLayout.partitionId(), + blockedLayout.currentAccountCheckpoint(), + stableIncarnation("stable-a"))) + .isInstanceOf(IllegalStateException.class); + assertNoIssuedRows(blockedLayout.testSchema().dsl()); + } finally { + dropSchema(blockedLayout.testSchema().schema()); + } + } + + private static CanonicalGameplayIssuerBootstrapPartitionWork preparePartitionAtGate( + Fixture fixture, CountDownLatch ready, CountDownLatch start) throws InterruptedException { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Test start gate timed out"); + } + return new CanonicalGameplayIssuerBootstrapMemberOperationRepository(fixture.testSchema().dsl()) + .preparePartitionWork( + fixture.intent().operationId(), + fixture.requestId(), + fixture.partitionId(), + fixture.currentAccountCheckpoint(), + stableIncarnation("stable-a")); + } + + private static Fixture pendingFixture( + String prefix, + BigInteger reservationCapacity, + BigInteger descriptorLayoutVersion, + boolean addReservationOnly, + boolean createPlan) { + TestSchema testSchema = newTestSchemaAtVersion(prefix, "1030"); + establishActualLegacyDisposition(testSchema.dsl()); + CanonicalGameplayBindingTransitionSnapshot preparedBinding = + prepareActualBinding( + new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()), reservationCapacity); + BigInteger partitionId = preparedBinding.candidate().bindingRef().partitionId(PARTITION_COUNT); + if (addReservationOnly) { + insertReservationOnly( + testSchema.dsl(), + preparedBinding.candidate(), + preparedBinding.inventoryRevision(), + reservationCapacity, + PARTITION_COUNT, + partitionId); + } + UUID requestId = UUID.randomUUID(); + var checkpoint = sourceCheckpoint(BigInteger.valueOf(7)); + var intent = + new CanonicalGameplayIssuerLayoutBootstrapRepository(testSchema.dsl()) + .beginInitialBootstrapIntent( + requestId, + descriptor(descriptorLayoutVersion, PARTITION_COUNT, reservationCapacity), + checkpoint); + migrateThrough1031(testSchema); + CanonicalGameplayIssuerPartitionBuildPlan plan = + createPlan + ? new CanonicalGameplayIssuerPartitionBuildRepository(testSchema.dsl()) + .prepareInitialBuildPlan(intent.operationId(), requestId) + : null; + return new Fixture( + testSchema, preparedBinding, intent, requestId, checkpoint, partitionId, plan); + } + + private static CanonicalGameplayBindingTransitionSnapshot prepareActualBinding( + CanonicalGameplayBindingInventoryRepository inventory, BigInteger reservationCapacity) { + UUID transitionId = UUID.randomUUID(); + UUID reservationId = UUID.randomUUID(); + UUID reservationFence = UUID.randomUUID(); + UUID issuerCoverageOperationId = UUID.randomUUID(); + var candidate = + new CanonicalGameplayBindingIdentity( + ACCOUNT_ID, + TENANT_ID, + NAMESPACE_ID, + CHARACTER_ID, + "SHARED", + GAME_INSTANCE_ID, + 23L, + UUID.fromString("77777777-7777-4777-8777-777777777777").toString(), + REGION_ID, + BigInteger.valueOf(12), + ISSUER, + BigInteger.valueOf(7), + LAYOUT_VERSION, + PARTITION_COUNT, + reservationCapacity); + return inventory.prepare( + new CanonicalGameplayBindingTransitionRequest( + transitionId, + UUID.randomUUID(), + candidate, + new CanonicalIssuerReservationFenceEvidence( + reservationId, + reservationFence, + issuerCoverageOperationId, + BigInteger.valueOf(17), + BigInteger.valueOf(19), + BigInteger.ONE), + null, + null)); + } + + private static void insertReservationOnly( + DSLContext dsl, + CanonicalGameplayBindingIdentity template, + BigInteger revision, + BigInteger capacity, + BigInteger partitionCount, + BigInteger partitionId) { + UUID sessionUuid = sessionUuidForPartition(template, partitionCount, partitionId); + UUID reservationId = UUID.randomUUID(); + UUID transitionId = UUID.randomUUID(); + UUID reservationFence = UUID.randomUUID(); + UUID originalCoverageOperationId = UUID.randomUUID(); + String sessionId = sessionUuid.toString(); + byte[] bindingRef = + CanonicalGameplayBindingRef.of( + template.tenantId().toString(), template.gameInstanceId().toString(), sessionId) + .bytes(); + dsl.execute( + "INSERT INTO game_session_canonical_issuer_partition_reservation" + + " (reservation_id, binding_ref, account_id, tenant_id, game_instance_id," + + " runtime_game_instance_id, session_id, binding_generation, transition_id, issuer_id," + + " issuer_auth_generation, playable_state_namespace_id, character_id," + + " playable_state_scope, region_id, region_epoch, partition_id," + + " issuer_index_layout_version, issuer_index_partition_count," + + " issuer_index_partition_capacity, lifecycle, reservation_fence," + + " issuer_coverage_operation_id, issuer_coverage_operation_fence, coverage_fence," + + " inventory_snapshot_revision, inventory_revision)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'RESERVED'," + + " ?, ?, 17, 19, ?, ?)", + reservationId, + bindingRef, + template.accountId(), + template.tenantId(), + template.gameInstanceId(), + template.runtimeGameInstanceId(), + sessionId, + transitionId, + ISSUER, + new BigDecimal(template.issuerAuthGeneration()), + template.playableStateNamespaceId(), + UUID.fromString("88888888-8888-4888-8888-888888888888"), + template.playableStateScope(), + template.regionId(), + new BigDecimal(template.regionEpoch()), + new BigDecimal(partitionId), + new BigDecimal(LAYOUT_VERSION), + new BigDecimal(partitionCount), + new BigDecimal(capacity), + reservationFence, + originalCoverageOperationId, + new BigDecimal(revision), + new BigDecimal(revision)); + } + + private static UUID sessionUuidForPartition( + CanonicalGameplayBindingIdentity template, + BigInteger partitionCount, + BigInteger targetPartition) { + for (int candidate = 1; candidate <= 10_000; candidate++) { + UUID sessionUuid = + UUID.nameUUIDFromBytes( + ("issuer-bootstrap-member-session-" + candidate).getBytes(StandardCharsets.UTF_8)); + byte[] bindingRef = + CanonicalGameplayBindingRef.of( + template.tenantId().toString(), + template.gameInstanceId().toString(), + sessionUuid.toString()) + .bytes(); + if (CanonicalGameplayBindingRef.fromExactBytes(bindingRef) + .partitionId(partitionCount) + .equals(targetPartition)) { + return sessionUuid; + } + } + throw new IllegalStateException("Could not prepare a reservation in the target partition"); + } + + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor + descriptor(BigInteger version, BigInteger count, BigInteger capacity) { + String encoded = + "issuer-layout-descriptor/v1|" + + ISSUER + + "|" + + version + + "|" + + count + + "|" + + capacity + + "|" + + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY; + return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor( + ISSUER, + version, + count, + capacity, + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY, + encoded.getBytes(StandardCharsets.UTF_8)); + } + + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + sourceCheckpoint(BigInteger issuerGeneration) { + long sequence = issuerGeneration.longValueExact() - 1L; + var event = + AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + UUID.randomUUID().toString(), + UUID.randomUUID().toString(), + AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + ISSUER, + Long.toString(sequence), + ISSUER, + issuerGeneration.toString(), + issuerGeneration.toString(), + "ISSUER_SECURITY_CHANGE")); + byte[] eventBytes = event.canonicalJsonUtf8(); + return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint( + ISSUER, issuerGeneration, eventBytes, eventBytes); + } + + private static CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation + stableIncarnation(String seed) { + String digest = digest(seed); + return new CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation( + "controlled-attestor-" + seed, + digest, + new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "controlled-deployment-" + seed, + "deployment-generation-" + seed, + List.of("controlled-node-" + seed), + "controlled-redis-build-" + seed, + "controlled-lua-registry-" + seed, + digest, + "READY", + "boot-" + seed, + "startup-" + seed, + "storage-" + seed, + "aof-" + seed), + digest, + digest); + } + + private static String digest(String text) { + try { + return "sha256:" + + java.util.HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(text.getBytes(StandardCharsets.UTF_8))); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static void establishActualLegacyDisposition(DSLContext dsl) { + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); + UUID cohortId = UUID.randomUUID(); + UUID writerFence = UUID.randomUUID(); + var storageIdentity = + new CanonicalGameplayLegacyMigrationStorageIdentity( + "controlled-cluster-uid", + "controlled-namespace-uid", + "controlled-producer-pod-uid", + "controlled-container-id", + "controlled-node-uid", + "123456789", + 42L, + "controlled-postgres-volume-uid", + "controlled-redis-run-id", + "controlled-redis-volume-uid"); + var fencedCohort = + new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { + @Override + public UUID cohortId() { + return cohortId; + } + + @Override + public UUID legacyWriterFence() { + return writerFence; + } + + @Override + public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + return storageIdentity; + } + + @Override + public void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity expected) { + if (!storageIdentity.equals(expected)) { + throw new IllegalStateException("Controlled fixture storage identity changed"); + } + } + }; + var owner = + new CanonicalGameplayLegacyMigrationOwner( + migration, + inventory, + () -> fencedCohort, + ignored -> + new CanonicalGameplayLegacyMigrationSourceSnapshot( + EnumSet.of( + Family.TENANT_SESSION_CONTEXT, + Family.SESSION_ALIAS_CONTEXT, + Family.GAMEPLAY_IDENTITY_CONTEXT, + Family.GAMEPLAY_NAME_CONTEXT, + Family.MOVEMENT_EFFECT, + Family.DURABLE_EFFECT), + List.of()), + new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { + @Override + public void rebuildExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + CanonicalGameplayLegacyMigrationSourceSnapshot source, + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot + canonical) { + assertThat(canonical.bindings()).isEmpty(); + assertThat(canonical.reservations()).isEmpty(); + } + + @Override + public CanonicalGameplayLegacyMigrationReadback readBackExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot + canonical) { + assertThat(canonical.bindings()).isEmpty(); + return new CanonicalGameplayLegacyMigrationReadback( + List.of(), List.of(), List.of(), List.of()); + } + }); + assertThat(owner.migrate().state()) + .isEqualTo(CanonicalGameplayLegacyMigrationOperation.State.VERIFIED); + } + + private static void migrateThrough1031(TestSchema testSchema) { + Flyway.configure() + .dataSource(testSchema.dataSource()) + .schemas(testSchema.schema()) + .defaultSchema(testSchema.schema()) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("1031")) + .load() + .migrate(); + } + + private static void migrateRemaining(TestSchema testSchema) { + Flyway.configure() + .dataSource(testSchema.dataSource()) + .schemas(testSchema.schema()) + .defaultSchema(testSchema.schema()) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + } + + private static TestSchema newTestSchemaAtVersion(String prefix, String version) { + String schema = prefix + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION); + if (version != null) configuration.target(MigrationVersion.fromVersion(version)); + configuration.load().migrate(); + return new TestSchema(schema, dataSource, DSL.using(dataSource, SQLDialect.POSTGRES)); + } + + private static Map> rowSnapshots(DSLContext dsl) { + Map> snapshots = new LinkedHashMap<>(); + for (String table : RETAINED_TABLES) snapshots.put(table, rowImages(dsl, table)); + return Map.copyOf(snapshots); + } + + private static List historySnapshot(DSLContext dsl) { + return dsl.fetch( + "SELECT to_jsonb(history_row)::text AS row_image FROM flyway_schema_history history_row" + + " ORDER BY installed_rank") + .getValues("row_image", String.class); + } + + private static List rowImages(DSLContext dsl, String tableName) { + return dsl.fetch( + "SELECT to_jsonb(retained_row)::text AS row_image FROM " + + tableName + + " retained_row ORDER BY to_jsonb(retained_row)::text") + .getValues("row_image", String.class); + } + + private static void assertNoIssuedRows(DSLContext dsl) { + assertThat(rowImages(dsl, "game_session_canonical_issuer_bootstrap_member_operation")) + .isEmpty(); + assertThat(rowImages(dsl, "game_session_canonical_issuer_bootstrap_member_op_counter")) + .isEmpty(); + } + + private static DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + String jdbcUrl = postgres.getJdbcUrl(); + String separator = jdbcUrl.contains("?") ? "&" : "?"; + dataSource.setUrl(jdbcUrl + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } + + private static void dropSchema(String schema) { + try (var connection = dataSource("public").getConnection()) { + DSL.using(connection, SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } catch (Exception failure) { + throw new IllegalStateException( + "Could not drop the owned member-operation test schema", failure); + } + } + + private record Fixture( + TestSchema testSchema, + CanonicalGameplayBindingTransitionSnapshot preparedBinding, + CanonicalGameplayIssuerLayoutBootstrapIntent intent, + UUID requestId, + CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + currentAccountCheckpoint, + BigInteger partitionId, + CanonicalGameplayIssuerPartitionBuildPlan plan) {} + + private record TestSchema(String schema, DriverManagerDataSource dataSource, DSLContext dsl) {} +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java new file mode 100644 index 0000000000..2c707fcbea --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java @@ -0,0 +1,1145 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.sql.Connection; +import java.sql.SQLException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Base64; +import java.util.EnumSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +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.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Actual one-partition Redis readback composed from SQL-issued initial-bootstrap work. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String OWNER_PRINCIPAL = "gamesession_coord_app"; + private static final String ISSUER_KEY_PREFIX = "session:game:index:issuer:"; + private static final UUID TERMINAL_CHARACTER_ID = + UUID.fromString("88888888-8888-4888-8888-888888888888"); + private static final BigInteger LAYOUT_VERSION = BigInteger.valueOf(3); + private static final BigInteger PARTITION_COUNT = BigInteger.valueOf(16); + private static final BigInteger PARTITION_CAPACITY = BigInteger.valueOf(32); + + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + private static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + private final List schemas = new ArrayList<>(); + private RedisClient administrator; + private RedisClient ownerClient; + private StatefulRedisConnection administratorConnection; + private RedisCommands administratorCommands; + + @BeforeEach + void setUpRedis() { + String password = UUID.randomUUID().toString(); + administrator = createRedisClient(null, null); + administratorConnection = administrator.connect(ByteArrayCodec.INSTANCE); + administratorCommands = administratorConnection.sync(); + administratorCommands.flushdb(); + administratorCommands.aclSetuser( + OWNER_PRINCIPAL, + new AclSetuserArgs() + .reset() + .on() + .addPassword(password) + .keyPattern(ISSUER_KEY_PREFIX + "*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.HLEN) + .addCommand(CommandType.HGETALL) + .addCommand(CommandType.HSET)); + ownerClient = createRedisClient(OWNER_PRINCIPAL, password); + } + + @AfterEach + void tearDown() { + if (administratorConnection != null) administratorConnection.close(); + if (ownerClient != null) ownerClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + if (administrator != null) administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + for (TestSchema schema : schemas) dropSchema(schema.schema()); + } + + @Test + void buildsCompletePopulatedPartitionAndCountsReleasedOnlyAsRetainedEvidence() { + Fixture fixture = fixture(true); + CanonicalGameplayIssuerBootstrapPartitionWork work = + partitionWork(fixture, fixture.partitionId()); + + assertThat(work.buildPlan().state()) + .isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED); + assertThat(work.memberOperations()).hasSize(2); + assertThat(work.memberOperations()) + .filteredOn(CanonicalGameplayIssuerBootstrapMemberOperation::expectedBindingPresent) + .singleElement() + .satisfies( + operation -> + assertThat(operation.bindingLifecycle()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventoryEntry.Lifecycle.ACTIVE)); + assertThat(work.memberOperations()) + .filteredOn(operation -> !operation.countsTowardCapacity()) + .singleElement() + .satisfies( + operation -> + assertThat(operation.expectedMemberValue().reservation().lifecycle()) + .isEqualTo(CanonicalIssuerPartitionReservation.Lifecycle.RELEASED)); + + var active = + work.memberOperations().stream() + .filter(CanonicalGameplayIssuerBootstrapMemberOperation::expectedBindingPresent) + .findFirst() + .orElseThrow(); + var value = active.expectedMemberValue(); + assertThat(value.reservation().issuerCoverageOperationId()) + .isNotEqualTo(value.anchor().issuerCoverageOperationId()); + assertThat(value.reservation().issuerCoverageOperationFence()) + .isNotEqualTo(value.anchor().operationFence()); + assertThat(value.reservation().coverageFence()).isNotEqualTo(value.anchor().coverageFence()); + assertThat(value.reservation().inventorySnapshotRevision()) + .isNotEqualTo(value.anchor().issuerInventorySnapshotRevision()); + + var firstOwner = owner(work, currentState(fixture, work)); + var first = firstOwner.buildAndRead(work); + assertThat(first.physicalFieldCount()).isEqualTo(4); + assertThat(first.physicalPartitionReservationCount()).isEqualTo(2); + assertThat(first.physicalBindingCount()).isEqualTo(1); + assertThat(first.physicalCountedCapacityCount()).isEqualTo(1); + assertThat(first.plannedAggregateCapacityCount()).isEqualTo(BigInteger.ONE); + + CanonicalGameplayIssuerBootstrapPartitionWork restartedWork = + partitionWork(fixture, fixture.partitionId()); + assertThat(restartedWork.memberOperations()) + .extracting(CanonicalGameplayIssuerBootstrapMemberOperation::exactMemberValueBytes) + .containsExactlyElementsOf( + work.memberOperations().stream() + .map(CanonicalGameplayIssuerBootstrapMemberOperation::exactMemberValueBytes) + .toList()); + var afterRestart = + owner(restartedWork, currentState(fixture, restartedWork)).buildAndRead(restartedWork); + assertThat(afterRestart.physicalFieldCount()).isEqualTo(first.physicalFieldCount()); + assertThat(afterRestart.physicalCountedCapacityCount()).isEqualTo(1); + + byte[] key = key(fixture, work.partitionId()); + assertThat(administratorCommands.type(key)).isEqualTo("hash"); + assertThat(administratorCommands.pttl(key)).isEqualTo(-1L); + assertThat(administratorCommands.hlen(key)).isEqualTo(4L); + assertThat(statusesRemainPending(fixture.dsl())).isTrue(); + } + + @Test + void positivelyPreparedEmptyPartitionBuildsOnlyItsCommonMetadata() { + Fixture fixture = fixture(false); + BigInteger emptyPartition = fixture.partitionId().add(BigInteger.ONE).mod(PARTITION_COUNT); + CanonicalGameplayIssuerBootstrapPartitionWork work = partitionWork(fixture, emptyPartition); + assertThat(work.buildPlan().state()) + .isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED); + assertThat(work.buildPlan().memberWorks()).hasSize(1); + assertThat(work.memberOperations()).isEmpty(); + + byte[] key = key(fixture, emptyPartition); + assertThat(administratorCommands.type(key)).isEqualTo("none"); + var readback = owner(work, currentState(fixture, work)).buildAndRead(work); + + assertThat(readback.physicalFieldCount()).isEqualTo(1); + assertThat(readback.physicalPartitionReservationCount()).isZero(); + assertThat(readback.physicalCountedCapacityCount()).isZero(); + assertThat(readback.plannedAggregateCapacityCount()).isEqualTo(BigInteger.ONE); + assertThat(administratorCommands.hlen(key)).isEqualTo(1L); + assertThat(statusesRemainPending(fixture.dsl())).isTrue(); + } + + @Test + void sameBindingWithDifferentAnchorReservationLifecycleOrLocalOperationIsAConflict() { + Fixture fixture = fixture(false); + CanonicalGameplayIssuerBootstrapPartitionWork work = + partitionWork(fixture, fixture.partitionId()); + var active = work.memberOperations().getFirst(); + assertThat(active.expectedBindingPresent()).isTrue(); + owner(work, currentState(fixture, work)).buildAndRead(work); + + byte[] key = key(fixture, work.partitionId()); + byte[] bindingField = active.expectedMemberValue().owner().bindingRef().bytes(); + byte[] exact = active.exactMemberValueBytes(); + List conflicts = + List.of( + encodeWith( + active.expectedMemberValue(), + active.expectedMemberValue().reservation(), + new CanonicalGameplayIssuerMemberV2Value.Anchor( + UUID.randomUUID(), + active.expectedMemberValue().anchor().operationFence(), + active.expectedMemberValue().anchor().coverageFence(), + active.expectedMemberValue().anchor().issuerInventorySnapshotRevision()), + active.expectedMemberValue().memberOperation()), + encodeWith( + active.expectedMemberValue(), + withReservation( + active.expectedMemberValue().reservation(), + UUID.randomUUID(), + active.expectedMemberValue().reservation().lifecycle()), + active.expectedMemberValue().anchor(), + active.expectedMemberValue().memberOperation()), + encodeWith( + active.expectedMemberValue(), + withReservation( + active.expectedMemberValue().reservation(), + active.expectedMemberValue().reservation().reservationId(), + CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING), + active.expectedMemberValue().anchor(), + active.expectedMemberValue().memberOperation()), + encodeWith( + active.expectedMemberValue(), + active.expectedMemberValue().reservation(), + active.expectedMemberValue().anchor(), + new CanonicalGameplayIssuerMemberV2Value.LocalMemberOperation( + UUID.randomUUID(), + active.expectedMemberValue().memberOperation().operationFence(), + active.expectedMemberValue().memberOperation().coverageGeneration())), + encodeNewerBinding(active.expectedMemberValue())); + + for (byte[] conflict : conflicts) { + administratorCommands.hset(key, bindingField, conflict); + assertThatThrownBy(() -> owner(work, currentState(fixture, work)).buildAndRead(work)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("projection is unavailable"); + assertThat(administratorCommands.hget(key, bindingField)).containsExactly(conflict); + assertThat(administratorCommands.hlen(key)).isEqualTo(3L); + administratorCommands.hset(key, bindingField, exact); + } + assertThat(statusesRemainPending(fixture.dsl())).isTrue(); + } + + @Test + void malformedLegacyForeignAndExpiringPhysicalStateRefuseWithoutMutation() { + Fixture fixture = fixture(false); + CanonicalGameplayIssuerBootstrapPartitionWork populated = + partitionWork(fixture, fixture.partitionId()); + var active = populated.memberOperations().getFirst(); + byte[] populatedKey = key(fixture, populated.partitionId()); + byte[] bindingField = active.expectedMemberValue().owner().bindingRef().bytes(); + byte[] legacyV1 = "{\"schemaVersion\":1}".getBytes(StandardCharsets.UTF_8); + administratorCommands.hset(populatedKey, bindingField, legacyV1); + + assertThatThrownBy(() -> owner(populated, currentState(fixture, populated)).buildAndRead(populated)) + .isInstanceOf(IllegalStateException.class); + assertThat(administratorCommands.hget(populatedKey, bindingField)).containsExactly(legacyV1); + assertThat(administratorCommands.hlen(populatedKey)).isEqualTo(1L); + + BigInteger foreignPartition = populated.partitionId().add(BigInteger.TWO).mod(PARTITION_COUNT); + var foreignWork = partitionWork(fixture, foreignPartition); + byte[] foreignKey = key(fixture, foreignPartition); + byte[] foreignField = ascii("unrelated-operator-field"); + byte[] foreignValue = ascii("retained-source"); + administratorCommands.hset(foreignKey, foreignField, foreignValue); + assertThatThrownBy(() -> owner(foreignWork, currentState(fixture, foreignWork)).buildAndRead(foreignWork)) + .isInstanceOf(IllegalStateException.class); + assertThat(administratorCommands.hlen(foreignKey)).isEqualTo(1L); + assertThat(administratorCommands.hget(foreignKey, foreignField)).containsExactly(foreignValue); + + BigInteger expiringPartition = populated.partitionId().add(BigInteger.valueOf(3)).mod(PARTITION_COUNT); + var expiringWork = partitionWork(fixture, expiringPartition); + byte[] expiringKey = key(fixture, expiringPartition); + byte[] expiringField = ascii("foreign-ttl-field"); + byte[] expiringValue = ascii("retained-ttl-source"); + administratorCommands.hset(expiringKey, expiringField, expiringValue); + administratorCommands.pexpire(expiringKey, 60_000); + long ttlBefore = administratorCommands.pttl(expiringKey); + + assertThatThrownBy(() -> owner(expiringWork, currentState(fixture, expiringWork)).buildAndRead(expiringWork)) + .isInstanceOf(IllegalStateException.class); + assertThat(administratorCommands.pttl(expiringKey)).isPositive().isLessThanOrEqualTo(ttlBefore); + assertThat(administratorCommands.hget(expiringKey, expiringField)).containsExactly(expiringValue); + + BigInteger wrongTypePartition = + populated.partitionId().add(BigInteger.valueOf(4)).mod(PARTITION_COUNT); + var wrongTypeWork = partitionWork(fixture, wrongTypePartition); + byte[] wrongTypeKey = key(fixture, wrongTypePartition); + byte[] wrongTypeValue = ascii("foreign-persistent-string"); + administratorCommands.set(wrongTypeKey, wrongTypeValue); + assertThatThrownBy( + () -> owner(wrongTypeWork, currentState(fixture, wrongTypeWork)).buildAndRead(wrongTypeWork)) + .isInstanceOf(IllegalStateException.class); + assertThat(administratorCommands.type(wrongTypeKey)).isEqualTo("string"); + assertThat(administratorCommands.get(wrongTypeKey)).containsExactly(wrongTypeValue); + assertThat(statusesRemainPending(fixture.dsl())).isTrue(); + } + + @Test + void changedFreshCheckpointOrIncarnationBeforeAndAfterRedisLeavesNoReadbackCapability() { + Fixture fixture = fixture(false); + CanonicalGameplayIssuerBootstrapPartitionWork work = + partitionWork(fixture, fixture.partitionId()); + byte[] key = key(fixture, work.partitionId()); + var changedCheckpoint = alternateCheckpointShape(BigInteger.valueOf(8)); + AtomicInteger beforeCalls = new AtomicInteger(); + var beforeOwner = + owner( + work, + () -> { + beforeCalls.incrementAndGet(); + return new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + changedCheckpoint, work.incarnation()); + }); + + assertThatThrownBy(() -> beforeOwner.buildAndRead(work)) + .isInstanceOf(IllegalStateException.class); + assertThat(beforeCalls).hasValue(1); + assertThat(administratorCommands.type(key)).isEqualTo("none"); + + AtomicInteger beforeIncarnationCalls = new AtomicInteger(); + var beforeIncarnationOwner = + owner( + work, + () -> { + beforeIncarnationCalls.incrementAndGet(); + return new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + fixture.intent().sourceCheckpoint(), changedIncarnation(work.incarnation())); + }); + assertThatThrownBy(() -> beforeIncarnationOwner.buildAndRead(work)) + .isInstanceOf(IllegalStateException.class); + assertThat(beforeIncarnationCalls).hasValue(1); + assertThat(administratorCommands.type(key)).isEqualTo("none"); + + AtomicInteger afterCheckpointCalls = new AtomicInteger(); + var changedAfterCheckpointOwner = + owner( + work, + () -> + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + afterCheckpointCalls.incrementAndGet() == 1 + ? fixture.intent().sourceCheckpoint() + : changedCheckpoint, + work.incarnation())); + assertThatThrownBy(() -> changedAfterCheckpointOwner.buildAndRead(work)) + .isInstanceOf(IllegalStateException.class); + assertThat(afterCheckpointCalls).hasValue(2); + assertThat(administratorCommands.type(key)).isEqualTo("hash"); + assertThat(administratorCommands.hlen(key)).isEqualTo(3L); + + AtomicInteger afterCalls = new AtomicInteger(); + var changedAfterOwner = + owner( + work, + () -> + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + fixture.intent().sourceCheckpoint(), + afterCalls.incrementAndGet() == 1 + ? work.incarnation() + : changedIncarnation(work.incarnation()))); + assertThatThrownBy(() -> changedAfterOwner.buildAndRead(work)) + .isInstanceOf(IllegalStateException.class); + assertThat(afterCalls).hasValue(2); + assertThat(administratorCommands.type(key)).isEqualTo("hash"); + assertThat(administratorCommands.hlen(key)).isEqualTo(3L); + assertThat(statusesRemainPending(fixture.dsl())).isTrue(); + } + + @Test + void retainedCommitAfterLostReplyReplaysFromFreshSqlWorkAndSeparatePhysicalReadback() throws Exception { + Fixture fixture = fixture(false); + CanonicalGameplayIssuerBootstrapPartitionWork work = + partitionWork(fixture, fixture.partitionId()); + var physical = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.expectedFields(work); + byte[] script = + resource(CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.RESOURCE_PATH); + String scriptSha = administratorCommands.scriptLoad(script); + byte[] key = key(fixture, work.partitionId()); + + // The test deliberately discards this post-commit script reply to model a lost reply/crash. + administratorCommands.evalsha( + scriptSha, + ScriptOutputType.INTEGER, + new byte[][] {key}, + scriptArguments(work, physical)); + + CanonicalGameplayIssuerBootstrapPartitionWork restartedWork = + partitionWork(fixture, work.partitionId()); + var readback = owner(restartedWork, currentState(fixture, restartedWork)).buildAndRead(restartedWork); + assertThat(readback.physicalFieldCount()).isEqualTo(3); + assertThat(readback.physicalCountedCapacityCount()).isEqualTo(1); + assertThat(statusesRemainPending(fixture.dsl())).isTrue(); + } + + @Test + void deliberatelyLowerCapacityLuaArgumentsRefuseWithoutChangingOwnedHashImage() throws Exception { + Fixture fixture = fixture(false, 2); + CanonicalGameplayIssuerBootstrapPartitionWork work = + partitionWork(fixture, fixture.partitionId()); + assertThat(work.buildPlan().state()) + .isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED); + assertThat(work.memberOperations()).hasSize(2); + assertThat(work.memberOperations()) + .allSatisfy( + operation -> assertThat(operation.countsTowardCapacity()).isTrue()); + var physical = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.expectedFields(work); + var catalog = + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution())); + RedisScriptDescriptor descriptor = + catalog.require(CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.SCRIPT_ID); + assertThat(descriptor.category()) + .isEqualTo(RedisScriptDescriptor.ScriptCategory.SESSION_ISSUER_INDEX); + assertThat(descriptor.principal()).isEqualTo(OWNER_PRINCIPAL); + byte[] script = resource(descriptor.resourcePath()); + assertThat(digest(script)).isEqualTo("sha256:" + descriptor.sha256()); + byte[] key = key(fixture, work.partitionId()); + byte[][] arguments = scriptArguments(work, physical); + // Deliberately inconsistent negative Lua arguments probe refusal only; the complete SQL plan + // remains valid at its pinned capacity of 32 and is never treated as positive overflow work. + arguments[3] = ascii("1"); + arguments[4] = lowerCapacityMetadata(physical.metadataBytes()); + for (int index = 0; index < work.memberOperations().size(); index++) { + int memberArgument = 7 + index * 4; + arguments[memberArgument] = lowerCapacityMember(arguments[memberArgument]); + } + + assertThat(administratorCommands.type(key)).isEqualTo("none"); + Map before = hashImage(key); + try (StatefulRedisConnection connection = + ownerClient.connect(ByteArrayCodec.INSTANCE)) { + RedisCommands commands = connection.sync(); + assertThat(commands.aclWhoami()).isEqualTo(OWNER_PRINCIPAL); + String loadedSha = commands.scriptLoad(script); + Long refused = + commands.evalsha(loadedSha, ScriptOutputType.INTEGER, new byte[][] {key}, arguments); + assertThat(refused).isEqualTo(-2L); + } + assertThat(administratorCommands.type(key)).isEqualTo("none"); + assertThat(hashImage(key)).isEqualTo(before); + assertThat(statusesRemainPending(fixture.dsl())).isTrue(); + } + + private Fixture fixture(boolean includeReleasedReservation) { + return fixture(includeReleasedReservation, 1); + } + + private Fixture fixture(boolean includeReleasedReservation, int activeBindingCount) { + if (activeBindingCount < 1 || activeBindingCount > 2) { + throw new IllegalArgumentException("Test fixtures support one or two active bindings"); + } + TestSchema testSchema = newTestSchemaAtVersion("gs_issuer_physical_", "1030"); + schemas.add(testSchema); + establishActualLegacyDisposition(testSchema.dsl()); + CanonicalGameplayBindingIdentity active = + CanonicalGameplayBindingInventoryRepositoryIntegrationTest.identity( + UUID.randomUUID().toString()); + CanonicalGameplayBindingInventoryRepositoryIntegrationTest.seedActiveSource( + testSchema.dsl(), active); + BigInteger partitionId = active.bindingRef().partitionId(PARTITION_COUNT); + for (int index = 1; index < activeBindingCount; index++) { + CanonicalGameplayBindingIdentity samePartition = + seedSamePartitionActiveBinding(testSchema.dsl(), partitionId); + assertThat(samePartition.bindingRef().partitionId(PARTITION_COUNT)).isEqualTo(partitionId); + } + if (includeReleasedReservation) insertReleasedReservation(testSchema.dsl(), active, partitionId); + + UUID requestId = UUID.randomUUID(); + var source = sourceCheckpoint(BigInteger.valueOf(7)); + var intent = + new CanonicalGameplayIssuerLayoutBootstrapRepository(testSchema.dsl()) + .beginInitialBootstrapIntent(requestId, descriptor(), source); + migrateRemaining(testSchema); + var plan = + new CanonicalGameplayIssuerPartitionBuildRepository(testSchema.dsl()) + .prepareInitialBuildPlan(intent.operationId(), requestId); + assertThat(plan.state()).isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED); + return new Fixture(testSchema, active, intent, requestId, source, partitionId); + } + + private CanonicalGameplayIssuerBootstrapPartitionWork partitionWork( + Fixture fixture, BigInteger partitionId) { + return new CanonicalGameplayIssuerBootstrapMemberOperationRepository(fixture.dsl()) + .preparePartitionWork( + fixture.intent().operationId(), + fixture.requestId(), + partitionId, + fixture.currentAccountCheckpoint(), + stableIncarnation("physical-owner")); + } + + private CanonicalGameplayIssuerBootstrapPartitionRedisOwner owner( + CanonicalGameplayIssuerBootstrapPartitionWork work, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource source) { + return new CanonicalGameplayIssuerBootstrapPartitionRedisOwner( + ownerClient, + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution())), + source); + } + + private CanonicalGameplayIssuerBootstrapPartitionRedisOwner owner( + CanonicalGameplayIssuerBootstrapPartitionWork work, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState source) { + return owner(work, () -> source); + } + + private CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState( + Fixture fixture, CanonicalGameplayIssuerBootstrapPartitionWork work) { + return new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + fixture.intent().sourceCheckpoint(), work.incarnation()); + } + + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor + descriptor() { + String bytes = + "issuer-layout-descriptor/v1|" + + ISSUER + + "|" + + LAYOUT_VERSION + + "|" + + PARTITION_COUNT + + "|" + + PARTITION_CAPACITY + + "|" + + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY; + return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor( + ISSUER, + LAYOUT_VERSION, + PARTITION_COUNT, + PARTITION_CAPACITY, + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY, + bytes.getBytes(StandardCharsets.UTF_8)); + } + + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + sourceCheckpoint(BigInteger generation) { + long sequence = generation.longValueExact() - 1; + var event = + AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + UUID.randomUUID().toString(), + UUID.randomUUID().toString(), + AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + ISSUER, + Long.toString(sequence), + ISSUER, + generation.toString(), + generation.toString(), + "ISSUER_SECURITY_CHANGE")); + byte[] exactEvent = event.canonicalJsonUtf8(); + return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint( + ISSUER, generation, exactEvent, exactEvent); + } + + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + alternateTrustedCheckpoint(BigInteger generation) { + return sourceCheckpoint(generation); + } + + private static CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint + alternateCheckpointShape(BigInteger generation) { + var trusted = alternateTrustedCheckpoint(generation); + byte[] checkpoint = trusted.checkpointBytes(); + byte[] event = trusted.latestEventBytes(); + return new CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint( + trusted.issuerId(), + trusted.issuerAuthGeneration(), + checkpoint, + CanonicalGameplayIssuerMemberV2Codec.sha256(checkpoint), + event, + CanonicalGameplayIssuerMemberV2Codec.sha256(event)); + } + + private static CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation + stableIncarnation(String seed) { + String digest = digest(seed.getBytes(StandardCharsets.UTF_8)); + return new CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation( + "controlled-attestor-" + seed, + digest, + targetDeploymentEvidence(seed, digest), + digest, + digest); + } + + private static CanonicalGameplayIssuerMemberV2Value.Incarnation changedIncarnation( + CanonicalGameplayIssuerMemberV2Value.Incarnation current) { + return new CanonicalGameplayIssuerMemberV2Value.Incarnation( + current.attestorBinding() + "-changed", + current.acceptedAttestationDigest(), + current.targetDeploymentEvidence(), + current.coordOpsRoAclDigest(), + current.coordRedisConfigObservedDigest()); + } + + private static CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + targetDeploymentEvidence(String seed, String digest) { + return new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "controlled-deployment-" + seed, + "deployment-generation-" + seed, + List.of("controlled-node-" + seed), + "controlled-redis-build-" + seed, + "controlled-lua-registry-" + seed, + digest, + "READY", + "boot-" + seed, + "startup-" + seed, + "storage-" + seed, + "aof-" + seed); + } + + private static byte[] encodeWith( + CanonicalGameplayIssuerMemberV2Value base, + CanonicalIssuerPartitionReservation reservation, + CanonicalGameplayIssuerMemberV2Value.Anchor anchor, + CanonicalGameplayIssuerMemberV2Value.LocalMemberOperation memberOperation) { + return CanonicalGameplayIssuerMemberV2Codec.encode( + new CanonicalGameplayIssuerMemberV2Value( + base.owner(), + base.bindingGeneration(), + reservation, + anchor, + memberOperation, + base.issuerControlEpoch(), + base.layoutDescriptor(), + base.sourceCheckpoint(), + base.incarnation())); + } + + private static byte[] encodeNewerBinding(CanonicalGameplayIssuerMemberV2Value original) { + BigInteger nextGeneration = original.bindingGeneration().add(BigInteger.ONE); + CanonicalIssuerPartitionReservation nextReservation = + new CanonicalIssuerPartitionReservation( + UUID.randomUUID(), + original.owner(), + nextGeneration, + UUID.randomUUID(), + original.reservation().partitionId(), + CanonicalIssuerPartitionReservation.Lifecycle.BOUND, + UUID.randomUUID(), + original.reservation().issuerCoverageOperationId(), + original.reservation().issuerCoverageOperationFence(), + original.reservation().coverageFence(), + original.reservation().inventorySnapshotRevision(), + original.reservation().inventoryRevision().add(BigInteger.ONE)); + return CanonicalGameplayIssuerMemberV2Codec.encode( + new CanonicalGameplayIssuerMemberV2Value( + original.owner(), + nextGeneration, + nextReservation, + original.anchor(), + new CanonicalGameplayIssuerMemberV2Value.LocalMemberOperation( + UUID.randomUUID(), + original.memberOperation().operationFence().add(BigInteger.ONE), + original.memberOperation().coverageGeneration().add(BigInteger.ONE)), + original.issuerControlEpoch(), + original.layoutDescriptor(), + original.sourceCheckpoint(), + original.incarnation())); + } + + private static CanonicalIssuerPartitionReservation withReservation( + CanonicalIssuerPartitionReservation original, + UUID reservationId, + CanonicalIssuerPartitionReservation.Lifecycle lifecycle) { + return new CanonicalIssuerPartitionReservation( + reservationId, + original.owner(), + original.bindingGeneration(), + original.transitionId(), + original.partitionId(), + lifecycle, + original.reservationFence(), + original.issuerCoverageOperationId(), + original.issuerCoverageOperationFence(), + original.coverageFence(), + original.inventorySnapshotRevision(), + original.inventoryRevision()); + } + + private static byte[][] scriptArguments( + CanonicalGameplayIssuerBootstrapPartitionWork work, + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.PhysicalFieldSet physical) { + var intent = work.buildPlan().bootstrapIntent(); + byte[][] arguments = new byte[6 + work.memberOperations().size() * 4][]; + arguments[0] = ascii(intent.issuerId()); + arguments[1] = ascii(work.partitionId().toString()); + arguments[2] = ascii(intent.layoutDescriptor().partitionCount().toString()); + arguments[3] = ascii(intent.layoutDescriptor().partitionCapacity().toString()); + arguments[4] = physical.metadataBytes(); + arguments[5] = ascii(Integer.toString(work.memberOperations().size())); + int offset = 6; + for (CanonicalGameplayIssuerBootstrapMemberOperation operation : work.memberOperations()) { + arguments[offset++] = operation.expectedMemberValue().owner().bindingRef().bytes(); + arguments[offset++] = operation.exactMemberValueBytes(); + arguments[offset++] = + ascii( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + operation.expectedMemberValue().reservation().reservationId())); + arguments[offset++] = ascii(operation.expectedBindingPresent() ? "1" : "0"); + } + return arguments; + } + + private static byte[] key(Fixture fixture, BigInteger partitionId) { + return CanonicalGameplayIssuerRedisKeys.forPartition( + fixture.intent().layoutDescriptor(), partitionId) + .getBytes(StandardCharsets.US_ASCII); + } + + private void insertReleasedReservation( + DSLContext dsl, CanonicalGameplayBindingIdentity template, BigInteger targetPartition) { + UUID sessionId = sessionUuidForPartition(template, targetPartition); + UUID reservationId = UUID.randomUUID(); + UUID transitionId = UUID.randomUUID(); + UUID reservationFence = UUID.randomUUID(); + UUID originalCoverageOperationId = UUID.randomUUID(); + byte[] bindingRef = + CanonicalGameplayBindingRef.of( + template.tenantId().toString(), template.gameInstanceId().toString(), sessionId.toString()) + .bytes(); + dsl.execute( + "INSERT INTO game_session_canonical_issuer_partition_reservation" + + " (reservation_id, binding_ref, account_id, tenant_id, game_instance_id," + + " runtime_game_instance_id, session_id, binding_generation, transition_id, issuer_id," + + " issuer_auth_generation, playable_state_namespace_id, character_id," + + " playable_state_scope, region_id, region_epoch, partition_id," + + " issuer_index_layout_version, issuer_index_partition_count," + + " issuer_index_partition_capacity, lifecycle, reservation_fence," + + " issuer_coverage_operation_id, issuer_coverage_operation_fence, coverage_fence," + + " inventory_snapshot_revision, inventory_revision)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + + " 'RELEASED', ?, ?, 17, 19, 7, 8)", + reservationId, + bindingRef, + template.accountId(), + template.tenantId(), + template.gameInstanceId(), + template.runtimeGameInstanceId(), + sessionId.toString(), + transitionId, + ISSUER, + new BigDecimal(template.issuerAuthGeneration()), + template.playableStateNamespaceId(), + TERMINAL_CHARACTER_ID, + template.playableStateScope(), + template.regionId(), + new BigDecimal(template.regionEpoch()), + new BigDecimal(targetPartition), + new BigDecimal(LAYOUT_VERSION), + new BigDecimal(PARTITION_COUNT), + new BigDecimal(PARTITION_CAPACITY), + reservationFence, + originalCoverageOperationId); + } + + private static UUID sessionUuidForPartition( + CanonicalGameplayBindingIdentity template, BigInteger targetPartition) { + for (int candidate = 1; candidate <= 10_000; candidate++) { + UUID session = + UUID.nameUUIDFromBytes( + ("physical-release-session-" + candidate).getBytes(StandardCharsets.UTF_8)); + byte[] ref = + CanonicalGameplayBindingRef.of( + template.tenantId().toString(), template.gameInstanceId().toString(), session.toString()) + .bytes(); + if (CanonicalGameplayBindingRef.fromExactBytes(ref) + .partitionId(PARTITION_COUNT) + .equals(targetPartition) + && !session.toString().equals(template.sessionId())) { + return session; + } + } + throw new IllegalStateException("Could not create an isolated released reservation field"); + } + + private static byte[] resource(String name) throws Exception { + try (var input = + CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.class + .getClassLoader() + .getResourceAsStream(name)) { + if (input == null) throw new IllegalStateException("Redis script resource is missing"); + return input.readAllBytes(); + } + } + + private Map hashImage(byte[] key) { + Map raw = administratorCommands.hgetall(key); + Map image = new LinkedHashMap<>(); + raw.forEach( + (field, value) -> + image.put( + Base64.getEncoder().encodeToString(field), + Base64.getEncoder().encodeToString(value))); + return image; + } + + private static byte[] lowerCapacityMetadata(byte[] exactMetadata) { + return lowerCapacityJson(exactMetadata); + } + + private static byte[] lowerCapacityMember(byte[] exactMemberValue) { + return lowerCapacityJson(exactMemberValue); + } + + private static byte[] lowerCapacityJson(byte[] exactJson) { + String original = new String(exactJson, StandardCharsets.UTF_8); + String fullCapacity = "\"partitionCapacity\":\"" + PARTITION_CAPACITY + "\""; + String reducedCapacity = "\"partitionCapacity\":\"1\""; + if (!original.contains(fullCapacity)) { + throw new IllegalStateException("Controlled physical input has no exact partition capacity field"); + } + return original.replace(fullCapacity, reducedCapacity).getBytes(StandardCharsets.UTF_8); + } + + private static CanonicalGameplayBindingIdentity seedSamePartitionActiveBinding( + DSLContext dsl, BigInteger partitionId) { + for (int candidate = 0; candidate < 10_000; candidate++) { + CanonicalGameplayBindingIdentity identity = + new CanonicalGameplayBindingIdentity( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + 90_000L + candidate, + UUID.randomUUID().toString(), + UUID.randomUUID(), + BigInteger.valueOf(12), + ISSUER, + BigInteger.valueOf(7), + LAYOUT_VERSION, + PARTITION_COUNT, + PARTITION_CAPACITY); + if (identity.bindingRef().partitionId(PARTITION_COUNT).equals(partitionId)) { + insertAdditionalActiveSource(dsl, identity); + return identity; + } + } + throw new IllegalStateException("Could not seed an active binding in the controlled partition"); + } + + private static void insertAdditionalActiveSource( + DSLContext dsl, CanonicalGameplayBindingIdentity identity) { + byte[] bindingRef = identity.bindingRef().bytes(); + BigInteger partitionId = identity.bindingRef().partitionId(identity.issuerIndexPartitionCount()); + UUID accountIndexFence = UUID.randomUUID(); + UUID reservationId = UUID.randomUUID(); + UUID transitionId = UUID.randomUUID(); + UUID reservationFence = UUID.randomUUID(); + UUID originalCoverageOperationId = UUID.randomUUID(); + dsl.execute( + "UPDATE game_session_canonical_binding_inventory_clock SET inventory_revision = 8" + + " WHERE singleton_id = 1"); + dsl.execute( + "INSERT INTO game_session_canonical_binding_generation" + + " (tenant_id, playable_state_namespace_id, character_id, last_issued_generation)" + + " VALUES (?, ?, ?, 5)", + identity.tenantId(), + identity.playableStateNamespaceId(), + identity.characterId()); + dsl.execute( + "INSERT INTO game_session_canonical_gameplay_binding_inventory" + + " (binding_ref, account_id, tenant_id, playable_state_namespace_id, character_id," + + " playable_state_scope, game_instance_id, runtime_game_instance_id, session_id," + + " binding_generation, region_id, region_epoch, issuer_id, issuer_auth_generation," + + " issuer_index_layout_version, issuer_index_partition_count," + + " issuer_index_partition_capacity, issuer_partition_id, account_index_fence," + + " issuer_reservation_id, transition_id, lifecycle, account_index_state," + + " issuer_index_state, inventory_revision)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 5, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + + " 'ACTIVE', 'ACKNOWLEDGED', 'ACKNOWLEDGED', 8)", + bindingRef, + identity.accountId(), + identity.tenantId(), + identity.playableStateNamespaceId(), + identity.characterId(), + identity.playableStateScope(), + identity.gameInstanceId(), + identity.runtimeGameInstanceId(), + identity.sessionId(), + identity.regionId(), + new BigDecimal(identity.regionEpoch()), + identity.issuerId(), + new BigDecimal(identity.issuerAuthGeneration()), + new BigDecimal(identity.issuerIndexLayoutVersion()), + new BigDecimal(identity.issuerIndexPartitionCount()), + new BigDecimal(identity.issuerIndexPartitionCapacity()), + new BigDecimal(partitionId), + accountIndexFence, + reservationId, + transitionId); + dsl.execute( + "INSERT INTO game_session_canonical_issuer_partition_reservation" + + " (reservation_id, binding_ref, account_id, tenant_id, game_instance_id," + + " runtime_game_instance_id, session_id, binding_generation, transition_id, issuer_id," + + " issuer_auth_generation, playable_state_namespace_id, character_id," + + " playable_state_scope, region_id, region_epoch, partition_id," + + " issuer_index_layout_version, issuer_index_partition_count," + + " issuer_index_partition_capacity, lifecycle, reservation_fence," + + " issuer_coverage_operation_id, issuer_coverage_operation_fence, coverage_fence," + + " inventory_snapshot_revision, inventory_revision)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, 5, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + + " 'BOUND', ?, ?, 1, 1, 7, 8)", + reservationId, + bindingRef, + identity.accountId(), + identity.tenantId(), + identity.gameInstanceId(), + identity.runtimeGameInstanceId(), + identity.sessionId(), + transitionId, + identity.issuerId(), + new BigDecimal(identity.issuerAuthGeneration()), + identity.playableStateNamespaceId(), + identity.characterId(), + identity.playableStateScope(), + identity.regionId(), + new BigDecimal(identity.regionEpoch()), + new BigDecimal(partitionId), + new BigDecimal(identity.issuerIndexLayoutVersion()), + new BigDecimal(identity.issuerIndexPartitionCount()), + new BigDecimal(identity.issuerIndexPartitionCapacity()), + reservationFence, + originalCoverageOperationId); + dsl.execute( + "INSERT INTO game_session_canonical_binding_transition" + + " (transition_id, tenant_id, playable_state_namespace_id, character_id," + + " expected_prior_binding_ref, expected_prior_binding_generation, candidate_binding_ref," + + " candidate_binding_generation, candidate_account_index_fence, issuer_reservation_id," + + " status, inventory_revision)" + + " VALUES (?, ?, ?, ?, NULL, NULL, ?, 5, ?, ?, 'COMMITTED', 8)", + transitionId, + identity.tenantId(), + identity.playableStateNamespaceId(), + identity.characterId(), + bindingRef, + accountIndexFence, + reservationId); + } + + private static boolean statusesRemainPending(DSLContext dsl) { + Long operations = + dsl.fetchOne("SELECT count(*) FROM game_session_canonical_issuer_bootstrap_member_operation") + .get(0, Long.class); + Long pending = + dsl.fetchOne( + "SELECT count(*) FROM game_session_canonical_issuer_bootstrap_member_operation" + + " WHERE member_status = 'PENDING_PHYSICAL_PROOF'") + .get(0, Long.class); + return operations.equals(pending); + } + + private static void establishActualLegacyDisposition(DSLContext dsl) { + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); + UUID cohortId = UUID.randomUUID(); + UUID writerFence = UUID.randomUUID(); + var storageIdentity = + new CanonicalGameplayLegacyMigrationStorageIdentity( + "controlled-cluster-uid", + "controlled-namespace-uid", + "controlled-producer-pod-uid", + "controlled-container-id", + "controlled-node-uid", + "123456789", + 42L, + "controlled-postgres-volume-uid", + "controlled-redis-run-id", + "controlled-redis-volume-uid"); + var fencedCohort = + new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { + @Override + public UUID cohortId() { + return cohortId; + } + + @Override + public UUID legacyWriterFence() { + return writerFence; + } + + @Override + public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + return storageIdentity; + } + + @Override + public void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity expected) { + if (!storageIdentity.equals(expected)) { + throw new IllegalStateException("Controlled test storage identity changed"); + } + } + }; + new CanonicalGameplayLegacyMigrationOwner( + migration, + inventory, + () -> fencedCohort, + ignored -> + new CanonicalGameplayLegacyMigrationSourceSnapshot( + EnumSet.of( + Family.TENANT_SESSION_CONTEXT, + Family.SESSION_ALIAS_CONTEXT, + Family.GAMEPLAY_IDENTITY_CONTEXT, + Family.GAMEPLAY_NAME_CONTEXT, + Family.MOVEMENT_EFFECT, + Family.DURABLE_EFFECT), + List.of()), + new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { + @Override + public void rebuildExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + CanonicalGameplayLegacyMigrationSourceSnapshot source, + net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventorySnapshot + canonical) { + assertThat(canonical.bindings()).isEmpty(); + assertThat(canonical.reservations()).isEmpty(); + } + + @Override + public CanonicalGameplayLegacyMigrationReadback readBackExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventorySnapshot + canonical) { + assertThat(canonical.bindings()).isEmpty(); + return new CanonicalGameplayLegacyMigrationReadback( + List.of(), List.of(), List.of(), List.of()); + } + }) + .migrate(); + } + + private TestSchema newTestSchemaAtVersion(String prefix, String version) { + String schema = prefix + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion(version)) + .load() + .migrate(); + return new TestSchema(schema, dataSource, DSL.using(dataSource, SQLDialect.POSTGRES)); + } + + private static void migrateRemaining(TestSchema schema) { + Flyway.configure() + .dataSource(schema.dataSource()) + .schemas(schema.schema()) + .defaultSchema(schema.schema()) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + } + + private DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + String jdbcUrl = POSTGRES.getJdbcUrl(); + dataSource.setUrl(jdbcUrl + (jdbcUrl.contains("?") ? "&" : "?") + "currentSchema=" + schema); + dataSource.setUsername(POSTGRES.getUsername()); + dataSource.setPassword(POSTGRES.getPassword()); + return dataSource; + } + + private void dropSchema(String schema) { + try (Connection connection = dataSource("public").getConnection()) { + DSL.using(connection, SQLDialect.POSTGRES).execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } catch (SQLException failure) { + throw new IllegalStateException("Could not drop the owned issuer physical test schema", failure); + } + } + + private static RedisClient createRedisClient(String username, String password) { + RedisURI.Builder builder = RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(6379)); + if (username != null) builder.withAuthentication(username, password); + RedisURI uri = builder.build(); + uri.setTimeout(Duration.ofSeconds(5)); + RedisClient client = RedisClient.create(uri); + client.setOptions( + ClientOptions.builder().autoReconnect(false).protocolVersion(io.lettuce.core.protocol.ProtocolVersion.RESP2).build()); + return client; + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private record Fixture( + TestSchema schema, + CanonicalGameplayBindingIdentity activeBinding, + CanonicalGameplayIssuerLayoutBootstrapIntent intent, + UUID requestId, + CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + currentAccountCheckpoint, + BigInteger partitionId) { + DSLContext dsl() { + return schema.dsl(); + } + } + + private record TestSchema(String schema, DriverManagerDataSource dataSource, DSLContext dsl) {} +} 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 c8bcc5c681..539de03fac 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 @@ -107,7 +107,52 @@ void populatedPendingIntentRetainsCompleteCohortAndBothCoverageTuplesAcrossConcu List inventoryClockBefore = rowImages(testSchema.dsl(), "game_session_canonical_binding_inventory_clock"); List migrationHistoryBefore = rowImages(testSchema.dsl(), "flyway_schema_history"); + List retainedSourceTables = + List.of( + "game_session_canonical_gameplay_binding_inventory", + "game_session_canonical_issuer_partition_reservation", + "game_session_canonical_issuer_layout_bootstrap_intent", + "game_session_canonical_issuer_layout_bootstrap_control", + "game_session_canonical_issuer_layout_bootstrap_cohort_row", + "game_session_canonical_binding_transition", + "game_session_canonical_binding_account_index_obligation", + "game_session_canonical_binding_issuer_index_obligation", + "game_session_canonical_binding_region_bridge_obligation", + "game_session_canonical_binding_inventory_clock"); + List> retainedRowsWithXminBefore = + retainedSourceTables.stream() + .map(table -> rowImagesWithXmin(testSchema.dsl(), table)) + .toList(); + + migrateThrough1031(testSchema); + List migrationHistoryAfter1031 = rowImages(testSchema.dsl(), "flyway_schema_history"); + assertThat(migrationHistoryAfter1031) + .hasSize(migrationHistoryBefore.size() + 1) + .containsAll(migrationHistoryBefore); + assertThat( + testSchema + .dsl() + .fetchSingle("SELECT script FROM flyway_schema_history WHERE version = '1031'") + .get(0, String.class)) + .isEqualTo("V1031__canonical_issuer_partition_build_plan.sql"); + assertThat( + retainedSourceTables.stream() + .map(table -> rowImagesWithXmin(testSchema.dsl(), table)) + .toList()) + .isEqualTo(retainedRowsWithXminBefore); + migrateRemaining(testSchema); + List migrationHistoryAfterCurrent = + rowImages(testSchema.dsl(), "flyway_schema_history"); + assertThat(migrationHistoryAfterCurrent) + .hasSize(migrationHistoryAfter1031.size() + 1) + .containsAll(migrationHistoryAfter1031); + assertThat( + testSchema + .dsl() + .fetchSingle("SELECT script FROM flyway_schema_history WHERE version = '1032'") + .get(0, String.class)) + .isEqualTo("V1032__canonical_issuer_bootstrap_member_operation.sql"); var ready = new CountDownLatch(2); var start = new CountDownLatch(1); @@ -232,9 +277,12 @@ void populatedPendingIntentRetainsCompleteCohortAndBothCoverageTuplesAcrossConcu assertThat(rowImages(testSchema.dsl(), "game_session_canonical_binding_inventory_clock")) .containsExactlyElementsOf(inventoryClockBefore); List migrationHistoryAfter = rowImages(testSchema.dsl(), "flyway_schema_history"); - assertThat(migrationHistoryAfter) - .hasSize(migrationHistoryBefore.size() + 1) - .containsAll(migrationHistoryBefore); + assertThat(migrationHistoryAfter).containsExactlyElementsOf(migrationHistoryAfterCurrent); + assertThat( + retainedSourceTables.stream() + .map(table -> rowImagesWithXmin(testSchema.dsl(), table)) + .toList()) + .isEqualTo(retainedRowsWithXminBefore); } finally { executor.shutdownNow(); dropSchema(testSchema.schema()); @@ -320,9 +368,9 @@ void immutableBuildArtifactsRejectTruncateAndRetainTheirCompletePostimage() { + " game_session_canonical_issuer_partition_build_plan," + " game_session_canonical_issuer_partition_build_cohort_row," + " game_session_canonical_issuer_partition_build_member_work," - + " game_session_canonical_issuer_partition_build_blocker")) + + " game_session_canonical_issuer_partition_build_blocker CASCADE")) .isInstanceOf(DataAccessException.class) - .hasMessageContaining("issuer partition build preparation artifacts are immutable"); + .hasMessageContaining("artifacts are immutable"); assertThat(rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_build_plan")) .containsExactlyElementsOf(planBefore); @@ -1208,6 +1256,18 @@ private static TestSchema newTestSchemaAtVersion(String prefix, String version) return new TestSchema(schema, dataSource, DSL.using(dataSource, SQLDialect.POSTGRES)); } + private static void migrateThrough1031(TestSchema testSchema) { + Flyway.configure() + .dataSource(testSchema.dataSource()) + .schemas(testSchema.schema()) + .defaultSchema(testSchema.schema()) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("1031")) + .load() + .migrate(); + } + private static void migrateRemaining(TestSchema testSchema) { Flyway.configure() .dataSource(testSchema.dataSource()) @@ -1317,6 +1377,14 @@ private static List rowImages(DSLContext dsl, String tableName) { .getValues("row_image", String.class); } + private static List rowImagesWithXmin(DSLContext dsl, String tableName) { + return dsl.fetch( + "SELECT xmin::text || ':' || to_jsonb(retained_row)::text AS row_image FROM " + + tableName + + " retained_row ORDER BY to_jsonb(retained_row)::text, xmin::text") + .getValues("row_image", String.class); + } + private static void dropSchema(String schema) { try (Connection connection = dataSource("public").getConnection()) { DSL.using(connection, SQLDialect.POSTGRES) From ffd6edde966df557387c4c8d5c5931aaa32538d3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 26 Oct 2026 15:39:44 +1300 Subject: [PATCH 05/34] Qualify issuer member operation SQL producer --- ...ameplayIssuerBootstrapMemberOperation.java | 239 +++++ ...uerBootstrapMemberOperationRepository.java | 745 ++++++++++++++ ...lGameplayIssuerBootstrapPartitionWork.java | 98 ++ ...ameplayIssuerPartitionBuildRepository.java | 186 ++++ ...ical_issuer_bootstrap_member_operation.sql | 254 +++++ ...berOperationRepositoryIntegrationTest.java | 952 ++++++++++++++++++ ...rtitionBuildRepositoryIntegrationTest.java | 78 +- 7 files changed, 2547 insertions(+), 5 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperation.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionWork.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V1032__canonical_issuer_bootstrap_member_operation.sql create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperation.java new file mode 100644 index 0000000000..85dba352fb --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperation.java @@ -0,0 +1,239 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; + +/** + * Immutable SQL-issued identity and exact v2 member value for one initial-bootstrap work item. + * + *

{@link Status#PENDING_PHYSICAL_PROOF} is preparation for the next physical owner. The local + * member generation in this record is not an issuer-wide coverage acknowledgement or proof that a + * Redis member was written. + */ +final class CanonicalGameplayIssuerBootstrapMemberOperation { + enum Status { + PENDING_PHYSICAL_PROOF + } + + private final UUID operationId; + private final java.math.BigInteger operationFence; + private final java.math.BigInteger localMemberGeneration; + private final UUID bootstrapOperationId; + private final UUID bootstrapRequestId; + private final UUID buildOperationId; + private final String buildPlanDigest; + private final long workOrdinal; + private final UUID preparationOperationId; + private final UUID preparationFenceId; + private final long reservationSourceRowOrdinal; + private final String reservationSourceRowDigest; + private final CanonicalGameplayIssuerMemberV2Value memberValue; + private final CanonicalGameplayBindingInventoryEntry.Lifecycle bindingLifecycle; + private final boolean expectedBindingPresent; + private final boolean countsTowardCapacity; + private final byte[] exactMemberValueBytes; + private final String memberValueDigest; + private final Status status; + + CanonicalGameplayIssuerBootstrapMemberOperation( + UUID operationId, + java.math.BigInteger operationFence, + java.math.BigInteger localMemberGeneration, + UUID bootstrapOperationId, + UUID bootstrapRequestId, + UUID buildOperationId, + String buildPlanDigest, + long workOrdinal, + UUID preparationOperationId, + UUID preparationFenceId, + long reservationSourceRowOrdinal, + String reservationSourceRowDigest, + CanonicalGameplayIssuerMemberV2Value memberValue, + CanonicalGameplayBindingInventoryEntry.Lifecycle bindingLifecycle, + boolean expectedBindingPresent, + boolean countsTowardCapacity, + byte[] exactMemberValueBytes, + String memberValueDigest, + Status status) { + this.operationId = requireNonNil(operationId, "operationId"); + this.operationFence = requirePositive(operationFence, "operationFence"); + this.localMemberGeneration = requirePositive(localMemberGeneration, "localMemberGeneration"); + this.bootstrapOperationId = requireNonNil(bootstrapOperationId, "bootstrapOperationId"); + this.bootstrapRequestId = requireNonNil(bootstrapRequestId, "bootstrapRequestId"); + this.buildOperationId = requireNonNil(buildOperationId, "buildOperationId"); + this.buildPlanDigest = requireDigest(buildPlanDigest, "buildPlanDigest"); + this.workOrdinal = requireNonNegative(workOrdinal, "workOrdinal"); + this.preparationOperationId = requireNonNil(preparationOperationId, "preparationOperationId"); + this.preparationFenceId = requireNonNil(preparationFenceId, "preparationFenceId"); + this.reservationSourceRowOrdinal = + requireNonNegative(reservationSourceRowOrdinal, "reservationSourceRowOrdinal"); + this.reservationSourceRowDigest = + requireDigest(reservationSourceRowDigest, "reservationSourceRowDigest"); + this.memberValue = Objects.requireNonNull(memberValue, "memberValue"); + this.bindingLifecycle = bindingLifecycle; + this.expectedBindingPresent = expectedBindingPresent; + this.countsTowardCapacity = countsTowardCapacity; + this.exactMemberValueBytes = + Objects.requireNonNull(exactMemberValueBytes, "exactMemberValueBytes").clone(); + if (this.exactMemberValueBytes.length == 0 + || this.exactMemberValueBytes.length + > CanonicalGameplayIssuerMemberV2Codec.MAX_VALUE_BYTES) { + throw new IllegalArgumentException( + "Exact issuer member value bytes are outside the local limit"); + } + this.memberValueDigest = requireDigest(memberValueDigest, "memberValueDigest"); + this.status = Objects.requireNonNull(status, "status"); + if (bootstrapOperationId.equals(bootstrapRequestId) + || buildOperationId.equals(bootstrapOperationId) + || buildOperationId.equals(bootstrapRequestId) + || operationId.equals(bootstrapOperationId) + || operationId.equals(bootstrapRequestId) + || operationId.equals(buildOperationId) + || operationId.equals(preparationOperationId) + || operationId.equals(preparationFenceId) + || localMemberGeneration.compareTo(operationFence) <= 0) { + throw new IllegalArgumentException( + "Issued local member identity must be distinct from preparation"); + } + if (!operationId.equals(memberValue.memberOperation().operationId()) + || !operationFence.equals(memberValue.memberOperation().operationFence()) + || !localMemberGeneration.equals(memberValue.memberOperation().coverageGeneration()) + || !bootstrapOperationId.equals(memberValue.anchor().issuerCoverageOperationId()) + || !Arrays.equals( + this.exactMemberValueBytes, CanonicalGameplayIssuerMemberV2Codec.encode(memberValue)) + || !memberValueDigest.equals( + CanonicalGameplayIssuerMemberV2Codec.sha256(this.exactMemberValueBytes))) { + throw new IllegalArgumentException( + "Issued operation fields differ from its exact schema-v2 member value"); + } + CanonicalIssuerPartitionReservation originalReservation = memberValue.reservation(); + boolean lifecycleCounts = + originalReservation.lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED; + boolean lifecycleHasBinding = + bindingLifecycle == CanonicalGameplayBindingInventoryEntry.Lifecycle.ACTIVE + || bindingLifecycle == CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL; + if (countsTowardCapacity != lifecycleCounts + || expectedBindingPresent != lifecycleHasBinding + || (expectedBindingPresent && bindingLifecycle == null)) { + throw new IllegalArgumentException( + "Physical binding and capacity actions must match the frozen SQL source lifecycle"); + } + CanonicalGameplayIssuerMemberV2Value decoded = + CanonicalGameplayIssuerMemberV2Codec.decode(this.exactMemberValueBytes); + if (!memberValue.equals(decoded)) { + throw new IllegalArgumentException( + "Exact schema-v2 member bytes decode to a different value"); + } + } + + UUID operationId() { + return operationId; + } + + BigInteger operationFence() { + return operationFence; + } + + BigInteger localMemberGeneration() { + return localMemberGeneration; + } + + UUID bootstrapOperationId() { + return bootstrapOperationId; + } + + UUID bootstrapRequestId() { + return bootstrapRequestId; + } + + UUID buildOperationId() { + return buildOperationId; + } + + String buildPlanDigest() { + return buildPlanDigest; + } + + long workOrdinal() { + return workOrdinal; + } + + UUID preparationOperationId() { + return preparationOperationId; + } + + UUID preparationFenceId() { + return preparationFenceId; + } + + long reservationSourceRowOrdinal() { + return reservationSourceRowOrdinal; + } + + String reservationSourceRowDigest() { + return reservationSourceRowDigest; + } + + CanonicalGameplayIssuerMemberV2Value memberValue() { + return memberValue; + } + + /** Full closed v2 value the physical owner must compare; not a coverage acknowledgement. */ + CanonicalGameplayIssuerMemberV2Value expectedMemberValue() { + return memberValue; + } + + CanonicalGameplayBindingInventoryEntry.Lifecycle bindingLifecycle() { + return bindingLifecycle; + } + + boolean expectedBindingPresent() { + return expectedBindingPresent; + } + + boolean countsTowardCapacity() { + return countsTowardCapacity; + } + + byte[] exactMemberValueBytes() { + return exactMemberValueBytes.clone(); + } + + String memberValueDigest() { + return memberValueDigest; + } + + Status status() { + return status; + } + + private static UUID requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException(name + " must not be nil"); + return value; + } + + private static BigInteger requirePositive(BigInteger value, String name) { + Objects.requireNonNull(value, name); + if (value.signum() <= 0) throw new IllegalArgumentException(name + " must be positive"); + return value; + } + + private static long requireNonNegative(long value, String name) { + if (value < 0) throw new IllegalArgumentException(name + " must not be negative"); + return value; + } + + private static String requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(name + " must be canonical SHA-256"); + } + return value; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepository.java new file mode 100644 index 0000000000..1ac5aa5d38 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepository.java @@ -0,0 +1,745 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Local SQL owner for issuing one immutable member operation from an exact prepared initial + * bootstrap work item. It does not execute physical Redis work or record proof completion. + */ +final class CanonicalGameplayIssuerBootstrapMemberOperationRepository { + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String COUNTER = "game_session_canonical_issuer_bootstrap_member_op_counter"; + private static final String OPERATION = + "game_session_canonical_issuer_bootstrap_member_operation"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final DSLContext dsl; + + CanonicalGameplayIssuerBootstrapMemberOperationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Begins or resumes one exact planned member work item. The current Account checkpoint and stable + * storage-incarnation inputs are explicitly controlled local collaborators: this method checks + * them against the persisted bootstrap tuple but does not authenticate their authority. + */ + CanonicalGameplayIssuerBootstrapMemberOperation beginOrResumePendingPhysicalProof( + UUID bootstrapOperationId, + UUID bootstrapRequestId, + long workOrdinal, + CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + currentAccountCheckpoint, + TrustedStableIncarnation stableIncarnation) { + requireNonNil(bootstrapOperationId, "bootstrapOperationId"); + requireNonNil(bootstrapRequestId, "bootstrapRequestId"); + if (workOrdinal < 0) throw new IllegalArgumentException("workOrdinal must not be negative"); + Objects.requireNonNull(currentAccountCheckpoint, "currentAccountCheckpoint"); + Objects.requireNonNull(stableIncarnation, "stableIncarnation"); + requireNoAmbientTransaction(); + return dsl.transactionResult( + configuration -> + beginOrResumeInTransaction( + org.jooq.impl.DSL.using(configuration), + bootstrapOperationId, + bootstrapRequestId, + workOrdinal, + currentAccountCheckpoint, + stableIncarnation)); + } + + /** + * Qualifies and issues the complete member-operation set for one exact partition in one SQL + * transaction. The partition id selects from the persisted plan; no member list is accepted. + */ + CanonicalGameplayIssuerBootstrapPartitionWork preparePartitionWork( + UUID bootstrapOperationId, + UUID bootstrapRequestId, + BigInteger partitionId, + CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + currentAccountCheckpoint, + TrustedStableIncarnation stableIncarnation) { + requireNonNil(bootstrapOperationId, "bootstrapOperationId"); + requireNonNil(bootstrapRequestId, "bootstrapRequestId"); + Objects.requireNonNull(partitionId, "partitionId"); + Objects.requireNonNull(currentAccountCheckpoint, "currentAccountCheckpoint"); + Objects.requireNonNull(stableIncarnation, "stableIncarnation"); + requireNoAmbientTransaction(); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + CanonicalGameplayIssuerPartitionBuildRepository buildRepository = + new CanonicalGameplayIssuerPartitionBuildRepository(transaction); + CanonicalGameplayIssuerPartitionBuildPlan plan = + buildRepository.readPreparedPlanInTransaction( + transaction, bootstrapOperationId, bootstrapRequestId); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); + if (partitionId.signum() < 0 + || partitionId.compareTo(intent.layoutDescriptor().partitionCount()) >= 0) { + throw conflict("Requested partition is outside the exact prepared bootstrap layout"); + } + requireCurrentAccountCheckpoint(currentAccountCheckpoint, intent.sourceCheckpoint()); + CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation = stableIncarnation.value(); + List operations = new ArrayList<>(); + for (CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work : plan.memberWorks()) { + if (!work.plannedPartitionId().equals(partitionId)) continue; + CanonicalGameplayIssuerPartitionBuildRepository.PreparedMemberWork prepared = + buildRepository.readPreparedMemberWorkFromVerifiedPlan(plan, work.workOrdinal()); + operations.add( + beginOrResumePreparedInTransaction( + transaction, prepared, currentAccountCheckpoint, incarnation)); + } + return new CanonicalGameplayIssuerBootstrapPartitionWork( + plan, partitionId, operations, incarnation); + }); + } + + private static CanonicalGameplayIssuerBootstrapMemberOperation beginOrResumeInTransaction( + DSLContext transaction, + UUID bootstrapOperationId, + UUID bootstrapRequestId, + long workOrdinal, + CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + currentAccountCheckpoint, + TrustedStableIncarnation stableIncarnation) { + CanonicalGameplayIssuerPartitionBuildRepository.PreparedMemberWork prepared = + new CanonicalGameplayIssuerPartitionBuildRepository(transaction) + .readPreparedMemberWorkInTransaction( + transaction, bootstrapOperationId, bootstrapRequestId, workOrdinal); + return beginOrResumePreparedInTransaction( + transaction, prepared, currentAccountCheckpoint, stableIncarnation.value()); + } + + private static CanonicalGameplayIssuerBootstrapMemberOperation beginOrResumePreparedInTransaction( + DSLContext transaction, + CanonicalGameplayIssuerPartitionBuildRepository.PreparedMemberWork prepared, + CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + currentAccountCheckpoint, + CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation) { + CanonicalGameplayIssuerPartitionBuildPlan plan = prepared.plan(); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work = prepared.work(); + requireCurrentAccountCheckpoint(currentAccountCheckpoint, intent.sourceCheckpoint()); + + Record existing = + transaction.fetchOne( + "SELECT * FROM " + + OPERATION + + " WHERE issuer_id = ? AND bootstrap_operation_id = ? AND work_ordinal = ? FOR UPDATE", + ISSUER, + intent.operationId(), + work.workOrdinal()); + if (existing != null) { + return loadAndRequireExactOperation(existing, prepared, incarnation); + } + + IssuedCounters counters = allocateLocalCounters(transaction, prepared); + UUID operationId = nextOperationId(transaction, prepared); + CanonicalGameplayIssuerMemberV2Value memberValue = + createMemberValue( + prepared, operationId, counters.operationFence(), counters.generation(), incarnation); + byte[] memberValueBytes = CanonicalGameplayIssuerMemberV2Codec.encode(memberValue); + String memberValueDigest = CanonicalGameplayIssuerMemberV2Codec.sha256(memberValueBytes); + insertOperation( + transaction, prepared, operationId, counters, memberValueBytes, memberValueDigest); + Record saved = + transaction.fetchOne( + "SELECT * FROM " + + OPERATION + + " WHERE issuer_id = ? AND bootstrap_operation_id = ? AND work_ordinal = ? FOR UPDATE", + ISSUER, + intent.operationId(), + work.workOrdinal()); + if (saved == null) throw conflict("Persisted bootstrap member operation is unreadable"); + CanonicalGameplayIssuerBootstrapMemberOperation result = + loadAndRequireExactOperation(saved, prepared, incarnation); + if (!result.operationId().equals(operationId) + || !result.operationFence().equals(counters.operationFence()) + || !result.localMemberGeneration().equals(counters.generation()) + || !Arrays.equals(result.exactMemberValueBytes(), memberValueBytes)) { + throw conflict("Persisted member operation differs from the SQL owner-issued value"); + } + return result; + } + + private static void requireCurrentAccountCheckpoint( + CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint current, + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint persisted) { + if (!ISSUER.equals(current.issuerId()) + || !ISSUER.equals(persisted.issuerId()) + || !current.issuerAuthGeneration().equals(persisted.issuerAuthGeneration()) + || !Arrays.equals(current.checkpointBytes(), persisted.exactCheckpointBytes()) + || !Arrays.equals(current.latestEventBytes(), persisted.latestIssuerEventBytes())) { + throw conflict( + "Controlled current Account checkpoint differs from the exact pending bootstrap source"); + } + } + + private static CanonicalGameplayIssuerBootstrapMemberOperation loadAndRequireExactOperation( + Record row, + CanonicalGameplayIssuerPartitionBuildRepository.PreparedMemberWork prepared, + CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation) { + CanonicalGameplayIssuerPartitionBuildPlan plan = prepared.plan(); + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work = prepared.work(); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); + CanonicalIssuerPartitionReservation original = prepared.originalReservation(); + byte[] bytes = requireBytes(row, "member_value_bytes"); + String digest = requireText(row, "member_value_digest"); + if (!digest.equals(CanonicalGameplayIssuerMemberV2Codec.sha256(bytes))) { + throw conflict("Persisted pending member value digest differs from its exact bytes"); + } + CanonicalGameplayIssuerMemberV2Value value; + try { + value = CanonicalGameplayIssuerMemberV2Codec.decode(bytes); + } catch (RuntimeException malformed) { + throw conflict("Persisted pending member value is not canonical schema v2"); + } + UUID operationId = requireUuid(row, "member_operation_id"); + BigInteger operationFence = readPositive(row, "operation_fence"); + BigInteger generation = readPositive(row, "local_member_generation"); + UUID bootstrapOperationId = requireUuid(row, "bootstrap_operation_id"); + UUID bootstrapRequestId = requireUuid(row, "bootstrap_request_id"); + UUID buildOperationId = requireUuid(row, "build_operation_id"); + String planDigest = requireText(row, "build_plan_digest"); + long workOrdinal = requireNonNegativeLong(row, "work_ordinal"); + UUID preparationOperationId = requireUuid(row, "preparation_operation_id"); + UUID preparationFenceId = requireUuid(row, "preparation_fence_id"); + long sourceOrdinal = requireNonNegativeLong(row, "reservation_source_row_ordinal"); + String sourceDigest = requireText(row, "reservation_source_row_digest"); + Long bindingSourceOrdinal = row.get("binding_source_row_ordinal", Long.class); + String bindingSourceDigest = row.get("binding_source_row_digest", String.class); + String bindingLifecycleText = row.get("binding_lifecycle", String.class); + CanonicalGameplayBindingInventoryEntry.Lifecycle bindingLifecycle = null; + if (bindingLifecycleText != null) { + try { + bindingLifecycle = + CanonicalGameplayBindingInventoryEntry.Lifecycle.valueOf(bindingLifecycleText); + } catch (RuntimeException malformed) { + throw conflict("Persisted pending operation has an unsupported binding lifecycle"); + } + } + boolean expectedBindingPresent = + Objects.requireNonNull(row.get("expected_binding_present", Boolean.class)); + boolean countsTowardCapacity = + Objects.requireNonNull(row.get("counts_toward_capacity", Boolean.class)); + String status = requireText(row, "member_status"); + BindingAction action = bindingAction(prepared); + + requireSameRowLinkage( + row, + prepared, + plan, + work, + original, + intent, + operationId, + operationFence, + generation, + bootstrapOperationId, + bootstrapRequestId, + buildOperationId, + planDigest, + workOrdinal, + preparationOperationId, + preparationFenceId, + sourceOrdinal, + sourceDigest, + bindingSourceOrdinal, + bindingSourceDigest, + bindingLifecycleText, + action, + expectedBindingPresent, + countsTowardCapacity, + status, + value); + CanonicalGameplayIssuerMemberV2Value expectedValue = + createMemberValue(prepared, operationId, operationFence, generation, incarnation); + if (!expectedValue.equals(value) + || !Arrays.equals(bytes, CanonicalGameplayIssuerMemberV2Codec.encode(expectedValue))) { + throw conflict("Pending member operation retry changed an exact schema-v2 field or tuple"); + } + try { + return new CanonicalGameplayIssuerBootstrapMemberOperation( + operationId, + operationFence, + generation, + bootstrapOperationId, + bootstrapRequestId, + buildOperationId, + planDigest, + workOrdinal, + preparationOperationId, + preparationFenceId, + sourceOrdinal, + sourceDigest, + value, + bindingLifecycle, + expectedBindingPresent, + countsTowardCapacity, + bytes, + digest, + CanonicalGameplayIssuerBootstrapMemberOperation.Status.valueOf(status)); + } catch (RuntimeException malformed) { + throw conflict("Persisted bootstrap member operation metadata is malformed"); + } + } + + private static void requireSameRowLinkage( + Record row, + CanonicalGameplayIssuerPartitionBuildRepository.PreparedMemberWork prepared, + CanonicalGameplayIssuerPartitionBuildPlan plan, + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work, + CanonicalIssuerPartitionReservation original, + CanonicalGameplayIssuerLayoutBootstrapIntent intent, + UUID operationId, + BigInteger operationFence, + BigInteger generation, + UUID bootstrapOperationId, + UUID bootstrapRequestId, + UUID buildOperationId, + String planDigest, + long workOrdinal, + UUID preparationOperationId, + UUID preparationFenceId, + long sourceOrdinal, + String sourceDigest, + Long bindingSourceOrdinal, + String bindingSourceDigest, + String bindingLifecycle, + BindingAction action, + boolean expectedBindingPresent, + boolean countsTowardCapacity, + String status, + CanonicalGameplayIssuerMemberV2Value value) { + if (!ISSUER.equals(requireText(row, "issuer_id")) + || !bootstrapOperationId.equals(intent.operationId()) + || !bootstrapRequestId.equals(intent.requestId()) + || !buildOperationId.equals(plan.buildOperationId()) + || !planDigest.equals(plan.planDigest()) + || workOrdinal != work.workOrdinal() + || !preparationOperationId.equals(work.memberOperationId()) + || !preparationFenceId.equals(work.memberPreparationFenceId()) + || sourceOrdinal != work.reservationSourceRowOrdinal() + || !sourceDigest.equals(work.reservationSourceRowDigest()) + || !Objects.equals(bindingSourceOrdinal, work.bindingSourceRowOrdinal()) + || !Objects.equals(bindingSourceDigest, work.bindingSourceRowDigest()) + || !Objects.equals( + bindingLifecycle, + prepared.bindingLifecycle() == null ? null : prepared.bindingLifecycle().name()) + || expectedBindingPresent != action.expectedBindingPresent() + || countsTowardCapacity != work.countsTowardCapacity() + || !original.lifecycle().name().equals(requireText(row, "reservation_lifecycle")) + || !original.reservationId().equals(row.get("reservation_id", UUID.class)) + || !original + .issuerCoverageOperationId() + .equals(row.get("original_issuer_coverage_operation_id", UUID.class)) + || !original + .issuerCoverageOperationFence() + .equals(readPositive(row, "original_issuer_coverage_operation_fence")) + || !original.coverageFence().equals(readPositive(row, "original_coverage_fence")) + || !original + .inventorySnapshotRevision() + .equals(readPositive(row, "original_inventory_snapshot_revision")) + || !intent.operationId().equals(row.get("bootstrap_anchor_operation_id", UUID.class)) + || !intent.operationFence().equals(readPositive(row, "bootstrap_anchor_operation_fence")) + || !intent.coverageFence().equals(readPositive(row, "bootstrap_anchor_coverage_fence")) + || !intent + .inventorySnapshotRevision() + .equals(readPositive(row, "bootstrap_anchor_inventory_snapshot_revision")) + || !"PENDING_PHYSICAL_PROOF".equals(status) + || row.get("member_schema_version", Short.class) == null + || row.get("member_schema_version", Short.class) + != CanonicalGameplayIssuerMemberV2Value.SCHEMA_VERSION + || !operationId.equals(value.memberOperation().operationId()) + || !operationFence.equals(value.memberOperation().operationFence()) + || !generation.equals(value.memberOperation().coverageGeneration())) { + throw conflict("Persisted member operation linkage differs from its exact prepared work"); + } + } + + private static CanonicalGameplayIssuerMemberV2Value createMemberValue( + CanonicalGameplayIssuerPartitionBuildRepository.PreparedMemberWork prepared, + UUID operationId, + BigInteger operationFence, + BigInteger generation, + CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation) { + CanonicalGameplayIssuerPartitionBuildPlan plan = prepared.plan(); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); + return new CanonicalGameplayIssuerMemberV2Value( + prepared.originalReservation().owner(), + prepared.originalReservation().bindingGeneration(), + prepared.originalReservation(), + new CanonicalGameplayIssuerMemberV2Value.Anchor( + intent.operationId(), + intent.operationFence(), + intent.coverageFence(), + intent.inventorySnapshotRevision()), + new CanonicalGameplayIssuerMemberV2Value.LocalMemberOperation( + operationId, operationFence, generation), + intent.controlEpoch(), + intent.layoutDescriptor(), + intent.sourceCheckpoint(), + incarnation); + } + + private static BindingAction bindingAction( + CanonicalGameplayIssuerPartitionBuildRepository.PreparedMemberWork prepared) { + CanonicalIssuerPartitionReservation.Lifecycle reservationLifecycle = + prepared.originalReservation().lifecycle(); + CanonicalGameplayBindingInventoryEntry.Lifecycle bindingLifecycle = prepared.bindingLifecycle(); + if (bindingLifecycle == null) { + if (reservationLifecycle == CanonicalIssuerPartitionReservation.Lifecycle.RESERVED + || reservationLifecycle == CanonicalIssuerPartitionReservation.Lifecycle.RELEASED) { + return new BindingAction(false); + } + throw conflict( + "A BOUND or RELEASE_PENDING reservation without a linked binding cannot qualify physical work"); + } + return switch (bindingLifecycle) { + case CANDIDATE_PREPARED -> { + if (reservationLifecycle != CanonicalIssuerPartitionReservation.Lifecycle.RESERVED) { + throw conflict("CANDIDATE_PREPARED binding must retain its exact RESERVED reservation"); + } + yield new BindingAction(false); + } + case PROVISIONAL -> { + if (reservationLifecycle != CanonicalIssuerPartitionReservation.Lifecycle.RESERVED) { + throw conflict("PROVISIONAL binding must retain its exact RESERVED reservation"); + } + yield new BindingAction(true); + } + case ACTIVE -> { + if (reservationLifecycle != CanonicalIssuerPartitionReservation.Lifecycle.BOUND + && reservationLifecycle + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING) { + throw conflict( + "ACTIVE binding must retain its exact BOUND or RELEASE_PENDING reservation"); + } + yield new BindingAction(true); + } + case TERMINAL -> { + if (reservationLifecycle != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED) { + throw conflict("TERMINAL binding must retain its exact RELEASED reservation"); + } + yield new BindingAction(false); + } + case TERMINAL_UNRESOLVED -> + throw conflict("TERMINAL_UNRESOLVED source cannot qualify initial physical member work"); + }; + } + + private static IssuedCounters allocateLocalCounters( + DSLContext transaction, + CanonicalGameplayIssuerPartitionBuildRepository.PreparedMemberWork prepared) { + Record counter = + transaction.fetchOne( + "SELECT * FROM " + COUNTER + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (counter == null) { + Record priorOperation = + transaction.fetchOne( + "SELECT 1 FROM " + OPERATION + " WHERE issuer_id = ? LIMIT 1", ISSUER); + if (priorOperation != null) { + throw conflict("Issuer-local member-operation counter is missing after prior issuance"); + } + transaction.execute( + "INSERT INTO " + + COUNTER + + " (issuer_id, last_issued_operation_fence, last_issued_member_generation, counter_version)" + + " VALUES (?, 0, 0, 0) ON CONFLICT (issuer_id) DO NOTHING", + ISSUER); + counter = + transaction.fetchOne( + "SELECT * FROM " + COUNTER + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (counter == null) + throw conflict("Issuer-local member-operation counter could not initialize"); + } + BigInteger previousFence = readNonNegative(counter, "last_issued_operation_fence"); + BigInteger previousGeneration = readNonNegative(counter, "last_issued_member_generation"); + long previousVersion = Objects.requireNonNull(counter.get("counter_version", Long.class)); + if (previousVersion < 0 + || (previousVersion == 0 + && (previousFence.signum() != 0 || previousGeneration.signum() != 0)) + || (previousVersion > 0 + && (!previousFence.add(BigInteger.ONE).equals(previousGeneration) + || previousFence.signum() <= 0))) { + throw conflict("Issuer-local member-operation counter state is malformed"); + } + + CanonicalGameplayIssuerPartitionBuildPlan plan = prepared.plan(); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); + CanonicalIssuerPartitionReservation original = prepared.originalReservation(); + BigInteger qualifiedSeed = + max( + intent.controlEpoch(), + intent.operationFence(), + intent.coverageFence(), + intent.inventorySnapshotRevision(), + original.issuerCoverageOperationFence(), + original.coverageFence(), + original.inventorySnapshotRevision(), + original.inventoryRevision(), + previousFence, + previousGeneration); + BigInteger newFence = qualifiedSeed.add(BigInteger.ONE); + BigInteger newGeneration = newFence.add(BigInteger.ONE); + requireCounterLimit(newFence, "operationFence"); + requireCounterLimit(newGeneration, "localMemberGeneration"); + long nextVersion; + try { + nextVersion = Math.addExact(previousVersion, 1L); + } catch (ArithmeticException overflow) { + throw conflict("Issuer-local member-operation counter version is exhausted"); + } + Record updated = + transaction.fetchOne( + "UPDATE " + + COUNTER + + " SET last_issued_operation_fence = ?, last_issued_member_generation = ?, counter_version = ?" + + " WHERE issuer_id = ? AND last_issued_operation_fence = ?" + + " AND last_issued_member_generation = ? AND counter_version = ?" + + " RETURNING issuer_id", + decimal(newFence), + decimal(newGeneration), + nextVersion, + ISSUER, + decimal(previousFence), + decimal(previousGeneration), + previousVersion); + if (updated == null) + throw conflict("Issuer-local member-operation counter compare-and-set lost"); + return new IssuedCounters(newFence, newGeneration); + } + + private static UUID nextOperationId( + DSLContext transaction, + CanonicalGameplayIssuerPartitionBuildRepository.PreparedMemberWork prepared) { + Set reserved = new HashSet<>(); + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work = prepared.work(); + CanonicalIssuerPartitionReservation original = prepared.originalReservation(); + CanonicalGameplayBindingIdentity owner = original.owner(); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = prepared.plan().bootstrapIntent(); + reserved.add(NIL_UUID); + reserved.add(intent.operationId()); + reserved.add(intent.requestId()); + reserved.add(prepared.plan().buildOperationId()); + reserved.add(work.memberOperationId()); + reserved.add(work.memberPreparationFenceId()); + reserved.add(original.reservationId()); + reserved.add(original.transitionId()); + reserved.add(original.reservationFence()); + reserved.add(original.issuerCoverageOperationId()); + reserved.add(owner.accountId()); + reserved.add(owner.tenantId()); + reserved.add(owner.playableStateNamespaceId()); + reserved.add(owner.characterId()); + reserved.add(owner.gameInstanceId()); + reserved.add(owner.regionId()); + reserved.add(UUID.fromString(owner.sessionId())); + while (true) { + UUID candidate = UUID.randomUUID(); + if (reserved.contains(candidate)) continue; + Record collision = + transaction.fetchOne( + "SELECT 1 FROM " + OPERATION + " WHERE member_operation_id = ?", candidate); + if (collision == null) return candidate; + } + } + + private static void insertOperation( + DSLContext transaction, + CanonicalGameplayIssuerPartitionBuildRepository.PreparedMemberWork prepared, + UUID operationId, + IssuedCounters counters, + byte[] bytes, + String digest) { + CanonicalGameplayIssuerPartitionBuildPlan plan = prepared.plan(); + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work = prepared.work(); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); + CanonicalIssuerPartitionReservation original = prepared.originalReservation(); + BindingAction action = bindingAction(prepared); + transaction.execute( + "INSERT INTO " + + OPERATION + + " (member_operation_id, issuer_id, bootstrap_operation_id, bootstrap_request_id," + + " build_operation_id, build_plan_digest, work_ordinal, preparation_operation_id," + + " preparation_fence_id, reservation_source_row_ordinal, reservation_source_row_digest," + + " binding_source_row_ordinal, binding_source_row_digest, binding_lifecycle," + + " reservation_id, reservation_lifecycle, expected_binding_present, counts_toward_capacity," + + " original_issuer_coverage_operation_id," + + " original_issuer_coverage_operation_fence, original_coverage_fence," + + " original_inventory_snapshot_revision, bootstrap_anchor_operation_id," + + " bootstrap_anchor_operation_fence, bootstrap_anchor_coverage_fence," + + " bootstrap_anchor_inventory_snapshot_revision, operation_fence," + + " local_member_generation, member_status, member_schema_version, member_value_bytes," + + " member_value_digest)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + + " 'PENDING_PHYSICAL_PROOF', 2, ?, ?)", + operationId, + ISSUER, + intent.operationId(), + intent.requestId(), + plan.buildOperationId(), + plan.planDigest(), + work.workOrdinal(), + work.memberOperationId(), + work.memberPreparationFenceId(), + work.reservationSourceRowOrdinal(), + work.reservationSourceRowDigest(), + work.bindingSourceRowOrdinal(), + work.bindingSourceRowDigest(), + prepared.bindingLifecycle() == null ? null : prepared.bindingLifecycle().name(), + original.reservationId(), + original.lifecycle().name(), + action.expectedBindingPresent(), + work.countsTowardCapacity(), + original.issuerCoverageOperationId(), + decimal(original.issuerCoverageOperationFence()), + decimal(original.coverageFence()), + decimal(original.inventorySnapshotRevision()), + intent.operationId(), + decimal(intent.operationFence()), + decimal(intent.coverageFence()), + decimal(intent.inventorySnapshotRevision()), + decimal(counters.operationFence()), + decimal(counters.generation()), + bytes, + digest); + } + + private static BigInteger max(BigInteger... values) { + BigInteger greatest = BigInteger.ZERO; + for (BigInteger value : values) { + if (value.compareTo(greatest) > 0) greatest = value; + } + return greatest; + } + + private static BigInteger readPositive(Record row, String field) { + BigInteger value = readNonNegative(row, field); + if (value.signum() <= 0) throw conflict(field + " must be positive"); + return value; + } + + private static BigInteger readNonNegative(Record row, String field) { + BigDecimal value = row.get(field, BigDecimal.class); + if (value == null) throw conflict(field + " is missing"); + try { + BigInteger integer = value.toBigIntegerExact(); + if (integer.signum() < 0) throw conflict(field + " must not be negative"); + requireCounterLimit(integer, field); + return integer; + } catch (ArithmeticException malformed) { + throw conflict(field + " must be an exact integer"); + } + } + + private static long requireNonNegativeLong(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null || value < 0) throw conflict(field + " must be a non-negative bigint"); + return value; + } + + private static String requireText(Record row, String field) { + String value = row.get(field, String.class); + if (value == null) throw conflict(field + " is missing"); + return value; + } + + private static byte[] requireBytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + if (value == null || value.length == 0) throw conflict(field + " is missing"); + return value; + } + + private static BigDecimal decimal(BigInteger value) { + return new BigDecimal(value); + } + + private static void requireCounterLimit(BigInteger value, String name) { + if (value.signum() < 0 + || value.toString().length() > CanonicalGameplayIssuerMemberV2Codec.MAX_COUNTER_DIGITS) { + throw conflict(name + " is outside the canonical unsigned local counter range"); + } + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(NIL_UUID)) throw new IllegalArgumentException(name + " must not be nil"); + } + + private static UUID requireUuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null || NIL_UUID.equals(value)) throw conflict(field + " must be a non-nil UUID"); + return value; + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw conflict("Issuer bootstrap member operation owner cannot join an ambient transaction"); + } + } + + private static IllegalStateException conflict(String message) { + return new IllegalStateException(message); + } + + private record BindingAction(boolean expectedBindingPresent) {} + + private record IssuedCounters(BigInteger operationFence, BigInteger generation) {} + + /** + * Shape-only controlled local input for a stable coordination-storage incarnation. Its name + * describes the required consumer input, not an authenticated attestation or production source. + */ + static final class TrustedStableIncarnation { + private final String attestorBinding; + private final String acceptedAttestationDigest; + private final CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + targetDeploymentEvidence; + private final String coordOpsRoAclDigest; + private final String coordRedisConfigObservedDigest; + + TrustedStableIncarnation( + String attestorBinding, + String acceptedAttestationDigest, + CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + targetDeploymentEvidence, + String coordOpsRoAclDigest, + String coordRedisConfigObservedDigest) { + this.attestorBinding = Objects.requireNonNull(attestorBinding, "attestorBinding"); + this.acceptedAttestationDigest = + Objects.requireNonNull(acceptedAttestationDigest, "acceptedAttestationDigest"); + this.targetDeploymentEvidence = + Objects.requireNonNull(targetDeploymentEvidence, "targetDeploymentEvidence"); + this.coordOpsRoAclDigest = Objects.requireNonNull(coordOpsRoAclDigest, "coordOpsRoAclDigest"); + this.coordRedisConfigObservedDigest = + Objects.requireNonNull(coordRedisConfigObservedDigest, "coordRedisConfigObservedDigest"); + // Reuse the v2 typed carrier's closed local shape validation without claiming custody. + value(); + } + + private CanonicalGameplayIssuerMemberV2Value.Incarnation value() { + return new CanonicalGameplayIssuerMemberV2Value.Incarnation( + attestorBinding, + acceptedAttestationDigest, + targetDeploymentEvidence, + coordOpsRoAclDigest, + coordRedisConfigObservedDigest); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionWork.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionWork.java new file mode 100644 index 0000000000..050b7d6c55 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionWork.java @@ -0,0 +1,98 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.util.List; +import java.util.Objects; + +/** + * Read-only output of the local SQL owner for one exact partition in a prepared initial bootstrap. + * + *

Its members are SQL-issued operations still pending physical proof. An empty partition has an + * empty member list and does not receive a fabricated member generation. + */ +final class CanonicalGameplayIssuerBootstrapPartitionWork { + private final CanonicalGameplayIssuerPartitionBuildPlan buildPlan; + private final BigInteger partitionId; + private final List memberOperations; + private final CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation; + + CanonicalGameplayIssuerBootstrapPartitionWork( + CanonicalGameplayIssuerPartitionBuildPlan buildPlan, + BigInteger partitionId, + List memberOperations, + CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation) { + this.buildPlan = Objects.requireNonNull(buildPlan, "buildPlan"); + if (buildPlan.state() != CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED) { + throw new IllegalArgumentException("Partition work requires the exact PREPARED build plan"); + } + this.partitionId = Objects.requireNonNull(partitionId, "partitionId"); + if (partitionId.signum() < 0 + || partitionId.compareTo(buildPlan.bootstrapIntent().layoutDescriptor().partitionCount()) + >= 0) { + throw new IllegalArgumentException("partitionId is outside the exact bootstrap layout"); + } + this.memberOperations = + List.copyOf(Objects.requireNonNull(memberOperations, "memberOperations")); + if (this.memberOperations.stream().anyMatch(Objects::isNull)) { + throw new IllegalArgumentException("memberOperations must not contain null"); + } + this.incarnation = Objects.requireNonNull(incarnation, "incarnation"); + List expectedWork = + buildPlan.memberWorks().stream() + .filter(work -> work.plannedPartitionId().equals(partitionId)) + .toList(); + if (expectedWork.size() != this.memberOperations.size()) { + throw new IllegalArgumentException( + "Partition work must contain every exact prepared member operation for its partition"); + } + for (int index = 0; index < expectedWork.size(); index++) { + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work = expectedWork.get(index); + CanonicalGameplayIssuerBootstrapMemberOperation operation = this.memberOperations.get(index); + CanonicalGameplayIssuerMemberV2Value value = operation.expectedMemberValue(); + if (operation.status() + != CanonicalGameplayIssuerBootstrapMemberOperation.Status.PENDING_PHYSICAL_PROOF + || operation.workOrdinal() != work.workOrdinal() + || !operation.buildOperationId().equals(buildPlan.buildOperationId()) + || !operation.buildPlanDigest().equals(buildPlan.planDigest()) + || !operation.preparationOperationId().equals(work.memberOperationId()) + || !operation.preparationFenceId().equals(work.memberPreparationFenceId()) + || operation.reservationSourceRowOrdinal() != work.reservationSourceRowOrdinal() + || !operation.reservationSourceRowDigest().equals(work.reservationSourceRowDigest()) + || !operation.bootstrapOperationId().equals(buildPlan.bootstrapIntent().operationId()) + || !operation.bootstrapRequestId().equals(buildPlan.bootstrapIntent().requestId()) + || !value.reservation().reservationId().equals(work.reservationId()) + || !value.reservation().transitionId().equals(work.transitionId()) + || !value.reservation().partitionId().equals(partitionId) + || !value + .anchor() + .issuerCoverageOperationId() + .equals(buildPlan.bootstrapIntent().operationId()) + || !value.anchor().operationFence().equals(buildPlan.bootstrapIntent().operationFence()) + || !value.anchor().coverageFence().equals(buildPlan.bootstrapIntent().coverageFence()) + || !value + .anchor() + .issuerInventorySnapshotRevision() + .equals(buildPlan.bootstrapIntent().inventorySnapshotRevision()) + || !incarnation.equals(value.incarnation())) { + throw new IllegalArgumentException( + "Partition operation differs from its exact planned source or incarnation"); + } + } + } + + CanonicalGameplayIssuerPartitionBuildPlan buildPlan() { + return buildPlan; + } + + BigInteger partitionId() { + return partitionId; + } + + List memberOperations() { + return memberOperations; + } + + CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation() { + return incarnation; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java index e0a6aaa612..5bc8b97bc4 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java @@ -25,8 +25,11 @@ import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.IssuerEvent; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationDisposition; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.impl.DSL; @@ -219,6 +222,169 @@ private CanonicalGameplayIssuerPartitionBuildPlan prepareInTransaction( "saved issuer partition build plan must be readable")); } + /** + * Reads one exact work item from an already persisted complete PREPARED plan using the caller's + * transaction. This deliberately repeats the same locks and exact source/plan checks as plan + * preparation; it does not open a nested transaction or create a missing plan. + */ + PreparedMemberWork readPreparedMemberWorkInTransaction( + DSLContext transaction, + UUID bootstrapOperationId, + UUID bootstrapRequestId, + long workOrdinal) { + return readPreparedMemberWorkFromVerifiedPlan( + readPreparedPlanInTransaction(transaction, bootstrapOperationId, bootstrapRequestId), + workOrdinal); + } + + /** Loads and locks the already persisted complete PREPARED plan and its current sources. */ + CanonicalGameplayIssuerPartitionBuildPlan readPreparedPlanInTransaction( + DSLContext transaction, UUID bootstrapOperationId, UUID bootstrapRequestId) { + requireNonNil(bootstrapOperationId, "bootstrapOperationId"); + requireNonNil(bootstrapRequestId, "bootstrapRequestId"); + if (bootstrapOperationId.equals(bootstrapRequestId)) { + throw conflict("Bootstrap operation and request identities must be distinct"); + } + BigInteger currentInventoryRevision = lockInventoryRevision(transaction); + Record control = lockControl(transaction, ISSUER); + if (control == null) { + Record orphan = + transaction.fetchOne( + "SELECT operation_id FROM " + BOOTSTRAP_INTENT + " WHERE issuer_id = ?", ISSUER); + if (orphan != null) { + throw conflict("Pending issuer-bootstrap intent lost its positive current control row"); + } + throw conflict("Exact pending issuer-bootstrap control row is missing"); + } + Record intentRow = lockIntent(transaction, bootstrapOperationId); + if (intentRow == null) throw conflict("Exact pending issuer-bootstrap operation is missing"); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = + loadAndRequireCurrentIntent( + transaction, + control, + intentRow, + bootstrapOperationId, + bootstrapRequestId, + currentInventoryRevision); + List currentRows = + captureCurrentCohort(transaction, intent.inventorySnapshotRevision()); + requireSameCohort(intent.cohortRows(), currentRows); + DerivedPlan derived = derivePlan(intent, currentRows); + Record buildPlanRow = + transaction.fetchOne( + "SELECT * FROM " + BUILD_PLAN + " WHERE bootstrap_operation_id = ? FOR UPDATE", + bootstrapOperationId); + if (buildPlanRow == null) { + throw conflict("Exact complete issuer partition build plan is missing"); + } + CanonicalGameplayIssuerPartitionBuildPlan plan = + loadAndRequireExactPlan(transaction, intent, currentRows, derived, buildPlanRow); + if (plan.state() != CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED) { + throw conflict("Blocked issuer partition build plan cannot issue member operations"); + } + return plan; + } + + /** Extracts typed source only from a plan returned by {@link #readPreparedPlanInTransaction}. */ + PreparedMemberWork readPreparedMemberWorkFromVerifiedPlan( + CanonicalGameplayIssuerPartitionBuildPlan plan, long workOrdinal) { + Objects.requireNonNull(plan, "plan"); + if (plan.state() != CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED) { + throw conflict("Blocked issuer partition build plan cannot issue member operations"); + } + if (workOrdinal < 0) throw conflict("Member work ordinal must not be negative"); + if (workOrdinal >= plan.memberWorks().size()) { + throw conflict("Member work ordinal is outside the exact prepared plan"); + } + CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work = + plan.memberWorks().get(Math.toIntExact(workOrdinal)); + int sourceIndex = Math.toIntExact(work.reservationSourceRowOrdinal()); + if (sourceIndex >= intent.cohortRows().size()) { + throw conflict("Prepared member work lost its exact reservation cohort row"); + } + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow sourceRow = + intent.cohortRows().get(sourceIndex); + if (sourceRow.kind() != CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.RESERVATION + || !sourceRow.sourceRowDigest().equals(work.reservationSourceRowDigest())) { + throw conflict("Prepared member work no longer links to its exact original reservation"); + } + ReservationSource source = parseReservation(sourceRow); + CanonicalGameplayBindingIdentity owner = + new CanonicalGameplayBindingIdentity( + UUID.fromString(source.accountId()), + UUID.fromString(source.tenantId()), + UUID.fromString(source.namespaceId()), + UUID.fromString(source.characterId()), + source.playableStateScope(), + UUID.fromString(source.gameInstanceId()), + source.runtimeGameInstanceId().longValueExact(), + source.sessionId(), + UUID.fromString(source.regionId()), + source.regionEpoch(), + source.issuerId(), + source.issuerAuthGeneration(), + source.layoutVersion(), + source.partitionCount(), + source.partitionCapacity()); + CanonicalIssuerPartitionReservation reservation = + new CanonicalIssuerPartitionReservation( + source.reservationId(), + owner, + source.bindingGeneration(), + source.transitionId(), + source.partitionId(), + CanonicalIssuerPartitionReservation.Lifecycle.valueOf(source.lifecycle()), + source.reservationFence(), + source.coverageOperationId(), + source.coverageOperationFence(), + source.coverageFence(), + source.inventorySnapshotRevision(), + sourceRow.sourceInventoryRevision()); + if (!work.reservationId().equals(reservation.reservationId()) + || !Arrays.equals(work.bindingRef(), owner.bindingRef().bytes()) + || !work.transitionId().equals(reservation.transitionId()) + || !work.reservationLifecycle().equals(reservation.lifecycle().name()) + || !work.reservationFence().equals(reservation.reservationFence()) + || !work.originalPartitionId().equals(reservation.partitionId()) + || !work.originalLayoutVersion().equals(reservation.owner().issuerIndexLayoutVersion()) + || !work.originalPartitionCount().equals(reservation.owner().issuerIndexPartitionCount()) + || !work.originalPartitionCapacity() + .equals(reservation.owner().issuerIndexPartitionCapacity()) + || !work.originalIssuerCoverageOperationId().equals(reservation.issuerCoverageOperationId()) + || !work.originalIssuerCoverageOperationFence() + .equals(reservation.issuerCoverageOperationFence()) + || !work.originalCoverageFence().equals(reservation.coverageFence()) + || !work.originalInventorySnapshotRevision() + .equals(reservation.inventorySnapshotRevision())) { + throw conflict("Prepared member work differs from its exact typed original reservation"); + } + CanonicalGameplayBindingInventoryEntry.Lifecycle bindingLifecycle = null; + if (work.bindingSourceRowOrdinal() != null) { + int bindingIndex = Math.toIntExact(work.bindingSourceRowOrdinal()); + if (bindingIndex >= intent.cohortRows().size()) { + throw conflict("Prepared member work lost its exact binding cohort row"); + } + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow bindingRow = + intent.cohortRows().get(bindingIndex); + if (bindingRow.kind() != CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.BINDING + || !bindingRow.sourceRowDigest().equals(work.bindingSourceRowDigest())) { + throw conflict("Prepared member work no longer links to its exact binding cohort row"); + } + BindingSource binding = parseBinding(bindingRow); + if (!binding.matches(source)) { + throw conflict("Prepared member work binding differs from the exact original reservation"); + } + try { + bindingLifecycle = + CanonicalGameplayBindingInventoryEntry.Lifecycle.valueOf(binding.lifecycle()); + } catch (RuntimeException malformed) { + throw conflict("Prepared member work has an unsupported binding lifecycle"); + } + } + return new PreparedMemberWork(plan, work, reservation, bindingLifecycle); + } + private static CanonicalGameplayIssuerLayoutBootstrapIntent loadAndRequireCurrentIntent( DSLContext transaction, Record control, @@ -792,6 +958,12 @@ private static BindingSource parseBinding( if (!ISSUER.equals(issuerId)) { throw conflict("Binding source does not use the exact Account issuer"); } + String lifecycle = text(json, "lifecycle"); + try { + CanonicalGameplayBindingInventoryEntry.Lifecycle.valueOf(lifecycle); + } catch (RuntimeException malformed) { + throw conflict("Binding source uses an unsupported lifecycle"); + } return new BindingSource( row.rowOrdinal(), row.sourceRowDigest(), @@ -814,6 +986,7 @@ private static BindingSource parseBinding( integer(json, "issuer_index_partition_count"), integer(json, "issuer_index_partition_capacity"), integer(json, "issuer_partition_id"), + lifecycle, integer(json, "binding_generation")); } @@ -1773,6 +1946,7 @@ private record BindingSource( BigInteger partitionCount, BigInteger partitionCapacity, BigInteger partitionId, + String lifecycle, BigInteger bindingGeneration) { BindingSource { bindingRef = bindingRef.clone(); @@ -1806,4 +1980,16 @@ boolean matches(ReservationSource reservation) { && partitionId.equals(reservation.partitionId()); } } + + record PreparedMemberWork( + CanonicalGameplayIssuerPartitionBuildPlan plan, + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work, + CanonicalIssuerPartitionReservation originalReservation, + CanonicalGameplayBindingInventoryEntry.Lifecycle bindingLifecycle) { + PreparedMemberWork { + Objects.requireNonNull(plan, "plan"); + Objects.requireNonNull(work, "work"); + Objects.requireNonNull(originalReservation, "originalReservation"); + } + } } diff --git a/services/game-session-service/src/main/resources/db/migration/V1032__canonical_issuer_bootstrap_member_operation.sql b/services/game-session-service/src/main/resources/db/migration/V1032__canonical_issuer_bootstrap_member_operation.sql new file mode 100644 index 0000000000..3e4198b460 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1032__canonical_issuer_bootstrap_member_operation.sql @@ -0,0 +1,254 @@ +-- A persisted local SQL-issued operation for one exact work item in the current complete +-- PREPARED initial-bootstrap plan. This is still pending physical proof: it installs no pointer, +-- records no Redis result, and issues no issuer-wide coverage acknowledgement. +-- The local numeric generation is an operation identity, not global coverage evidence. + +ALTER TABLE game_session_canonical_issuer_partition_build_plan + ADD CONSTRAINT uq_gs_issuer_partition_build_plan_digest_link + UNIQUE (build_operation_id, bootstrap_operation_id, bootstrap_request_id, issuer_id, plan_digest); + +ALTER TABLE game_session_canonical_issuer_layout_bootstrap_intent + ADD CONSTRAINT uq_gs_issuer_bootstrap_intent_request_link + UNIQUE (operation_id, issuer_id, request_id); + +ALTER TABLE game_session_canonical_issuer_partition_build_cohort_row + ADD CONSTRAINT uq_gs_issuer_partition_build_cohort_digest_link + UNIQUE (build_operation_id, source_row_ordinal, source_row_digest); + +ALTER TABLE game_session_canonical_issuer_partition_build_member_work + ADD CONSTRAINT uq_gs_issuer_partition_build_member_operation_link UNIQUE ( + build_operation_id, bootstrap_operation_id, issuer_id, work_ordinal, + member_operation_id, member_preparation_fence_id, + reservation_source_row_ordinal, reservation_source_row_digest, + reservation_id, + original_issuer_coverage_operation_id, original_issuer_coverage_operation_fence, + original_coverage_fence, original_inventory_snapshot_revision, + planned_anchor_operation_id, planned_anchor_operation_fence, + planned_anchor_coverage_fence, planned_anchor_inventory_snapshot_revision); + +ALTER TABLE game_session_canonical_issuer_partition_build_member_work + ADD CONSTRAINT uq_gs_issuer_partition_build_binding_link UNIQUE ( + build_operation_id, bootstrap_operation_id, issuer_id, work_ordinal, + binding_source_row_ordinal, binding_source_row_digest); + +CREATE TABLE game_session_canonical_issuer_bootstrap_member_op_counter ( + issuer_id character varying(64) NOT NULL, + last_issued_operation_fence numeric NOT NULL, + last_issued_member_generation numeric NOT NULL, + counter_version bigint NOT NULL, + CONSTRAINT pk_gs_issuer_bootstrap_member_op_counter PRIMARY KEY (issuer_id), + CONSTRAINT chk_gs_issuer_bootstrap_member_op_counter CHECK ( + issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND counter_version >= 0 + AND last_issued_operation_fence >= 0 + AND last_issued_member_generation >= 0 + AND last_issued_operation_fence = floor(last_issued_operation_fence) + AND last_issued_member_generation = floor(last_issued_member_generation) + AND length(CAST(last_issued_operation_fence AS varchar)) <= 256 + AND length(CAST(last_issued_member_generation AS varchar)) <= 256 + AND ((counter_version = 0 + AND last_issued_operation_fence = 0 + AND last_issued_member_generation = 0) + OR (counter_version > 0 + AND last_issued_operation_fence > 0 + AND last_issued_member_generation = last_issued_operation_fence + 1)) + ) +); + +CREATE TABLE game_session_canonical_issuer_bootstrap_member_operation ( + member_operation_id uuid NOT NULL, + issuer_id character varying(64) NOT NULL, + bootstrap_operation_id uuid NOT NULL, + bootstrap_request_id uuid NOT NULL, + build_operation_id uuid NOT NULL, + build_plan_digest character varying(71) NOT NULL, + work_ordinal bigint NOT NULL, + preparation_operation_id uuid NOT NULL, + preparation_fence_id uuid NOT NULL, + reservation_source_row_ordinal bigint NOT NULL, + reservation_source_row_digest character varying(71) NOT NULL, + binding_source_row_ordinal bigint, + binding_source_row_digest character varying(71), + binding_lifecycle character varying(24), + reservation_id uuid NOT NULL, + reservation_lifecycle character varying(24) NOT NULL, + expected_binding_present boolean NOT NULL, + counts_toward_capacity boolean NOT NULL, + original_issuer_coverage_operation_id uuid NOT NULL, + original_issuer_coverage_operation_fence numeric NOT NULL, + original_coverage_fence numeric NOT NULL, + original_inventory_snapshot_revision numeric NOT NULL, + bootstrap_anchor_operation_id uuid NOT NULL, + bootstrap_anchor_operation_fence numeric NOT NULL, + bootstrap_anchor_coverage_fence numeric NOT NULL, + bootstrap_anchor_inventory_snapshot_revision numeric NOT NULL, + operation_fence numeric NOT NULL, + local_member_generation numeric NOT NULL, + member_status character varying(32) NOT NULL, + member_schema_version smallint NOT NULL, + member_value_bytes bytea NOT NULL, + member_value_digest character varying(71) NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_issuer_bootstrap_member_operation PRIMARY KEY (member_operation_id), + CONSTRAINT uq_gs_issuer_bootstrap_member_operation_work + UNIQUE (issuer_id, bootstrap_operation_id, work_ordinal), + CONSTRAINT uq_gs_issuer_bootstrap_member_operation_fence + UNIQUE (issuer_id, operation_fence), + CONSTRAINT uq_gs_issuer_bootstrap_member_operation_generation + UNIQUE (issuer_id, local_member_generation), + CONSTRAINT fk_gs_issuer_bootstrap_member_operation_intent + FOREIGN KEY (bootstrap_operation_id, issuer_id) + REFERENCES game_session_canonical_issuer_layout_bootstrap_intent (operation_id, issuer_id), + CONSTRAINT fk_gs_issuer_bootstrap_member_operation_request + FOREIGN KEY (bootstrap_operation_id, issuer_id, bootstrap_request_id) + REFERENCES game_session_canonical_issuer_layout_bootstrap_intent (operation_id, issuer_id, request_id), + CONSTRAINT fk_gs_issuer_bootstrap_member_operation_plan + FOREIGN KEY (build_operation_id, bootstrap_operation_id, bootstrap_request_id, + issuer_id, build_plan_digest) + REFERENCES game_session_canonical_issuer_partition_build_plan + (build_operation_id, bootstrap_operation_id, bootstrap_request_id, issuer_id, plan_digest), + CONSTRAINT fk_gs_issuer_bootstrap_member_operation_work + FOREIGN KEY ( + build_operation_id, bootstrap_operation_id, issuer_id, work_ordinal, + preparation_operation_id, preparation_fence_id, + reservation_source_row_ordinal, reservation_source_row_digest, reservation_id, + original_issuer_coverage_operation_id, original_issuer_coverage_operation_fence, + original_coverage_fence, original_inventory_snapshot_revision, + bootstrap_anchor_operation_id, bootstrap_anchor_operation_fence, + bootstrap_anchor_coverage_fence, bootstrap_anchor_inventory_snapshot_revision) + REFERENCES game_session_canonical_issuer_partition_build_member_work ( + build_operation_id, bootstrap_operation_id, issuer_id, work_ordinal, + member_operation_id, member_preparation_fence_id, + reservation_source_row_ordinal, reservation_source_row_digest, reservation_id, + original_issuer_coverage_operation_id, original_issuer_coverage_operation_fence, + original_coverage_fence, original_inventory_snapshot_revision, + planned_anchor_operation_id, planned_anchor_operation_fence, + planned_anchor_coverage_fence, planned_anchor_inventory_snapshot_revision), + CONSTRAINT fk_gs_issuer_bootstrap_member_operation_binding_work + FOREIGN KEY (build_operation_id, bootstrap_operation_id, issuer_id, work_ordinal, + binding_source_row_ordinal, binding_source_row_digest) + REFERENCES game_session_canonical_issuer_partition_build_member_work ( + build_operation_id, bootstrap_operation_id, issuer_id, work_ordinal, + binding_source_row_ordinal, binding_source_row_digest), + CONSTRAINT fk_gs_issuer_bootstrap_member_operation_source + FOREIGN KEY (build_operation_id, reservation_source_row_ordinal, + reservation_source_row_digest) + REFERENCES game_session_canonical_issuer_partition_build_cohort_row + (build_operation_id, source_row_ordinal, source_row_digest), + CONSTRAINT fk_gs_issuer_bootstrap_member_operation_binding_source + FOREIGN KEY (build_operation_id, binding_source_row_ordinal, + binding_source_row_digest) + REFERENCES game_session_canonical_issuer_partition_build_cohort_row + (build_operation_id, source_row_ordinal, source_row_digest), + CONSTRAINT fk_gs_issuer_bootstrap_member_operation_anchor + FOREIGN KEY (build_operation_id, bootstrap_operation_id, issuer_id, + bootstrap_anchor_operation_fence, bootstrap_anchor_coverage_fence, + bootstrap_anchor_inventory_snapshot_revision) + REFERENCES game_session_canonical_issuer_partition_build_plan + (build_operation_id, bootstrap_operation_id, issuer_id, + bootstrap_operation_fence, bootstrap_coverage_fence, + issuer_inventory_snapshot_revision), + CONSTRAINT chk_gs_issuer_bootstrap_member_operation CHECK ( + member_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND bootstrap_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND bootstrap_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND build_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND preparation_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND preparation_fence_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND reservation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND original_issuer_coverage_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND bootstrap_anchor_operation_id = bootstrap_operation_id + AND member_operation_id <> bootstrap_operation_id + AND member_operation_id <> bootstrap_request_id + AND member_operation_id <> build_operation_id + AND member_operation_id <> preparation_operation_id + AND member_operation_id <> preparation_fence_id + AND reservation_lifecycle IN ('RESERVED', 'BOUND', 'RELEASE_PENDING', 'RELEASED') + AND ((binding_source_row_ordinal IS NULL + AND binding_source_row_digest IS NULL + AND binding_lifecycle IS NULL + AND expected_binding_present = FALSE + AND reservation_lifecycle IN ('RESERVED', 'RELEASED')) + OR (binding_source_row_ordinal IS NOT NULL + AND binding_source_row_ordinal >= 0 + AND binding_source_row_digest IS NOT NULL + AND binding_source_row_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((binding_lifecycle = 'CANDIDATE_PREPARED' + AND reservation_lifecycle = 'RESERVED' + AND expected_binding_present = FALSE) + OR (binding_lifecycle = 'PROVISIONAL' + AND reservation_lifecycle = 'RESERVED' + AND expected_binding_present = TRUE) + OR (binding_lifecycle = 'ACTIVE' + AND reservation_lifecycle IN ('BOUND', 'RELEASE_PENDING') + AND expected_binding_present = TRUE) + OR (binding_lifecycle = 'TERMINAL' + AND reservation_lifecycle = 'RELEASED' + AND expected_binding_present = FALSE)))) + AND operation_fence > 0 + AND local_member_generation > operation_fence + AND original_issuer_coverage_operation_fence > 0 + AND original_coverage_fence > 0 + AND original_inventory_snapshot_revision > 0 + AND bootstrap_anchor_operation_fence > 0 + AND bootstrap_anchor_coverage_fence > 0 + AND bootstrap_anchor_inventory_snapshot_revision > 0 + AND member_status = 'PENDING_PHYSICAL_PROOF' + AND member_schema_version = 2 + AND counts_toward_capacity = (reservation_lifecycle <> 'RELEASED') + AND octet_length(member_value_bytes) BETWEEN 1 AND 65536 + AND build_plan_digest ~ '^sha256:[0-9a-f]{64}$' + AND reservation_source_row_digest ~ '^sha256:[0-9a-f]{64}$' + AND member_value_digest ~ '^sha256:[0-9a-f]{64}$' + AND work_ordinal >= 0 + AND reservation_source_row_ordinal >= 0) +); + +-- jOOQ's H2 DDL parser does not model PostgreSQL trigger functions. The deployed PostgreSQL +-- migration retains these immutable-artifact and monotonic compare-and-set guards. +-- [jooq ignore start] +CREATE FUNCTION game_session_reject_issuer_bootstrap_member_operation_change() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'issuer bootstrap member operation artifacts are immutable' + USING ERRCODE = 'check_violation'; +END; +$$; + +CREATE TRIGGER trg_gs_issuer_bootstrap_member_operation_immutable + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_bootstrap_member_operation + FOR EACH ROW EXECUTE FUNCTION game_session_reject_issuer_bootstrap_member_operation_change(); +CREATE TRIGGER trg_gs_issuer_bootstrap_member_operation_no_truncate + BEFORE TRUNCATE ON game_session_canonical_issuer_bootstrap_member_operation + FOR EACH STATEMENT EXECUTE FUNCTION game_session_reject_issuer_bootstrap_member_operation_change(); + +CREATE FUNCTION game_session_guard_issuer_bootstrap_member_operation_counter() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'issuer bootstrap member operation counters cannot be deleted' + USING ERRCODE = 'check_violation'; + END IF; + IF NEW.issuer_id IS DISTINCT FROM OLD.issuer_id + OR NEW.counter_version <> OLD.counter_version + 1 + OR NEW.last_issued_operation_fence <= OLD.last_issued_operation_fence + OR NEW.last_issued_member_generation <= OLD.last_issued_member_generation + OR NEW.last_issued_member_generation <> NEW.last_issued_operation_fence + 1 THEN + RAISE EXCEPTION 'issuer bootstrap member operation counter CAS must advance both local domains' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_gs_issuer_bootstrap_member_operation_counter_guard + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_bootstrap_member_op_counter + FOR EACH ROW EXECUTE FUNCTION game_session_guard_issuer_bootstrap_member_operation_counter(); +CREATE TRIGGER trg_gs_issuer_bootstrap_member_operation_counter_no_truncate + BEFORE TRUNCATE ON game_session_canonical_issuer_bootstrap_member_op_counter + FOR EACH STATEMENT EXECUTE FUNCTION game_session_reject_issuer_bootstrap_member_operation_change(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java new file mode 100644 index 0000000000..f9aa136284 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java @@ -0,0 +1,952 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.util.EnumSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; +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.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL proof for the SQL-issued pending initial-bootstrap member-operation boundary. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final UUID ACCOUNT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID NAMESPACE_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID GAME_INSTANCE_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID REGION_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID CHARACTER_ID = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final BigInteger LAYOUT_VERSION = BigInteger.valueOf(3); + private static final BigInteger PARTITION_COUNT = BigInteger.valueOf(16); + private static final BigInteger PARTITION_CAPACITY = BigInteger.valueOf(32); + private static final List RETAINED_TABLES = + List.of( + "game_session_canonical_binding_inventory_clock", + "game_session_canonical_binding_legacy_disposition", + "game_session_canonical_gameplay_binding_inventory", + "game_session_canonical_issuer_partition_reservation", + "game_session_canonical_issuer_layout_bootstrap_intent", + "game_session_canonical_issuer_layout_bootstrap_control", + "game_session_canonical_issuer_layout_bootstrap_cohort_row", + "game_session_canonical_issuer_partition_build_plan", + "game_session_canonical_issuer_partition_build_cohort_row", + "game_session_canonical_issuer_partition_build_member_work", + "game_session_canonical_issuer_partition_build_blocker"); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void actualPreparedPlanIssuesExactPendingV2OperationAndPreservesV1031RowsAcrossRestart() + throws Exception { + Fixture fixture = + pendingFixture( + "gs_bootstrap_member_issue_", PARTITION_CAPACITY, LAYOUT_VERSION, false, true); + try { + assertThat(fixture.plan().state()) + .isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED); + Map> retainedBefore = rowSnapshots(fixture.testSchema().dsl()); + List historyBefore = historySnapshot(fixture.testSchema().dsl()); + migrateRemaining(fixture.testSchema()); + + assertThat(rowSnapshots(fixture.testSchema().dsl())).isEqualTo(retainedBefore); + List historyAfterMigration = historySnapshot(fixture.testSchema().dsl()); + assertThat(historyAfterMigration).hasSize(historyBefore.size() + 1); + assertThat(historyAfterMigration.subList(0, historyBefore.size())) + .containsExactlyElementsOf(historyBefore); + assertThat( + fixture + .testSchema() + .dsl() + .fetchSingle("SELECT script FROM flyway_schema_history WHERE version = '1032'") + .get(0, String.class)) + .isEqualTo("V1032__canonical_issuer_bootstrap_member_operation.sql"); + assertThat( + fixture + .testSchema() + .dsl() + .fetchSingle( + "SELECT count(*) FROM game_session_canonical_issuer_bootstrap_member_operation") + .get(0, Long.class)) + .isZero(); + + var owner = + new CanonicalGameplayIssuerBootstrapMemberOperationRepository(fixture.testSchema().dsl()); + var operation = + owner.beginOrResumePendingPhysicalProof( + fixture.intent().operationId(), + fixture.requestId(), + 0, + fixture.currentAccountCheckpoint(), + stableIncarnation("stable-a")); + var value = operation.expectedMemberValue(); + assertThat(operation.status()) + .isEqualTo(CanonicalGameplayIssuerBootstrapMemberOperation.Status.PENDING_PHYSICAL_PROOF); + assertThat(operation.operationId()) + .isNotEqualTo(fixture.plan().memberWorks().getFirst().memberOperationId()) + .isNotEqualTo(fixture.plan().memberWorks().getFirst().memberPreparationFenceId()); + assertThat(operation.operationFence()).isGreaterThan(value.anchor().coverageFence()); + assertThat(operation.localMemberGeneration()).isGreaterThan(operation.operationFence()); + assertThat(value.memberOperation().coverageGeneration()) + .isEqualTo(operation.localMemberGeneration()); + assertThat(value.anchor().issuerCoverageOperationId()) + .isEqualTo(fixture.intent().operationId()); + assertThat(value.anchor().operationFence()).isEqualTo(fixture.intent().operationFence()); + assertThat(value.anchor().coverageFence()).isEqualTo(fixture.intent().coverageFence()); + assertThat(value.anchor().issuerInventorySnapshotRevision()) + .isEqualTo(fixture.intent().inventorySnapshotRevision()); + assertThat(value.reservation().issuerCoverageOperationId()) + .isNotEqualTo(value.anchor().issuerCoverageOperationId()); + assertThat(value.reservation().issuerCoverageOperationFence()) + .isEqualTo(BigInteger.valueOf(17)); + assertThat(value.reservation().coverageFence()).isEqualTo(BigInteger.valueOf(19)); + var originalReservationRow = + fixture + .testSchema() + .dsl() + .fetchOne( + "SELECT issuer_coverage_operation_id, issuer_coverage_operation_fence," + + " coverage_fence, inventory_snapshot_revision" + + " FROM game_session_canonical_issuer_partition_reservation" + + " WHERE reservation_id = ?", + fixture.preparedBinding().issuerReservationId()); + assertThat(originalReservationRow).isNotNull(); + assertThat(value.reservation().issuerCoverageOperationId()) + .isEqualTo(originalReservationRow.get("issuer_coverage_operation_id", UUID.class)); + assertThat(value.reservation().issuerCoverageOperationFence()) + .isEqualTo( + originalReservationRow + .get("issuer_coverage_operation_fence", BigDecimal.class) + .toBigIntegerExact()); + assertThat(value.reservation().coverageFence()) + .isEqualTo( + originalReservationRow.get("coverage_fence", BigDecimal.class).toBigIntegerExact()); + assertThat(value.reservation().inventorySnapshotRevision()) + .isEqualTo( + originalReservationRow + .get("inventory_snapshot_revision", BigDecimal.class) + .toBigIntegerExact()); + assertThat(operation.bindingLifecycle()) + .isEqualTo(CanonicalGameplayBindingInventoryEntry.Lifecycle.CANDIDATE_PREPARED); + assertThat(operation.expectedBindingPresent()).isFalse(); + assertThat(operation.countsTowardCapacity()).isTrue(); + assertThat(CanonicalGameplayIssuerMemberV2Codec.decode(operation.exactMemberValueBytes())) + .isEqualTo(value); + + var restarted = + new CanonicalGameplayIssuerBootstrapMemberOperationRepository(fixture.testSchema().dsl()) + .beginOrResumePendingPhysicalProof( + fixture.intent().operationId(), + fixture.requestId(), + 0, + fixture.currentAccountCheckpoint(), + stableIncarnation("stable-a")); + assertThat(restarted.operationId()).isEqualTo(operation.operationId()); + assertThat(restarted.operationFence()).isEqualTo(operation.operationFence()); + assertThat(restarted.localMemberGeneration()).isEqualTo(operation.localMemberGeneration()); + assertThat(restarted.exactMemberValueBytes()) + .containsExactly(operation.exactMemberValueBytes()); + assertThat(rowSnapshots(fixture.testSchema().dsl())).isEqualTo(retainedBefore); + + assertThatThrownBy( + () -> + owner.beginOrResumePendingPhysicalProof( + fixture.intent().operationId(), + fixture.requestId(), + 0, + fixture.currentAccountCheckpoint(), + stableIncarnation("changed-incarnation"))) + .isInstanceOf(IllegalStateException.class); + assertThat( + rowImages( + fixture.testSchema().dsl(), + "game_session_canonical_issuer_bootstrap_member_operation")) + .hasSize(1); + + assertThatThrownBy( + () -> + fixture + .testSchema() + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_bootstrap_member_operation" + + " SET member_status = 'PHYSICAL_PROOF_COMPLETE' WHERE member_operation_id = ?", + operation.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + fixture + .testSchema() + .dsl() + .execute( + "DELETE FROM game_session_canonical_issuer_bootstrap_member_operation" + + " WHERE member_operation_id = ?", + operation.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + fixture + .testSchema() + .dsl() + .execute("TRUNCATE game_session_canonical_issuer_bootstrap_member_operation")) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + fixture + .testSchema() + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_bootstrap_member_op_counter" + + " SET last_issued_operation_fence = last_issued_operation_fence + 1" + + " WHERE issuer_id = ?", + ISSUER)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + fixture + .testSchema() + .dsl() + .execute( + "DELETE FROM game_session_canonical_issuer_bootstrap_member_op_counter" + + " WHERE issuer_id = ?", + ISSUER)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + fixture + .testSchema() + .dsl() + .execute( + "TRUNCATE game_session_canonical_issuer_bootstrap_member_op_counter")) + .isInstanceOf(DataAccessException.class); + assertThat( + rowImages( + fixture.testSchema().dsl(), + "game_session_canonical_issuer_bootstrap_member_operation")) + .hasSize(1); + assertThat( + fixture + .testSchema() + .dsl() + .fetchSingle( + "SELECT counter_version FROM game_session_canonical_issuer_bootstrap_member_op_counter" + + " WHERE issuer_id = ?", + ISSUER) + .get(0, Long.class)) + .isEqualTo(1L); + assertThat(historySnapshot(fixture.testSchema().dsl())) + .containsExactlyElementsOf(historyAfterMigration); + } finally { + dropSchema(fixture.testSchema().schema()); + } + } + + @Test + void groupedPartitionWorkIssuesAllExactOperationsConcurrentlyAndLeavesEmptyPartitionsUnallocated() + throws Exception { + Fixture fixture = + pendingFixture( + "gs_bootstrap_member_group_", PARTITION_CAPACITY, LAYOUT_VERSION, true, true); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + assertThat(fixture.plan().state()) + .isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED); + assertThat(fixture.plan().memberWorks()).hasSize(2); + migrateRemaining(fixture.testSchema()); + + var ready = new CountDownLatch(2); + var start = new CountDownLatch(1); + var first = executor.submit(() -> preparePartitionAtGate(fixture, ready, start)); + var second = executor.submit(() -> preparePartitionAtGate(fixture, ready, start)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + var firstWork = first.get(30, TimeUnit.SECONDS); + var secondWork = second.get(30, TimeUnit.SECONDS); + + assertThat(firstWork.buildPlan().planDigest()).isEqualTo(fixture.plan().planDigest()); + assertThat(firstWork.partitionId()).isEqualTo(fixture.partitionId()); + assertThat(firstWork.memberOperations()).hasSize(2); + assertThat(secondWork.memberOperations()) + .extracting(CanonicalGameplayIssuerBootstrapMemberOperation::operationId) + .containsExactlyElementsOf( + firstWork.memberOperations().stream() + .map(CanonicalGameplayIssuerBootstrapMemberOperation::operationId) + .toList()); + assertThat(firstWork.memberOperations()) + .extracting(CanonicalGameplayIssuerBootstrapMemberOperation::operationId) + .doesNotHaveDuplicates(); + assertThat(firstWork.memberOperations()) + .extracting(CanonicalGameplayIssuerBootstrapMemberOperation::expectedBindingPresent) + .containsOnly(false); + assertThat(firstWork.memberOperations().get(1).operationFence()) + .isGreaterThan(firstWork.memberOperations().getFirst().operationFence()); + assertThat(firstWork.memberOperations().get(1).localMemberGeneration()) + .isGreaterThan(firstWork.memberOperations().getFirst().localMemberGeneration()); + for (var operation : firstWork.memberOperations()) { + assertThat(operation.expectedMemberValue().reservation().partitionId()) + .isEqualTo(firstWork.partitionId()); + assertThat(operation.status()) + .isEqualTo( + CanonicalGameplayIssuerBootstrapMemberOperation.Status.PENDING_PHYSICAL_PROOF); + } + assertThat( + fixture + .testSchema() + .dsl() + .fetchSingle( + "SELECT counter_version FROM game_session_canonical_issuer_bootstrap_member_op_counter" + + " WHERE issuer_id = ?", + ISSUER) + .get(0, Long.class)) + .isEqualTo(2L); + + BigInteger emptyPartition = fixture.partitionId().add(BigInteger.ONE).mod(PARTITION_COUNT); + var empty = + new CanonicalGameplayIssuerBootstrapMemberOperationRepository(fixture.testSchema().dsl()) + .preparePartitionWork( + fixture.intent().operationId(), + fixture.requestId(), + emptyPartition, + fixture.currentAccountCheckpoint(), + stableIncarnation("stable-a")); + assertThat(empty.buildPlan().planDigest()).isEqualTo(fixture.plan().planDigest()); + assertThat(empty.partitionId()).isEqualTo(emptyPartition); + assertThat(empty.memberOperations()).isEmpty(); + assertThat( + fixture + .testSchema() + .dsl() + .fetchSingle( + "SELECT counter_version FROM game_session_canonical_issuer_bootstrap_member_op_counter" + + " WHERE issuer_id = ?", + ISSUER) + .get(0, Long.class)) + .isEqualTo(2L); + } finally { + executor.shutdownNow(); + dropSchema(fixture.testSchema().schema()); + } + } + + @Test + void wrongRequestCheckpointAndChangedFrozenSourceRefuseWithoutAllocatingCounters() { + Fixture fixture = + pendingFixture( + "gs_bootstrap_member_refusal_", PARTITION_CAPACITY, LAYOUT_VERSION, false, true); + try { + migrateRemaining(fixture.testSchema()); + var owner = + new CanonicalGameplayIssuerBootstrapMemberOperationRepository(fixture.testSchema().dsl()); + assertThatThrownBy( + () -> + owner.preparePartitionWork( + fixture.intent().operationId(), + UUID.randomUUID(), + fixture.partitionId(), + fixture.currentAccountCheckpoint(), + stableIncarnation("stable-a"))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + owner.preparePartitionWork( + fixture.intent().operationId(), + fixture.requestId(), + fixture.partitionId(), + sourceCheckpoint(BigInteger.valueOf(8)), + stableIncarnation("stable-a"))) + .isInstanceOf(IllegalStateException.class); + assertThat( + fixture + .testSchema() + .dsl() + .fetchSingle( + "SELECT count(*) FROM game_session_canonical_issuer_bootstrap_member_op_counter") + .get(0, Long.class)) + .isZero(); + + fixture + .testSchema() + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_partition_reservation" + + " SET coverage_fence = coverage_fence + 1 WHERE reservation_id = ?", + fixture.preparedBinding().issuerReservationId()); + assertThatThrownBy( + () -> + owner.preparePartitionWork( + fixture.intent().operationId(), + fixture.requestId(), + fixture.partitionId(), + fixture.currentAccountCheckpoint(), + stableIncarnation("stable-a"))) + .isInstanceOf(IllegalStateException.class); + assertThat( + rowImages( + fixture.testSchema().dsl(), + "game_session_canonical_issuer_bootstrap_member_operation")) + .isEmpty(); + assertThat( + fixture + .testSchema() + .dsl() + .fetchSingle( + "SELECT count(*) FROM game_session_canonical_issuer_bootstrap_member_op_counter") + .get(0, Long.class)) + .isZero(); + } finally { + dropSchema(fixture.testSchema().schema()); + } + } + + @Test + void missingPlanMissingControlAndBlockedLayoutRefuseWithoutMemberOperation() { + Fixture missingPlan = + pendingFixture( + "gs_bootstrap_member_no_plan_", PARTITION_CAPACITY, LAYOUT_VERSION, false, false); + try { + migrateRemaining(missingPlan.testSchema()); + assertThatThrownBy( + () -> + new CanonicalGameplayIssuerBootstrapMemberOperationRepository( + missingPlan.testSchema().dsl()) + .preparePartitionWork( + missingPlan.intent().operationId(), + missingPlan.requestId(), + missingPlan.partitionId(), + missingPlan.currentAccountCheckpoint(), + stableIncarnation("stable-a"))) + .isInstanceOf(IllegalStateException.class); + assertNoIssuedRows(missingPlan.testSchema().dsl()); + } finally { + dropSchema(missingPlan.testSchema().schema()); + } + + Fixture missingControl = + pendingFixture( + "gs_bootstrap_member_no_control_", PARTITION_CAPACITY, LAYOUT_VERSION, false, true); + try { + migrateRemaining(missingControl.testSchema()); + missingControl + .testSchema() + .dsl() + .execute( + "ALTER TABLE game_session_canonical_issuer_layout_bootstrap_control" + + " DROP CONSTRAINT fk_gs_issuer_layout_bootstrap_control_intent"); + missingControl + .testSchema() + .dsl() + .execute( + "DELETE FROM game_session_canonical_issuer_layout_bootstrap_control WHERE issuer_id = ?", + ISSUER); + assertThatThrownBy( + () -> + new CanonicalGameplayIssuerBootstrapMemberOperationRepository( + missingControl.testSchema().dsl()) + .preparePartitionWork( + missingControl.intent().operationId(), + missingControl.requestId(), + missingControl.partitionId(), + missingControl.currentAccountCheckpoint(), + stableIncarnation("stable-a"))) + .isInstanceOf(IllegalStateException.class); + assertNoIssuedRows(missingControl.testSchema().dsl()); + } finally { + dropSchema(missingControl.testSchema().schema()); + } + + Fixture blockedLayout = + pendingFixture( + "gs_bootstrap_member_bad_layout_", + PARTITION_CAPACITY, + LAYOUT_VERSION.add(BigInteger.ONE), + false, + true); + try { + assertThat(blockedLayout.plan().state()) + .isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.BLOCKED); + migrateRemaining(blockedLayout.testSchema()); + assertThatThrownBy( + () -> + new CanonicalGameplayIssuerBootstrapMemberOperationRepository( + blockedLayout.testSchema().dsl()) + .preparePartitionWork( + blockedLayout.intent().operationId(), + blockedLayout.requestId(), + blockedLayout.partitionId(), + blockedLayout.currentAccountCheckpoint(), + stableIncarnation("stable-a"))) + .isInstanceOf(IllegalStateException.class); + assertNoIssuedRows(blockedLayout.testSchema().dsl()); + } finally { + dropSchema(blockedLayout.testSchema().schema()); + } + } + + private static CanonicalGameplayIssuerBootstrapPartitionWork preparePartitionAtGate( + Fixture fixture, CountDownLatch ready, CountDownLatch start) throws InterruptedException { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Test start gate timed out"); + } + return new CanonicalGameplayIssuerBootstrapMemberOperationRepository(fixture.testSchema().dsl()) + .preparePartitionWork( + fixture.intent().operationId(), + fixture.requestId(), + fixture.partitionId(), + fixture.currentAccountCheckpoint(), + stableIncarnation("stable-a")); + } + + private static Fixture pendingFixture( + String prefix, + BigInteger reservationCapacity, + BigInteger descriptorLayoutVersion, + boolean addReservationOnly, + boolean createPlan) { + TestSchema testSchema = newTestSchemaAtVersion(prefix, "1030"); + establishActualLegacyDisposition(testSchema.dsl()); + CanonicalGameplayBindingTransitionSnapshot preparedBinding = + prepareActualBinding( + new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()), reservationCapacity); + BigInteger partitionId = preparedBinding.candidate().bindingRef().partitionId(PARTITION_COUNT); + if (addReservationOnly) { + insertReservationOnly( + testSchema.dsl(), + preparedBinding.candidate(), + preparedBinding.inventoryRevision(), + reservationCapacity, + PARTITION_COUNT, + partitionId); + } + UUID requestId = UUID.randomUUID(); + var checkpoint = sourceCheckpoint(BigInteger.valueOf(7)); + var intent = + new CanonicalGameplayIssuerLayoutBootstrapRepository(testSchema.dsl()) + .beginInitialBootstrapIntent( + requestId, + descriptor(descriptorLayoutVersion, PARTITION_COUNT, reservationCapacity), + checkpoint); + migrateThrough1031(testSchema); + CanonicalGameplayIssuerPartitionBuildPlan plan = + createPlan + ? new CanonicalGameplayIssuerPartitionBuildRepository(testSchema.dsl()) + .prepareInitialBuildPlan(intent.operationId(), requestId) + : null; + return new Fixture( + testSchema, preparedBinding, intent, requestId, checkpoint, partitionId, plan); + } + + private static CanonicalGameplayBindingTransitionSnapshot prepareActualBinding( + CanonicalGameplayBindingInventoryRepository inventory, BigInteger reservationCapacity) { + UUID transitionId = UUID.randomUUID(); + UUID reservationId = UUID.randomUUID(); + UUID reservationFence = UUID.randomUUID(); + UUID issuerCoverageOperationId = UUID.randomUUID(); + var candidate = + new CanonicalGameplayBindingIdentity( + ACCOUNT_ID, + TENANT_ID, + NAMESPACE_ID, + CHARACTER_ID, + "SHARED", + GAME_INSTANCE_ID, + 23L, + UUID.fromString("77777777-7777-4777-8777-777777777777").toString(), + REGION_ID, + BigInteger.valueOf(12), + ISSUER, + BigInteger.valueOf(7), + LAYOUT_VERSION, + PARTITION_COUNT, + reservationCapacity); + return inventory.prepare( + new CanonicalGameplayBindingTransitionRequest( + transitionId, + UUID.randomUUID(), + candidate, + new CanonicalIssuerReservationFenceEvidence( + reservationId, + reservationFence, + issuerCoverageOperationId, + BigInteger.valueOf(17), + BigInteger.valueOf(19), + BigInteger.ONE), + null, + null)); + } + + private static void insertReservationOnly( + DSLContext dsl, + CanonicalGameplayBindingIdentity template, + BigInteger revision, + BigInteger capacity, + BigInteger partitionCount, + BigInteger partitionId) { + UUID sessionUuid = sessionUuidForPartition(template, partitionCount, partitionId); + UUID reservationId = UUID.randomUUID(); + UUID transitionId = UUID.randomUUID(); + UUID reservationFence = UUID.randomUUID(); + UUID originalCoverageOperationId = UUID.randomUUID(); + String sessionId = sessionUuid.toString(); + byte[] bindingRef = + CanonicalGameplayBindingRef.of( + template.tenantId().toString(), template.gameInstanceId().toString(), sessionId) + .bytes(); + dsl.execute( + "INSERT INTO game_session_canonical_issuer_partition_reservation" + + " (reservation_id, binding_ref, account_id, tenant_id, game_instance_id," + + " runtime_game_instance_id, session_id, binding_generation, transition_id, issuer_id," + + " issuer_auth_generation, playable_state_namespace_id, character_id," + + " playable_state_scope, region_id, region_epoch, partition_id," + + " issuer_index_layout_version, issuer_index_partition_count," + + " issuer_index_partition_capacity, lifecycle, reservation_fence," + + " issuer_coverage_operation_id, issuer_coverage_operation_fence, coverage_fence," + + " inventory_snapshot_revision, inventory_revision)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'RESERVED'," + + " ?, ?, 17, 19, ?, ?)", + reservationId, + bindingRef, + template.accountId(), + template.tenantId(), + template.gameInstanceId(), + template.runtimeGameInstanceId(), + sessionId, + transitionId, + ISSUER, + new BigDecimal(template.issuerAuthGeneration()), + template.playableStateNamespaceId(), + UUID.fromString("88888888-8888-4888-8888-888888888888"), + template.playableStateScope(), + template.regionId(), + new BigDecimal(template.regionEpoch()), + new BigDecimal(partitionId), + new BigDecimal(LAYOUT_VERSION), + new BigDecimal(partitionCount), + new BigDecimal(capacity), + reservationFence, + originalCoverageOperationId, + new BigDecimal(revision), + new BigDecimal(revision)); + } + + private static UUID sessionUuidForPartition( + CanonicalGameplayBindingIdentity template, + BigInteger partitionCount, + BigInteger targetPartition) { + for (int candidate = 1; candidate <= 10_000; candidate++) { + UUID sessionUuid = + UUID.nameUUIDFromBytes( + ("issuer-bootstrap-member-session-" + candidate).getBytes(StandardCharsets.UTF_8)); + byte[] bindingRef = + CanonicalGameplayBindingRef.of( + template.tenantId().toString(), + template.gameInstanceId().toString(), + sessionUuid.toString()) + .bytes(); + if (CanonicalGameplayBindingRef.fromExactBytes(bindingRef) + .partitionId(partitionCount) + .equals(targetPartition)) { + return sessionUuid; + } + } + throw new IllegalStateException("Could not prepare a reservation in the target partition"); + } + + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor + descriptor(BigInteger version, BigInteger count, BigInteger capacity) { + String encoded = + "issuer-layout-descriptor/v1|" + + ISSUER + + "|" + + version + + "|" + + count + + "|" + + capacity + + "|" + + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY; + return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor( + ISSUER, + version, + count, + capacity, + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY, + encoded.getBytes(StandardCharsets.UTF_8)); + } + + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + sourceCheckpoint(BigInteger issuerGeneration) { + long sequence = issuerGeneration.longValueExact() - 1L; + var event = + AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + UUID.randomUUID().toString(), + UUID.randomUUID().toString(), + AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + ISSUER, + Long.toString(sequence), + ISSUER, + issuerGeneration.toString(), + issuerGeneration.toString(), + "ISSUER_SECURITY_CHANGE")); + byte[] eventBytes = event.canonicalJsonUtf8(); + return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint( + ISSUER, issuerGeneration, eventBytes, eventBytes); + } + + private static CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation + stableIncarnation(String seed) { + String digest = digest(seed); + return new CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation( + "controlled-attestor-" + seed, + digest, + new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "controlled-deployment-" + seed, + "deployment-generation-" + seed, + List.of("controlled-node-" + seed), + "controlled-redis-build-" + seed, + "controlled-lua-registry-" + seed, + digest, + "READY", + "boot-" + seed, + "startup-" + seed, + "storage-" + seed, + "aof-" + seed), + digest, + digest); + } + + private static String digest(String text) { + try { + return "sha256:" + + java.util.HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(text.getBytes(StandardCharsets.UTF_8))); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static void establishActualLegacyDisposition(DSLContext dsl) { + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); + UUID cohortId = UUID.randomUUID(); + UUID writerFence = UUID.randomUUID(); + var storageIdentity = + new CanonicalGameplayLegacyMigrationStorageIdentity( + "controlled-cluster-uid", + "controlled-namespace-uid", + "controlled-producer-pod-uid", + "controlled-container-id", + "controlled-node-uid", + "123456789", + 42L, + "controlled-postgres-volume-uid", + "controlled-redis-run-id", + "controlled-redis-volume-uid"); + var fencedCohort = + new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { + @Override + public UUID cohortId() { + return cohortId; + } + + @Override + public UUID legacyWriterFence() { + return writerFence; + } + + @Override + public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + return storageIdentity; + } + + @Override + public void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity expected) { + if (!storageIdentity.equals(expected)) { + throw new IllegalStateException("Controlled fixture storage identity changed"); + } + } + }; + var owner = + new CanonicalGameplayLegacyMigrationOwner( + migration, + inventory, + () -> fencedCohort, + ignored -> + new CanonicalGameplayLegacyMigrationSourceSnapshot( + EnumSet.of( + Family.TENANT_SESSION_CONTEXT, + Family.SESSION_ALIAS_CONTEXT, + Family.GAMEPLAY_IDENTITY_CONTEXT, + Family.GAMEPLAY_NAME_CONTEXT, + Family.MOVEMENT_EFFECT, + Family.DURABLE_EFFECT), + List.of()), + new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { + @Override + public void rebuildExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + CanonicalGameplayLegacyMigrationSourceSnapshot source, + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot + canonical) { + assertThat(canonical.bindings()).isEmpty(); + assertThat(canonical.reservations()).isEmpty(); + } + + @Override + public CanonicalGameplayLegacyMigrationReadback readBackExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot + canonical) { + assertThat(canonical.bindings()).isEmpty(); + return new CanonicalGameplayLegacyMigrationReadback( + List.of(), List.of(), List.of(), List.of()); + } + }); + assertThat(owner.migrate().state()) + .isEqualTo(CanonicalGameplayLegacyMigrationOperation.State.VERIFIED); + } + + private static void migrateThrough1031(TestSchema testSchema) { + Flyway.configure() + .dataSource(testSchema.dataSource()) + .schemas(testSchema.schema()) + .defaultSchema(testSchema.schema()) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("1031")) + .load() + .migrate(); + } + + private static void migrateRemaining(TestSchema testSchema) { + Flyway.configure() + .dataSource(testSchema.dataSource()) + .schemas(testSchema.schema()) + .defaultSchema(testSchema.schema()) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + } + + private static TestSchema newTestSchemaAtVersion(String prefix, String version) { + String schema = prefix + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION); + if (version != null) configuration.target(MigrationVersion.fromVersion(version)); + configuration.load().migrate(); + return new TestSchema(schema, dataSource, DSL.using(dataSource, SQLDialect.POSTGRES)); + } + + private static Map> rowSnapshots(DSLContext dsl) { + Map> snapshots = new LinkedHashMap<>(); + for (String table : RETAINED_TABLES) snapshots.put(table, rowImages(dsl, table)); + return Map.copyOf(snapshots); + } + + private static List historySnapshot(DSLContext dsl) { + return dsl.fetch( + "SELECT to_jsonb(history_row)::text AS row_image FROM flyway_schema_history history_row" + + " ORDER BY installed_rank") + .getValues("row_image", String.class); + } + + private static List rowImages(DSLContext dsl, String tableName) { + return dsl.fetch( + "SELECT to_jsonb(retained_row)::text AS row_image FROM " + + tableName + + " retained_row ORDER BY to_jsonb(retained_row)::text") + .getValues("row_image", String.class); + } + + private static void assertNoIssuedRows(DSLContext dsl) { + assertThat(rowImages(dsl, "game_session_canonical_issuer_bootstrap_member_operation")) + .isEmpty(); + assertThat(rowImages(dsl, "game_session_canonical_issuer_bootstrap_member_op_counter")) + .isEmpty(); + } + + private static DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + String jdbcUrl = postgres.getJdbcUrl(); + String separator = jdbcUrl.contains("?") ? "&" : "?"; + dataSource.setUrl(jdbcUrl + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } + + private static void dropSchema(String schema) { + try (var connection = dataSource("public").getConnection()) { + DSL.using(connection, SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } catch (Exception failure) { + throw new IllegalStateException( + "Could not drop the owned member-operation test schema", failure); + } + } + + private record Fixture( + TestSchema testSchema, + CanonicalGameplayBindingTransitionSnapshot preparedBinding, + CanonicalGameplayIssuerLayoutBootstrapIntent intent, + UUID requestId, + CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + currentAccountCheckpoint, + BigInteger partitionId, + CanonicalGameplayIssuerPartitionBuildPlan plan) {} + + private record TestSchema(String schema, DriverManagerDataSource dataSource, DSLContext dsl) {} +} 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 c8bcc5c681..539de03fac 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 @@ -107,7 +107,52 @@ void populatedPendingIntentRetainsCompleteCohortAndBothCoverageTuplesAcrossConcu List inventoryClockBefore = rowImages(testSchema.dsl(), "game_session_canonical_binding_inventory_clock"); List migrationHistoryBefore = rowImages(testSchema.dsl(), "flyway_schema_history"); + List retainedSourceTables = + List.of( + "game_session_canonical_gameplay_binding_inventory", + "game_session_canonical_issuer_partition_reservation", + "game_session_canonical_issuer_layout_bootstrap_intent", + "game_session_canonical_issuer_layout_bootstrap_control", + "game_session_canonical_issuer_layout_bootstrap_cohort_row", + "game_session_canonical_binding_transition", + "game_session_canonical_binding_account_index_obligation", + "game_session_canonical_binding_issuer_index_obligation", + "game_session_canonical_binding_region_bridge_obligation", + "game_session_canonical_binding_inventory_clock"); + List> retainedRowsWithXminBefore = + retainedSourceTables.stream() + .map(table -> rowImagesWithXmin(testSchema.dsl(), table)) + .toList(); + + migrateThrough1031(testSchema); + List migrationHistoryAfter1031 = rowImages(testSchema.dsl(), "flyway_schema_history"); + assertThat(migrationHistoryAfter1031) + .hasSize(migrationHistoryBefore.size() + 1) + .containsAll(migrationHistoryBefore); + assertThat( + testSchema + .dsl() + .fetchSingle("SELECT script FROM flyway_schema_history WHERE version = '1031'") + .get(0, String.class)) + .isEqualTo("V1031__canonical_issuer_partition_build_plan.sql"); + assertThat( + retainedSourceTables.stream() + .map(table -> rowImagesWithXmin(testSchema.dsl(), table)) + .toList()) + .isEqualTo(retainedRowsWithXminBefore); + migrateRemaining(testSchema); + List migrationHistoryAfterCurrent = + rowImages(testSchema.dsl(), "flyway_schema_history"); + assertThat(migrationHistoryAfterCurrent) + .hasSize(migrationHistoryAfter1031.size() + 1) + .containsAll(migrationHistoryAfter1031); + assertThat( + testSchema + .dsl() + .fetchSingle("SELECT script FROM flyway_schema_history WHERE version = '1032'") + .get(0, String.class)) + .isEqualTo("V1032__canonical_issuer_bootstrap_member_operation.sql"); var ready = new CountDownLatch(2); var start = new CountDownLatch(1); @@ -232,9 +277,12 @@ void populatedPendingIntentRetainsCompleteCohortAndBothCoverageTuplesAcrossConcu assertThat(rowImages(testSchema.dsl(), "game_session_canonical_binding_inventory_clock")) .containsExactlyElementsOf(inventoryClockBefore); List migrationHistoryAfter = rowImages(testSchema.dsl(), "flyway_schema_history"); - assertThat(migrationHistoryAfter) - .hasSize(migrationHistoryBefore.size() + 1) - .containsAll(migrationHistoryBefore); + assertThat(migrationHistoryAfter).containsExactlyElementsOf(migrationHistoryAfterCurrent); + assertThat( + retainedSourceTables.stream() + .map(table -> rowImagesWithXmin(testSchema.dsl(), table)) + .toList()) + .isEqualTo(retainedRowsWithXminBefore); } finally { executor.shutdownNow(); dropSchema(testSchema.schema()); @@ -320,9 +368,9 @@ void immutableBuildArtifactsRejectTruncateAndRetainTheirCompletePostimage() { + " game_session_canonical_issuer_partition_build_plan," + " game_session_canonical_issuer_partition_build_cohort_row," + " game_session_canonical_issuer_partition_build_member_work," - + " game_session_canonical_issuer_partition_build_blocker")) + + " game_session_canonical_issuer_partition_build_blocker CASCADE")) .isInstanceOf(DataAccessException.class) - .hasMessageContaining("issuer partition build preparation artifacts are immutable"); + .hasMessageContaining("artifacts are immutable"); assertThat(rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_build_plan")) .containsExactlyElementsOf(planBefore); @@ -1208,6 +1256,18 @@ private static TestSchema newTestSchemaAtVersion(String prefix, String version) return new TestSchema(schema, dataSource, DSL.using(dataSource, SQLDialect.POSTGRES)); } + private static void migrateThrough1031(TestSchema testSchema) { + Flyway.configure() + .dataSource(testSchema.dataSource()) + .schemas(testSchema.schema()) + .defaultSchema(testSchema.schema()) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("1031")) + .load() + .migrate(); + } + private static void migrateRemaining(TestSchema testSchema) { Flyway.configure() .dataSource(testSchema.dataSource()) @@ -1317,6 +1377,14 @@ private static List rowImages(DSLContext dsl, String tableName) { .getValues("row_image", String.class); } + private static List rowImagesWithXmin(DSLContext dsl, String tableName) { + return dsl.fetch( + "SELECT xmin::text || ':' || to_jsonb(retained_row)::text AS row_image FROM " + + tableName + + " retained_row ORDER BY to_jsonb(retained_row)::text, xmin::text") + .getValues("row_image", String.class); + } + private static void dropSchema(String schema) { try (Connection connection = dataSource("public").getConnection()) { DSL.using(connection, SQLDialect.POSTGRES) From 81600188f7c823e4595ca5cc090d0940f64e48e3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 26 Oct 2026 15:50:46 +1300 Subject: [PATCH 06/34] Qualify composed issuer partition projection and exact readback --- ...IssuerBootstrapPartitionPhysicalCodec.java | 87 ++++++++++---- ...layIssuerBootstrapPartitionRedisOwner.java | 81 +++++++------ ...rapPartitionRedisOwnerIntegrationTest.java | 113 +++++++++++------- 3 files changed, 178 insertions(+), 103 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.java index 5ec07768b3..70040fb7ae 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.java @@ -25,7 +25,9 @@ import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; -/** Narrow canonical metadata and exact field-set codec for one initial-bootstrap issuer partition. */ +/** + * Narrow canonical metadata and exact field-set codec for one initial-bootstrap issuer partition. + */ final class CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec { static final String METADATA_FIELD = "!issuer-partition-bootstrap/v1"; static final String RESERVATION_FIELD_PREFIX = "!issuer-reservation-capacity/v1:"; @@ -84,13 +86,15 @@ static PhysicalFieldSet expectedFields(CanonicalGameplayIssuerBootstrapPartition if (valueBytes.length == 0 || valueBytes.length > MAX_VALUE_BYTES) { throw invalid("Exact SQL-issued v2 member exceeds its resource limit"); } - CanonicalGameplayIssuerMemberV2Value decoded = CanonicalGameplayIssuerMemberV2Codec.decode(valueBytes); + CanonicalGameplayIssuerMemberV2Value decoded = + CanonicalGameplayIssuerMemberV2Codec.decode(valueBytes); if (!decoded.equals(value) || !Arrays.equals(valueBytes, CanonicalGameplayIssuerMemberV2Codec.encode(decoded))) { throw invalid("SQL-issued v2 member bytes do not round-trip exactly"); } UUID reservationId = value.reservation().reservationId(); - if (!reservations.add(reservationId)) throw invalid("Duplicate partition reservation identity"); + if (!reservations.add(reservationId)) + throw invalid("Duplicate partition reservation identity"); byte[] bindingRefBytes = value.owner().bindingRef().bytes(); if (bindingRefBytes.length == 0 || bindingRefBytes.length > MAX_BINDING_REF_BYTES) { @@ -120,7 +124,8 @@ static PhysicalFieldSet expectedFields(CanonicalGameplayIssuerBootstrapPartition throw invalid("Issuer bootstrap partition field set exceeds its bounded resource limits"); } if (BigInteger.valueOf(partitionCapacityCount) - .compareTo(intent.layoutDescriptor().partitionCapacity()) > 0) { + .compareTo(intent.layoutDescriptor().partitionCapacity()) + > 0) { throw invalid("Prepared issuer partition exceeds its exact finite capacity"); } long aggregateCapacity = @@ -128,7 +133,10 @@ static PhysicalFieldSet expectedFields(CanonicalGameplayIssuerBootstrapPartition .filter(CanonicalGameplayIssuerPartitionBuildPlan.MemberWork::countsTowardCapacity) .count(); BigInteger aggregateBound = - intent.layoutDescriptor().partitionCount().multiply(intent.layoutDescriptor().partitionCapacity()); + intent + .layoutDescriptor() + .partitionCount() + .multiply(intent.layoutDescriptor().partitionCapacity()); if (BigInteger.valueOf(aggregateCapacity).compareTo(aggregateBound) > 0) { throw invalid("Prepared issuer aggregate capacity exceeds its exact finite layout bound"); } @@ -155,7 +163,8 @@ static void requireExactMetadata(byte[] encoded, byte[] expected) { } try { JsonNode decoded = JSON.readTree(strictUtf8(encoded)); - if (!(decoded instanceof ObjectNode root)) throw invalid("Bootstrap metadata must be an object"); + if (!(decoded instanceof ObjectNode root)) + throw invalid("Bootstrap metadata must be an object"); requireExactFields( root, Set.of( @@ -214,7 +223,9 @@ private static void validatePreparedWork(CanonicalGameplayIssuerBootstrapPartiti CanonicalGameplayBindingRef reference = CanonicalGameplayBindingRef.fromExactBytes(member.bindingRef()); if (member.workOrdinal() != index - || !member.plannedPartitionId().equals(reference.partitionId(intent.layoutDescriptor().partitionCount())) + || !member + .plannedPartitionId() + .equals(reference.partitionId(intent.layoutDescriptor().partitionCount())) || !reservationIds.add(member.reservationId()) || !memberOperationIds.add(member.memberOperationId())) { throw invalid("Prepared issuer plan has a duplicate or mis-mapped cohort member"); @@ -245,20 +256,35 @@ private static void validatePreparedWork(CanonicalGameplayIssuerBootstrapPartiti || !reservation.lifecycle().name().equals(planned.reservationLifecycle()) || !reservation.partitionId().equals(planned.plannedPartitionId()) || !reservation.partitionId().equals(planned.originalPartitionId()) - || !reservation.issuerCoverageOperationId().equals(planned.originalIssuerCoverageOperationId()) - || !reservation.issuerCoverageOperationFence().equals(planned.originalIssuerCoverageOperationFence()) + || !reservation + .issuerCoverageOperationId() + .equals(planned.originalIssuerCoverageOperationId()) + || !reservation + .issuerCoverageOperationFence() + .equals(planned.originalIssuerCoverageOperationFence()) || !reservation.coverageFence().equals(planned.originalCoverageFence()) - || !reservation.inventorySnapshotRevision().equals(planned.originalInventorySnapshotRevision()) + || !reservation + .inventorySnapshotRevision() + .equals(planned.originalInventorySnapshotRevision()) || !value.owner().issuerIndexLayoutVersion().equals(planned.originalLayoutVersion()) || !value.owner().issuerIndexPartitionCount().equals(planned.originalPartitionCount()) - || !value.owner().issuerIndexPartitionCapacity().equals(planned.originalPartitionCapacity()) + || !value + .owner() + .issuerIndexPartitionCapacity() + .equals(planned.originalPartitionCapacity()) || !Arrays.equals(memberRef.bytes(), planned.bindingRef()) || !value.incarnation().equals(work.incarnation()) || !value.anchor().issuerCoverageOperationId().equals(intent.operationId()) || !value.anchor().operationFence().equals(intent.operationFence()) || !value.anchor().coverageFence().equals(intent.coverageFence()) - || !value.anchor().issuerInventorySnapshotRevision().equals(intent.inventorySnapshotRevision()) - || !value.layoutDescriptor().descriptorDigest().equals(intent.layoutDescriptor().descriptorDigest()) + || !value + .anchor() + .issuerInventorySnapshotRevision() + .equals(intent.inventorySnapshotRevision()) + || !value + .layoutDescriptor() + .descriptorDigest() + .equals(intent.layoutDescriptor().descriptorDigest()) || !sameLayout(value.layoutDescriptor(), intent.layoutDescriptor()) || !sameCheckpoint(value.sourceCheckpoint(), intent.sourceCheckpoint()) || !value.issuerControlEpoch().equals(intent.controlEpoch()) @@ -267,9 +293,9 @@ private static void validatePreparedWork(CanonicalGameplayIssuerBootstrapPartiti || !issuedGenerations.add(operation.localMemberGeneration()) || operation.countsTowardCapacity() != (value.reservation().lifecycle() - != net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation.Lifecycle.RELEASED) - || operation.expectedBindingPresent() - != (planned.bindingSourceRowOrdinal() != null)) { + != net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation + .Lifecycle.RELEASED) + || operation.expectedBindingPresent() != (planned.bindingSourceRowOrdinal() != null)) { throw invalid("SQL-issued member differs from the complete frozen preparation tuple"); } } @@ -319,7 +345,8 @@ private static byte[] encodeMetadata( bootstrap.put("controlEpoch", intent.controlEpoch().toString()); bootstrap.put("operationFence", intent.operationFence().toString()); bootstrap.put("coverageFence", intent.coverageFence().toString()); - bootstrap.put("issuerInventorySnapshotRevision", intent.inventorySnapshotRevision().toString()); + bootstrap.put( + "issuerInventorySnapshotRevision", intent.inventorySnapshotRevision().toString()); bootstrap.put("cohortDigest", intent.cohortDigest()); ObjectNode build = root.putObject("build"); build.put("operationId", work.buildPlan().buildOperationId().toString()); @@ -329,7 +356,8 @@ private static byte[] encodeMetadata( layoutObject.put("partitionCount", layout.partitionCount().toString()); layoutObject.put("partitionCapacity", layout.partitionCapacity().toString()); layoutObject.put("mappingIdentity", layout.mappingIdentity()); - layoutObject.put("descriptorBytes", Base64.getEncoder().encodeToString(layout.exactDescriptorBytes())); + layoutObject.put( + "descriptorBytes", Base64.getEncoder().encodeToString(layout.exactDescriptorBytes())); layoutObject.put("descriptorDigest", layout.descriptorDigest()); ObjectNode anchor = root.putObject("anchor"); anchor.put("issuerCoverageOperationId", intent.operationId().toString()); @@ -337,7 +365,9 @@ private static byte[] encodeMetadata( anchor.put("coverageFence", intent.coverageFence().toString()); anchor.put("issuerInventorySnapshotRevision", intent.inventorySnapshotRevision().toString()); anchor.put("issuerAuthGeneration", source.issuerAuthGeneration().toString()); - anchor.put("sourceCheckpointBytes", Base64.getEncoder().encodeToString(source.exactCheckpointBytes())); + anchor.put( + "sourceCheckpointBytes", + Base64.getEncoder().encodeToString(source.exactCheckpointBytes())); anchor.put("sourceCheckpointDigest", source.checkpointDigest()); putNullableBase64(anchor, "sourceEventBytes", source.latestIssuerEventBytes()); putNullableText(anchor, "sourceEventDigest", source.latestIssuerEventDigest()); @@ -359,13 +389,15 @@ private static byte[] encodeMetadata( deploymentObject.put("storageGeneration", deployment.storageGeneration()); deploymentObject.put("aofGeneration", deployment.aofGeneration()); incarnationObject.put("coordOpsRoAclDigest", incarnation.coordOpsRoAclDigest()); - incarnationObject.put("coordRedisConfigObservedDigest", incarnation.coordRedisConfigObservedDigest()); + incarnationObject.put( + "coordRedisConfigObservedDigest", incarnation.coordRedisConfigObservedDigest()); root.put("plannedAggregateCapacityCount", plannedAggregateCapacityCount.toString()); - root.put("plannedPartitionReservationCount", Integer.toString(work.memberOperations().size())); + root.put( + "plannedPartitionReservationCount", Integer.toString(work.memberOperations().size())); root.put("plannedPartitionCapacityCount", Long.toString(plannedPartitionCapacityCount)); - byte[] encoded = - Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); - if (encoded.length > MAX_METADATA_BYTES) throw invalid("Bootstrap metadata exceeds its resource limit"); + byte[] encoded = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + if (encoded.length > MAX_METADATA_BYTES) + throw invalid("Bootstrap metadata exceeds its resource limit"); return encoded; } catch (IOException failure) { throw new IllegalArgumentException("Could not encode canonical bootstrap metadata", failure); @@ -383,7 +415,9 @@ private static void putNullableText(ObjectNode object, String name, String value } private static void putUnique(Map fields, String field, byte[] value) { - if (field == null || field.isEmpty() || field.getBytes(StandardCharsets.UTF_8).length > MAX_BINDING_REF_BYTES + if (field == null + || field.isEmpty() + || field.getBytes(StandardCharsets.UTF_8).length > MAX_BINDING_REF_BYTES || fields.putIfAbsent(field, value.clone()) != null) { throw invalid("Issuer bootstrap field identity is reserved, oversized, or duplicated"); } @@ -398,7 +432,8 @@ private static String strictUtf8(byte[] bytes) { .decode(ByteBuffer.wrap(bytes)) .toString(); } catch (CharacterCodingException malformed) { - throw new IllegalArgumentException("Issuer bootstrap field is not canonical UTF-8", malformed); + throw new IllegalArgumentException( + "Issuer bootstrap field is not canonical UTF-8", malformed); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwner.java index caff08a9d8..c68d89fac1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwner.java @@ -1,7 +1,7 @@ package net.firedevops.firemud.gamesession.repository; -import io.lettuce.core.RedisFuture; import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisFuture; import io.lettuce.core.ScriptOutputType; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.async.RedisAsyncCommands; @@ -38,9 +38,7 @@ public final class CanonicalGameplayIssuerBootstrapPartitionRedisOwner { private static final List EXPECTED_KEYS = List.of( new RedisScriptDescriptor.KeySpec( - "issuerPartition", - KEY_PREFIX, - RedisScriptDescriptor.HashTagDeclaration.REQUIRED)); + "issuerPartition", KEY_PREFIX, RedisScriptDescriptor.HashTagDeclaration.REQUIRED)); private static final List EXPECTED_ARGUMENTS = List.of( new RedisScriptDescriptor.ArgumentSpec("issuerId"), @@ -49,7 +47,8 @@ public final class CanonicalGameplayIssuerBootstrapPartitionRedisOwner { new RedisScriptDescriptor.ArgumentSpec("partitionCapacity"), new RedisScriptDescriptor.ArgumentSpec("exactBootstrapMetadata"), new RedisScriptDescriptor.ArgumentSpec("memberOperationCount"), - new RedisScriptDescriptor.ArgumentSpec("repeatedBindingRefMemberCapacityFieldBindingPresence")); + new RedisScriptDescriptor.ArgumentSpec( + "repeatedBindingRefMemberCapacityFieldBindingPresence")); private static final List EXPECTED_OUTCOMES = List.of( new RedisScriptDescriptor.OutcomeSpec( @@ -73,7 +72,9 @@ public final class CanonicalGameplayIssuerBootstrapPartitionRedisOwner { private final RedisScriptCatalog catalog; private final CurrentIssuerStateSource currentStateSource; - /** The Redis client, manual owner contribution catalog, and protected local source are explicit. */ + /** + * The Redis client, manual owner contribution catalog, and protected local source are explicit. + */ public CanonicalGameplayIssuerBootstrapPartitionRedisOwner( RedisClient redisClient, RedisScriptCatalog catalog, @@ -114,8 +115,7 @@ public Readback buildAndRead(CanonicalGameplayIssuerBootstrapPartitionWork work) } } - private long writeOneKey( - byte[] script, byte[] key, byte[][] arguments) { + private long writeOneKey(byte[] script, byte[] key, byte[][] arguments) { requireNoAmbientTransaction(); try (StatefulRedisConnection connection = redisClient.connect(ByteArrayCodec.INSTANCE)) { @@ -125,11 +125,7 @@ private long writeOneKey( if (!digest("SHA-1", script).equals(loadedSha)) throw unavailable(); Long reply = await( - commands.evalsha( - loadedSha, - ScriptOutputType.INTEGER, - new byte[][] {key}, - arguments)); + commands.evalsha(loadedSha, ScriptOutputType.INTEGER, new byte[][] {key}, arguments)); if (reply == null) throw unavailable(); return reply; } catch (RuntimeException failure) { @@ -138,7 +134,8 @@ private long writeOneKey( } private PhysicalReadback readExactPhysicalState( - byte[] key, CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.PhysicalFieldSet expected) { + byte[] key, + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.PhysicalFieldSet expected) { requireNoAmbientTransaction(); try (StatefulRedisConnection connection = redisClient.connect(ByteArrayCodec.INSTANCE)) { @@ -162,7 +159,8 @@ private PhysicalReadback readExactPhysicalState( byte[] field = Objects.requireNonNull(entry.getKey(), "Redis field"); byte[] value = Objects.requireNonNull(entry.getValue(), "Redis value"); totalBytes += (long) field.length + value.length; - if (totalBytes > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_TOTAL_HASH_BYTES) { + if (totalBytes + > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_TOTAL_HASH_BYTES) { throw unavailable(); } String encodedField = Base64.getEncoder().encodeToString(field); @@ -175,11 +173,12 @@ private PhysicalReadback readExactPhysicalState( byte[] observed = actual.get(Base64.getEncoder().encodeToString(redisField)); if (!Arrays.equals(entry.getValue(), observed)) throw unavailable(); } - byte[] metadata = actual.get( - Base64.getEncoder() - .encodeToString( - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.METADATA_FIELD - .getBytes(StandardCharsets.US_ASCII))); + byte[] metadata = + actual.get( + Base64.getEncoder() + .encodeToString( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.METADATA_FIELD + .getBytes(StandardCharsets.US_ASCII))); CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.requireExactMetadata( metadata, expected.metadataBytes()); @@ -190,19 +189,23 @@ private PhysicalReadback readExactPhysicalState( if (field.startsWith( CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.RESERVATION_FIELD_PREFIX)) { CanonicalGameplayIssuerMemberV2Value decoded = - CanonicalGameplayIssuerMemberV2Codec.decode(actual.get( - Base64.getEncoder().encodeToString(field.getBytes(StandardCharsets.US_ASCII)))); + CanonicalGameplayIssuerMemberV2Codec.decode( + actual.get( + Base64.getEncoder() + .encodeToString(field.getBytes(StandardCharsets.US_ASCII)))); if (!decoded.equals(CanonicalGameplayIssuerMemberV2Codec.decode(entry.getValue()))) { throw unavailable(); } if (decoded.reservation().lifecycle() - != net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation.Lifecycle.RELEASED) { + != net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation + .Lifecycle.RELEASED) { capacityCount++; } } else if (!field.equals( CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.METADATA_FIELD)) { - CanonicalGameplayIssuerMemberV2Codec.decode(actual.get( - Base64.getEncoder().encodeToString(field.getBytes(StandardCharsets.UTF_8)))); + CanonicalGameplayIssuerMemberV2Codec.decode( + actual.get( + Base64.getEncoder().encodeToString(field.getBytes(StandardCharsets.UTF_8)))); bindingCount++; } } @@ -232,11 +235,12 @@ private void requireFreshCurrentState(CanonicalGameplayIssuerBootstrapPartitionW private RedisScriptDescriptor requireDescriptor() { try { RedisScriptDescriptor descriptor = - catalog.require(CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.SCRIPT_ID); - if (!CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.SCRIPT_ID - .equals(descriptor.scriptId()) - || !CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.RESOURCE_PATH - .equals(descriptor.resourcePath()) + catalog.require( + CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.SCRIPT_ID); + if (!CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.SCRIPT_ID.equals( + descriptor.scriptId()) + || !CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.RESOURCE_PATH.equals( + descriptor.resourcePath()) || !"game-session-service".equals(descriptor.owner()) || !PRINCIPAL.equals(descriptor.principal()) || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION @@ -373,13 +377,17 @@ private static IllegalStateException unavailable(Throwable cause) { return new IllegalStateException("Issuer bootstrap partition projection is unavailable", cause); } - /** Fresh, trusted local read collaborator. No default implementation derives authority from work. */ + /** + * Fresh, trusted local read collaborator. No default implementation derives authority from work. + */ @FunctionalInterface public interface CurrentIssuerStateSource { CurrentIssuerState readFreshCurrentState(); } - /** One current exact Account checkpoint and stable incarnation observation from the collaborator. */ + /** + * One current exact Account checkpoint and stable incarnation observation from the collaborator. + */ public record CurrentIssuerState( CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint accountCheckpoint, CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation) { @@ -391,7 +399,10 @@ public record CurrentIssuerState( private record PhysicalReadback(int fieldCount, int countedReservationCount, int bindingCount) {} - /** Exact physical partition readback; it carries no global aggregate, acknowledgement, or OPEN authority. */ + /** + * Exact physical partition readback; it carries no global aggregate, acknowledgement, or OPEN + * authority. + */ public static final class Readback { private final CanonicalGameplayIssuerBootstrapPartitionWork work; private final int physicalFieldCount; @@ -412,8 +423,8 @@ private Readback( this.plannedAggregateCapacityCount = Objects.requireNonNull(plannedAggregateCapacityCount); if (observed.fieldCount() != 1 + physicalReservationCount + physicalBindingCount || BigInteger.valueOf(observed.countedReservationCount()) - .compareTo( - work.buildPlan().bootstrapIntent().layoutDescriptor().partitionCapacity()) + .compareTo( + work.buildPlan().bootstrapIntent().layoutDescriptor().partitionCapacity()) > 0) { throw unavailable(); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java index 2c707fcbea..4bfd924115 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java @@ -153,13 +153,19 @@ void buildsCompletePopulatedPartitionAndCountsReleasedOnlyAsRetainedEvidence() { .findFirst() .orElseThrow(); var value = active.expectedMemberValue(); - assertThat(value.reservation().issuerCoverageOperationId()) - .isNotEqualTo(value.anchor().issuerCoverageOperationId()); - assertThat(value.reservation().issuerCoverageOperationFence()) - .isNotEqualTo(value.anchor().operationFence()); - assertThat(value.reservation().coverageFence()).isNotEqualTo(value.anchor().coverageFence()); - assertThat(value.reservation().inventorySnapshotRevision()) - .isNotEqualTo(value.anchor().issuerInventorySnapshotRevision()); + var originalReservationCoverageTuple = + List.of( + value.reservation().issuerCoverageOperationId(), + value.reservation().issuerCoverageOperationFence(), + value.reservation().coverageFence(), + value.reservation().inventorySnapshotRevision()); + var bootstrapAnchorTuple = + List.of( + value.anchor().issuerCoverageOperationId(), + value.anchor().operationFence(), + value.anchor().coverageFence(), + value.anchor().issuerInventorySnapshotRevision()); + assertThat(originalReservationCoverageTuple).isNotEqualTo(bootstrapAnchorTuple); var firstOwner = owner(work, currentState(fixture, work)); var first = firstOwner.buildAndRead(work); @@ -283,7 +289,8 @@ void malformedLegacyForeignAndExpiringPhysicalStateRefuseWithoutMutation() { byte[] legacyV1 = "{\"schemaVersion\":1}".getBytes(StandardCharsets.UTF_8); administratorCommands.hset(populatedKey, bindingField, legacyV1); - assertThatThrownBy(() -> owner(populated, currentState(fixture, populated)).buildAndRead(populated)) + assertThatThrownBy( + () -> owner(populated, currentState(fixture, populated)).buildAndRead(populated)) .isInstanceOf(IllegalStateException.class); assertThat(administratorCommands.hget(populatedKey, bindingField)).containsExactly(legacyV1); assertThat(administratorCommands.hlen(populatedKey)).isEqualTo(1L); @@ -294,12 +301,14 @@ void malformedLegacyForeignAndExpiringPhysicalStateRefuseWithoutMutation() { byte[] foreignField = ascii("unrelated-operator-field"); byte[] foreignValue = ascii("retained-source"); administratorCommands.hset(foreignKey, foreignField, foreignValue); - assertThatThrownBy(() -> owner(foreignWork, currentState(fixture, foreignWork)).buildAndRead(foreignWork)) + assertThatThrownBy( + () -> owner(foreignWork, currentState(fixture, foreignWork)).buildAndRead(foreignWork)) .isInstanceOf(IllegalStateException.class); assertThat(administratorCommands.hlen(foreignKey)).isEqualTo(1L); assertThat(administratorCommands.hget(foreignKey, foreignField)).containsExactly(foreignValue); - BigInteger expiringPartition = populated.partitionId().add(BigInteger.valueOf(3)).mod(PARTITION_COUNT); + BigInteger expiringPartition = + populated.partitionId().add(BigInteger.valueOf(3)).mod(PARTITION_COUNT); var expiringWork = partitionWork(fixture, expiringPartition); byte[] expiringKey = key(fixture, expiringPartition); byte[] expiringField = ascii("foreign-ttl-field"); @@ -308,10 +317,13 @@ void malformedLegacyForeignAndExpiringPhysicalStateRefuseWithoutMutation() { administratorCommands.pexpire(expiringKey, 60_000); long ttlBefore = administratorCommands.pttl(expiringKey); - assertThatThrownBy(() -> owner(expiringWork, currentState(fixture, expiringWork)).buildAndRead(expiringWork)) + assertThatThrownBy( + () -> + owner(expiringWork, currentState(fixture, expiringWork)).buildAndRead(expiringWork)) .isInstanceOf(IllegalStateException.class); assertThat(administratorCommands.pttl(expiringKey)).isPositive().isLessThanOrEqualTo(ttlBefore); - assertThat(administratorCommands.hget(expiringKey, expiringField)).containsExactly(expiringValue); + assertThat(administratorCommands.hget(expiringKey, expiringField)) + .containsExactly(expiringValue); BigInteger wrongTypePartition = populated.partitionId().add(BigInteger.valueOf(4)).mod(PARTITION_COUNT); @@ -320,7 +332,9 @@ void malformedLegacyForeignAndExpiringPhysicalStateRefuseWithoutMutation() { byte[] wrongTypeValue = ascii("foreign-persistent-string"); administratorCommands.set(wrongTypeKey, wrongTypeValue); assertThatThrownBy( - () -> owner(wrongTypeWork, currentState(fixture, wrongTypeWork)).buildAndRead(wrongTypeWork)) + () -> + owner(wrongTypeWork, currentState(fixture, wrongTypeWork)) + .buildAndRead(wrongTypeWork)) .isInstanceOf(IllegalStateException.class); assertThat(administratorCommands.type(wrongTypeKey)).isEqualTo("string"); assertThat(administratorCommands.get(wrongTypeKey)).containsExactly(wrongTypeValue); @@ -398,7 +412,8 @@ void changedFreshCheckpointOrIncarnationBeforeAndAfterRedisLeavesNoReadbackCapab } @Test - void retainedCommitAfterLostReplyReplaysFromFreshSqlWorkAndSeparatePhysicalReadback() throws Exception { + void retainedCommitAfterLostReplyReplaysFromFreshSqlWorkAndSeparatePhysicalReadback() + throws Exception { Fixture fixture = fixture(false); CanonicalGameplayIssuerBootstrapPartitionWork work = partitionWork(fixture, fixture.partitionId()); @@ -410,14 +425,12 @@ void retainedCommitAfterLostReplyReplaysFromFreshSqlWorkAndSeparatePhysicalReadb // The test deliberately discards this post-commit script reply to model a lost reply/crash. administratorCommands.evalsha( - scriptSha, - ScriptOutputType.INTEGER, - new byte[][] {key}, - scriptArguments(work, physical)); + scriptSha, ScriptOutputType.INTEGER, new byte[][] {key}, scriptArguments(work, physical)); CanonicalGameplayIssuerBootstrapPartitionWork restartedWork = partitionWork(fixture, work.partitionId()); - var readback = owner(restartedWork, currentState(fixture, restartedWork)).buildAndRead(restartedWork); + var readback = + owner(restartedWork, currentState(fixture, restartedWork)).buildAndRead(restartedWork); assertThat(readback.physicalFieldCount()).isEqualTo(3); assertThat(readback.physicalCountedCapacityCount()).isEqualTo(1); assertThat(statusesRemainPending(fixture.dsl())).isTrue(); @@ -432,8 +445,7 @@ void deliberatelyLowerCapacityLuaArgumentsRefuseWithoutChangingOwnedHashImage() .isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED); assertThat(work.memberOperations()).hasSize(2); assertThat(work.memberOperations()) - .allSatisfy( - operation -> assertThat(operation.countsTowardCapacity()).isTrue()); + .allSatisfy(operation -> assertThat(operation.countsTowardCapacity()).isTrue()); var physical = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.expectedFields(work); var catalog = RedisScriptCatalog.fromContributions( @@ -494,7 +506,8 @@ private Fixture fixture(boolean includeReleasedReservation, int activeBindingCou seedSamePartitionActiveBinding(testSchema.dsl(), partitionId); assertThat(samePartition.bindingRef().partitionId(PARTITION_COUNT)).isEqualTo(partitionId); } - if (includeReleasedReservation) insertReleasedReservation(testSchema.dsl(), active, partitionId); + if (includeReleasedReservation) + insertReleasedReservation(testSchema.dsl(), active, partitionId); UUID requestId = UUID.randomUUID(); var source = sourceCheckpoint(BigInteger.valueOf(7)); @@ -747,7 +760,9 @@ private void insertReleasedReservation( UUID originalCoverageOperationId = UUID.randomUUID(); byte[] bindingRef = CanonicalGameplayBindingRef.of( - template.tenantId().toString(), template.gameInstanceId().toString(), sessionId.toString()) + template.tenantId().toString(), + template.gameInstanceId().toString(), + sessionId.toString()) .bytes(); dsl.execute( "INSERT INTO game_session_canonical_issuer_partition_reservation" @@ -792,11 +807,13 @@ private static UUID sessionUuidForPartition( ("physical-release-session-" + candidate).getBytes(StandardCharsets.UTF_8)); byte[] ref = CanonicalGameplayBindingRef.of( - template.tenantId().toString(), template.gameInstanceId().toString(), session.toString()) + template.tenantId().toString(), + template.gameInstanceId().toString(), + session.toString()) .bytes(); if (CanonicalGameplayBindingRef.fromExactBytes(ref) - .partitionId(PARTITION_COUNT) - .equals(targetPartition) + .partitionId(PARTITION_COUNT) + .equals(targetPartition) && !session.toString().equals(template.sessionId())) { return session; } @@ -838,7 +855,8 @@ private static byte[] lowerCapacityJson(byte[] exactJson) { String fullCapacity = "\"partitionCapacity\":\"" + PARTITION_CAPACITY + "\""; String reducedCapacity = "\"partitionCapacity\":\"1\""; if (!original.contains(fullCapacity)) { - throw new IllegalStateException("Controlled physical input has no exact partition capacity field"); + throw new IllegalStateException( + "Controlled physical input has no exact partition capacity field"); } return original.replace(fullCapacity, reducedCapacity).getBytes(StandardCharsets.UTF_8); } @@ -874,7 +892,8 @@ private static CanonicalGameplayBindingIdentity seedSamePartitionActiveBinding( private static void insertAdditionalActiveSource( DSLContext dsl, CanonicalGameplayBindingIdentity identity) { byte[] bindingRef = identity.bindingRef().bytes(); - BigInteger partitionId = identity.bindingRef().partitionId(identity.issuerIndexPartitionCount()); + BigInteger partitionId = + identity.bindingRef().partitionId(identity.issuerIndexPartitionCount()); UUID accountIndexFence = UUID.randomUUID(); UUID reservationId = UUID.randomUUID(); UUID transitionId = UUID.randomUUID(); @@ -971,15 +990,17 @@ private static void insertAdditionalActiveSource( } private static boolean statusesRemainPending(DSLContext dsl) { - Long operations = - dsl.fetchOne("SELECT count(*) FROM game_session_canonical_issuer_bootstrap_member_operation") - .get(0, Long.class); - Long pending = + var operationsRow = + dsl.fetchOne( + "SELECT count(*) FROM game_session_canonical_issuer_bootstrap_member_operation"); + var pendingRow = dsl.fetchOne( - "SELECT count(*) FROM game_session_canonical_issuer_bootstrap_member_operation" - + " WHERE member_status = 'PENDING_PHYSICAL_PROOF'") - .get(0, Long.class); - return operations.equals(pending); + "SELECT count(*) FROM game_session_canonical_issuer_bootstrap_member_operation" + + " WHERE member_status = 'PENDING_PHYSICAL_PROOF'"); + if (operationsRow == null || pendingRow == null) return false; + Long operations = operationsRow.get(0, Long.class); + Long pending = pendingRow.get(0, Long.class); + return operations != null && pending != null && operations.equals(pending); } private static void establishActualLegacyDisposition(DSLContext dsl) { @@ -1042,7 +1063,8 @@ public void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity e public void rebuildExact( CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, CanonicalGameplayLegacyMigrationSourceSnapshot source, - net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventorySnapshot + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot canonical) { assertThat(canonical.bindings()).isEmpty(); assertThat(canonical.reservations()).isEmpty(); @@ -1051,7 +1073,8 @@ public void rebuildExact( @Override public CanonicalGameplayLegacyMigrationReadback readBackExact( CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, - net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventorySnapshot + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot canonical) { assertThat(canonical.bindings()).isEmpty(); return new CanonicalGameplayLegacyMigrationReadback( @@ -1099,9 +1122,11 @@ private DriverManagerDataSource dataSource(String schema) { private void dropSchema(String schema) { try (Connection connection = dataSource("public").getConnection()) { - DSL.using(connection, SQLDialect.POSTGRES).execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + DSL.using(connection, SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); } catch (SQLException failure) { - throw new IllegalStateException("Could not drop the owned issuer physical test schema", failure); + throw new IllegalStateException( + "Could not drop the owned issuer physical test schema", failure); } } @@ -1112,13 +1137,17 @@ private static RedisClient createRedisClient(String username, String password) { uri.setTimeout(Duration.ofSeconds(5)); RedisClient client = RedisClient.create(uri); client.setOptions( - ClientOptions.builder().autoReconnect(false).protocolVersion(io.lettuce.core.protocol.ProtocolVersion.RESP2).build()); + ClientOptions.builder() + .autoReconnect(false) + .protocolVersion(io.lettuce.core.protocol.ProtocolVersion.RESP2) + .build()); return client; } private static String digest(byte[] bytes) { try { - return "sha256:" + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); } catch (java.security.NoSuchAlgorithmException impossible) { throw new IllegalStateException(impossible); } From 6aaf218b80a662b3d72d55bf0d9e7a0b93609ce1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 26 Oct 2026 15:58:44 +1300 Subject: [PATCH 07/34] Permit exact frozen binding replay during issuer bootstrap intent --- ...calGameplayBindingInventoryRepository.java | 12 ++-- ...outBootstrapRepositoryIntegrationTest.java | 61 +++++++++++++++++-- 2 files changed, 65 insertions(+), 8 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index f0eaebd77a..88f98af39a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -1497,7 +1497,8 @@ private static void requireSameProvisionalOperation( private static CanonicalGameplayBindingTransitionSnapshot prepareInTransaction( DSLContext transaction, CanonicalGameplayBindingTransitionRequest request) { BigInteger revision = lockInventoryRevision(transaction); - requireNoPendingIssuerLayoutBootstrapIntent(transaction, request.candidate().issuerId()); + boolean pendingIssuerLayoutBootstrapIntent = + validatePendingIssuerLayoutBootstrapIntent(transaction, request.candidate().issuerId()); CanonicalGameplayAccountCoverageEvidence accountCoverageEvidence = lockAccountCoverageEvidence(transaction, request.candidate().accountId()); boolean initialBinding = request.expectedPriorBindingRef() == null; @@ -1513,6 +1514,9 @@ private static CanonicalGameplayBindingTransitionSnapshot prepareInTransaction( } return retry; } + if (pendingIssuerLayoutBootstrapIntent) { + throw conflict("Initial issuer-layout bootstrap intent blocks new binding preparation"); + } CanonicalGameplayBindingIdentity candidate = request.candidate(); byte[] candidateRef = candidate.bindingRef().bytes(); @@ -1611,7 +1615,7 @@ private static CanonicalGameplayBindingTransitionSnapshot prepareInTransaction( return prepared; } - private static void requireNoPendingIssuerLayoutBootstrapIntent( + private static boolean validatePendingIssuerLayoutBootstrapIntent( DSLContext transaction, String issuerId) { Record control = transaction.fetchOne( @@ -1627,7 +1631,7 @@ private static void requireNoPendingIssuerLayoutBootstrapIntent( if (orphanIntent != null) { throw conflict("Issuer bootstrap intent exists without its positive current control row"); } - return; + return false; } UUID operationId = control.get("current_operation_id", UUID.class); @@ -1666,7 +1670,7 @@ private static void requireNoPendingIssuerLayoutBootstrapIntent( || readBigInteger(intent, "inventory_snapshot_revision").signum() <= 0) { throw conflict("Issuer bootstrap control does not point to its exact durable intent tuple"); } - throw conflict("Initial issuer-layout bootstrap intent blocks new binding preparation"); + return true; } private static void validateRequest(CanonicalGameplayBindingTransitionRequest request) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java index 519462ba52..57753dd948 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java @@ -306,7 +306,8 @@ void pendingIntentBlocksLaterPreparationWithoutChangingInventoryOrItsCohort() { try { establishActualLegacyDisposition(testSchema.dsl()); var inventory = new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); - prepareActualBinding(inventory); + var originalRequest = actualBindingRequest(PREPARED_CHARACTER_ID); + var originalPreparation = inventory.prepare(originalRequest); var owner = new CanonicalGameplayIssuerLayoutBootstrapRepository(testSchema.dsl()); UUID requestId = UUID.randomUUID(); @@ -326,6 +327,55 @@ void pendingIntentBlocksLaterPreparationWithoutChangingInventoryOrItsCohort() { countRows(testSchema.dsl(), "game_session_canonical_issuer_partition_reservation"); int generationCount = countRows(testSchema.dsl(), "game_session_canonical_binding_generation"); + List inventoryBefore = + rowImages(testSchema.dsl(), "game_session_canonical_gameplay_binding_inventory"); + List transitionBefore = + rowImages(testSchema.dsl(), "game_session_canonical_binding_transition"); + List reservationBefore = + rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_reservation"); + List generationBefore = + rowImages(testSchema.dsl(), "game_session_canonical_binding_generation"); + List accountObligationBefore = + rowImages(testSchema.dsl(), "game_session_canonical_binding_account_index_obligation"); + List issuerObligationBefore = + rowImages(testSchema.dsl(), "game_session_canonical_binding_issuer_index_obligation"); + List regionObligationBefore = + rowImages(testSchema.dsl(), "game_session_canonical_binding_region_bridge_obligation"); + + assertThat(inventory.prepare(originalRequest)).isEqualTo(originalPreparation); + var conflictingRequest = + new CanonicalGameplayBindingTransitionRequest( + originalRequest.transitionId(), + UUID.randomUUID(), + originalRequest.candidate(), + originalRequest.issuerReservation(), + originalRequest.expectedPriorBindingRef(), + originalRequest.expectedPriorBindingGeneration()); + assertThatThrownBy(() -> inventory.prepare(conflictingRequest)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining( + "same transition identity was retried with a different exact request"); + + assertThat(currentInventoryRevision(testSchema.dsl())).isEqualTo(originalInventoryRevision); + assertThat(rowImages(testSchema.dsl(), "game_session_canonical_gameplay_binding_inventory")) + .containsExactlyElementsOf(inventoryBefore); + assertThat(rowImages(testSchema.dsl(), "game_session_canonical_binding_transition")) + .containsExactlyElementsOf(transitionBefore); + assertThat(rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_reservation")) + .containsExactlyElementsOf(reservationBefore); + assertThat(rowImages(testSchema.dsl(), "game_session_canonical_binding_generation")) + .containsExactlyElementsOf(generationBefore); + assertThat( + rowImages( + testSchema.dsl(), "game_session_canonical_binding_account_index_obligation")) + .containsExactlyElementsOf(accountObligationBefore); + assertThat( + rowImages(testSchema.dsl(), "game_session_canonical_binding_issuer_index_obligation")) + .containsExactlyElementsOf(issuerObligationBefore); + assertThat( + rowImages( + testSchema.dsl(), "game_session_canonical_binding_region_bridge_obligation")) + .containsExactlyElementsOf(regionObligationBefore); assertThatThrownBy(() -> prepareActualBinding(inventory, BLOCKED_CHARACTER_ID)) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) @@ -778,6 +828,10 @@ private static CanonicalGameplayBindingTransitionSnapshot prepareActualBinding( private static CanonicalGameplayBindingTransitionSnapshot prepareActualBinding( CanonicalGameplayBindingInventoryRepository inventory, UUID characterId) { + return inventory.prepare(actualBindingRequest(characterId)); + } + + private static CanonicalGameplayBindingTransitionRequest actualBindingRequest(UUID characterId) { UUID transitionId = UUID.randomUUID(); UUID reservationId = UUID.randomUUID(); UUID reservationFence = UUID.randomUUID(); @@ -807,9 +861,8 @@ private static CanonicalGameplayBindingTransitionSnapshot prepareActualBinding( BigInteger.ONE, BigInteger.TWO, BigInteger.ONE); - return inventory.prepare( - new CanonicalGameplayBindingTransitionRequest( - transitionId, UUID.randomUUID(), candidate, reservation, null, null)); + return new CanonicalGameplayBindingTransitionRequest( + transitionId, UUID.randomUUID(), candidate, reservation, null, null); } private static void insertReservationOnly( From 43d6d50d214755c7b06c267285189ebf76f570c6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:46:36 +1300 Subject: [PATCH 08/34] Prepare complete initial issuer bootstrap owner for consolidated validation --- .../player-access-and-session.md | 6 +- ...calGameplayBindingInventoryRepository.java | 12 +- ...lGameplayIssuerBootstrapCoverageOwner.java | 239 ++++ ...playIssuerBootstrapCoverageRepository.java | 1130 +++++++++++++++++ ...IssuerBootstrapPartitionPhysicalCodec.java | 87 +- ...layIssuerBootstrapPartitionRedisOwner.java | 104 +- ...anonicalGameplayIssuerInstalledAnchor.java | 322 +++++ ...3__canonical_issuer_bootstrap_coverage.sql | 259 ++++ ...BootstrapCoverageOwnerIntegrationTest.java | 911 +++++++++++++ ...rapPartitionRedisOwnerIntegrationTest.java | 113 +- ...outBootstrapRepositoryIntegrationTest.java | 61 +- 11 files changed, 3131 insertions(+), 113 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwner.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerInstalledAnchor.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V1033__canonical_issuer_bootstrap_coverage.sql create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index d91036bde3..f0976c775f 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,7 +12,7 @@ The Account gameplay-admission lease and the unregistered Game Session receiver The Game Session canonical inventory now retains Account's exact issuer string through the forward V1024→V1025 conversion. R488 passes 19 selected PostgreSQL cases, including populated-row migration preservation, restart, canonical writes, and refusal by the typed reader to reinterpret retained UUID issuers. This proves storage identity conversion only; issuer ownership and admission remain unqualified. -The receiving source includes a pending issuer-bootstrap SQL owner that freezes the complete issuer cohort under the inventory clock, requires actual persisted `VERIFIED` legacy-owner evidence, and blocks later preparation. Descriptor and Account issuer-checkpoint inputs remain controlled. Donor-source R539 recorded 65 focused cases (9 unit and 56 PostgreSQL/Redis, including existing account-member regressions); donor-source R545 recorded 12 cases for the physical schema-v2 shape work. Those remain donor-only attributions. Receiving-parent R548 passes 106 fresh cases (12 unit and 94 PostgreSQL/Redis) on parent `be0e20b`, including the 38-case roster regression, full pending-intent repository/migration coverage and existing account-member owners. jOOQ generation, enabled affected Checkstyle/SpotBugs/formatting and documentation checks pass; all exact test containers are absent. This focused receiving proof does not establish a complete service-suite pass or public runtime admission. Donor proof includes the missing-control refusal, both PostgreSQL-observed prepare/intent lock orders, and populated V1029→V1030 retention/restart. The V1028 retained-row fixture uses controlled historical SQL rows, not an actual pre-migration prepare. The receiving tree has shape-only v2 member model, codec and key-helper sources, but no physical Redis mutation/readback, capacity accounting or separate issuer acknowledgement. The canonical physical schema v2 preserves the original reservation coverage tuple separately from the anchor tuple; R551 passes 21 fresh focused cases (12 unit and nine PostgreSQL), including an actual populated reservation with distinct original coverage and new bootstrap anchor, preserved source rows and cohort, independent physical identities and closed malformed-field refusal. Enabled affected Checkstyle/SpotBugs/formatting and documentation checks pass; all exact test containers are absent. This is representation proof with controlled member-operation and incarnation inputs, not an installed anchor or qualified physical write. Retained v1 artifacts remain unqualified with no fallback. No installed pointer, complete partition/capacity proof, issuer acknowledgement, barrier `OPEN`, final CAS or admission is established. Operational source/incarnation custody, legacy recovery, PKI and activation holds remain; see the [issuer anchor owner](../../architecture/system-architecture-redis.md#installed-issuer-anchor-for-ordinary-new). +The receiving source includes a pending issuer-bootstrap SQL owner that freezes the complete issuer cohort under the inventory clock, requires actual persisted `VERIFIED` legacy-owner evidence, and blocks new preparation. Exact replay of a pre-intent frozen transition retains all original request, reservation and current Account checks and performs no new allocation. Descriptor and Account issuer-checkpoint inputs remain controlled. Donor-source R539 recorded 65 focused cases (9 unit and 56 PostgreSQL/Redis, including existing account-member regressions); donor-source R545 recorded 12 cases for the physical schema-v2 shape work. Those remain donor-only attributions. Receiving-parent R548 passes 106 fresh cases (12 unit and 94 PostgreSQL/Redis) on parent `be0e20b`, including the 38-case roster regression, full pending-intent repository/migration coverage and existing account-member owners. jOOQ generation, enabled affected Checkstyle/SpotBugs/formatting and documentation checks pass; all exact test containers are absent. This focused receiving proof does not establish a complete service-suite pass or public runtime admission. Donor proof includes the missing-control refusal, both PostgreSQL-observed prepare/intent lock orders, and populated V1029→V1030 retention/restart. The V1028 retained-row fixture uses controlled historical SQL rows, not an actual pre-migration prepare. That receiving checkpoint had shape-only v2 member model, codec and key-helper sources, without physical Redis mutation/readback, capacity accounting or a separate issuer acknowledgement. The canonical physical schema v2 preserves the original reservation coverage tuple separately from the anchor tuple; R551 passes 21 fresh focused cases (12 unit and nine PostgreSQL), including an actual populated reservation with distinct original coverage and new bootstrap anchor, preserved source rows and cohort, independent physical identities and closed malformed-field refusal. Enabled affected Checkstyle/SpotBugs/formatting and documentation checks pass; all exact test containers are absent. This is representation proof with controlled member-operation and incarnation inputs, not an installed anchor or qualified physical write. Retained v1 artifacts remain unqualified with no fallback. No installed pointer, complete partition/capacity proof, issuer acknowledgement, barrier `OPEN`, final CAS or admission is established. Operational source/incarnation custody, legacy recovery, PKI and activation holds remain; see the [issuer anchor owner](../../architecture/system-architecture-redis.md#installed-issuer-anchor-for-ordinary-new). The unregistered no-active first-NEW member-repair owner composes the original durable operation, the physical one-key global account-member write/readback outside SQL, and separate SQL acceptance. V1026 preserves the operation and completion. R506 freshly passes all 29 selected PostgreSQL/Redis cases, including composed completion, frozen retry/restart, retained prior PRESENT observations, positive control-row requirements, exact member preservation, and malformed-completion refusal. Seven focused unit cases retain R505 attribution; ten shared Redis contract cases retain R500 attribution. This is binding-local `ADD_OR_RETAIN` evidence only: it does not enumerate the account, establish global completeness, or admit the candidate. @@ -20,7 +20,9 @@ The account-fence preparation source consists of the durable intent/cohort owner A Redis restart or reset can change the stable incarnation while AOF retains the original CLOSED barrier. The same operation and epoch then remain a non-mutating conflict even with a fresh protected observation; the pending intent and historical receipts are retained, and admission remains closed. The local installer does not implement the canonical Game Session account-wide fenced replacement or original-intent settlement, so restart recovery liveness is unqualified. No in-place same-epoch rewrite, key deletion, inferred recovery, or automatic opening is supplied. -The local issuer build-plan checkpoint at `a9b6f886cdcf88f188d79d0e38d50d1f3a253e01` retains the complete V1030 cohort and original reservation provenance in immutable V1031 plan/work/blocker rows. R569 freshly passes seven PostgreSQL cases, including concurrent original retry, restart, source/control/layout refusal, old reservation versus new anchor tuples, row and TRUNCATE guards, and per-partition/aggregate nonterminal reservation bounds with RELEASED exclusion. Enabled main and integration static analysis and formatting pass through R567/R569; the exact R569 container is independently confirmed absent. Earlier failed attempts remain retained. This qualifies preparation-time counting and retained storage only. Actual issuer-local operation issuance, physical single-key capacity/member write/readback, complete finite acknowledgement, installed anchor and ordinary NEW consumption remain unqualified until their separately constructed owners and composition pass proof; no unpublished work counts as reviewable green runway. +The current local issuer source extends the retained V1030 cohort through immutable V1031 plan/work/blocker rows and V1032 SQL-issued member operations. The original reservation coverage tuple remains distinct from the new bootstrap anchor; equal numeric counters across those separate domains are permissible and do not equate their full identities. R569 passes seven PostgreSQL plan cases, including source/control/layout refusal, original retry, retained-row and TRUNCATE guards, and per-partition/aggregate nonterminal reservation bounds with RELEASED exclusion. R575 passes four operation-producer and seven plan-regression cases. The owner allocates the local member-operation fence and generation before projection; those values confer no global coverage generation or completion. + +R578 freshly passes the composed four SQL-producer, seven plan-regression and seven physical Redis-owner cases on local checkpoint `a5c2b1c69151029a5be203c720c2618f0866f71a` plus its qualified formatter and test corrections. The actual owner builds or exactly replays one canonical partition HASH, independently reads the complete field set through a separate connection, and brackets the remote phase with controlled current Account checkpoint and stable-incarnation reads. Proof includes populated and positively prepared empty partitions, full original/new tuple conflict, retained terminal reservations, capacity refusal, wrong type/TTL/foreign/v1 evidence, original lost-reply retry and source/incarnation movement. Enabled affected Checkstyle, SpotBugs and formatting pass; all five exact R578 containers are independently confirmed absent. R577 remains a failed aggregate: a fixture incorrectly required independent numeric fences to differ and its status-query helper failed null-safety static analysis; the correction preserves full tuple comparison and exact stored bytes. These results prove local partition projection/readback under controlled collaborators, not operational source or incarnation custody. R579 separately passes all nine PostgreSQL bootstrap-owner cases with enabled affected static analysis and formatting, including the accepted exact pre-intent replay correction, conflicting retry refusal and unchanged durable row/counter images; its exact PostgreSQL container is independently confirmed absent. Complete finite coverage acceptance, installed anchor, ordinary NEW consumption, cleanup and admission remain unfinished; the combined owner scope stays in #3310 and unpublished work is not green runway. ### Player-created roster consumer preparation diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index f0eaebd77a..88f98af39a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -1497,7 +1497,8 @@ private static void requireSameProvisionalOperation( private static CanonicalGameplayBindingTransitionSnapshot prepareInTransaction( DSLContext transaction, CanonicalGameplayBindingTransitionRequest request) { BigInteger revision = lockInventoryRevision(transaction); - requireNoPendingIssuerLayoutBootstrapIntent(transaction, request.candidate().issuerId()); + boolean pendingIssuerLayoutBootstrapIntent = + validatePendingIssuerLayoutBootstrapIntent(transaction, request.candidate().issuerId()); CanonicalGameplayAccountCoverageEvidence accountCoverageEvidence = lockAccountCoverageEvidence(transaction, request.candidate().accountId()); boolean initialBinding = request.expectedPriorBindingRef() == null; @@ -1513,6 +1514,9 @@ private static CanonicalGameplayBindingTransitionSnapshot prepareInTransaction( } return retry; } + if (pendingIssuerLayoutBootstrapIntent) { + throw conflict("Initial issuer-layout bootstrap intent blocks new binding preparation"); + } CanonicalGameplayBindingIdentity candidate = request.candidate(); byte[] candidateRef = candidate.bindingRef().bytes(); @@ -1611,7 +1615,7 @@ private static CanonicalGameplayBindingTransitionSnapshot prepareInTransaction( return prepared; } - private static void requireNoPendingIssuerLayoutBootstrapIntent( + private static boolean validatePendingIssuerLayoutBootstrapIntent( DSLContext transaction, String issuerId) { Record control = transaction.fetchOne( @@ -1627,7 +1631,7 @@ private static void requireNoPendingIssuerLayoutBootstrapIntent( if (orphanIntent != null) { throw conflict("Issuer bootstrap intent exists without its positive current control row"); } - return; + return false; } UUID operationId = control.get("current_operation_id", UUID.class); @@ -1666,7 +1670,7 @@ private static void requireNoPendingIssuerLayoutBootstrapIntent( || readBigInteger(intent, "inventory_snapshot_revision").signum() <= 0) { throw conflict("Issuer bootstrap control does not point to its exact durable intent tuple"); } - throw conflict("Initial issuer-layout bootstrap intent blocks new binding preparation"); + return true; } private static void validateRequest(CanonicalGameplayBindingTransitionRequest request) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwner.java new file mode 100644 index 0000000000..c6aa5d1e03 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwner.java @@ -0,0 +1,239 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import org.jooq.DSLContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Manually composed local owner for finite initial issuer bootstrap completion. It is not + * registered in operational composition and issues no tenant barrier or admission authority. + */ +public final class CanonicalGameplayIssuerBootstrapCoverageOwner { + private final DSLContext dsl; + private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner partitionRedisOwner; + private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentStateSource; + + public CanonicalGameplayIssuerBootstrapCoverageOwner( + DSLContext dsl, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner partitionRedisOwner, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentStateSource) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.partitionRedisOwner = + Objects.requireNonNull(partitionRedisOwner, "partitionRedisOwner"); + this.currentStateSource = Objects.requireNonNull(currentStateSource, "currentStateSource"); + } + + /** + * Completes or replays one exact pending initial bootstrap operation. Its finite partition range, + * complete source cohort, and partition work are all read from the persisted SQL owners. + */ + public CanonicalGameplayIssuerInstalledAnchor completeInitialBootstrap( + UUID bootstrapOperationId, UUID bootstrapRequestId) { + requireNonNil(bootstrapOperationId, "bootstrapOperationId"); + requireNonNil(bootstrapRequestId, "bootstrapRequestId"); + requireNoAmbientTransaction(); + + CanonicalGameplayIssuerPartitionBuildPlan plan = + new CanonicalGameplayIssuerPartitionBuildRepository(dsl) + .prepareInitialBuildPlan(bootstrapOperationId, bootstrapRequestId); + if (plan.state() != CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED) { + throw unavailable("Complete issuer bootstrap plan contains unresolved blockers"); + } + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState initialState = + readAndRequireCurrentState(plan); + CanonicalGameplayIssuerBootstrapCoverageRepository coverageRepository = + new CanonicalGameplayIssuerBootstrapCoverageRepository(dsl); + Optional installed = + coverageRepository.readInstalledAnchor( + bootstrapOperationId, bootstrapRequestId, initialState); + if (installed.isPresent()) { + return readInstalledAnchorPartitions( + plan, installed.get(), coverageRepository, initialState); + } + + CanonicalGameplayIssuerBootstrapMemberOperationRepository memberOperationRepository = + new CanonicalGameplayIssuerBootstrapMemberOperationRepository(dsl); + BigInteger partitionCount = plan.bootstrapIntent().layoutDescriptor().partitionCount(); + for (BigInteger partitionId = BigInteger.ZERO; + partitionId.compareTo(partitionCount) < 0; + partitionId = partitionId.add(BigInteger.ONE)) { + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState before = + readAndRequireSameCurrentState(plan, initialState); + CanonicalGameplayIssuerBootstrapPartitionWork work = + memberOperationRepository.preparePartitionWork( + bootstrapOperationId, + bootstrapRequestId, + partitionId, + trustedCheckpoint(before.accountCheckpoint()), + trustedIncarnation(before.incarnation())); + requireSamePlan(plan, work.buildPlan()); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.Readback readback = + partitionRedisOwner.buildAndRead(work); + readAndRequireSameCurrentState(plan, initialState); + coverageRepository.recordPartitionProof(readback); + } + + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState beforeInstall = + readAndRequireSameCurrentState(plan, initialState); + CanonicalGameplayIssuerInstalledAnchor anchor = + coverageRepository.installInitialAnchor( + bootstrapOperationId, bootstrapRequestId, beforeInstall); + return anchor; + } + + private CanonicalGameplayIssuerInstalledAnchor readInstalledAnchorPartitions( + CanonicalGameplayIssuerPartitionBuildPlan plan, + CanonicalGameplayIssuerInstalledAnchor installed, + CanonicalGameplayIssuerBootstrapCoverageRepository coverageRepository, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState initialState) { + CanonicalGameplayIssuerBootstrapMemberOperationRepository memberOperationRepository = + new CanonicalGameplayIssuerBootstrapMemberOperationRepository(dsl); + BigInteger partitionCount = plan.bootstrapIntent().layoutDescriptor().partitionCount(); + for (BigInteger partitionId = BigInteger.ZERO; + partitionId.compareTo(partitionCount) < 0; + partitionId = partitionId.add(BigInteger.ONE)) { + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current = + readAndRequireSameCurrentState(plan, initialState); + CanonicalGameplayIssuerBootstrapPartitionWork work = + memberOperationRepository.preparePartitionWork( + plan.bootstrapIntent().operationId(), + plan.bootstrapIntent().requestId(), + partitionId, + trustedCheckpoint(current.accountCheckpoint()), + trustedIncarnation(current.incarnation())); + requireSamePlan(plan, work.buildPlan()); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.Readback readback = + partitionRedisOwner.readExistingAndRead(work); + readAndRequireSameCurrentState(plan, initialState); + coverageRepository.verifyExistingPartitionProof(readback); + } + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState afterReadback = + readAndRequireSameCurrentState(plan, initialState); + CanonicalGameplayIssuerInstalledAnchor confirmed = + coverageRepository + .readInstalledAnchor( + installed.bootstrapOperationId(), installed.bootstrapRequestId(), afterReadback) + .orElseThrow(() -> unavailable("Installed issuer anchor disappeared during exact readback")); + if (!Arrays.equals(installed.exactAnchorBytes(), confirmed.exactAnchorBytes()) + || !installed.exactAnchorDigest().equals(confirmed.exactAnchorDigest())) { + throw unavailable("Installed issuer anchor changed during physical partition readback"); + } + return confirmed; + } + + private CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState + readAndRequireCurrentState(CanonicalGameplayIssuerPartitionBuildPlan plan) { + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current = + readFreshCurrentState(); + requireCurrentSource(plan, current); + return current; + } + + private CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState + readAndRequireSameCurrentState( + CanonicalGameplayIssuerPartitionBuildPlan plan, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState expected) { + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current = + readAndRequireCurrentState(plan); + if (!Arrays.equals( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(current.incarnation()), + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(expected.incarnation())) + || !sameCheckpoint(current.accountCheckpoint(), expected.accountCheckpoint())) { + throw unavailable("Current Account source or stable Redis incarnation changed during bootstrap"); + } + return current; + } + + private CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState + readFreshCurrentState() { + requireNoAmbientTransaction(); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current; + try { + current = currentStateSource.readFreshCurrentState(); + } catch (RuntimeException unavailable) { + throw unavailable("Fresh issuer source or stable incarnation is unavailable", unavailable); + } + requireNoAmbientTransaction(); + if (current == null) throw unavailable("Fresh issuer source or stable incarnation is missing"); + return current; + } + + private static void requireCurrentSource( + CanonicalGameplayIssuerPartitionBuildPlan plan, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current) { + var expected = plan.bootstrapIntent().sourceCheckpoint(); + if (!sameCheckpoint(current.accountCheckpoint(), expected)) { + throw unavailable("Current Account checkpoint differs from the frozen bootstrap source"); + } + } + + private static boolean sameCheckpoint( + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint left, + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint right) { + return left != null + && right != null + && left.issuerId().equals(right.issuerId()) + && left.issuerAuthGeneration().equals(right.issuerAuthGeneration()) + && Arrays.equals(left.exactCheckpointBytes(), right.exactCheckpointBytes()) + && left.checkpointDigest().equals(right.checkpointDigest()) + && Arrays.equals(left.latestIssuerEventBytes(), right.latestIssuerEventBytes()) + && Objects.equals(left.latestIssuerEventDigest(), right.latestIssuerEventDigest()); + } + + private static void requireSamePlan( + CanonicalGameplayIssuerPartitionBuildPlan expected, + CanonicalGameplayIssuerPartitionBuildPlan actual) { + if (!expected.buildOperationId().equals(actual.buildOperationId()) + || !expected.planDigest().equals(actual.planDigest()) + || !expected.bootstrapIntent().operationId().equals(actual.bootstrapIntent().operationId()) + || !expected.bootstrapIntent().requestId().equals(actual.bootstrapIntent().requestId())) { + throw unavailable("Member-operation owner returned work for a different persisted plan"); + } + } + + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + trustedCheckpoint( + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint source) { + return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint( + source.issuerId(), + source.issuerAuthGeneration(), + source.exactCheckpointBytes(), + source.latestIssuerEventBytes()); + } + + private static CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation + trustedIncarnation(CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation) { + var deployment = incarnation.targetDeploymentEvidence(); + return new CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation( + incarnation.attestorBinding(), + incarnation.acceptedAttestationDigest(), + deployment, + incarnation.coordOpsRoAclDigest(), + incarnation.coordRedisConfigObservedDigest()); + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) throw new IllegalArgumentException(name + " must not be nil"); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw unavailable("Initial issuer bootstrap completion cannot join an ambient SQL transaction"); + } + } + + private static IllegalStateException unavailable(String message) { + return new IllegalStateException(message); + } + + private static IllegalStateException unavailable(String message, Throwable cause) { + return new IllegalStateException(message, cause); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java new file mode 100644 index 0000000000..dee6a30666 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java @@ -0,0 +1,1130 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** SQL owner for exact per-partition proof retention and one local initial anchor installation. */ +final class CanonicalGameplayIssuerBootstrapCoverageRepository { + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String OPERATION = "game_session_canonical_issuer_bootstrap_member_operation"; + private static final String PROOF = "game_session_canonical_issuer_bootstrap_partition_proof"; + private static final String COUNTER = "game_session_canonical_issuer_bootstrap_coverage_counter"; + private static final String ANCHOR = "game_session_canonical_issuer_installed_anchor"; + private static final String CONTROL = "game_session_canonical_issuer_layout_bootstrap_control"; + private static final String FIELDSET_MAGIC = "issuer-physical-field-set/v1"; + private static final String METADATA_FIELD = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.METADATA_FIELD; + private static final String CAPACITY_PREFIX = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.RESERVATION_FIELD_PREFIX; + + private final DSLContext dsl; + + CanonicalGameplayIssuerBootstrapCoverageRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + void recordPartitionProof(CanonicalGameplayIssuerBootstrapPartitionRedisOwner.Readback readback) { + Objects.requireNonNull(readback, "readback"); + CanonicalGameplayIssuerBootstrapPartitionWork work = readback.work(); + requireNoAmbientTransaction(); + ProofInput input = proofInput(readback); + dsl.transaction( + configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + CanonicalGameplayIssuerPartitionBuildPlan currentPlan = + new CanonicalGameplayIssuerPartitionBuildRepository(transaction) + .readPreparedPlanInTransaction( + transaction, + work.buildPlan().bootstrapIntent().operationId(), + work.buildPlan().bootstrapIntent().requestId()); + requireSamePlan(currentPlan, work.buildPlan()); + requireProofContext(input, currentPlan); + Record existing = + transaction.fetchOne( + "SELECT * FROM " + PROOF + " WHERE bootstrap_operation_id = ? AND partition_id = ? FOR UPDATE", + currentPlan.bootstrapIntent().operationId(), + input.partitionId()); + if (existing != null) { + requireSameProof(existing, input); + return; + } + int inserted = + transaction.execute( + "INSERT INTO " + PROOF + " (" + + "build_operation_id, bootstrap_operation_id, bootstrap_request_id, issuer_id, " + + "build_plan_digest, bootstrap_operation_fence, bootstrap_coverage_fence, " + + "issuer_inventory_snapshot_revision, layout_version, partition_count, " + + "partition_capacity, mapping_identity, layout_descriptor_bytes, " + + "layout_descriptor_digest, source_checkpoint_bytes, source_checkpoint_digest, " + + "source_event_bytes, source_event_digest, incarnation_bytes, incarnation_digest, " + + "partition_id, exact_metadata_bytes, exact_physical_field_set_bytes, " + + "exact_physical_field_set_digest, physical_field_count, physical_reservation_count, " + + "physical_binding_count, physical_counted_capacity_count, " + + "planned_aggregate_capacity_count, proof_state) VALUES (" + + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'EXACT_PHYSICAL_READBACK')", + input.buildOperationId(), + input.bootstrapOperationId(), + input.bootstrapRequestId(), + ISSUER, + input.planDigest(), + input.operationFence(), + input.coverageFence(), + input.snapshotRevision(), + input.layoutVersion(), + input.partitionCount(), + input.partitionCapacity(), + input.mappingIdentity(), + input.layoutDescriptorBytes(), + input.layoutDescriptorDigest(), + input.sourceCheckpointBytes(), + input.sourceCheckpointDigest(), + input.sourceEventBytes(), + input.sourceEventDigest(), + input.incarnationBytes(), + input.incarnationDigest(), + input.partitionId(), + input.metadataBytes(), + input.fieldSetBytes(), + input.fieldSetDigest(), + input.fieldCount(), + input.reservationCount(), + input.bindingCount(), + input.countedCapacityCount(), + input.aggregateCountedCapacity()); + if (inserted != 1) throw conflict("Exact partition proof did not persist"); + Record saved = + transaction.fetchOne( + "SELECT * FROM " + PROOF + " WHERE bootstrap_operation_id = ? AND partition_id = ?", + input.bootstrapOperationId(), + input.partitionId()); + if (saved == null) throw conflict("Exact partition proof is unreadable after persistence"); + requireSameProof(saved, input); + }); + } + + Optional readInstalledAnchor( + UUID bootstrapOperationId, + UUID bootstrapRequestId, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState) { + Objects.requireNonNull(bootstrapOperationId, "bootstrapOperationId"); + Objects.requireNonNull(bootstrapRequestId, "bootstrapRequestId"); + Objects.requireNonNull(currentState, "currentState"); + requireNoAmbientTransaction(); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + CanonicalGameplayIssuerPartitionBuildPlan plan = + new CanonicalGameplayIssuerPartitionBuildRepository(transaction) + .readPreparedPlanInTransaction( + transaction, bootstrapOperationId, bootstrapRequestId); + requireCurrentState(currentState, plan.bootstrapIntent()); + Record row = + transaction.fetchOne( + "SELECT * FROM " + ANCHOR + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (row == null) return Optional.empty(); + CanonicalGameplayIssuerInstalledAnchor installed = loadAnchor(row); + requireAnchorMatchesPlan(installed, plan, currentState); + requireProofSummaryMatchesAnchor( + verifyCompleteProof(transaction, plan, installed.incarnationBytes()), installed); + requireCounterCoversAnchor(transaction, installed); + return Optional.of(installed); + }); + } + + void verifyExistingPartitionProof( + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.Readback readback) { + Objects.requireNonNull(readback, "readback"); + CanonicalGameplayIssuerBootstrapPartitionWork work = readback.work(); + ProofInput input = proofInput(readback); + requireNoAmbientTransaction(); + dsl.transaction( + configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + CanonicalGameplayIssuerPartitionBuildPlan currentPlan = + new CanonicalGameplayIssuerPartitionBuildRepository(transaction) + .readPreparedPlanInTransaction( + transaction, + work.buildPlan().bootstrapIntent().operationId(), + work.buildPlan().bootstrapIntent().requestId()); + requireSamePlan(currentPlan, work.buildPlan()); + requireProofContext(input, currentPlan); + Record row = + transaction.fetchOne( + "SELECT * FROM " + PROOF + " WHERE bootstrap_operation_id = ? AND partition_id = ?", + input.bootstrapOperationId(), + input.partitionId()); + if (row == null) throw conflict("Installed anchor is missing an exact partition proof"); + requireSameProof(row, input); + }); + } + + CanonicalGameplayIssuerInstalledAnchor installInitialAnchor( + UUID bootstrapOperationId, + UUID bootstrapRequestId, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState) { + Objects.requireNonNull(bootstrapOperationId, "bootstrapOperationId"); + Objects.requireNonNull(bootstrapRequestId, "bootstrapRequestId"); + Objects.requireNonNull(currentState, "currentState"); + requireNoAmbientTransaction(); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + CanonicalGameplayIssuerPartitionBuildRepository buildRepository = + new CanonicalGameplayIssuerPartitionBuildRepository(transaction); + CanonicalGameplayIssuerPartitionBuildPlan plan = + buildRepository.readPreparedPlanInTransaction( + transaction, bootstrapOperationId, bootstrapRequestId); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); + requireCurrentState(currentState, intent); + Record existing = + transaction.fetchOne( + "SELECT * FROM " + ANCHOR + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (existing != null) { + CanonicalGameplayIssuerInstalledAnchor installed = loadAnchor(existing); + requireAnchorMatchesPlan(installed, plan, currentState); + requireProofSummaryMatchesAnchor( + verifyCompleteProof(transaction, plan, installed.incarnationBytes()), installed); + requireCounterCoversAnchor(transaction, installed); + return installed; + } + + ProofSummary proof = + verifyCompleteProof( + transaction, + plan, + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation( + currentState.incarnation())); + BigInteger generation = allocateGlobalCoverageGeneration(transaction); + CanonicalGameplayIssuerInstalledAnchor anchor = + createAnchor(plan, currentState, generation, proof); + int inserted = + transaction.execute( + "INSERT INTO " + ANCHOR + " (" + + "issuer_id, bootstrap_operation_id, bootstrap_request_id, build_operation_id, " + + "build_plan_digest, control_epoch, issuer_coverage_operation_id, operation_fence, " + + "coverage_fence, issuer_inventory_snapshot_revision, layout_version, partition_count, " + + "partition_capacity, mapping_identity, layout_descriptor_bytes, layout_descriptor_digest, " + + "issuer_auth_generation, source_checkpoint_bytes, source_checkpoint_digest, " + + "source_event_bytes, source_event_digest, incarnation_bytes, incarnation_digest, " + + "global_coverage_generation, partition_proof_count, physical_reservation_count, " + + "physical_binding_count, aggregate_counted_capacity, partition_proof_root_digest, " + + "exact_anchor_bytes, exact_anchor_digest, anchor_state) " + + "SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'INITIAL_INSTALLED' " + + "FROM " + CONTROL + " c WHERE c.issuer_id = ? AND c.state = 'INITIAL_BOOTSTRAP_INTENT' " + + "AND c.control_epoch = ? AND c.current_operation_id = ? " + + "AND c.current_operation_fence = ? AND c.current_coverage_fence = ? " + + "AND NOT EXISTS (SELECT 1 FROM " + ANCHOR + " a WHERE a.issuer_id = c.issuer_id)", + anchor.issuerId(), + anchor.bootstrapOperationId(), + anchor.bootstrapRequestId(), + plan.buildOperationId(), + plan.planDigest(), + anchor.controlEpoch(), + anchor.issuerCoverageOperationId(), + anchor.operationFence(), + anchor.coverageFence(), + anchor.issuerInventorySnapshotRevision(), + anchor.layoutVersion(), + anchor.partitionCount(), + anchor.partitionCapacity(), + anchor.mappingIdentity(), + anchor.layoutDescriptorBytes(), + anchor.layoutDescriptorDigest(), + anchor.issuerAuthGeneration(), + anchor.sourceCheckpointBytes(), + anchor.sourceCheckpointDigest(), + anchor.sourceEventBytes(), + anchor.sourceEventDigest(), + anchor.incarnationBytes(), + anchor.incarnationDigest(), + anchor.globalCoverageGeneration(), + anchor.partitionProofCount(), + anchor.physicalReservationCount(), + anchor.physicalBindingCount(), + anchor.aggregateCountedCapacity(), + anchor.partitionProofRootDigest(), + anchor.exactAnchorBytes(), + anchor.exactAnchorDigest(), + ISSUER, + intent.controlEpoch(), + intent.operationId(), + intent.operationFence(), + intent.coverageFence()); + if (inserted != 1) throw conflict("Exact initial issuer anchor compare-and-set refused"); + Record saved = + transaction.fetchOne( + "SELECT * FROM " + ANCHOR + " WHERE issuer_id = ?", ISSUER); + if (saved == null) throw conflict("Installed issuer anchor is unreadable after its CAS"); + CanonicalGameplayIssuerInstalledAnchor result = loadAnchor(saved); + requireSameAnchor(result, anchor); + return result; + }); + } + + private CanonicalGameplayIssuerInstalledAnchor createAnchor( + CanonicalGameplayIssuerPartitionBuildPlan plan, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState, + BigInteger generation, + ProofSummary proof) { + CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); + CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor layout = intent.layoutDescriptor(); + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint source = + intent.sourceCheckpoint(); + byte[] incarnationBytes = + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(currentState.incarnation()); + return new CanonicalGameplayIssuerInstalledAnchor( + intent.operationId(), + intent.requestId(), + plan.buildOperationId(), + plan.planDigest(), + intent.issuerId(), + intent.controlEpoch(), + intent.operationId(), + intent.operationFence(), + intent.coverageFence(), + intent.inventorySnapshotRevision(), + layout.layoutVersion(), + layout.partitionCount(), + layout.partitionCapacity(), + layout.mappingIdentity(), + layout.exactDescriptorBytes(), + layout.descriptorDigest(), + source.issuerAuthGeneration(), + source.exactCheckpointBytes(), + source.checkpointDigest(), + source.latestIssuerEventBytes(), + source.latestIssuerEventDigest(), + incarnationBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(incarnationBytes), + generation, + proof.partitionCount(), + proof.reservationCount(), + proof.bindingCount(), + proof.aggregateCountedCapacity(), + proof.rootDigest(), + null, + null); + } + + private ProofSummary verifyCompleteProof( + DSLContext transaction, + CanonicalGameplayIssuerPartitionBuildPlan plan, + byte[] expectedIncarnationBytes) { + if (plan.state() != CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED) { + throw conflict("Only a complete unblocked issuer plan can install an anchor"); + } + CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); + List proofRows = + transaction.fetch( + "SELECT * FROM " + PROOF + " WHERE bootstrap_operation_id = ? ORDER BY partition_id", + intent.operationId()); + BigInteger partitionCount = intent.layoutDescriptor().partitionCount(); + if (!BigInteger.valueOf(proofRows.size()).equals(partitionCount)) { + throw conflict("Initial issuer anchor requires one positive physical proof per finite partition"); + } + + Map worksByOrdinal = new HashMap<>(); + Map exactOperationValues = new HashMap<>(); + Map expectedReservationsByPartition = new HashMap<>(); + Map expectedCapacityByPartition = new HashMap<>(); + int expectedBindingCount = 0; + int expectedCapacityCount = 0; + for (CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work : plan.memberWorks()) { + worksByOrdinal.put(work.workOrdinal(), work); + expectedReservationsByPartition.merge(work.plannedPartitionId(), 1, Integer::sum); + if (work.countsTowardCapacity()) { + expectedCapacityCount++; + expectedCapacityByPartition.merge(work.plannedPartitionId(), 1, Integer::sum); + } + } + List operations = + transaction.fetch( + "SELECT * FROM " + OPERATION + " WHERE bootstrap_operation_id = ? ORDER BY work_ordinal", + intent.operationId()); + if (operations.size() != plan.memberWorks().size()) { + throw conflict("Finite coverage cannot complete while any SQL member operation is unresolved"); + } + for (Record operation : operations) { + long ordinal = requireNonNegativeLong(operation, "work_ordinal"); + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work = worksByOrdinal.get(ordinal); + if (work == null) throw conflict("SQL member operation is outside the exact persisted plan"); + byte[] bytes = requireBytes(operation, "member_value_bytes"); + String digest = requireText(operation, "member_value_digest"); + if (!digest.equals(CanonicalGameplayIssuerMemberV2Codec.sha256(bytes))) { + throw conflict("SQL member operation value digest is not exact"); + } + CanonicalGameplayIssuerMemberV2Value value; + try { + value = CanonicalGameplayIssuerMemberV2Codec.decode(bytes); + } catch (RuntimeException malformed) { + throw conflict("SQL member operation is not a closed schema-v2 value"); + } + requireOperationMatches(operation, plan, work, value); + if (exactOperationValues.putIfAbsent(work.reservationId(), bytes) != null) { + throw conflict("Finite SQL work contains a duplicate reservation identity"); + } + if (Boolean.TRUE.equals(operation.get("expected_binding_present", Boolean.class))) expectedBindingCount++; + } + + BigInteger expectedPartition = BigInteger.ZERO; + BigInteger reservationCount = BigInteger.ZERO; + BigInteger bindingCount = BigInteger.ZERO; + BigInteger aggregateCountedCapacity = BigInteger.ZERO; + BigInteger expectedAggregateCapacity = BigInteger.valueOf(expectedCapacityCount); + BigInteger aggregateBound = partitionCount.multiply(intent.layoutDescriptor().partitionCapacity()); + MessageDigest root = sha256Digest(); + for (Record row : proofRows) { + BigInteger partitionId = readInteger(row, "partition_id"); + if (!partitionId.equals(expectedPartition)) { + throw conflict("Initial issuer physical proof set is not the exact contiguous finite range"); + } + requireProofMatchesPlan(row, plan, expectedIncarnationBytes, partitionId); + int expectedPartitionReservations = expectedReservationsByPartition.getOrDefault(partitionId, 0); + int expectedPartitionCapacity = expectedCapacityByPartition.getOrDefault(partitionId, 0); + Map fields = decodeFieldSet(requireBytes(row, "exact_physical_field_set_bytes")); + byte[] metadata = fields.get(METADATA_FIELD); + if (metadata == null || !Arrays.equals(metadata, requireBytes(row, "exact_metadata_bytes"))) { + throw conflict("Partition proof does not retain its exact common physical metadata"); + } + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.requireExactMetadata(metadata, metadata); + Set reservationIds = new HashSet<>(); + int physicalBindings = 0; + int physicalCapacity = 0; + int physicalReservations = 0; + Set expectedFieldNames = new HashSet<>(); + expectedFieldNames.add(METADATA_FIELD); + for (Map.Entry field : fields.entrySet()) { + String fieldName = field.getKey(); + if (fieldName.equals(METADATA_FIELD)) continue; + CanonicalGameplayIssuerMemberV2Value value; + try { + value = CanonicalGameplayIssuerMemberV2Codec.decode(field.getValue()); + } catch (RuntimeException malformed) { + throw conflict("Exact physical proof contains a malformed v2 member value"); + } + BigInteger mapped = value.owner().bindingRef().partitionId(partitionCount); + if (!mapped.equals(partitionId)) { + throw conflict("Physical issuer field is stored outside its canonical partition"); + } + byte[] expectedValue = exactOperationValues.get(value.reservation().reservationId()); + if (expectedValue == null || !Arrays.equals(expectedValue, field.getValue())) { + throw conflict("Physical issuer field differs from its exact SQL member operation"); + } + if (fieldName.startsWith(CAPACITY_PREFIX)) { + String reservationText = fieldName.substring(CAPACITY_PREFIX.length()); + UUID reservationId; + try { + reservationId = UUID.fromString(reservationText); + } catch (RuntimeException malformed) { + throw conflict("Physical issuer capacity field has malformed identity"); + } + if (!reservationId.toString().equals(reservationText) + || !reservationId.equals(value.reservation().reservationId()) + || !reservationIds.add(reservationId)) { + throw conflict("Physical issuer capacity field does not match a unique reservation"); + } + physicalReservations++; + if (value.reservation().lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED) { + physicalCapacity++; + } + } else { + CanonicalGameplayBindingRef bindingRef; + try { + bindingRef = CanonicalGameplayBindingRef.fromExactBytes(fieldName.getBytes(StandardCharsets.UTF_8)); + } catch (RuntimeException malformed) { + throw conflict("Physical issuer binding field has invalid canonical identity"); + } + if (!Arrays.equals(bindingRef.bytes(), value.owner().bindingRef().bytes())) { + throw conflict("Physical issuer binding field and v2 owner identity disagree"); + } + expectedFieldNames.add(fieldName); + physicalBindings++; + } + } + expectedFieldNames.addAll( + reservationIds.stream().map(CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec::reservationField).toList()); + if (!expectedFieldNames.equals(fields.keySet()) + || physicalReservations != expectedPartitionReservations + || physicalCapacity != expectedPartitionCapacity + || physicalBindings != countBindingsForPartition(operations, worksByOrdinal, partitionId) + || physicalReservations != readInt(row, "physical_reservation_count") + || physicalBindings != readInt(row, "physical_binding_count") + || physicalCapacity != readInt(row, "physical_counted_capacity_count") + || fields.size() != readInt(row, "physical_field_count") + || !expectedAggregateCapacity.equals(readInteger(row, "planned_aggregate_capacity_count"))) { + throw conflict("Physical partition proof differs from SQL work or capacity expectations"); + } + if (BigInteger.valueOf(physicalCapacity).compareTo(intent.layoutDescriptor().partitionCapacity()) > 0) { + throw conflict("Physical issuer partition exceeds its pinned reservation capacity"); + } + reservationCount = reservationCount.add(BigInteger.valueOf(physicalReservations)); + bindingCount = bindingCount.add(BigInteger.valueOf(physicalBindings)); + aggregateCountedCapacity = aggregateCountedCapacity.add(BigInteger.valueOf(physicalCapacity)); + updateRoot(root, partitionId.toString().getBytes(StandardCharsets.US_ASCII)); + updateRoot(root, CanonicalGameplayIssuerMemberV2Codec.sha256( + requireBytes(row, "exact_physical_field_set_bytes")).getBytes(StandardCharsets.US_ASCII)); + expectedPartition = expectedPartition.add(BigInteger.ONE); + } + if (!expectedPartition.equals(partitionCount) + || !reservationCount.equals(BigInteger.valueOf(plan.memberWorks().size())) + || !bindingCount.equals(BigInteger.valueOf(expectedBindingCount)) + || !aggregateCountedCapacity.equals(expectedAggregateCapacity) + || aggregateCountedCapacity.compareTo(aggregateBound) > 0) { + throw conflict("Initial issuer proof does not cover complete reservation and aggregate capacity"); + } + return new ProofSummary( + proofRows.size(), + reservationCount.longValueExact(), + bindingCount.longValueExact(), + aggregateCountedCapacity, + "sha256:" + java.util.HexFormat.of().formatHex(root.digest())); + } + + private static int countBindingsForPartition( + List operations, + Map worksByOrdinal, + BigInteger partitionId) { + int count = 0; + for (Record operation : operations) { + long ordinal = requireNonNegativeLong(operation, "work_ordinal"); + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work = worksByOrdinal.get(ordinal); + if (work != null + && work.plannedPartitionId().equals(partitionId) + && Boolean.TRUE.equals(operation.get("expected_binding_present", Boolean.class))) count++; + } + return count; + } + + private static void requireOperationMatches( + Record row, + CanonicalGameplayIssuerPartitionBuildPlan plan, + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work, + CanonicalGameplayIssuerMemberV2Value value) { + var intent = plan.bootstrapIntent(); + var reservation = value.reservation(); + var anchor = value.anchor(); + var operation = value.memberOperation(); + if (!requireUuid(row, "member_operation_id").equals(work.memberOperationId()) + || !requireUuid(row, "bootstrap_operation_id").equals(intent.operationId()) + || !requireUuid(row, "bootstrap_request_id").equals(intent.requestId()) + || !requireUuid(row, "build_operation_id").equals(plan.buildOperationId()) + || !plan.planDigest().equals(requireText(row, "build_plan_digest")) + || work.workOrdinal() != requireNonNegativeLong(row, "work_ordinal") + || !requireUuid(row, "preparation_operation_id").equals(work.memberOperationId()) + || !requireUuid(row, "preparation_fence_id").equals(work.memberPreparationFenceId()) + || work.reservationSourceRowOrdinal() + != requireNonNegativeLong(row, "reservation_source_row_ordinal") + || !work.reservationLifecycle().equals(requireText(row, "reservation_lifecycle")) + || !Objects.equals( + work.bindingSourceRowOrdinal(), row.get("binding_source_row_ordinal", Long.class)) + || !Objects.equals( + work.bindingSourceRowDigest(), row.get("binding_source_row_digest", String.class)) + || !"PENDING_PHYSICAL_PROOF".equals(requireText(row, "member_status")) + || readInt(row, "member_schema_version") != 2 + || !operation.operationId().equals(requireUuid(row, "member_operation_id")) + || !operation.operationFence().equals(readInteger(row, "operation_fence")) + || !operation.coverageGeneration().equals(readInteger(row, "local_member_generation")) + || !reservation.reservationId().equals(work.reservationId()) + || !reservation.transitionId().equals(work.transitionId()) + || !reservation.partitionId().equals(work.plannedPartitionId()) + || !reservation.issuerCoverageOperationId().equals(work.originalIssuerCoverageOperationId()) + || !reservation.issuerCoverageOperationFence().equals(work.originalIssuerCoverageOperationFence()) + || !reservation.coverageFence().equals(work.originalCoverageFence()) + || !reservation.inventorySnapshotRevision().equals(work.originalInventorySnapshotRevision()) + || !work.reservationLifecycle().equals(reservation.lifecycle().name()) + || !work.reservationFence().equals(reservation.reservationFence()) + || !anchor.issuerCoverageOperationId().equals(intent.operationId()) + || !anchor.operationFence().equals(intent.operationFence()) + || !anchor.coverageFence().equals(intent.coverageFence()) + || !anchor.issuerInventorySnapshotRevision().equals(intent.inventorySnapshotRevision()) + || !value.issuerControlEpoch().equals(intent.controlEpoch()) + || !Arrays.equals(value.layoutDescriptor().exactDescriptorBytes(), intent.layoutDescriptor().exactDescriptorBytes()) + || !Arrays.equals(work.bindingRef(), value.owner().bindingRef().bytes()) + || !Boolean.valueOf(work.countsTowardCapacity()).equals(row.get("counts_toward_capacity", Boolean.class)) + || !Boolean.valueOf(isBindingPresent(row)).equals(row.get("expected_binding_present", Boolean.class)) + || !work.reservationId().equals(requireUuid(row, "reservation_id")) + || !work.reservationSourceRowDigest().equals(requireText(row, "reservation_source_row_digest")) + || !work.originalIssuerCoverageOperationId().equals(requireUuid(row, "original_issuer_coverage_operation_id")) + || !work.originalIssuerCoverageOperationFence().equals(readInteger(row, "original_issuer_coverage_operation_fence")) + || !work.originalCoverageFence().equals(readInteger(row, "original_coverage_fence")) + || !work.originalInventorySnapshotRevision().equals(readInteger(row, "original_inventory_snapshot_revision")) + || !intent.operationId().equals(requireUuid(row, "bootstrap_anchor_operation_id")) + || !intent.operationFence().equals(readInteger(row, "bootstrap_anchor_operation_fence")) + || !intent.coverageFence().equals(readInteger(row, "bootstrap_anchor_coverage_fence")) + || !intent.inventorySnapshotRevision().equals(readInteger(row, "bootstrap_anchor_inventory_snapshot_revision"))) { + throw conflict("SQL member operation does not match its exact reservation, anchor, and plan tuple"); + } + } + + private static void requireProofMatchesPlan( + Record row, + CanonicalGameplayIssuerPartitionBuildPlan plan, + byte[] expectedIncarnationBytes, + BigInteger partitionId) { + var intent = plan.bootstrapIntent(); + var layout = intent.layoutDescriptor(); + var source = intent.sourceCheckpoint(); + byte[] expectedEvent = source.latestIssuerEventBytes(); + byte[] exactIncarnation = requireBytes(row, "incarnation_bytes"); + if (!requireUuid(row, "build_operation_id").equals(plan.buildOperationId()) + || !requireUuid(row, "bootstrap_operation_id").equals(intent.operationId()) + || !requireUuid(row, "bootstrap_request_id").equals(intent.requestId()) + || !ISSUER.equals(requireText(row, "issuer_id")) + || !plan.planDigest().equals(requireText(row, "build_plan_digest")) + || !intent.operationFence().equals(readInteger(row, "bootstrap_operation_fence")) + || !intent.coverageFence().equals(readInteger(row, "bootstrap_coverage_fence")) + || !intent.inventorySnapshotRevision().equals(readInteger(row, "issuer_inventory_snapshot_revision")) + || !layout.layoutVersion().equals(readInteger(row, "layout_version")) + || !layout.partitionCount().equals(readInteger(row, "partition_count")) + || !layout.partitionCapacity().equals(readInteger(row, "partition_capacity")) + || !layout.mappingIdentity().equals(requireText(row, "mapping_identity")) + || !Arrays.equals(layout.exactDescriptorBytes(), requireBytes(row, "layout_descriptor_bytes")) + || !layout.descriptorDigest().equals(requireText(row, "layout_descriptor_digest")) + || !Arrays.equals(source.exactCheckpointBytes(), requireBytes(row, "source_checkpoint_bytes")) + || !source.checkpointDigest().equals(requireText(row, "source_checkpoint_digest")) + || !Arrays.equals(expectedEvent, optionalBytes(row, "source_event_bytes")) + || !Objects.equals(source.latestIssuerEventDigest(), row.get("source_event_digest", String.class)) + || !Arrays.equals(expectedIncarnationBytes, exactIncarnation) + || !CanonicalGameplayIssuerMemberV2Codec.sha256(exactIncarnation).equals(requireText(row, "incarnation_digest")) + || !partitionId.equals(readInteger(row, "partition_id")) + || !"EXACT_PHYSICAL_READBACK".equals(requireText(row, "proof_state"))) { + throw conflict("Persisted physical proof differs from the exact current plan tuple"); + } + } + + private static void requireCurrentState( + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current, + CanonicalGameplayIssuerLayoutBootstrapIntent intent) { + var source = intent.sourceCheckpoint(); + if (!sameCheckpoint(current.accountCheckpoint(), source)) { + throw conflict("Current Account issuer checkpoint moved from the frozen bootstrap source"); + } + } + + private static boolean sameCheckpoint( + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint left, + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint right) { + return left.issuerId().equals(right.issuerId()) + && left.issuerAuthGeneration().equals(right.issuerAuthGeneration()) + && Arrays.equals(left.exactCheckpointBytes(), right.exactCheckpointBytes()) + && left.checkpointDigest().equals(right.checkpointDigest()) + && Arrays.equals(left.latestIssuerEventBytes(), right.latestIssuerEventBytes()) + && Objects.equals(left.latestIssuerEventDigest(), right.latestIssuerEventDigest()); + } + + private static void requireAnchorMatchesPlan( + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerPartitionBuildPlan plan, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current) { + var intent = plan.bootstrapIntent(); + var layout = intent.layoutDescriptor(); + var source = intent.sourceCheckpoint(); + byte[] currentIncarnation = + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(current.incarnation()); + if (!anchor.bootstrapOperationId().equals(intent.operationId()) + || !anchor.bootstrapRequestId().equals(intent.requestId()) + || !anchor.buildOperationId().equals(plan.buildOperationId()) + || !anchor.buildPlanDigest().equals(plan.planDigest()) + || !anchor.issuerId().equals(intent.issuerId()) + || !anchor.controlEpoch().equals(intent.controlEpoch()) + || !anchor.issuerCoverageOperationId().equals(intent.operationId()) + || !anchor.operationFence().equals(intent.operationFence()) + || !anchor.coverageFence().equals(intent.coverageFence()) + || !anchor.issuerInventorySnapshotRevision().equals(intent.inventorySnapshotRevision()) + || !anchor.layoutVersion().equals(layout.layoutVersion()) + || !anchor.partitionCount().equals(layout.partitionCount()) + || !anchor.partitionCapacity().equals(layout.partitionCapacity()) + || !anchor.mappingIdentity().equals(layout.mappingIdentity()) + || !Arrays.equals(anchor.layoutDescriptorBytes(), layout.exactDescriptorBytes()) + || !anchor.layoutDescriptorDigest().equals(layout.descriptorDigest()) + || !anchor.issuerAuthGeneration().equals(source.issuerAuthGeneration()) + || !Arrays.equals(anchor.sourceCheckpointBytes(), source.exactCheckpointBytes()) + || !anchor.sourceCheckpointDigest().equals(source.checkpointDigest()) + || !Arrays.equals(anchor.sourceEventBytes(), source.latestIssuerEventBytes()) + || !Objects.equals(anchor.sourceEventDigest(), source.latestIssuerEventDigest()) + || !Arrays.equals(anchor.incarnationBytes(), currentIncarnation) + || !sameCheckpoint(current.accountCheckpoint(), source)) { + throw conflict("Installed issuer anchor does not match the exact current source and initial layout"); + } + } + + private static void requireProofSummaryMatchesAnchor( + ProofSummary proof, CanonicalGameplayIssuerInstalledAnchor anchor) { + if (!BigInteger.valueOf(proof.partitionCount()).equals(anchor.partitionCount()) + || proof.reservationCount() != anchor.physicalReservationCount() + || proof.bindingCount() != anchor.physicalBindingCount() + || !proof.aggregateCountedCapacity().equals(anchor.aggregateCountedCapacity()) + || !proof.rootDigest().equals(anchor.partitionProofRootDigest())) { + throw conflict("Installed anchor does not retain the complete exact finite proof summary"); + } + } + + private static void requireCounterCoversAnchor( + DSLContext transaction, CanonicalGameplayIssuerInstalledAnchor anchor) { + Record counter = + transaction.fetchOne( + "SELECT last_issued_coverage_generation FROM " + COUNTER + " WHERE issuer_id = ?", + anchor.issuerId()); + if (counter == null + || readInteger(counter, "last_issued_coverage_generation") + .compareTo(anchor.globalCoverageGeneration()) + < 0) { + throw conflict("Installed anchor generation is beyond the current global issuer counter"); + } + } + + private static boolean isBindingPresent(Record row) { + String lifecycle = row.get("binding_lifecycle", String.class); + return CanonicalGameplayBindingInventoryEntry.Lifecycle.ACTIVE.name().equals(lifecycle) + || CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL.name().equals(lifecycle); + } + + private static void requireSameAnchor( + CanonicalGameplayIssuerInstalledAnchor actual, + CanonicalGameplayIssuerInstalledAnchor expected) { + if (!Arrays.equals(actual.exactAnchorBytes(), expected.exactAnchorBytes()) + || !actual.exactAnchorDigest().equals(expected.exactAnchorDigest())) { + throw conflict("Installed issuer anchor readback differs from its exact owner-issued pointer"); + } + } + + private static CanonicalGameplayIssuerInstalledAnchor loadAnchor(Record row) { + try { + return new CanonicalGameplayIssuerInstalledAnchor( + requireUuid(row, "bootstrap_operation_id"), + requireUuid(row, "bootstrap_request_id"), + requireUuid(row, "build_operation_id"), + requireText(row, "build_plan_digest"), + requireText(row, "issuer_id"), + readInteger(row, "control_epoch"), + requireUuid(row, "issuer_coverage_operation_id"), + readInteger(row, "operation_fence"), + readInteger(row, "coverage_fence"), + readInteger(row, "issuer_inventory_snapshot_revision"), + readInteger(row, "layout_version"), + readInteger(row, "partition_count"), + readInteger(row, "partition_capacity"), + requireText(row, "mapping_identity"), + requireBytes(row, "layout_descriptor_bytes"), + requireText(row, "layout_descriptor_digest"), + readInteger(row, "issuer_auth_generation"), + requireBytes(row, "source_checkpoint_bytes"), + requireText(row, "source_checkpoint_digest"), + optionalBytes(row, "source_event_bytes"), + row.get("source_event_digest", String.class), + requireBytes(row, "incarnation_bytes"), + requireText(row, "incarnation_digest"), + readInteger(row, "global_coverage_generation"), + requireNonNegativeLong(row, "partition_proof_count"), + requireNonNegativeLong(row, "physical_reservation_count"), + requireNonNegativeLong(row, "physical_binding_count"), + readInteger(row, "aggregate_counted_capacity"), + requireText(row, "partition_proof_root_digest"), + requireBytes(row, "exact_anchor_bytes"), + requireText(row, "exact_anchor_digest")); + } catch (RuntimeException malformed) { + throw conflict("Persisted installed issuer anchor is malformed or noncanonical"); + } + } + + private BigInteger allocateGlobalCoverageGeneration(DSLContext transaction) { + transaction.execute( + "INSERT INTO " + COUNTER + " (issuer_id, last_issued_coverage_generation, counter_version) " + + "VALUES (?, 0, 0) ON CONFLICT (issuer_id) DO NOTHING", + ISSUER); + Record counter = + transaction.fetchOne( + "SELECT * FROM " + COUNTER + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (counter == null) throw conflict("Global issuer coverage generation counter is missing"); + BigInteger previous = readInteger(counter, "last_issued_coverage_generation"); + long version = requireNonNegativeLong(counter, "counter_version"); + BigInteger next = previous.add(BigInteger.ONE); + if (next.toString().length() > 256) throw conflict("Global issuer coverage generation is outside its bound"); + int updated = + transaction.execute( + "UPDATE " + COUNTER + + " SET last_issued_coverage_generation = ?, counter_version = ?, updated_at = CURRENT_TIMESTAMP " + + "WHERE issuer_id = ? AND last_issued_coverage_generation = ? AND counter_version = ?", + next, + Math.addExact(version, 1L), + ISSUER, + previous, + version); + if (updated != 1) throw conflict("Global issuer coverage generation compare-and-set refused"); + return next; + } + + private static ProofInput proofInput( + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.Readback readback) { + CanonicalGameplayIssuerBootstrapPartitionWork work = readback.work(); + CanonicalGameplayIssuerPartitionBuildPlan plan = work.buildPlan(); + var intent = plan.bootstrapIntent(); + var layout = intent.layoutDescriptor(); + var source = intent.sourceCheckpoint(); + var physical = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.expectedFields(work); + byte[] fieldSet = encodeFieldSet(physical.fields()); + int expectedFieldCount = physical.fields().size(); + if (readback.physicalFieldCount() != expectedFieldCount + || readback.physicalPartitionReservationCount() != physical.reservationCount() + || readback.physicalBindingCount() != physical.bindingCount() + || readback.physicalCountedCapacityCount() != physical.countedReservationCount() + || !readback.plannedAggregateCapacityCount().equals(physical.plannedAggregateCapacityCount())) { + throw conflict("Physical Redis readback capability differs from its exact prepared field set"); + } + return new ProofInput( + plan.buildOperationId(), + intent.operationId(), + intent.requestId(), + plan.planDigest(), + intent.operationFence(), + intent.coverageFence(), + intent.inventorySnapshotRevision(), + layout.layoutVersion(), + layout.partitionCount(), + layout.partitionCapacity(), + layout.mappingIdentity(), + layout.exactDescriptorBytes(), + layout.descriptorDigest(), + source.exactCheckpointBytes(), + source.checkpointDigest(), + source.latestIssuerEventBytes(), + source.latestIssuerEventDigest(), + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(work.incarnation()), + CanonicalGameplayIssuerMemberV2Codec.sha256( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(work.incarnation())), + work.partitionId(), + physical.metadataBytes(), + fieldSet, + CanonicalGameplayIssuerMemberV2Codec.sha256(fieldSet), + expectedFieldCount, + physical.reservationCount(), + physical.bindingCount(), + physical.countedReservationCount(), + physical.plannedAggregateCapacityCount()); + } + + private static void requireProofContext( + ProofInput proof, CanonicalGameplayIssuerPartitionBuildPlan plan) { + var intent = plan.bootstrapIntent(); + var layout = intent.layoutDescriptor(); + var source = intent.sourceCheckpoint(); + if (!proof.buildOperationId().equals(plan.buildOperationId()) + || !proof.bootstrapOperationId().equals(intent.operationId()) + || !proof.bootstrapRequestId().equals(intent.requestId()) + || !proof.planDigest().equals(plan.planDigest()) + || !proof.operationFence().equals(intent.operationFence()) + || !proof.coverageFence().equals(intent.coverageFence()) + || !proof.snapshotRevision().equals(intent.inventorySnapshotRevision()) + || !proof.layoutVersion().equals(layout.layoutVersion()) + || !proof.partitionCount().equals(layout.partitionCount()) + || !proof.partitionCapacity().equals(layout.partitionCapacity()) + || !proof.mappingIdentity().equals(layout.mappingIdentity()) + || !Arrays.equals(proof.layoutDescriptorBytes(), layout.exactDescriptorBytes()) + || !proof.layoutDescriptorDigest().equals(layout.descriptorDigest()) + || !Arrays.equals(proof.sourceCheckpointBytes(), source.exactCheckpointBytes()) + || !proof.sourceCheckpointDigest().equals(source.checkpointDigest()) + || !Arrays.equals(proof.sourceEventBytes(), source.latestIssuerEventBytes()) + || !Objects.equals(proof.sourceEventDigest(), source.latestIssuerEventDigest()) + || proof.partitionId().compareTo(proof.partitionCount()) >= 0) { + throw conflict("Physical readback proof belongs to a different bootstrap plan or source"); + } + } + + private static void requireSamePlan( + CanonicalGameplayIssuerPartitionBuildPlan current, + CanonicalGameplayIssuerPartitionBuildPlan expected) { + if (!current.buildOperationId().equals(expected.buildOperationId()) + || !current.planDigest().equals(expected.planDigest()) + || !current.bootstrapIntent().operationId().equals(expected.bootstrapIntent().operationId()) + || !current.bootstrapIntent().requestId().equals(expected.bootstrapIntent().requestId()) + || current.memberWorks().size() != expected.memberWorks().size() + || current.cohortRows().size() != expected.cohortRows().size()) { + throw conflict("Current complete bootstrap plan differs from physical work"); + } + } + + private static void requireSameProof(Record row, ProofInput expected) { + if (!requireUuid(row, "build_operation_id").equals(expected.buildOperationId()) + || !requireUuid(row, "bootstrap_operation_id").equals(expected.bootstrapOperationId()) + || !requireUuid(row, "bootstrap_request_id").equals(expected.bootstrapRequestId()) + || !ISSUER.equals(requireText(row, "issuer_id")) + || !expected.planDigest().equals(requireText(row, "build_plan_digest")) + || !expected.operationFence().equals(readInteger(row, "bootstrap_operation_fence")) + || !expected.coverageFence().equals(readInteger(row, "bootstrap_coverage_fence")) + || !expected.snapshotRevision().equals(readInteger(row, "issuer_inventory_snapshot_revision")) + || !expected.layoutVersion().equals(readInteger(row, "layout_version")) + || !expected.partitionCount().equals(readInteger(row, "partition_count")) + || !expected.partitionCapacity().equals(readInteger(row, "partition_capacity")) + || !expected.mappingIdentity().equals(requireText(row, "mapping_identity")) + || !Arrays.equals(expected.layoutDescriptorBytes(), requireBytes(row, "layout_descriptor_bytes")) + || !expected.layoutDescriptorDigest().equals(requireText(row, "layout_descriptor_digest")) + || !Arrays.equals(expected.sourceCheckpointBytes(), requireBytes(row, "source_checkpoint_bytes")) + || !expected.sourceCheckpointDigest().equals(requireText(row, "source_checkpoint_digest")) + || !Arrays.equals(expected.sourceEventBytes(), optionalBytes(row, "source_event_bytes")) + || !Objects.equals(expected.sourceEventDigest(), row.get("source_event_digest", String.class)) + || !Arrays.equals(expected.incarnationBytes(), requireBytes(row, "incarnation_bytes")) + || !expected.incarnationDigest().equals(requireText(row, "incarnation_digest")) + || !expected.partitionId().equals(readInteger(row, "partition_id")) + || !Arrays.equals(expected.metadataBytes(), requireBytes(row, "exact_metadata_bytes")) + || !Arrays.equals(expected.fieldSetBytes(), requireBytes(row, "exact_physical_field_set_bytes")) + || !expected.fieldSetDigest().equals(requireText(row, "exact_physical_field_set_digest")) + || expected.fieldCount() != readInt(row, "physical_field_count") + || expected.reservationCount() != readInt(row, "physical_reservation_count") + || expected.bindingCount() != readInt(row, "physical_binding_count") + || expected.countedCapacityCount() != readInt(row, "physical_counted_capacity_count") + || !expected.aggregateCountedCapacity().equals(readInteger(row, "planned_aggregate_capacity_count")) + || !"EXACT_PHYSICAL_READBACK".equals(requireText(row, "proof_state"))) { + throw conflict("Exact partition proof retry changed its original physical bytes or tuple"); + } + } + + private static byte[] encodeFieldSet(Map fields) { + List> entries = new ArrayList<>(fields.entrySet()); + entries.sort((left, right) -> compareUnsigned( + left.getKey().getBytes(StandardCharsets.UTF_8), + right.getKey().getBytes(StandardCharsets.UTF_8))); + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream output = new DataOutputStream(bytes)) { + writeBytes(output, FIELDSET_MAGIC.getBytes(StandardCharsets.US_ASCII)); + output.writeInt(entries.size()); + for (Map.Entry entry : entries) { + writeBytes(output, entry.getKey().getBytes(StandardCharsets.UTF_8)); + writeBytes(output, entry.getValue()); + } + } + if (bytes.size() > 17 * 1024 * 1024) throw conflict("Physical field proof exceeds its bounded storage limit"); + return bytes.toByteArray(); + } catch (IOException impossible) { + throw new IllegalStateException("Could not encode exact issuer physical readback", impossible); + } + } + + private static Map decodeFieldSet(byte[] encoded) { + if (encoded.length == 0 || encoded.length > 17 * 1024 * 1024) { + throw conflict("Persisted issuer physical field proof is outside its bound"); + } + try (DataInputStream input = new DataInputStream(new ByteArrayInputStream(encoded))) { + if (!Arrays.equals(readBytes(input, 256), FIELDSET_MAGIC.getBytes(StandardCharsets.US_ASCII))) { + throw conflict("Persisted issuer physical field proof has an unsupported encoding"); + } + int count = input.readInt(); + if (count < 1 || count > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_HASH_FIELDS) { + throw conflict("Persisted issuer physical field count is outside its bound"); + } + Map fields = new HashMap<>(); + byte[] previous = null; + for (int index = 0; index < count; index++) { + byte[] rawField = readBytes(input, CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_BINDING_REF_BYTES); + if (rawField.length == 0 || (previous != null && compareUnsigned(previous, rawField) >= 0)) { + throw conflict("Persisted issuer physical fields are duplicated or noncanonical"); + } + String field = decodeUtf8(rawField); + byte[] value = readBytes(input, CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_VALUE_BYTES); + if (value.length == 0 || fields.putIfAbsent(field, value) != null) { + throw conflict("Persisted issuer physical field is empty or duplicated"); + } + previous = rawField; + } + if (input.read() != -1) throw conflict("Persisted issuer physical proof has trailing bytes"); + return fields; + } catch (IOException malformed) { + throw conflict("Persisted issuer physical field proof is malformed"); + } + } + + private static void writeBytes(DataOutputStream output, byte[] bytes) throws IOException { + output.writeInt(bytes.length); + output.write(bytes); + } + + private static byte[] readBytes(DataInputStream input, int maxBytes) throws IOException { + int length = input.readInt(); + if (length < 0 || length > maxBytes) throw conflict("Issuer physical proof field exceeds its bound"); + byte[] value = input.readNBytes(length); + if (value.length != length) throw conflict("Issuer physical proof field is truncated"); + return value; + } + + private static String decodeUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8.newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw conflict("Issuer physical field name is not canonical UTF-8"); + } + } + + private static int compareUnsigned(byte[] left, byte[] right) { + int common = Math.min(left.length, right.length); + for (int index = 0; index < common; index++) { + int difference = Byte.toUnsignedInt(left[index]) - Byte.toUnsignedInt(right[index]); + if (difference != 0) return difference; + } + return Integer.compare(left.length, right.length); + } + + private static void updateRoot(MessageDigest digest, byte[] bytes) { + digest.update((byte) (bytes.length >>> 24)); + digest.update((byte) (bytes.length >>> 16)); + digest.update((byte) (bytes.length >>> 8)); + digest.update((byte) bytes.length); + digest.update(bytes); + } + + private static MessageDigest sha256Digest() { + try { + return MessageDigest.getInstance("SHA-256"); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException("JVM does not provide SHA-256", impossible); + } + } + + private static int readInt(Record row, String field) { + return Math.toIntExact(requireNonNegativeLong(row, field)); + } + + private static long requireNonNegativeLong(Record row, String field) { + Number value = row.get(field, Number.class); + if (value == null) throw conflict(field + " is missing"); + long result = value.longValue(); + if (result < 0 || !BigInteger.valueOf(result).equals(toBigInteger(value))) { + throw conflict(field + " is outside its exact nonnegative integer domain"); + } + return result; + } + + private static BigInteger readInteger(Record row, String field) { + Object value = row.get(field); + if (!(value instanceof Number number)) throw conflict(field + " is missing or nonnumeric"); + BigInteger result = toBigInteger(number); + if (result.signum() < 0) throw conflict(field + " must not be negative"); + return result; + } + + private static BigInteger toBigInteger(Number value) { + try { + if (value instanceof BigInteger integer) return integer; + if (value instanceof BigDecimal decimal) return decimal.toBigIntegerExact(); + return BigInteger.valueOf(value.longValue()); + } catch (ArithmeticException malformed) { + throw conflict("Stored counter is not an exact integer"); + } + } + + private static UUID requireUuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null) throw conflict(field + " is missing"); + return value; + } + + private static String requireText(Record row, String field) { + String value = row.get(field, String.class); + if (value == null) throw conflict(field + " is missing"); + return value; + } + + private static byte[] requireBytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + if (value == null || value.length == 0) throw conflict(field + " is missing or empty"); + return value; + } + + private static byte[] optionalBytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + return value == null ? null : value; + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw conflict("Issuer bootstrap coverage owner cannot join an ambient SQL transaction"); + } + } + + private static IllegalStateException conflict(String message) { + return new IllegalStateException(message); + } + + private record ProofInput( + UUID buildOperationId, + UUID bootstrapOperationId, + UUID bootstrapRequestId, + String planDigest, + BigInteger operationFence, + BigInteger coverageFence, + BigInteger snapshotRevision, + BigInteger layoutVersion, + BigInteger partitionCount, + BigInteger partitionCapacity, + String mappingIdentity, + byte[] layoutDescriptorBytes, + String layoutDescriptorDigest, + byte[] sourceCheckpointBytes, + String sourceCheckpointDigest, + byte[] sourceEventBytes, + String sourceEventDigest, + byte[] incarnationBytes, + String incarnationDigest, + BigInteger partitionId, + byte[] metadataBytes, + byte[] fieldSetBytes, + String fieldSetDigest, + int fieldCount, + int reservationCount, + int bindingCount, + int countedCapacityCount, + BigInteger aggregateCountedCapacity) { + private ProofInput { + layoutDescriptorBytes = layoutDescriptorBytes.clone(); + sourceCheckpointBytes = sourceCheckpointBytes.clone(); + sourceEventBytes = sourceEventBytes == null ? null : sourceEventBytes.clone(); + incarnationBytes = incarnationBytes.clone(); + metadataBytes = metadataBytes.clone(); + fieldSetBytes = fieldSetBytes.clone(); + } + + @Override public byte[] layoutDescriptorBytes() { return layoutDescriptorBytes.clone(); } + @Override public byte[] sourceCheckpointBytes() { return sourceCheckpointBytes.clone(); } + @Override public byte[] sourceEventBytes() { return sourceEventBytes == null ? null : sourceEventBytes.clone(); } + @Override public byte[] incarnationBytes() { return incarnationBytes.clone(); } + @Override public byte[] metadataBytes() { return metadataBytes.clone(); } + @Override public byte[] fieldSetBytes() { return fieldSetBytes.clone(); } + } + + private record ProofSummary( + long partitionCount, + long reservationCount, + long bindingCount, + BigInteger aggregateCountedCapacity, + String rootDigest) {} +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.java index 5ec07768b3..70040fb7ae 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.java @@ -25,7 +25,9 @@ import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; -/** Narrow canonical metadata and exact field-set codec for one initial-bootstrap issuer partition. */ +/** + * Narrow canonical metadata and exact field-set codec for one initial-bootstrap issuer partition. + */ final class CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec { static final String METADATA_FIELD = "!issuer-partition-bootstrap/v1"; static final String RESERVATION_FIELD_PREFIX = "!issuer-reservation-capacity/v1:"; @@ -84,13 +86,15 @@ static PhysicalFieldSet expectedFields(CanonicalGameplayIssuerBootstrapPartition if (valueBytes.length == 0 || valueBytes.length > MAX_VALUE_BYTES) { throw invalid("Exact SQL-issued v2 member exceeds its resource limit"); } - CanonicalGameplayIssuerMemberV2Value decoded = CanonicalGameplayIssuerMemberV2Codec.decode(valueBytes); + CanonicalGameplayIssuerMemberV2Value decoded = + CanonicalGameplayIssuerMemberV2Codec.decode(valueBytes); if (!decoded.equals(value) || !Arrays.equals(valueBytes, CanonicalGameplayIssuerMemberV2Codec.encode(decoded))) { throw invalid("SQL-issued v2 member bytes do not round-trip exactly"); } UUID reservationId = value.reservation().reservationId(); - if (!reservations.add(reservationId)) throw invalid("Duplicate partition reservation identity"); + if (!reservations.add(reservationId)) + throw invalid("Duplicate partition reservation identity"); byte[] bindingRefBytes = value.owner().bindingRef().bytes(); if (bindingRefBytes.length == 0 || bindingRefBytes.length > MAX_BINDING_REF_BYTES) { @@ -120,7 +124,8 @@ static PhysicalFieldSet expectedFields(CanonicalGameplayIssuerBootstrapPartition throw invalid("Issuer bootstrap partition field set exceeds its bounded resource limits"); } if (BigInteger.valueOf(partitionCapacityCount) - .compareTo(intent.layoutDescriptor().partitionCapacity()) > 0) { + .compareTo(intent.layoutDescriptor().partitionCapacity()) + > 0) { throw invalid("Prepared issuer partition exceeds its exact finite capacity"); } long aggregateCapacity = @@ -128,7 +133,10 @@ static PhysicalFieldSet expectedFields(CanonicalGameplayIssuerBootstrapPartition .filter(CanonicalGameplayIssuerPartitionBuildPlan.MemberWork::countsTowardCapacity) .count(); BigInteger aggregateBound = - intent.layoutDescriptor().partitionCount().multiply(intent.layoutDescriptor().partitionCapacity()); + intent + .layoutDescriptor() + .partitionCount() + .multiply(intent.layoutDescriptor().partitionCapacity()); if (BigInteger.valueOf(aggregateCapacity).compareTo(aggregateBound) > 0) { throw invalid("Prepared issuer aggregate capacity exceeds its exact finite layout bound"); } @@ -155,7 +163,8 @@ static void requireExactMetadata(byte[] encoded, byte[] expected) { } try { JsonNode decoded = JSON.readTree(strictUtf8(encoded)); - if (!(decoded instanceof ObjectNode root)) throw invalid("Bootstrap metadata must be an object"); + if (!(decoded instanceof ObjectNode root)) + throw invalid("Bootstrap metadata must be an object"); requireExactFields( root, Set.of( @@ -214,7 +223,9 @@ private static void validatePreparedWork(CanonicalGameplayIssuerBootstrapPartiti CanonicalGameplayBindingRef reference = CanonicalGameplayBindingRef.fromExactBytes(member.bindingRef()); if (member.workOrdinal() != index - || !member.plannedPartitionId().equals(reference.partitionId(intent.layoutDescriptor().partitionCount())) + || !member + .plannedPartitionId() + .equals(reference.partitionId(intent.layoutDescriptor().partitionCount())) || !reservationIds.add(member.reservationId()) || !memberOperationIds.add(member.memberOperationId())) { throw invalid("Prepared issuer plan has a duplicate or mis-mapped cohort member"); @@ -245,20 +256,35 @@ private static void validatePreparedWork(CanonicalGameplayIssuerBootstrapPartiti || !reservation.lifecycle().name().equals(planned.reservationLifecycle()) || !reservation.partitionId().equals(planned.plannedPartitionId()) || !reservation.partitionId().equals(planned.originalPartitionId()) - || !reservation.issuerCoverageOperationId().equals(planned.originalIssuerCoverageOperationId()) - || !reservation.issuerCoverageOperationFence().equals(planned.originalIssuerCoverageOperationFence()) + || !reservation + .issuerCoverageOperationId() + .equals(planned.originalIssuerCoverageOperationId()) + || !reservation + .issuerCoverageOperationFence() + .equals(planned.originalIssuerCoverageOperationFence()) || !reservation.coverageFence().equals(planned.originalCoverageFence()) - || !reservation.inventorySnapshotRevision().equals(planned.originalInventorySnapshotRevision()) + || !reservation + .inventorySnapshotRevision() + .equals(planned.originalInventorySnapshotRevision()) || !value.owner().issuerIndexLayoutVersion().equals(planned.originalLayoutVersion()) || !value.owner().issuerIndexPartitionCount().equals(planned.originalPartitionCount()) - || !value.owner().issuerIndexPartitionCapacity().equals(planned.originalPartitionCapacity()) + || !value + .owner() + .issuerIndexPartitionCapacity() + .equals(planned.originalPartitionCapacity()) || !Arrays.equals(memberRef.bytes(), planned.bindingRef()) || !value.incarnation().equals(work.incarnation()) || !value.anchor().issuerCoverageOperationId().equals(intent.operationId()) || !value.anchor().operationFence().equals(intent.operationFence()) || !value.anchor().coverageFence().equals(intent.coverageFence()) - || !value.anchor().issuerInventorySnapshotRevision().equals(intent.inventorySnapshotRevision()) - || !value.layoutDescriptor().descriptorDigest().equals(intent.layoutDescriptor().descriptorDigest()) + || !value + .anchor() + .issuerInventorySnapshotRevision() + .equals(intent.inventorySnapshotRevision()) + || !value + .layoutDescriptor() + .descriptorDigest() + .equals(intent.layoutDescriptor().descriptorDigest()) || !sameLayout(value.layoutDescriptor(), intent.layoutDescriptor()) || !sameCheckpoint(value.sourceCheckpoint(), intent.sourceCheckpoint()) || !value.issuerControlEpoch().equals(intent.controlEpoch()) @@ -267,9 +293,9 @@ private static void validatePreparedWork(CanonicalGameplayIssuerBootstrapPartiti || !issuedGenerations.add(operation.localMemberGeneration()) || operation.countsTowardCapacity() != (value.reservation().lifecycle() - != net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation.Lifecycle.RELEASED) - || operation.expectedBindingPresent() - != (planned.bindingSourceRowOrdinal() != null)) { + != net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation + .Lifecycle.RELEASED) + || operation.expectedBindingPresent() != (planned.bindingSourceRowOrdinal() != null)) { throw invalid("SQL-issued member differs from the complete frozen preparation tuple"); } } @@ -319,7 +345,8 @@ private static byte[] encodeMetadata( bootstrap.put("controlEpoch", intent.controlEpoch().toString()); bootstrap.put("operationFence", intent.operationFence().toString()); bootstrap.put("coverageFence", intent.coverageFence().toString()); - bootstrap.put("issuerInventorySnapshotRevision", intent.inventorySnapshotRevision().toString()); + bootstrap.put( + "issuerInventorySnapshotRevision", intent.inventorySnapshotRevision().toString()); bootstrap.put("cohortDigest", intent.cohortDigest()); ObjectNode build = root.putObject("build"); build.put("operationId", work.buildPlan().buildOperationId().toString()); @@ -329,7 +356,8 @@ private static byte[] encodeMetadata( layoutObject.put("partitionCount", layout.partitionCount().toString()); layoutObject.put("partitionCapacity", layout.partitionCapacity().toString()); layoutObject.put("mappingIdentity", layout.mappingIdentity()); - layoutObject.put("descriptorBytes", Base64.getEncoder().encodeToString(layout.exactDescriptorBytes())); + layoutObject.put( + "descriptorBytes", Base64.getEncoder().encodeToString(layout.exactDescriptorBytes())); layoutObject.put("descriptorDigest", layout.descriptorDigest()); ObjectNode anchor = root.putObject("anchor"); anchor.put("issuerCoverageOperationId", intent.operationId().toString()); @@ -337,7 +365,9 @@ private static byte[] encodeMetadata( anchor.put("coverageFence", intent.coverageFence().toString()); anchor.put("issuerInventorySnapshotRevision", intent.inventorySnapshotRevision().toString()); anchor.put("issuerAuthGeneration", source.issuerAuthGeneration().toString()); - anchor.put("sourceCheckpointBytes", Base64.getEncoder().encodeToString(source.exactCheckpointBytes())); + anchor.put( + "sourceCheckpointBytes", + Base64.getEncoder().encodeToString(source.exactCheckpointBytes())); anchor.put("sourceCheckpointDigest", source.checkpointDigest()); putNullableBase64(anchor, "sourceEventBytes", source.latestIssuerEventBytes()); putNullableText(anchor, "sourceEventDigest", source.latestIssuerEventDigest()); @@ -359,13 +389,15 @@ private static byte[] encodeMetadata( deploymentObject.put("storageGeneration", deployment.storageGeneration()); deploymentObject.put("aofGeneration", deployment.aofGeneration()); incarnationObject.put("coordOpsRoAclDigest", incarnation.coordOpsRoAclDigest()); - incarnationObject.put("coordRedisConfigObservedDigest", incarnation.coordRedisConfigObservedDigest()); + incarnationObject.put( + "coordRedisConfigObservedDigest", incarnation.coordRedisConfigObservedDigest()); root.put("plannedAggregateCapacityCount", plannedAggregateCapacityCount.toString()); - root.put("plannedPartitionReservationCount", Integer.toString(work.memberOperations().size())); + root.put( + "plannedPartitionReservationCount", Integer.toString(work.memberOperations().size())); root.put("plannedPartitionCapacityCount", Long.toString(plannedPartitionCapacityCount)); - byte[] encoded = - Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); - if (encoded.length > MAX_METADATA_BYTES) throw invalid("Bootstrap metadata exceeds its resource limit"); + byte[] encoded = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + if (encoded.length > MAX_METADATA_BYTES) + throw invalid("Bootstrap metadata exceeds its resource limit"); return encoded; } catch (IOException failure) { throw new IllegalArgumentException("Could not encode canonical bootstrap metadata", failure); @@ -383,7 +415,9 @@ private static void putNullableText(ObjectNode object, String name, String value } private static void putUnique(Map fields, String field, byte[] value) { - if (field == null || field.isEmpty() || field.getBytes(StandardCharsets.UTF_8).length > MAX_BINDING_REF_BYTES + if (field == null + || field.isEmpty() + || field.getBytes(StandardCharsets.UTF_8).length > MAX_BINDING_REF_BYTES || fields.putIfAbsent(field, value.clone()) != null) { throw invalid("Issuer bootstrap field identity is reserved, oversized, or duplicated"); } @@ -398,7 +432,8 @@ private static String strictUtf8(byte[] bytes) { .decode(ByteBuffer.wrap(bytes)) .toString(); } catch (CharacterCodingException malformed) { - throw new IllegalArgumentException("Issuer bootstrap field is not canonical UTF-8", malformed); + throw new IllegalArgumentException( + "Issuer bootstrap field is not canonical UTF-8", malformed); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwner.java index caff08a9d8..e52a26415b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwner.java @@ -1,7 +1,7 @@ package net.firedevops.firemud.gamesession.repository; -import io.lettuce.core.RedisFuture; import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisFuture; import io.lettuce.core.ScriptOutputType; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.async.RedisAsyncCommands; @@ -38,9 +38,7 @@ public final class CanonicalGameplayIssuerBootstrapPartitionRedisOwner { private static final List EXPECTED_KEYS = List.of( new RedisScriptDescriptor.KeySpec( - "issuerPartition", - KEY_PREFIX, - RedisScriptDescriptor.HashTagDeclaration.REQUIRED)); + "issuerPartition", KEY_PREFIX, RedisScriptDescriptor.HashTagDeclaration.REQUIRED)); private static final List EXPECTED_ARGUMENTS = List.of( new RedisScriptDescriptor.ArgumentSpec("issuerId"), @@ -49,7 +47,8 @@ public final class CanonicalGameplayIssuerBootstrapPartitionRedisOwner { new RedisScriptDescriptor.ArgumentSpec("partitionCapacity"), new RedisScriptDescriptor.ArgumentSpec("exactBootstrapMetadata"), new RedisScriptDescriptor.ArgumentSpec("memberOperationCount"), - new RedisScriptDescriptor.ArgumentSpec("repeatedBindingRefMemberCapacityFieldBindingPresence")); + new RedisScriptDescriptor.ArgumentSpec( + "repeatedBindingRefMemberCapacityFieldBindingPresence")); private static final List EXPECTED_OUTCOMES = List.of( new RedisScriptDescriptor.OutcomeSpec( @@ -73,7 +72,9 @@ public final class CanonicalGameplayIssuerBootstrapPartitionRedisOwner { private final RedisScriptCatalog catalog; private final CurrentIssuerStateSource currentStateSource; - /** The Redis client, manual owner contribution catalog, and protected local source are explicit. */ + /** + * The Redis client, manual owner contribution catalog, and protected local source are explicit. + */ public CanonicalGameplayIssuerBootstrapPartitionRedisOwner( RedisClient redisClient, RedisScriptCatalog catalog, @@ -114,8 +115,30 @@ public Readback buildAndRead(CanonicalGameplayIssuerBootstrapPartitionWork work) } } - private long writeOneKey( - byte[] script, byte[] key, byte[][] arguments) { + /** + * Reads and verifies the exact current physical field set for an installed-anchor retry or + * reader. This method never creates, repairs, or rebuilds a missing partition. + */ + public Readback readExistingAndRead(CanonicalGameplayIssuerBootstrapPartitionWork work) { + Objects.requireNonNull(work, "Prepared issuer partition work is required"); + try { + requireNoAmbientTransaction(); + var physical = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.expectedFields(work); + requireFreshCurrentState(work); + PhysicalReadback observed = readExactPhysicalState(exactPartitionKey(work), physical); + requireFreshCurrentState(work); + return new Readback(work, observed, physical.plannedAggregateCapacityCount()); + } catch (RuntimeException failure) { + if (failure instanceof IllegalStateException state + && state.getMessage() != null + && state.getMessage().contains("partition projection is unavailable")) { + throw state; + } + throw unavailable(failure); + } + } + + private long writeOneKey(byte[] script, byte[] key, byte[][] arguments) { requireNoAmbientTransaction(); try (StatefulRedisConnection connection = redisClient.connect(ByteArrayCodec.INSTANCE)) { @@ -125,11 +148,7 @@ private long writeOneKey( if (!digest("SHA-1", script).equals(loadedSha)) throw unavailable(); Long reply = await( - commands.evalsha( - loadedSha, - ScriptOutputType.INTEGER, - new byte[][] {key}, - arguments)); + commands.evalsha(loadedSha, ScriptOutputType.INTEGER, new byte[][] {key}, arguments)); if (reply == null) throw unavailable(); return reply; } catch (RuntimeException failure) { @@ -138,7 +157,8 @@ private long writeOneKey( } private PhysicalReadback readExactPhysicalState( - byte[] key, CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.PhysicalFieldSet expected) { + byte[] key, + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.PhysicalFieldSet expected) { requireNoAmbientTransaction(); try (StatefulRedisConnection connection = redisClient.connect(ByteArrayCodec.INSTANCE)) { @@ -162,7 +182,8 @@ private PhysicalReadback readExactPhysicalState( byte[] field = Objects.requireNonNull(entry.getKey(), "Redis field"); byte[] value = Objects.requireNonNull(entry.getValue(), "Redis value"); totalBytes += (long) field.length + value.length; - if (totalBytes > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_TOTAL_HASH_BYTES) { + if (totalBytes + > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_TOTAL_HASH_BYTES) { throw unavailable(); } String encodedField = Base64.getEncoder().encodeToString(field); @@ -175,11 +196,12 @@ private PhysicalReadback readExactPhysicalState( byte[] observed = actual.get(Base64.getEncoder().encodeToString(redisField)); if (!Arrays.equals(entry.getValue(), observed)) throw unavailable(); } - byte[] metadata = actual.get( - Base64.getEncoder() - .encodeToString( - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.METADATA_FIELD - .getBytes(StandardCharsets.US_ASCII))); + byte[] metadata = + actual.get( + Base64.getEncoder() + .encodeToString( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.METADATA_FIELD + .getBytes(StandardCharsets.US_ASCII))); CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.requireExactMetadata( metadata, expected.metadataBytes()); @@ -190,19 +212,23 @@ private PhysicalReadback readExactPhysicalState( if (field.startsWith( CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.RESERVATION_FIELD_PREFIX)) { CanonicalGameplayIssuerMemberV2Value decoded = - CanonicalGameplayIssuerMemberV2Codec.decode(actual.get( - Base64.getEncoder().encodeToString(field.getBytes(StandardCharsets.US_ASCII)))); + CanonicalGameplayIssuerMemberV2Codec.decode( + actual.get( + Base64.getEncoder() + .encodeToString(field.getBytes(StandardCharsets.US_ASCII)))); if (!decoded.equals(CanonicalGameplayIssuerMemberV2Codec.decode(entry.getValue()))) { throw unavailable(); } if (decoded.reservation().lifecycle() - != net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation.Lifecycle.RELEASED) { + != net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation + .Lifecycle.RELEASED) { capacityCount++; } } else if (!field.equals( CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.METADATA_FIELD)) { - CanonicalGameplayIssuerMemberV2Codec.decode(actual.get( - Base64.getEncoder().encodeToString(field.getBytes(StandardCharsets.UTF_8)))); + CanonicalGameplayIssuerMemberV2Codec.decode( + actual.get( + Base64.getEncoder().encodeToString(field.getBytes(StandardCharsets.UTF_8)))); bindingCount++; } } @@ -232,11 +258,12 @@ private void requireFreshCurrentState(CanonicalGameplayIssuerBootstrapPartitionW private RedisScriptDescriptor requireDescriptor() { try { RedisScriptDescriptor descriptor = - catalog.require(CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.SCRIPT_ID); - if (!CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.SCRIPT_ID - .equals(descriptor.scriptId()) - || !CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.RESOURCE_PATH - .equals(descriptor.resourcePath()) + catalog.require( + CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.SCRIPT_ID); + if (!CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.SCRIPT_ID.equals( + descriptor.scriptId()) + || !CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.RESOURCE_PATH.equals( + descriptor.resourcePath()) || !"game-session-service".equals(descriptor.owner()) || !PRINCIPAL.equals(descriptor.principal()) || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION @@ -373,13 +400,17 @@ private static IllegalStateException unavailable(Throwable cause) { return new IllegalStateException("Issuer bootstrap partition projection is unavailable", cause); } - /** Fresh, trusted local read collaborator. No default implementation derives authority from work. */ + /** + * Fresh, trusted local read collaborator. No default implementation derives authority from work. + */ @FunctionalInterface public interface CurrentIssuerStateSource { CurrentIssuerState readFreshCurrentState(); } - /** One current exact Account checkpoint and stable incarnation observation from the collaborator. */ + /** + * One current exact Account checkpoint and stable incarnation observation from the collaborator. + */ public record CurrentIssuerState( CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint accountCheckpoint, CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation) { @@ -391,7 +422,10 @@ public record CurrentIssuerState( private record PhysicalReadback(int fieldCount, int countedReservationCount, int bindingCount) {} - /** Exact physical partition readback; it carries no global aggregate, acknowledgement, or OPEN authority. */ + /** + * Exact physical partition readback; it carries no global aggregate, acknowledgement, or OPEN + * authority. + */ public static final class Readback { private final CanonicalGameplayIssuerBootstrapPartitionWork work; private final int physicalFieldCount; @@ -412,8 +446,8 @@ private Readback( this.plannedAggregateCapacityCount = Objects.requireNonNull(plannedAggregateCapacityCount); if (observed.fieldCount() != 1 + physicalReservationCount + physicalBindingCount || BigInteger.valueOf(observed.countedReservationCount()) - .compareTo( - work.buildPlan().bootstrapIntent().layoutDescriptor().partitionCapacity()) + .compareTo( + work.buildPlan().bootstrapIntent().layoutDescriptor().partitionCapacity()) > 0) { throw unavailable(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerInstalledAnchor.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerInstalledAnchor.java new file mode 100644 index 0000000000..427c587275 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerInstalledAnchor.java @@ -0,0 +1,322 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.math.BigInteger; +import java.util.Objects; +import java.util.UUID; + +/** + * Immutable local initial issuer coverage/layout anchor returned only after finite physical + * readback and an exact SQL installation CAS. This is not an issuer tenant barrier or admission + * capability. + */ +public final class CanonicalGameplayIssuerInstalledAnchor { + private static final String ENCODING = "canonical-installed-issuer-anchor/v1"; + + private final UUID bootstrapOperationId; + private final UUID bootstrapRequestId; + private final UUID buildOperationId; + private final String buildPlanDigest; + private final String issuerId; + private final BigInteger controlEpoch; + private final UUID issuerCoverageOperationId; + private final BigInteger operationFence; + private final BigInteger coverageFence; + private final BigInteger issuerInventorySnapshotRevision; + private final BigInteger layoutVersion; + private final BigInteger partitionCount; + private final BigInteger partitionCapacity; + private final String mappingIdentity; + private final byte[] layoutDescriptorBytes; + private final String layoutDescriptorDigest; + private final BigInteger issuerAuthGeneration; + private final byte[] sourceCheckpointBytes; + private final String sourceCheckpointDigest; + private final byte[] sourceEventBytes; + private final String sourceEventDigest; + private final byte[] incarnationBytes; + private final String incarnationDigest; + private final BigInteger globalCoverageGeneration; + private final long partitionProofCount; + private final long physicalReservationCount; + private final long physicalBindingCount; + private final BigInteger aggregateCountedCapacity; + private final String partitionProofRootDigest; + private final byte[] exactAnchorBytes; + private final String exactAnchorDigest; + + CanonicalGameplayIssuerInstalledAnchor( + UUID bootstrapOperationId, + UUID bootstrapRequestId, + UUID buildOperationId, + String buildPlanDigest, + String issuerId, + BigInteger controlEpoch, + UUID issuerCoverageOperationId, + BigInteger operationFence, + BigInteger coverageFence, + BigInteger issuerInventorySnapshotRevision, + BigInteger layoutVersion, + BigInteger partitionCount, + BigInteger partitionCapacity, + String mappingIdentity, + byte[] layoutDescriptorBytes, + String layoutDescriptorDigest, + BigInteger issuerAuthGeneration, + byte[] sourceCheckpointBytes, + String sourceCheckpointDigest, + byte[] sourceEventBytes, + String sourceEventDigest, + byte[] incarnationBytes, + String incarnationDigest, + BigInteger globalCoverageGeneration, + long partitionProofCount, + long physicalReservationCount, + long physicalBindingCount, + BigInteger aggregateCountedCapacity, + String partitionProofRootDigest, + byte[] storedExactAnchorBytes, + String storedExactAnchorDigest) { + this.bootstrapOperationId = requireNonNil(bootstrapOperationId, "bootstrapOperationId"); + this.bootstrapRequestId = requireNonNil(bootstrapRequestId, "bootstrapRequestId"); + this.buildOperationId = requireNonNil(buildOperationId, "buildOperationId"); + this.buildPlanDigest = requireDigest(buildPlanDigest, "buildPlanDigest"); + this.issuerId = requireIssuer(issuerId); + this.controlEpoch = requirePositive(controlEpoch, "controlEpoch"); + this.issuerCoverageOperationId = requireNonNil(issuerCoverageOperationId, "issuerCoverageOperationId"); + this.operationFence = requirePositive(operationFence, "operationFence"); + this.coverageFence = requirePositive(coverageFence, "coverageFence"); + if (!this.issuerCoverageOperationId.equals(this.bootstrapOperationId) + || !this.controlEpoch.equals(this.operationFence) + || this.operationFence.equals(this.coverageFence)) { + throw new IllegalArgumentException("Initial anchor must retain its exact distinct operation tuple"); + } + this.issuerInventorySnapshotRevision = + requirePositive(issuerInventorySnapshotRevision, "issuerInventorySnapshotRevision"); + this.layoutVersion = requirePositive(layoutVersion, "layoutVersion"); + this.partitionCount = requirePositive(partitionCount, "partitionCount"); + this.partitionCapacity = requirePositive(partitionCapacity, "partitionCapacity"); + this.mappingIdentity = Objects.requireNonNull(mappingIdentity, "mappingIdentity"); + if (!CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY.equals(mappingIdentity)) { + throw new IllegalArgumentException("Unsupported issuer layout mapping identity"); + } + this.layoutDescriptorBytes = nonEmpty(layoutDescriptorBytes, "layoutDescriptorBytes"); + this.layoutDescriptorDigest = requireDigest(layoutDescriptorDigest, "layoutDescriptorDigest"); + requireDigestMatches(this.layoutDescriptorBytes, this.layoutDescriptorDigest, "layout descriptor"); + this.issuerAuthGeneration = requirePositive(issuerAuthGeneration, "issuerAuthGeneration"); + this.sourceCheckpointBytes = nonEmpty(sourceCheckpointBytes, "sourceCheckpointBytes"); + this.sourceCheckpointDigest = requireDigest(sourceCheckpointDigest, "sourceCheckpointDigest"); + requireDigestMatches(this.sourceCheckpointBytes, this.sourceCheckpointDigest, "source checkpoint"); + this.sourceEventBytes = sourceEventBytes == null ? null : nonEmpty(sourceEventBytes, "sourceEventBytes"); + this.sourceEventDigest = sourceEventDigest == null ? null : requireDigest(sourceEventDigest, "sourceEventDigest"); + if ((this.sourceEventBytes == null) != (this.sourceEventDigest == null)) { + throw new IllegalArgumentException("Account source event bytes and digest must be paired"); + } + if (this.sourceEventBytes != null) { + requireDigestMatches(this.sourceEventBytes, this.sourceEventDigest, "source event"); + } + this.incarnationBytes = nonEmpty(incarnationBytes, "incarnationBytes"); + this.incarnationDigest = requireDigest(incarnationDigest, "incarnationDigest"); + requireDigestMatches(this.incarnationBytes, this.incarnationDigest, "stable incarnation"); + this.globalCoverageGeneration = requirePositive(globalCoverageGeneration, "globalCoverageGeneration"); + if (partitionProofCount < 1 + || !BigInteger.valueOf(partitionProofCount).equals(partitionCount) + || physicalReservationCount < 0 + || physicalBindingCount < 0 + || physicalBindingCount > physicalReservationCount) { + throw new IllegalArgumentException("Installed anchor must retain the complete finite proof counts"); + } + this.partitionProofCount = partitionProofCount; + this.physicalReservationCount = physicalReservationCount; + this.physicalBindingCount = physicalBindingCount; + this.aggregateCountedCapacity = Objects.requireNonNull(aggregateCountedCapacity, "aggregateCountedCapacity"); + if (aggregateCountedCapacity.signum() < 0 + || aggregateCountedCapacity.compareTo(partitionCount.multiply(partitionCapacity)) > 0 + || aggregateCountedCapacity.compareTo(BigInteger.valueOf(physicalReservationCount)) > 0) { + throw new IllegalArgumentException("Installed anchor aggregate capacity is outside its finite bound"); + } + this.partitionProofRootDigest = requireDigest(partitionProofRootDigest, "partitionProofRootDigest"); + this.exactAnchorBytes = encodeExactAnchor(); + this.exactAnchorDigest = CanonicalGameplayIssuerMemberV2Codec.sha256(this.exactAnchorBytes); + if ((storedExactAnchorBytes == null) != (storedExactAnchorDigest == null) + || (storedExactAnchorBytes != null + && (!java.util.Arrays.equals(this.exactAnchorBytes, storedExactAnchorBytes) + || !this.exactAnchorDigest.equals(storedExactAnchorDigest)))) { + throw new IllegalArgumentException("Stored installed-anchor bytes differ from their exact tuple"); + } + } + + static byte[] encodeIncarnation(CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation) { + Objects.requireNonNull(incarnation, "incarnation"); + var deployment = incarnation.targetDeploymentEvidence(); + return encode( + output -> { + writeText(output, "canonical-stable-issuer-incarnation/v1"); + writeText(output, incarnation.attestorBinding()); + writeText(output, incarnation.acceptedAttestationDigest()); + writeText(output, deployment.deploymentIdentity()); + writeText(output, deployment.deploymentGeneration()); + output.writeInt(deployment.canonicalNodeSet().size()); + for (String node : deployment.canonicalNodeSet()) writeText(output, node); + writeText(output, deployment.redisBuildIdentity()); + writeText(output, deployment.luaScriptRegistryVersion()); + writeText(output, deployment.luaScriptRegistryDigest()); + writeText(output, deployment.startupState()); + writeText(output, deployment.bootGeneration()); + writeText(output, deployment.startupGeneration()); + writeText(output, deployment.storageGeneration()); + writeText(output, deployment.aofGeneration()); + writeText(output, incarnation.coordOpsRoAclDigest()); + writeText(output, incarnation.coordRedisConfigObservedDigest()); + }); + } + + private byte[] encodeExactAnchor() { + return encode( + output -> { + writeText(output, ENCODING); + writeText(output, bootstrapOperationId.toString()); + writeText(output, bootstrapRequestId.toString()); + writeText(output, buildOperationId.toString()); + writeText(output, buildPlanDigest); + writeText(output, issuerId); + writeBigInteger(output, controlEpoch); + writeText(output, issuerCoverageOperationId.toString()); + writeBigInteger(output, operationFence); + writeBigInteger(output, coverageFence); + writeBigInteger(output, issuerInventorySnapshotRevision); + writeBigInteger(output, layoutVersion); + writeBigInteger(output, partitionCount); + writeBigInteger(output, partitionCapacity); + writeText(output, mappingIdentity); + writeBytes(output, layoutDescriptorBytes); + writeText(output, layoutDescriptorDigest); + writeBigInteger(output, issuerAuthGeneration); + writeBytes(output, sourceCheckpointBytes); + writeText(output, sourceCheckpointDigest); + writeNullableBytes(output, sourceEventBytes); + writeNullableText(output, sourceEventDigest); + writeBytes(output, incarnationBytes); + writeText(output, incarnationDigest); + writeBigInteger(output, globalCoverageGeneration); + output.writeLong(partitionProofCount); + output.writeLong(physicalReservationCount); + output.writeLong(physicalBindingCount); + writeBigInteger(output, aggregateCountedCapacity); + writeText(output, partitionProofRootDigest); + }); + } + + public UUID bootstrapOperationId() { return bootstrapOperationId; } + public UUID bootstrapRequestId() { return bootstrapRequestId; } + public UUID buildOperationId() { return buildOperationId; } + public String buildPlanDigest() { return buildPlanDigest; } + public String issuerId() { return issuerId; } + public BigInteger controlEpoch() { return controlEpoch; } + public UUID issuerCoverageOperationId() { return issuerCoverageOperationId; } + public BigInteger operationFence() { return operationFence; } + public BigInteger coverageFence() { return coverageFence; } + public BigInteger issuerInventorySnapshotRevision() { return issuerInventorySnapshotRevision; } + public BigInteger layoutVersion() { return layoutVersion; } + public BigInteger partitionCount() { return partitionCount; } + public BigInteger partitionCapacity() { return partitionCapacity; } + public String mappingIdentity() { return mappingIdentity; } + public byte[] layoutDescriptorBytes() { return layoutDescriptorBytes.clone(); } + public String layoutDescriptorDigest() { return layoutDescriptorDigest; } + public BigInteger issuerAuthGeneration() { return issuerAuthGeneration; } + public byte[] sourceCheckpointBytes() { return sourceCheckpointBytes.clone(); } + public String sourceCheckpointDigest() { return sourceCheckpointDigest; } + public byte[] sourceEventBytes() { return sourceEventBytes == null ? null : sourceEventBytes.clone(); } + public String sourceEventDigest() { return sourceEventDigest; } + public byte[] incarnationBytes() { return incarnationBytes.clone(); } + public String incarnationDigest() { return incarnationDigest; } + public BigInteger globalCoverageGeneration() { return globalCoverageGeneration; } + public long partitionProofCount() { return partitionProofCount; } + public long physicalReservationCount() { return physicalReservationCount; } + public long physicalBindingCount() { return physicalBindingCount; } + public BigInteger aggregateCountedCapacity() { return aggregateCountedCapacity; } + public String partitionProofRootDigest() { return partitionProofRootDigest; } + public byte[] exactAnchorBytes() { return exactAnchorBytes.clone(); } + public String exactAnchorDigest() { return exactAnchorDigest; } + + private static byte[] encode(IoWriter writer) { + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream output = new DataOutputStream(bytes)) { + writer.write(output); + } + return bytes.toByteArray(); + } catch (IOException impossible) { + throw new IllegalStateException("Could not encode exact issuer anchor bytes", impossible); + } + } + + private static void writeText(DataOutputStream output, String value) throws IOException { + writeBytes(output, Objects.requireNonNull(value, "exact text").getBytes(java.nio.charset.StandardCharsets.UTF_8)); + } + + private static void writeBigInteger(DataOutputStream output, BigInteger value) throws IOException { + writeText(output, Objects.requireNonNull(value, "exact counter").toString()); + } + + private static void writeBytes(DataOutputStream output, byte[] bytes) throws IOException { + output.writeInt(bytes.length); + output.write(bytes); + } + + private static void writeNullableBytes(DataOutputStream output, byte[] bytes) throws IOException { + output.writeBoolean(bytes != null); + if (bytes != null) writeBytes(output, bytes); + } + + private static void writeNullableText(DataOutputStream output, String value) throws IOException { + output.writeBoolean(value != null); + if (value != null) writeText(output, value); + } + + private static UUID requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) throw new IllegalArgumentException(name + " must not be nil"); + return value; + } + + private static String requireIssuer(String value) { + if (!net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.ISSUER.equals(value)) { + throw new IllegalArgumentException("Installed anchor issuer scope is not canonical"); + } + return value; + } + + private static BigInteger requirePositive(BigInteger value, String name) { + Objects.requireNonNull(value, name); + if (value.signum() <= 0) throw new IllegalArgumentException(name + " must be positive"); + return value; + } + + private static byte[] nonEmpty(byte[] value, String name) { + Objects.requireNonNull(value, name); + if (value.length == 0) throw new IllegalArgumentException(name + " must not be empty"); + return value.clone(); + } + + private static String requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(name + " must be a canonical SHA-256 digest"); + } + return value; + } + + private static void requireDigestMatches(byte[] bytes, String digest, String name) { + if (!CanonicalGameplayIssuerMemberV2Codec.sha256(bytes).equals(digest)) { + throw new IllegalArgumentException(name + " digest does not match its exact bytes"); + } + } + + @FunctionalInterface + private interface IoWriter { + void write(DataOutputStream output) throws IOException; + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V1033__canonical_issuer_bootstrap_coverage.sql b/services/game-session-service/src/main/resources/db/migration/V1033__canonical_issuer_bootstrap_coverage.sql new file mode 100644 index 0000000000..08b2c61d61 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1033__canonical_issuer_bootstrap_coverage.sql @@ -0,0 +1,259 @@ +-- These records qualify one local initial issuer-layout installation only. They do not install +-- an issuer tenant barrier, open it, or authorize a binding or admission. +CREATE TABLE game_session_canonical_issuer_bootstrap_partition_proof ( + build_operation_id uuid NOT NULL, + bootstrap_operation_id uuid NOT NULL, + bootstrap_request_id uuid NOT NULL, + issuer_id character varying(64) NOT NULL, + build_plan_digest character varying(71) NOT NULL, + bootstrap_operation_fence numeric NOT NULL, + bootstrap_coverage_fence numeric NOT NULL, + issuer_inventory_snapshot_revision numeric NOT NULL, + layout_version numeric NOT NULL, + partition_count numeric NOT NULL, + partition_capacity numeric NOT NULL, + mapping_identity character varying(96) NOT NULL, + layout_descriptor_bytes bytea NOT NULL, + layout_descriptor_digest character varying(71) NOT NULL, + source_checkpoint_bytes bytea NOT NULL, + source_checkpoint_digest character varying(71) NOT NULL, + source_event_bytes bytea, + source_event_digest character varying(71), + incarnation_bytes bytea NOT NULL, + incarnation_digest character varying(71) NOT NULL, + partition_id numeric NOT NULL, + exact_metadata_bytes bytea NOT NULL, + exact_physical_field_set_bytes bytea NOT NULL, + exact_physical_field_set_digest character varying(71) NOT NULL, + physical_field_count integer NOT NULL, + physical_reservation_count integer NOT NULL, + physical_binding_count integer NOT NULL, + physical_counted_capacity_count integer NOT NULL, + planned_aggregate_capacity_count numeric NOT NULL, + proof_state character varying(24) NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_issuer_bootstrap_partition_proof + PRIMARY KEY (bootstrap_operation_id, partition_id), + CONSTRAINT fk_gs_issuer_bootstrap_partition_proof_plan FOREIGN KEY ( + build_operation_id, bootstrap_operation_id, bootstrap_request_id, issuer_id, + build_plan_digest) + REFERENCES game_session_canonical_issuer_partition_build_plan ( + build_operation_id, bootstrap_operation_id, bootstrap_request_id, issuer_id, plan_digest), + CONSTRAINT chk_gs_issuer_bootstrap_partition_proof CHECK ( + issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND bootstrap_operation_fence > 0 + AND bootstrap_coverage_fence > 0 + AND bootstrap_operation_fence <> bootstrap_coverage_fence + AND issuer_inventory_snapshot_revision > 0 + AND layout_version > 0 + AND partition_count > 0 + AND partition_capacity > 0 + AND mapping_identity = 'bindingRef/v1;sha256-u256-mod/v1' + AND octet_length(layout_descriptor_bytes) > 0 + AND layout_descriptor_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(source_checkpoint_bytes) > 0 + AND source_checkpoint_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((source_event_bytes IS NULL AND source_event_digest IS NULL) + OR (source_event_bytes IS NOT NULL + AND octet_length(source_event_bytes) > 0 + AND source_event_digest IS NOT NULL + AND source_event_digest ~ '^sha256:[0-9a-f]{64}$')) + AND octet_length(incarnation_bytes) > 0 + AND incarnation_digest ~ '^sha256:[0-9a-f]{64}$' + AND partition_id >= 0 + AND partition_id < partition_count + AND partition_id = floor(partition_id) + AND octet_length(exact_metadata_bytes) BETWEEN 1 AND 65536 + AND octet_length(exact_physical_field_set_bytes) BETWEEN 1 AND 17825792 + AND exact_physical_field_set_digest ~ '^sha256:[0-9a-f]{64}$' + AND physical_field_count > 0 + AND physical_reservation_count >= 0 + AND physical_binding_count >= 0 + AND physical_counted_capacity_count >= 0 + AND physical_counted_capacity_count <= partition_capacity + AND physical_field_count = 1 + physical_reservation_count + physical_binding_count + AND planned_aggregate_capacity_count >= 0 + AND planned_aggregate_capacity_count <= partition_count * partition_capacity + AND proof_state = 'EXACT_PHYSICAL_READBACK') +); + +CREATE TABLE game_session_canonical_issuer_bootstrap_coverage_counter ( + issuer_id character varying(64) NOT NULL, + last_issued_coverage_generation numeric NOT NULL, + counter_version bigint NOT NULL, + updated_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_issuer_bootstrap_coverage_counter PRIMARY KEY (issuer_id), + CONSTRAINT uq_gs_issuer_bootstrap_coverage_counter_value + UNIQUE (issuer_id, last_issued_coverage_generation), + CONSTRAINT chk_gs_issuer_bootstrap_coverage_counter CHECK ( + issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND last_issued_coverage_generation >= 0 + AND last_issued_coverage_generation = floor(last_issued_coverage_generation) + AND length(CAST(last_issued_coverage_generation AS varchar)) <= 256 + AND counter_version >= 0 + AND ((counter_version = 0 AND last_issued_coverage_generation = 0) + OR (counter_version > 0 AND last_issued_coverage_generation > 0))) +); + +CREATE TABLE game_session_canonical_issuer_installed_anchor ( + issuer_id character varying(64) NOT NULL, + bootstrap_operation_id uuid NOT NULL, + bootstrap_request_id uuid NOT NULL, + build_operation_id uuid NOT NULL, + build_plan_digest character varying(71) NOT NULL, + control_epoch numeric NOT NULL, + issuer_coverage_operation_id uuid NOT NULL, + operation_fence numeric NOT NULL, + coverage_fence numeric NOT NULL, + issuer_inventory_snapshot_revision numeric NOT NULL, + layout_version numeric NOT NULL, + partition_count numeric NOT NULL, + partition_capacity numeric NOT NULL, + mapping_identity character varying(96) NOT NULL, + layout_descriptor_bytes bytea NOT NULL, + layout_descriptor_digest character varying(71) NOT NULL, + issuer_auth_generation numeric NOT NULL, + source_checkpoint_bytes bytea NOT NULL, + source_checkpoint_digest character varying(71) NOT NULL, + source_event_bytes bytea, + source_event_digest character varying(71), + incarnation_bytes bytea NOT NULL, + incarnation_digest character varying(71) NOT NULL, + global_coverage_generation numeric NOT NULL, + partition_proof_count bigint NOT NULL, + physical_reservation_count bigint NOT NULL, + physical_binding_count bigint NOT NULL, + aggregate_counted_capacity numeric NOT NULL, + partition_proof_root_digest character varying(71) NOT NULL, + exact_anchor_bytes bytea NOT NULL, + exact_anchor_digest character varying(71) NOT NULL, + anchor_state character varying(24) NOT NULL, + installed_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_issuer_installed_anchor PRIMARY KEY (issuer_id), + CONSTRAINT uq_gs_issuer_installed_anchor_operation UNIQUE (bootstrap_operation_id), + CONSTRAINT uq_gs_issuer_installed_anchor_generation + UNIQUE (issuer_id, global_coverage_generation), + CONSTRAINT fk_gs_issuer_installed_anchor_intent FOREIGN KEY ( + bootstrap_operation_id, issuer_id, control_epoch, operation_fence, coverage_fence) + REFERENCES game_session_canonical_issuer_layout_bootstrap_intent ( + operation_id, issuer_id, control_epoch, operation_fence, coverage_fence), + CONSTRAINT fk_gs_issuer_installed_anchor_request FOREIGN KEY ( + issuer_id, bootstrap_request_id) + REFERENCES game_session_canonical_issuer_layout_bootstrap_intent (issuer_id, request_id), + CONSTRAINT fk_gs_issuer_installed_anchor_plan FOREIGN KEY ( + build_operation_id, bootstrap_operation_id, bootstrap_request_id, issuer_id, + build_plan_digest) + REFERENCES game_session_canonical_issuer_partition_build_plan ( + build_operation_id, bootstrap_operation_id, bootstrap_request_id, issuer_id, plan_digest), + CONSTRAINT fk_gs_issuer_installed_anchor_counter FOREIGN KEY (issuer_id) + REFERENCES game_session_canonical_issuer_bootstrap_coverage_counter (issuer_id), + CONSTRAINT chk_gs_issuer_installed_anchor CHECK ( + issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND issuer_coverage_operation_id = bootstrap_operation_id + AND control_epoch > 0 + AND operation_fence = control_epoch + AND operation_fence > 0 + AND coverage_fence > 0 + AND coverage_fence <> operation_fence + AND issuer_inventory_snapshot_revision > 0 + AND layout_version > 0 + AND partition_count > 0 + AND partition_capacity > 0 + AND mapping_identity = 'bindingRef/v1;sha256-u256-mod/v1' + AND octet_length(layout_descriptor_bytes) > 0 + AND layout_descriptor_digest ~ '^sha256:[0-9a-f]{64}$' + AND issuer_auth_generation > 0 + AND octet_length(source_checkpoint_bytes) > 0 + AND source_checkpoint_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((source_event_bytes IS NULL AND source_event_digest IS NULL) + OR (source_event_bytes IS NOT NULL + AND octet_length(source_event_bytes) > 0 + AND source_event_digest IS NOT NULL + AND source_event_digest ~ '^sha256:[0-9a-f]{64}$')) + AND octet_length(incarnation_bytes) > 0 + AND incarnation_digest ~ '^sha256:[0-9a-f]{64}$' + AND global_coverage_generation > 0 + AND partition_proof_count = partition_count + AND physical_reservation_count >= 0 + AND physical_binding_count >= 0 + AND aggregate_counted_capacity >= 0 + AND aggregate_counted_capacity <= partition_count * partition_capacity + AND partition_proof_root_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(exact_anchor_bytes) BETWEEN 1 AND 262144 + AND exact_anchor_digest ~ '^sha256:[0-9a-f]{64}$' + AND anchor_state = 'INITIAL_INSTALLED') +); + +-- The proof, counter, and initial pointer are append-only. Counter advancement is the only +-- mutable write and is a same-issuer monotonic compare-and-set in the installation transaction. +-- [jooq ignore start] +CREATE FUNCTION game_session_reject_issuer_bootstrap_coverage_change() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'issuer bootstrap coverage artifacts are immutable' + USING ERRCODE = 'check_violation'; +END; +$$; + +CREATE TRIGGER trg_gs_issuer_bootstrap_partition_proof_immutable + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_bootstrap_partition_proof + FOR EACH ROW EXECUTE FUNCTION game_session_reject_issuer_bootstrap_coverage_change(); +CREATE TRIGGER trg_gs_issuer_bootstrap_partition_proof_no_truncate + BEFORE TRUNCATE ON game_session_canonical_issuer_bootstrap_partition_proof + FOR EACH STATEMENT EXECUTE FUNCTION game_session_reject_issuer_bootstrap_coverage_change(); +CREATE TRIGGER trg_gs_issuer_installed_anchor_immutable + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_installed_anchor + FOR EACH ROW EXECUTE FUNCTION game_session_reject_issuer_bootstrap_coverage_change(); +CREATE TRIGGER trg_gs_issuer_installed_anchor_no_truncate + BEFORE TRUNCATE ON game_session_canonical_issuer_installed_anchor + FOR EACH STATEMENT EXECUTE FUNCTION game_session_reject_issuer_bootstrap_coverage_change(); +CREATE TRIGGER trg_gs_issuer_bootstrap_coverage_counter_no_truncate + BEFORE TRUNCATE ON game_session_canonical_issuer_bootstrap_coverage_counter + FOR EACH STATEMENT EXECUTE FUNCTION game_session_reject_issuer_bootstrap_coverage_change(); + +CREATE FUNCTION game_session_guard_issuer_bootstrap_coverage_counter() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'issuer bootstrap coverage counter cannot be deleted' + USING ERRCODE = 'check_violation'; + END IF; + IF NEW.issuer_id IS DISTINCT FROM OLD.issuer_id + OR NEW.counter_version <> OLD.counter_version + 1 + OR NEW.last_issued_coverage_generation <= OLD.last_issued_coverage_generation THEN + RAISE EXCEPTION 'issuer bootstrap coverage counter CAS must advance its global domain' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION game_session_guard_issuer_bootstrap_coverage_counter_insert() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.counter_version <> 0 OR NEW.last_issued_coverage_generation <> 0 THEN + RAISE EXCEPTION 'issuer bootstrap coverage counter must start at its unissued zero state' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_gs_issuer_bootstrap_coverage_counter_initial + BEFORE INSERT ON game_session_canonical_issuer_bootstrap_coverage_counter + FOR EACH ROW EXECUTE FUNCTION game_session_guard_issuer_bootstrap_coverage_counter_insert(); +CREATE TRIGGER trg_gs_issuer_bootstrap_coverage_counter_guard + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_bootstrap_coverage_counter + FOR EACH ROW EXECUTE FUNCTION game_session_guard_issuer_bootstrap_coverage_counter(); +-- [jooq ignore stop] + +COMMENT ON TABLE game_session_canonical_issuer_bootstrap_partition_proof IS + 'Exact per-partition physical readback proof for local initial issuer bootstrap; not tenant barrier state or admission authority.'; +COMMENT ON TABLE game_session_canonical_issuer_installed_anchor IS + 'Unique local initial installed issuer coverage/layout anchor; distinct from issuer tenant-barrier INSTALLED or OPEN.'; diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java new file mode 100644 index 0000000000..248424f121 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java @@ -0,0 +1,911 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.sql.Connection; +import java.sql.SQLException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +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.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Actual finite SQL-and-Redis source proof for the local initial issuer anchor owner. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String OWNER_PRINCIPAL = "gamesession_coord_app"; + private static final String ISSUER_KEY_PREFIX = "session:game:index:issuer:"; + private static final BigInteger LAYOUT_VERSION = BigInteger.valueOf(3); + private static final BigInteger PARTITION_COUNT = BigInteger.valueOf(16); + private static final BigInteger PARTITION_CAPACITY = BigInteger.valueOf(32); + + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + private static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + private final List schemas = new ArrayList<>(); + private RedisClient administrator; + private RedisClient ownerClient; + private StatefulRedisConnection administratorConnection; + private RedisCommands administratorCommands; + + @BeforeEach + void setUpRedis() { + String password = UUID.randomUUID().toString(); + administrator = createRedisClient(null, null); + administratorConnection = administrator.connect(ByteArrayCodec.INSTANCE); + administratorCommands = administratorConnection.sync(); + administratorCommands.flushdb(); + administratorCommands.aclSetuser( + OWNER_PRINCIPAL, + new AclSetuserArgs() + .reset() + .on() + .addPassword(password) + .keyPattern(ISSUER_KEY_PREFIX + "*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.HLEN) + .addCommand(CommandType.HGETALL) + .addCommand(CommandType.HSET)); + ownerClient = createRedisClient(OWNER_PRINCIPAL, password); + } + + @AfterEach + void tearDown() { + if (administratorConnection != null) administratorConnection.close(); + if (ownerClient != null) ownerClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + if (administrator != null) administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + for (TestSchema schema : schemas) dropSchema(schema.schema()); + } + + @Test + void installsOnlyAfterEveryPopulatedAndEmptyPartitionHasExactPhysicalProofAndReplaysOriginal() { + Fixture fixture = fixture(PARTITION_COUNT, PARTITION_CAPACITY, 1); + String originalReservationImage = originalReservationImage(fixture.dsl()); + var current = currentState(fixture, stableIncarnation("finite")); + + CanonicalGameplayIssuerInstalledAnchor first = + owner(fixture, () -> current) + .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId()); + + assertThat(first.issuerCoverageOperationId()).isEqualTo(fixture.intent().operationId()); + assertThat(first.operationFence()).isEqualTo(fixture.intent().operationFence()); + assertThat(first.coverageFence()).isEqualTo(fixture.intent().coverageFence()); + assertThat(first.partitionProofCount()).isEqualTo(PARTITION_COUNT.longValueExact()); + assertThat(first.physicalReservationCount()).isEqualTo(1L); + assertThat(first.physicalBindingCount()).isEqualTo(1L); + CanonicalGameplayIssuerBootstrapPartitionWork originalWork = + partitionWork( + fixture, + fixture.activePartition(), + trustedIncarnation(current.incarnation())); + var physicalValue = originalWork.memberOperations().getFirst().expectedMemberValue(); + var originalReservationRow = + fixture.dsl().fetchOne( + "SELECT issuer_coverage_operation_id, issuer_coverage_operation_fence, coverage_fence," + + " inventory_snapshot_revision, inventory_revision" + + " FROM game_session_canonical_issuer_partition_reservation WHERE reservation_id = ?", + physicalValue.reservation().reservationId()); + assertThat(physicalValue.reservation().issuerCoverageOperationId()) + .isEqualTo(originalReservationRow.get("issuer_coverage_operation_id", UUID.class)) + .isNotEqualTo(physicalValue.anchor().issuerCoverageOperationId()); + assertThat(physicalValue.reservation().issuerCoverageOperationFence()) + .isEqualTo(originalReservationRow.get("issuer_coverage_operation_fence", BigDecimal.class).toBigIntegerExact()); + assertThat(physicalValue.reservation().coverageFence()) + .isEqualTo(originalReservationRow.get("coverage_fence", BigDecimal.class).toBigIntegerExact()); + assertThat(physicalValue.reservation().inventorySnapshotRevision()) + .isEqualTo(originalReservationRow.get("inventory_snapshot_revision", BigDecimal.class).toBigIntegerExact()); + assertThat(physicalValue.reservation().inventoryRevision()) + .isEqualTo(originalReservationRow.get("inventory_revision", BigDecimal.class).toBigIntegerExact()); + assertThat(physicalValue.anchor().issuerCoverageOperationId()) + .isEqualTo(first.issuerCoverageOperationId()); + assertThat(physicalValue.anchor().operationFence()).isEqualTo(first.operationFence()); + assertThat(physicalValue.anchor().coverageFence()).isEqualTo(first.coverageFence()); + assertThat(physicalValue.anchor().issuerInventorySnapshotRevision()) + .isEqualTo(first.issuerInventorySnapshotRevision()); + assertThat(fixture.dsl().fetchOne( + "SELECT count(*) AS proof_count FROM game_session_canonical_issuer_bootstrap_partition_proof") + .get("proof_count", Long.class)) + .isEqualTo(PARTITION_COUNT.longValueExact()); + assertThat(fixture.dsl().fetchOne( + "SELECT count(*) AS anchor_count FROM game_session_canonical_issuer_installed_anchor") + .get("anchor_count", Long.class)) + .isEqualTo(1L); + assertThat(fixture.dsl().fetchOne( + "SELECT count(*) AS pending_count FROM game_session_canonical_issuer_bootstrap_member_operation" + + " WHERE member_status = 'PENDING_PHYSICAL_PROOF'") + .get("pending_count", Long.class)) + .isEqualTo((long) fixture.plan().memberWorks().size()); + assertThat(fixture.dsl().fetchOne( + "SELECT last_issued_coverage_generation FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", + ISSUER) + .get("last_issued_coverage_generation", BigDecimal.class)) + .isEqualTo(new BigDecimal(first.globalCoverageGeneration())); + assertThat(fixture.dsl().fetchOne( + "SELECT state FROM game_session_canonical_issuer_layout_bootstrap_control WHERE issuer_id = ?", + ISSUER) + .get("state", String.class)) + .isEqualTo("INITIAL_BOOTSTRAP_INTENT"); + + for (BigInteger partitionId = BigInteger.ZERO; + partitionId.compareTo(PARTITION_COUNT) < 0; + partitionId = partitionId.add(BigInteger.ONE)) { + byte[] key = key(fixture, partitionId); + assertThat(administratorCommands.type(key)).isEqualTo("hash"); + assertThat(administratorCommands.pttl(key)).isEqualTo(-1L); + if (partitionId.equals(fixture.activePartition())) { + assertThat(administratorCommands.hlen(key)).isEqualTo(3L); + } else { + assertThat(administratorCommands.hlen(key)).isEqualTo(1L); + } + } + assertThat(originalReservationImage(fixture.dsl())).isEqualTo(originalReservationImage); + + byte[] exactAnchorBeforeCounterAdvance = first.exactAnchorBytes(); + String anchorStorageBeforeCounterAdvance = anchorStorageImage(fixture.dsl()); + String proofStorageBeforeCounterAdvance = proofStorageImage(fixture.dsl()); + BigInteger laterCoverageGeneration = first.globalCoverageGeneration().add(BigInteger.valueOf(4)); + fixture.dsl().execute( + "UPDATE game_session_canonical_issuer_bootstrap_coverage_counter" + + " SET last_issued_coverage_generation = ?, counter_version = 2" + + " WHERE issuer_id = ? AND last_issued_coverage_generation = ? AND counter_version = 1", + laterCoverageGeneration, + ISSUER, + first.globalCoverageGeneration()); + assertThat(originalReservationImage(fixture.dsl())).isEqualTo(originalReservationImage); + assertThat(anchorStorageImage(fixture.dsl())).isEqualTo(anchorStorageBeforeCounterAdvance); + assertThat(proofStorageImage(fixture.dsl())).isEqualTo(proofStorageBeforeCounterAdvance); + + // Discard the first reply and replay the same operation identity; it must reuse the pointer. + CanonicalGameplayIssuerInstalledAnchor replay = + owner(fixture, () -> current) + .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId()); + assertThat(replay.exactAnchorBytes()).containsExactly(first.exactAnchorBytes()); + assertThat(replay.exactAnchorBytes()).containsExactly(exactAnchorBeforeCounterAdvance); + assertThat(replay.globalCoverageGeneration()).isEqualTo(first.globalCoverageGeneration()); + assertThat(fixture.dsl().fetchOne( + "SELECT counter_version FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", + ISSUER) + .get("counter_version", Long.class)) + .isEqualTo(2L); + assertThat(fixture.dsl().fetchOne( + "SELECT last_issued_coverage_generation FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", + ISSUER) + .get("last_issued_coverage_generation", BigDecimal.class)) + .isEqualTo(new BigDecimal(laterCoverageGeneration)); + assertThat(originalReservationImage(fixture.dsl())).isEqualTo(originalReservationImage); + } + + @Test + void installedReplayRefusesMissingPartitionWithoutRebuildingOrAllocatingAnotherGeneration() { + Fixture fixture = fixture(BigInteger.valueOf(4), PARTITION_CAPACITY, 1); + var current = currentState(fixture, stableIncarnation("missing-installed")); + CanonicalGameplayIssuerInstalledAnchor installed = + owner(fixture, () -> current) + .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId()); + byte[] missingKey = key(fixture, fixture.activePartition()); + administratorCommands.del(missingKey); + + assertThatThrownBy( + () -> + owner(fixture, () -> current) + .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId())) + .isInstanceOf(IllegalStateException.class); + assertThat(administratorCommands.type(missingKey)).isEqualTo("none"); + assertThat(fixture.dsl().fetchOne( + "SELECT global_coverage_generation FROM game_session_canonical_issuer_installed_anchor WHERE issuer_id = ?", + ISSUER) + .get("global_coverage_generation", BigDecimal.class)) + .isEqualTo(new BigDecimal(installed.globalCoverageGeneration())); + assertThat(fixture.dsl().fetchOne( + "SELECT counter_version FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", + ISSUER) + .get("counter_version", Long.class)) + .isEqualTo(1L); + } + + @Test + void movedAccountCheckpointOrStorageIncarnationLeavesNoCoverageGenerationOrPointer() { + Fixture sourceFixture = fixture(PARTITION_COUNT, PARTITION_CAPACITY, 1); + var sourceIncarnation = stableIncarnation("source-movement"); + var changedCheckpoint = checkpointShape(BigInteger.valueOf(8)); + AtomicInteger sourceCalls = new AtomicInteger(); + var changedAfterReadback = + () -> + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + sourceCalls.incrementAndGet() == 5 + ? changedCheckpoint + : sourceFixture.intent().sourceCheckpoint(), + sourceIncarnation); + assertThatThrownBy( + () -> + owner(sourceFixture, changedAfterReadback) + .completeInitialBootstrap( + sourceFixture.intent().operationId(), sourceFixture.requestId())) + .isInstanceOf(IllegalStateException.class); + assertNoInstalledCoverage(sourceFixture); + assertThat(fixtureProofCount(sourceFixture)).isZero(); + + Fixture incarnationFixture = fixture(PARTITION_COUNT, PARTITION_CAPACITY, 1); + var initialIncarnation = stableIncarnation("incarnation-movement"); + var changedIncarnation = changedIncarnation(initialIncarnation); + AtomicInteger incarnationCalls = new AtomicInteger(); + var changedIncarnationAfterReadback = + () -> + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + incarnationFixture.intent().sourceCheckpoint(), + incarnationCalls.incrementAndGet() == 5 ? changedIncarnation : initialIncarnation); + assertThatThrownBy( + () -> + owner(incarnationFixture, changedIncarnationAfterReadback) + .completeInitialBootstrap( + incarnationFixture.intent().operationId(), incarnationFixture.requestId())) + .isInstanceOf(IllegalStateException.class); + assertNoInstalledCoverage(incarnationFixture); + assertThat(fixtureProofCount(incarnationFixture)).isZero(); + } + + @Test + void absentOrMalformedPartitionAndLegacyValueDoNotIssueCoverageGeneration() { + Fixture fixture = fixture(BigInteger.ONE, PARTITION_CAPACITY, 1); + byte[] partitionKey = key(fixture, BigInteger.ZERO); + administratorCommands.set(partitionKey, ascii("retained-wrong-type")); + var current = currentState(fixture, stableIncarnation("wrong-type")); + + assertThatThrownBy( + () -> + owner(fixture, () -> current) + .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId())) + .isInstanceOf(IllegalStateException.class); + assertNoInstalledCoverage(fixture); + assertThat(administratorCommands.type(partitionKey)).isEqualTo("string"); + assertThat(fixtureProofCount(fixture)).isZero(); + } + + @Test + void originalReservationAndNewAnchorTupleConflictsRefuseTheSamePhysicalBinding() { + assertPhysicalTupleConflict(false); + assertPhysicalTupleConflict(true); + } + + @Test + void finitePlanCapacityConflictDoesNotCreateAnyPartitionOrCoverageGeneration() { + Fixture fixture = fixture(BigInteger.ONE, BigInteger.ONE, 2); + assertThat(fixture.plan().state()) + .isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.BLOCKED); + var current = currentState(fixture, stableIncarnation("capacity-conflict")); + + assertThatThrownBy( + () -> + owner(fixture, () -> current) + .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("blockers"); + assertNoInstalledCoverage(fixture); + assertThat(fixture.dsl().fetchOne( + "SELECT count(*) AS proof_count FROM game_session_canonical_issuer_bootstrap_partition_proof") + .get("proof_count", Long.class)) + .isZero(); + assertThat(administratorCommands.type(key(fixture, BigInteger.ZERO))).isEqualTo("none"); + } + + private void assertPhysicalTupleConflict(boolean wrongNewAnchor) { + Fixture fixture = fixture(BigInteger.ONE, PARTITION_CAPACITY, 1); + var incarnation = stableIncarnation(wrongNewAnchor ? "wrong-anchor" : "wrong-original"); + CanonicalGameplayIssuerBootstrapPartitionWork work = + partitionWork(fixture, BigInteger.ZERO, trustedIncarnation(incarnation)); + var current = currentState(fixture, incarnation); + partitionRedisOwner(fixture, () -> current).buildAndRead(work); + var operation = work.memberOperations().getFirst(); + var expected = operation.expectedMemberValue(); + CanonicalGameplayIssuerMemberV2Value changed = + wrongNewAnchor + ? new CanonicalGameplayIssuerMemberV2Value( + expected.owner(), + expected.bindingGeneration(), + expected.reservation(), + new CanonicalGameplayIssuerMemberV2Value.Anchor( + UUID.randomUUID(), + expected.anchor().operationFence(), + expected.anchor().coverageFence(), + expected.anchor().issuerInventorySnapshotRevision()), + expected.memberOperation(), + expected.issuerControlEpoch(), + expected.layoutDescriptor(), + expected.sourceCheckpoint(), + expected.incarnation()) + : new CanonicalGameplayIssuerMemberV2Value( + expected.owner(), + expected.bindingGeneration(), + changedOriginalReservation(expected.reservation()), + expected.anchor(), + expected.memberOperation(), + expected.issuerControlEpoch(), + expected.layoutDescriptor(), + expected.sourceCheckpoint(), + expected.incarnation()); + byte[] changedBytes = CanonicalGameplayIssuerMemberV2Codec.encode(changed); + byte[] key = key(fixture, BigInteger.ZERO); + administratorCommands.hset( + key, + expected.owner().bindingRef().bytes(), + changedBytes); + administratorCommands.hset( + key, + ascii(CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + expected.reservation().reservationId())), + changedBytes); + + assertThatThrownBy( + () -> + owner(fixture, () -> current) + .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId())) + .isInstanceOf(IllegalStateException.class); + assertNoInstalledCoverage(fixture); + assertThat(fixtureProofCount(fixture)).isZero(); + } + + private Fixture fixture(BigInteger partitions, BigInteger capacity, int activeBindingCount) { + TestSchema schema = newTestSchemaAtVersion("gs_issuer_coverage_", "1030"); + schemas.add(schema); + establishActualLegacyDisposition(schema.dsl()); + CanonicalGameplayBindingIdentity active = identity(partitions, capacity, "coverage-active"); + seedActiveSource(schema.dsl(), active); + BigInteger activePartition = active.bindingRef().partitionId(partitions); + for (int index = 1; index < activeBindingCount; index++) { + CanonicalGameplayBindingIdentity samePartition = + identityInPartition(partitions, capacity, activePartition, index); + seedActiveSource(schema.dsl(), samePartition); + } + UUID requestId = UUID.randomUUID(); + var checkpoint = sourceCheckpoint(BigInteger.valueOf(7)); + var intent = + new CanonicalGameplayIssuerLayoutBootstrapRepository(schema.dsl()) + .beginInitialBootstrapIntent(requestId, descriptor(partitions, capacity), checkpoint); + migrateRemaining(schema); + var plan = + new CanonicalGameplayIssuerPartitionBuildRepository(schema.dsl()) + .prepareInitialBuildPlan(intent.operationId(), requestId); + return new Fixture(schema, activePartition, intent, requestId, checkpoint, plan); + } + + private CanonicalGameplayIssuerBootstrapCoverageOwner owner( + Fixture fixture, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource source) { + return new CanonicalGameplayIssuerBootstrapCoverageOwner( + fixture.dsl(), partitionRedisOwner(fixture, source), source); + } + + private CanonicalGameplayIssuerBootstrapPartitionRedisOwner partitionRedisOwner( + Fixture fixture, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource source) { + return new CanonicalGameplayIssuerBootstrapPartitionRedisOwner( + ownerClient, + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution())), + source); + } + + private CanonicalGameplayIssuerBootstrapPartitionWork partitionWork( + Fixture fixture, + BigInteger partitionId, + CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation incarnation) { + return new CanonicalGameplayIssuerBootstrapMemberOperationRepository(fixture.dsl()) + .preparePartitionWork( + fixture.intent().operationId(), + fixture.requestId(), + partitionId, + fixture.currentAccountCheckpoint(), + incarnation); + } + + private CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState( + Fixture fixture, CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation) { + return new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + fixture.intent().sourceCheckpoint(), incarnation); + } + + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor + descriptor(BigInteger partitions, BigInteger capacity) { + String exact = + "issuer-layout-descriptor/v1|" + + ISSUER + + "|" + + LAYOUT_VERSION + + "|" + + partitions + + "|" + + capacity + + "|" + + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY; + return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor( + ISSUER, + LAYOUT_VERSION, + partitions, + capacity, + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY, + exact.getBytes(StandardCharsets.UTF_8)); + } + + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + sourceCheckpoint(BigInteger generation) { + long sequence = generation.longValueExact() - 1; + var event = + AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + UUID.randomUUID().toString(), + UUID.randomUUID().toString(), + AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + ISSUER, + Long.toString(sequence), + ISSUER, + generation.toString(), + generation.toString(), + "ISSUER_SECURITY_CHANGE")); + byte[] bytes = event.canonicalJsonUtf8(); + return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint( + ISSUER, generation, bytes, bytes); + } + + private static CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint + checkpointShape(BigInteger generation) { + var trusted = sourceCheckpoint(generation); + byte[] checkpoint = trusted.checkpointBytes(); + byte[] event = trusted.latestEventBytes(); + return new CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint( + trusted.issuerId(), + trusted.issuerAuthGeneration(), + checkpoint, + CanonicalGameplayIssuerMemberV2Codec.sha256(checkpoint), + event, + CanonicalGameplayIssuerMemberV2Codec.sha256(event)); + } + + private static CanonicalGameplayIssuerMemberV2Value.Incarnation + stableIncarnation(String seed) { + String digest = digest(seed.getBytes(StandardCharsets.UTF_8)); + return new CanonicalGameplayIssuerMemberV2Value.Incarnation( + "controlled-attestor-" + seed, + digest, + deploymentEvidence(seed, digest), + digest, + digest); + } + + private static CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation + trustedIncarnation(CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation) { + return new CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation( + incarnation.attestorBinding(), + incarnation.acceptedAttestationDigest(), + incarnation.targetDeploymentEvidence(), + incarnation.coordOpsRoAclDigest(), + incarnation.coordRedisConfigObservedDigest()); + } + + private static CanonicalGameplayIssuerMemberV2Value.Incarnation changedIncarnation( + CanonicalGameplayIssuerMemberV2Value.Incarnation current) { + return new CanonicalGameplayIssuerMemberV2Value.Incarnation( + current.attestorBinding() + "-changed", + current.acceptedAttestationDigest(), + current.targetDeploymentEvidence(), + current.coordOpsRoAclDigest(), + current.coordRedisConfigObservedDigest()); + } + + private static CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + deploymentEvidence(String seed, String digest) { + return new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "controlled-deployment-" + seed, + "deployment-generation-" + seed, + List.of("controlled-node-" + seed), + "controlled-redis-build-" + seed, + "controlled-lua-registry-" + seed, + digest, + "READY", + "boot-" + seed, + "startup-" + seed, + "storage-" + seed, + "aof-" + seed); + } + + private static CanonicalIssuerPartitionReservation changedOriginalReservation( + CanonicalIssuerPartitionReservation original) { + return new CanonicalIssuerPartitionReservation( + original.reservationId(), + original.owner(), + original.bindingGeneration(), + original.transitionId(), + original.partitionId(), + original.lifecycle(), + original.reservationFence(), + UUID.randomUUID(), + original.issuerCoverageOperationFence(), + original.coverageFence(), + original.inventorySnapshotRevision(), + original.inventoryRevision()); + } + + private static CanonicalGameplayBindingIdentity identity( + BigInteger partitions, BigInteger capacity, String seed) { + return new CanonicalGameplayBindingIdentity( + UUID.nameUUIDFromBytes((seed + "-account").getBytes(StandardCharsets.UTF_8)), + UUID.nameUUIDFromBytes((seed + "-tenant").getBytes(StandardCharsets.UTF_8)), + UUID.nameUUIDFromBytes((seed + "-namespace").getBytes(StandardCharsets.UTF_8)), + UUID.nameUUIDFromBytes((seed + "-character").getBytes(StandardCharsets.UTF_8)), + "SHARED", + UUID.nameUUIDFromBytes((seed + "-game").getBytes(StandardCharsets.UTF_8)), + 90_000L + Math.abs((long) seed.hashCode()), + UUID.nameUUIDFromBytes((seed + "-session").getBytes(StandardCharsets.UTF_8)).toString(), + UUID.nameUUIDFromBytes((seed + "-region").getBytes(StandardCharsets.UTF_8)), + BigInteger.valueOf(12), + ISSUER, + BigInteger.valueOf(7), + LAYOUT_VERSION, + partitions, + capacity); + } + + private static CanonicalGameplayBindingIdentity identityInPartition( + BigInteger partitions, BigInteger capacity, BigInteger partitionId, int seed) { + for (int candidate = 0; candidate < 100_000; candidate++) { + CanonicalGameplayBindingIdentity identity = + identity(partitions, capacity, "coverage-active-" + seed + "-" + candidate); + if (identity.bindingRef().partitionId(partitions).equals(partitionId)) return identity; + } + throw new IllegalStateException("Could not create a second reservation in the target partition"); + } + + private static void seedActiveSource( + DSLContext dsl, CanonicalGameplayBindingIdentity identity) { + byte[] bindingRef = identity.bindingRef().bytes(); + BigInteger partitionId = identity.bindingRef().partitionId(identity.issuerIndexPartitionCount()); + UUID accountIndexFence = UUID.randomUUID(); + UUID reservationId = UUID.randomUUID(); + UUID transitionId = UUID.randomUUID(); + UUID reservationFence = UUID.randomUUID(); + UUID originalCoverageOperationId = UUID.randomUUID(); + dsl.execute( + "UPDATE game_session_canonical_binding_inventory_clock SET inventory_revision = 8" + + " WHERE singleton_id = 1"); + dsl.execute( + "INSERT INTO game_session_canonical_binding_generation" + + " (tenant_id, playable_state_namespace_id, character_id, last_issued_generation)" + + " VALUES (?, ?, ?, 5)", + identity.tenantId(), + identity.playableStateNamespaceId(), + identity.characterId()); + dsl.execute( + "INSERT INTO game_session_canonical_gameplay_binding_inventory" + + " (binding_ref, account_id, tenant_id, playable_state_namespace_id, character_id," + + " playable_state_scope, game_instance_id, runtime_game_instance_id, session_id," + + " binding_generation, region_id, region_epoch, issuer_id, issuer_auth_generation," + + " issuer_index_layout_version, issuer_index_partition_count," + + " issuer_index_partition_capacity, issuer_partition_id, account_index_fence," + + " issuer_reservation_id, transition_id, lifecycle, account_index_state," + + " issuer_index_state, inventory_revision)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 5, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + + " 'ACTIVE', 'ACKNOWLEDGED', 'ACKNOWLEDGED', 8)", + bindingRef, + identity.accountId(), + identity.tenantId(), + identity.playableStateNamespaceId(), + identity.characterId(), + identity.playableStateScope(), + identity.gameInstanceId(), + identity.runtimeGameInstanceId(), + identity.sessionId(), + identity.regionId(), + new BigDecimal(identity.regionEpoch()), + identity.issuerId(), + new BigDecimal(identity.issuerAuthGeneration()), + new BigDecimal(identity.issuerIndexLayoutVersion()), + new BigDecimal(identity.issuerIndexPartitionCount()), + new BigDecimal(identity.issuerIndexPartitionCapacity()), + new BigDecimal(partitionId), + accountIndexFence, + reservationId, + transitionId); + dsl.execute( + "INSERT INTO game_session_canonical_issuer_partition_reservation" + + " (reservation_id, binding_ref, account_id, tenant_id, game_instance_id," + + " runtime_game_instance_id, session_id, binding_generation, transition_id, issuer_id," + + " issuer_auth_generation, playable_state_namespace_id, character_id," + + " playable_state_scope, region_id, region_epoch, partition_id," + + " issuer_index_layout_version, issuer_index_partition_count," + + " issuer_index_partition_capacity, lifecycle, reservation_fence," + + " issuer_coverage_operation_id, issuer_coverage_operation_fence, coverage_fence," + + " inventory_snapshot_revision, inventory_revision)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, 5, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + + " 'BOUND', ?, ?, 1, 1, 7, 8)", + reservationId, + bindingRef, + identity.accountId(), + identity.tenantId(), + identity.gameInstanceId(), + identity.runtimeGameInstanceId(), + identity.sessionId(), + transitionId, + identity.issuerId(), + new BigDecimal(identity.issuerAuthGeneration()), + identity.playableStateNamespaceId(), + identity.characterId(), + identity.playableStateScope(), + identity.regionId(), + new BigDecimal(identity.regionEpoch()), + new BigDecimal(partitionId), + new BigDecimal(identity.issuerIndexLayoutVersion()), + new BigDecimal(identity.issuerIndexPartitionCount()), + new BigDecimal(identity.issuerIndexPartitionCapacity()), + reservationFence, + originalCoverageOperationId); + dsl.execute( + "INSERT INTO game_session_canonical_binding_transition" + + " (transition_id, tenant_id, playable_state_namespace_id, character_id," + + " expected_prior_binding_ref, expected_prior_binding_generation, candidate_binding_ref," + + " candidate_binding_generation, candidate_account_index_fence, issuer_reservation_id," + + " status, inventory_revision)" + + " VALUES (?, ?, ?, ?, NULL, NULL, ?, 5, ?, ?, 'COMMITTED', 8)", + transitionId, + identity.tenantId(), + identity.playableStateNamespaceId(), + identity.characterId(), + bindingRef, + accountIndexFence, + reservationId); + } + + private static String originalReservationImage(DSLContext dsl) { + return dsl.fetchOne( + "SELECT coalesce(jsonb_agg(to_jsonb(r) ORDER BY reservation_id), '[]'::jsonb)::text AS image " + + "FROM game_session_canonical_issuer_partition_reservation r") + .get("image", String.class); + } + + private static String anchorStorageImage(DSLContext dsl) { + return dsl.fetchOne( + "SELECT encode(exact_anchor_bytes, 'base64') || ':' || exact_anchor_digest || ':'" + + " || global_coverage_generation::text AS image" + + " FROM game_session_canonical_issuer_installed_anchor WHERE issuer_id = ?", + ISSUER) + .get("image", String.class); + } + + private static String proofStorageImage(DSLContext dsl) { + return dsl.fetchOne( + "SELECT coalesce(string_agg(partition_id::text || ':'" + + " || encode(exact_metadata_bytes, 'base64') || ':'" + + " || encode(exact_physical_field_set_bytes, 'base64') || ':'" + + " || exact_physical_field_set_digest, '|' ORDER BY partition_id), '') AS image" + + " FROM game_session_canonical_issuer_bootstrap_partition_proof") + .get("image", String.class); + } + + private static long fixtureProofCount(Fixture fixture) { + return fixture.dsl() + .fetchOne( + "SELECT count(*) AS proof_count FROM game_session_canonical_issuer_bootstrap_partition_proof") + .get("proof_count", Long.class); + } + + private static void assertNoInstalledCoverage(Fixture fixture) { + assertThat(fixture.dsl().fetchOne( + "SELECT count(*) AS anchor_count FROM game_session_canonical_issuer_installed_anchor") + .get("anchor_count", Long.class)) + .isZero(); + assertThat(fixture.dsl().fetchOne( + "SELECT count(*) AS counter_count FROM game_session_canonical_issuer_bootstrap_coverage_counter") + .get("counter_count", Long.class)) + .isZero(); + } + + private static byte[] key(Fixture fixture, BigInteger partitionId) { + return CanonicalGameplayIssuerRedisKeys.forPartition( + fixture.intent().layoutDescriptor(), partitionId) + .getBytes(StandardCharsets.US_ASCII); + } + + private void establishActualLegacyDisposition(DSLContext dsl) { + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); + UUID cohortId = UUID.randomUUID(); + UUID writerFence = UUID.randomUUID(); + var storageIdentity = + new CanonicalGameplayLegacyMigrationStorageIdentity( + "controlled-cluster-uid", + "controlled-namespace-uid", + "controlled-producer-pod-uid", + "controlled-container-id", + "controlled-node-uid", + "123456789", + 42L, + "controlled-postgres-volume-uid", + "controlled-redis-run-id", + "controlled-redis-volume-uid"); + var fencedCohort = + new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { + @Override public UUID cohortId() { return cohortId; } + @Override public UUID legacyWriterFence() { return writerFence; } + @Override public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + return storageIdentity; + } + @Override public void requireStillFenced( + CanonicalGameplayLegacyMigrationStorageIdentity expected) { + if (!storageIdentity.equals(expected)) { + throw new IllegalStateException("Controlled test storage identity changed"); + } + } + }; + new CanonicalGameplayLegacyMigrationOwner( + migration, + inventory, + () -> fencedCohort, + ignored -> + new CanonicalGameplayLegacyMigrationSourceSnapshot( + EnumSet.of( + Family.TENANT_SESSION_CONTEXT, + Family.SESSION_ALIAS_CONTEXT, + Family.GAMEPLAY_IDENTITY_CONTEXT, + Family.GAMEPLAY_NAME_CONTEXT, + Family.MOVEMENT_EFFECT, + Family.DURABLE_EFFECT), + List.of()), + new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { + @Override public void rebuildExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + CanonicalGameplayLegacyMigrationSourceSnapshot source, + net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventorySnapshot + canonical) { + assertThat(canonical.bindings()).isEmpty(); + assertThat(canonical.reservations()).isEmpty(); + } + @Override public CanonicalGameplayLegacyMigrationReadback readBackExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventorySnapshot + canonical) { + assertThat(canonical.bindings()).isEmpty(); + return new CanonicalGameplayLegacyMigrationReadback( + List.of(), List.of(), List.of(), List.of()); + } + }) + .migrate(); + } + + private TestSchema newTestSchemaAtVersion(String prefix, String version) { + String schema = prefix + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion(version)) + .load() + .migrate(); + return new TestSchema(schema, dataSource, DSL.using(dataSource, SQLDialect.POSTGRES)); + } + + private static void migrateRemaining(TestSchema schema) { + Flyway.configure() + .dataSource(schema.dataSource()) + .schemas(schema.schema()) + .defaultSchema(schema.schema()) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + } + + private DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + String jdbcUrl = POSTGRES.getJdbcUrl(); + dataSource.setUrl(jdbcUrl + (jdbcUrl.contains("?") ? "&" : "?") + "currentSchema=" + schema); + dataSource.setUsername(POSTGRES.getUsername()); + dataSource.setPassword(POSTGRES.getPassword()); + return dataSource; + } + + private void dropSchema(String schema) { + try (Connection connection = dataSource("public").getConnection()) { + DSL.using(connection, SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } catch (SQLException failure) { + throw new IllegalStateException("Could not drop the owned issuer coverage test schema", failure); + } + } + + private static RedisClient createRedisClient(String username, String password) { + RedisURI.Builder builder = RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(6379)); + if (username != null) builder.withAuthentication(username, password); + RedisURI uri = builder.build(); + uri.setTimeout(Duration.ofSeconds(5)); + RedisClient client = RedisClient.create(uri); + client.setOptions( + ClientOptions.builder() + .autoReconnect(false) + .protocolVersion(io.lettuce.core.protocol.ProtocolVersion.RESP2) + .build()); + return client; + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private record Fixture( + TestSchema schema, + BigInteger activePartition, + CanonicalGameplayIssuerLayoutBootstrapIntent intent, + UUID requestId, + CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + currentAccountCheckpoint, + CanonicalGameplayIssuerPartitionBuildPlan plan) { + DSLContext dsl() { return schema.dsl(); } + } + + private record TestSchema(String schema, DriverManagerDataSource dataSource, DSLContext dsl) {} +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java index 2c707fcbea..4bfd924115 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java @@ -153,13 +153,19 @@ void buildsCompletePopulatedPartitionAndCountsReleasedOnlyAsRetainedEvidence() { .findFirst() .orElseThrow(); var value = active.expectedMemberValue(); - assertThat(value.reservation().issuerCoverageOperationId()) - .isNotEqualTo(value.anchor().issuerCoverageOperationId()); - assertThat(value.reservation().issuerCoverageOperationFence()) - .isNotEqualTo(value.anchor().operationFence()); - assertThat(value.reservation().coverageFence()).isNotEqualTo(value.anchor().coverageFence()); - assertThat(value.reservation().inventorySnapshotRevision()) - .isNotEqualTo(value.anchor().issuerInventorySnapshotRevision()); + var originalReservationCoverageTuple = + List.of( + value.reservation().issuerCoverageOperationId(), + value.reservation().issuerCoverageOperationFence(), + value.reservation().coverageFence(), + value.reservation().inventorySnapshotRevision()); + var bootstrapAnchorTuple = + List.of( + value.anchor().issuerCoverageOperationId(), + value.anchor().operationFence(), + value.anchor().coverageFence(), + value.anchor().issuerInventorySnapshotRevision()); + assertThat(originalReservationCoverageTuple).isNotEqualTo(bootstrapAnchorTuple); var firstOwner = owner(work, currentState(fixture, work)); var first = firstOwner.buildAndRead(work); @@ -283,7 +289,8 @@ void malformedLegacyForeignAndExpiringPhysicalStateRefuseWithoutMutation() { byte[] legacyV1 = "{\"schemaVersion\":1}".getBytes(StandardCharsets.UTF_8); administratorCommands.hset(populatedKey, bindingField, legacyV1); - assertThatThrownBy(() -> owner(populated, currentState(fixture, populated)).buildAndRead(populated)) + assertThatThrownBy( + () -> owner(populated, currentState(fixture, populated)).buildAndRead(populated)) .isInstanceOf(IllegalStateException.class); assertThat(administratorCommands.hget(populatedKey, bindingField)).containsExactly(legacyV1); assertThat(administratorCommands.hlen(populatedKey)).isEqualTo(1L); @@ -294,12 +301,14 @@ void malformedLegacyForeignAndExpiringPhysicalStateRefuseWithoutMutation() { byte[] foreignField = ascii("unrelated-operator-field"); byte[] foreignValue = ascii("retained-source"); administratorCommands.hset(foreignKey, foreignField, foreignValue); - assertThatThrownBy(() -> owner(foreignWork, currentState(fixture, foreignWork)).buildAndRead(foreignWork)) + assertThatThrownBy( + () -> owner(foreignWork, currentState(fixture, foreignWork)).buildAndRead(foreignWork)) .isInstanceOf(IllegalStateException.class); assertThat(administratorCommands.hlen(foreignKey)).isEqualTo(1L); assertThat(administratorCommands.hget(foreignKey, foreignField)).containsExactly(foreignValue); - BigInteger expiringPartition = populated.partitionId().add(BigInteger.valueOf(3)).mod(PARTITION_COUNT); + BigInteger expiringPartition = + populated.partitionId().add(BigInteger.valueOf(3)).mod(PARTITION_COUNT); var expiringWork = partitionWork(fixture, expiringPartition); byte[] expiringKey = key(fixture, expiringPartition); byte[] expiringField = ascii("foreign-ttl-field"); @@ -308,10 +317,13 @@ void malformedLegacyForeignAndExpiringPhysicalStateRefuseWithoutMutation() { administratorCommands.pexpire(expiringKey, 60_000); long ttlBefore = administratorCommands.pttl(expiringKey); - assertThatThrownBy(() -> owner(expiringWork, currentState(fixture, expiringWork)).buildAndRead(expiringWork)) + assertThatThrownBy( + () -> + owner(expiringWork, currentState(fixture, expiringWork)).buildAndRead(expiringWork)) .isInstanceOf(IllegalStateException.class); assertThat(administratorCommands.pttl(expiringKey)).isPositive().isLessThanOrEqualTo(ttlBefore); - assertThat(administratorCommands.hget(expiringKey, expiringField)).containsExactly(expiringValue); + assertThat(administratorCommands.hget(expiringKey, expiringField)) + .containsExactly(expiringValue); BigInteger wrongTypePartition = populated.partitionId().add(BigInteger.valueOf(4)).mod(PARTITION_COUNT); @@ -320,7 +332,9 @@ void malformedLegacyForeignAndExpiringPhysicalStateRefuseWithoutMutation() { byte[] wrongTypeValue = ascii("foreign-persistent-string"); administratorCommands.set(wrongTypeKey, wrongTypeValue); assertThatThrownBy( - () -> owner(wrongTypeWork, currentState(fixture, wrongTypeWork)).buildAndRead(wrongTypeWork)) + () -> + owner(wrongTypeWork, currentState(fixture, wrongTypeWork)) + .buildAndRead(wrongTypeWork)) .isInstanceOf(IllegalStateException.class); assertThat(administratorCommands.type(wrongTypeKey)).isEqualTo("string"); assertThat(administratorCommands.get(wrongTypeKey)).containsExactly(wrongTypeValue); @@ -398,7 +412,8 @@ void changedFreshCheckpointOrIncarnationBeforeAndAfterRedisLeavesNoReadbackCapab } @Test - void retainedCommitAfterLostReplyReplaysFromFreshSqlWorkAndSeparatePhysicalReadback() throws Exception { + void retainedCommitAfterLostReplyReplaysFromFreshSqlWorkAndSeparatePhysicalReadback() + throws Exception { Fixture fixture = fixture(false); CanonicalGameplayIssuerBootstrapPartitionWork work = partitionWork(fixture, fixture.partitionId()); @@ -410,14 +425,12 @@ void retainedCommitAfterLostReplyReplaysFromFreshSqlWorkAndSeparatePhysicalReadb // The test deliberately discards this post-commit script reply to model a lost reply/crash. administratorCommands.evalsha( - scriptSha, - ScriptOutputType.INTEGER, - new byte[][] {key}, - scriptArguments(work, physical)); + scriptSha, ScriptOutputType.INTEGER, new byte[][] {key}, scriptArguments(work, physical)); CanonicalGameplayIssuerBootstrapPartitionWork restartedWork = partitionWork(fixture, work.partitionId()); - var readback = owner(restartedWork, currentState(fixture, restartedWork)).buildAndRead(restartedWork); + var readback = + owner(restartedWork, currentState(fixture, restartedWork)).buildAndRead(restartedWork); assertThat(readback.physicalFieldCount()).isEqualTo(3); assertThat(readback.physicalCountedCapacityCount()).isEqualTo(1); assertThat(statusesRemainPending(fixture.dsl())).isTrue(); @@ -432,8 +445,7 @@ void deliberatelyLowerCapacityLuaArgumentsRefuseWithoutChangingOwnedHashImage() .isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED); assertThat(work.memberOperations()).hasSize(2); assertThat(work.memberOperations()) - .allSatisfy( - operation -> assertThat(operation.countsTowardCapacity()).isTrue()); + .allSatisfy(operation -> assertThat(operation.countsTowardCapacity()).isTrue()); var physical = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.expectedFields(work); var catalog = RedisScriptCatalog.fromContributions( @@ -494,7 +506,8 @@ private Fixture fixture(boolean includeReleasedReservation, int activeBindingCou seedSamePartitionActiveBinding(testSchema.dsl(), partitionId); assertThat(samePartition.bindingRef().partitionId(PARTITION_COUNT)).isEqualTo(partitionId); } - if (includeReleasedReservation) insertReleasedReservation(testSchema.dsl(), active, partitionId); + if (includeReleasedReservation) + insertReleasedReservation(testSchema.dsl(), active, partitionId); UUID requestId = UUID.randomUUID(); var source = sourceCheckpoint(BigInteger.valueOf(7)); @@ -747,7 +760,9 @@ private void insertReleasedReservation( UUID originalCoverageOperationId = UUID.randomUUID(); byte[] bindingRef = CanonicalGameplayBindingRef.of( - template.tenantId().toString(), template.gameInstanceId().toString(), sessionId.toString()) + template.tenantId().toString(), + template.gameInstanceId().toString(), + sessionId.toString()) .bytes(); dsl.execute( "INSERT INTO game_session_canonical_issuer_partition_reservation" @@ -792,11 +807,13 @@ private static UUID sessionUuidForPartition( ("physical-release-session-" + candidate).getBytes(StandardCharsets.UTF_8)); byte[] ref = CanonicalGameplayBindingRef.of( - template.tenantId().toString(), template.gameInstanceId().toString(), session.toString()) + template.tenantId().toString(), + template.gameInstanceId().toString(), + session.toString()) .bytes(); if (CanonicalGameplayBindingRef.fromExactBytes(ref) - .partitionId(PARTITION_COUNT) - .equals(targetPartition) + .partitionId(PARTITION_COUNT) + .equals(targetPartition) && !session.toString().equals(template.sessionId())) { return session; } @@ -838,7 +855,8 @@ private static byte[] lowerCapacityJson(byte[] exactJson) { String fullCapacity = "\"partitionCapacity\":\"" + PARTITION_CAPACITY + "\""; String reducedCapacity = "\"partitionCapacity\":\"1\""; if (!original.contains(fullCapacity)) { - throw new IllegalStateException("Controlled physical input has no exact partition capacity field"); + throw new IllegalStateException( + "Controlled physical input has no exact partition capacity field"); } return original.replace(fullCapacity, reducedCapacity).getBytes(StandardCharsets.UTF_8); } @@ -874,7 +892,8 @@ private static CanonicalGameplayBindingIdentity seedSamePartitionActiveBinding( private static void insertAdditionalActiveSource( DSLContext dsl, CanonicalGameplayBindingIdentity identity) { byte[] bindingRef = identity.bindingRef().bytes(); - BigInteger partitionId = identity.bindingRef().partitionId(identity.issuerIndexPartitionCount()); + BigInteger partitionId = + identity.bindingRef().partitionId(identity.issuerIndexPartitionCount()); UUID accountIndexFence = UUID.randomUUID(); UUID reservationId = UUID.randomUUID(); UUID transitionId = UUID.randomUUID(); @@ -971,15 +990,17 @@ private static void insertAdditionalActiveSource( } private static boolean statusesRemainPending(DSLContext dsl) { - Long operations = - dsl.fetchOne("SELECT count(*) FROM game_session_canonical_issuer_bootstrap_member_operation") - .get(0, Long.class); - Long pending = + var operationsRow = + dsl.fetchOne( + "SELECT count(*) FROM game_session_canonical_issuer_bootstrap_member_operation"); + var pendingRow = dsl.fetchOne( - "SELECT count(*) FROM game_session_canonical_issuer_bootstrap_member_operation" - + " WHERE member_status = 'PENDING_PHYSICAL_PROOF'") - .get(0, Long.class); - return operations.equals(pending); + "SELECT count(*) FROM game_session_canonical_issuer_bootstrap_member_operation" + + " WHERE member_status = 'PENDING_PHYSICAL_PROOF'"); + if (operationsRow == null || pendingRow == null) return false; + Long operations = operationsRow.get(0, Long.class); + Long pending = pendingRow.get(0, Long.class); + return operations != null && pending != null && operations.equals(pending); } private static void establishActualLegacyDisposition(DSLContext dsl) { @@ -1042,7 +1063,8 @@ public void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity e public void rebuildExact( CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, CanonicalGameplayLegacyMigrationSourceSnapshot source, - net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventorySnapshot + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot canonical) { assertThat(canonical.bindings()).isEmpty(); assertThat(canonical.reservations()).isEmpty(); @@ -1051,7 +1073,8 @@ public void rebuildExact( @Override public CanonicalGameplayLegacyMigrationReadback readBackExact( CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, - net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventorySnapshot + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot canonical) { assertThat(canonical.bindings()).isEmpty(); return new CanonicalGameplayLegacyMigrationReadback( @@ -1099,9 +1122,11 @@ private DriverManagerDataSource dataSource(String schema) { private void dropSchema(String schema) { try (Connection connection = dataSource("public").getConnection()) { - DSL.using(connection, SQLDialect.POSTGRES).execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + DSL.using(connection, SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); } catch (SQLException failure) { - throw new IllegalStateException("Could not drop the owned issuer physical test schema", failure); + throw new IllegalStateException( + "Could not drop the owned issuer physical test schema", failure); } } @@ -1112,13 +1137,17 @@ private static RedisClient createRedisClient(String username, String password) { uri.setTimeout(Duration.ofSeconds(5)); RedisClient client = RedisClient.create(uri); client.setOptions( - ClientOptions.builder().autoReconnect(false).protocolVersion(io.lettuce.core.protocol.ProtocolVersion.RESP2).build()); + ClientOptions.builder() + .autoReconnect(false) + .protocolVersion(io.lettuce.core.protocol.ProtocolVersion.RESP2) + .build()); return client; } private static String digest(byte[] bytes) { try { - return "sha256:" + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); } catch (java.security.NoSuchAlgorithmException impossible) { throw new IllegalStateException(impossible); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java index 519462ba52..57753dd948 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java @@ -306,7 +306,8 @@ void pendingIntentBlocksLaterPreparationWithoutChangingInventoryOrItsCohort() { try { establishActualLegacyDisposition(testSchema.dsl()); var inventory = new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); - prepareActualBinding(inventory); + var originalRequest = actualBindingRequest(PREPARED_CHARACTER_ID); + var originalPreparation = inventory.prepare(originalRequest); var owner = new CanonicalGameplayIssuerLayoutBootstrapRepository(testSchema.dsl()); UUID requestId = UUID.randomUUID(); @@ -326,6 +327,55 @@ void pendingIntentBlocksLaterPreparationWithoutChangingInventoryOrItsCohort() { countRows(testSchema.dsl(), "game_session_canonical_issuer_partition_reservation"); int generationCount = countRows(testSchema.dsl(), "game_session_canonical_binding_generation"); + List inventoryBefore = + rowImages(testSchema.dsl(), "game_session_canonical_gameplay_binding_inventory"); + List transitionBefore = + rowImages(testSchema.dsl(), "game_session_canonical_binding_transition"); + List reservationBefore = + rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_reservation"); + List generationBefore = + rowImages(testSchema.dsl(), "game_session_canonical_binding_generation"); + List accountObligationBefore = + rowImages(testSchema.dsl(), "game_session_canonical_binding_account_index_obligation"); + List issuerObligationBefore = + rowImages(testSchema.dsl(), "game_session_canonical_binding_issuer_index_obligation"); + List regionObligationBefore = + rowImages(testSchema.dsl(), "game_session_canonical_binding_region_bridge_obligation"); + + assertThat(inventory.prepare(originalRequest)).isEqualTo(originalPreparation); + var conflictingRequest = + new CanonicalGameplayBindingTransitionRequest( + originalRequest.transitionId(), + UUID.randomUUID(), + originalRequest.candidate(), + originalRequest.issuerReservation(), + originalRequest.expectedPriorBindingRef(), + originalRequest.expectedPriorBindingGeneration()); + assertThatThrownBy(() -> inventory.prepare(conflictingRequest)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining( + "same transition identity was retried with a different exact request"); + + assertThat(currentInventoryRevision(testSchema.dsl())).isEqualTo(originalInventoryRevision); + assertThat(rowImages(testSchema.dsl(), "game_session_canonical_gameplay_binding_inventory")) + .containsExactlyElementsOf(inventoryBefore); + assertThat(rowImages(testSchema.dsl(), "game_session_canonical_binding_transition")) + .containsExactlyElementsOf(transitionBefore); + assertThat(rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_reservation")) + .containsExactlyElementsOf(reservationBefore); + assertThat(rowImages(testSchema.dsl(), "game_session_canonical_binding_generation")) + .containsExactlyElementsOf(generationBefore); + assertThat( + rowImages( + testSchema.dsl(), "game_session_canonical_binding_account_index_obligation")) + .containsExactlyElementsOf(accountObligationBefore); + assertThat( + rowImages(testSchema.dsl(), "game_session_canonical_binding_issuer_index_obligation")) + .containsExactlyElementsOf(issuerObligationBefore); + assertThat( + rowImages( + testSchema.dsl(), "game_session_canonical_binding_region_bridge_obligation")) + .containsExactlyElementsOf(regionObligationBefore); assertThatThrownBy(() -> prepareActualBinding(inventory, BLOCKED_CHARACTER_ID)) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) @@ -778,6 +828,10 @@ private static CanonicalGameplayBindingTransitionSnapshot prepareActualBinding( private static CanonicalGameplayBindingTransitionSnapshot prepareActualBinding( CanonicalGameplayBindingInventoryRepository inventory, UUID characterId) { + return inventory.prepare(actualBindingRequest(characterId)); + } + + private static CanonicalGameplayBindingTransitionRequest actualBindingRequest(UUID characterId) { UUID transitionId = UUID.randomUUID(); UUID reservationId = UUID.randomUUID(); UUID reservationFence = UUID.randomUUID(); @@ -807,9 +861,8 @@ private static CanonicalGameplayBindingTransitionSnapshot prepareActualBinding( BigInteger.ONE, BigInteger.TWO, BigInteger.ONE); - return inventory.prepare( - new CanonicalGameplayBindingTransitionRequest( - transitionId, UUID.randomUUID(), candidate, reservation, null, null)); + return new CanonicalGameplayBindingTransitionRequest( + transitionId, UUID.randomUUID(), candidate, reservation, null, null); } private static void insertReservationOnly( From 890fc41399f01d6c74f66b22e5c7d30a5873f457 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:36:01 +1300 Subject: [PATCH 09/34] Qualify ordinary issuer registration and one-key reservation projection --- ...calGameplayBindingInventoryRepository.java | 177 ++- ...alGameplayIssuerBindingLocalOperation.java | 232 ++++ ...IssuerBindingLocalOperationRepository.java | 1118 +++++++++++++++++ ...ssuerBindingLocalProjectionRepository.java | 1114 ++++++++++++++++ ...lGameplayIssuerBindingLocalRedisOwner.java | 530 ++++++++ ...lGameplayIssuerBootstrapCoverageOwner.java | 18 +- ...playIssuerBootstrapCoverageRepository.java | 431 +++++-- ...anonicalGameplayIssuerInstalledAnchor.java | 204 ++- ...ameplayIssuerPartitionBuildRepository.java | 42 + ...erBindingLocalRedisScriptContribution.java | 51 + ...nonical_issuer_binding_local_operation.sql | 206 +++ .../game-session-issuer-binding-local-add.lua | 404 ++++++ ...game-session-issuer-binding-local-add.json | 40 + ...calOperationRepositoryIntegrationTest.java | 803 ++++++++++++ ...BindingLocalRedisOwnerIntegrationTest.java | 1085 ++++++++++++++++ ...BootstrapCoverageOwnerIntegrationTest.java | 276 ++-- ...berOperationRepositoryIntegrationTest.java | 60 +- ...rtitionBuildRepositoryIntegrationTest.java | 66 +- 18 files changed, 6596 insertions(+), 261 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperation.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRedisScriptContribution.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V1034__canonical_issuer_binding_local_operation.sql create mode 100644 services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-add.lua create mode 100644 services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-add.json create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index 88f98af39a..b5cf5ea2af 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -74,6 +74,77 @@ CanonicalGameplayBindingTransitionSnapshot prepare( configuration -> prepareInTransaction(DSL.using(configuration), request)); } + /** + * Prepares and registers one ordinary NEW candidate while the exact installed initial issuer + * anchor remains current. The inventory clock and issuer control are locked before the request + * factory resolves or allocates owner identities; Account remains the next lock. + */ + CanonicalGameplayBindingTransitionSnapshot prepareAfterInstalledIssuerAnchor( + InstalledAnchorPreparationRequestFactory requestFactory, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentIssuerState, + InstalledAnchorPreparationRecorder registrationRecorder) { + Objects.requireNonNull(requestFactory, "requestFactory"); + Objects.requireNonNull(currentIssuerState, "currentIssuerState"); + Objects.requireNonNull(registrationRecorder, "registrationRecorder"); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger revision = lockInventoryRevision(transaction); + CanonicalGameplayIssuerInstalledAnchor actualAnchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction( + transaction, currentIssuerState); + InstalledAnchorPreparationContext context = + new InstalledAnchorPreparationContext(revision, actualAnchor, currentIssuerState); + CanonicalGameplayBindingTransitionRequest request = + Objects.requireNonNull( + requestFactory.create(transaction, actualAnchor, currentIssuerState), + "installed-anchor request factory returned null"); + validateRequest(request); + if (request.expectedPriorBindingRef() != null + || request.expectedPriorBindingGeneration() != null) { + throw conflict("Installed-anchor local issuer operation accepts only ordinary NEW"); + } + requireCandidateMatchesInstalledAnchor(request.candidate(), actualAnchor); + return prepareInTransaction(transaction, request, context, registrationRecorder); + }); + } + + @FunctionalInterface + interface InstalledAnchorPreparationRequestFactory { + /** + * Resolves an exact retry or allocates new owner identities inside the serialized SQL + * transaction. + */ + CanonicalGameplayBindingTransitionRequest create( + DSLContext transaction, + CanonicalGameplayIssuerInstalledAnchor actualAnchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentIssuerState); + } + + @FunctionalInterface + interface InstalledAnchorPreparationRecorder { + /** Called in the same transaction after candidate preparation or exact retry qualification. */ + void record( + DSLContext transaction, + CanonicalGameplayBindingTransitionRequest request, + CanonicalGameplayIssuerInstalledAnchor actualAnchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentIssuerState, + CanonicalGameplayBindingTransitionSnapshot prepared, + boolean exactRetry); + } + + private record InstalledAnchorPreparationContext( + BigInteger inventoryRevision, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentIssuerState) { + private InstalledAnchorPreparationContext { + Objects.requireNonNull(inventoryRevision, "inventoryRevision"); + Objects.requireNonNull(anchor, "anchor"); + Objects.requireNonNull(currentIssuerState, "currentIssuerState"); + } + } + /** * Reads the complete typed inventory and all retained repair obligations from one DB snapshot. */ @@ -1496,9 +1567,31 @@ private static void requireSameProvisionalOperation( private static CanonicalGameplayBindingTransitionSnapshot prepareInTransaction( DSLContext transaction, CanonicalGameplayBindingTransitionRequest request) { - BigInteger revision = lockInventoryRevision(transaction); - boolean pendingIssuerLayoutBootstrapIntent = - validatePendingIssuerLayoutBootstrapIntent(transaction, request.candidate().issuerId()); + return prepareInTransaction(transaction, request, null, null); + } + + private static CanonicalGameplayBindingTransitionSnapshot prepareInTransaction( + DSLContext transaction, + CanonicalGameplayBindingTransitionRequest request, + InstalledAnchorPreparationContext installedAnchorContext, + InstalledAnchorPreparationRecorder registrationRecorder) { + BigInteger revision; + CanonicalGameplayIssuerInstalledAnchor actualAnchor; + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentIssuerState; + boolean pendingIssuerLayoutBootstrapIntent; + if (installedAnchorContext == null) { + revision = lockInventoryRevision(transaction); + actualAnchor = null; + currentIssuerState = null; + pendingIssuerLayoutBootstrapIntent = + validatePendingIssuerLayoutBootstrapIntent(transaction, request.candidate().issuerId()); + } else { + revision = installedAnchorContext.inventoryRevision(); + actualAnchor = installedAnchorContext.anchor(); + currentIssuerState = installedAnchorContext.currentIssuerState(); + requireCandidateMatchesInstalledAnchor(request.candidate(), actualAnchor); + pendingIssuerLayoutBootstrapIntent = false; + } CanonicalGameplayAccountCoverageEvidence accountCoverageEvidence = lockAccountCoverageEvidence(transaction, request.candidate().accountId()); boolean initialBinding = request.expectedPriorBindingRef() == null; @@ -1512,6 +1605,15 @@ private static CanonicalGameplayBindingTransitionSnapshot prepareInTransaction( if (!retry.accountCoverageEvidence().equals(accountCoverageEvidence)) { throw conflict("Same transition retry carries stale account-wide coverage evidence"); } + if (registrationRecorder != null) { + registrationRecorder.record( + transaction, + request, + Objects.requireNonNull(actualAnchor), + currentIssuerState, + retry, + true); + } return retry; } if (pendingIssuerLayoutBootstrapIntent) { @@ -1548,6 +1650,10 @@ private static CanonicalGameplayBindingTransitionSnapshot prepareInTransaction( throw conflict("An unresolved candidate or repair obligation already fences this controller"); } + if (actualAnchor != null) { + requireIssuerCapacityAvailable(transaction, request.candidate(), actualAnchor); + } + ensureGenerationRow(transaction, candidate); Record generationRow = Objects.requireNonNull( @@ -1612,9 +1718,74 @@ private static CanonicalGameplayBindingTransitionSnapshot prepareInTransaction( decimal(nextRevision), decimal(revision)); requireOne(revisionUpdated, "durable inventory revision compare-and-set lost its locked row"); + if (registrationRecorder != null) { + registrationRecorder.record( + transaction, + request, + Objects.requireNonNull(actualAnchor), + currentIssuerState, + prepared, + false); + } return prepared; } + private static void requireCandidateMatchesInstalledAnchor( + CanonicalGameplayBindingIdentity candidate, CanonicalGameplayIssuerInstalledAnchor anchor) { + if (!candidate.issuerId().equals(anchor.issuerId()) + || !candidate.issuerAuthGeneration().equals(anchor.issuerAuthGeneration()) + || !candidate.issuerIndexLayoutVersion().equals(anchor.layoutVersion()) + || !candidate.issuerIndexPartitionCount().equals(anchor.partitionCount()) + || !candidate.issuerIndexPartitionCapacity().equals(anchor.partitionCapacity())) { + throw conflict( + "Candidate issuer, Account source, or layout differs from the installed anchor"); + } + } + + /** + * Counts the current V29 owner rows under the inventory-clock lock. The initial immutable anchor + * is a baseline; every post-baseline candidate is represented by this same inventory, never by a + * parallel local-operation inventory. + */ + private static void requireIssuerCapacityAvailable( + DSLContext transaction, + CanonicalGameplayBindingIdentity candidate, + CanonicalGameplayIssuerInstalledAnchor anchor) { + BigInteger candidatePartition = candidate.bindingRef().partitionId(anchor.partitionCount()); + BigInteger aggregate = BigInteger.ZERO; + BigInteger partition = BigInteger.ZERO; + List reservations = + transaction.fetch( + "SELECT issuer_index_layout_version, issuer_index_partition_count," + + " issuer_index_partition_capacity, partition_id, lifecycle FROM " + + RESERVATION + + " WHERE issuer_id = ? AND lifecycle <> 'RELEASED' ORDER BY reservation_id FOR UPDATE", + candidate.issuerId()); + for (Record reservation : reservations) { + BigInteger layoutVersion = readBigInteger(reservation, "issuer_index_layout_version"); + BigInteger partitionCount = readBigInteger(reservation, "issuer_index_partition_count"); + BigInteger partitionCapacity = readBigInteger(reservation, "issuer_index_partition_capacity"); + BigInteger partitionId = readBigInteger(reservation, "partition_id"); + if (!layoutVersion.equals(anchor.layoutVersion()) + || !partitionCount.equals(anchor.partitionCount()) + || !partitionCapacity.equals(anchor.partitionCapacity()) + || partitionId.signum() < 0 + || partitionId.compareTo(anchor.partitionCount()) >= 0) { + throw conflict( + "Current issuer inventory contains a reservation outside the installed layout"); + } + aggregate = aggregate.add(BigInteger.ONE); + if (partitionId.equals(candidatePartition)) partition = partition.add(BigInteger.ONE); + } + BigInteger nextPartition = partition.add(BigInteger.ONE); + BigInteger nextAggregate = aggregate.add(BigInteger.ONE); + BigInteger aggregateBound = anchor.partitionCount().multiply(anchor.partitionCapacity()); + if (nextPartition.compareTo(anchor.partitionCapacity()) > 0 + || nextAggregate.compareTo(aggregateBound) > 0) { + throw conflict("Installed issuer partition or aggregate reservation capacity is full"); + } + } + private static boolean validatePendingIssuerLayoutBootstrapIntent( DSLContext transaction, String issuerId) { Record control = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperation.java new file mode 100644 index 0000000000..87b759fd4c --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperation.java @@ -0,0 +1,232 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; + +/** + * Immutable SQL-issued preparation for one ordinary NEW issuer member after the initial installed + * anchor. This operation remains pending physical proof and is not an issuer-wide acknowledgement + * or admission capability. + */ +final class CanonicalGameplayIssuerBindingLocalOperation { + enum Status { + PENDING_PHYSICAL_PROOF + } + + /** Caller correlation and expected candidate identity; it carries no reservation authority. */ + record Request( + UUID requestId, + UUID transitionId, + CanonicalGameplayBindingIdentity candidate, + CanonicalGameplayBindingRef expectedPriorBindingRef, + BigInteger expectedPriorBindingGeneration) { + Request { + requireNonNil(requestId, "requestId"); + requireNonNil(transitionId, "transitionId"); + if (requestId.equals(transitionId)) { + throw new IllegalArgumentException("requestId and transitionId must be distinct"); + } + Objects.requireNonNull(candidate, "candidate"); + if ((expectedPriorBindingRef == null) != (expectedPriorBindingGeneration == null)) { + throw new IllegalArgumentException( + "Expected prior reference and generation must be paired"); + } + if (expectedPriorBindingGeneration != null && expectedPriorBindingGeneration.signum() <= 0) { + throw new IllegalArgumentException("Expected prior generation must be positive"); + } + } + } + + private final Request request; + private final UUID candidateAccountIndexFence; + private final CanonicalGameplayBindingTransitionSnapshot preparedTransition; + private final BigInteger localInventorySnapshotRevision; + private final CanonicalIssuerPartitionReservation reservation; + private final CanonicalGameplayIssuerInstalledAnchor anchor; + private final CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof + baselinePartitionProof; + private final CanonicalGameplayIssuerMemberV2Value memberValue; + private final UUID operationId; + private final BigInteger operationFence; + private final BigInteger localMemberGeneration; + private final byte[] exactMemberValueBytes; + private final String memberValueDigest; + private final Status status; + + CanonicalGameplayIssuerBindingLocalOperation( + Request request, + UUID candidateAccountIndexFence, + CanonicalGameplayBindingTransitionSnapshot preparedTransition, + BigInteger localInventorySnapshotRevision, + CanonicalIssuerPartitionReservation reservation, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof + baselinePartitionProof, + CanonicalGameplayIssuerMemberV2Value memberValue, + UUID operationId, + BigInteger operationFence, + BigInteger localMemberGeneration, + byte[] exactMemberValueBytes, + String memberValueDigest, + Status status) { + this.request = Objects.requireNonNull(request, "request"); + this.candidateAccountIndexFence = + requireNonNil(candidateAccountIndexFence, "candidateAccountIndexFence"); + this.preparedTransition = Objects.requireNonNull(preparedTransition, "preparedTransition"); + this.localInventorySnapshotRevision = + requirePositive(localInventorySnapshotRevision, "localInventorySnapshotRevision"); + this.reservation = Objects.requireNonNull(reservation, "reservation"); + this.anchor = Objects.requireNonNull(anchor, "anchor"); + this.baselinePartitionProof = + Objects.requireNonNull(baselinePartitionProof, "baselinePartitionProof"); + this.memberValue = Objects.requireNonNull(memberValue, "memberValue"); + this.operationId = requireNonNil(operationId, "operationId"); + this.operationFence = requirePositive(operationFence, "operationFence"); + this.localMemberGeneration = requirePositive(localMemberGeneration, "localMemberGeneration"); + this.exactMemberValueBytes = + Objects.requireNonNull(exactMemberValueBytes, "exactMemberValueBytes").clone(); + if (this.exactMemberValueBytes.length == 0 + || this.exactMemberValueBytes.length + > CanonicalGameplayIssuerMemberV2Codec.MAX_VALUE_BYTES) { + throw new IllegalArgumentException("Exact local member bytes are outside their bound"); + } + this.memberValueDigest = requireDigest(memberValueDigest, "memberValueDigest"); + this.status = Objects.requireNonNull(status, "status"); + + if (request.expectedPriorBindingRef() != null + || request.expectedPriorBindingGeneration() != null + || !preparedTransition.transitionId().equals(request.transitionId()) + || !preparedTransition.candidate().equals(request.candidate()) + || !preparedTransition.bindingRef().equals(request.candidate().bindingRef()) + || !reservation.owner().equals(request.candidate()) + || !reservation.transitionId().equals(request.transitionId()) + || !reservation.inventoryRevision().equals(localInventorySnapshotRevision) + || !reservation.bindingGeneration().equals(preparedTransition.bindingGeneration()) + || !reservation.reservationId().equals(preparedTransition.issuerReservationId()) + || !anchor.issuerId().equals(request.candidate().issuerId()) + || !anchor.layoutVersion().equals(request.candidate().issuerIndexLayoutVersion()) + || !anchor.partitionCount().equals(request.candidate().issuerIndexPartitionCount()) + || !anchor.partitionCapacity().equals(request.candidate().issuerIndexPartitionCapacity()) + || !baselinePartitionProof + .partitionId() + .equals(request.candidate().bindingRef().partitionId(anchor.partitionCount())) + || !operationId.equals(memberValue.memberOperation().operationId()) + || !operationFence.equals(memberValue.memberOperation().operationFence()) + || !localMemberGeneration.equals(memberValue.memberOperation().coverageGeneration()) + || !memberValue.owner().equals(request.candidate()) + || !memberValue.bindingGeneration().equals(preparedTransition.bindingGeneration()) + || !memberValue.reservation().equals(reservation) + || !memberValue + .anchor() + .issuerCoverageOperationId() + .equals(anchor.issuerCoverageOperationId()) + || !memberValue.anchor().operationFence().equals(anchor.operationFence()) + || !memberValue.anchor().coverageFence().equals(anchor.coverageFence()) + || !memberValue + .anchor() + .issuerInventorySnapshotRevision() + .equals(anchor.issuerInventorySnapshotRevision()) + || !Arrays.equals( + this.exactMemberValueBytes, CanonicalGameplayIssuerMemberV2Codec.encode(memberValue)) + || !memberValueDigest.equals( + CanonicalGameplayIssuerMemberV2Codec.sha256(this.exactMemberValueBytes)) + || !memberValue.equals( + CanonicalGameplayIssuerMemberV2Codec.decode(this.exactMemberValueBytes)) + || status != Status.PENDING_PHYSICAL_PROOF) { + throw new IllegalArgumentException( + "Local issuer operation differs from its exact prepared NEW tuple"); + } + } + + Request request() { + return request; + } + + UUID candidateAccountIndexFence() { + return candidateAccountIndexFence; + } + + CanonicalGameplayBindingTransitionSnapshot preparedTransition() { + return preparedTransition; + } + + BigInteger localInventorySnapshotRevision() { + return localInventorySnapshotRevision; + } + + CanonicalIssuerPartitionReservation reservation() { + return reservation; + } + + CanonicalGameplayIssuerInstalledAnchor anchor() { + return anchor; + } + + CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof + baselinePartitionProof() { + return baselinePartitionProof; + } + + CanonicalGameplayIssuerMemberV2Value memberValue() { + return memberValue; + } + + UUID operationId() { + return operationId; + } + + BigInteger operationFence() { + return operationFence; + } + + BigInteger localMemberGeneration() { + return localMemberGeneration; + } + + byte[] exactMemberValueBytes() { + return exactMemberValueBytes.clone(); + } + + String memberValueDigest() { + return memberValueDigest; + } + + Status status() { + return status; + } + + /** The exact binding and capacity fields are absent before this pending operation is applied. */ + String expectedOldMemberState() { + return "ABSENT"; + } + + String expectedOldCapacityState() { + return "ABSENT"; + } + + private static UUID requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException(name + " must not be nil"); + return value; + } + + private static BigInteger requirePositive(BigInteger value, String name) { + Objects.requireNonNull(value, name); + if (value.signum() <= 0) throw new IllegalArgumentException(name + " must be positive"); + return value; + } + + private static String requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!value.matches("sha256:[0-9a-f]{64}")) + throw new IllegalArgumentException(name + " must be canonical SHA-256"); + return value; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java new file mode 100644 index 0000000000..cd32f610be --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java @@ -0,0 +1,1118 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountCoverageEvidence; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** SQL owner for an ordinary NEW issuer registration linked to the actual installed anchor. */ +final class CanonicalGameplayIssuerBindingLocalOperationRepository { + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String OPERATION = "game_session_canonical_issuer_binding_local_operation"; + private static final String RESERVATION = "game_session_canonical_issuer_partition_reservation"; + private static final String ACCOUNT_CONTROL = "game_session_canonical_account_coverage_control"; + private static final String MEMBER_COUNTER = + "game_session_canonical_issuer_bootstrap_member_op_counter"; + private static final String BOOTSTRAP_MEMBER_OPERATION = + "game_session_canonical_issuer_bootstrap_member_operation"; + + private final DSLContext dsl; + private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentIssuerStateSource; + + CanonicalGameplayIssuerBindingLocalOperationRepository( + DSLContext dsl, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentIssuerStateSource) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.currentIssuerStateSource = + Objects.requireNonNull(currentIssuerStateSource, "currentIssuerStateSource"); + } + + /** + * Begins or exactly replays one caller-correlated ordinary NEW request. The current Account + * checkpoint and stable incarnation are explicit controlled collaborators; SQL still owns the + * installed anchor, inventory/reservation, local operation identity and exact v2 bytes. + */ + CanonicalGameplayIssuerBindingLocalOperation beginOrResumeOrdinaryNew( + CanonicalGameplayIssuerBindingLocalOperation.Request request) { + Objects.requireNonNull(request, "request"); + requireNoAmbientTransaction(); + if (request.expectedPriorBindingRef() != null + || request.expectedPriorBindingGeneration() != null) { + throw conflict("Local issuer registration is restricted to ordinary NEW"); + } + + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState = + Objects.requireNonNull( + currentIssuerStateSource.readFreshCurrentState(), + "current issuer state source returned null"); + AtomicReference result = new AtomicReference<>(); + new CanonicalGameplayBindingInventoryRepository(dsl) + .prepareAfterInstalledIssuerAnchor( + (transaction, actualAnchor, ignoredCurrentState) -> + resolveTransitionRequestInTransaction(transaction, request, actualAnchor), + currentState, + (transaction, exactRequest, actualAnchor, state, prepared, exactRetry) -> + result.set( + recordOrReplayInTransaction( + request, + transaction, + exactRequest, + actualAnchor, + state, + prepared, + exactRetry))); + if (result.get() == null) { + throw conflict("Local issuer registration did not produce a durable operation"); + } + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState postReadState; + try { + postReadState = + Objects.requireNonNull( + currentIssuerStateSource.readFreshCurrentState(), + "current issuer state source returned null after local registration"); + } catch (RuntimeException sourceFailure) { + throw new IllegalStateException( + "Could not requalify issuer source after SQL registration; the pending local operation remains durable", + sourceFailure); + } + if (!sameCurrentIssuerState(currentState, postReadState)) { + throw conflict( + "Issuer source or incarnation moved during SQL registration; the pending local operation remains durable"); + } + return result.get(); + } + + private CanonicalGameplayBindingTransitionRequest resolveTransitionRequestInTransaction( + DSLContext transaction, + CanonicalGameplayIssuerBindingLocalOperation.Request request, + CanonicalGameplayIssuerInstalledAnchor anchor) { + requireCandidateMatchesAnchor(request.candidate(), anchor); + Record priorByTransition = + transaction.fetchOne( + "SELECT * FROM " + OPERATION + " WHERE issuer_id = ? AND transition_id = ?", + ISSUER, + request.transitionId()); + Record priorByRequest = + transaction.fetchOne( + "SELECT * FROM " + OPERATION + " WHERE issuer_id = ? AND request_id = ?", + ISSUER, + request.requestId()); + if ((priorByTransition == null) != (priorByRequest == null) + || (priorByTransition != null + && !requireUuid(priorByTransition, "operation_id") + .equals(requireUuid(priorByRequest, "operation_id")))) { + throw conflict( + "Request and transition identities refer to different local issuer operations"); + } + + UUID accountIndexFence; + CanonicalIssuerReservationFenceEvidence reservationEvidence; + if (priorByTransition == null) { + accountIndexFence = freshNonNilUuid(); + reservationEvidence = + new CanonicalIssuerReservationFenceEvidence( + freshNonNilUuid(), + freshNonNilUuid(), + anchor.issuerCoverageOperationId(), + anchor.operationFence(), + anchor.coverageFence(), + anchor.issuerInventorySnapshotRevision()); + } else { + requireCallerRequestMatches(priorByTransition, request); + accountIndexFence = requireUuid(priorByTransition, "candidate_account_index_fence"); + reservationEvidence = readOriginalReservationEvidence(priorByTransition); + } + + return new CanonicalGameplayBindingTransitionRequest( + request.transitionId(), + accountIndexFence, + request.candidate(), + reservationEvidence, + null, + null); + } + + private CanonicalGameplayIssuerBindingLocalOperation recordOrReplayInTransaction( + CanonicalGameplayIssuerBindingLocalOperation.Request request, + DSLContext transaction, + CanonicalGameplayBindingTransitionRequest transitionRequest, + CanonicalGameplayIssuerInstalledAnchor actualAnchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState, + CanonicalGameplayBindingTransitionSnapshot prepared, + boolean exactRetry) { + Record operationRow = + transaction.fetchOne( + "SELECT * FROM " + OPERATION + " WHERE issuer_id = ? AND transition_id = ? FOR UPDATE", + ISSUER, + transitionRequest.transitionId()); + if (exactRetry) { + if (operationRow == null) { + throw conflict("Prepared NEW transition has no matching local issuer registration"); + } + requireCallerRequestMatches(operationRow, request); + CanonicalIssuerPartitionReservation reservation = + readAndRequireReservation(transaction, transitionRequest, prepared, operationRow); + var proof = + CanonicalGameplayIssuerBootstrapCoverageRepository.readInstalledAnchorPartitionProof( + transaction, actualAnchor, reservation.partitionId()); + CanonicalGameplayIssuerBootstrapCoverageRepository.requireNewMemberAbsentFromBaseline( + proof, prepared.bindingRef(), reservation.reservationId()); + AccountControlSnapshot accountControl = + readAndRequireAccountControl( + transaction, + transitionRequest.candidate().accountId(), + prepared.accountCoverageEvidence()); + return returnOperation( + request, + prepared, + reservation, + actualAnchor, + proof, + currentState, + accountControl, + operationRow); + } + if (operationRow != null) { + throw conflict("A local issuer operation already exists for a newly prepared transition"); + } + if (operationRequestExists(transaction, transitionRequest.transitionId())) { + throw conflict("A different request already owns this local issuer transition"); + } + + CanonicalIssuerPartitionReservation reservation = + readAndRequireReservation(transaction, transitionRequest, prepared, null); + var proof = + CanonicalGameplayIssuerBootstrapCoverageRepository.readInstalledAnchorPartitionProof( + transaction, actualAnchor, reservation.partitionId()); + CanonicalGameplayIssuerBootstrapCoverageRepository.requireNewMemberAbsentFromBaseline( + proof, prepared.bindingRef(), reservation.reservationId()); + AccountControlSnapshot accountControl = + readAndRequireAccountControl( + transaction, + transitionRequest.candidate().accountId(), + prepared.accountCoverageEvidence()); + + IssuedCounters counters = allocateLocalCounters(transaction, actualAnchor, reservation); + UUID operationId = freshOperationId(request, reservation, actualAnchor); + CanonicalGameplayIssuerMemberV2Value memberValue = + createMemberValue( + request.candidate(), + prepared.bindingGeneration(), + reservation, + actualAnchor, + currentState.incarnation(), + operationId, + counters.operationFence(), + counters.localMemberGeneration()); + byte[] valueBytes = CanonicalGameplayIssuerMemberV2Codec.encode(memberValue); + String valueDigest = CanonicalGameplayIssuerMemberV2Codec.sha256(valueBytes); + insertOperation( + transaction, + request, + transitionRequest, + prepared, + reservation, + actualAnchor, + proof, + accountControl, + operationId, + counters, + valueBytes, + valueDigest); + Record saved = + transaction.fetchOne( + "SELECT * FROM " + OPERATION + " WHERE issuer_id = ? AND transition_id = ? FOR UPDATE", + ISSUER, + transitionRequest.transitionId()); + if (saved == null) throw conflict("Local issuer operation is unreadable after persistence"); + return returnOperation( + request, prepared, reservation, actualAnchor, proof, currentState, accountControl, saved); + } + + private CanonicalGameplayIssuerBindingLocalOperation returnOperation( + CanonicalGameplayIssuerBindingLocalOperation.Request request, + CanonicalGameplayBindingTransitionSnapshot prepared, + CanonicalIssuerPartitionReservation reservation, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof proof, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState, + AccountControlSnapshot accountControl, + Record row) { + requireSameStoredOperation( + row, request, prepared, reservation, anchor, proof, currentState, accountControl); + UUID operationId = requireUuid(row, "operation_id"); + BigInteger operationFence = readPositive(row, "operation_fence"); + BigInteger localMemberGeneration = readPositive(row, "local_member_generation"); + byte[] bytes = requireBytes(row, "member_value_bytes"); + String digest = requireText(row, "member_value_digest"); + CanonicalGameplayIssuerMemberV2Value value; + try { + value = CanonicalGameplayIssuerMemberV2Codec.decode(bytes); + } catch (RuntimeException malformed) { + throw conflict("Stored local issuer value is not canonical schema v2"); + } + CanonicalGameplayIssuerMemberV2Value expected = + createMemberValue( + request.candidate(), + prepared.bindingGeneration(), + reservation, + anchor, + currentState.incarnation(), + operationId, + operationFence, + localMemberGeneration); + if (!expected.equals(value) + || !Arrays.equals(bytes, CanonicalGameplayIssuerMemberV2Codec.encode(expected)) + || !digest.equals(CanonicalGameplayIssuerMemberV2Codec.sha256(bytes))) { + throw conflict( + "Stored local issuer operation differs from its exact anchor, source, or reservation"); + } + try { + return new CanonicalGameplayIssuerBindingLocalOperation( + request, + requireUuid(row, "candidate_account_index_fence"), + prepared, + readPositive(row, "local_inventory_snapshot_revision"), + reservation, + anchor, + proof, + expected, + operationId, + operationFence, + localMemberGeneration, + bytes, + digest, + CanonicalGameplayIssuerBindingLocalOperation.Status.valueOf( + requireText(row, "member_status"))); + } catch (RuntimeException malformed) { + throw conflict("Stored local issuer operation metadata is malformed"); + } + } + + private static CanonicalGameplayIssuerMemberV2Value createMemberValue( + CanonicalGameplayBindingIdentity candidate, + BigInteger bindingGeneration, + CanonicalIssuerPartitionReservation reservation, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation, + UUID operationId, + BigInteger operationFence, + BigInteger localMemberGeneration) { + var layout = + new CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor( + anchor.issuerId(), + anchor.layoutVersion(), + anchor.partitionCount(), + anchor.partitionCapacity(), + anchor.mappingIdentity(), + anchor.layoutDescriptorBytes(), + anchor.layoutDescriptorDigest()); + var source = + new CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint( + anchor.issuerId(), + anchor.issuerAuthGeneration(), + anchor.sourceCheckpointBytes(), + anchor.sourceCheckpointDigest(), + anchor.sourceEventBytes(), + anchor.sourceEventDigest()); + return new CanonicalGameplayIssuerMemberV2Value( + candidate, + bindingGeneration, + reservation, + new CanonicalGameplayIssuerMemberV2Value.Anchor( + anchor.issuerCoverageOperationId(), + anchor.operationFence(), + anchor.coverageFence(), + anchor.issuerInventorySnapshotRevision()), + new CanonicalGameplayIssuerMemberV2Value.LocalMemberOperation( + operationId, operationFence, localMemberGeneration), + anchor.controlEpoch(), + layout, + source, + incarnation); + } + + private static CanonicalIssuerPartitionReservation readAndRequireReservation( + DSLContext transaction, + CanonicalGameplayBindingTransitionRequest request, + CanonicalGameplayBindingTransitionSnapshot prepared, + Record operationRow) { + Record row = + transaction.fetchOne( + "SELECT * FROM " + RESERVATION + " WHERE reservation_id = ? FOR UPDATE", + prepared.issuerReservationId()); + if (row == null) throw conflict("Prepared ordinary NEW reservation is missing"); + CanonicalIssuerPartitionReservation reservation; + try { + if (operationRow == null) { + reservation = + new CanonicalIssuerPartitionReservation( + requireUuid(row, "reservation_id"), + requireIdentityMatchesReservation(request.candidate(), row), + readPositive(row, "binding_generation"), + requireUuid(row, "transition_id"), + readNonNegative(row, "partition_id"), + CanonicalIssuerPartitionReservation.Lifecycle.valueOf( + requireText(row, "lifecycle")), + requireUuid(row, "reservation_fence"), + requireUuid(row, "issuer_coverage_operation_id"), + readPositive(row, "issuer_coverage_operation_fence"), + readPositive(row, "coverage_fence"), + readPositive(row, "inventory_snapshot_revision"), + readPositive(row, "inventory_revision")); + } else { + CanonicalGameplayIssuerMemberV2Value stored = + CanonicalGameplayIssuerMemberV2Codec.decode( + requireBytes(operationRow, "member_value_bytes")); + reservation = stored.reservation(); + requireIdentityMatchesReservation(request.candidate(), row); + if (!reservation.reservationId().equals(requireUuid(row, "reservation_id")) + || !reservation.transitionId().equals(requireUuid(row, "transition_id")) + || !reservation.bindingGeneration().equals(readPositive(row, "binding_generation")) + || !reservation.partitionId().equals(readNonNegative(row, "partition_id")) + || !reservation.lifecycle().name().equals(requireText(row, "lifecycle")) + || !reservation.reservationFence().equals(requireUuid(row, "reservation_fence")) + || !reservation + .issuerCoverageOperationId() + .equals(requireUuid(row, "issuer_coverage_operation_id")) + || !reservation + .issuerCoverageOperationFence() + .equals(readPositive(row, "issuer_coverage_operation_fence")) + || !reservation.coverageFence().equals(readPositive(row, "coverage_fence")) + || !reservation + .inventorySnapshotRevision() + .equals(readPositive(row, "inventory_snapshot_revision")) + || !reservation.inventoryRevision().equals(readPositive(row, "inventory_revision"))) { + throw conflict( + "Current reservation no longer matches its immutable local operation source"); + } + } + } catch (IllegalStateException conflict) { + throw conflict; + } catch (RuntimeException malformed) { + throw conflict("Prepared ordinary NEW reservation is malformed"); + } + if (!reservation.reservationId().equals(prepared.issuerReservationId()) + || !reservation.transitionId().equals(request.transitionId()) + || !reservation.bindingGeneration().equals(prepared.bindingGeneration()) + || !reservation.reservationFence().equals(prepared.reservationFence()) + || !reservation.owner().equals(request.candidate()) + || !reservation + .issuerCoverageOperationId() + .equals(request.issuerReservation().issuerCoverageOperationId()) + || !reservation + .issuerCoverageOperationFence() + .equals(request.issuerReservation().issuerCoverageOperationFence()) + || !reservation.coverageFence().equals(request.issuerReservation().coverageFence()) + || !reservation + .inventorySnapshotRevision() + .equals(request.issuerReservation().inventorySnapshotRevision()) + || (operationRow != null + && (!reservation.reservationId().equals(requireUuid(operationRow, "reservation_id")) + || !reservation + .reservationFence() + .equals(requireUuid(operationRow, "reservation_fence")) + || !reservation + .issuerCoverageOperationId() + .equals(requireUuid(operationRow, "original_issuer_coverage_operation_id")) + || !reservation + .issuerCoverageOperationFence() + .equals(readPositive(operationRow, "original_issuer_coverage_operation_fence")) + || !reservation + .coverageFence() + .equals(readPositive(operationRow, "original_coverage_fence")) + || !reservation + .inventorySnapshotRevision() + .equals(readPositive(operationRow, "original_inventory_snapshot_revision"))))) { + throw conflict("Persisted reservation differs from its exact original local request"); + } + return reservation; + } + + private static CanonicalGameplayBindingIdentity requireIdentityMatchesReservation( + CanonicalGameplayBindingIdentity expected, Record row) { + if (!expected.accountId().equals(row.get("account_id", UUID.class)) + || !expected.tenantId().equals(row.get("tenant_id", UUID.class)) + || !expected.gameInstanceId().equals(row.get("game_instance_id", UUID.class)) + || expected.runtimeGameInstanceId() + != Objects.requireNonNull(row.get("runtime_game_instance_id", Long.class)) + || !expected.sessionId().equals(row.get("session_id", String.class)) + || !expected.issuerId().equals(row.get("issuer_id", String.class)) + || !expected.issuerAuthGeneration().equals(readPositive(row, "issuer_auth_generation")) + || !expected + .playableStateNamespaceId() + .equals(row.get("playable_state_namespace_id", UUID.class)) + || !expected.characterId().equals(row.get("character_id", UUID.class)) + || !expected.playableStateScope().equals(row.get("playable_state_scope", String.class)) + || !expected.regionId().equals(row.get("region_id", UUID.class)) + || !expected.regionEpoch().equals(readPositive(row, "region_epoch")) + || !expected + .issuerIndexLayoutVersion() + .equals(readPositive(row, "issuer_index_layout_version")) + || !expected + .issuerIndexPartitionCount() + .equals(readPositive(row, "issuer_index_partition_count")) + || !expected + .issuerIndexPartitionCapacity() + .equals(readPositive(row, "issuer_index_partition_capacity")) + || !Arrays.equals(expected.bindingRef().bytes(), requireBytes(row, "binding_ref"))) { + throw conflict( + "Persisted issuer reservation owner differs from the exact candidate identity"); + } + return expected; + } + + private static AccountControlSnapshot readAndRequireAccountControl( + DSLContext transaction, + UUID accountId, + CanonicalGameplayAccountCoverageEvidence expectedEvidence) { + Record row = + transaction.fetchOne( + "SELECT * FROM " + ACCOUNT_CONTROL + " WHERE account_id = ?", accountId); + if (row == null) throw conflict("Current Account coverage control row is missing"); + AccountControlSnapshot current = AccountControlSnapshot.from(row, accountId); + if (!current.evidence().equals(expectedEvidence)) { + throw conflict("Current Account coverage control changed during ordinary NEW preparation"); + } + return current; + } + + private static void insertOperation( + DSLContext transaction, + CanonicalGameplayIssuerBindingLocalOperation.Request request, + CanonicalGameplayBindingTransitionRequest transitionRequest, + CanonicalGameplayBindingTransitionSnapshot prepared, + CanonicalIssuerPartitionReservation reservation, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof proof, + AccountControlSnapshot account, + UUID operationId, + IssuedCounters counters, + byte[] valueBytes, + String valueDigest) { + Object[] values = { + operationId, + request.requestId(), + request.transitionId(), + ISSUER, + transitionRequest.candidateAccountIndexFence(), + prepared.bindingRef().bytes(), + decimal(prepared.bindingGeneration()), + reservation.reservationId(), + reservation.reservationFence(), + decimal(reservation.partitionId()), + decimal(prepared.inventoryRevision()), + null, + null, + reservation.issuerCoverageOperationId(), + decimal(reservation.issuerCoverageOperationFence()), + decimal(reservation.coverageFence()), + decimal(reservation.inventorySnapshotRevision()), + anchor.bootstrapOperationId(), + anchor.bootstrapRequestId(), + anchor.buildOperationId(), + anchor.buildPlanDigest(), + decimal(anchor.controlEpoch()), + anchor.issuerCoverageOperationId(), + decimal(anchor.operationFence()), + decimal(anchor.coverageFence()), + decimal(anchor.issuerInventorySnapshotRevision()), + decimal(anchor.layoutVersion()), + decimal(anchor.partitionCount()), + decimal(anchor.partitionCapacity()), + anchor.mappingIdentity(), + anchor.layoutDescriptorBytes(), + anchor.layoutDescriptorDigest(), + decimal(anchor.issuerAuthGeneration()), + anchor.sourceCheckpointBytes(), + anchor.sourceCheckpointDigest(), + anchor.sourceEventBytes(), + anchor.sourceEventDigest(), + anchor.incarnationBytes(), + anchor.incarnationDigest(), + anchor.exactAnchorBytes(), + anchor.exactAnchorDigest(), + decimal(proof.partitionId()), + proof.exactPhysicalFieldSetBytes(), + proof.exactPhysicalFieldSetDigest(), + proof.physicalCountedCapacityCount(), + proof.physicalReservationCount(), + proof.physicalBindingCount(), + account.state(), + decimal(account.epoch()), + account.currentOperationId(), + account.currentFenceIntentId(), + decimalNullable(account.currentOperationFence()), + account.accountAdmissionFence(), + account.historicalAccountAdmissionFence(), + account.coverageFence(), + decimalNullable(account.inventorySnapshotRevision()), + decimalNullable(account.coverageGeneration()), + decimal(counters.operationFence()), + decimal(counters.localMemberGeneration()), + "ABSENT", + "ABSENT", + "PENDING_PHYSICAL_PROOF", + (short) 2, + valueBytes, + valueDigest + }; + String placeholders = String.join(",", java.util.Collections.nCopies(values.length, "?")); + transaction.execute( + "INSERT INTO " + + OPERATION + + " (" + + "operation_id, request_id, transition_id, issuer_id, candidate_account_index_fence," + + "binding_ref, binding_generation, reservation_id, reservation_fence, partition_id," + + "local_inventory_snapshot_revision, expected_prior_binding_ref, expected_prior_binding_generation," + + "original_issuer_coverage_operation_id, original_issuer_coverage_operation_fence," + + "original_coverage_fence, original_inventory_snapshot_revision," + + "anchor_bootstrap_operation_id, anchor_bootstrap_request_id, anchor_build_operation_id," + + "anchor_build_plan_digest, anchor_control_epoch, anchor_issuer_coverage_operation_id," + + "anchor_operation_fence, anchor_coverage_fence, anchor_issuer_inventory_snapshot_revision," + + "anchor_layout_version, anchor_partition_count, anchor_partition_capacity, anchor_mapping_identity," + + "anchor_layout_descriptor_bytes, anchor_layout_descriptor_digest, anchor_issuer_auth_generation," + + "anchor_source_checkpoint_bytes, anchor_source_checkpoint_digest, anchor_source_event_bytes," + + "anchor_source_event_digest, anchor_incarnation_bytes, anchor_incarnation_digest," + + "exact_anchor_bytes, exact_anchor_digest, baseline_partition_id, baseline_field_set_bytes," + + "baseline_field_set_digest, baseline_counted_capacity, baseline_reservation_count, baseline_binding_count," + + "account_control_state, account_control_epoch, account_current_operation_id," + + "account_current_fence_intent_id, account_current_operation_fence, account_admission_fence," + + "account_historical_admission_fence, account_coverage_fence, account_inventory_snapshot_revision," + + "account_coverage_generation, operation_fence, local_member_generation, expected_old_member_state," + + "expected_old_capacity_state, member_status, member_schema_version, member_value_bytes, member_value_digest)" + + " VALUES (" + + placeholders + + ")", + values); + } + + private static IssuedCounters allocateLocalCounters( + DSLContext transaction, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalIssuerPartitionReservation reservation) { + Record counter = + transaction.fetchOne( + "SELECT * FROM " + MEMBER_COUNTER + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (counter == null) { + Record priorBootstrapOperation = + transaction.fetchOne( + "SELECT 1 FROM " + BOOTSTRAP_MEMBER_OPERATION + " WHERE issuer_id = ? LIMIT 1", + ISSUER); + Record priorLocalOperation = + transaction.fetchOne( + "SELECT 1 FROM " + OPERATION + " WHERE issuer_id = ? LIMIT 1", ISSUER); + if (priorBootstrapOperation != null || priorLocalOperation != null) { + throw conflict("Issuer-local operation counter is missing after prior issuance"); + } + transaction.execute( + "INSERT INTO " + + MEMBER_COUNTER + + " (issuer_id, last_issued_operation_fence, last_issued_member_generation, counter_version)" + + " VALUES (?, 0, 0, 0) ON CONFLICT (issuer_id) DO NOTHING", + ISSUER); + counter = + transaction.fetchOne( + "SELECT * FROM " + MEMBER_COUNTER + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (counter == null) throw conflict("Issuer-local operation counter could not initialize"); + } + BigInteger previousFence = readNonNegative(counter, "last_issued_operation_fence"); + BigInteger previousGeneration = readNonNegative(counter, "last_issued_member_generation"); + Long versionValue = counter.get("counter_version", Long.class); + if (versionValue == null + || versionValue < 0 + || (versionValue == 0 && (previousFence.signum() != 0 || previousGeneration.signum() != 0)) + || (versionValue > 0 + && (!previousFence.add(BigInteger.ONE).equals(previousGeneration) + || previousFence.signum() <= 0))) { + throw conflict("Issuer-local member-operation counter state is malformed"); + } + BigInteger seed = + max( + anchor.controlEpoch(), + anchor.operationFence(), + anchor.coverageFence(), + anchor.issuerInventorySnapshotRevision(), + reservation.issuerCoverageOperationFence(), + reservation.coverageFence(), + reservation.inventorySnapshotRevision(), + reservation.inventoryRevision(), + previousFence, + previousGeneration); + BigInteger operationFence = seed.add(BigInteger.ONE); + BigInteger generation = operationFence.add(BigInteger.ONE); + requireCounterLimit(operationFence, "operationFence"); + requireCounterLimit(generation, "localMemberGeneration"); + long nextVersion; + try { + nextVersion = Math.addExact(versionValue, 1L); + } catch (ArithmeticException overflow) { + throw conflict("Issuer-local member-operation counter version is exhausted"); + } + Record updated = + transaction.fetchOne( + "UPDATE " + + MEMBER_COUNTER + + " SET last_issued_operation_fence = ?, last_issued_member_generation = ?, counter_version = ?" + + " WHERE issuer_id = ? AND last_issued_operation_fence = ?" + + " AND last_issued_member_generation = ? AND counter_version = ? RETURNING issuer_id", + decimal(operationFence), + decimal(generation), + nextVersion, + ISSUER, + decimal(previousFence), + decimal(previousGeneration), + versionValue); + if (updated == null) throw conflict("Issuer-local operation counter compare-and-set lost"); + return new IssuedCounters(operationFence, generation); + } + + private static void requireSameStoredOperation( + Record row, + CanonicalGameplayIssuerBindingLocalOperation.Request request, + CanonicalGameplayBindingTransitionSnapshot prepared, + CanonicalIssuerPartitionReservation reservation, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof proof, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState, + AccountControlSnapshot account) { + CanonicalGameplayIssuerMemberV2Value storedMemberValue; + try { + storedMemberValue = + CanonicalGameplayIssuerMemberV2Codec.decode(requireBytes(row, "member_value_bytes")); + } catch (RuntimeException malformed) { + throw conflict("Stored local operation does not contain a canonical v2 member"); + } + if (!requireUuid(row, "request_id").equals(request.requestId()) + || !requireUuid(row, "transition_id").equals(request.transitionId()) + || !ISSUER.equals(requireText(row, "issuer_id")) + || !requireUuid(row, "candidate_account_index_fence") + .equals(prepared.candidateAccountIndexFence()) + || !Arrays.equals(requireBytes(row, "binding_ref"), prepared.bindingRef().bytes()) + || !readPositive(row, "binding_generation").equals(prepared.bindingGeneration()) + || !requireUuid(row, "reservation_id").equals(reservation.reservationId()) + || !requireUuid(row, "reservation_fence").equals(reservation.reservationFence()) + || !readNonNegative(row, "partition_id").equals(reservation.partitionId()) + || row.get("expected_prior_binding_ref", byte[].class) != null + || row.get("expected_prior_binding_generation") != null + || !requireUuid(row, "original_issuer_coverage_operation_id") + .equals(reservation.issuerCoverageOperationId()) + || !readPositive(row, "original_issuer_coverage_operation_fence") + .equals(reservation.issuerCoverageOperationFence()) + || !readPositive(row, "original_coverage_fence").equals(reservation.coverageFence()) + || !readPositive(row, "original_inventory_snapshot_revision") + .equals(reservation.inventorySnapshotRevision()) + || !requireUuid(row, "anchor_bootstrap_operation_id").equals(anchor.bootstrapOperationId()) + || !requireUuid(row, "anchor_bootstrap_request_id").equals(anchor.bootstrapRequestId()) + || !requireUuid(row, "anchor_build_operation_id").equals(anchor.buildOperationId()) + || !anchor.buildPlanDigest().equals(requireText(row, "anchor_build_plan_digest")) + || !readPositive(row, "anchor_control_epoch").equals(anchor.controlEpoch()) + || !requireUuid(row, "anchor_issuer_coverage_operation_id") + .equals(anchor.issuerCoverageOperationId()) + || !readPositive(row, "anchor_operation_fence").equals(anchor.operationFence()) + || !readPositive(row, "anchor_coverage_fence").equals(anchor.coverageFence()) + || !readPositive(row, "anchor_issuer_inventory_snapshot_revision") + .equals(anchor.issuerInventorySnapshotRevision()) + || !readPositive(row, "anchor_layout_version").equals(anchor.layoutVersion()) + || !readPositive(row, "anchor_partition_count").equals(anchor.partitionCount()) + || !readPositive(row, "anchor_partition_capacity").equals(anchor.partitionCapacity()) + || !anchor.mappingIdentity().equals(requireText(row, "anchor_mapping_identity")) + || !Arrays.equals( + requireBytes(row, "anchor_layout_descriptor_bytes"), anchor.layoutDescriptorBytes()) + || !anchor + .layoutDescriptorDigest() + .equals(requireText(row, "anchor_layout_descriptor_digest")) + || !readPositive(row, "anchor_issuer_auth_generation").equals(anchor.issuerAuthGeneration()) + || !Arrays.equals( + requireBytes(row, "anchor_source_checkpoint_bytes"), anchor.sourceCheckpointBytes()) + || !anchor + .sourceCheckpointDigest() + .equals(requireText(row, "anchor_source_checkpoint_digest")) + || !Arrays.equals( + optionalBytes(row, "anchor_source_event_bytes"), anchor.sourceEventBytes()) + || !Objects.equals( + row.get("anchor_source_event_digest", String.class), anchor.sourceEventDigest()) + || !Arrays.equals(requireBytes(row, "anchor_incarnation_bytes"), anchor.incarnationBytes()) + || !anchor.incarnationDigest().equals(requireText(row, "anchor_incarnation_digest")) + || !Arrays.equals(requireBytes(row, "exact_anchor_bytes"), anchor.exactAnchorBytes()) + || !anchor.exactAnchorDigest().equals(requireText(row, "exact_anchor_digest")) + || !readNonNegative(row, "baseline_partition_id").equals(proof.partitionId()) + || !Arrays.equals( + requireBytes(row, "baseline_field_set_bytes"), proof.exactPhysicalFieldSetBytes()) + || !proof + .exactPhysicalFieldSetDigest() + .equals(requireText(row, "baseline_field_set_digest")) + || readInt(row, "baseline_counted_capacity") != proof.physicalCountedCapacityCount() + || readInt(row, "baseline_reservation_count") != proof.physicalReservationCount() + || readInt(row, "baseline_binding_count") != proof.physicalBindingCount() + || !Arrays.equals( + anchor.incarnationBytes(), + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(currentState.incarnation())) + || !account.equals( + AccountControlSnapshot.fromOperation(row, request.candidate().accountId())) + || !readPositive(row, "local_inventory_snapshot_revision") + .equals(storedMemberValue.reservation().inventoryRevision()) + || !readPositive(row, "local_inventory_snapshot_revision") + .equals(prepared.inventoryRevision()) + || !"ABSENT".equals(requireText(row, "expected_old_member_state")) + || !"ABSENT".equals(requireText(row, "expected_old_capacity_state")) + || !"PENDING_PHYSICAL_PROOF".equals(requireText(row, "member_status")) + || !Objects.equals(row.get("member_schema_version", Short.class), (short) 2)) { + throw conflict( + "Stored ordinary NEW operation differs from its current exact anchor, Account, or reservation"); + } + } + + private static void requireCallerRequestMatches( + Record row, CanonicalGameplayIssuerBindingLocalOperation.Request request) { + if (!request.requestId().equals(requireUuid(row, "request_id")) + || !request.transitionId().equals(requireUuid(row, "transition_id")) + || !ISSUER.equals(requireText(row, "issuer_id")) + || !Arrays.equals( + requireBytes(row, "binding_ref"), request.candidate().bindingRef().bytes()) + || request.expectedPriorBindingRef() != null + || request.expectedPriorBindingGeneration() != null) { + throw conflict("Stored local issuer operation is not an ordinary NEW transition"); + } + CanonicalGameplayIssuerMemberV2Value storedValue; + try { + storedValue = + CanonicalGameplayIssuerMemberV2Codec.decode(requireBytes(row, "member_value_bytes")); + } catch (RuntimeException malformed) { + throw conflict("Stored local issuer operation has a malformed candidate identity"); + } + if (!storedValue.owner().equals(request.candidate()) + || !storedValue.reservation().transitionId().equals(request.transitionId())) { + throw conflict("Same request or transition identity was retried with a different candidate"); + } + } + + private static CanonicalIssuerReservationFenceEvidence readOriginalReservationEvidence( + Record operationRow) { + return new CanonicalIssuerReservationFenceEvidence( + requireUuid(operationRow, "reservation_id"), + requireUuid(operationRow, "reservation_fence"), + requireUuid(operationRow, "original_issuer_coverage_operation_id"), + readPositive(operationRow, "original_issuer_coverage_operation_fence"), + readPositive(operationRow, "original_coverage_fence"), + readPositive(operationRow, "original_inventory_snapshot_revision")); + } + + private static void requireCandidateMatchesAnchor( + CanonicalGameplayBindingIdentity candidate, CanonicalGameplayIssuerInstalledAnchor anchor) { + if (!ISSUER.equals(candidate.issuerId()) + || !candidate.issuerId().equals(anchor.issuerId()) + || !candidate.issuerAuthGeneration().equals(anchor.issuerAuthGeneration()) + || !candidate.issuerIndexLayoutVersion().equals(anchor.layoutVersion()) + || !candidate.issuerIndexPartitionCount().equals(anchor.partitionCount()) + || !candidate.issuerIndexPartitionCapacity().equals(anchor.partitionCapacity())) { + throw conflict("Caller candidate differs from the exact installed issuer source or layout"); + } + } + + private static boolean sameCurrentIssuerState( + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState left, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState right) { + var leftCheckpoint = left.accountCheckpoint(); + var rightCheckpoint = right.accountCheckpoint(); + return leftCheckpoint.issuerId().equals(rightCheckpoint.issuerId()) + && leftCheckpoint.issuerAuthGeneration().equals(rightCheckpoint.issuerAuthGeneration()) + && Arrays.equals( + leftCheckpoint.exactCheckpointBytes(), rightCheckpoint.exactCheckpointBytes()) + && leftCheckpoint.checkpointDigest().equals(rightCheckpoint.checkpointDigest()) + && Arrays.equals( + leftCheckpoint.latestIssuerEventBytes(), rightCheckpoint.latestIssuerEventBytes()) + && Objects.equals( + leftCheckpoint.latestIssuerEventDigest(), rightCheckpoint.latestIssuerEventDigest()) + && Arrays.equals( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(left.incarnation()), + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(right.incarnation())); + } + + private static boolean operationRequestExists(DSLContext transaction, UUID transitionId) { + return transaction.fetchOne( + "SELECT 1 FROM " + OPERATION + " WHERE issuer_id = ? AND transition_id = ?", + ISSUER, + transitionId) + != null; + } + + private static UUID freshOperationId( + CanonicalGameplayIssuerBindingLocalOperation.Request request, + CanonicalIssuerPartitionReservation reservation, + CanonicalGameplayIssuerInstalledAnchor anchor) { + UUID result; + do { + result = freshNonNilUuid(); + } while (result.equals(request.requestId()) + || result.equals(request.transitionId()) + || result.equals(reservation.reservationId()) + || result.equals(reservation.reservationFence()) + || result.equals(anchor.bootstrapOperationId()) + || result.equals(anchor.bootstrapRequestId()) + || result.equals(anchor.buildOperationId())); + return result; + } + + private static UUID freshNonNilUuid() { + UUID value; + do { + value = UUID.randomUUID(); + } while (value.equals(new UUID(0L, 0L))); + return value; + } + + private static BigInteger max(BigInteger... values) { + BigInteger result = BigInteger.ZERO; + for (BigInteger value : values) if (value.compareTo(result) > 0) result = value; + return result; + } + + private static void requireCounterLimit(BigInteger value, String name) { + if (value.signum() <= 0 || value.toString().length() > 256) { + throw conflict(name + " exceeds the bounded local issuer counter range"); + } + } + + private static BigDecimal decimal(BigInteger value) { + return new BigDecimal(value); + } + + private static BigDecimal decimalNullable(BigInteger value) { + return value == null ? null : decimal(value); + } + + private static BigInteger readPositive(Record row, String field) { + BigInteger value = readNonNegative(row, field); + if (value.signum() <= 0) throw conflict(field + " must be positive"); + return value; + } + + private static BigInteger readNonNegative(Record row, String field) { + Object value = row.get(field); + if (!(value instanceof Number number)) throw conflict(field + " is missing or nonnumeric"); + BigInteger integer; + try { + integer = + number instanceof BigDecimal decimal + ? decimal.toBigIntegerExact() + : BigInteger.valueOf(number.longValue()); + } catch (ArithmeticException malformed) { + throw conflict(field + " is not an exact integer"); + } + if (integer.signum() < 0 || integer.toString().length() > 256) + throw conflict(field + " is outside its bounded counter range"); + return integer; + } + + private static int readInt(Record row, String field) { + try { + return readNonNegative(row, field).intValueExact(); + } catch (ArithmeticException malformed) { + throw conflict(field + " exceeds its exact integer range"); + } + } + + private static UUID requireUuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null) throw conflict(field + " is missing"); + return value; + } + + private static String requireText(Record row, String field) { + String value = row.get(field, String.class); + if (value == null) throw conflict(field + " is missing"); + return value; + } + + private static byte[] requireBytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + if (value == null || value.length == 0) throw conflict(field + " is missing or empty"); + return value; + } + + private static byte[] optionalBytes(Record row, String field) { + return row.get(field, byte[].class); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw conflict("Issuer local-operation owner cannot join an ambient SQL transaction"); + } + } + + private static IllegalStateException conflict(String message) { + return new IllegalStateException(message); + } + + private record IssuedCounters(BigInteger operationFence, BigInteger localMemberGeneration) {} + + private record AccountControlSnapshot( + String state, + BigInteger epoch, + UUID currentOperationId, + UUID currentFenceIntentId, + BigInteger currentOperationFence, + UUID accountAdmissionFence, + UUID historicalAccountAdmissionFence, + UUID coverageFence, + BigInteger inventorySnapshotRevision, + BigInteger coverageGeneration, + CanonicalGameplayAccountCoverageEvidence evidence) { + private static AccountControlSnapshot from(Record row, UUID accountId) { + String state = requireText(row, "state"); + BigInteger epoch = readNonNegative(row, "last_operation_fence"); + UUID operationId = row.get("current_operation_id", UUID.class); + UUID intentId = row.get("current_fence_intent_id", UUID.class); + BigInteger operationFence = nullableInteger(row, "current_operation_fence"); + UUID admissionFence = row.get("account_admission_fence", UUID.class); + UUID historicalFence = row.get("historical_account_admission_fence", UUID.class); + UUID coverageFence = row.get("coverage_fence", UUID.class); + BigInteger inventoryRevision = nullableInteger(row, "inventory_snapshot_revision"); + BigInteger coverageGeneration = nullableInteger(row, "coverage_generation"); + CanonicalGameplayAccountCoverageEvidence evidence; + if ("NO_ACTIVE_ACCOUNT_WIDE_FLOW".equals(state)) { + if (operationId != null + || intentId != null + || operationFence != null + || admissionFence != null + || historicalFence != null + || coverageFence != null + || inventoryRevision != null + || coverageGeneration != null) { + throw conflict("No-active Account control tuple contains active fence fields"); + } + evidence = CanonicalGameplayAccountCoverageEvidence.noActiveFlow(); + return new AccountControlSnapshot( + state, epoch, null, null, null, null, null, null, null, null, evidence); + } else if ("HISTORICAL".equals(state)) { + if (operationId == null + || intentId != null + || operationFence == null + || admissionFence != null + || historicalFence == null + || coverageFence == null + || inventoryRevision == null + || coverageGeneration == null) { + throw conflict("Historical Account control tuple is incomplete"); + } + evidence = + CanonicalGameplayAccountCoverageEvidence.historical( + operationId, + operationFence, + historicalFence, + coverageFence, + accountId, + inventoryRevision, + coverageGeneration); + return new AccountControlSnapshot( + state, + epoch, + operationId, + null, + operationFence, + null, + historicalFence, + coverageFence, + inventoryRevision, + coverageGeneration, + evidence); + } else { + throw conflict("Active or unknown Account control state blocks ordinary NEW"); + } + } + + private static AccountControlSnapshot fromOperation(Record row, UUID accountId) { + String state = requireText(row, "account_control_state"); + BigInteger epoch = readNonNegative(row, "account_control_epoch"); + UUID operationId = row.get("account_current_operation_id", UUID.class); + UUID intentId = row.get("account_current_fence_intent_id", UUID.class); + BigInteger operationFence = nullableInteger(row, "account_current_operation_fence"); + UUID admissionFence = row.get("account_admission_fence", UUID.class); + UUID historicalFence = row.get("account_historical_admission_fence", UUID.class); + UUID coverageFence = row.get("account_coverage_fence", UUID.class); + BigInteger inventoryRevision = nullableInteger(row, "account_inventory_snapshot_revision"); + BigInteger coverageGeneration = nullableInteger(row, "account_coverage_generation"); + CanonicalGameplayAccountCoverageEvidence evidence; + if ("NO_ACTIVE_ACCOUNT_WIDE_FLOW".equals(state)) { + if (operationId != null + || intentId != null + || operationFence != null + || admissionFence != null + || historicalFence != null + || coverageFence != null + || inventoryRevision != null + || coverageGeneration != null) { + throw conflict("Stored no-active Account tuple contains active fence fields"); + } + evidence = CanonicalGameplayAccountCoverageEvidence.noActiveFlow(); + return new AccountControlSnapshot( + state, epoch, null, null, null, null, null, null, null, null, evidence); + } else if ("HISTORICAL".equals(state)) { + if (operationId == null + || intentId != null + || operationFence == null + || admissionFence != null + || historicalFence == null + || coverageFence == null + || inventoryRevision == null + || coverageGeneration == null) { + throw conflict("Stored historical Account control tuple is incomplete"); + } + evidence = + CanonicalGameplayAccountCoverageEvidence.historical( + operationId, + operationFence, + historicalFence, + coverageFence, + accountId, + inventoryRevision, + coverageGeneration); + return new AccountControlSnapshot( + state, + epoch, + operationId, + null, + operationFence, + null, + historicalFence, + coverageFence, + inventoryRevision, + coverageGeneration, + evidence); + } else { + throw conflict("Stored operation has an active or unknown Account control state"); + } + } + } + + private static BigInteger nullableInteger(Record row, String field) { + Object value = row.get(field); + if (value == null) return null; + if (!(value instanceof Number number)) throw conflict(field + " is not numeric"); + try { + BigInteger result = + number instanceof BigDecimal decimal + ? decimal.toBigIntegerExact() + : BigInteger.valueOf(number.longValue()); + if (result.signum() < 0) throw conflict(field + " must be nonnegative"); + return result; + } catch (ArithmeticException malformed) { + throw conflict(field + " is not an exact integer"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java new file mode 100644 index 0000000000..0bee2ba31c --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java @@ -0,0 +1,1114 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Read-only SQL owner for a current, complete one-partition view of ordinary local issuer work. */ +final class CanonicalGameplayIssuerBindingLocalProjectionRepository { + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String LOCAL_OPERATION = + "game_session_canonical_issuer_binding_local_operation"; + private static final String BOOTSTRAP_OPERATION = + "game_session_canonical_issuer_bootstrap_member_operation"; + private static final String RESERVATION = "game_session_canonical_issuer_partition_reservation"; + private static final String INVENTORY = "game_session_canonical_gameplay_binding_inventory"; + private static final String TRANSITION = "game_session_canonical_binding_transition"; + private static final String ISSUER_OBLIGATION = + "game_session_canonical_binding_issuer_index_obligation"; + private static final String ACCOUNT_CONTROL = "game_session_canonical_account_coverage_control"; + private static final String INVENTORY_CLOCK = "game_session_canonical_binding_inventory_clock"; + private static final int MAX_LOCAL_OPERATIONS_PER_PARTITION = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_MEMBER_OPERATIONS; + + private final DSLContext dsl; + private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentIssuerStateSource; + + CanonicalGameplayIssuerBindingLocalProjectionRepository( + DSLContext dsl, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentIssuerStateSource) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.currentIssuerStateSource = + Objects.requireNonNull(currentIssuerStateSource, "currentIssuerStateSource"); + } + + /** + * Reads only from the installed-anchor owner, the ordinary NEW SQL operation owner, and its + * current V29 rows. There is deliberately no constructor that accepts caller-supplied members. + */ + PreparedPartitionWork readPreparedPartitionWork( + CanonicalGameplayIssuerBindingLocalOperation target) { + Objects.requireNonNull(target, "target"); + requireNoAmbientTransaction(); + var before = readCurrentIssuerState(); + requireCurrentSourceMatches(target.anchor(), before); + PreparedPartitionWork work = + dsl.transactionResult( + configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + lockInventoryClock(transaction); + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, before); + requireSameAnchor(target.anchor(), anchor); + return prepareInTransaction(transaction, target, anchor); + }); + var after = readCurrentIssuerState(); + requireSameCurrentIssuerState(before, after); + requireCurrentSourceMatches(work.anchor(), after); + return work; + } + + /** Re-reads the durable set and all currentness inputs after the Redis round trip. */ + void requireStillCurrent(PreparedPartitionWork expected) { + Objects.requireNonNull(expected, "expected"); + PreparedPartitionWork current = readPreparedPartitionWork(expected.targetOperation()); + if (!Arrays.equals(expected.sqlCurrentnessDigest(), current.sqlCurrentnessDigest())) { + throw unavailable( + "The registered issuer member set or current SQL phase changed during projection"); + } + } + + private PreparedPartitionWork prepareInTransaction( + DSLContext transaction, + CanonicalGameplayIssuerBindingLocalOperation target, + CanonicalGameplayIssuerInstalledAnchor anchor) { + BigInteger targetPartition = target.reservation().partitionId(); + CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof + targetBaseline = + CanonicalGameplayIssuerBootstrapCoverageRepository.readInstalledAnchorPartitionProof( + transaction, anchor, targetPartition); + Map targetBaselineFields = + CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( + targetBaseline.exactPhysicalFieldSetBytes()); + requireQualifiedBaseline(anchor, targetBaseline, targetBaselineFields); + + List operationRows = + transaction.fetch( + "SELECT * FROM " + + LOCAL_OPERATION + + " WHERE issuer_id = ? ORDER BY operation_fence, operation_id", + ISSUER); + List entries = new ArrayList<>(operationRows.size()); + Set localReservationIds = new HashSet<>(); + Set localBindingRefs = new HashSet<>(); + Set localOperationIds = new HashSet<>(); + Map< + BigInteger, + CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof> + proofsByPartition = new HashMap<>(); + proofsByPartition.put(targetPartition, targetBaseline); + + int partitionLocalOperationCount = 0; + BigInteger localAggregateCapacity = BigInteger.ZERO; + BigInteger localPartitionCapacity = BigInteger.ZERO; + boolean foundTarget = false; + for (Record row : operationRows) { + LocalEntry entry = readLocalEntry(transaction, row, anchor, target); + if (!localOperationIds.add(entry.operationId()) + || !localReservationIds.add(entry.memberValue().reservation().reservationId()) + || !localBindingRefs.add( + new String( + entry.memberValue().owner().bindingRef().bytes(), StandardCharsets.UTF_8))) { + throw unavailable("The registered local issuer operations contain duplicate identities"); + } + BigInteger partitionId = entry.memberValue().reservation().partitionId(); + var baseline = proofsByPartition.get(partitionId); + if (baseline == null) { + baseline = + CanonicalGameplayIssuerBootstrapCoverageRepository.readInstalledAnchorPartitionProof( + transaction, anchor, partitionId); + proofsByPartition.put(partitionId, baseline); + Map baselineFields = + CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( + baseline.exactPhysicalFieldSetBytes()); + requireQualifiedBaseline(anchor, baseline, baselineFields); + } + CanonicalGameplayIssuerBootstrapCoverageRepository.requireNewMemberAbsentFromBaseline( + baseline, + entry.memberValue().owner().bindingRef(), + entry.memberValue().reservation().reservationId()); + if (partitionId.equals(targetPartition)) { + partitionLocalOperationCount++; + if (entry.countsTowardCapacity()) + localPartitionCapacity = localPartitionCapacity.add(BigInteger.ONE); + } + if (entry.countsTowardCapacity()) + localAggregateCapacity = localAggregateCapacity.add(BigInteger.ONE); + if (entry.operationId().equals(target.operationId())) { + if (!Arrays.equals(entry.exactMemberValueBytes(), target.exactMemberValueBytes()) + || !entry.memberValue().equals(target.memberValue()) + || !targetPartition.equals(partitionId)) { + throw unavailable("The requested operation differs from its current SQL registration"); + } + foundTarget = true; + } + entries.add(entry); + } + if (!foundTarget) + throw unavailable("The requested ordinary NEW operation is not durably registered"); + if (partitionLocalOperationCount > MAX_LOCAL_OPERATIONS_PER_PARTITION) { + throw unavailable("The local partition operation set exceeds the physical owner bound"); + } + + Set baselineReservationIds = readAndVerifyBootstrapReservationIds(transaction, anchor); + if (baselineReservationIds.size() != anchor.physicalReservationCount()) { + throw unavailable("The installed baseline reservation cohort is incomplete"); + } + Set expectedReservationIds = new HashSet<>(baselineReservationIds); + for (UUID reservationId : localReservationIds) { + if (!expectedReservationIds.add(reservationId)) { + throw unavailable( + "A post-baseline issuer operation reuses an installed reservation identity"); + } + } + Set currentReservationIds = readCurrentReservationIds(transaction); + if (!currentReservationIds.equals(expectedReservationIds)) { + throw unavailable( + "Durable issuer reservations differ from the installed baseline and registered local set"); + } + + BigInteger aggregateCapacity = anchor.aggregateCountedCapacity().add(localAggregateCapacity); + BigInteger aggregateBound = anchor.partitionCount().multiply(anchor.partitionCapacity()); + BigInteger partitionCapacity = + BigInteger.valueOf(targetBaseline.physicalCountedCapacityCount()) + .add(localPartitionCapacity); + if (partitionCapacity.compareTo(anchor.partitionCapacity()) > 0 + || aggregateCapacity.compareTo(aggregateBound) > 0) { + throw unavailable( + "Current SQL issuer reservations exceed the pinned partition or aggregate capacity"); + } + + LocalEntry targetEntry = + entries.stream() + .filter(entry -> entry.operationId().equals(target.operationId())) + .findFirst() + .orElseThrow(() -> unavailable("The requested operation disappeared from its SQL set")); + Map allowedFields = new HashMap<>(targetBaselineFields); + for (LocalEntry entry : entries) { + if (!entry.memberValue().reservation().partitionId().equals(targetPartition)) continue; + putUnique( + allowedFields, + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + entry.memberValue().reservation().reservationId()), + entry.exactMemberValueBytes()); + if (entry.bindingPresent()) { + putUnique( + allowedFields, + new String(entry.memberValue().owner().bindingRef().bytes(), StandardCharsets.UTF_8), + entry.exactMemberValueBytes()); + } + } + if (allowedFields.size() + > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_HASH_FIELDS + + 2 * MAX_LOCAL_OPERATIONS_PER_PARTITION + || totalFieldBytes(allowedFields) + > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_TOTAL_HASH_BYTES) { + throw unavailable("The prepared local issuer partition exceeds its bounded field set"); + } + byte[] currentnessDigest = + currentnessDigest( + anchor, + targetBaseline.exactPhysicalFieldSetBytes(), + entries, + currentReservationIds, + aggregateCapacity, + partitionCapacity); + return new PreparedPartitionWork( + anchor, + target, + targetBaseline, + targetBaselineFields, + allowedFields, + entries, + targetEntry, + aggregateCapacity, + aggregateBound, + partitionCapacity, + currentnessDigest); + } + + private LocalEntry readLocalEntry( + DSLContext transaction, + Record row, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBindingLocalOperation target) { + if (!ISSUER.equals(text(row, "issuer_id")) + || !"PENDING_PHYSICAL_PROOF".equals(text(row, "member_status")) + || !Objects.equals(row.get("member_schema_version", Short.class), (short) 2) + || !"ABSENT".equals(text(row, "expected_old_capacity_state")) + || !"ABSENT".equals(text(row, "expected_old_member_state")) + || row.get("expected_prior_binding_ref", byte[].class) != null + || row.get("expected_prior_binding_generation") != null) { + throw unavailable("A durable local issuer operation is malformed or not an ordinary NEW"); + } + byte[] exactValue = bytes(row, "member_value_bytes"); + String valueDigest = text(row, "member_value_digest"); + if (!valueDigest.equals(CanonicalGameplayIssuerMemberV2Codec.sha256(exactValue))) { + throw unavailable("A durable local issuer member digest does not match its exact bytes"); + } + CanonicalGameplayIssuerMemberV2Value member; + try { + member = CanonicalGameplayIssuerMemberV2Codec.decode(exactValue); + } catch (RuntimeException malformed) { + throw unavailable("A durable local issuer operation is not closed schema v2", malformed); + } + UUID operationId = uuid(row, "operation_id"); + BigInteger operationFence = positive(row, "operation_fence"); + BigInteger localGeneration = positive(row, "local_member_generation"); + if (operationId.equals(target.operationId()) + && (!uuid(row, "request_id").equals(target.request().requestId()) + || !uuid(row, "transition_id").equals(target.request().transitionId()) + || !uuid(row, "candidate_account_index_fence") + .equals(target.candidateAccountIndexFence()) + || !operationFence.equals(target.operationFence()) + || !localGeneration.equals(target.localMemberGeneration()))) { + throw unavailable( + "The requested local issuer operation identity differs from its current SQL row"); + } + CanonicalIssuerPartitionReservation reservation = member.reservation(); + if (reservation.lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RESERVED + || !operationId.equals(member.memberOperation().operationId()) + || !operationFence.equals(member.memberOperation().operationFence()) + || !localGeneration.equals(member.memberOperation().coverageGeneration()) + || !bytesEqual(row, "binding_ref", member.owner().bindingRef().bytes()) + || !positive(row, "binding_generation").equals(member.bindingGeneration()) + || !uuid(row, "transition_id").equals(reservation.transitionId()) + || !uuid(row, "reservation_id").equals(reservation.reservationId()) + || !uuid(row, "reservation_fence").equals(reservation.reservationFence()) + || !nonnegative(row, "partition_id").equals(reservation.partitionId()) + || !positive(row, "local_inventory_snapshot_revision") + .equals(reservation.inventoryRevision()) + || !uuid(row, "original_issuer_coverage_operation_id") + .equals(reservation.issuerCoverageOperationId()) + || !positive(row, "original_issuer_coverage_operation_fence") + .equals(reservation.issuerCoverageOperationFence()) + || !positive(row, "original_coverage_fence").equals(reservation.coverageFence()) + || !positive(row, "original_inventory_snapshot_revision") + .equals(reservation.inventorySnapshotRevision()) + || !member.anchor().issuerCoverageOperationId().equals(anchor.issuerCoverageOperationId()) + || !member.anchor().operationFence().equals(anchor.operationFence()) + || !member.anchor().coverageFence().equals(anchor.coverageFence()) + || !member + .anchor() + .issuerInventorySnapshotRevision() + .equals(anchor.issuerInventorySnapshotRevision()) + || !member.owner().issuerId().equals(anchor.issuerId()) + || !Arrays.equals( + member.layoutDescriptor().exactDescriptorBytes(), anchor.layoutDescriptorBytes()) + || !Arrays.equals( + member.sourceCheckpoint().exactCheckpointBytes(), anchor.sourceCheckpointBytes()) + || !Arrays.equals( + member.sourceCheckpoint().latestIssuerEventBytes(), anchor.sourceEventBytes()) + || !Arrays.equals( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(member.incarnation()), + anchor.incarnationBytes()) + || !Arrays.equals(bytes(row, "exact_anchor_bytes"), anchor.exactAnchorBytes()) + || !text(row, "exact_anchor_digest").equals(anchor.exactAnchorDigest()) + || !bytesEqual(row, "anchor_layout_descriptor_bytes", anchor.layoutDescriptorBytes()) + || !text(row, "anchor_layout_descriptor_digest").equals(anchor.layoutDescriptorDigest()) + || !bytesEqual(row, "anchor_source_checkpoint_bytes", anchor.sourceCheckpointBytes()) + || !text(row, "anchor_source_checkpoint_digest").equals(anchor.sourceCheckpointDigest()) + || !nullableBytesEqual(row, "anchor_source_event_bytes", anchor.sourceEventBytes()) + || !Objects.equals( + row.get("anchor_source_event_digest", String.class), anchor.sourceEventDigest()) + || !bytesEqual(row, "anchor_incarnation_bytes", anchor.incarnationBytes()) + || !text(row, "anchor_incarnation_digest").equals(anchor.incarnationDigest()) + || !text(row, "baseline_field_set_digest") + .equals( + CanonicalGameplayIssuerMemberV2Codec.sha256( + bytes(row, "baseline_field_set_bytes")))) { + throw unavailable( + "A durable local issuer operation differs from its original reservation or installed anchor"); + } + requireAnchorColumns(row, anchor); + + var baseline = + CanonicalGameplayIssuerBootstrapCoverageRepository.readInstalledAnchorPartitionProof( + transaction, anchor, reservation.partitionId()); + if (!Arrays.equals( + bytes(row, "baseline_field_set_bytes"), baseline.exactPhysicalFieldSetBytes()) + || !nonnegative(row, "baseline_partition_id").equals(baseline.partitionId()) + || integer(row, "baseline_counted_capacity") != baseline.physicalCountedCapacityCount() + || integer(row, "baseline_reservation_count") != baseline.physicalReservationCount() + || integer(row, "baseline_binding_count") != baseline.physicalBindingCount()) { + throw unavailable( + "A durable local issuer operation no longer links to its exact immutable baseline partition"); + } + + Record reservationRow = + transaction.fetchOne( + "SELECT * FROM " + RESERVATION + " WHERE reservation_id = ?", + reservation.reservationId()); + Record inventoryRow = + transaction.fetchOne( + "SELECT * FROM " + INVENTORY + " WHERE binding_ref = ?", + member.owner().bindingRef().bytes()); + Record transitionRow = + transaction.fetchOne( + "SELECT * FROM " + TRANSITION + " WHERE transition_id = ?", reservation.transitionId()); + Record issuerObligation = + transaction.fetchOne( + "SELECT * FROM " + ISSUER_OBLIGATION + " WHERE transition_id = ? AND binding_ref = ?", + reservation.transitionId(), + member.owner().bindingRef().bytes()); + if (reservationRow == null + || inventoryRow == null + || transitionRow == null + || issuerObligation == null) { + throw unavailable("The local issuer operation is missing its current V29 source rows"); + } + CurrentPhase phase = + verifyCurrentSourceRows( + row, member, reservationRow, inventoryRow, transitionRow, issuerObligation); + requireAccountControlCurrent(transaction, row, member.owner().accountId()); + return new LocalEntry( + operationId, + exactValue, + member, + phase.bindingPresent(), + phase.countsTowardCapacity(), + phase.lifecycle(), + phase.transitionStatus(), + phase.inventoryRevision()); + } + + private static CurrentPhase verifyCurrentSourceRows( + Record operationRow, + CanonicalGameplayIssuerMemberV2Value member, + Record reservationRow, + Record inventoryRow, + Record transitionRow, + Record issuerObligation) { + CanonicalGameplayBindingIdentity owner = member.owner(); + CanonicalIssuerPartitionReservation original = member.reservation(); + requireOwnerColumns(reservationRow, owner, original.partitionId(), "partition_id"); + requireOwnerColumns(inventoryRow, owner, original.partitionId(), "issuer_partition_id"); + BigInteger currentBindingGeneration = positive(inventoryRow, "binding_generation"); + String candidateLifecycle = text(inventoryRow, "lifecycle"); + String transitionStatus = text(transitionRow, "status"); + String reservationLifecycle = text(reservationRow, "lifecycle"); + BigInteger currentReservationRevision = positive(reservationRow, "inventory_revision"); + if (!uuid(reservationRow, "reservation_id").equals(original.reservationId()) + || !uuid(reservationRow, "transition_id").equals(original.transitionId()) + || !uuid(reservationRow, "reservation_fence").equals(original.reservationFence()) + || !uuid(reservationRow, "issuer_coverage_operation_id") + .equals(original.issuerCoverageOperationId()) + || !positive(reservationRow, "issuer_coverage_operation_fence") + .equals(original.issuerCoverageOperationFence()) + || !positive(reservationRow, "coverage_fence").equals(original.coverageFence()) + || !positive(reservationRow, "inventory_snapshot_revision") + .equals(original.inventorySnapshotRevision()) + || currentReservationRevision.compareTo(original.inventoryRevision()) < 0 + || !bytesEqual(reservationRow, "binding_ref", owner.bindingRef().bytes()) + || !currentBindingGeneration.equals(member.bindingGeneration()) + || !positive(inventoryRow, "inventory_revision") + .equals(positive(transitionRow, "inventory_revision")) + || !uuid(transitionRow, "transition_id").equals(original.transitionId()) + || !bytesEqual(transitionRow, "candidate_binding_ref", owner.bindingRef().bytes()) + || !uuid(transitionRow, "tenant_id").equals(owner.tenantId()) + || !uuid(transitionRow, "playable_state_namespace_id") + .equals(owner.playableStateNamespaceId()) + || !uuid(transitionRow, "character_id").equals(owner.characterId()) + || !positive(transitionRow, "candidate_binding_generation") + .equals(member.bindingGeneration()) + || !uuid(transitionRow, "candidate_account_index_fence") + .equals(uuid(operationRow, "candidate_account_index_fence")) + || !uuid(transitionRow, "issuer_reservation_id").equals(original.reservationId()) + || !uuid(inventoryRow, "transition_id").equals(original.transitionId()) + || !uuid(inventoryRow, "account_index_fence") + .equals(uuid(operationRow, "candidate_account_index_fence")) + || !uuid(inventoryRow, "issuer_reservation_id").equals(original.reservationId()) + || transitionRow.get("expected_prior_binding_ref", byte[].class) != null + || transitionRow.get("expected_prior_binding_generation") != null + || !bytesEqual(issuerObligation, "binding_ref", owner.bindingRef().bytes()) + || !uuid(issuerObligation, "reservation_id").equals(original.reservationId()) + || !positive(issuerObligation, "binding_generation").equals(member.bindingGeneration()) + || !"REQUIRED".equals(text(issuerObligation, "status"))) { + throw unavailable( + "The actual V29 issuer transition no longer matches its immutable local operation"); + } + if (!Arrays.equals(bytes(operationRow, "binding_ref"), owner.bindingRef().bytes()) + || !positive(operationRow, "binding_generation").equals(member.bindingGeneration())) { + throw unavailable( + "The issuer operation's frozen candidate differs from the current V29 source"); + } + + boolean bindingPresent; + boolean counted; + if ("PREPARED".equals(transitionStatus) + && "CANDIDATE_PREPARED".equals(candidateLifecycle) + && "RESERVED".equals(reservationLifecycle)) { + bindingPresent = false; + counted = true; + } else if ("PROVISIONAL".equals(transitionStatus) + && "PROVISIONAL".equals(candidateLifecycle) + && "RESERVED".equals(reservationLifecycle)) { + bindingPresent = true; + counted = true; + } else if ("COMMITTED".equals(transitionStatus) + && "ACTIVE".equals(candidateLifecycle) + && "BOUND".equals(reservationLifecycle)) { + bindingPresent = true; + counted = true; + } else { + throw unavailable( + "The current SQL transition phase does not qualify an issuer reservation/member projection"); + } + if (!positive(inventoryRow, "inventory_revision") + .equals(positive(transitionRow, "inventory_revision")) + || !positive(issuerObligation, "inventory_revision") + .equals(positive(transitionRow, "inventory_revision")) + || !positive(reservationRow, "inventory_revision") + .equals(positive(transitionRow, "inventory_revision"))) { + throw unavailable( + "The V29 candidate, reservation, and issuer obligation revisions are not one current transition"); + } + return new CurrentPhase( + bindingPresent, + counted, + reservationLifecycle, + transitionStatus, + positive(transitionRow, "inventory_revision")); + } + + private static void requireOwnerColumns( + Record row, + CanonicalGameplayBindingIdentity owner, + BigInteger partitionId, + String partitionField) { + if (!uuid(row, "account_id").equals(owner.accountId()) + || !uuid(row, "tenant_id").equals(owner.tenantId()) + || !uuid(row, "game_instance_id").equals(owner.gameInstanceId()) + || !number(row, "runtime_game_instance_id") + .equals(BigInteger.valueOf(owner.runtimeGameInstanceId())) + || !text(row, "session_id").equals(owner.sessionId()) + || !text(row, "issuer_id").equals(owner.issuerId()) + || !positive(row, "issuer_auth_generation").equals(owner.issuerAuthGeneration()) + || !uuid(row, "playable_state_namespace_id").equals(owner.playableStateNamespaceId()) + || !uuid(row, "character_id").equals(owner.characterId()) + || !text(row, "playable_state_scope").equals(owner.playableStateScope()) + || !uuid(row, "region_id").equals(owner.regionId()) + || !positive(row, "region_epoch").equals(owner.regionEpoch()) + || !positive(row, "issuer_index_layout_version").equals(owner.issuerIndexLayoutVersion()) + || !positive(row, "issuer_index_partition_count").equals(owner.issuerIndexPartitionCount()) + || !positive(row, "issuer_index_partition_capacity") + .equals(owner.issuerIndexPartitionCapacity()) + || !nonnegative(row, partitionField).equals(partitionId)) { + throw unavailable( + "The actual issuer reservation or candidate owner differs from the full v2 owner tuple"); + } + } + + private static void requireAccountControlCurrent( + DSLContext transaction, Record operation, UUID accountId) { + Record account = + transaction.fetchOne( + "SELECT * FROM " + ACCOUNT_CONTROL + " WHERE account_id = ? FOR UPDATE", accountId); + if (account == null + || !Objects.equals(text(account, "state"), text(operation, "account_control_state")) + || !number(account, "last_operation_fence") + .equals(number(operation, "account_control_epoch")) + || !Objects.equals( + account.get("current_operation_id", UUID.class), + operation.get("account_current_operation_id", UUID.class)) + || !Objects.equals( + account.get("current_operation_fence", BigDecimal.class), + operation.get("account_current_operation_fence", BigDecimal.class)) + || !Objects.equals( + account.get("account_admission_fence", UUID.class), + operation.get("account_admission_fence", UUID.class)) + || !Objects.equals( + account.get("historical_account_admission_fence", UUID.class), + operation.get("account_historical_admission_fence", UUID.class)) + || !Objects.equals( + account.get("coverage_fence", UUID.class), + operation.get("account_coverage_fence", UUID.class)) + || !Objects.equals( + account.get("inventory_snapshot_revision", BigDecimal.class), + operation.get("account_inventory_snapshot_revision", BigDecimal.class)) + || !Objects.equals( + account.get("coverage_generation", BigDecimal.class), + operation.get("account_coverage_generation", BigDecimal.class))) { + throw unavailable( + "The original Account coverage control changed after local issuer registration"); + } + } + + private static Set readAndVerifyBootstrapReservationIds( + DSLContext transaction, CanonicalGameplayIssuerInstalledAnchor anchor) { + List rows = + transaction.fetch( + "SELECT * FROM " + + BOOTSTRAP_OPERATION + + " WHERE issuer_id = ? AND bootstrap_operation_id = ? ORDER BY work_ordinal", + ISSUER, + anchor.bootstrapOperationId()); + Set reservationIds = new HashSet<>(); + for (Record row : rows) { + byte[] valueBytes = bytes(row, "member_value_bytes"); + if (!text(row, "member_value_digest") + .equals(CanonicalGameplayIssuerMemberV2Codec.sha256(valueBytes)) + || !"PENDING_PHYSICAL_PROOF".equals(text(row, "member_status")) + || !Objects.equals(row.get("member_schema_version", Short.class), (short) 2)) { + throw unavailable("The installed bootstrap member history is malformed"); + } + CanonicalGameplayIssuerMemberV2Value value; + try { + value = CanonicalGameplayIssuerMemberV2Codec.decode(valueBytes); + } catch (RuntimeException malformed) { + throw unavailable( + "The installed bootstrap member history is not closed schema v2", malformed); + } + if (!value.anchor().issuerCoverageOperationId().equals(anchor.issuerCoverageOperationId()) + || !value.anchor().operationFence().equals(anchor.operationFence()) + || !value.anchor().coverageFence().equals(anchor.coverageFence()) + || !value + .anchor() + .issuerInventorySnapshotRevision() + .equals(anchor.issuerInventorySnapshotRevision()) + || !value.owner().issuerId().equals(anchor.issuerId()) + || !value + .reservation() + .partitionId() + .equals(value.owner().bindingRef().partitionId(anchor.partitionCount())) + || !reservationIds.add(value.reservation().reservationId()) + || !uuid(row, "reservation_id").equals(value.reservation().reservationId())) { + throw unavailable( + "The installed bootstrap member history differs from its exact anchor cohort"); + } + } + return reservationIds; + } + + private static Set readCurrentReservationIds(DSLContext transaction) { + List rows = + transaction.fetch( + "SELECT reservation_id FROM " + + RESERVATION + + " WHERE issuer_id = ? ORDER BY reservation_id", + ISSUER); + Set result = new HashSet<>(); + for (Record row : rows) { + if (!result.add(uuid(row, "reservation_id"))) { + throw unavailable("The current issuer reservation inventory contains duplicate identities"); + } + } + return result; + } + + private static void requireQualifiedBaseline( + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof proof, + Map fields) { + String headerField = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.METADATA_FIELD; + byte[] header = fields.get(headerField); + if (header == null || !Arrays.equals(header, proofMetadata(proof))) { + throw unavailable("The installed issuer baseline header is missing or changed"); + } + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.requireExactMetadata(header, header); + Set reservations = new HashSet<>(); + Set bindings = new HashSet<>(); + Map capacityMembers = new HashMap<>(); + Map bindingReservations = new HashMap<>(); + int countedCapacity = 0; + int reservationCount = 0; + int bindingCount = 0; + for (Map.Entry field : fields.entrySet()) { + if (field.getKey().equals(headerField)) continue; + CanonicalGameplayIssuerMemberV2Value value; + try { + value = CanonicalGameplayIssuerMemberV2Codec.decode(field.getValue()); + } catch (RuntimeException malformed) { + throw unavailable( + "The exact issuer baseline contains a malformed or legacy member value", malformed); + } + requireMemberMatchesAnchor(value, anchor); + if (!value.reservation().partitionId().equals(proof.partitionId()) + || !value + .owner() + .bindingRef() + .partitionId(anchor.partitionCount()) + .equals(proof.partitionId())) { + throw unavailable( + "An immutable issuer baseline member is stored under the wrong partition"); + } + String name = field.getKey(); + if (name.startsWith( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.RESERVATION_FIELD_PREFIX)) { + UUID reservationId = parseReservationField(name); + if (!reservationId.equals(value.reservation().reservationId()) + || !reservations.add(reservationId)) { + throw unavailable( + "The immutable issuer baseline has a duplicate or conflicting capacity field"); + } + capacityMembers.put(reservationId, field.getValue()); + reservationCount++; + if (value.reservation().lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED) { + countedCapacity++; + } + } else { + if (name.startsWith("!") + || !Arrays.equals( + name.getBytes(StandardCharsets.UTF_8), value.owner().bindingRef().bytes()) + || !bindings.add(name)) { + throw unavailable("The immutable issuer baseline has an invalid canonical binding field"); + } + UUID reservationId = value.reservation().reservationId(); + if (bindingReservations.putIfAbsent(name, reservationId) != null) { + throw unavailable("The immutable issuer baseline repeats a binding owner"); + } + bindingCount++; + } + } + Set boundReservations = new HashSet<>(); + for (Map.Entry binding : bindingReservations.entrySet()) { + byte[] capacityValue = capacityMembers.get(binding.getValue()); + byte[] bindingValue = fields.get(binding.getKey()); + if (capacityValue == null + || !Arrays.equals(capacityValue, bindingValue) + || !boundReservations.add(binding.getValue())) { + throw unavailable( + "An immutable issuer baseline binding has no exact unique capacity reservation"); + } + } + if (reservationCount != proof.physicalReservationCount() + || bindingCount != proof.physicalBindingCount() + || countedCapacity != proof.physicalCountedCapacityCount() + || fields.size() != 1 + reservationCount + bindingCount) { + throw unavailable( + "The immutable issuer baseline field set does not match its retained counts"); + } + } + + private static byte[] proofMetadata( + CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof proof) { + Map fields = + CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( + proof.exactPhysicalFieldSetBytes()); + byte[] metadata = + fields.get(CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.METADATA_FIELD); + if (metadata == null) throw unavailable("The installed issuer baseline has no metadata header"); + return metadata; + } + + static void requireMemberMatchesAnchor( + CanonicalGameplayIssuerMemberV2Value value, CanonicalGameplayIssuerInstalledAnchor anchor) { + if (!value.owner().issuerId().equals(anchor.issuerId()) + || !value.owner().issuerAuthGeneration().equals(anchor.issuerAuthGeneration()) + || !value.owner().issuerIndexLayoutVersion().equals(anchor.layoutVersion()) + || !value.owner().issuerIndexPartitionCount().equals(anchor.partitionCount()) + || !value.owner().issuerIndexPartitionCapacity().equals(anchor.partitionCapacity()) + || !value.issuerControlEpoch().equals(anchor.controlEpoch()) + || !value.anchor().issuerCoverageOperationId().equals(anchor.issuerCoverageOperationId()) + || !value.anchor().operationFence().equals(anchor.operationFence()) + || !value.anchor().coverageFence().equals(anchor.coverageFence()) + || !value + .anchor() + .issuerInventorySnapshotRevision() + .equals(anchor.issuerInventorySnapshotRevision()) + || !Arrays.equals( + value.layoutDescriptor().exactDescriptorBytes(), anchor.layoutDescriptorBytes()) + || !value.layoutDescriptor().descriptorDigest().equals(anchor.layoutDescriptorDigest()) + || !Arrays.equals( + value.sourceCheckpoint().exactCheckpointBytes(), anchor.sourceCheckpointBytes()) + || !value.sourceCheckpoint().checkpointDigest().equals(anchor.sourceCheckpointDigest()) + || !Arrays.equals( + value.sourceCheckpoint().latestIssuerEventBytes(), anchor.sourceEventBytes()) + || !Objects.equals( + value.sourceCheckpoint().latestIssuerEventDigest(), anchor.sourceEventDigest()) + || !Arrays.equals( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(value.incarnation()), + anchor.incarnationBytes())) { + throw unavailable( + "An issuer member differs from the exact installed anchor, layout, source, or incarnation"); + } + } + + private static void requireAnchorColumns( + Record row, CanonicalGameplayIssuerInstalledAnchor anchor) { + if (!uuid(row, "anchor_bootstrap_operation_id").equals(anchor.bootstrapOperationId()) + || !uuid(row, "anchor_bootstrap_request_id").equals(anchor.bootstrapRequestId()) + || !uuid(row, "anchor_build_operation_id").equals(anchor.buildOperationId()) + || !text(row, "anchor_build_plan_digest").equals(anchor.buildPlanDigest()) + || !positive(row, "anchor_control_epoch").equals(anchor.controlEpoch()) + || !uuid(row, "anchor_issuer_coverage_operation_id") + .equals(anchor.issuerCoverageOperationId()) + || !positive(row, "anchor_operation_fence").equals(anchor.operationFence()) + || !positive(row, "anchor_coverage_fence").equals(anchor.coverageFence()) + || !positive(row, "anchor_issuer_inventory_snapshot_revision") + .equals(anchor.issuerInventorySnapshotRevision()) + || !positive(row, "anchor_layout_version").equals(anchor.layoutVersion()) + || !positive(row, "anchor_partition_count").equals(anchor.partitionCount()) + || !positive(row, "anchor_partition_capacity").equals(anchor.partitionCapacity()) + || !text(row, "anchor_mapping_identity").equals(anchor.mappingIdentity()) + || !positive(row, "anchor_issuer_auth_generation").equals(anchor.issuerAuthGeneration())) { + throw unavailable("A durable local issuer anchor column differs from its immutable anchor"); + } + } + + private static void requireCurrentSourceMatches( + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState state) { + if (!sameCheckpoint(state.accountCheckpoint(), anchor) + || !Arrays.equals( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(state.incarnation()), + anchor.incarnationBytes())) { + throw unavailable( + "Current Account issuer source or storage incarnation differs from the installed anchor"); + } + } + + private CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState + readCurrentIssuerState() { + requireNoAmbientTransaction(); + try { + return Objects.requireNonNull( + currentIssuerStateSource.readFreshCurrentState(), + "current issuer state source returned null"); + } catch (RuntimeException failure) { + throw unavailable( + "The current issuer checkpoint or storage incarnation is unavailable", failure); + } + } + + private static void requireSameCurrentIssuerState( + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState left, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState right) { + var leftCheckpoint = left.accountCheckpoint(); + var rightCheckpoint = right.accountCheckpoint(); + if (!leftCheckpoint.issuerId().equals(rightCheckpoint.issuerId()) + || !leftCheckpoint.issuerAuthGeneration().equals(rightCheckpoint.issuerAuthGeneration()) + || !Arrays.equals( + leftCheckpoint.exactCheckpointBytes(), rightCheckpoint.exactCheckpointBytes()) + || !leftCheckpoint.checkpointDigest().equals(rightCheckpoint.checkpointDigest()) + || !Arrays.equals( + leftCheckpoint.latestIssuerEventBytes(), rightCheckpoint.latestIssuerEventBytes()) + || !Objects.equals( + leftCheckpoint.latestIssuerEventDigest(), rightCheckpoint.latestIssuerEventDigest()) + || !Arrays.equals( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(left.incarnation()), + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(right.incarnation()))) { + throw unavailable("The issuer source or storage incarnation changed during the SQL read"); + } + } + + private static boolean sameCheckpoint( + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint current, + CanonicalGameplayIssuerInstalledAnchor anchor) { + return current != null + && current.issuerId().equals(anchor.issuerId()) + && current.issuerAuthGeneration().equals(anchor.issuerAuthGeneration()) + && Arrays.equals(current.exactCheckpointBytes(), anchor.sourceCheckpointBytes()) + && current.checkpointDigest().equals(anchor.sourceCheckpointDigest()) + && Arrays.equals(current.latestIssuerEventBytes(), anchor.sourceEventBytes()) + && Objects.equals(current.latestIssuerEventDigest(), anchor.sourceEventDigest()); + } + + private static void requireSameAnchor( + CanonicalGameplayIssuerInstalledAnchor expected, + CanonicalGameplayIssuerInstalledAnchor current) { + if (!Arrays.equals(expected.exactAnchorBytes(), current.exactAnchorBytes()) + || !expected.exactAnchorDigest().equals(current.exactAnchorDigest())) { + throw unavailable("The positively installed issuer anchor changed"); + } + } + + private static void lockInventoryClock(DSLContext transaction) { + Record row = + transaction.fetchOne( + "SELECT inventory_revision FROM " + + INVENTORY_CLOCK + + " WHERE singleton_id = 1 FOR UPDATE"); + if (row == null || number(row, "inventory_revision").signum() < 0) { + throw unavailable("The durable binding inventory serialization clock is unavailable"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw unavailable("Issuer physical projection cannot run inside an ambient SQL transaction"); + } + } + + private static void putUnique(Map fields, String field, byte[] value) { + if (fields.putIfAbsent(field, value.clone()) != null) { + throw unavailable("Two SQL owner operations claim the same issuer partition field"); + } + } + + private static long totalFieldBytes(Map fields) { + long total = 0; + for (Map.Entry field : fields.entrySet()) { + total = + Math.addExact( + total, + field.getKey().getBytes(StandardCharsets.UTF_8).length + + (long) field.getValue().length); + } + return total; + } + + private static UUID parseReservationField(String field) { + try { + String suffix = + field.substring( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.RESERVATION_FIELD_PREFIX + .length()); + UUID value = UUID.fromString(suffix); + if (!value.toString().equals(suffix) || value.equals(new UUID(0L, 0L))) + throw unavailable("Capacity field identity is not canonical"); + return value; + } catch (RuntimeException malformed) { + throw unavailable("Capacity field identity is malformed", malformed); + } + } + + private static byte[] currentnessDigest( + CanonicalGameplayIssuerInstalledAnchor anchor, + byte[] baselineBytes, + List entries, + Set reservationIds, + BigInteger aggregateCapacity, + BigInteger partitionCapacity) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + update(digest, anchor.exactAnchorBytes()); + update(digest, baselineBytes); + for (LocalEntry entry : + entries.stream().sorted(Comparator.comparing(LocalEntry::operationId)).toList()) { + update(digest, entry.operationId().toString().getBytes(StandardCharsets.US_ASCII)); + update(digest, entry.exactMemberValueBytes()); + update(digest, entry.transitionStatus().getBytes(StandardCharsets.US_ASCII)); + update(digest, entry.lifecycle().getBytes(StandardCharsets.US_ASCII)); + update(digest, entry.inventoryRevision().toString().getBytes(StandardCharsets.US_ASCII)); + digest.update((byte) (entry.bindingPresent() ? 1 : 0)); + digest.update((byte) (entry.countsTowardCapacity() ? 1 : 0)); + } + for (UUID id : reservationIds.stream().sorted().toList()) { + update(digest, id.toString().getBytes(StandardCharsets.US_ASCII)); + } + update(digest, aggregateCapacity.toString().getBytes(StandardCharsets.US_ASCII)); + update(digest, partitionCapacity.toString().getBytes(StandardCharsets.US_ASCII)); + return digest.digest(); + } catch (Exception impossible) { + throw new IllegalStateException("Could not retain local issuer SQL currentness", impossible); + } + } + + private static void update(MessageDigest digest, byte[] bytes) { + digest.update(BigInteger.valueOf(bytes.length).toByteArray()); + digest.update(bytes); + } + + private static BigInteger number(Record row, String field) { + Object value = row.get(field); + if (!(value instanceof Number number)) throw unavailable(field + " is missing or nonnumeric"); + try { + if (number instanceof BigDecimal decimal) return decimal.toBigIntegerExact(); + return BigInteger.valueOf(number.longValue()); + } catch (ArithmeticException malformed) { + throw unavailable(field + " is not an exact integer", malformed); + } + } + + private static BigInteger positive(Record row, String field) { + BigInteger value = number(row, field); + if (value.signum() <= 0 + || value.toString().length() > CanonicalGameplayIssuerMemberV2Codec.MAX_COUNTER_DIGITS) { + throw unavailable(field + " is not a bounded positive counter"); + } + return value; + } + + private static BigInteger nonnegative(Record row, String field) { + BigInteger value = number(row, field); + if (value.signum() < 0 + || value.toString().length() > CanonicalGameplayIssuerMemberV2Codec.MAX_COUNTER_DIGITS) { + throw unavailable(field + " is not a bounded nonnegative counter"); + } + return value; + } + + private static int integer(Record row, String field) { + try { + return number(row, field).intValueExact(); + } catch (ArithmeticException malformed) { + throw unavailable(field + " is outside its bounded integer range", malformed); + } + } + + private static UUID uuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null) throw unavailable(field + " is missing"); + return value; + } + + private static String text(Record row, String field) { + String value = row.get(field, String.class); + if (value == null) throw unavailable(field + " is missing"); + return value; + } + + private static byte[] bytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + if (value == null || value.length == 0) throw unavailable(field + " is missing or empty"); + return value; + } + + private static boolean bytesEqual(Record row, String field, byte[] expected) { + return Arrays.equals(bytes(row, field), expected); + } + + private static boolean nullableBytesEqual(Record row, String field, byte[] expected) { + return Arrays.equals(row.get(field, byte[].class), expected); + } + + private static IllegalStateException unavailable(String message) { + return new IllegalStateException("Issuer binding-local projection is unavailable: " + message); + } + + private static IllegalStateException unavailable(String message, Throwable cause) { + return new IllegalStateException( + "Issuer binding-local projection is unavailable: " + message, cause); + } + + private record CurrentPhase( + boolean bindingPresent, + boolean countsTowardCapacity, + String lifecycle, + String transitionStatus, + BigInteger inventoryRevision) {} + + record LocalEntry( + UUID operationId, + byte[] exactMemberValueBytes, + CanonicalGameplayIssuerMemberV2Value memberValue, + boolean bindingPresent, + boolean countsTowardCapacity, + String lifecycle, + String transitionStatus, + BigInteger inventoryRevision) { + LocalEntry { + exactMemberValueBytes = exactMemberValueBytes.clone(); + } + + @Override + public byte[] exactMemberValueBytes() { + return exactMemberValueBytes.clone(); + } + } + + /** Private-construction output of the SQL owner; it has no public/raw-list factory. */ + static final class PreparedPartitionWork { + private final CanonicalGameplayIssuerInstalledAnchor anchor; + private final CanonicalGameplayIssuerBindingLocalOperation targetOperation; + private final CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof + baselineProof; + private final Map baselineFields; + private final Map allowedFields; + private final List localEntries; + private final LocalEntry targetEntry; + private final BigInteger aggregateCapacity; + private final BigInteger aggregateBound; + private final BigInteger partitionCapacity; + private final byte[] sqlCurrentnessDigest; + + private PreparedPartitionWork( + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBindingLocalOperation targetOperation, + CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof + baselineProof, + Map baselineFields, + Map allowedFields, + List localEntries, + LocalEntry targetEntry, + BigInteger aggregateCapacity, + BigInteger aggregateBound, + BigInteger partitionCapacity, + byte[] sqlCurrentnessDigest) { + this.anchor = anchor; + this.targetOperation = targetOperation; + this.baselineProof = baselineProof; + this.baselineFields = copyFields(baselineFields); + this.allowedFields = copyFields(allowedFields); + this.localEntries = List.copyOf(localEntries); + this.targetEntry = targetEntry; + this.aggregateCapacity = aggregateCapacity; + this.aggregateBound = aggregateBound; + this.partitionCapacity = partitionCapacity; + this.sqlCurrentnessDigest = sqlCurrentnessDigest.clone(); + } + + CanonicalGameplayIssuerInstalledAnchor anchor() { + return anchor; + } + + CanonicalGameplayIssuerBindingLocalOperation targetOperation() { + return targetOperation; + } + + CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof + baselineProof() { + return baselineProof; + } + + Map baselineFields() { + return copyFields(baselineFields); + } + + Map allowedFields() { + return copyFields(allowedFields); + } + + List localEntries() { + return localEntries; + } + + LocalEntry targetEntry() { + return targetEntry; + } + + BigInteger aggregateCapacity() { + return aggregateCapacity; + } + + BigInteger aggregateBound() { + return aggregateBound; + } + + BigInteger partitionCapacity() { + return partitionCapacity; + } + + byte[] sqlCurrentnessDigest() { + return sqlCurrentnessDigest.clone(); + } + + private static Map copyFields(Map source) { + Map copy = new HashMap<>(); + source.forEach((key, value) -> copy.put(key, value.clone())); + return Map.copyOf(copy); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java new file mode 100644 index 0000000000..811f6627f2 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java @@ -0,0 +1,530 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisFuture; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.async.RedisAsyncCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigInteger; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Explicit, unregistered one-key projection owner for SQL-prepared ordinary issuer NEW work. + * Physical readback is local evidence only and leaves its SQL operation pending. + */ +public final class CanonicalGameplayIssuerBindingLocalRedisOwner { + private static final String PRINCIPAL = "gamesession_coord_app"; + private static final String KEY_PREFIX = "session:game:index:issuer:"; + private static final int MAX_SCRIPT_BYTES = 128 * 1024; + private static final long COMMAND_TIMEOUT_MILLIS = 5_000; + private static final List EXPECTED_KEYS = + List.of( + new RedisScriptDescriptor.KeySpec( + "issuerPartition", KEY_PREFIX, RedisScriptDescriptor.HashTagDeclaration.REQUIRED)); + private static final List EXPECTED_ARGUMENTS = + List.of( + new RedisScriptDescriptor.ArgumentSpec("issuerId"), + new RedisScriptDescriptor.ArgumentSpec("partitionId"), + new RedisScriptDescriptor.ArgumentSpec("partitionCount"), + new RedisScriptDescriptor.ArgumentSpec("partitionCapacity"), + new RedisScriptDescriptor.ArgumentSpec("baselineFieldCountAndExactFieldValuePairs"), + new RedisScriptDescriptor.ArgumentSpec( + "registeredLocalOperationCountAndExactOperationTupleAndCurrentPhase"), + new RedisScriptDescriptor.ArgumentSpec( + "targetOperationAndRequiredFieldsAndCapacityCounts")); + private static final List EXPECTED_OUTCOMES = + List.of( + new RedisScriptDescriptor.OutcomeSpec( + "CAPACITY_RESERVED", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "MEMBER_PROJECTED", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "LOCAL_OPERATION_REPLAY", + RedisScriptDescriptor.OutcomeCategory.REPLAY, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "TYPE_TTL_OR_FIELDSET_REFUSED", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "INVALID_ARGUMENTS_OR_CAPACITY", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING)); + + private final RedisClient redisClient; + private final RedisScriptCatalog catalog; + private final CanonicalGameplayIssuerBindingLocalProjectionRepository projectionRepository; + private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentStateSource; + + /** + * Redis client, passive manual descriptor catalog, actual SQL reader, and current source are + * explicit. + */ + public CanonicalGameplayIssuerBindingLocalRedisOwner( + RedisClient redisClient, + RedisScriptCatalog catalog, + CanonicalGameplayIssuerBindingLocalProjectionRepository projectionRepository, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentStateSource) { + this.redisClient = Objects.requireNonNull(redisClient, "Configured Redis client is required"); + this.catalog = Objects.requireNonNull(catalog, "Manual Redis script catalog is required"); + this.projectionRepository = + Objects.requireNonNull(projectionRepository, "Actual SQL projection reader is required"); + this.currentStateSource = + Objects.requireNonNull(currentStateSource, "Fresh issuer source is required"); + } + + /** Writes only the exact target reservation and SQL-qualified target binding field. */ + public Readback projectAndRead(CanonicalGameplayIssuerBindingLocalOperation operation) { + Objects.requireNonNull(operation, "SQL-issued local issuer operation is required"); + try { + requireNoAmbientTransaction(); + var work = projectionRepository.readPreparedPartitionWork(operation); + requireFreshCurrentState(work); + RedisScriptDescriptor descriptor = requireDescriptor(); + byte[] script = scriptSource(descriptor); + byte[] key = exactPartitionKey(work); + byte[][] arguments = scriptArguments(work); + long result = writeOneKey(script, key, arguments); + if (result < 1 || result > 3) { + throw new IllegalStateException( + "Issuer binding-local projection returned script outcome " + result); + } + byte[] readbackBytes = readExactPhysicalState(key, work); + requireFreshCurrentState(work); + projectionRepository.requireStillCurrent(work); + return new Readback(operation, result, readbackBytes); + } catch (RuntimeException failure) { + if (failure instanceof IllegalStateException state + && state.getMessage() != null + && state.getMessage().contains("issuer binding-local projection is unavailable")) { + throw state; + } + throw unavailable(failure); + } + } + + private long writeOneKey(byte[] script, byte[] key, byte[][] arguments) { + requireNoAmbientTransaction(); + try (StatefulRedisConnection connection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(connection); + requirePrincipal(await(commands.aclWhoami())); + String sha = await(commands.scriptLoad(script)); + if (!digest("SHA-1", script).equals(sha)) throw unavailable(); + Long reply = + await(commands.evalsha(sha, ScriptOutputType.INTEGER, new byte[][] {key}, arguments)); + if (reply == null) throw unavailable(); + return reply; + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private byte[] readExactPhysicalState( + byte[] key, + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work) { + requireNoAmbientTransaction(); + try (StatefulRedisConnection connection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(connection); + requirePrincipal(await(commands.aclWhoami())); + if (!"hash".equals(await(commands.type(key))) + || !Long.valueOf(-1L).equals(await(commands.pttl(key)))) { + throw unavailable(); + } + Long length = await(commands.hlen(key)); + int maxFields = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_HASH_FIELDS + + 2 * CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_MEMBER_OPERATIONS; + if (length == null || length < 1 || length > maxFields) throw unavailable(); + Map raw = await(commands.hgetall(key)); + if (raw == null || raw.size() != length) throw unavailable(); + Map actual = new HashMap<>(); + long totalBytes = 0; + for (Map.Entry entry : raw.entrySet()) { + byte[] field = Objects.requireNonNull(entry.getKey(), "Redis field"); + byte[] value = Objects.requireNonNull(entry.getValue(), "Redis value"); + totalBytes = Math.addExact(totalBytes, field.length + (long) value.length); + if (totalBytes + > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_TOTAL_HASH_BYTES) { + throw unavailable(); + } + String encoded = Base64.getEncoder().encodeToString(field); + if (actual.putIfAbsent(encoded, value.clone()) != null) throw unavailable(); + } + + Map baseline = work.baselineFields(); + Map allowed = work.allowedFields(); + if (actual.size() > allowed.size()) throw unavailable(); + for (Map.Entry field : baseline.entrySet()) { + byte[] redisValue = + actual.get( + Base64.getEncoder() + .encodeToString(field.getKey().getBytes(StandardCharsets.UTF_8))); + if (redisValue == null || !Arrays.equals(redisValue, field.getValue())) throw unavailable(); + } + for (Map.Entry field : actual.entrySet()) { + String decodedField = decodeUtf8(Base64.getDecoder().decode(field.getKey())); + byte[] expected = allowed.get(decodedField); + if (expected == null || !Arrays.equals(expected, field.getValue())) throw unavailable(); + } + + var target = work.targetEntry(); + String capacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + target.memberValue().reservation().reservationId()); + byte[] targetCapacity = + actual.get( + Base64.getEncoder() + .encodeToString(capacityField.getBytes(StandardCharsets.US_ASCII))); + if (!Arrays.equals(targetCapacity, target.exactMemberValueBytes())) throw unavailable(); + String bindingField = + new String(target.memberValue().owner().bindingRef().bytes(), StandardCharsets.UTF_8); + byte[] targetBinding = + actual.get( + Base64.getEncoder().encodeToString(bindingField.getBytes(StandardCharsets.UTF_8))); + if (target.bindingPresent()) { + if (!Arrays.equals(targetBinding, target.exactMemberValueBytes())) throw unavailable(); + } else if (targetBinding != null) { + throw unavailable(); + } + + int physicalCapacityCount = 0; + int physicalReservationCount = 0; + int physicalBindingCount = 0; + int qualifiedLocalBindingCount = 0; + for (var entry : work.localEntries()) { + if (entry + .memberValue() + .reservation() + .partitionId() + .equals(work.targetOperation().memberValue().reservation().partitionId()) + && entry.bindingPresent()) { + qualifiedLocalBindingCount++; + } + } + for (var entry : actual.entrySet()) { + String field = decodeUtf8(Base64.getDecoder().decode(entry.getKey())); + byte[] valueBytes = entry.getValue(); + if (field.startsWith( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.RESERVATION_FIELD_PREFIX)) { + var value = CanonicalGameplayIssuerMemberV2Codec.decode(valueBytes); + if (value.reservation().lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED) { + physicalCapacityCount++; + } + physicalReservationCount++; + } else if (!field.equals( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.METADATA_FIELD)) { + CanonicalGameplayIssuerMemberV2Codec.decode(valueBytes); + physicalBindingCount++; + } + } + int baselineCapacityCount = work.baselineProof().physicalCountedCapacityCount(); + int baselineReservationCount = work.baselineProof().physicalReservationCount(); + int baselineBindingCount = work.baselineProof().physicalBindingCount(); + int registeredCapacityCount = + Math.toIntExact( + work.localEntries().stream() + .filter( + entry -> + entry + .memberValue() + .reservation() + .partitionId() + .equals( + work.targetOperation() + .memberValue() + .reservation() + .partitionId()) + && entry.countsTowardCapacity()) + .count()); + int registeredReservationCount = + Math.toIntExact( + work.localEntries().stream() + .filter( + entry -> + entry + .memberValue() + .reservation() + .partitionId() + .equals( + work.targetOperation().memberValue().reservation().partitionId())) + .count()); + if (BigInteger.valueOf(physicalCapacityCount).compareTo(work.anchor().partitionCapacity()) > 0 + || physicalCapacityCount < baselineCapacityCount + 1 + || physicalCapacityCount > baselineCapacityCount + registeredCapacityCount + || physicalReservationCount < baselineReservationCount + 1 + || physicalReservationCount > baselineReservationCount + registeredReservationCount + || physicalBindingCount < baselineBindingCount + || physicalBindingCount > baselineBindingCount + qualifiedLocalBindingCount + || work.partitionCapacity().compareTo(work.anchor().partitionCapacity()) > 0 + || work.aggregateCapacity().compareTo(work.aggregateBound()) > 0) { + throw unavailable(); + } + return CanonicalGameplayIssuerBootstrapCoverageRepository.encodeFieldSet( + decodePhysicalMap(actual)); + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private static Map decodePhysicalMap(Map encoded) { + Map result = new HashMap<>(); + encoded.forEach( + (field, value) -> result.put(decodeUtf8(Base64.getDecoder().decode(field)), value.clone())); + return result; + } + + private void requireFreshCurrentState( + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work) { + requireNoAmbientTransaction(); + var current = currentStateSource.readFreshCurrentState(); + requireNoAmbientTransaction(); + var anchor = work.anchor(); + if (current == null + || !sameCheckpoint(current.accountCheckpoint(), anchor) + || !Arrays.equals( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(current.incarnation()), + anchor.incarnationBytes())) { + throw unavailable(); + } + } + + private RedisScriptDescriptor requireDescriptor() { + try { + RedisScriptDescriptor descriptor = + catalog.require(CanonicalGameplayIssuerBindingLocalRedisScriptContribution.SCRIPT_ID); + if (!CanonicalGameplayIssuerBindingLocalRedisScriptContribution.SCRIPT_ID.equals( + descriptor.scriptId()) + || !CanonicalGameplayIssuerBindingLocalRedisScriptContribution.RESOURCE_PATH.equals( + descriptor.resourcePath()) + || !"game-session-service".equals(descriptor.owner()) + || !PRINCIPAL.equals(descriptor.principal()) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || !EXPECTED_KEYS.equals(descriptor.keys()) + || !EXPECTED_ARGUMENTS.equals(descriptor.arguments()) + || descriptor.category() != RedisScriptDescriptor.ScriptCategory.SESSION_ISSUER_INDEX + || !EXPECTED_OUTCOMES.equals(descriptor.outcomes()) + || descriptor.resetSensitivity() != RedisScriptDescriptor.ResetSensitivity.CLUSTER + || descriptor.lossClass() + != RedisScriptDescriptor.LossClass.EMPTY_REDIS_COLD_START_OR_RESET + || descriptor.compatibilityLevel() + != RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET + || !descriptor + .supportedCoexistence() + .equals(List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "v2"))) + || descriptor.legacyPayloadShape() != null) { + throw unavailable(); + } + return descriptor; + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private static byte[] scriptSource(RedisScriptDescriptor descriptor) { + try (InputStream input = + CanonicalGameplayIssuerBindingLocalRedisOwner.class + .getClassLoader() + .getResourceAsStream(descriptor.resourcePath())) { + if (input == null) throw unavailable(); + byte[] bytes = input.readNBytes(MAX_SCRIPT_BYTES + 1); + if (bytes.length == 0 + || bytes.length > MAX_SCRIPT_BYTES + || !descriptor.sha256().equals(digest("SHA-256", bytes))) { + throw unavailable(); + } + return bytes; + } catch (IOException | RuntimeException failure) { + throw unavailable(failure); + } + } + + private static byte[] exactPartitionKey( + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work) { + String key = CanonicalGameplayIssuerRedisKeys.forMember(work.targetOperation().memberValue()); + if (!key.startsWith(KEY_PREFIX) || key.length() > 512) throw unavailable(); + return key.getBytes(StandardCharsets.US_ASCII); + } + + private static byte[][] scriptArguments( + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work) { + var anchor = work.anchor(); + Map baseline = work.baselineFields(); + List> baselineEntries = + baseline.entrySet().stream().sorted(Map.Entry.comparingByKey()).toList(); + List arguments = new ArrayList<>(); + arguments.add(ascii(anchor.issuerId())); + arguments.add( + ascii(work.targetOperation().memberValue().reservation().partitionId().toString())); + arguments.add(ascii(anchor.partitionCount().toString())); + arguments.add(ascii(anchor.partitionCapacity().toString())); + arguments.add(ascii(Integer.toString(baselineEntries.size()))); + for (Map.Entry field : baselineEntries) { + arguments.add(field.getKey().getBytes(StandardCharsets.UTF_8)); + arguments.add(field.getValue()); + } + List entries = + work.localEntries().stream() + .filter( + entry -> + entry + .memberValue() + .reservation() + .partitionId() + .equals(work.targetOperation().memberValue().reservation().partitionId())) + .sorted(java.util.Comparator.comparing(entry -> entry.operationId().toString())) + .toList(); + arguments.add(ascii(Integer.toString(entries.size()))); + for (var entry : entries) { + arguments.add(ascii(entry.operationId().toString())); + arguments.add(entry.memberValue().owner().bindingRef().bytes()); + arguments.add(ascii(entry.memberValue().reservation().reservationId().toString())); + arguments.add(entry.exactMemberValueBytes()); + arguments.add(ascii(entry.bindingPresent() ? "1" : "0")); + arguments.add(ascii(entry.countsTowardCapacity() ? "1" : "0")); + } + var target = work.targetEntry(); + arguments.add(ascii(target.operationId().toString())); + arguments.add(ascii(target.memberValue().reservation().reservationId().toString())); + arguments.add(target.memberValue().owner().bindingRef().bytes()); + arguments.add(target.exactMemberValueBytes()); + arguments.add(ascii(target.bindingPresent() ? "1" : "0")); + arguments.add(ascii(work.partitionCapacity().toString())); + arguments.add(ascii(work.aggregateCapacity().toString())); + arguments.add(ascii(work.aggregateBound().toString())); + return arguments.toArray(byte[][]::new); + } + + private static boolean sameCheckpoint( + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint current, + CanonicalGameplayIssuerInstalledAnchor anchor) { + return current != null + && current.issuerId().equals(anchor.issuerId()) + && current.issuerAuthGeneration().equals(anchor.issuerAuthGeneration()) + && Arrays.equals(current.exactCheckpointBytes(), anchor.sourceCheckpointBytes()) + && current.checkpointDigest().equals(anchor.sourceCheckpointDigest()) + && Arrays.equals(current.latestIssuerEventBytes(), anchor.sourceEventBytes()) + && Objects.equals(current.latestIssuerEventDigest(), anchor.sourceEventDigest()); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static String decodeUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw unavailable(malformed); + } + } + + private static RedisAsyncCommands requireCommands( + StatefulRedisConnection connection) { + if (connection == null || !connection.isOpen()) throw unavailable(); + return connection.async(); + } + + private static void requirePrincipal(String principal) { + if (!PRINCIPAL.equals(principal)) throw unavailable(); + } + + private static T await(RedisFuture future) { + try { + return future.get(COMMAND_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + future.cancel(true); + throw unavailable(interrupted); + } catch (ExecutionException | TimeoutException | RuntimeException failure) { + future.cancel(true); + throw unavailable(failure); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + } + + private static String digest(String algorithm, byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(bytes)); + } catch (Exception failure) { + throw unavailable(failure); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Issuer binding-local projection is unavailable"); + } + + private static IllegalStateException unavailable(Throwable cause) { + return new IllegalStateException("Issuer binding-local projection is unavailable", cause); + } + + /** + * Exact SQL operation plus independent physical readback; no acknowledgement or admission claim. + */ + public static final class Readback { + private final CanonicalGameplayIssuerBindingLocalOperation operation; + private final long scriptOutcome; + private final byte[] exactReadbackBytes; + + private Readback( + CanonicalGameplayIssuerBindingLocalOperation operation, + long scriptOutcome, + byte[] exactReadbackBytes) { + this.operation = Objects.requireNonNull(operation, "operation"); + this.scriptOutcome = scriptOutcome; + this.exactReadbackBytes = + Objects.requireNonNull(exactReadbackBytes, "exactReadbackBytes").clone(); + } + + public CanonicalGameplayIssuerBindingLocalOperation operation() { + return operation; + } + + public long scriptOutcome() { + return scriptOutcome; + } + + public byte[] exactReadbackBytes() { + return exactReadbackBytes.clone(); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwner.java index c6aa5d1e03..84169b204d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwner.java @@ -24,8 +24,7 @@ public CanonicalGameplayIssuerBootstrapCoverageOwner( CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource currentStateSource) { this.dsl = Objects.requireNonNull(dsl, "dsl"); - this.partitionRedisOwner = - Objects.requireNonNull(partitionRedisOwner, "partitionRedisOwner"); + this.partitionRedisOwner = Objects.requireNonNull(partitionRedisOwner, "partitionRedisOwner"); this.currentStateSource = Objects.requireNonNull(currentStateSource, "currentStateSource"); } @@ -53,8 +52,7 @@ public CanonicalGameplayIssuerInstalledAnchor completeInitialBootstrap( coverageRepository.readInstalledAnchor( bootstrapOperationId, bootstrapRequestId, initialState); if (installed.isPresent()) { - return readInstalledAnchorPartitions( - plan, installed.get(), coverageRepository, initialState); + return readInstalledAnchorPartitions(plan, installed.get(), coverageRepository, initialState); } CanonicalGameplayIssuerBootstrapMemberOperationRepository memberOperationRepository = @@ -119,7 +117,8 @@ private CanonicalGameplayIssuerInstalledAnchor readInstalledAnchorPartitions( coverageRepository .readInstalledAnchor( installed.bootstrapOperationId(), installed.bootstrapRequestId(), afterReadback) - .orElseThrow(() -> unavailable("Installed issuer anchor disappeared during exact readback")); + .orElseThrow( + () -> unavailable("Installed issuer anchor disappeared during exact readback")); if (!Arrays.equals(installed.exactAnchorBytes(), confirmed.exactAnchorBytes()) || !installed.exactAnchorDigest().equals(confirmed.exactAnchorDigest())) { throw unavailable("Installed issuer anchor changed during physical partition readback"); @@ -145,7 +144,8 @@ private CanonicalGameplayIssuerInstalledAnchor readInstalledAnchorPartitions( CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(current.incarnation()), CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(expected.incarnation())) || !sameCheckpoint(current.accountCheckpoint(), expected.accountCheckpoint())) { - throw unavailable("Current Account source or stable Redis incarnation changed during bootstrap"); + throw unavailable( + "Current Account source or stable Redis incarnation changed during bootstrap"); } return current; } @@ -220,12 +220,14 @@ private static void requireSamePlan( private static void requireNonNil(UUID value, String name) { Objects.requireNonNull(value, name); - if (value.equals(new UUID(0L, 0L))) throw new IllegalArgumentException(name + " must not be nil"); + if (value.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException(name + " must not be nil"); } private static void requireNoAmbientTransaction() { if (TransactionSynchronizationManager.isActualTransactionActive()) { - throw unavailable("Initial issuer bootstrap completion cannot join an ambient SQL transaction"); + throw unavailable( + "Initial issuer bootstrap completion cannot join an ambient SQL transaction"); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java index dee6a30666..69100f7480 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java @@ -22,8 +22,8 @@ import java.util.Set; import java.util.UUID; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; import org.jooq.DSLContext; import org.jooq.Record; @@ -32,7 +32,8 @@ /** SQL owner for exact per-partition proof retention and one local initial anchor installation. */ final class CanonicalGameplayIssuerBootstrapCoverageRepository { private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; - private static final String OPERATION = "game_session_canonical_issuer_bootstrap_member_operation"; + private static final String OPERATION = + "game_session_canonical_issuer_bootstrap_member_operation"; private static final String PROOF = "game_session_canonical_issuer_bootstrap_partition_proof"; private static final String COUNTER = "game_session_canonical_issuer_bootstrap_coverage_counter"; private static final String ANCHOR = "game_session_canonical_issuer_installed_anchor"; @@ -67,7 +68,9 @@ void recordPartitionProof(CanonicalGameplayIssuerBootstrapPartitionRedisOwner.Re requireProofContext(input, currentPlan); Record existing = transaction.fetchOne( - "SELECT * FROM " + PROOF + " WHERE bootstrap_operation_id = ? AND partition_id = ? FOR UPDATE", + "SELECT * FROM " + + PROOF + + " WHERE bootstrap_operation_id = ? AND partition_id = ? FOR UPDATE", currentPlan.bootstrapIntent().operationId(), input.partitionId()); if (existing != null) { @@ -76,7 +79,9 @@ void recordPartitionProof(CanonicalGameplayIssuerBootstrapPartitionRedisOwner.Re } int inserted = transaction.execute( - "INSERT INTO " + PROOF + " (" + "INSERT INTO " + + PROOF + + " (" + "build_operation_id, bootstrap_operation_id, bootstrap_request_id, issuer_id, " + "build_plan_digest, bootstrap_operation_fence, bootstrap_coverage_fence, " + "issuer_inventory_snapshot_revision, layout_version, partition_count, " @@ -120,10 +125,13 @@ void recordPartitionProof(CanonicalGameplayIssuerBootstrapPartitionRedisOwner.Re if (inserted != 1) throw conflict("Exact partition proof did not persist"); Record saved = transaction.fetchOne( - "SELECT * FROM " + PROOF + " WHERE bootstrap_operation_id = ? AND partition_id = ?", + "SELECT * FROM " + + PROOF + + " WHERE bootstrap_operation_id = ? AND partition_id = ?", input.bootstrapOperationId(), input.partitionId()); - if (saved == null) throw conflict("Exact partition proof is unreadable after persistence"); + if (saved == null) + throw conflict("Exact partition proof is unreadable after persistence"); requireSameProof(saved, input); }); } @@ -157,6 +165,163 @@ Optional readInstalledAnchor( }); } + /** + * Requalifies an installed anchor while the binding inventory clock is already locked. The caller + * must acquire that clock before entering this method so the issuer-control lock remains second + * in the shared inventory -> issuer -> account order. + */ + static CanonicalGameplayIssuerInstalledAnchor + readInstalledAnchorForBindingPreparationInTransaction( + DSLContext transaction, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState) { + Objects.requireNonNull(transaction, "transaction"); + Objects.requireNonNull(currentState, "currentState"); + + Record control = + transaction.fetchOne( + "SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (control == null + || !ISSUER.equals(requireText(control, "issuer_id")) + || !"INITIAL_BOOTSTRAP_INTENT".equals(requireText(control, "state"))) { + throw conflict("Ordinary NEW requires the positive current installed issuer-control row"); + } + UUID currentOperationId = requireUuid(control, "current_operation_id"); + BigInteger controlEpoch = readInteger(control, "control_epoch"); + BigInteger operationFence = readInteger(control, "current_operation_fence"); + BigInteger coverageFence = readInteger(control, "current_coverage_fence"); + if (controlEpoch.signum() <= 0 + || !controlEpoch.equals(operationFence) + || coverageFence.signum() <= 0 + || coverageFence.equals(operationFence) + || readInteger(control, "last_issued_fence").compareTo(coverageFence) < 0) { + throw conflict("Current issuer-control tuple is malformed or no longer positive"); + } + + List issuerIntents = + transaction.fetch( + "SELECT operation_id FROM " + + "game_session_canonical_issuer_layout_bootstrap_intent" + + " WHERE issuer_id = ? ORDER BY operation_id FOR UPDATE", + ISSUER); + if (issuerIntents.size() != 1 + || !currentOperationId.equals(requireUuid(issuerIntents.get(0), "operation_id"))) { + throw conflict("A conflicting or unpointed issuer layout intent prevents ordinary NEW"); + } + + Record intentRequest = + transaction.fetchOne( + "SELECT request_id FROM " + + "game_session_canonical_issuer_layout_bootstrap_intent" + + " WHERE operation_id = ? AND issuer_id = ?", + currentOperationId, + ISSUER); + if (intentRequest == null) + throw conflict("Current issuer control points to no durable layout intent"); + CanonicalGameplayIssuerPartitionBuildPlan plan = + new CanonicalGameplayIssuerPartitionBuildRepository(transaction) + .readInstalledPlanForAnchorInTransaction( + transaction, currentOperationId, requireUuid(intentRequest, "request_id")); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); + if (!currentOperationId.equals(intent.operationId()) + || !controlEpoch.equals(intent.controlEpoch()) + || !operationFence.equals(intent.operationFence()) + || !coverageFence.equals(intent.coverageFence())) { + throw conflict("Current issuer control no longer points at its exact initial intent tuple"); + } + requireCurrentState(currentState, intent); + + Record anchorRow = + transaction.fetchOne("SELECT * FROM " + ANCHOR + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (anchorRow == null) { + throw conflict("Ordinary NEW requires an actual immutable installed issuer anchor"); + } + CanonicalGameplayIssuerInstalledAnchor actual = loadAnchor(anchorRow); + requireAnchorMatchesPlan(actual, plan, currentState); + requireProofSummaryMatchesAnchor( + verifyCompleteProof(transaction, plan, actual.incarnationBytes()), actual); + requireCounterCoversAnchor(transaction, actual); + return actual; + } + + /** Exact immutable baseline field set for one partition of the installed initial anchor. */ + static InstalledAnchorPartitionProof readInstalledAnchorPartitionProof( + DSLContext transaction, + CanonicalGameplayIssuerInstalledAnchor anchor, + BigInteger partitionId) { + Objects.requireNonNull(transaction, "transaction"); + Objects.requireNonNull(anchor, "anchor"); + Objects.requireNonNull(partitionId, "partitionId"); + if (partitionId.signum() < 0 || partitionId.compareTo(anchor.partitionCount()) >= 0) { + throw conflict("Candidate partition is outside the exact installed layout"); + } + Record row = + transaction.fetchOne( + "SELECT * FROM " + PROOF + " WHERE bootstrap_operation_id = ? AND partition_id = ?", + anchor.bootstrapOperationId(), + new BigDecimal(partitionId)); + if (row == null + || !"EXACT_PHYSICAL_READBACK".equals(requireText(row, "proof_state")) + || !anchor.operationFence().equals(readInteger(row, "bootstrap_operation_fence")) + || !anchor.coverageFence().equals(readInteger(row, "bootstrap_coverage_fence")) + || !anchor + .issuerInventorySnapshotRevision() + .equals(readInteger(row, "issuer_inventory_snapshot_revision"))) { + throw conflict("Exact installed-anchor partition proof is missing or mismatched"); + } + byte[] fieldSetBytes = requireBytes(row, "exact_physical_field_set_bytes"); + String fieldSetDigest = requireText(row, "exact_physical_field_set_digest"); + if (!fieldSetDigest.equals(CanonicalGameplayIssuerMemberV2Codec.sha256(fieldSetBytes))) { + throw conflict("Installed-anchor partition field set does not match its exact digest"); + } + return new InstalledAnchorPartitionProof( + partitionId, + fieldSetBytes, + fieldSetDigest, + readInt(row, "physical_counted_capacity_count"), + readInt(row, "physical_reservation_count"), + readInt(row, "physical_binding_count")); + } + + /** Refuses a post-anchor candidate whose exact field already exists in the frozen baseline. */ + static void requireNewMemberAbsentFromBaseline( + InstalledAnchorPartitionProof proof, + CanonicalGameplayBindingRef bindingRef, + UUID reservationId) { + Objects.requireNonNull(proof, "proof"); + Objects.requireNonNull(bindingRef, "bindingRef"); + Objects.requireNonNull(reservationId, "reservationId"); + Map fields = decodeFieldSet(proof.exactPhysicalFieldSetBytes()); + if (fields.containsKey(new String(bindingRef.bytes(), StandardCharsets.UTF_8)) + || fields.containsKey(CAPACITY_PREFIX + reservationId)) { + throw conflict( + "Installed issuer baseline already contains the requested NEW member or reservation"); + } + } + + record InstalledAnchorPartitionProof( + BigInteger partitionId, + byte[] exactPhysicalFieldSetBytes, + String exactPhysicalFieldSetDigest, + int physicalCountedCapacityCount, + int physicalReservationCount, + int physicalBindingCount) { + InstalledAnchorPartitionProof { + Objects.requireNonNull(partitionId, "partitionId"); + exactPhysicalFieldSetBytes = Objects.requireNonNull(exactPhysicalFieldSetBytes).clone(); + Objects.requireNonNull(exactPhysicalFieldSetDigest, "exactPhysicalFieldSetDigest"); + if (physicalCountedCapacityCount < 0 + || physicalReservationCount < 0 + || physicalBindingCount < 0) { + throw new IllegalArgumentException("Installed partition proof counts must be nonnegative"); + } + } + + @Override + public byte[] exactPhysicalFieldSetBytes() { + return exactPhysicalFieldSetBytes.clone(); + } + } + void verifyExistingPartitionProof( CanonicalGameplayIssuerBootstrapPartitionRedisOwner.Readback readback) { Objects.requireNonNull(readback, "readback"); @@ -176,7 +341,9 @@ void verifyExistingPartitionProof( requireProofContext(input, currentPlan); Record row = transaction.fetchOne( - "SELECT * FROM " + PROOF + " WHERE bootstrap_operation_id = ? AND partition_id = ?", + "SELECT * FROM " + + PROOF + + " WHERE bootstrap_operation_id = ? AND partition_id = ?", input.bootstrapOperationId(), input.partitionId()); if (row == null) throw conflict("Installed anchor is missing an exact partition proof"); @@ -225,7 +392,9 @@ CanonicalGameplayIssuerInstalledAnchor installInitialAnchor( createAnchor(plan, currentState, generation, proof); int inserted = transaction.execute( - "INSERT INTO " + ANCHOR + " (" + "INSERT INTO " + + ANCHOR + + " (" + "issuer_id, bootstrap_operation_id, bootstrap_request_id, build_operation_id, " + "build_plan_digest, control_epoch, issuer_coverage_operation_id, operation_fence, " + "coverage_fence, issuer_inventory_snapshot_revision, layout_version, partition_count, " @@ -236,10 +405,14 @@ CanonicalGameplayIssuerInstalledAnchor installInitialAnchor( + "physical_binding_count, aggregate_counted_capacity, partition_proof_root_digest, " + "exact_anchor_bytes, exact_anchor_digest, anchor_state) " + "SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'INITIAL_INSTALLED' " - + "FROM " + CONTROL + " c WHERE c.issuer_id = ? AND c.state = 'INITIAL_BOOTSTRAP_INTENT' " + + "FROM " + + CONTROL + + " c WHERE c.issuer_id = ? AND c.state = 'INITIAL_BOOTSTRAP_INTENT' " + "AND c.control_epoch = ? AND c.current_operation_id = ? " + "AND c.current_operation_fence = ? AND c.current_coverage_fence = ? " - + "AND NOT EXISTS (SELECT 1 FROM " + ANCHOR + " a WHERE a.issuer_id = c.issuer_id)", + + "AND NOT EXISTS (SELECT 1 FROM " + + ANCHOR + + " a WHERE a.issuer_id = c.issuer_id)", anchor.issuerId(), anchor.bootstrapOperationId(), anchor.bootstrapRequestId(), @@ -278,8 +451,7 @@ CanonicalGameplayIssuerInstalledAnchor installInitialAnchor( intent.coverageFence()); if (inserted != 1) throw conflict("Exact initial issuer anchor compare-and-set refused"); Record saved = - transaction.fetchOne( - "SELECT * FROM " + ANCHOR + " WHERE issuer_id = ?", ISSUER); + transaction.fetchOne("SELECT * FROM " + ANCHOR + " WHERE issuer_id = ?", ISSUER); if (saved == null) throw conflict("Installed issuer anchor is unreadable after its CAS"); CanonicalGameplayIssuerInstalledAnchor result = loadAnchor(saved); requireSameAnchor(result, anchor); @@ -293,7 +465,8 @@ private CanonicalGameplayIssuerInstalledAnchor createAnchor( BigInteger generation, ProofSummary proof) { CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); - CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor layout = intent.layoutDescriptor(); + CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor layout = + intent.layoutDescriptor(); CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint source = intent.sourceCheckpoint(); byte[] incarnationBytes = @@ -332,7 +505,7 @@ private CanonicalGameplayIssuerInstalledAnchor createAnchor( null); } - private ProofSummary verifyCompleteProof( + private static ProofSummary verifyCompleteProof( DSLContext transaction, CanonicalGameplayIssuerPartitionBuildPlan plan, byte[] expectedIncarnationBytes) { @@ -346,10 +519,12 @@ private ProofSummary verifyCompleteProof( intent.operationId()); BigInteger partitionCount = intent.layoutDescriptor().partitionCount(); if (!BigInteger.valueOf(proofRows.size()).equals(partitionCount)) { - throw conflict("Initial issuer anchor requires one positive physical proof per finite partition"); + throw conflict( + "Initial issuer anchor requires one positive physical proof per finite partition"); } - Map worksByOrdinal = new HashMap<>(); + Map worksByOrdinal = + new HashMap<>(); Map exactOperationValues = new HashMap<>(); Map expectedReservationsByPartition = new HashMap<>(); Map expectedCapacityByPartition = new HashMap<>(); @@ -365,10 +540,13 @@ private ProofSummary verifyCompleteProof( } List operations = transaction.fetch( - "SELECT * FROM " + OPERATION + " WHERE bootstrap_operation_id = ? ORDER BY work_ordinal", + "SELECT * FROM " + + OPERATION + + " WHERE bootstrap_operation_id = ? ORDER BY work_ordinal", intent.operationId()); if (operations.size() != plan.memberWorks().size()) { - throw conflict("Finite coverage cannot complete while any SQL member operation is unresolved"); + throw conflict( + "Finite coverage cannot complete while any SQL member operation is unresolved"); } for (Record operation : operations) { long ordinal = requireNonNegativeLong(operation, "work_ordinal"); @@ -389,7 +567,8 @@ private ProofSummary verifyCompleteProof( if (exactOperationValues.putIfAbsent(work.reservationId(), bytes) != null) { throw conflict("Finite SQL work contains a duplicate reservation identity"); } - if (Boolean.TRUE.equals(operation.get("expected_binding_present", Boolean.class))) expectedBindingCount++; + if (Boolean.TRUE.equals(operation.get("expected_binding_present", Boolean.class))) + expectedBindingCount++; } BigInteger expectedPartition = BigInteger.ZERO; @@ -397,22 +576,27 @@ private ProofSummary verifyCompleteProof( BigInteger bindingCount = BigInteger.ZERO; BigInteger aggregateCountedCapacity = BigInteger.ZERO; BigInteger expectedAggregateCapacity = BigInteger.valueOf(expectedCapacityCount); - BigInteger aggregateBound = partitionCount.multiply(intent.layoutDescriptor().partitionCapacity()); + BigInteger aggregateBound = + partitionCount.multiply(intent.layoutDescriptor().partitionCapacity()); MessageDigest root = sha256Digest(); for (Record row : proofRows) { BigInteger partitionId = readInteger(row, "partition_id"); if (!partitionId.equals(expectedPartition)) { - throw conflict("Initial issuer physical proof set is not the exact contiguous finite range"); + throw conflict( + "Initial issuer physical proof set is not the exact contiguous finite range"); } requireProofMatchesPlan(row, plan, expectedIncarnationBytes, partitionId); - int expectedPartitionReservations = expectedReservationsByPartition.getOrDefault(partitionId, 0); + int expectedPartitionReservations = + expectedReservationsByPartition.getOrDefault(partitionId, 0); int expectedPartitionCapacity = expectedCapacityByPartition.getOrDefault(partitionId, 0); - Map fields = decodeFieldSet(requireBytes(row, "exact_physical_field_set_bytes")); + Map fields = + decodeFieldSet(requireBytes(row, "exact_physical_field_set_bytes")); byte[] metadata = fields.get(METADATA_FIELD); if (metadata == null || !Arrays.equals(metadata, requireBytes(row, "exact_metadata_bytes"))) { throw conflict("Partition proof does not retain its exact common physical metadata"); } - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.requireExactMetadata(metadata, metadata); + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.requireExactMetadata( + metadata, metadata); Set reservationIds = new HashSet<>(); int physicalBindings = 0; int physicalCapacity = 0; @@ -457,7 +641,9 @@ private ProofSummary verifyCompleteProof( } else { CanonicalGameplayBindingRef bindingRef; try { - bindingRef = CanonicalGameplayBindingRef.fromExactBytes(fieldName.getBytes(StandardCharsets.UTF_8)); + bindingRef = + CanonicalGameplayBindingRef.fromExactBytes( + fieldName.getBytes(StandardCharsets.UTF_8)); } catch (RuntimeException malformed) { throw conflict("Physical issuer binding field has invalid canonical identity"); } @@ -469,7 +655,9 @@ private ProofSummary verifyCompleteProof( } } expectedFieldNames.addAll( - reservationIds.stream().map(CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec::reservationField).toList()); + reservationIds.stream() + .map(CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec::reservationField) + .toList()); if (!expectedFieldNames.equals(fields.keySet()) || physicalReservations != expectedPartitionReservations || physicalCapacity != expectedPartitionCapacity @@ -478,18 +666,24 @@ private ProofSummary verifyCompleteProof( || physicalBindings != readInt(row, "physical_binding_count") || physicalCapacity != readInt(row, "physical_counted_capacity_count") || fields.size() != readInt(row, "physical_field_count") - || !expectedAggregateCapacity.equals(readInteger(row, "planned_aggregate_capacity_count"))) { + || !expectedAggregateCapacity.equals( + readInteger(row, "planned_aggregate_capacity_count"))) { throw conflict("Physical partition proof differs from SQL work or capacity expectations"); } - if (BigInteger.valueOf(physicalCapacity).compareTo(intent.layoutDescriptor().partitionCapacity()) > 0) { + if (BigInteger.valueOf(physicalCapacity) + .compareTo(intent.layoutDescriptor().partitionCapacity()) + > 0) { throw conflict("Physical issuer partition exceeds its pinned reservation capacity"); } reservationCount = reservationCount.add(BigInteger.valueOf(physicalReservations)); bindingCount = bindingCount.add(BigInteger.valueOf(physicalBindings)); aggregateCountedCapacity = aggregateCountedCapacity.add(BigInteger.valueOf(physicalCapacity)); updateRoot(root, partitionId.toString().getBytes(StandardCharsets.US_ASCII)); - updateRoot(root, CanonicalGameplayIssuerMemberV2Codec.sha256( - requireBytes(row, "exact_physical_field_set_bytes")).getBytes(StandardCharsets.US_ASCII)); + updateRoot( + root, + CanonicalGameplayIssuerMemberV2Codec.sha256( + requireBytes(row, "exact_physical_field_set_bytes")) + .getBytes(StandardCharsets.US_ASCII)); expectedPartition = expectedPartition.add(BigInteger.ONE); } if (!expectedPartition.equals(partitionCount) @@ -497,7 +691,8 @@ private ProofSummary verifyCompleteProof( || !bindingCount.equals(BigInteger.valueOf(expectedBindingCount)) || !aggregateCountedCapacity.equals(expectedAggregateCapacity) || aggregateCountedCapacity.compareTo(aggregateBound) > 0) { - throw conflict("Initial issuer proof does not cover complete reservation and aggregate capacity"); + throw conflict( + "Initial issuer proof does not cover complete reservation and aggregate capacity"); } return new ProofSummary( proofRows.size(), @@ -531,8 +726,7 @@ private static void requireOperationMatches( var reservation = value.reservation(); var anchor = value.anchor(); var operation = value.memberOperation(); - if (!requireUuid(row, "member_operation_id").equals(work.memberOperationId()) - || !requireUuid(row, "bootstrap_operation_id").equals(intent.operationId()) + if (!requireUuid(row, "bootstrap_operation_id").equals(intent.operationId()) || !requireUuid(row, "bootstrap_request_id").equals(intent.requestId()) || !requireUuid(row, "build_operation_id").equals(plan.buildOperationId()) || !plan.planDigest().equals(requireText(row, "build_plan_digest")) @@ -555,7 +749,9 @@ private static void requireOperationMatches( || !reservation.transitionId().equals(work.transitionId()) || !reservation.partitionId().equals(work.plannedPartitionId()) || !reservation.issuerCoverageOperationId().equals(work.originalIssuerCoverageOperationId()) - || !reservation.issuerCoverageOperationFence().equals(work.originalIssuerCoverageOperationFence()) + || !reservation + .issuerCoverageOperationFence() + .equals(work.originalIssuerCoverageOperationFence()) || !reservation.coverageFence().equals(work.originalCoverageFence()) || !reservation.inventorySnapshotRevision().equals(work.originalInventorySnapshotRevision()) || !work.reservationLifecycle().equals(reservation.lifecycle().name()) @@ -565,21 +761,32 @@ private static void requireOperationMatches( || !anchor.coverageFence().equals(intent.coverageFence()) || !anchor.issuerInventorySnapshotRevision().equals(intent.inventorySnapshotRevision()) || !value.issuerControlEpoch().equals(intent.controlEpoch()) - || !Arrays.equals(value.layoutDescriptor().exactDescriptorBytes(), intent.layoutDescriptor().exactDescriptorBytes()) + || !Arrays.equals( + value.layoutDescriptor().exactDescriptorBytes(), + intent.layoutDescriptor().exactDescriptorBytes()) || !Arrays.equals(work.bindingRef(), value.owner().bindingRef().bytes()) - || !Boolean.valueOf(work.countsTowardCapacity()).equals(row.get("counts_toward_capacity", Boolean.class)) - || !Boolean.valueOf(isBindingPresent(row)).equals(row.get("expected_binding_present", Boolean.class)) + || !Boolean.valueOf(work.countsTowardCapacity()) + .equals(row.get("counts_toward_capacity", Boolean.class)) + || !Boolean.valueOf(isBindingPresent(row)) + .equals(row.get("expected_binding_present", Boolean.class)) || !work.reservationId().equals(requireUuid(row, "reservation_id")) - || !work.reservationSourceRowDigest().equals(requireText(row, "reservation_source_row_digest")) - || !work.originalIssuerCoverageOperationId().equals(requireUuid(row, "original_issuer_coverage_operation_id")) - || !work.originalIssuerCoverageOperationFence().equals(readInteger(row, "original_issuer_coverage_operation_fence")) + || !work.reservationSourceRowDigest() + .equals(requireText(row, "reservation_source_row_digest")) + || !work.originalIssuerCoverageOperationId() + .equals(requireUuid(row, "original_issuer_coverage_operation_id")) + || !work.originalIssuerCoverageOperationFence() + .equals(readInteger(row, "original_issuer_coverage_operation_fence")) || !work.originalCoverageFence().equals(readInteger(row, "original_coverage_fence")) - || !work.originalInventorySnapshotRevision().equals(readInteger(row, "original_inventory_snapshot_revision")) + || !work.originalInventorySnapshotRevision() + .equals(readInteger(row, "original_inventory_snapshot_revision")) || !intent.operationId().equals(requireUuid(row, "bootstrap_anchor_operation_id")) || !intent.operationFence().equals(readInteger(row, "bootstrap_anchor_operation_fence")) || !intent.coverageFence().equals(readInteger(row, "bootstrap_anchor_coverage_fence")) - || !intent.inventorySnapshotRevision().equals(readInteger(row, "bootstrap_anchor_inventory_snapshot_revision"))) { - throw conflict("SQL member operation does not match its exact reservation, anchor, and plan tuple"); + || !intent + .inventorySnapshotRevision() + .equals(readInteger(row, "bootstrap_anchor_inventory_snapshot_revision"))) { + throw conflict( + "SQL member operation does not match its exact reservation, anchor, and plan tuple"); } } @@ -600,19 +807,25 @@ private static void requireProofMatchesPlan( || !plan.planDigest().equals(requireText(row, "build_plan_digest")) || !intent.operationFence().equals(readInteger(row, "bootstrap_operation_fence")) || !intent.coverageFence().equals(readInteger(row, "bootstrap_coverage_fence")) - || !intent.inventorySnapshotRevision().equals(readInteger(row, "issuer_inventory_snapshot_revision")) + || !intent + .inventorySnapshotRevision() + .equals(readInteger(row, "issuer_inventory_snapshot_revision")) || !layout.layoutVersion().equals(readInteger(row, "layout_version")) || !layout.partitionCount().equals(readInteger(row, "partition_count")) || !layout.partitionCapacity().equals(readInteger(row, "partition_capacity")) || !layout.mappingIdentity().equals(requireText(row, "mapping_identity")) - || !Arrays.equals(layout.exactDescriptorBytes(), requireBytes(row, "layout_descriptor_bytes")) + || !Arrays.equals( + layout.exactDescriptorBytes(), requireBytes(row, "layout_descriptor_bytes")) || !layout.descriptorDigest().equals(requireText(row, "layout_descriptor_digest")) - || !Arrays.equals(source.exactCheckpointBytes(), requireBytes(row, "source_checkpoint_bytes")) + || !Arrays.equals( + source.exactCheckpointBytes(), requireBytes(row, "source_checkpoint_bytes")) || !source.checkpointDigest().equals(requireText(row, "source_checkpoint_digest")) || !Arrays.equals(expectedEvent, optionalBytes(row, "source_event_bytes")) - || !Objects.equals(source.latestIssuerEventDigest(), row.get("source_event_digest", String.class)) + || !Objects.equals( + source.latestIssuerEventDigest(), row.get("source_event_digest", String.class)) || !Arrays.equals(expectedIncarnationBytes, exactIncarnation) - || !CanonicalGameplayIssuerMemberV2Codec.sha256(exactIncarnation).equals(requireText(row, "incarnation_digest")) + || !CanonicalGameplayIssuerMemberV2Codec.sha256(exactIncarnation) + .equals(requireText(row, "incarnation_digest")) || !partitionId.equals(readInteger(row, "partition_id")) || !"EXACT_PHYSICAL_READBACK".equals(requireText(row, "proof_state"))) { throw conflict("Persisted physical proof differs from the exact current plan tuple"); @@ -671,7 +884,8 @@ private static void requireAnchorMatchesPlan( || !Objects.equals(anchor.sourceEventDigest(), source.latestIssuerEventDigest()) || !Arrays.equals(anchor.incarnationBytes(), currentIncarnation) || !sameCheckpoint(current.accountCheckpoint(), source)) { - throw conflict("Installed issuer anchor does not match the exact current source and initial layout"); + throw conflict( + "Installed issuer anchor does not match the exact current source and initial layout"); } } @@ -694,7 +908,7 @@ private static void requireCounterCoversAnchor( anchor.issuerId()); if (counter == null || readInteger(counter, "last_issued_coverage_generation") - .compareTo(anchor.globalCoverageGeneration()) + .compareTo(anchor.globalCoverageGeneration()) < 0) { throw conflict("Installed anchor generation is beyond the current global issuer counter"); } @@ -711,7 +925,8 @@ private static void requireSameAnchor( CanonicalGameplayIssuerInstalledAnchor expected) { if (!Arrays.equals(actual.exactAnchorBytes(), expected.exactAnchorBytes()) || !actual.exactAnchorDigest().equals(expected.exactAnchorDigest())) { - throw conflict("Installed issuer anchor readback differs from its exact owner-issued pointer"); + throw conflict( + "Installed issuer anchor readback differs from its exact owner-issued pointer"); } } @@ -756,7 +971,9 @@ private static CanonicalGameplayIssuerInstalledAnchor loadAnchor(Record row) { private BigInteger allocateGlobalCoverageGeneration(DSLContext transaction) { transaction.execute( - "INSERT INTO " + COUNTER + " (issuer_id, last_issued_coverage_generation, counter_version) " + "INSERT INTO " + + COUNTER + + " (issuer_id, last_issued_coverage_generation, counter_version) " + "VALUES (?, 0, 0) ON CONFLICT (issuer_id) DO NOTHING", ISSUER); Record counter = @@ -766,10 +983,12 @@ private BigInteger allocateGlobalCoverageGeneration(DSLContext transaction) { BigInteger previous = readInteger(counter, "last_issued_coverage_generation"); long version = requireNonNegativeLong(counter, "counter_version"); BigInteger next = previous.add(BigInteger.ONE); - if (next.toString().length() > 256) throw conflict("Global issuer coverage generation is outside its bound"); + if (next.toString().length() > 256) + throw conflict("Global issuer coverage generation is outside its bound"); int updated = transaction.execute( - "UPDATE " + COUNTER + "UPDATE " + + COUNTER + " SET last_issued_coverage_generation = ?, counter_version = ?, updated_at = CURRENT_TIMESTAMP " + "WHERE issuer_id = ? AND last_issued_coverage_generation = ? AND counter_version = ?", next, @@ -795,8 +1014,11 @@ private static ProofInput proofInput( || readback.physicalPartitionReservationCount() != physical.reservationCount() || readback.physicalBindingCount() != physical.bindingCount() || readback.physicalCountedCapacityCount() != physical.countedReservationCount() - || !readback.plannedAggregateCapacityCount().equals(physical.plannedAggregateCapacityCount())) { - throw conflict("Physical Redis readback capability differs from its exact prepared field set"); + || !readback + .plannedAggregateCapacityCount() + .equals(physical.plannedAggregateCapacityCount())) { + throw conflict( + "Physical Redis readback capability differs from its exact prepared field set"); } return new ProofInput( plan.buildOperationId(), @@ -878,38 +1100,48 @@ private static void requireSameProof(Record row, ProofInput expected) { || !expected.planDigest().equals(requireText(row, "build_plan_digest")) || !expected.operationFence().equals(readInteger(row, "bootstrap_operation_fence")) || !expected.coverageFence().equals(readInteger(row, "bootstrap_coverage_fence")) - || !expected.snapshotRevision().equals(readInteger(row, "issuer_inventory_snapshot_revision")) + || !expected + .snapshotRevision() + .equals(readInteger(row, "issuer_inventory_snapshot_revision")) || !expected.layoutVersion().equals(readInteger(row, "layout_version")) || !expected.partitionCount().equals(readInteger(row, "partition_count")) || !expected.partitionCapacity().equals(readInteger(row, "partition_capacity")) || !expected.mappingIdentity().equals(requireText(row, "mapping_identity")) - || !Arrays.equals(expected.layoutDescriptorBytes(), requireBytes(row, "layout_descriptor_bytes")) + || !Arrays.equals( + expected.layoutDescriptorBytes(), requireBytes(row, "layout_descriptor_bytes")) || !expected.layoutDescriptorDigest().equals(requireText(row, "layout_descriptor_digest")) - || !Arrays.equals(expected.sourceCheckpointBytes(), requireBytes(row, "source_checkpoint_bytes")) + || !Arrays.equals( + expected.sourceCheckpointBytes(), requireBytes(row, "source_checkpoint_bytes")) || !expected.sourceCheckpointDigest().equals(requireText(row, "source_checkpoint_digest")) || !Arrays.equals(expected.sourceEventBytes(), optionalBytes(row, "source_event_bytes")) - || !Objects.equals(expected.sourceEventDigest(), row.get("source_event_digest", String.class)) + || !Objects.equals( + expected.sourceEventDigest(), row.get("source_event_digest", String.class)) || !Arrays.equals(expected.incarnationBytes(), requireBytes(row, "incarnation_bytes")) || !expected.incarnationDigest().equals(requireText(row, "incarnation_digest")) || !expected.partitionId().equals(readInteger(row, "partition_id")) || !Arrays.equals(expected.metadataBytes(), requireBytes(row, "exact_metadata_bytes")) - || !Arrays.equals(expected.fieldSetBytes(), requireBytes(row, "exact_physical_field_set_bytes")) + || !Arrays.equals( + expected.fieldSetBytes(), requireBytes(row, "exact_physical_field_set_bytes")) || !expected.fieldSetDigest().equals(requireText(row, "exact_physical_field_set_digest")) || expected.fieldCount() != readInt(row, "physical_field_count") || expected.reservationCount() != readInt(row, "physical_reservation_count") || expected.bindingCount() != readInt(row, "physical_binding_count") || expected.countedCapacityCount() != readInt(row, "physical_counted_capacity_count") - || !expected.aggregateCountedCapacity().equals(readInteger(row, "planned_aggregate_capacity_count")) + || !expected + .aggregateCountedCapacity() + .equals(readInteger(row, "planned_aggregate_capacity_count")) || !"EXACT_PHYSICAL_READBACK".equals(requireText(row, "proof_state"))) { throw conflict("Exact partition proof retry changed its original physical bytes or tuple"); } } - private static byte[] encodeFieldSet(Map fields) { + static byte[] encodeFieldSet(Map fields) { List> entries = new ArrayList<>(fields.entrySet()); - entries.sort((left, right) -> compareUnsigned( - left.getKey().getBytes(StandardCharsets.UTF_8), - right.getKey().getBytes(StandardCharsets.UTF_8))); + entries.sort( + (left, right) -> + compareUnsigned( + left.getKey().getBytes(StandardCharsets.UTF_8), + right.getKey().getBytes(StandardCharsets.UTF_8))); try { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); try (DataOutputStream output = new DataOutputStream(bytes)) { @@ -920,34 +1152,44 @@ private static byte[] encodeFieldSet(Map fields) { writeBytes(output, entry.getValue()); } } - if (bytes.size() > 17 * 1024 * 1024) throw conflict("Physical field proof exceeds its bounded storage limit"); + if (bytes.size() > 17 * 1024 * 1024) + throw conflict("Physical field proof exceeds its bounded storage limit"); return bytes.toByteArray(); } catch (IOException impossible) { - throw new IllegalStateException("Could not encode exact issuer physical readback", impossible); + throw new IllegalStateException( + "Could not encode exact issuer physical readback", impossible); } } - private static Map decodeFieldSet(byte[] encoded) { + static Map decodeFieldSet(byte[] encoded) { if (encoded.length == 0 || encoded.length > 17 * 1024 * 1024) { throw conflict("Persisted issuer physical field proof is outside its bound"); } try (DataInputStream input = new DataInputStream(new ByteArrayInputStream(encoded))) { - if (!Arrays.equals(readBytes(input, 256), FIELDSET_MAGIC.getBytes(StandardCharsets.US_ASCII))) { + if (!Arrays.equals( + readBytes(input, 256), FIELDSET_MAGIC.getBytes(StandardCharsets.US_ASCII))) { throw conflict("Persisted issuer physical field proof has an unsupported encoding"); } int count = input.readInt(); - if (count < 1 || count > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_HASH_FIELDS) { + if (count < 1 + || count > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_HASH_FIELDS) { throw conflict("Persisted issuer physical field count is outside its bound"); } Map fields = new HashMap<>(); byte[] previous = null; for (int index = 0; index < count; index++) { - byte[] rawField = readBytes(input, CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_BINDING_REF_BYTES); - if (rawField.length == 0 || (previous != null && compareUnsigned(previous, rawField) >= 0)) { + byte[] rawField = + readBytes( + input, + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_BINDING_REF_BYTES); + if (rawField.length == 0 + || (previous != null && compareUnsigned(previous, rawField) >= 0)) { throw conflict("Persisted issuer physical fields are duplicated or noncanonical"); } String field = decodeUtf8(rawField); - byte[] value = readBytes(input, CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_VALUE_BYTES); + byte[] value = + readBytes( + input, CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_VALUE_BYTES); if (value.length == 0 || fields.putIfAbsent(field, value) != null) { throw conflict("Persisted issuer physical field is empty or duplicated"); } @@ -967,7 +1209,8 @@ private static void writeBytes(DataOutputStream output, byte[] bytes) throws IOE private static byte[] readBytes(DataInputStream input, int maxBytes) throws IOException { int length = input.readInt(); - if (length < 0 || length > maxBytes) throw conflict("Issuer physical proof field exceeds its bound"); + if (length < 0 || length > maxBytes) + throw conflict("Issuer physical proof field exceeds its bound"); byte[] value = input.readNBytes(length); if (value.length != length) throw conflict("Issuer physical proof field is truncated"); return value; @@ -975,7 +1218,8 @@ private static byte[] readBytes(DataInputStream input, int maxBytes) throws IOEx private static String decodeUtf8(byte[] bytes) { try { - return StandardCharsets.UTF_8.newDecoder() + return StandardCharsets.UTF_8 + .newDecoder() .onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT) .decode(java.nio.ByteBuffer.wrap(bytes)) @@ -1113,12 +1357,35 @@ private record ProofInput( fieldSetBytes = fieldSetBytes.clone(); } - @Override public byte[] layoutDescriptorBytes() { return layoutDescriptorBytes.clone(); } - @Override public byte[] sourceCheckpointBytes() { return sourceCheckpointBytes.clone(); } - @Override public byte[] sourceEventBytes() { return sourceEventBytes == null ? null : sourceEventBytes.clone(); } - @Override public byte[] incarnationBytes() { return incarnationBytes.clone(); } - @Override public byte[] metadataBytes() { return metadataBytes.clone(); } - @Override public byte[] fieldSetBytes() { return fieldSetBytes.clone(); } + @Override + public byte[] layoutDescriptorBytes() { + return layoutDescriptorBytes.clone(); + } + + @Override + public byte[] sourceCheckpointBytes() { + return sourceCheckpointBytes.clone(); + } + + @Override + public byte[] sourceEventBytes() { + return sourceEventBytes == null ? null : sourceEventBytes.clone(); + } + + @Override + public byte[] incarnationBytes() { + return incarnationBytes.clone(); + } + + @Override + public byte[] metadataBytes() { + return metadataBytes.clone(); + } + + @Override + public byte[] fieldSetBytes() { + return fieldSetBytes.clone(); + } } private record ProofSummary( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerInstalledAnchor.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerInstalledAnchor.java index 427c587275..e80b4b8124 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerInstalledAnchor.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerInstalledAnchor.java @@ -85,13 +85,15 @@ public final class CanonicalGameplayIssuerInstalledAnchor { this.buildPlanDigest = requireDigest(buildPlanDigest, "buildPlanDigest"); this.issuerId = requireIssuer(issuerId); this.controlEpoch = requirePositive(controlEpoch, "controlEpoch"); - this.issuerCoverageOperationId = requireNonNil(issuerCoverageOperationId, "issuerCoverageOperationId"); + this.issuerCoverageOperationId = + requireNonNil(issuerCoverageOperationId, "issuerCoverageOperationId"); this.operationFence = requirePositive(operationFence, "operationFence"); this.coverageFence = requirePositive(coverageFence, "coverageFence"); if (!this.issuerCoverageOperationId.equals(this.bootstrapOperationId) || !this.controlEpoch.equals(this.operationFence) || this.operationFence.equals(this.coverageFence)) { - throw new IllegalArgumentException("Initial anchor must retain its exact distinct operation tuple"); + throw new IllegalArgumentException( + "Initial anchor must retain its exact distinct operation tuple"); } this.issuerInventorySnapshotRevision = requirePositive(issuerInventorySnapshotRevision, "issuerInventorySnapshotRevision"); @@ -104,13 +106,17 @@ public final class CanonicalGameplayIssuerInstalledAnchor { } this.layoutDescriptorBytes = nonEmpty(layoutDescriptorBytes, "layoutDescriptorBytes"); this.layoutDescriptorDigest = requireDigest(layoutDescriptorDigest, "layoutDescriptorDigest"); - requireDigestMatches(this.layoutDescriptorBytes, this.layoutDescriptorDigest, "layout descriptor"); + requireDigestMatches( + this.layoutDescriptorBytes, this.layoutDescriptorDigest, "layout descriptor"); this.issuerAuthGeneration = requirePositive(issuerAuthGeneration, "issuerAuthGeneration"); this.sourceCheckpointBytes = nonEmpty(sourceCheckpointBytes, "sourceCheckpointBytes"); this.sourceCheckpointDigest = requireDigest(sourceCheckpointDigest, "sourceCheckpointDigest"); - requireDigestMatches(this.sourceCheckpointBytes, this.sourceCheckpointDigest, "source checkpoint"); - this.sourceEventBytes = sourceEventBytes == null ? null : nonEmpty(sourceEventBytes, "sourceEventBytes"); - this.sourceEventDigest = sourceEventDigest == null ? null : requireDigest(sourceEventDigest, "sourceEventDigest"); + requireDigestMatches( + this.sourceCheckpointBytes, this.sourceCheckpointDigest, "source checkpoint"); + this.sourceEventBytes = + sourceEventBytes == null ? null : nonEmpty(sourceEventBytes, "sourceEventBytes"); + this.sourceEventDigest = + sourceEventDigest == null ? null : requireDigest(sourceEventDigest, "sourceEventDigest"); if ((this.sourceEventBytes == null) != (this.sourceEventDigest == null)) { throw new IllegalArgumentException("Account source event bytes and digest must be paired"); } @@ -120,31 +126,37 @@ public final class CanonicalGameplayIssuerInstalledAnchor { this.incarnationBytes = nonEmpty(incarnationBytes, "incarnationBytes"); this.incarnationDigest = requireDigest(incarnationDigest, "incarnationDigest"); requireDigestMatches(this.incarnationBytes, this.incarnationDigest, "stable incarnation"); - this.globalCoverageGeneration = requirePositive(globalCoverageGeneration, "globalCoverageGeneration"); + this.globalCoverageGeneration = + requirePositive(globalCoverageGeneration, "globalCoverageGeneration"); if (partitionProofCount < 1 || !BigInteger.valueOf(partitionProofCount).equals(partitionCount) || physicalReservationCount < 0 || physicalBindingCount < 0 || physicalBindingCount > physicalReservationCount) { - throw new IllegalArgumentException("Installed anchor must retain the complete finite proof counts"); + throw new IllegalArgumentException( + "Installed anchor must retain the complete finite proof counts"); } this.partitionProofCount = partitionProofCount; this.physicalReservationCount = physicalReservationCount; this.physicalBindingCount = physicalBindingCount; - this.aggregateCountedCapacity = Objects.requireNonNull(aggregateCountedCapacity, "aggregateCountedCapacity"); + this.aggregateCountedCapacity = + Objects.requireNonNull(aggregateCountedCapacity, "aggregateCountedCapacity"); if (aggregateCountedCapacity.signum() < 0 || aggregateCountedCapacity.compareTo(partitionCount.multiply(partitionCapacity)) > 0 || aggregateCountedCapacity.compareTo(BigInteger.valueOf(physicalReservationCount)) > 0) { - throw new IllegalArgumentException("Installed anchor aggregate capacity is outside its finite bound"); + throw new IllegalArgumentException( + "Installed anchor aggregate capacity is outside its finite bound"); } - this.partitionProofRootDigest = requireDigest(partitionProofRootDigest, "partitionProofRootDigest"); + this.partitionProofRootDigest = + requireDigest(partitionProofRootDigest, "partitionProofRootDigest"); this.exactAnchorBytes = encodeExactAnchor(); this.exactAnchorDigest = CanonicalGameplayIssuerMemberV2Codec.sha256(this.exactAnchorBytes); if ((storedExactAnchorBytes == null) != (storedExactAnchorDigest == null) || (storedExactAnchorBytes != null && (!java.util.Arrays.equals(this.exactAnchorBytes, storedExactAnchorBytes) || !this.exactAnchorDigest.equals(storedExactAnchorDigest)))) { - throw new IllegalArgumentException("Stored installed-anchor bytes differ from their exact tuple"); + throw new IllegalArgumentException( + "Stored installed-anchor bytes differ from their exact tuple"); } } @@ -209,37 +221,129 @@ private byte[] encodeExactAnchor() { }); } - public UUID bootstrapOperationId() { return bootstrapOperationId; } - public UUID bootstrapRequestId() { return bootstrapRequestId; } - public UUID buildOperationId() { return buildOperationId; } - public String buildPlanDigest() { return buildPlanDigest; } - public String issuerId() { return issuerId; } - public BigInteger controlEpoch() { return controlEpoch; } - public UUID issuerCoverageOperationId() { return issuerCoverageOperationId; } - public BigInteger operationFence() { return operationFence; } - public BigInteger coverageFence() { return coverageFence; } - public BigInteger issuerInventorySnapshotRevision() { return issuerInventorySnapshotRevision; } - public BigInteger layoutVersion() { return layoutVersion; } - public BigInteger partitionCount() { return partitionCount; } - public BigInteger partitionCapacity() { return partitionCapacity; } - public String mappingIdentity() { return mappingIdentity; } - public byte[] layoutDescriptorBytes() { return layoutDescriptorBytes.clone(); } - public String layoutDescriptorDigest() { return layoutDescriptorDigest; } - public BigInteger issuerAuthGeneration() { return issuerAuthGeneration; } - public byte[] sourceCheckpointBytes() { return sourceCheckpointBytes.clone(); } - public String sourceCheckpointDigest() { return sourceCheckpointDigest; } - public byte[] sourceEventBytes() { return sourceEventBytes == null ? null : sourceEventBytes.clone(); } - public String sourceEventDigest() { return sourceEventDigest; } - public byte[] incarnationBytes() { return incarnationBytes.clone(); } - public String incarnationDigest() { return incarnationDigest; } - public BigInteger globalCoverageGeneration() { return globalCoverageGeneration; } - public long partitionProofCount() { return partitionProofCount; } - public long physicalReservationCount() { return physicalReservationCount; } - public long physicalBindingCount() { return physicalBindingCount; } - public BigInteger aggregateCountedCapacity() { return aggregateCountedCapacity; } - public String partitionProofRootDigest() { return partitionProofRootDigest; } - public byte[] exactAnchorBytes() { return exactAnchorBytes.clone(); } - public String exactAnchorDigest() { return exactAnchorDigest; } + public UUID bootstrapOperationId() { + return bootstrapOperationId; + } + + public UUID bootstrapRequestId() { + return bootstrapRequestId; + } + + public UUID buildOperationId() { + return buildOperationId; + } + + public String buildPlanDigest() { + return buildPlanDigest; + } + + public String issuerId() { + return issuerId; + } + + public BigInteger controlEpoch() { + return controlEpoch; + } + + public UUID issuerCoverageOperationId() { + return issuerCoverageOperationId; + } + + public BigInteger operationFence() { + return operationFence; + } + + public BigInteger coverageFence() { + return coverageFence; + } + + public BigInteger issuerInventorySnapshotRevision() { + return issuerInventorySnapshotRevision; + } + + public BigInteger layoutVersion() { + return layoutVersion; + } + + public BigInteger partitionCount() { + return partitionCount; + } + + public BigInteger partitionCapacity() { + return partitionCapacity; + } + + public String mappingIdentity() { + return mappingIdentity; + } + + public byte[] layoutDescriptorBytes() { + return layoutDescriptorBytes.clone(); + } + + public String layoutDescriptorDigest() { + return layoutDescriptorDigest; + } + + public BigInteger issuerAuthGeneration() { + return issuerAuthGeneration; + } + + public byte[] sourceCheckpointBytes() { + return sourceCheckpointBytes.clone(); + } + + public String sourceCheckpointDigest() { + return sourceCheckpointDigest; + } + + public byte[] sourceEventBytes() { + return sourceEventBytes == null ? null : sourceEventBytes.clone(); + } + + public String sourceEventDigest() { + return sourceEventDigest; + } + + public byte[] incarnationBytes() { + return incarnationBytes.clone(); + } + + public String incarnationDigest() { + return incarnationDigest; + } + + public BigInteger globalCoverageGeneration() { + return globalCoverageGeneration; + } + + public long partitionProofCount() { + return partitionProofCount; + } + + public long physicalReservationCount() { + return physicalReservationCount; + } + + public long physicalBindingCount() { + return physicalBindingCount; + } + + public BigInteger aggregateCountedCapacity() { + return aggregateCountedCapacity; + } + + public String partitionProofRootDigest() { + return partitionProofRootDigest; + } + + public byte[] exactAnchorBytes() { + return exactAnchorBytes.clone(); + } + + public String exactAnchorDigest() { + return exactAnchorDigest; + } private static byte[] encode(IoWriter writer) { try { @@ -254,10 +358,14 @@ private static byte[] encode(IoWriter writer) { } private static void writeText(DataOutputStream output, String value) throws IOException { - writeBytes(output, Objects.requireNonNull(value, "exact text").getBytes(java.nio.charset.StandardCharsets.UTF_8)); + writeBytes( + output, + Objects.requireNonNull(value, "exact text") + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); } - private static void writeBigInteger(DataOutputStream output, BigInteger value) throws IOException { + private static void writeBigInteger(DataOutputStream output, BigInteger value) + throws IOException { writeText(output, Objects.requireNonNull(value, "exact counter").toString()); } @@ -278,12 +386,14 @@ private static void writeNullableText(DataOutputStream output, String value) thr private static UUID requireNonNil(UUID value, String name) { Objects.requireNonNull(value, name); - if (value.equals(new UUID(0L, 0L))) throw new IllegalArgumentException(name + " must not be nil"); + if (value.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException(name + " must not be nil"); return value; } private static String requireIssuer(String value) { - if (!net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.ISSUER.equals(value)) { + if (!net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.ISSUER.equals( + value)) { throw new IllegalArgumentException("Installed anchor issuer scope is not canonical"); } return value; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java index 5bc8b97bc4..8c1703afcb 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java @@ -285,6 +285,48 @@ CanonicalGameplayIssuerPartitionBuildPlan readPreparedPlanInTransaction( return plan; } + /** + * Reconstructs the immutable plan retained by an already installed initial anchor. This reads + * only the frozen V1030 cohort and V1031 plan artifacts; it deliberately does not compare them + * with the now-advancing live inventory clock or source rows. + */ + CanonicalGameplayIssuerPartitionBuildPlan readInstalledPlanForAnchorInTransaction( + DSLContext transaction, UUID bootstrapOperationId, UUID bootstrapRequestId) { + requireNonNil(bootstrapOperationId, "bootstrapOperationId"); + requireNonNil(bootstrapRequestId, "bootstrapRequestId"); + if (bootstrapOperationId.equals(bootstrapRequestId)) { + throw conflict("Bootstrap operation and request identities must be distinct"); + } + Record control = lockControl(transaction, ISSUER); + if (control == null) throw conflict("Installed initial anchor lost its issuer control row"); + Record intentRow = lockIntent(transaction, bootstrapOperationId); + if (intentRow == null) throw conflict("Installed initial anchor lost its bootstrap intent row"); + BigInteger frozenRevision = readBigInteger(intentRow, "inventory_snapshot_revision"); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = + loadAndRequireCurrentIntent( + transaction, + control, + intentRow, + bootstrapOperationId, + bootstrapRequestId, + frozenRevision); + List frozenRows = + intent.cohortRows().stream().map(IssuerCohortSourceRow::new).toList(); + DerivedPlan derived = derivePlan(intent, frozenRows); + Record buildPlanRow = + transaction.fetchOne( + "SELECT * FROM " + BUILD_PLAN + " WHERE bootstrap_operation_id = ? FOR UPDATE", + bootstrapOperationId); + if (buildPlanRow == null) + throw conflict("Installed initial anchor lost its immutable build plan"); + CanonicalGameplayIssuerPartitionBuildPlan plan = + loadAndRequireExactPlan(transaction, intent, frozenRows, derived, buildPlanRow); + if (plan.state() != CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED) { + throw conflict("Installed initial anchor plan contains an unresolved blocker"); + } + return plan; + } + /** Extracts typed source only from a plan returned by {@link #readPreparedPlanInTransaction}. */ PreparedMemberWork readPreparedMemberWorkFromVerifiedPlan( CanonicalGameplayIssuerPartitionBuildPlan plan, long workOrdinal) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRedisScriptContribution.java new file mode 100644 index 0000000000..9c9c71bd5e --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRedisScriptContribution.java @@ -0,0 +1,51 @@ +package net.firedevops.firemud.gamesession.service; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Collection; +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Passive manual-catalog contribution for ordinary binding-local issuer projection. */ +public final class CanonicalGameplayIssuerBindingLocalRedisScriptContribution + implements RedisScriptContribution { + public static final String SCRIPT_ID = "game-session.issuer-binding-local-add.v1"; + public static final String RESOURCE_PATH = "redis/lua/game-session-issuer-binding-local-add.lua"; + private static final String DESCRIPTOR_PATH = + "/redis/scripts/game-session-issuer-binding-local-add.json"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @Override + public String ownerId() { + return "game-session-service"; + } + + @Override + public Collection descriptors() { + try (InputStream input = getClass().getResourceAsStream(DESCRIPTOR_PATH)) { + if (input == null) throw unavailable(); + byte[] bytes = input.readNBytes(16 * 1024 + 1); + if (bytes.length == 0 || bytes.length > 16 * 1024) throw unavailable(); + RedisScriptDescriptor descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); + if (!ownerId().equals(descriptor.owner()) || !SCRIPT_ID.equals(descriptor.scriptId())) { + throw unavailable(); + } + return List.of(descriptor); + } catch (IOException | RuntimeException failure) { + throw unavailable(); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Issuer binding-local Redis descriptor is unavailable"); + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V1034__canonical_issuer_binding_local_operation.sql b/services/game-session-service/src/main/resources/db/migration/V1034__canonical_issuer_binding_local_operation.sql new file mode 100644 index 0000000000..4bfb697e58 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1034__canonical_issuer_binding_local_operation.sql @@ -0,0 +1,206 @@ +-- Ordinary NEW operations are registered only after a positive initial installed issuer anchor. +-- This local durable transition is not a new inventory, an issuer-wide coverage acknowledgement, +-- a tenant barrier, or admission authority. + +CREATE TABLE game_session_canonical_issuer_binding_local_operation ( + operation_id uuid NOT NULL, + request_id uuid NOT NULL, + transition_id uuid NOT NULL, + issuer_id character varying(64) NOT NULL, + candidate_account_index_fence uuid NOT NULL, + binding_ref bytea NOT NULL, + binding_generation numeric NOT NULL, + reservation_id uuid NOT NULL, + reservation_fence uuid NOT NULL, + partition_id numeric NOT NULL, + local_inventory_snapshot_revision numeric NOT NULL, + expected_prior_binding_ref bytea, + expected_prior_binding_generation numeric, + + original_issuer_coverage_operation_id uuid NOT NULL, + original_issuer_coverage_operation_fence numeric NOT NULL, + original_coverage_fence numeric NOT NULL, + original_inventory_snapshot_revision numeric NOT NULL, + + anchor_bootstrap_operation_id uuid NOT NULL, + anchor_bootstrap_request_id uuid NOT NULL, + anchor_build_operation_id uuid NOT NULL, + anchor_build_plan_digest character varying(71) NOT NULL, + anchor_control_epoch numeric NOT NULL, + anchor_issuer_coverage_operation_id uuid NOT NULL, + anchor_operation_fence numeric NOT NULL, + anchor_coverage_fence numeric NOT NULL, + anchor_issuer_inventory_snapshot_revision numeric NOT NULL, + anchor_layout_version numeric NOT NULL, + anchor_partition_count numeric NOT NULL, + anchor_partition_capacity numeric NOT NULL, + anchor_mapping_identity character varying(96) NOT NULL, + anchor_layout_descriptor_bytes bytea NOT NULL, + anchor_layout_descriptor_digest character varying(71) NOT NULL, + anchor_issuer_auth_generation numeric NOT NULL, + anchor_source_checkpoint_bytes bytea NOT NULL, + anchor_source_checkpoint_digest character varying(71) NOT NULL, + anchor_source_event_bytes bytea, + anchor_source_event_digest character varying(71), + anchor_incarnation_bytes bytea NOT NULL, + anchor_incarnation_digest character varying(71) NOT NULL, + exact_anchor_bytes bytea NOT NULL, + exact_anchor_digest character varying(71) NOT NULL, + + baseline_partition_id numeric NOT NULL, + baseline_field_set_bytes bytea NOT NULL, + baseline_field_set_digest character varying(71) NOT NULL, + baseline_counted_capacity integer NOT NULL, + baseline_reservation_count integer NOT NULL, + baseline_binding_count integer NOT NULL, + + account_control_state character varying(32) NOT NULL, + account_control_epoch numeric NOT NULL, + account_current_operation_id uuid, + account_current_fence_intent_id uuid, + account_current_operation_fence numeric, + account_admission_fence uuid, + account_historical_admission_fence uuid, + account_coverage_fence uuid, + account_inventory_snapshot_revision numeric, + account_coverage_generation numeric, + + operation_fence numeric NOT NULL, + local_member_generation numeric NOT NULL, + expected_old_member_state character varying(16) NOT NULL, + expected_old_capacity_state character varying(16) NOT NULL, + member_status character varying(32) NOT NULL, + member_schema_version smallint NOT NULL, + member_value_bytes bytea NOT NULL, + member_value_digest character varying(71) NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT pk_gs_issuer_binding_local_operation PRIMARY KEY (operation_id), + CONSTRAINT uq_gs_issuer_binding_local_operation_request UNIQUE (issuer_id, request_id), + CONSTRAINT uq_gs_issuer_binding_local_operation_transition UNIQUE (issuer_id, transition_id), + CONSTRAINT uq_gs_issuer_binding_local_operation_reservation UNIQUE (reservation_id), + CONSTRAINT uq_gs_issuer_binding_local_operation_fence UNIQUE (issuer_id, operation_fence), + CONSTRAINT uq_gs_issuer_binding_local_operation_generation UNIQUE (issuer_id, local_member_generation), + CONSTRAINT fk_gs_issuer_binding_local_operation_transition + FOREIGN KEY (transition_id) REFERENCES game_session_canonical_binding_transition (transition_id), + CONSTRAINT fk_gs_issuer_binding_local_operation_reservation + FOREIGN KEY (reservation_id) REFERENCES game_session_canonical_issuer_partition_reservation (reservation_id), + CONSTRAINT fk_gs_issuer_binding_local_operation_anchor + FOREIGN KEY (anchor_bootstrap_operation_id) + REFERENCES game_session_canonical_issuer_installed_anchor (bootstrap_operation_id), + CONSTRAINT chk_gs_issuer_binding_local_operation CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND transition_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND request_id <> transition_id + AND issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND candidate_account_index_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND octet_length(binding_ref) > 0 + AND binding_generation > 0 + AND reservation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND reservation_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND partition_id >= 0 + AND local_inventory_snapshot_revision > 0 + AND expected_prior_binding_ref IS NULL + AND expected_prior_binding_generation IS NULL + AND original_issuer_coverage_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND original_issuer_coverage_operation_fence > 0 + AND original_coverage_fence > 0 + AND original_inventory_snapshot_revision > 0 + AND anchor_bootstrap_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND anchor_bootstrap_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND anchor_build_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND anchor_build_plan_digest ~ '^sha256:[0-9a-f]{64}$' + AND anchor_control_epoch > 0 + AND anchor_issuer_coverage_operation_id = anchor_bootstrap_operation_id + AND anchor_operation_fence = anchor_control_epoch + AND anchor_operation_fence > 0 + AND anchor_coverage_fence > 0 + AND anchor_coverage_fence <> anchor_operation_fence + AND anchor_issuer_inventory_snapshot_revision > 0 + AND anchor_layout_version > 0 + AND anchor_partition_count > 0 + AND anchor_partition_capacity > 0 + AND partition_id < anchor_partition_count + AND anchor_mapping_identity = 'bindingRef/v1;sha256-u256-mod/v1' + AND octet_length(anchor_layout_descriptor_bytes) > 0 + AND anchor_layout_descriptor_digest ~ '^sha256:[0-9a-f]{64}$' + AND anchor_issuer_auth_generation > 0 + AND octet_length(anchor_source_checkpoint_bytes) > 0 + AND anchor_source_checkpoint_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((anchor_source_event_bytes IS NULL AND anchor_source_event_digest IS NULL) + OR (anchor_source_event_bytes IS NOT NULL + AND octet_length(anchor_source_event_bytes) > 0 + AND anchor_source_event_digest ~ '^sha256:[0-9a-f]{64}$')) + AND octet_length(anchor_incarnation_bytes) > 0 + AND anchor_incarnation_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(exact_anchor_bytes) BETWEEN 1 AND 262144 + AND exact_anchor_digest ~ '^sha256:[0-9a-f]{64}$' + AND baseline_partition_id = partition_id + AND octet_length(baseline_field_set_bytes) BETWEEN 1 AND 17825792 + AND baseline_field_set_digest ~ '^sha256:[0-9a-f]{64}$' + AND baseline_counted_capacity >= 0 + AND baseline_counted_capacity <= anchor_partition_capacity + AND baseline_reservation_count >= 0 + AND baseline_binding_count >= 0 + AND account_control_state IN ('NO_ACTIVE_ACCOUNT_WIDE_FLOW', 'HISTORICAL') + AND account_control_epoch >= 0 + AND ((account_control_state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW' + AND account_current_operation_id IS NULL + AND account_current_fence_intent_id IS NULL + AND account_current_operation_fence IS NULL + AND account_admission_fence IS NULL + AND account_historical_admission_fence IS NULL + AND account_coverage_fence IS NULL + AND account_inventory_snapshot_revision IS NULL + AND account_coverage_generation IS NULL) + OR (account_control_state = 'HISTORICAL' + AND account_current_operation_id IS NOT NULL + AND account_current_fence_intent_id IS NULL + AND account_current_operation_fence > 0 + AND account_admission_fence IS NULL + AND account_historical_admission_fence IS NOT NULL + AND account_coverage_fence IS NOT NULL + AND account_inventory_snapshot_revision > 0 + AND account_coverage_generation > 0)) + AND operation_fence > 0 + AND local_member_generation = operation_fence + 1 + AND expected_old_member_state = 'ABSENT' + AND expected_old_capacity_state = 'ABSENT' + AND member_status = 'PENDING_PHYSICAL_PROOF' + AND member_schema_version = 2 + AND octet_length(member_value_bytes) BETWEEN 1 AND 65536 + AND member_value_digest ~ '^sha256:[0-9a-f]{64}$') +); + +-- V1032 owns the local issuer-member operation counter. The operation below shares that +-- local-only fence/generation domain; neither value advances or substitutes for global coverage. + +-- [jooq ignore start] +-- H2 maps PostgreSQL bytea to an incomparable BLOB and cannot model this foreign key. +-- PostgreSQL still enforces the exact inventory identity; native migration proof is required. +ALTER TABLE game_session_canonical_issuer_binding_local_operation + ADD CONSTRAINT fk_gs_issuer_binding_local_operation_inventory + FOREIGN KEY (binding_ref) + REFERENCES game_session_canonical_gameplay_binding_inventory (binding_ref); + +CREATE FUNCTION game_session_reject_issuer_binding_local_operation_change() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'issuer binding-local operations are immutable' + USING ERRCODE = 'check_violation'; +END; +$$; + +CREATE TRIGGER trg_gs_issuer_binding_local_operation_immutable + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_binding_local_operation + FOR EACH ROW EXECUTE FUNCTION game_session_reject_issuer_binding_local_operation_change(); +CREATE TRIGGER trg_gs_issuer_binding_local_operation_no_truncate + BEFORE TRUNCATE ON game_session_canonical_issuer_binding_local_operation + FOR EACH STATEMENT EXECUTE FUNCTION game_session_reject_issuer_binding_local_operation_change(); +-- [jooq ignore stop] + +COMMENT ON TABLE game_session_canonical_issuer_binding_local_operation IS + 'Immutable ordinary NEW preparation linked to a positively installed initial issuer anchor; pending physical proof only, not global issuer coverage or admission.'; diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-add.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-add.lua new file mode 100644 index 0000000000..fe79426301 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-add.lua @@ -0,0 +1,404 @@ +-- Project one SQL-registered ordinary issuer reservation and, only after its V29 phase +-- qualifies, its binding member. KEYS[1] is the only issuer partition hash. +local keyPrefix = 'session:game:index:issuer:' +local metadataField = '!issuer-partition-bootstrap/v1' +local capacityPrefix = '!issuer-reservation-capacity/v1:' +local maxDecimalBytes = 256 +local maxBindingRefBytes = 6144 +local maxMemberValueBytes = 65536 +local maxMetadataBytes = 65536 +local maxMemberOperations = 256 +local maxHashFields = 1025 +local maxHashBytes = 16777216 + +local function uuid(value) + return type(value) == 'string' and #value == 36 + and string.match(value, '^%x%x%x%x%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x$') + and value == string.lower(value) + and value ~= '00000000-0000-0000-0000-000000000000' +end + +local function positive(value) + return type(value) == 'string' and #value > 0 and #value <= maxDecimalBytes + and string.match(value, '^[1-9][0-9]*$') ~= nil +end + +local function nonnegative(value) + return value == '0' or positive(value) +end + +local function digest(value) + return type(value) == 'string' and #value == 71 + and string.match(value, '^sha256:[0-9a-f]+$') ~= nil +end + +local function greaterDecimal(left, right) + if #left ~= #right then return #left > #right end + return left > right +end + +local function readSegment(bytes, offset) + local start = offset + while offset <= #bytes do + local char = string.byte(bytes, offset) + if char < 48 or char > 57 then break end + offset = offset + 1 + end + if offset == start or offset > #bytes or string.byte(bytes, offset) ~= 58 then return nil end + if offset - start > 1 and string.byte(bytes, start) == 48 then return nil end + local lengthText = string.sub(bytes, start, offset - 1) + if #lengthText > 5 then return nil end + local length = tonumber(lengthText) + if not length or length > maxBindingRefBytes or offset + length > #bytes then return nil end + local valueStart = offset + 1 + local valueEnd = offset + length + return string.sub(bytes, valueStart, valueEnd), valueEnd + 1 +end + +local function canonicalBindingRef(bytes, member) + if type(bytes) ~= 'string' or #bytes == 0 or #bytes > maxBindingRefBytes then return false end + local domain, offset = readSegment(bytes, 1) + if domain ~= 'bindingRef/v1' or not offset then return false end + local tenant, afterTenant = readSegment(bytes, offset) + local instance, afterInstance = readSegment(bytes, afterTenant) + local session, afterSession = readSegment(bytes, afterInstance) + if not tenant or not instance or not session or not afterSession or afterSession ~= #bytes + 1 then + return false + end + return uuid(tenant) and uuid(instance) and uuid(session) + and tenant == member.tenantId and instance == member.gameInstanceId and session == member.sessionId +end + +local function sameIncarnation(left, right) + if type(left) ~= 'table' or type(right) ~= 'table' + or left.attestorBinding ~= right.attestorBinding + or left.acceptedAttestationDigest ~= right.acceptedAttestationDigest + or left.coordOpsRoAclDigest ~= right.coordOpsRoAclDigest + or left.coordRedisConfigObservedDigest ~= right.coordRedisConfigObservedDigest then return false end + local a = left.targetDeploymentEvidence + local b = right.targetDeploymentEvidence + if type(a) ~= 'table' or type(b) ~= 'table' + or a.deploymentIdentity ~= b.deploymentIdentity + or a.deploymentGeneration ~= b.deploymentGeneration + or a.redisBuildIdentity ~= b.redisBuildIdentity + or a.luaScriptRegistryVersion ~= b.luaScriptRegistryVersion + or a.luaScriptRegistryDigest ~= b.luaScriptRegistryDigest + or a.startupState ~= b.startupState + or a.bootGeneration ~= b.bootGeneration + or a.startupGeneration ~= b.startupGeneration + or a.storageGeneration ~= b.storageGeneration + or a.aofGeneration ~= b.aofGeneration + or type(a.canonicalNodeSet) ~= 'table' + or type(b.canonicalNodeSet) ~= 'table' + or #a.canonicalNodeSet ~= #b.canonicalNodeSet then return false end + for index = 1, #a.canonicalNodeSet do + if a.canonicalNodeSet[index] ~= b.canonicalNodeSet[index] then return false end + end + return true +end + +local function validMember(member, memberBytes, issuerId, partitionId, metadata, bindingRef, operationId, reservationId) + if type(member) ~= 'table' or type(member.layout) ~= 'table' + or type(member.reservation) ~= 'table' or type(member.anchor) ~= 'table' + or type(member.memberOperation) ~= 'table' or type(member.incarnation) ~= 'table' + or member.schemaVersion ~= 2 or member.issuerId ~= issuerId + or member.issuerId ~= metadata.issuerId + or member.issuerAuthGeneration ~= metadata.anchor.issuerAuthGeneration + or member.issuerControlEpoch ~= metadata.issuerControlEpoch + or member.issuerIndexLayoutVersion ~= metadata.layout.version + or member.layout.partitionCount ~= metadata.layout.partitionCount + or member.layout.partitionCapacity ~= metadata.layout.partitionCapacity + or member.layout.mappingIdentity ~= metadata.layout.mappingIdentity + or member.layout.descriptorBytes ~= metadata.layout.descriptorBytes + or member.layout.descriptorDigest ~= metadata.layout.descriptorDigest + or member.anchor.issuerCoverageOperationId ~= metadata.anchor.issuerCoverageOperationId + or member.anchor.operationFence ~= metadata.anchor.operationFence + or member.anchor.coverageFence ~= metadata.anchor.coverageFence + or member.anchor.issuerInventorySnapshotRevision ~= metadata.anchor.issuerInventorySnapshotRevision + or member.anchor.sourceCheckpointBytes ~= metadata.anchor.sourceCheckpointBytes + or member.anchor.sourceCheckpointDigest ~= metadata.anchor.sourceCheckpointDigest + or member.anchor.sourceEventBytes ~= metadata.anchor.sourceEventBytes + or member.anchor.sourceEventDigest ~= metadata.anchor.sourceEventDigest + or member.reservation.reservationId ~= reservationId + or member.reservation.partitionId ~= partitionId + or member.memberOperation.operationId ~= operationId + or (bindingRef ~= nil and not canonicalBindingRef(bindingRef, member)) + or not uuid(member.accountId) or not uuid(member.tenantId) + or not uuid(member.gameInstanceId) or not uuid(member.sessionId) + or not uuid(member.playableStateNamespaceId) or not uuid(member.characterId) + or not uuid(member.regionId) or not uuid(member.reservation.transitionId) + or not uuid(member.reservation.reservationFence) + or not uuid(member.reservation.issuerCoverageOperationId) + or not positive(member.bindingGeneration) or not positive(member.issuerAuthGeneration) + or not positive(member.issuerIndexLayoutVersion) or not positive(member.regionEpoch) + or not positive(member.issuerControlEpoch) + or not positive(member.layout.partitionCount) or not positive(member.layout.partitionCapacity) + or not positive(member.reservation.issuerCoverageOperationFence) + or not positive(member.reservation.coverageFence) + or not positive(member.reservation.inventorySnapshotRevision) + or not positive(member.reservation.inventoryRevision) + or not positive(member.anchor.operationFence) + or not positive(member.anchor.coverageFence) + or not positive(member.anchor.issuerInventorySnapshotRevision) + or not positive(member.memberOperation.operationFence) + or not positive(member.memberOperation.coverageGeneration) + or not digest(member.layout.descriptorDigest) + or not digest(member.anchor.sourceCheckpointDigest) + or (member.anchor.sourceEventDigest ~= cjson.null and not digest(member.anchor.sourceEventDigest)) + or not sameIncarnation(member.incarnation, metadata.incarnation) then return false end + if member.reservation.lifecycle ~= 'RESERVED' and member.reservation.lifecycle ~= 'BOUND' + and member.reservation.lifecycle ~= 'RELEASE_PENDING' and member.reservation.lifecycle ~= 'RELEASED' then + return false + end + return true +end + +if #KEYS ~= 1 or #ARGV < 13 then return -2 end +if type(KEYS[1]) ~= 'string' or #KEYS[1] > 512 or string.sub(KEYS[1], 1, #keyPrefix) ~= keyPrefix then + return -2 +end + +local issuerId = ARGV[1] +local partitionId = ARGV[2] +local partitionCount = ARGV[3] +local partitionCapacity = ARGV[4] +local baselineCountText = ARGV[5] +if issuerId ~= 'firemud-account-service' or not nonnegative(partitionId) + or not positive(partitionCount) or not positive(partitionCapacity) + or not positive(baselineCountText) then return -2 end +local baselineCount = tonumber(baselineCountText) +if not baselineCount or baselineCount > maxHashFields then return -2 end + +local cursor = 6 +local baseline = {} +local baselineCapacity = 0 +local baselineReservations = 0 +local baselineBindings = 0 +local baselineCapacityMembers = {} +local baselineBindingMembers = {} +local metadataBytes = nil +for index = 1, baselineCount do + local field = ARGV[cursor] + local valueBytes = ARGV[cursor + 1] + cursor = cursor + 2 + if type(field) ~= 'string' or #field == 0 or baseline[field] ~= nil + or type(valueBytes) ~= 'string' or #valueBytes == 0 or #valueBytes > maxMemberValueBytes then return -2 end + baseline[field] = valueBytes + if field == metadataField then + metadataBytes = valueBytes + else + local decodedOk, value = pcall(cjson.decode, valueBytes) + if not decodedOk or type(value) ~= 'table' or type(value.reservation) ~= 'table' then return -2 end + if string.sub(field, 1, #capacityPrefix) == capacityPrefix then + local reservationId = string.sub(field, #capacityPrefix + 1) + if not uuid(reservationId) or value.reservation.reservationId ~= reservationId then return -2 end + baselineCapacityMembers[reservationId] = valueBytes + baselineReservations = baselineReservations + 1 + if value.reservation.lifecycle ~= 'RELEASED' then baselineCapacity = baselineCapacity + 1 end + else + if string.sub(field, 1, 1) == '!' + or not canonicalBindingRef(field, value) + or not uuid(value.reservation.reservationId) then return -2 end + if baselineBindingMembers[value.reservation.reservationId] ~= nil then return -2 end + baselineBindingMembers[value.reservation.reservationId] = valueBytes + baselineBindings = baselineBindings + 1 + end + end +end +for reservationId, memberBytes in pairs(baselineBindingMembers) do + if baselineCapacityMembers[reservationId] ~= memberBytes then return -2 end +end +if metadataBytes == nil or #metadataBytes > maxMetadataBytes then return -2 end +local metadataOk, metadata = pcall(cjson.decode, metadataBytes) +if not metadataOk or type(metadata) ~= 'table' or metadata.schemaVersion ~= 1 + or metadata.issuerId ~= issuerId or metadata.partitionId ~= partitionId + or type(metadata.layoutTag) ~= 'string' or #metadata.layoutTag ~= 70 + or not string.match(metadata.layoutTag, '^il%-v1%-%x+$') + or type(metadata.bootstrap) ~= 'table' or type(metadata.build) ~= 'table' + or type(metadata.layout) ~= 'table' or type(metadata.anchor) ~= 'table' + or type(metadata.incarnation) ~= 'table' + or metadata.layout.partitionCount ~= partitionCount + or metadata.layout.partitionCapacity ~= partitionCapacity + or metadata.layout.mappingIdentity ~= 'bindingRef/v1;sha256-u256-mod/v1' + or metadata.anchor.issuerCoverageOperationId ~= metadata.bootstrap.operationId + or metadata.anchor.operationFence ~= metadata.bootstrap.operationFence + or metadata.anchor.coverageFence ~= metadata.bootstrap.coverageFence + or metadata.anchor.issuerInventorySnapshotRevision ~= metadata.bootstrap.issuerInventorySnapshotRevision + or metadata.issuerControlEpoch ~= metadata.bootstrap.controlEpoch + or not uuid(metadata.bootstrap.operationId) or not uuid(metadata.bootstrap.requestId) + or not uuid(metadata.build.operationId) + or not positive(metadata.bootstrap.operationFence) + or not positive(metadata.bootstrap.coverageFence) + or metadata.bootstrap.operationFence == metadata.bootstrap.coverageFence + or not positive(metadata.bootstrap.issuerInventorySnapshotRevision) + or not positive(metadata.issuerControlEpoch) + or not digest(metadata.bootstrap.cohortDigest) + or not digest(metadata.build.planDigest) then return -2 end +local expectedKey = keyPrefix .. '{' .. metadata.layoutTag .. '}:' .. issuerId .. ':' .. partitionId +if KEYS[1] ~= expectedKey or not greaterDecimal(partitionCount, partitionId) then return -2 end + +for field, valueBytes in pairs(baseline) do + if field ~= metadataField then + local decodedOk, member = pcall(cjson.decode, valueBytes) + if not decodedOk or type(member) ~= 'table' or type(member.reservation) ~= 'table' + or type(member.memberOperation) ~= 'table' then return -2 end + if not validMember( + member, + valueBytes, + issuerId, + partitionId, + metadata, + nil, + member.memberOperation.operationId, + member.reservation.reservationId) then return -2 end + if string.sub(field, 1, #capacityPrefix) ~= capacityPrefix + and not canonicalBindingRef(field, member) then return -2 end + end +end + +local allowed = {} +local allowedCount = 0 +local totalExpectedBytes = 0 +local function putAllowed(field, valueBytes) + if type(field) ~= 'string' or #field == 0 or allowed[field] ~= nil then return false end + allowed[field] = valueBytes + allowedCount = allowedCount + 1 + totalExpectedBytes = totalExpectedBytes + #field + #valueBytes + return allowedCount <= maxHashFields and totalExpectedBytes <= maxHashBytes +end +for field, valueBytes in pairs(baseline) do + if not putAllowed(field, valueBytes) then return -2 end +end + +local operationCountText = ARGV[cursor] +cursor = cursor + 1 +if not positive(operationCountText) then return -2 end +local operationCount = tonumber(operationCountText) +if not operationCount or operationCount > maxMemberOperations then return -2 end +local seenOperationIds = {} +local seenReservationIds = {} +local seenBindings = {} +local registeredOperations = {} +local localCapacity = 0 +local localBindingCount = 0 +local targetOperationId = ARGV[cursor + operationCount * 6] +local targetReservationId = ARGV[cursor + operationCount * 6 + 1] +local targetBindingRef = ARGV[cursor + operationCount * 6 + 2] +local targetMemberBytes = ARGV[cursor + operationCount * 6 + 3] +local targetBindingPresent = ARGV[cursor + operationCount * 6 + 4] +local plannedPartitionCapacity = ARGV[cursor + operationCount * 6 + 5] +local plannedAggregateCapacity = ARGV[cursor + operationCount * 6 + 6] +local aggregateBound = ARGV[cursor + operationCount * 6 + 7] +if not uuid(targetOperationId) or not uuid(targetReservationId) + or type(targetBindingRef) ~= 'string' or type(targetMemberBytes) ~= 'string' + or (targetBindingPresent ~= '0' and targetBindingPresent ~= '1') + or not nonnegative(plannedPartitionCapacity) + or not nonnegative(plannedAggregateCapacity) + or not positive(aggregateBound) + or #ARGV ~= cursor + operationCount * 6 + 7 then return -2 end + +local targetFound = false +local position = cursor +for index = 1, operationCount do + local operationId = ARGV[position] + local bindingRef = ARGV[position + 1] + local reservationId = ARGV[position + 2] + local memberBytes = ARGV[position + 3] + local bindingPresent = ARGV[position + 4] + local countsCapacity = ARGV[position + 5] + position = position + 6 + if not uuid(operationId) or not uuid(reservationId) + or (bindingPresent ~= '0' and bindingPresent ~= '1') + or countsCapacity ~= '1' + or type(memberBytes) ~= 'string' or #memberBytes == 0 or #memberBytes > maxMemberValueBytes + or seenOperationIds[operationId] or seenReservationIds[reservationId] + or seenBindings[bindingRef] then return -2 end + local decodedOk, member = pcall(cjson.decode, memberBytes) + if not decodedOk or not validMember(member, memberBytes, issuerId, partitionId, metadata, bindingRef, operationId, reservationId) then return -2 end + if member.reservation.lifecycle == 'RELEASED' then return -2 end + seenOperationIds[operationId] = true + seenReservationIds[reservationId] = true + seenBindings[bindingRef] = true + registeredOperations[#registeredOperations + 1] = { + bindingRef = bindingRef, + reservationId = reservationId, + memberBytes = memberBytes, + bindingPresent = bindingPresent + } + localCapacity = localCapacity + 1 + local capacityField = capacityPrefix .. reservationId + if not putAllowed(capacityField, memberBytes) then return -2 end + if bindingPresent == '1' then + if string.sub(bindingRef, 1, 1) == '!' or not putAllowed(bindingRef, memberBytes) then return -2 end + localBindingCount = localBindingCount + 1 + end + if operationId == targetOperationId then + if reservationId ~= targetReservationId or bindingRef ~= targetBindingRef + or memberBytes ~= targetMemberBytes or bindingPresent ~= targetBindingPresent then return -2 end + targetFound = true + end +end +if not targetFound or not seenOperationIds[targetOperationId] + or tostring(localCapacity + baselineCapacity) ~= plannedPartitionCapacity + or greaterDecimal(plannedPartitionCapacity, partitionCapacity) + or greaterDecimal(plannedAggregateCapacity, aggregateBound) then return -2 end +local targetCapacityField = capacityPrefix .. targetReservationId +if not allowed[targetCapacityField] or allowed[targetCapacityField] ~= targetMemberBytes then return -2 end +if targetBindingPresent == '1' and allowed[targetBindingRef] ~= targetMemberBytes then return -2 end + +-- A missing header, legacy key, wrong type, expiration, omitted baseline field, extra field, +-- or conflicting registered post-baseline value is refused before any write. +local kind = redis.call('TYPE', KEYS[1]).ok +if kind ~= 'hash' or redis.call('PTTL', KEYS[1]) ~= -1 then return -1 end +local actual = redis.call('HGETALL', KEYS[1]) +if #actual % 2 ~= 0 or #actual / 2 > maxHashFields then return -1 end +local actualCapacityCount = 0 +local actualReservationCount = 0 +local actualBindingCount = 0 +local totalActualBytes = 0 +local actualFields = {} +for index = 1, #actual, 2 do + local field = actual[index] + local valueBytes = actual[index + 1] + actualFields[field] = valueBytes + totalActualBytes = totalActualBytes + #field + #valueBytes + if totalActualBytes > maxHashBytes then return -1 end + local expected = allowed[field] + if expected == nil or expected ~= valueBytes then return -1 end + if string.sub(field, 1, #capacityPrefix) == capacityPrefix then + local decodedOk, member = pcall(cjson.decode, valueBytes) + if not decodedOk or type(member) ~= 'table' or type(member.reservation) ~= 'table' then return -1 end + actualReservationCount = actualReservationCount + 1 + if member.reservation.lifecycle ~= 'RELEASED' then actualCapacityCount = actualCapacityCount + 1 end + elseif field ~= metadataField then + actualBindingCount = actualBindingCount + 1 + end +end +for _, operation in ipairs(registeredOperations) do + local capacity = actualFields[capacityPrefix .. operation.reservationId] + local binding = actualFields[operation.bindingRef] + if binding ~= nil and capacity == nil then return -1 end + if capacity ~= nil and capacity ~= operation.memberBytes then return -1 end + if binding ~= nil and binding ~= operation.memberBytes then return -1 end +end +for field, valueBytes in pairs(baseline) do + if redis.call('HGET', KEYS[1], field) ~= valueBytes then return -1 end +end +if actualCapacityCount > tonumber(plannedPartitionCapacity) + or actualReservationCount < baselineReservations + or actualBindingCount < baselineBindings + or actualBindingCount > baselineBindings + localBindingCount then return -1 end + +local capacityBefore = redis.call('HGET', KEYS[1], targetCapacityField) +local bindingBefore = redis.call('HGET', KEYS[1], targetBindingRef) +if capacityBefore ~= nil and capacityBefore ~= false and capacityBefore ~= targetMemberBytes then return -1 end +if bindingBefore ~= nil and bindingBefore ~= false and targetBindingPresent == '1' + and bindingBefore ~= targetMemberBytes then return -1 end +if targetBindingPresent == '0' and bindingBefore ~= nil and bindingBefore ~= false then return -1 end +local changedCapacity = capacityBefore == false or capacityBefore == nil +local changedBinding = targetBindingPresent == '1' and (bindingBefore == false or bindingBefore == nil) +if changedCapacity then redis.call('HSET', KEYS[1], targetCapacityField, targetMemberBytes) end +if changedBinding then redis.call('HSET', KEYS[1], targetBindingRef, targetMemberBytes) end +if changedBinding then return 2 end +if changedCapacity then return 1 end +return 3 diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-add.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-add.json new file mode 100644 index 0000000000..8e090902a7 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-add.json @@ -0,0 +1,40 @@ +{ + "scriptId": "game-session.issuer-binding-local-add.v1", + "resourcePath": "redis/lua/game-session-issuer-binding-local-add.lua", + "sha256": "af4673f3218afb68d6730a5aea901a551c24a128fc86a6e6412a6dc37ad845cf", + "owner": "game-session-service", + "principal": "gamesession_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "issuerPartition", + "ownedPrefix": "session:game:index:issuer:", + "hashTagDeclaration": "REQUIRED" + } + ], + "arguments": [ + {"name": "issuerId"}, + {"name": "partitionId"}, + {"name": "partitionCount"}, + {"name": "partitionCapacity"}, + {"name": "baselineFieldCountAndExactFieldValuePairs"}, + {"name": "registeredLocalOperationCountAndExactOperationTupleAndCurrentPhase"}, + {"name": "targetOperationAndRequiredFieldsAndCapacityCounts"} + ], + "category": "SESSION_ISSUER_INDEX", + "outcomes": [ + {"code": "CAPACITY_RESERVED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "MEMBER_PROJECTED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "LOCAL_OPERATION_REPLAY", "category": "REPLAY", "effect": "NON_MUTATING"}, + {"code": "TYPE_TTL_OR_FIELDSET_REFUSED", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, + {"code": "INVALID_ARGUMENTS_OR_CAPACITY", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} + ], + "resetSensitivity": "CLUSTER", + "tailLossBehavior": "This local one-key projection requires the exact positively installed issuer anchor, complete immutable partition baseline, and complete SQL-registered post-baseline reservation set. Existing baseline fields must all remain present and exact. A locally registered pending field may be absent or exact, while the physical owner mutates only the target original capacity field and its SQL-qualified target binding field. Missing baseline/header, legacy or malformed values, unknown fields, current source or incarnation movement, or incomplete SQL accounting leaves the operation unqualified. The result is physical readback evidence only; it does not acknowledge issuer-wide coverage, open a barrier, or authorize admission.", + "lossClass": "EMPTY_REDIS_COLD_START_OR_RESET", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [ + {"callerVersion": "v1", "payloadVersion": "v2"} + ], + "legacyPayloadShape": null +} 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 new file mode 100644 index 0000000000..2a4c14a406 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java @@ -0,0 +1,803 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.SQLException; +import java.time.Duration; +import java.util.EnumSet; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutorService; +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.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; +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.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Actual PostgreSQL/Redis proof for local ordinary NEW registration after the installed anchor. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String OWNER_PRINCIPAL = "gamesession_coord_app"; + private static final String ISSUER_KEY_PREFIX = "session:game:index:issuer:"; + private static final BigInteger LAYOUT_VERSION = BigInteger.valueOf(3); + private static final BigInteger PARTITION_COUNT = BigInteger.ONE; + private static final BigInteger PARTITION_CAPACITY = BigInteger.valueOf(2); + + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + private static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + private TestSchema schema; + private RedisClient administrator; + private RedisClient ownerClient; + private StatefulRedisConnection administratorConnection; + private RedisCommands administratorCommands; + + @BeforeEach + void setUp() { + String password = UUID.randomUUID().toString(); + administrator = createRedisClient(null, null); + administratorConnection = administrator.connect(ByteArrayCodec.INSTANCE); + administratorCommands = administratorConnection.sync(); + administratorCommands.flushdb(); + administratorCommands.aclSetuser( + OWNER_PRINCIPAL, + new AclSetuserArgs() + .reset() + .on() + .addPassword(password) + .keyPattern(ISSUER_KEY_PREFIX + "*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.HLEN) + .addCommand(CommandType.HGETALL) + .addCommand(CommandType.HSET)); + ownerClient = createRedisClient(OWNER_PRINCIPAL, password); + schema = newTestSchemaAtVersion("gs_issuer_local_new_"); + } + + @AfterEach + void tearDown() { + if (administratorConnection != null) administratorConnection.close(); + if (ownerClient != null) ownerClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + if (administrator != null) administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + if (schema != null) dropSchema(schema.schema()); + } + + @Test + void registersOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() throws Exception { + DSLContext dsl = schema.dsl(); + establishActualLegacyDisposition(dsl); + var layout = descriptor(); + UUID bootstrapRequestId = UUID.randomUUID(); + var source = sourceCheckpoint(BigInteger.valueOf(7)); + var intent = + new CanonicalGameplayIssuerLayoutBootstrapRepository(dsl) + .beginInitialBootstrapIntent(bootstrapRequestId, layout, source); + migrateRemaining(schema); + + var incarnation = stableIncarnation("local-new-anchor"); + var initialState = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + intent.sourceCheckpoint(), incarnation); + AtomicReference + currentState = new AtomicReference<>(initialState); + var operationRepository = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, currentState::get); + var firstCandidate = identity("first-new"); + var firstRequest = request("first-new-request", "first-new-transition", firstCandidate); + + assertThatThrownBy(() -> operationRepository.beginOrResumeOrdinaryNew(firstRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("anchor"); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isZero(); + assertThat(count(dsl, "game_session_canonical_gameplay_binding_inventory")).isZero(); + + CanonicalGameplayIssuerInstalledAnchor anchor = + initialCoverageOwner(dsl, currentState::get) + .completeInitialBootstrap(intent.operationId(), bootstrapRequestId); + String installedAnchorImage = anchorImage(dsl); + String installedProofImage = proofImage(dsl); + String initialReservationImage = reservationImage(dsl); + BigInteger initialGlobalCoverageGeneration = anchor.globalCoverageGeneration(); + + AtomicInteger sourceReads = new AtomicInteger(); + CyclicBarrier concurrentPreReadBarrier = new CyclicBarrier(2); + var concurrentSource = + (CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource) + () -> { + if (sourceReads.incrementAndGet() <= 2) { + try { + concurrentPreReadBarrier.await(30, TimeUnit.SECONDS); + } catch (Exception failure) { + throw new IllegalStateException( + "Concurrent source pre-reads did not rendezvous", failure); + } + } + return currentState.get(); + }; + var concurrentRepository = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, concurrentSource); + ExecutorService concurrentCallers = Executors.newFixedThreadPool(2); + CanonicalGameplayIssuerBindingLocalOperation first; + CanonicalGameplayIssuerBindingLocalOperation concurrentReplay; + try { + var firstCall = + concurrentCallers.submit( + () -> concurrentRepository.beginOrResumeOrdinaryNew(firstRequest)); + var secondCall = + concurrentCallers.submit( + () -> concurrentRepository.beginOrResumeOrdinaryNew(firstRequest)); + first = firstCall.get(30, TimeUnit.SECONDS); + concurrentReplay = secondCall.get(30, TimeUnit.SECONDS); + } finally { + concurrentCallers.shutdownNow(); + } + assertThat(sourceReads.get()).isEqualTo(4); + assertThat(concurrentReplay.operationId()).isEqualTo(first.operationId()); + assertThat(concurrentReplay.reservation().reservationId()) + .isEqualTo(first.reservation().reservationId()); + assertThat(concurrentReplay.reservation().reservationFence()) + .isEqualTo(first.reservation().reservationFence()); + assertThat(concurrentReplay.candidateAccountIndexFence()) + .isEqualTo(first.candidateAccountIndexFence()); + assertThat(concurrentReplay.operationFence()).isEqualTo(first.operationFence()); + assertThat(concurrentReplay.localMemberGeneration()).isEqualTo(first.localMemberGeneration()); + assertThat(concurrentReplay.localInventorySnapshotRevision()) + .isEqualTo(first.localInventorySnapshotRevision()); + assertThat(concurrentReplay.exactMemberValueBytes()) + .containsExactly(first.exactMemberValueBytes()); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isEqualTo(1L); + assertThat(count(dsl, "game_session_canonical_issuer_partition_reservation")).isEqualTo(1L); + assertThat(first.status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalOperation.Status.PENDING_PHYSICAL_PROOF); + assertThat(first.request()).isEqualTo(firstRequest); + assertThat(first.preparedTransition().status()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot + .Status.PREPARED); + assertThat(first.reservation().lifecycle()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation.Lifecycle + .RESERVED); + assertThat(first.reservation().issuerCoverageOperationId()) + .isEqualTo(first.anchor().issuerCoverageOperationId()); + assertThat(first.reservation().issuerCoverageOperationFence()) + .isEqualTo(first.anchor().operationFence()); + assertThat(first.reservation().coverageFence()).isEqualTo(first.anchor().coverageFence()); + assertThat(first.reservation().inventorySnapshotRevision()) + .isEqualTo(first.anchor().issuerInventorySnapshotRevision()); + assertThat(first.localInventorySnapshotRevision()) + .isEqualTo(first.reservation().inventoryRevision()); + assertThat(first.memberValue().anchor().issuerCoverageOperationId()) + .isEqualTo(anchor.issuerCoverageOperationId()); + assertThat(first.anchor().exactAnchorBytes()).containsExactly(anchor.exactAnchorBytes()); + assertThat(first.memberValue().issuerControlEpoch()).isEqualTo(anchor.controlEpoch()); + assertThat(first.memberValue().layoutDescriptor().exactDescriptorBytes()) + .containsExactly(anchor.layoutDescriptorBytes()); + assertThat(first.memberValue().layoutDescriptor().descriptorDigest()) + .isEqualTo(anchor.layoutDescriptorDigest()); + assertThat(first.memberValue().sourceCheckpoint().exactCheckpointBytes()) + .containsExactly(anchor.sourceCheckpointBytes()); + assertThat(first.memberValue().sourceCheckpoint().latestIssuerEventBytes()) + .containsExactly(anchor.sourceEventBytes()); + assertThat(first.memberValue().incarnation()).isEqualTo(incarnation); + assertThat(first.memberValue().memberOperation().coverageGeneration()) + .isEqualTo(first.localMemberGeneration()); + assertThat(first.expectedOldMemberState()).isEqualTo("ABSENT"); + assertThat(first.expectedOldCapacityState()).isEqualTo("ABSENT"); + assertThat(first.exactMemberValueBytes()) + .containsExactly(CanonicalGameplayIssuerMemberV2Codec.encode(first.memberValue())); + assertThat(first.memberValueDigest()) + .isEqualTo(CanonicalGameplayIssuerMemberV2Codec.sha256(first.exactMemberValueBytes())); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT member_status, member_schema_version FROM" + + " game_session_canonical_issuer_binding_local_operation WHERE transition_id = ?", + firstRequest.transitionId()), + "Expected local operation row") + .get("member_status", String.class)) + .isEqualTo("PENDING_PHYSICAL_PROOF"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT member_schema_version FROM" + + " game_session_canonical_issuer_binding_local_operation WHERE transition_id = ?", + firstRequest.transitionId()), + "Expected local operation row") + .get("member_schema_version", Short.class)) + .isEqualTo((short) 2); + assertThat(count(dsl, "game_session_canonical_binding_issuer_index_obligation")).isEqualTo(1L); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isEqualTo(1L); + assertThat(count(dsl, "game_session_canonical_gameplay_binding_inventory")).isEqualTo(1L); + assertThat(count(dsl, "game_session_canonical_binding_generation")).isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT last_issued_coverage_generation FROM" + + " game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", + ISSUER), + "Expected issuer coverage counter row") + .get("last_issued_coverage_generation", BigDecimal.class)) + .isEqualTo(new BigDecimal(initialGlobalCoverageGeneration)); + assertThat(anchorImage(dsl)).isEqualTo(installedAnchorImage); + assertThat(proofImage(dsl)).isEqualTo(installedProofImage); + assertThat( + administratorCommands.hlen( + CanonicalGameplayIssuerRedisKeys.forPartition( + intent.layoutDescriptor(), BigInteger.ZERO) + .getBytes(StandardCharsets.US_ASCII))) + .isEqualTo(1L); + + String afterFirstRegistration = localRegistrationImage(dsl); + CanonicalGameplayIssuerBindingLocalOperation replay = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, currentState::get) + .beginOrResumeOrdinaryNew(firstRequest); + assertThat(replay.operationId()).isEqualTo(first.operationId()); + assertThat(replay.operationFence()).isEqualTo(first.operationFence()); + assertThat(replay.localMemberGeneration()).isEqualTo(first.localMemberGeneration()); + assertThat(replay.exactMemberValueBytes()).containsExactly(first.exactMemberValueBytes()); + assertThat(localRegistrationImage(dsl)).isEqualTo(afterFirstRegistration); + assertThat(anchorImage(dsl)).isEqualTo(installedAnchorImage); + assertThat(proofImage(dsl)).isEqualTo(installedProofImage); + + String beforeRefusals = localRegistrationImage(dsl); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request("changed-first-request", "first-new-transition", firstCandidate))) + .isInstanceOf(IllegalStateException.class); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request("first-new-request", "other-transition", identity("changed-first")))) + .isInstanceOf(IllegalStateException.class); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); + + currentState.set( + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + checkpointShape(BigInteger.valueOf(8)), incarnation)); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request( + "moved-source-request", + "moved-source-transition", + identity("moved-source")))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source"); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); + currentState.set(initialState); + + currentState.set( + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + intent.sourceCheckpoint(), stableIncarnation("moved-incarnation"))); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request( + "moved-incarnation-request", + "moved-incarnation-transition", + identity("moved-incarnation")))) + .isInstanceOf(IllegalStateException.class); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); + currentState.set(initialState); + + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request( + "wrong-layout-request", + "wrong-layout-transition", + identityWithLayout("wrong-layout", BigInteger.TWO)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("layout"); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); + + var sameController = sameControllerDifferentBinding(firstCandidate, "same-controller"); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request("controller-request", "controller-transition", sameController))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("controller"); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); + + var fencedCandidate = identityForAccount("account-fenced", firstCandidate.accountId()); + new CanonicalGameplayAccountAdmissionBarrierRepository(dsl) + .beginFenceIntent(firstCandidate.accountId(), UUID.randomUUID()); + String accountFencedImage = localRegistrationImage(dsl); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request( + "account-fenced-request", "account-fenced-transition", fencedCandidate))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("Account"); + assertThat(localRegistrationImage(dsl)).isEqualTo(accountFencedImage); + + var secondCandidate = identity("second-new"); + var secondRequest = request("second-new-request", "second-new-transition", secondCandidate); + var movedAfterRegistrationState = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + checkpointShape(BigInteger.valueOf(8)), incarnation); + AtomicInteger movementReadCount = new AtomicInteger(); + var movingSource = + (CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource) + () -> + movementReadCount.incrementAndGet() == 1 + ? initialState + : movedAfterRegistrationState; + var movingRepository = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, movingSource); + assertThatThrownBy(() -> movingRepository.beginOrResumeOrdinaryNew(secondRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("pending local operation remains durable"); + UUID persistedSecondOperationId = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT operation_id FROM game_session_canonical_issuer_binding_local_operation" + + " WHERE transition_id = ?", + secondRequest.transitionId()), + "Expected local operation row") + .get("operation_id", UUID.class); + var second = operationRepository.beginOrResumeOrdinaryNew(secondRequest); + assertThat(second.operationId()).isEqualTo(persistedSecondOperationId); + assertThat(second.localMemberGeneration()).isGreaterThan(first.localMemberGeneration()); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isEqualTo(2L); + assertThat(count(dsl, "game_session_canonical_issuer_partition_reservation")).isEqualTo(2L); + assertThat(anchorImage(dsl)).isEqualTo(installedAnchorImage); + assertThat(proofImage(dsl)).isEqualTo(installedProofImage); + + String beforeCapacityRefusal = localRegistrationImage(dsl); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request("capacity-request", "capacity-transition", identity("capacity-new")))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("capacity"); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeCapacityRefusal); + assertThat(anchorImage(dsl)).isEqualTo(installedAnchorImage); + assertThat(proofImage(dsl)).isEqualTo(installedProofImage); + assertThat(reservationImage(dsl)).isNotEqualTo(initialReservationImage); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isEqualTo(2L); + assertThat( + administratorCommands.hlen( + CanonicalGameplayIssuerRedisKeys.forPartition( + intent.layoutDescriptor(), BigInteger.ZERO) + .getBytes(StandardCharsets.US_ASCII))) + .isEqualTo(1L); + } + + private CanonicalGameplayIssuerBootstrapCoverageOwner initialCoverageOwner( + DSLContext dsl, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource source) { + var partitionOwner = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner( + ownerClient, + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution())), + source); + return new CanonicalGameplayIssuerBootstrapCoverageOwner(dsl, partitionOwner, source); + } + + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor + descriptor() { + String exact = + "issuer-layout-descriptor/v1|" + + ISSUER + + "|" + + LAYOUT_VERSION + + "|" + + PARTITION_COUNT + + "|" + + PARTITION_CAPACITY + + "|" + + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY; + return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor( + ISSUER, + LAYOUT_VERSION, + PARTITION_COUNT, + PARTITION_CAPACITY, + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY, + exact.getBytes(StandardCharsets.UTF_8)); + } + + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + sourceCheckpoint(BigInteger generation) { + long sequence = generation.longValueExact() - 1; + var event = + AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + UUID.randomUUID().toString(), + UUID.randomUUID().toString(), + AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + ISSUER, + Long.toString(sequence), + ISSUER, + generation.toString(), + generation.toString(), + "ISSUER_SECURITY_CHANGE")); + byte[] bytes = event.canonicalJsonUtf8(); + return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint( + ISSUER, generation, bytes, bytes); + } + + private static CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint + checkpointShape(BigInteger generation) { + var trusted = sourceCheckpoint(generation); + byte[] checkpoint = trusted.checkpointBytes(); + byte[] event = trusted.latestEventBytes(); + return new CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint( + trusted.issuerId(), + trusted.issuerAuthGeneration(), + checkpoint, + CanonicalGameplayIssuerMemberV2Codec.sha256(checkpoint), + event, + CanonicalGameplayIssuerMemberV2Codec.sha256(event)); + } + + private static CanonicalGameplayIssuerMemberV2Value.Incarnation stableIncarnation(String seed) { + String digest = digest(seed.getBytes(StandardCharsets.UTF_8)); + var deployment = + new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "controlled-deployment-" + seed, + "deployment-generation-" + seed, + List.of("controlled-node-" + seed), + "controlled-redis-build-" + seed, + "controlled-lua-registry-" + seed, + digest, + "READY", + "boot-" + seed, + "startup-" + seed, + "storage-" + seed, + "aof-" + seed); + return new CanonicalGameplayIssuerMemberV2Value.Incarnation( + "controlled-attestor-" + seed, digest, deployment, digest, digest); + } + + private static CanonicalGameplayIssuerBindingLocalOperation.Request request( + String requestSeed, String transitionSeed, CanonicalGameplayBindingIdentity candidate) { + return new CanonicalGameplayIssuerBindingLocalOperation.Request( + UUID.nameUUIDFromBytes(requestSeed.getBytes(StandardCharsets.UTF_8)), + UUID.nameUUIDFromBytes(transitionSeed.getBytes(StandardCharsets.UTF_8)), + candidate, + null, + null); + } + + private static CanonicalGameplayBindingIdentity identity(String seed) { + return identityWithLayout(seed, LAYOUT_VERSION); + } + + private static CanonicalGameplayBindingIdentity identityForAccount(String seed, UUID accountId) { + CanonicalGameplayBindingIdentity identity = identity(seed); + return new CanonicalGameplayBindingIdentity( + accountId, + identity.tenantId(), + identity.playableStateNamespaceId(), + identity.characterId(), + identity.playableStateScope(), + identity.gameInstanceId(), + identity.runtimeGameInstanceId(), + identity.sessionId(), + identity.regionId(), + identity.regionEpoch(), + identity.issuerId(), + identity.issuerAuthGeneration(), + identity.issuerIndexLayoutVersion(), + identity.issuerIndexPartitionCount(), + identity.issuerIndexPartitionCapacity()); + } + + private static CanonicalGameplayBindingIdentity identityWithLayout( + String seed, BigInteger layoutVersion) { + return new CanonicalGameplayBindingIdentity( + uuid(seed + "-account"), + uuid(seed + "-tenant"), + uuid(seed + "-namespace"), + uuid(seed + "-character"), + "SHARED", + uuid(seed + "-game"), + 90_000L + Math.abs((long) seed.hashCode()), + uuid(seed + "-session").toString(), + uuid(seed + "-region"), + BigInteger.valueOf(12), + ISSUER, + BigInteger.valueOf(7), + layoutVersion, + PARTITION_COUNT, + PARTITION_CAPACITY); + } + + private static CanonicalGameplayBindingIdentity sameControllerDifferentBinding( + CanonicalGameplayBindingIdentity original, String seed) { + return new CanonicalGameplayBindingIdentity( + original.accountId(), + original.tenantId(), + original.playableStateNamespaceId(), + original.characterId(), + original.playableStateScope(), + uuid(seed + "-game"), + original.runtimeGameInstanceId() + 1, + uuid(seed + "-session").toString(), + original.regionId(), + original.regionEpoch(), + original.issuerId(), + original.issuerAuthGeneration(), + original.issuerIndexLayoutVersion(), + original.issuerIndexPartitionCount(), + original.issuerIndexPartitionCapacity()); + } + + private static UUID uuid(String value) { + return UUID.nameUUIDFromBytes(value.getBytes(StandardCharsets.UTF_8)); + } + + private void establishActualLegacyDisposition(DSLContext dsl) { + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); + UUID cohortId = UUID.randomUUID(); + UUID writerFence = UUID.randomUUID(); + var storageIdentity = + new CanonicalGameplayLegacyMigrationStorageIdentity( + "controlled-cluster-uid", + "controlled-namespace-uid", + "controlled-producer-pod-uid", + "controlled-container-id", + "controlled-node-uid", + "123456789", + 42L, + "controlled-postgres-volume-uid", + "controlled-redis-run-id", + "controlled-redis-volume-uid"); + var fencedCohort = + new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { + @Override + public UUID cohortId() { + return cohortId; + } + + @Override + public UUID legacyWriterFence() { + return writerFence; + } + + @Override + public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + return storageIdentity; + } + + @Override + public void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity expected) { + if (!storageIdentity.equals(expected)) { + throw new IllegalStateException("Controlled test storage identity changed"); + } + } + }; + new CanonicalGameplayLegacyMigrationOwner( + migration, + inventory, + () -> fencedCohort, + ignored -> + new CanonicalGameplayLegacyMigrationSourceSnapshot( + EnumSet.of( + Family.TENANT_SESSION_CONTEXT, + Family.SESSION_ALIAS_CONTEXT, + Family.GAMEPLAY_IDENTITY_CONTEXT, + Family.GAMEPLAY_NAME_CONTEXT, + Family.MOVEMENT_EFFECT, + Family.DURABLE_EFFECT), + List.of()), + new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { + @Override + public void rebuildExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + CanonicalGameplayLegacyMigrationSourceSnapshot source, + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot + canonical) { + assertThat(canonical.bindings()).isEmpty(); + assertThat(canonical.reservations()).isEmpty(); + } + + @Override + public CanonicalGameplayLegacyMigrationReadback readBackExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot + canonical) { + assertThat(canonical.bindings()).isEmpty(); + return new CanonicalGameplayLegacyMigrationReadback( + List.of(), List.of(), List.of(), List.of()); + } + }) + .migrate(); + } + + private TestSchema newTestSchemaAtVersion(String prefix) { + String schema = prefix + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("1030")) + .load() + .migrate(); + return new TestSchema(schema, dataSource, DSL.using(dataSource, SQLDialect.POSTGRES)); + } + + private static void migrateRemaining(TestSchema schema) { + Flyway.configure() + .dataSource(schema.dataSource()) + .schemas(schema.schema()) + .defaultSchema(schema.schema()) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + } + + private DriverManagerDataSource dataSource(String schemaName) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + String jdbcUrl = POSTGRES.getJdbcUrl(); + dataSource.setUrl( + jdbcUrl + (jdbcUrl.contains("?") ? "&" : "?") + "currentSchema=" + schemaName); + dataSource.setUsername(POSTGRES.getUsername()); + dataSource.setPassword(POSTGRES.getPassword()); + return dataSource; + } + + private void dropSchema(String schemaName) { + try (Connection connection = dataSource("public").getConnection()) { + DSL.using(connection, SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + schemaName + "\" CASCADE"); + } catch (SQLException failure) { + throw new IllegalStateException( + "Could not drop the owned issuer local-operation test schema", failure); + } + } + + private static RedisClient createRedisClient(String username, String password) { + RedisURI.Builder builder = RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(6379)); + if (username != null) builder.withAuthentication(username, password); + RedisURI uri = builder.build(); + uri.setTimeout(Duration.ofSeconds(5)); + RedisClient client = RedisClient.create(uri); + client.setOptions( + ClientOptions.builder() + .autoReconnect(false) + .protocolVersion(io.lettuce.core.protocol.ProtocolVersion.RESP2) + .build()); + return client; + } + + private static long count(DSLContext dsl, String table) { + return Objects.requireNonNull( + dsl.fetchOne("SELECT count(*) AS row_count FROM " + table), "Expected count row") + .get("row_count", Long.class); + } + + private static String anchorImage(DSLContext dsl) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT encode(exact_anchor_bytes, 'base64') || ':' || exact_anchor_digest || ':'" + + " || global_coverage_generation::text FROM" + + " game_session_canonical_issuer_installed_anchor WHERE issuer_id = ?", + ISSUER), + "Expected installed anchor row") + .get(0, String.class); + } + + private static String proofImage(DSLContext dsl) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT coalesce(string_agg(partition_id::text || ':'" + + " || encode(exact_physical_field_set_bytes, 'base64') || ':'" + + " || exact_physical_field_set_digest, '|' ORDER BY partition_id), '')" + + " FROM game_session_canonical_issuer_bootstrap_partition_proof"), + "Expected proof aggregate row") + .get(0, String.class); + } + + private static String reservationImage(DSLContext dsl) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT coalesce(jsonb_agg(to_jsonb(r) ORDER BY reservation_id), '[]'::jsonb)::text" + + " FROM game_session_canonical_issuer_partition_reservation r"), + "Expected reservation aggregate row") + .get(0, String.class); + } + + private static String localRegistrationImage(DSLContext dsl) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT" + + " (SELECT coalesce(jsonb_agg(to_jsonb(i) ORDER BY binding_ref), '[]'::jsonb)::text" + + " FROM game_session_canonical_gameplay_binding_inventory i) || ':'" + + " || (SELECT coalesce(jsonb_agg(to_jsonb(t) ORDER BY transition_id), '[]'::jsonb)::text" + + " FROM game_session_canonical_binding_transition t) || ':'" + + " || (SELECT coalesce(jsonb_agg(to_jsonb(r) ORDER BY reservation_id), '[]'::jsonb)::text" + + " FROM game_session_canonical_issuer_partition_reservation r) || ':'" + + " || (SELECT coalesce(jsonb_agg(to_jsonb(o) ORDER BY operation_id), '[]'::jsonb)::text" + + " FROM game_session_canonical_issuer_binding_local_operation o) || ':'" + + " || (SELECT coalesce(jsonb_agg(to_jsonb(g) ORDER BY tenant_id, playable_state_namespace_id, character_id), '[]'::jsonb)::text" + + " FROM game_session_canonical_binding_generation g) || ':'" + + " || (SELECT inventory_revision::text FROM game_session_canonical_binding_inventory_clock WHERE singleton_id = 1) || ':'" + + " || (SELECT coalesce(to_jsonb(c)::text, 'missing') FROM game_session_canonical_issuer_bootstrap_member_op_counter c WHERE issuer_id = '" + + ISSUER + + "')"), + "Expected local registration aggregate row") + .get(0, String.class); + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private record TestSchema(String schema, DriverManagerDataSource dataSource, DSLContext dsl) {} +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java new file mode 100644 index 0000000000..14b24ee0b5 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java @@ -0,0 +1,1085 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.SQLException; +import java.time.Duration; +import java.util.EnumSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutorService; +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.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; +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.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Actual PostgreSQL/Redis proof for local ordinary NEW registration after the installed anchor. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String OWNER_PRINCIPAL = "gamesession_coord_app"; + private static final String ISSUER_KEY_PREFIX = "session:game:index:issuer:"; + private static final BigInteger LAYOUT_VERSION = BigInteger.valueOf(3); + private static final BigInteger PARTITION_COUNT = BigInteger.ONE; + private static final BigInteger PARTITION_CAPACITY = BigInteger.valueOf(2); + + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + private static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + private TestSchema schema; + private RedisClient administrator; + private RedisClient ownerClient; + private StatefulRedisConnection administratorConnection; + private RedisCommands administratorCommands; + + @BeforeEach + void setUp() { + String password = UUID.randomUUID().toString(); + administrator = createRedisClient(null, null); + administratorConnection = administrator.connect(ByteArrayCodec.INSTANCE); + administratorCommands = administratorConnection.sync(); + administratorCommands.flushdb(); + administratorCommands.aclSetuser( + OWNER_PRINCIPAL, + new AclSetuserArgs() + .reset() + .on() + .addPassword(password) + .keyPattern(ISSUER_KEY_PREFIX + "*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.HGET) + .addCommand(CommandType.HLEN) + .addCommand(CommandType.HGETALL) + .addCommand(CommandType.HSET)); + ownerClient = createRedisClient(OWNER_PRINCIPAL, password); + schema = newTestSchemaAtVersion("gs_issuer_local_new_"); + } + + @AfterEach + void tearDown() { + if (administratorConnection != null) administratorConnection.close(); + if (ownerClient != null) ownerClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + if (administrator != null) administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + if (schema != null) dropSchema(schema.schema()); + } + + @Test + void registersOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() throws Exception { + DSLContext dsl = schema.dsl(); + establishActualLegacyDisposition(dsl); + var layout = descriptor(); + UUID bootstrapRequestId = UUID.randomUUID(); + var source = sourceCheckpoint(BigInteger.valueOf(7)); + var intent = + new CanonicalGameplayIssuerLayoutBootstrapRepository(dsl) + .beginInitialBootstrapIntent(bootstrapRequestId, layout, source); + migrateRemaining(schema); + + var incarnation = stableIncarnation("local-new-anchor"); + var initialState = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + intent.sourceCheckpoint(), incarnation); + AtomicReference + currentState = new AtomicReference<>(initialState); + var operationRepository = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, currentState::get); + var runtimeTarget = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( + schema.dataSource(), uuid("local-projection-tenant")); + var firstCandidate = identity("first-new", runtimeTarget); + var firstRequest = request("first-new-request", "first-new-transition", firstCandidate); + + assertThatThrownBy(() -> operationRepository.beginOrResumeOrdinaryNew(firstRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("anchor"); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isZero(); + assertThat(count(dsl, "game_session_canonical_gameplay_binding_inventory")).isZero(); + + CanonicalGameplayIssuerInstalledAnchor anchor = + initialCoverageOwner(dsl, currentState::get) + .completeInitialBootstrap(intent.operationId(), bootstrapRequestId); + String installedAnchorImage = anchorImage(dsl); + String installedProofImage = proofImage(dsl); + String initialReservationImage = reservationImage(dsl); + BigInteger initialGlobalCoverageGeneration = anchor.globalCoverageGeneration(); + + AtomicInteger sourceReads = new AtomicInteger(); + CyclicBarrier concurrentPreReadBarrier = new CyclicBarrier(2); + var concurrentSource = + (CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource) + () -> { + if (sourceReads.incrementAndGet() <= 2) { + try { + concurrentPreReadBarrier.await(30, TimeUnit.SECONDS); + } catch (Exception failure) { + throw new IllegalStateException( + "Concurrent source pre-reads did not rendezvous", failure); + } + } + return currentState.get(); + }; + var concurrentRepository = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, concurrentSource); + ExecutorService concurrentCallers = Executors.newFixedThreadPool(2); + CanonicalGameplayIssuerBindingLocalOperation first; + CanonicalGameplayIssuerBindingLocalOperation concurrentReplay; + try { + var firstCall = + concurrentCallers.submit( + () -> concurrentRepository.beginOrResumeOrdinaryNew(firstRequest)); + var secondCall = + concurrentCallers.submit( + () -> concurrentRepository.beginOrResumeOrdinaryNew(firstRequest)); + first = firstCall.get(30, TimeUnit.SECONDS); + concurrentReplay = secondCall.get(30, TimeUnit.SECONDS); + } finally { + concurrentCallers.shutdownNow(); + } + assertThat(sourceReads.get()).isEqualTo(4); + assertThat(concurrentReplay.operationId()).isEqualTo(first.operationId()); + assertThat(concurrentReplay.reservation().reservationId()) + .isEqualTo(first.reservation().reservationId()); + assertThat(concurrentReplay.reservation().reservationFence()) + .isEqualTo(first.reservation().reservationFence()); + assertThat(concurrentReplay.candidateAccountIndexFence()) + .isEqualTo(first.candidateAccountIndexFence()); + assertThat(concurrentReplay.operationFence()).isEqualTo(first.operationFence()); + assertThat(concurrentReplay.localMemberGeneration()).isEqualTo(first.localMemberGeneration()); + assertThat(concurrentReplay.localInventorySnapshotRevision()) + .isEqualTo(first.localInventorySnapshotRevision()); + assertThat(concurrentReplay.exactMemberValueBytes()) + .containsExactly(first.exactMemberValueBytes()); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isEqualTo(1L); + assertThat(count(dsl, "game_session_canonical_issuer_partition_reservation")).isEqualTo(1L); + assertThat(first.status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalOperation.Status.PENDING_PHYSICAL_PROOF); + assertThat(first.request()).isEqualTo(firstRequest); + assertThat(first.preparedTransition().status()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot + .Status.PREPARED); + assertThat(first.reservation().lifecycle()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation.Lifecycle + .RESERVED); + assertThat(first.reservation().issuerCoverageOperationId()) + .isEqualTo(first.anchor().issuerCoverageOperationId()); + assertThat(first.reservation().issuerCoverageOperationFence()) + .isEqualTo(first.anchor().operationFence()); + assertThat(first.reservation().coverageFence()).isEqualTo(first.anchor().coverageFence()); + assertThat(first.reservation().inventorySnapshotRevision()) + .isEqualTo(first.anchor().issuerInventorySnapshotRevision()); + assertThat(first.localInventorySnapshotRevision()) + .isEqualTo(first.reservation().inventoryRevision()); + assertThat(first.memberValue().anchor().issuerCoverageOperationId()) + .isEqualTo(anchor.issuerCoverageOperationId()); + assertThat(first.anchor().exactAnchorBytes()).containsExactly(anchor.exactAnchorBytes()); + assertThat(first.memberValue().issuerControlEpoch()).isEqualTo(anchor.controlEpoch()); + assertThat(first.memberValue().layoutDescriptor().exactDescriptorBytes()) + .containsExactly(anchor.layoutDescriptorBytes()); + assertThat(first.memberValue().layoutDescriptor().descriptorDigest()) + .isEqualTo(anchor.layoutDescriptorDigest()); + assertThat(first.memberValue().sourceCheckpoint().exactCheckpointBytes()) + .containsExactly(anchor.sourceCheckpointBytes()); + assertThat(first.memberValue().sourceCheckpoint().latestIssuerEventBytes()) + .containsExactly(anchor.sourceEventBytes()); + assertThat(first.memberValue().incarnation()).isEqualTo(incarnation); + assertThat(first.memberValue().memberOperation().coverageGeneration()) + .isEqualTo(first.localMemberGeneration()); + assertThat(first.expectedOldMemberState()).isEqualTo("ABSENT"); + assertThat(first.expectedOldCapacityState()).isEqualTo("ABSENT"); + assertThat(first.exactMemberValueBytes()) + .containsExactly(CanonicalGameplayIssuerMemberV2Codec.encode(first.memberValue())); + assertThat(first.memberValueDigest()) + .isEqualTo(CanonicalGameplayIssuerMemberV2Codec.sha256(first.exactMemberValueBytes())); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT member_status, member_schema_version FROM" + + " game_session_canonical_issuer_binding_local_operation WHERE transition_id = ?", + firstRequest.transitionId()), + "Expected local operation row") + .get("member_status", String.class)) + .isEqualTo("PENDING_PHYSICAL_PROOF"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT member_schema_version FROM" + + " game_session_canonical_issuer_binding_local_operation WHERE transition_id = ?", + firstRequest.transitionId()), + "Expected local operation row") + .get("member_schema_version", Short.class)) + .isEqualTo((short) 2); + assertThat(count(dsl, "game_session_canonical_binding_issuer_index_obligation")).isEqualTo(1L); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isEqualTo(1L); + assertThat(count(dsl, "game_session_canonical_gameplay_binding_inventory")).isEqualTo(1L); + assertThat(count(dsl, "game_session_canonical_binding_generation")).isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT last_issued_coverage_generation FROM" + + " game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", + ISSUER), + "Expected issuer coverage counter row") + .get("last_issued_coverage_generation", BigDecimal.class)) + .isEqualTo(new BigDecimal(initialGlobalCoverageGeneration)); + assertThat(anchorImage(dsl)).isEqualTo(installedAnchorImage); + assertThat(proofImage(dsl)).isEqualTo(installedProofImage); + assertThat( + administratorCommands.hlen( + CanonicalGameplayIssuerRedisKeys.forPartition( + intent.layoutDescriptor(), BigInteger.ZERO) + .getBytes(StandardCharsets.US_ASCII))) + .isEqualTo(1L); + + var projectionOwner = projectionOwner(dsl, currentState::get); + var firstCapacityOnly = projectionOwner.projectAndRead(first); + assertThat(firstCapacityOnly.operation()).isSameAs(first); + assertThat(firstCapacityOnly.scriptOutcome()).isEqualTo(1L); + var firstCapacityFields = + CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( + firstCapacityOnly.exactReadbackBytes()); + String firstCapacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + first.reservation().reservationId()); + assertThat(firstCapacityFields) + .containsEntry(firstCapacityField, first.exactMemberValueBytes()); + assertThat(firstCapacityFields) + .doesNotContainKey(new String(firstCandidate.bindingRef().bytes(), StandardCharsets.UTF_8)); + assertThat(projectionOwner.projectAndRead(first).scriptOutcome()).isEqualTo(3L); + assertThat(anchorImage(dsl)).isEqualTo(installedAnchorImage); + assertThat(proofImage(dsl)).isEqualTo(installedProofImage); + + String afterFirstRegistration = localRegistrationImage(dsl); + CanonicalGameplayIssuerBindingLocalOperation replay = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, currentState::get) + .beginOrResumeOrdinaryNew(firstRequest); + assertThat(replay.operationId()).isEqualTo(first.operationId()); + assertThat(replay.operationFence()).isEqualTo(first.operationFence()); + assertThat(replay.localMemberGeneration()).isEqualTo(first.localMemberGeneration()); + assertThat(replay.exactMemberValueBytes()).containsExactly(first.exactMemberValueBytes()); + assertThat(localRegistrationImage(dsl)).isEqualTo(afterFirstRegistration); + assertThat(anchorImage(dsl)).isEqualTo(installedAnchorImage); + assertThat(proofImage(dsl)).isEqualTo(installedProofImage); + + String beforeRefusals = localRegistrationImage(dsl); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request("changed-first-request", "first-new-transition", firstCandidate))) + .isInstanceOf(IllegalStateException.class); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request("first-new-request", "other-transition", identity("changed-first")))) + .isInstanceOf(IllegalStateException.class); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); + + currentState.set( + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + checkpointShape(BigInteger.valueOf(8)), incarnation)); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request( + "moved-source-request", + "moved-source-transition", + identity("moved-source")))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source"); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); + currentState.set(initialState); + + currentState.set( + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + intent.sourceCheckpoint(), stableIncarnation("moved-incarnation"))); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request( + "moved-incarnation-request", + "moved-incarnation-transition", + identity("moved-incarnation")))) + .isInstanceOf(IllegalStateException.class); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); + currentState.set(initialState); + + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request( + "wrong-layout-request", + "wrong-layout-transition", + identityWithLayout("wrong-layout", BigInteger.TWO)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("layout"); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); + + var sameController = sameControllerDifferentBinding(firstCandidate, "same-controller"); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request("controller-request", "controller-transition", sameController))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("controller"); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); + + var secondCandidate = identity("second-new"); + var secondRequest = request("second-new-request", "second-new-transition", secondCandidate); + var movedAfterRegistrationState = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + checkpointShape(BigInteger.valueOf(8)), incarnation); + AtomicInteger movementReadCount = new AtomicInteger(); + var movingSource = + (CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource) + () -> + movementReadCount.incrementAndGet() == 1 + ? initialState + : movedAfterRegistrationState; + var movingRepository = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, movingSource); + assertThatThrownBy(() -> movingRepository.beginOrResumeOrdinaryNew(secondRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("pending local operation remains durable"); + UUID persistedSecondOperationId = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT operation_id FROM game_session_canonical_issuer_binding_local_operation" + + " WHERE transition_id = ?", + secondRequest.transitionId()), + "Expected local operation row") + .get("operation_id", UUID.class); + var second = operationRepository.beginOrResumeOrdinaryNew(secondRequest); + assertThat(second.operationId()).isEqualTo(persistedSecondOperationId); + assertThat(second.localMemberGeneration()).isGreaterThan(first.localMemberGeneration()); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isEqualTo(2L); + assertThat(count(dsl, "game_session_canonical_issuer_partition_reservation")).isEqualTo(2L); + assertThat(anchorImage(dsl)).isEqualTo(installedAnchorImage); + assertThat(proofImage(dsl)).isEqualTo(installedProofImage); + + var concurrentProjectionResults = concurrentProjection(projectionOwner, first, second); + assertThat(concurrentProjectionResults.first().scriptOutcome()).isEqualTo(3L); + assertThat(concurrentProjectionResults.second().scriptOutcome()).isEqualTo(1L); + var provisionalEvidence = + new CanonicalGameplayBindingInventoryRepository(dsl) + .readProvisionalCasEvidence(firstRequest.transitionId()); + var firstLease = + controlledLeaseEvidence( + firstCandidate, + provisionalEvidence.transition().bindingGeneration(), + runtimeTarget.playableTarget()); + var firstDecision = + new CanonicalGameplayAdmissionDecision( + firstRequest.transitionId(), + firstLease, + firstCandidate, + provisionalEvidence.transition().bindingGeneration(), + null, + runtimeTarget.playableTarget()); + new CanonicalGameplayBindingInventoryRepository(dsl) + .markProvisional(provisionalEvidence, firstDecision); + var firstWithBinding = projectionOwner.projectAndRead(first); + assertThat(firstWithBinding.scriptOutcome()).isEqualTo(2L); + var firstProjectedFields = + CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( + firstWithBinding.exactReadbackBytes()); + assertThat(firstProjectedFields) + .containsEntry( + new String(firstCandidate.bindingRef().bytes(), StandardCharsets.UTF_8), + first.exactMemberValueBytes()); + assertThat(firstProjectedFields) + .containsEntry(firstCapacityField, first.exactMemberValueBytes()); + assertThat(projectionOwner.projectAndRead(first).scriptOutcome()).isEqualTo(3L); + + String beforeCapacityRefusal = localRegistrationImage(dsl); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request("capacity-request", "capacity-transition", identity("capacity-new")))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("capacity"); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeCapacityRefusal); + assertThat(anchorImage(dsl)).isEqualTo(installedAnchorImage); + assertThat(proofImage(dsl)).isEqualTo(installedProofImage); + assertThat(reservationImage(dsl)).isNotEqualTo(initialReservationImage); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isEqualTo(2L); + + byte[] key = + CanonicalGameplayIssuerRedisKeys.forPartition(intent.layoutDescriptor(), BigInteger.ZERO) + .getBytes(StandardCharsets.US_ASCII); + String secondCapacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + second.reservation().reservationId()); + byte[] secondCapacityFieldBytes = secondCapacityField.getBytes(StandardCharsets.US_ASCII); + assertThat(administratorCommands.hlen(key)).isEqualTo(4L); + assertThat(firstProjectedFields) + .containsEntry(secondCapacityField, second.exactMemberValueBytes()); + + var incarnationMovedState = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + intent.sourceCheckpoint(), stableIncarnation("moved-after-install")); + currentState.set(incarnationMovedState); + assertThatThrownBy(() -> projectionOwner.projectAndRead(second)) + .isInstanceOf(IllegalStateException.class); + currentState.set(initialState); + + administratorCommands.hset(key, secondCapacityFieldBytes, first.exactMemberValueBytes()); + assertThatThrownBy(() -> projectionOwner.projectAndRead(second)) + .isInstanceOf(IllegalStateException.class); + assertThat(administratorCommands.hget(key, secondCapacityFieldBytes)) + .containsExactly(first.exactMemberValueBytes()); + administratorCommands.hset(key, secondCapacityFieldBytes, second.exactMemberValueBytes()); + + var secondValue = second.memberValue(); + var wrongAnchorValue = + new CanonicalGameplayIssuerMemberV2Value( + secondValue.owner(), + secondValue.bindingGeneration(), + secondValue.reservation(), + new CanonicalGameplayIssuerMemberV2Value.Anchor( + UUID.randomUUID(), + secondValue.anchor().operationFence(), + secondValue.anchor().coverageFence(), + secondValue.anchor().issuerInventorySnapshotRevision()), + secondValue.memberOperation(), + secondValue.issuerControlEpoch(), + secondValue.layoutDescriptor(), + secondValue.sourceCheckpoint(), + secondValue.incarnation()); + byte[] wrongAnchorBytes = CanonicalGameplayIssuerMemberV2Codec.encode(wrongAnchorValue); + administratorCommands.hset(key, secondCapacityFieldBytes, wrongAnchorBytes); + assertThatThrownBy(() -> projectionOwner.projectAndRead(second)) + .isInstanceOf(IllegalStateException.class); + assertThat(administratorCommands.hget(key, secondCapacityFieldBytes)) + .containsExactly(wrongAnchorBytes); + administratorCommands.hset(key, secondCapacityFieldBytes, second.exactMemberValueBytes()); + + byte[] unknownField = "unregistered-issuer-member".getBytes(StandardCharsets.UTF_8); + byte[] unknownValue = "newer-v2-value".getBytes(StandardCharsets.UTF_8); + administratorCommands.hset(key, unknownField, unknownValue); + assertThatThrownBy(() -> projectionOwner.projectAndRead(second)) + .isInstanceOf(IllegalStateException.class); + assertThat(administratorCommands.hget(key, unknownField)).containsExactly(unknownValue); + byte[][] unknownFields = {unknownField}; + administratorCommands.hdel(key, unknownFields); + + byte[] headerField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.METADATA_FIELD.getBytes( + StandardCharsets.US_ASCII); + byte[] headerValue = + firstCapacityFields.get( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.METADATA_FIELD); + byte[][] headerFields = {headerField}; + administratorCommands.hdel(key, headerFields); + assertThatThrownBy(() -> projectionOwner.projectAndRead(second)) + .isInstanceOf(IllegalStateException.class); + administratorCommands.hset(key, headerField, headerValue); + + administratorCommands.hset( + key, secondCapacityFieldBytes, "{\"schemaVersion\":1}".getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy(() -> projectionOwner.projectAndRead(second)) + .isInstanceOf(IllegalStateException.class); + administratorCommands.hset(key, secondCapacityFieldBytes, second.exactMemberValueBytes()); + + assertThat(administratorCommands.pexpire(key, 60_000L)).isTrue(); + assertThatThrownBy(() -> projectionOwner.projectAndRead(second)) + .isInstanceOf(IllegalStateException.class); + assertThat(administratorCommands.persist(key)).isTrue(); + assertThat(administratorCommands.hlen(key)).isEqualTo(4L); + + var fencedCandidate = identityForAccount("account-fenced", firstCandidate.accountId()); + new CanonicalGameplayAccountAdmissionBarrierRepository(dsl) + .beginFenceIntent(firstCandidate.accountId(), UUID.randomUUID()); + String accountFencedImage = localRegistrationImage(dsl); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request( + "account-fenced-request", "account-fenced-transition", fencedCandidate))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("Account"); + assertThat(localRegistrationImage(dsl)).isEqualTo(accountFencedImage); + } + + private static ConcurrentProjections concurrentProjection( + CanonicalGameplayIssuerBindingLocalRedisOwner owner, + CanonicalGameplayIssuerBindingLocalOperation first, + CanonicalGameplayIssuerBindingLocalOperation second) + throws Exception { + ExecutorService callers = Executors.newFixedThreadPool(2); + try { + var firstCall = callers.submit(() -> owner.projectAndRead(first)); + var secondCall = callers.submit(() -> owner.projectAndRead(second)); + return new ConcurrentProjections( + firstCall.get(30, TimeUnit.SECONDS), secondCall.get(30, TimeUnit.SECONDS)); + } finally { + callers.shutdownNow(); + } + } + + private CanonicalGameplayIssuerBootstrapCoverageOwner initialCoverageOwner( + DSLContext dsl, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource source) { + var partitionOwner = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner( + ownerClient, + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution())), + source); + return new CanonicalGameplayIssuerBootstrapCoverageOwner(dsl, partitionOwner, source); + } + + private CanonicalGameplayIssuerBindingLocalRedisOwner projectionOwner( + DSLContext dsl, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource source) { + return new CanonicalGameplayIssuerBindingLocalRedisOwner( + ownerClient, + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayIssuerBindingLocalRedisScriptContribution())), + new CanonicalGameplayIssuerBindingLocalProjectionRepository(dsl, source), + source); + } + + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor + descriptor() { + String exact = + "issuer-layout-descriptor/v1|" + + ISSUER + + "|" + + LAYOUT_VERSION + + "|" + + PARTITION_COUNT + + "|" + + PARTITION_CAPACITY + + "|" + + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY; + return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor( + ISSUER, + LAYOUT_VERSION, + PARTITION_COUNT, + PARTITION_CAPACITY, + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY, + exact.getBytes(StandardCharsets.UTF_8)); + } + + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + sourceCheckpoint(BigInteger generation) { + long sequence = generation.longValueExact() - 1; + var event = + AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + UUID.randomUUID().toString(), + UUID.randomUUID().toString(), + AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + ISSUER, + Long.toString(sequence), + ISSUER, + generation.toString(), + generation.toString(), + "ISSUER_SECURITY_CHANGE")); + byte[] bytes = event.canonicalJsonUtf8(); + return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint( + ISSUER, generation, bytes, bytes); + } + + private static CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint + checkpointShape(BigInteger generation) { + var trusted = sourceCheckpoint(generation); + byte[] checkpoint = trusted.checkpointBytes(); + byte[] event = trusted.latestEventBytes(); + return new CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint( + trusted.issuerId(), + trusted.issuerAuthGeneration(), + checkpoint, + CanonicalGameplayIssuerMemberV2Codec.sha256(checkpoint), + event, + CanonicalGameplayIssuerMemberV2Codec.sha256(event)); + } + + private static CanonicalGameplayIssuerMemberV2Value.Incarnation stableIncarnation(String seed) { + String digest = digest(seed.getBytes(StandardCharsets.UTF_8)); + var deployment = + new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "controlled-deployment-" + seed, + "deployment-generation-" + seed, + List.of("controlled-node-" + seed), + "controlled-redis-build-" + seed, + "controlled-lua-registry-" + seed, + digest, + "READY", + "boot-" + seed, + "startup-" + seed, + "storage-" + seed, + "aof-" + seed); + return new CanonicalGameplayIssuerMemberV2Value.Incarnation( + "controlled-attestor-" + seed, digest, deployment, digest, digest); + } + + private static CanonicalGameplayIssuerBindingLocalOperation.Request request( + String requestSeed, String transitionSeed, CanonicalGameplayBindingIdentity candidate) { + return new CanonicalGameplayIssuerBindingLocalOperation.Request( + UUID.nameUUIDFromBytes(requestSeed.getBytes(StandardCharsets.UTF_8)), + UUID.nameUUIDFromBytes(transitionSeed.getBytes(StandardCharsets.UTF_8)), + candidate, + null, + null); + } + + private static CanonicalGameplayBindingIdentity identity(String seed) { + return identityWithLayout(seed, LAYOUT_VERSION); + } + + private static CanonicalGameplayBindingIdentity identityForAccount(String seed, UUID accountId) { + CanonicalGameplayBindingIdentity identity = identity(seed); + return new CanonicalGameplayBindingIdentity( + accountId, + identity.tenantId(), + identity.playableStateNamespaceId(), + identity.characterId(), + identity.playableStateScope(), + identity.gameInstanceId(), + identity.runtimeGameInstanceId(), + identity.sessionId(), + identity.regionId(), + identity.regionEpoch(), + identity.issuerId(), + identity.issuerAuthGeneration(), + identity.issuerIndexLayoutVersion(), + identity.issuerIndexPartitionCount(), + identity.issuerIndexPartitionCapacity()); + } + + private static CanonicalGameplayBindingIdentity identity( + String seed, CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget runtimeTarget) { + return new CanonicalGameplayBindingIdentity( + uuid(seed + "-account"), + runtimeTarget.canonicalTenantId(), + runtimeTarget.playableStateNamespaceId(), + uuid(seed + "-character"), + runtimeTarget.playableStateScope(), + runtimeTarget.gameInstanceUuid(), + runtimeTarget.gameInstanceId(), + uuid(seed + "-session").toString(), + uuid(seed + "-region"), + BigInteger.valueOf(12), + ISSUER, + BigInteger.valueOf(7), + LAYOUT_VERSION, + PARTITION_COUNT, + PARTITION_CAPACITY); + } + + private static CanonicalGameplayBindingIdentity identityWithLayout( + String seed, BigInteger layoutVersion) { + return new CanonicalGameplayBindingIdentity( + uuid(seed + "-account"), + uuid(seed + "-tenant"), + uuid(seed + "-namespace"), + uuid(seed + "-character"), + "SHARED", + uuid(seed + "-game"), + 90_000L + Math.abs((long) seed.hashCode()), + uuid(seed + "-session").toString(), + uuid(seed + "-region"), + BigInteger.valueOf(12), + ISSUER, + BigInteger.valueOf(7), + layoutVersion, + PARTITION_COUNT, + PARTITION_CAPACITY); + } + + private static CanonicalGameplayBindingIdentity sameControllerDifferentBinding( + CanonicalGameplayBindingIdentity original, String seed) { + return new CanonicalGameplayBindingIdentity( + original.accountId(), + original.tenantId(), + original.playableStateNamespaceId(), + original.characterId(), + original.playableStateScope(), + uuid(seed + "-game"), + original.runtimeGameInstanceId() + 1, + uuid(seed + "-session").toString(), + original.regionId(), + original.regionEpoch(), + original.issuerId(), + original.issuerAuthGeneration(), + original.issuerIndexLayoutVersion(), + original.issuerIndexPartitionCount(), + original.issuerIndexPartitionCapacity()); + } + + private static UUID uuid(String value) { + return UUID.nameUUIDFromBytes(value.getBytes(StandardCharsets.UTF_8)); + } + + /** Controlled upstream lease input; the SQL transition owner remains the phase authority. */ + private static AccountGameplayAdmissionLeaseEvidence controlledLeaseEvidence( + CanonicalGameplayBindingIdentity candidate, + BigInteger bindingGeneration, + CanonicalPlayableTarget target) { + long now = System.currentTimeMillis(); + String nowSeconds = Long.toString(now / 1000L); + Map carrier = new LinkedHashMap<>(); + carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + carrier.put("schemaVersion", "1"); + carrier.put("mode", "PUBLIC_PRODUCTION"); + carrier.put("leaseKind", AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING.name()); + carrier.put("targetNamespace", target.targetNamespace()); + carrier.put( + "callerWorkload", + "spiffe://firemud/ns/" + target.targetNamespace() + "/sa/game-session-service"); + carrier.put("requestId", "10101010-1010-4010-8010-101010101010"); + carrier.put("leaseId", "20202020-2020-4020-8020-202020202020"); + carrier.put("leaseFence", "1"); + Map scope = new LinkedHashMap<>(); + scope.put("accountId", candidate.accountId().toString()); + scope.put("tenantId", candidate.tenantId().toString()); + scope.put("realmId", target.realmId().toString()); + scope.put("worldSlug", target.worldSlug()); + scope.put("realmSlug", target.realmSlug()); + scope.put("playableStateNamespaceId", target.playableStateNamespaceId().toString()); + scope.put("playableStateScope", target.playableStateScope()); + scope.put("gameInstanceId", target.canonicalGameInstanceId().toString()); + scope.put("characterId", candidate.characterId().toString()); + scope.put("sessionId", candidate.sessionId()); + scope.put("bindingGeneration", bindingGeneration.toString()); + scope.put("catalogRevision", Long.toString(target.catalogRevision())); + scope.put("pointerVersion", Long.toString(target.pointerVersion())); + scope.put("regionId", candidate.regionId().toString()); + scope.put("regionEpoch", candidate.regionEpoch().toString()); + carrier.put("bindingScope", scope); + Map authority = new LinkedHashMap<>(); + authority.put("issuerAuthGeneration", candidate.issuerAuthGeneration().toString()); + authority.put("accountAuthorityGeneration", "1"); + authority.put("tenantAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1")); + authority.put("membershipAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1")); + authority.put("privateRealmGrantVersions", List.of()); + carrier.put("authorityTuple", authority); + carrier.put("issuanceFence", "1"); + carrier.put( + "membershipBaseline", + new LinkedHashMap<>( + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + Map.of(candidate.tenantId().toString(), "1"), + "membershipAuthorityGeneration", + "1"))); + String prefix = "account:auth-authority:v1:"; + List> checkpoints = new java.util.ArrayList<>(); + for (String stream : + List.of( + "account/" + candidate.accountId(), + "issuer/" + ISSUER, + "membership/" + candidate.accountId() + "/" + candidate.tenantId(), + "tenant/" + candidate.tenantId())) { + checkpoints.add( + new LinkedHashMap<>( + Map.of( + "outboxStreamKey", + prefix + stream, + "outboxSequence", + stream.startsWith("membership/") || stream.startsWith("tenant/") ? "1" : "0"))); + } + carrier.put("outboxCheckpoints", checkpoints); + Map tokenIdentity = new LinkedHashMap<>(); + tokenIdentity.put("accountId", candidate.accountId().toString()); + tokenIdentity.put("operationId", "40404040-4040-4040-8040-404040404040"); + tokenIdentity.put("issuanceRequestId", "50505050-5050-4050-8050-505050505050"); + tokenIdentity.put("tokenJti", "60606060-6060-4060-8060-606060606060"); + tokenIdentity.put("tokenSHA256", "a".repeat(64)); + tokenIdentity.put("tokenProfile", "game-session-account-delegation"); + tokenIdentity.put("tokenGeneration", "1"); + tokenIdentity.put("issuanceFence", "1"); + tokenIdentity.put("tokenIdentityFence", "1"); + tokenIdentity.put("issuedAt", nowSeconds); + tokenIdentity.put("notBefore", nowSeconds); + tokenIdentity.put("expiresAt", Long.toString(now / 1000L + 60L)); + carrier.put("tokenIdentityEvidence", tokenIdentity); + carrier.put("evaluatedAt", Long.toString(now)); + carrier.put( + "expiresAt", + Long.toString(now + AccountGameplayAdmissionLeaseEvidence.MAX_DURATION_MILLIS)); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + } + + private void establishActualLegacyDisposition(DSLContext dsl) { + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); + UUID cohortId = UUID.randomUUID(); + UUID writerFence = UUID.randomUUID(); + var storageIdentity = + new CanonicalGameplayLegacyMigrationStorageIdentity( + "controlled-cluster-uid", + "controlled-namespace-uid", + "controlled-producer-pod-uid", + "controlled-container-id", + "controlled-node-uid", + "123456789", + 42L, + "controlled-postgres-volume-uid", + "controlled-redis-run-id", + "controlled-redis-volume-uid"); + var fencedCohort = + new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { + @Override + public UUID cohortId() { + return cohortId; + } + + @Override + public UUID legacyWriterFence() { + return writerFence; + } + + @Override + public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + return storageIdentity; + } + + @Override + public void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity expected) { + if (!storageIdentity.equals(expected)) { + throw new IllegalStateException("Controlled test storage identity changed"); + } + } + }; + new CanonicalGameplayLegacyMigrationOwner( + migration, + inventory, + () -> fencedCohort, + ignored -> + new CanonicalGameplayLegacyMigrationSourceSnapshot( + EnumSet.of( + Family.TENANT_SESSION_CONTEXT, + Family.SESSION_ALIAS_CONTEXT, + Family.GAMEPLAY_IDENTITY_CONTEXT, + Family.GAMEPLAY_NAME_CONTEXT, + Family.MOVEMENT_EFFECT, + Family.DURABLE_EFFECT), + List.of()), + new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { + @Override + public void rebuildExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + CanonicalGameplayLegacyMigrationSourceSnapshot source, + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot + canonical) { + assertThat(canonical.bindings()).isEmpty(); + assertThat(canonical.reservations()).isEmpty(); + } + + @Override + public CanonicalGameplayLegacyMigrationReadback readBackExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot + canonical) { + assertThat(canonical.bindings()).isEmpty(); + return new CanonicalGameplayLegacyMigrationReadback( + List.of(), List.of(), List.of(), List.of()); + } + }) + .migrate(); + } + + private TestSchema newTestSchemaAtVersion(String prefix) { + String schema = prefix + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("1030")) + .load() + .migrate(); + return new TestSchema(schema, dataSource, DSL.using(dataSource, SQLDialect.POSTGRES)); + } + + private static void migrateRemaining(TestSchema schema) { + Flyway.configure() + .dataSource(schema.dataSource()) + .schemas(schema.schema()) + .defaultSchema(schema.schema()) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + } + + private DriverManagerDataSource dataSource(String schemaName) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + String jdbcUrl = POSTGRES.getJdbcUrl(); + dataSource.setUrl( + jdbcUrl + (jdbcUrl.contains("?") ? "&" : "?") + "currentSchema=" + schemaName); + dataSource.setUsername(POSTGRES.getUsername()); + dataSource.setPassword(POSTGRES.getPassword()); + return dataSource; + } + + private void dropSchema(String schemaName) { + try (Connection connection = dataSource("public").getConnection()) { + DSL.using(connection, SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + schemaName + "\" CASCADE"); + } catch (SQLException failure) { + throw new IllegalStateException( + "Could not drop the owned issuer local-operation test schema", failure); + } + } + + private static RedisClient createRedisClient(String username, String password) { + RedisURI.Builder builder = RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(6379)); + if (username != null) builder.withAuthentication(username, password); + RedisURI uri = builder.build(); + uri.setTimeout(Duration.ofSeconds(5)); + RedisClient client = RedisClient.create(uri); + client.setOptions( + ClientOptions.builder() + .autoReconnect(false) + .protocolVersion(io.lettuce.core.protocol.ProtocolVersion.RESP2) + .build()); + return client; + } + + private static long count(DSLContext dsl, String table) { + return Objects.requireNonNull( + dsl.fetchOne("SELECT count(*) AS row_count FROM " + table), "Expected count row") + .get("row_count", Long.class); + } + + private static String anchorImage(DSLContext dsl) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT encode(exact_anchor_bytes, 'base64') || ':' || exact_anchor_digest || ':'" + + " || global_coverage_generation::text FROM" + + " game_session_canonical_issuer_installed_anchor WHERE issuer_id = ?", + ISSUER), + "Expected installed anchor row") + .get(0, String.class); + } + + private static String proofImage(DSLContext dsl) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT coalesce(string_agg(partition_id::text || ':'" + + " || encode(exact_physical_field_set_bytes, 'base64') || ':'" + + " || exact_physical_field_set_digest, '|' ORDER BY partition_id), '')" + + " FROM game_session_canonical_issuer_bootstrap_partition_proof"), + "Expected proof aggregate row") + .get(0, String.class); + } + + private static String reservationImage(DSLContext dsl) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT coalesce(jsonb_agg(to_jsonb(r) ORDER BY reservation_id), '[]'::jsonb)::text" + + " FROM game_session_canonical_issuer_partition_reservation r"), + "Expected reservation aggregate row") + .get(0, String.class); + } + + private static String localRegistrationImage(DSLContext dsl) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT" + + " (SELECT coalesce(jsonb_agg(to_jsonb(i) ORDER BY binding_ref), '[]'::jsonb)::text" + + " FROM game_session_canonical_gameplay_binding_inventory i) || ':'" + + " || (SELECT coalesce(jsonb_agg(to_jsonb(t) ORDER BY transition_id), '[]'::jsonb)::text" + + " FROM game_session_canonical_binding_transition t) || ':'" + + " || (SELECT coalesce(jsonb_agg(to_jsonb(r) ORDER BY reservation_id), '[]'::jsonb)::text" + + " FROM game_session_canonical_issuer_partition_reservation r) || ':'" + + " || (SELECT coalesce(jsonb_agg(to_jsonb(o) ORDER BY operation_id), '[]'::jsonb)::text" + + " FROM game_session_canonical_issuer_binding_local_operation o) || ':'" + + " || (SELECT coalesce(jsonb_agg(to_jsonb(g) ORDER BY tenant_id, playable_state_namespace_id, character_id), '[]'::jsonb)::text" + + " FROM game_session_canonical_binding_generation g) || ':'" + + " || (SELECT inventory_revision::text FROM game_session_canonical_binding_inventory_clock WHERE singleton_id = 1) || ':'" + + " || (SELECT coalesce(to_jsonb(c)::text, 'missing') FROM game_session_canonical_issuer_bootstrap_member_op_counter c WHERE issuer_id = '" + + ISSUER + + "')"), + "Expected local registration aggregate row") + .get(0, String.class); + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private record TestSchema(String schema, DriverManagerDataSource dataSource, DSLContext dsl) {} + + private record ConcurrentProjections( + CanonicalGameplayIssuerBindingLocalRedisOwner.Readback first, + CanonicalGameplayIssuerBindingLocalRedisOwner.Readback second) {} +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java index 248424f121..b4a323197f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java @@ -39,6 +39,7 @@ import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; +import org.jooq.Record; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.AfterEach; @@ -131,12 +132,11 @@ void installsOnlyAfterEveryPopulatedAndEmptyPartitionHasExactPhysicalProofAndRep assertThat(first.physicalBindingCount()).isEqualTo(1L); CanonicalGameplayIssuerBootstrapPartitionWork originalWork = partitionWork( - fixture, - fixture.activePartition(), - trustedIncarnation(current.incarnation())); + fixture, fixture.activePartition(), trustedIncarnation(current.incarnation())); var physicalValue = originalWork.memberOperations().getFirst().expectedMemberValue(); var originalReservationRow = - fixture.dsl().fetchOne( + fetchRequired( + fixture.dsl(), "SELECT issuer_coverage_operation_id, issuer_coverage_operation_fence, coverage_fence," + " inventory_snapshot_revision, inventory_revision" + " FROM game_session_canonical_issuer_partition_reservation WHERE reservation_id = ?", @@ -145,41 +145,59 @@ void installsOnlyAfterEveryPopulatedAndEmptyPartitionHasExactPhysicalProofAndRep .isEqualTo(originalReservationRow.get("issuer_coverage_operation_id", UUID.class)) .isNotEqualTo(physicalValue.anchor().issuerCoverageOperationId()); assertThat(physicalValue.reservation().issuerCoverageOperationFence()) - .isEqualTo(originalReservationRow.get("issuer_coverage_operation_fence", BigDecimal.class).toBigIntegerExact()); + .isEqualTo( + originalReservationRow + .get("issuer_coverage_operation_fence", BigDecimal.class) + .toBigIntegerExact()); assertThat(physicalValue.reservation().coverageFence()) - .isEqualTo(originalReservationRow.get("coverage_fence", BigDecimal.class).toBigIntegerExact()); + .isEqualTo( + originalReservationRow.get("coverage_fence", BigDecimal.class).toBigIntegerExact()); assertThat(physicalValue.reservation().inventorySnapshotRevision()) - .isEqualTo(originalReservationRow.get("inventory_snapshot_revision", BigDecimal.class).toBigIntegerExact()); + .isEqualTo( + originalReservationRow + .get("inventory_snapshot_revision", BigDecimal.class) + .toBigIntegerExact()); assertThat(physicalValue.reservation().inventoryRevision()) - .isEqualTo(originalReservationRow.get("inventory_revision", BigDecimal.class).toBigIntegerExact()); + .isEqualTo( + originalReservationRow.get("inventory_revision", BigDecimal.class).toBigIntegerExact()); assertThat(physicalValue.anchor().issuerCoverageOperationId()) .isEqualTo(first.issuerCoverageOperationId()); assertThat(physicalValue.anchor().operationFence()).isEqualTo(first.operationFence()); assertThat(physicalValue.anchor().coverageFence()).isEqualTo(first.coverageFence()); assertThat(physicalValue.anchor().issuerInventorySnapshotRevision()) .isEqualTo(first.issuerInventorySnapshotRevision()); - assertThat(fixture.dsl().fetchOne( - "SELECT count(*) AS proof_count FROM game_session_canonical_issuer_bootstrap_partition_proof") - .get("proof_count", Long.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT count(*) AS proof_count FROM game_session_canonical_issuer_bootstrap_partition_proof") + .get("proof_count", Long.class)) .isEqualTo(PARTITION_COUNT.longValueExact()); - assertThat(fixture.dsl().fetchOne( - "SELECT count(*) AS anchor_count FROM game_session_canonical_issuer_installed_anchor") - .get("anchor_count", Long.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT count(*) AS anchor_count FROM game_session_canonical_issuer_installed_anchor") + .get("anchor_count", Long.class)) .isEqualTo(1L); - assertThat(fixture.dsl().fetchOne( - "SELECT count(*) AS pending_count FROM game_session_canonical_issuer_bootstrap_member_operation" - + " WHERE member_status = 'PENDING_PHYSICAL_PROOF'") - .get("pending_count", Long.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT count(*) AS pending_count FROM game_session_canonical_issuer_bootstrap_member_operation" + + " WHERE member_status = 'PENDING_PHYSICAL_PROOF'") + .get("pending_count", Long.class)) .isEqualTo((long) fixture.plan().memberWorks().size()); - assertThat(fixture.dsl().fetchOne( - "SELECT last_issued_coverage_generation FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", - ISSUER) - .get("last_issued_coverage_generation", BigDecimal.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT last_issued_coverage_generation FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", + ISSUER) + .get("last_issued_coverage_generation", BigDecimal.class)) .isEqualTo(new BigDecimal(first.globalCoverageGeneration())); - assertThat(fixture.dsl().fetchOne( - "SELECT state FROM game_session_canonical_issuer_layout_bootstrap_control WHERE issuer_id = ?", - ISSUER) - .get("state", String.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT state FROM game_session_canonical_issuer_layout_bootstrap_control WHERE issuer_id = ?", + ISSUER) + .get("state", String.class)) .isEqualTo("INITIAL_BOOTSTRAP_INTENT"); for (BigInteger partitionId = BigInteger.ZERO; @@ -199,14 +217,17 @@ void installsOnlyAfterEveryPopulatedAndEmptyPartitionHasExactPhysicalProofAndRep byte[] exactAnchorBeforeCounterAdvance = first.exactAnchorBytes(); String anchorStorageBeforeCounterAdvance = anchorStorageImage(fixture.dsl()); String proofStorageBeforeCounterAdvance = proofStorageImage(fixture.dsl()); - BigInteger laterCoverageGeneration = first.globalCoverageGeneration().add(BigInteger.valueOf(4)); - fixture.dsl().execute( - "UPDATE game_session_canonical_issuer_bootstrap_coverage_counter" - + " SET last_issued_coverage_generation = ?, counter_version = 2" - + " WHERE issuer_id = ? AND last_issued_coverage_generation = ? AND counter_version = 1", - laterCoverageGeneration, - ISSUER, - first.globalCoverageGeneration()); + BigInteger laterCoverageGeneration = + first.globalCoverageGeneration().add(BigInteger.valueOf(4)); + fixture + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_bootstrap_coverage_counter" + + " SET last_issued_coverage_generation = ?, counter_version = 2" + + " WHERE issuer_id = ? AND last_issued_coverage_generation = ? AND counter_version = 1", + laterCoverageGeneration, + ISSUER, + first.globalCoverageGeneration()); assertThat(originalReservationImage(fixture.dsl())).isEqualTo(originalReservationImage); assertThat(anchorStorageImage(fixture.dsl())).isEqualTo(anchorStorageBeforeCounterAdvance); assertThat(proofStorageImage(fixture.dsl())).isEqualTo(proofStorageBeforeCounterAdvance); @@ -218,15 +239,19 @@ void installsOnlyAfterEveryPopulatedAndEmptyPartitionHasExactPhysicalProofAndRep assertThat(replay.exactAnchorBytes()).containsExactly(first.exactAnchorBytes()); assertThat(replay.exactAnchorBytes()).containsExactly(exactAnchorBeforeCounterAdvance); assertThat(replay.globalCoverageGeneration()).isEqualTo(first.globalCoverageGeneration()); - assertThat(fixture.dsl().fetchOne( - "SELECT counter_version FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", - ISSUER) - .get("counter_version", Long.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT counter_version FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", + ISSUER) + .get("counter_version", Long.class)) .isEqualTo(2L); - assertThat(fixture.dsl().fetchOne( - "SELECT last_issued_coverage_generation FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", - ISSUER) - .get("last_issued_coverage_generation", BigDecimal.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT last_issued_coverage_generation FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", + ISSUER) + .get("last_issued_coverage_generation", BigDecimal.class)) .isEqualTo(new BigDecimal(laterCoverageGeneration)); assertThat(originalReservationImage(fixture.dsl())).isEqualTo(originalReservationImage); } @@ -239,7 +264,9 @@ void installedReplayRefusesMissingPartitionWithoutRebuildingOrAllocatingAnotherG owner(fixture, () -> current) .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId()); byte[] missingKey = key(fixture, fixture.activePartition()); - administratorCommands.del(missingKey); + byte[][] missingKeyArguments = new byte[1][]; + missingKeyArguments[0] = missingKey; + administratorCommands.del(missingKeyArguments); assertThatThrownBy( () -> @@ -247,15 +274,19 @@ void installedReplayRefusesMissingPartitionWithoutRebuildingOrAllocatingAnotherG .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId())) .isInstanceOf(IllegalStateException.class); assertThat(administratorCommands.type(missingKey)).isEqualTo("none"); - assertThat(fixture.dsl().fetchOne( - "SELECT global_coverage_generation FROM game_session_canonical_issuer_installed_anchor WHERE issuer_id = ?", - ISSUER) - .get("global_coverage_generation", BigDecimal.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT global_coverage_generation FROM game_session_canonical_issuer_installed_anchor WHERE issuer_id = ?", + ISSUER) + .get("global_coverage_generation", BigDecimal.class)) .isEqualTo(new BigDecimal(installed.globalCoverageGeneration())); - assertThat(fixture.dsl().fetchOne( - "SELECT counter_version FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", - ISSUER) - .get("counter_version", Long.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT counter_version FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", + ISSUER) + .get("counter_version", Long.class)) .isEqualTo(1L); } @@ -265,13 +296,14 @@ void movedAccountCheckpointOrStorageIncarnationLeavesNoCoverageGenerationOrPoint var sourceIncarnation = stableIncarnation("source-movement"); var changedCheckpoint = checkpointShape(BigInteger.valueOf(8)); AtomicInteger sourceCalls = new AtomicInteger(); - var changedAfterReadback = - () -> - new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( - sourceCalls.incrementAndGet() == 5 - ? changedCheckpoint - : sourceFixture.intent().sourceCheckpoint(), - sourceIncarnation); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + changedAfterReadback = + () -> + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + sourceCalls.incrementAndGet() == 5 + ? changedCheckpoint + : sourceFixture.intent().sourceCheckpoint(), + sourceIncarnation); assertThatThrownBy( () -> owner(sourceFixture, changedAfterReadback) @@ -285,11 +317,14 @@ void movedAccountCheckpointOrStorageIncarnationLeavesNoCoverageGenerationOrPoint var initialIncarnation = stableIncarnation("incarnation-movement"); var changedIncarnation = changedIncarnation(initialIncarnation); AtomicInteger incarnationCalls = new AtomicInteger(); - var changedIncarnationAfterReadback = - () -> - new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( - incarnationFixture.intent().sourceCheckpoint(), - incarnationCalls.incrementAndGet() == 5 ? changedIncarnation : initialIncarnation); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + changedIncarnationAfterReadback = + () -> + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + incarnationFixture.intent().sourceCheckpoint(), + incarnationCalls.incrementAndGet() == 5 + ? changedIncarnation + : initialIncarnation); assertThatThrownBy( () -> owner(incarnationFixture, changedIncarnationAfterReadback) @@ -337,15 +372,18 @@ void finitePlanCapacityConflictDoesNotCreateAnyPartitionOrCoverageGeneration() { .isInstanceOf(IllegalStateException.class) .hasMessageContaining("blockers"); assertNoInstalledCoverage(fixture); - assertThat(fixture.dsl().fetchOne( - "SELECT count(*) AS proof_count FROM game_session_canonical_issuer_bootstrap_partition_proof") - .get("proof_count", Long.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT count(*) AS proof_count FROM game_session_canonical_issuer_bootstrap_partition_proof") + .get("proof_count", Long.class)) .isZero(); assertThat(administratorCommands.type(key(fixture, BigInteger.ZERO))).isEqualTo("none"); } private void assertPhysicalTupleConflict(boolean wrongNewAnchor) { Fixture fixture = fixture(BigInteger.ONE, PARTITION_CAPACITY, 1); + administratorCommands.del(new byte[][] {key(fixture, BigInteger.ZERO)}); var incarnation = stableIncarnation(wrongNewAnchor ? "wrong-anchor" : "wrong-original"); CanonicalGameplayIssuerBootstrapPartitionWork work = partitionWork(fixture, BigInteger.ZERO, trustedIncarnation(incarnation)); @@ -381,14 +419,12 @@ private void assertPhysicalTupleConflict(boolean wrongNewAnchor) { expected.incarnation()); byte[] changedBytes = CanonicalGameplayIssuerMemberV2Codec.encode(changed); byte[] key = key(fixture, BigInteger.ZERO); + administratorCommands.hset(key, expected.owner().bindingRef().bytes(), changedBytes); administratorCommands.hset( key, - expected.owner().bindingRef().bytes(), - changedBytes); - administratorCommands.hset( - key, - ascii(CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( - expected.reservation().reservationId())), + ascii( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + expected.reservation().reservationId())), changedBytes); assertThatThrownBy( @@ -444,7 +480,8 @@ private CanonicalGameplayIssuerBootstrapPartitionRedisOwner partitionRedisOwner( private CanonicalGameplayIssuerBootstrapPartitionWork partitionWork( Fixture fixture, BigInteger partitionId, - CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation incarnation) { + CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation + incarnation) { return new CanonicalGameplayIssuerBootstrapMemberOperationRepository(fixture.dsl()) .preparePartitionWork( fixture.intent().operationId(), @@ -515,15 +552,10 @@ private CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState c CanonicalGameplayIssuerMemberV2Codec.sha256(event)); } - private static CanonicalGameplayIssuerMemberV2Value.Incarnation - stableIncarnation(String seed) { + private static CanonicalGameplayIssuerMemberV2Value.Incarnation stableIncarnation(String seed) { String digest = digest(seed.getBytes(StandardCharsets.UTF_8)); return new CanonicalGameplayIssuerMemberV2Value.Incarnation( - "controlled-attestor-" + seed, - digest, - deploymentEvidence(seed, digest), - digest, - digest); + "controlled-attestor-" + seed, digest, deploymentEvidence(seed, digest), digest, digest); } private static CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation @@ -606,13 +638,14 @@ private static CanonicalGameplayBindingIdentity identityInPartition( identity(partitions, capacity, "coverage-active-" + seed + "-" + candidate); if (identity.bindingRef().partitionId(partitions).equals(partitionId)) return identity; } - throw new IllegalStateException("Could not create a second reservation in the target partition"); + throw new IllegalStateException( + "Could not create a second reservation in the target partition"); } - private static void seedActiveSource( - DSLContext dsl, CanonicalGameplayBindingIdentity identity) { + private static void seedActiveSource(DSLContext dsl, CanonicalGameplayBindingIdentity identity) { byte[] bindingRef = identity.bindingRef().bytes(); - BigInteger partitionId = identity.bindingRef().partitionId(identity.issuerIndexPartitionCount()); + BigInteger partitionId = + identity.bindingRef().partitionId(identity.issuerIndexPartitionCount()); UUID accountIndexFence = UUID.randomUUID(); UUID reservationId = UUID.randomUUID(); UUID transitionId = UUID.randomUUID(); @@ -709,14 +742,16 @@ private static void seedActiveSource( } private static String originalReservationImage(DSLContext dsl) { - return dsl.fetchOne( + return fetchRequired( + dsl, "SELECT coalesce(jsonb_agg(to_jsonb(r) ORDER BY reservation_id), '[]'::jsonb)::text AS image " + "FROM game_session_canonical_issuer_partition_reservation r") .get("image", String.class); } private static String anchorStorageImage(DSLContext dsl) { - return dsl.fetchOne( + return fetchRequired( + dsl, "SELECT encode(exact_anchor_bytes, 'base64') || ':' || exact_anchor_digest || ':'" + " || global_coverage_generation::text AS image" + " FROM game_session_canonical_issuer_installed_anchor WHERE issuer_id = ?", @@ -725,7 +760,8 @@ private static String anchorStorageImage(DSLContext dsl) { } private static String proofStorageImage(DSLContext dsl) { - return dsl.fetchOne( + return fetchRequired( + dsl, "SELECT coalesce(string_agg(partition_id::text || ':'" + " || encode(exact_metadata_bytes, 'base64') || ':'" + " || encode(exact_physical_field_set_bytes, 'base64') || ':'" @@ -735,23 +771,33 @@ private static String proofStorageImage(DSLContext dsl) { } private static long fixtureProofCount(Fixture fixture) { - return fixture.dsl() - .fetchOne( + return fetchRequired( + fixture.dsl(), "SELECT count(*) AS proof_count FROM game_session_canonical_issuer_bootstrap_partition_proof") .get("proof_count", Long.class); } private static void assertNoInstalledCoverage(Fixture fixture) { - assertThat(fixture.dsl().fetchOne( - "SELECT count(*) AS anchor_count FROM game_session_canonical_issuer_installed_anchor") - .get("anchor_count", Long.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT count(*) AS anchor_count FROM game_session_canonical_issuer_installed_anchor") + .get("anchor_count", Long.class)) .isZero(); - assertThat(fixture.dsl().fetchOne( - "SELECT count(*) AS counter_count FROM game_session_canonical_issuer_bootstrap_coverage_counter") - .get("counter_count", Long.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT count(*) AS counter_count FROM game_session_canonical_issuer_bootstrap_coverage_counter") + .get("counter_count", Long.class)) .isZero(); } + private static Record fetchRequired(DSLContext dsl, String sql, Object... bindings) { + Record record = dsl.fetchOne(sql, bindings); + if (record == null) throw new IllegalStateException("Required focused query returned no row"); + return record; + } + private static byte[] key(Fixture fixture, BigInteger partitionId) { return CanonicalGameplayIssuerRedisKeys.forPartition( fixture.intent().layoutDescriptor(), partitionId) @@ -777,13 +823,23 @@ private void establishActualLegacyDisposition(DSLContext dsl) { "controlled-redis-volume-uid"); var fencedCohort = new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { - @Override public UUID cohortId() { return cohortId; } - @Override public UUID legacyWriterFence() { return writerFence; } - @Override public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + @Override + public UUID cohortId() { + return cohortId; + } + + @Override + public UUID legacyWriterFence() { + return writerFence; + } + + @Override + public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { return storageIdentity; } - @Override public void requireStillFenced( - CanonicalGameplayLegacyMigrationStorageIdentity expected) { + + @Override + public void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity expected) { if (!storageIdentity.equals(expected)) { throw new IllegalStateException("Controlled test storage identity changed"); } @@ -804,17 +860,22 @@ private void establishActualLegacyDisposition(DSLContext dsl) { Family.DURABLE_EFFECT), List.of()), new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { - @Override public void rebuildExact( + @Override + public void rebuildExact( CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, CanonicalGameplayLegacyMigrationSourceSnapshot source, - net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventorySnapshot + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot canonical) { assertThat(canonical.bindings()).isEmpty(); assertThat(canonical.reservations()).isEmpty(); } - @Override public CanonicalGameplayLegacyMigrationReadback readBackExact( + + @Override + public CanonicalGameplayLegacyMigrationReadback readBackExact( CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, - net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventorySnapshot + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot canonical) { assertThat(canonical.bindings()).isEmpty(); return new CanonicalGameplayLegacyMigrationReadback( @@ -865,7 +926,8 @@ private void dropSchema(String schema) { DSL.using(connection, SQLDialect.POSTGRES) .execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); } catch (SQLException failure) { - throw new IllegalStateException("Could not drop the owned issuer coverage test schema", failure); + throw new IllegalStateException( + "Could not drop the owned issuer coverage test schema", failure); } } @@ -904,7 +966,9 @@ private record Fixture( CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint currentAccountCheckpoint, CanonicalGameplayIssuerPartitionBuildPlan plan) { - DSLContext dsl() { return schema.dsl(); } + DSLContext dsl() { + return schema.dsl(); + } } private record TestSchema(String schema, DriverManagerDataSource dataSource, DSLContext dsl) {} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java index f9aa136284..a1c6c491aa 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java @@ -87,13 +87,17 @@ void actualPreparedPlanIssuesExactPendingV2OperationAndPreservesV1031RowsAcrossR assertThat(fixture.plan().state()) .isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED); Map> retainedBefore = rowSnapshots(fixture.testSchema().dsl()); + Map> retainedWithXminBefore = + rowSnapshotsWithXmin(fixture.testSchema().dsl()); List historyBefore = historySnapshot(fixture.testSchema().dsl()); - migrateRemaining(fixture.testSchema()); + migrateThrough1032(fixture.testSchema()); assertThat(rowSnapshots(fixture.testSchema().dsl())).isEqualTo(retainedBefore); - List historyAfterMigration = historySnapshot(fixture.testSchema().dsl()); - assertThat(historyAfterMigration).hasSize(historyBefore.size() + 1); - assertThat(historyAfterMigration.subList(0, historyBefore.size())) + assertThat(rowSnapshotsWithXmin(fixture.testSchema().dsl())) + .isEqualTo(retainedWithXminBefore); + List historyAfter1032 = historySnapshot(fixture.testSchema().dsl()); + assertThat(historyAfter1032).hasSize(historyBefore.size() + 1); + assertThat(historyAfter1032.subList(0, historyBefore.size())) .containsExactlyElementsOf(historyBefore); assertThat( fixture @@ -102,6 +106,28 @@ void actualPreparedPlanIssuesExactPendingV2OperationAndPreservesV1031RowsAcrossR .fetchSingle("SELECT script FROM flyway_schema_history WHERE version = '1032'") .get(0, String.class)) .isEqualTo("V1032__canonical_issuer_bootstrap_member_operation.sql"); + + migrateRemaining(fixture.testSchema()); + assertThat(rowSnapshots(fixture.testSchema().dsl())).isEqualTo(retainedBefore); + assertThat(rowSnapshotsWithXmin(fixture.testSchema().dsl())) + .isEqualTo(retainedWithXminBefore); + List historyAfterMigration = historySnapshot(fixture.testSchema().dsl()); + assertThat(historyAfterMigration.subList(0, historyAfter1032.size())) + .containsExactlyElementsOf(historyAfter1032); + assertThat( + fixture + .testSchema() + .dsl() + .fetchSingle("SELECT script FROM flyway_schema_history WHERE version = '1032'") + .get(0, String.class)) + .isEqualTo("V1032__canonical_issuer_bootstrap_member_operation.sql"); + assertThat( + fixture + .testSchema() + .dsl() + .fetchSingle("SELECT script FROM flyway_schema_history WHERE version = '1033'") + .get(0, String.class)) + .isEqualTo("V1033__canonical_issuer_bootstrap_coverage.sql"); assertThat( fixture .testSchema() @@ -863,6 +889,18 @@ private static void migrateThrough1031(TestSchema testSchema) { .migrate(); } + private static void migrateThrough1032(TestSchema testSchema) { + Flyway.configure() + .dataSource(testSchema.dataSource()) + .schemas(testSchema.schema()) + .defaultSchema(testSchema.schema()) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("1032")) + .load() + .migrate(); + } + private static void migrateRemaining(TestSchema testSchema) { Flyway.configure() .dataSource(testSchema.dataSource()) @@ -895,6 +933,12 @@ private static Map> rowSnapshots(DSLContext dsl) { return Map.copyOf(snapshots); } + private static Map> rowSnapshotsWithXmin(DSLContext dsl) { + Map> snapshots = new LinkedHashMap<>(); + for (String table : RETAINED_TABLES) snapshots.put(table, rowImagesWithXmin(dsl, table)); + return Map.copyOf(snapshots); + } + private static List historySnapshot(DSLContext dsl) { return dsl.fetch( "SELECT to_jsonb(history_row)::text AS row_image FROM flyway_schema_history history_row" @@ -910,6 +954,14 @@ private static List rowImages(DSLContext dsl, String tableName) { .getValues("row_image", String.class); } + private static List rowImagesWithXmin(DSLContext dsl, String tableName) { + return dsl.fetch( + "SELECT xmin::text || ':' || to_jsonb(retained_row)::text AS row_image FROM " + + tableName + + " retained_row ORDER BY to_jsonb(retained_row)::text, xmin::text") + .getValues("row_image", String.class); + } + private static void assertNoIssuedRows(DSLContext dsl) { assertThat(rowImages(dsl, "game_session_canonical_issuer_bootstrap_member_operation")) .isEmpty(); 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 539de03fac..b27c2e5441 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 @@ -106,7 +106,7 @@ void populatedPendingIntentRetainsCompleteCohortAndBothCoverageTuplesAcrossConcu rowImages(testSchema.dsl(), "game_session_canonical_binding_region_bridge_obligation"); List inventoryClockBefore = rowImages(testSchema.dsl(), "game_session_canonical_binding_inventory_clock"); - List migrationHistoryBefore = rowImages(testSchema.dsl(), "flyway_schema_history"); + List migrationHistoryBefore = migrationHistorySnapshot(testSchema.dsl()); List retainedSourceTables = List.of( "game_session_canonical_gameplay_binding_inventory", @@ -125,10 +125,10 @@ void populatedPendingIntentRetainsCompleteCohortAndBothCoverageTuplesAcrossConcu .toList(); migrateThrough1031(testSchema); - List migrationHistoryAfter1031 = rowImages(testSchema.dsl(), "flyway_schema_history"); - assertThat(migrationHistoryAfter1031) - .hasSize(migrationHistoryBefore.size() + 1) - .containsAll(migrationHistoryBefore); + List migrationHistoryAfter1031 = migrationHistorySnapshot(testSchema.dsl()); + assertThat(migrationHistoryAfter1031).hasSize(migrationHistoryBefore.size() + 1); + assertThat(migrationHistoryAfter1031.subList(0, migrationHistoryBefore.size())) + .containsExactlyElementsOf(migrationHistoryBefore); assertThat( testSchema .dsl() @@ -141,18 +141,43 @@ void populatedPendingIntentRetainsCompleteCohortAndBothCoverageTuplesAcrossConcu .toList()) .isEqualTo(retainedRowsWithXminBefore); + List> retainedRowsWithXminAt1031 = + retainedSourceTables.stream() + .map(table -> rowImagesWithXmin(testSchema.dsl(), table)) + .toList(); + migrateThrough1032(testSchema); + List migrationHistoryAfter1032 = migrationHistorySnapshot(testSchema.dsl()); + assertThat(migrationHistoryAfter1032).hasSize(migrationHistoryAfter1031.size() + 1); + assertThat(migrationHistoryAfter1032.subList(0, migrationHistoryAfter1031.size())) + .containsExactlyElementsOf(migrationHistoryAfter1031); + assertThat( + testSchema + .dsl() + .fetchSingle("SELECT script FROM flyway_schema_history WHERE version = '1032'") + .get(0, String.class)) + .isEqualTo("V1032__canonical_issuer_bootstrap_member_operation.sql"); + assertThat( + retainedSourceTables.stream() + .map(table -> rowImagesWithXmin(testSchema.dsl(), table)) + .toList()) + .isEqualTo(retainedRowsWithXminAt1031); + migrateRemaining(testSchema); - List migrationHistoryAfterCurrent = - rowImages(testSchema.dsl(), "flyway_schema_history"); - assertThat(migrationHistoryAfterCurrent) - .hasSize(migrationHistoryAfter1031.size() + 1) - .containsAll(migrationHistoryAfter1031); + List migrationHistoryAfterCurrent = migrationHistorySnapshot(testSchema.dsl()); + assertThat(migrationHistoryAfterCurrent.subList(0, migrationHistoryAfter1032.size())) + .containsExactlyElementsOf(migrationHistoryAfter1032); assertThat( testSchema .dsl() .fetchSingle("SELECT script FROM flyway_schema_history WHERE version = '1032'") .get(0, String.class)) .isEqualTo("V1032__canonical_issuer_bootstrap_member_operation.sql"); + assertThat( + testSchema + .dsl() + .fetchSingle("SELECT script FROM flyway_schema_history WHERE version = '1033'") + .get(0, String.class)) + .isEqualTo("V1033__canonical_issuer_bootstrap_coverage.sql"); var ready = new CountDownLatch(2); var start = new CountDownLatch(1); @@ -276,7 +301,7 @@ void populatedPendingIntentRetainsCompleteCohortAndBothCoverageTuplesAcrossConcu .containsExactlyElementsOf(regionObligationsBefore); assertThat(rowImages(testSchema.dsl(), "game_session_canonical_binding_inventory_clock")) .containsExactlyElementsOf(inventoryClockBefore); - List migrationHistoryAfter = rowImages(testSchema.dsl(), "flyway_schema_history"); + List migrationHistoryAfter = migrationHistorySnapshot(testSchema.dsl()); assertThat(migrationHistoryAfter).containsExactlyElementsOf(migrationHistoryAfterCurrent); assertThat( retainedSourceTables.stream() @@ -1268,6 +1293,18 @@ private static void migrateThrough1031(TestSchema testSchema) { .migrate(); } + private static void migrateThrough1032(TestSchema testSchema) { + Flyway.configure() + .dataSource(testSchema.dataSource()) + .schemas(testSchema.schema()) + .defaultSchema(testSchema.schema()) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("1032")) + .load() + .migrate(); + } + private static void migrateRemaining(TestSchema testSchema) { Flyway.configure() .dataSource(testSchema.dataSource()) @@ -1385,6 +1422,13 @@ private static List rowImagesWithXmin(DSLContext dsl, String tableName) .getValues("row_image", String.class); } + private static List migrationHistorySnapshot(DSLContext dsl) { + return dsl.fetch( + "SELECT to_jsonb(history_row)::text AS row_image FROM flyway_schema_history history_row" + + " ORDER BY installed_rank") + .getValues("row_image", String.class); + } + private static void dropSchema(String schema) { try (Connection connection = dataSource("public").getConnection()) { DSL.using(connection, SQLDialect.POSTGRES) From c9399be82b4903bff9a4e9192b4b9f1a956f7b56 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:36:26 +1300 Subject: [PATCH 10/34] Prepare actual first-NEW abort source and integrated issuer operations --- .../game-session-service/api-contracts.md | 2 +- .../player-access-and-session.md | 2 +- services/account-service/build.gradle.kts | 1 + ...nitiveAbortCompositionIntegrationTest.java | 317 +++++ ...CurrentSourcesPostgresIntegrationTest.java | 26 +- .../game-session-service/build.gradle.kts | 2 + ...anonicalGameplayAdmissionAbortOutcome.java | 73 ++ ...CanonicalGameplayAdmissionAbortSource.java | 81 ++ ...alGameplayAdmissionAbortManualFactory.java | 72 ++ .../CanonicalGameplayAdmissionAbortOwner.java | 132 ++ ...calGameplayBindingInventoryRepository.java | 637 +++++++++- ...alGameplayIssuerBindingLocalOperation.java | 232 ++++ ...IssuerBindingLocalOperationRepository.java | 1118 +++++++++++++++++ ...ssuerBindingLocalProjectionRepository.java | 1114 ++++++++++++++++ ...lGameplayIssuerBindingLocalRedisOwner.java | 530 ++++++++ ...lGameplayIssuerBootstrapCoverageOwner.java | 18 +- ...playIssuerBootstrapCoverageRepository.java | 431 +++++-- ...anonicalGameplayIssuerInstalledAnchor.java | 204 ++- ...ameplayIssuerPartitionBuildRepository.java | 42 + ...layAdmissionDecisionReadWorkloadGuard.java | 66 + ...tectedGameSessionLoginGrpcInterceptor.java | 3 +- ...erBindingLocalRedisScriptContribution.java | 51 + ...eplayAdmissionDecisionReadGrpcService.java | 212 ++++ ...nonical_issuer_binding_local_operation.sql | 206 +++ ...onical_gameplay_first_new_abort_source.sql | 660 ++++++++++ .../game-session-issuer-binding-local-add.lua | 404 ++++++ ...game-session-issuer-binding-local-add.json | 40 + ...eplayAdmissionAbortCompositionFixture.java | 182 +++ ...calGameplayBindingRuntimeTestFixtures.java | 8 +- ...calOperationRepositoryIntegrationTest.java | 803 ++++++++++++ ...BindingLocalRedisOwnerIntegrationTest.java | 1085 ++++++++++++++++ ...BootstrapCoverageOwnerIntegrationTest.java | 276 ++-- ...berOperationRepositoryIntegrationTest.java | 60 +- ...rtitionBuildRepositoryIntegrationTest.java | 66 +- ...onicalGameplayAdmissionAbortOwnerTest.java | 240 ++++ ...yAdmissionDecisionReadGrpcServiceTest.java | 91 ++ ...dmissionDecisionReadWorkloadGuardTest.java | 110 ++ ...edGameSessionLoginGrpcInterceptorTest.java | 25 + 38 files changed, 9337 insertions(+), 285 deletions(-) create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAdmissionAbortOutcome.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAdmissionAbortSource.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortManualFactory.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwner.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperation.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuard.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRedisScriptContribution.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V1034__canonical_issuer_binding_local_operation.sql create mode 100644 services/game-session-service/src/main/resources/db/migration/V1035__canonical_gameplay_first_new_abort_source.sql create mode 100644 services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-add.lua create mode 100644 services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-add.json create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwnerTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuardTest.java diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index fbbc34d7b0..fc55dc08ce 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -8,7 +8,7 @@ Target state makes Game Session the authoritative owner of region/tick coordinat ## Implementation Status -The local issuer-index model, codec and key helper carry the selected physical member schema v2; decoding validates shape, not current source, anchor, capacity or incarnation authority. This storage consequence adds no public or internal RPC. Retained physical v1 artifacts are unqualified and have no fallback, and Account acknowledgement schema v2 remains account-only. The separate owner-qualified issuer acknowledgement and final guarded controller CAS remain required before manual NEW consumers can admit; see the [issuer-index owner](../../system-architecture-redis.md#issuer-active-binding-index) and [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components). +The local issuer-index source carries the selected physical member schema v2 and manually composed SQL, partition and finite initial-coverage owners. Decoding alone validates shape, not current source, anchor, capacity or incarnation authority. Component qualification and the unfinished ordinary-operation and cleanup composition are recorded in the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components); this source is unregistered and supplies no player admission. Retained physical v1 artifacts remain unqualified without fallback, and Account acknowledgement schema v2 remains account-only. The separate owner-qualified issuer acknowledgement and final guarded controller CAS remain required before manual NEW consumers can admit; the [issuer-index owner](../../system-architecture-redis.md#issuer-active-binding-index) owns that contract. The local [canonical NEW admission lease contract](../../system-architecture-session-behavior.md#canonical-public-production-new-admission) now has generated transport carriers and a manually composed `AccountGameplayAdmissionLeaseClient` for Account’s four purpose-specific methods. Its narrow candidate uses the exact Account issuer string at the original string wire tag; shape validation supplies no issuer authority. The [Account API](../account-service/api-contracts.md#canonical-public-production-new-admission-lease-source) owns caller authentication, acquisition, original finalization and read/abort recovery. The prepared Account-only reverse-read proto and closed codec preserve separate current published-target and exact provisional-decision purposes, with their finite transport bounds; this prerequisite does not supply their genuine Game Session owner composition or register a source receiver. The Account receiver’s focused physical-COMMIT and durable-ACK proof uses explicitly controlled reverse responses. These local components do not acknowledge issuer/region obligations or admit a binding; the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) records component proof and remaining composition. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index f0976c775f..fc5a14f289 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -22,7 +22,7 @@ A Redis restart or reset can change the stable incarnation while AOF retains the The current local issuer source extends the retained V1030 cohort through immutable V1031 plan/work/blocker rows and V1032 SQL-issued member operations. The original reservation coverage tuple remains distinct from the new bootstrap anchor; equal numeric counters across those separate domains are permissible and do not equate their full identities. R569 passes seven PostgreSQL plan cases, including source/control/layout refusal, original retry, retained-row and TRUNCATE guards, and per-partition/aggregate nonterminal reservation bounds with RELEASED exclusion. R575 passes four operation-producer and seven plan-regression cases. The owner allocates the local member-operation fence and generation before projection; those values confer no global coverage generation or completion. -R578 freshly passes the composed four SQL-producer, seven plan-regression and seven physical Redis-owner cases on local checkpoint `a5c2b1c69151029a5be203c720c2618f0866f71a` plus its qualified formatter and test corrections. The actual owner builds or exactly replays one canonical partition HASH, independently reads the complete field set through a separate connection, and brackets the remote phase with controlled current Account checkpoint and stable-incarnation reads. Proof includes populated and positively prepared empty partitions, full original/new tuple conflict, retained terminal reservations, capacity refusal, wrong type/TTL/foreign/v1 evidence, original lost-reply retry and source/incarnation movement. Enabled affected Checkstyle, SpotBugs and formatting pass; all five exact R578 containers are independently confirmed absent. R577 remains a failed aggregate: a fixture incorrectly required independent numeric fences to differ and its status-query helper failed null-safety static analysis; the correction preserves full tuple comparison and exact stored bytes. These results prove local partition projection/readback under controlled collaborators, not operational source or incarnation custody. R579 separately passes all nine PostgreSQL bootstrap-owner cases with enabled affected static analysis and formatting, including the accepted exact pre-intent replay correction, conflicting retry refusal and unchanged durable row/counter images; its exact PostgreSQL container is independently confirmed absent. Complete finite coverage acceptance, installed anchor, ordinary NEW consumption, cleanup and admission remain unfinished; the combined owner scope stays in #3310 and unpublished work is not green runway. +R578 freshly passes the composed four SQL-producer, seven plan-regression and seven physical Redis-owner cases on local checkpoint `a5c2b1c69151029a5be203c720c2618f0866f71a` plus its qualified formatter and test corrections. The actual owner builds or exactly replays one canonical partition HASH, independently reads the complete field set through a separate connection, and brackets the remote phase with controlled current Account checkpoint and stable-incarnation reads. Proof includes populated and positively prepared empty partitions, full original/new tuple conflict, retained terminal reservations, capacity refusal, wrong type/TTL/foreign/v1 evidence, original lost-reply retry and source/incarnation movement. Enabled affected Checkstyle, SpotBugs and formatting pass; all five exact R578 containers are independently confirmed absent. R577 remains a failed aggregate: a fixture incorrectly required independent numeric fences to differ and its status-query helper failed null-safety static analysis; the correction preserves full tuple comparison and exact stored bytes. These results prove local partition projection/readback under controlled collaborators, not operational source or incarnation custody. R579 separately passes all nine PostgreSQL bootstrap-owner cases with enabled affected static analysis and formatting, including the accepted exact pre-intent replay correction, conflicting retry refusal and unchanged durable row/counter images; its exact PostgreSQL container is independently confirmed absent. R583 subsequently passes 33 focused actual PostgreSQL/Redis cases with enabled generation, static analysis and formatting, qualifying the finite initial coverage owner under controlled descriptor, current-source and incarnation collaborators. It retains every partition’s exact proof before allocating the global coverage generation and installing the immutable initial anchor. Exact installed replay reads existing physical state without rebuilding it, and a later counter-head advance preserves the retained anchor. All eight exact containers are independently confirmed absent. These component results do not establish operational source custody or tenant admission. The ordinary post-baseline SQL/Redis path and real Account-abort/issuer-cleanup consequence remain under local implementation and qualification; issuer/region acknowledgements, barrier OPEN, final CAS and playable admission remain unfinished. The complete combined owner scope stays in #3310; the published prefix and unpublished source are not green successor runway. ### Player-created roster consumer preparation diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index c73ad2554a..c482a1e39c 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -86,6 +86,7 @@ dependencies { testImplementation(testFixtures(project(":common-platform-core"))) testCompileOnly(libs.spotbugs.annotations) add("integrationTestCompileOnly", libs.spotbugs.annotations) + integrationTestImplementation(project(path = ":game-session-service", configuration = "gameSessionClassesProof")) integrationTestImplementation(testFixtures(project(":account-service"))) integrationTestImplementation(testFixtures(project(":logging-admin-service"))) } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java new file mode 100644 index 0000000000..f29d23367a --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java @@ -0,0 +1,317 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; + +import io.grpc.Server; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.PhysicalRedisFixture; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionLeaseManualFactory; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.State; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortOutcome; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +import net.firedevops.firemud.gamesession.client.AccountGameplayAdmissionLeaseClient; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayAdmissionAbortCompositionFixture; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayAdmissionAbortManualFactory; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; + +/** + * Actual Account acquisition/current caller/physical token and abort owner, real GS durable + * PROVISIONAL reverse read and guarded abort CAS, physical PostgreSQL/Redis and manual mTLS. + * Launch/publication/initial-target and test PKI inputs remain controlled. This proves neither + * physical issuer release nor runtime registration, admission, production PKI or terminal cleanup. + */ +@Execution(ExecutionMode.SAME_THREAD) +class AccountGameSessionDefinitiveAbortCompositionIntegrationTest { + private static final String GS = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String ACCOUNT = "spiffe://firemud/ns/test/sa/account-service"; + private final AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest accountFixtures = + new AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest(); + @TempDir Path temporaryDirectory; + + @BeforeAll static void startPostgres() { AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.startPostgres(); } + @AfterAll static void stopPostgres() { AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.stopPostgres(); } + @AfterEach void cleanupAccountSchemas() { accountFixtures.dropRunOwnedSchemas(); } + + @Test + void actualAbortExactRetryAndRestartRetainOriginalLeaseAndRejectTerminalRewrites() throws Exception { + try (var session = open()) { + var original = session.gs.source(); + var result = session.abort(); + assertThat(result.state()).isEqualTo(CanonicalGameplayAdmissionAbortOutcome.State.ABORTED); + var source = session.gs.source(); + var retainedImage = session.image(); + assertThat(source.isAccountAborted()).isTrue(); + assertThat(source.orphanCleanupId()).isEqualTo(result.orphanCleanupId()); + assertThat(source.originalDecision().leaseEvidenceJson()).isEqualTo(original.originalDecision().leaseEvidenceJson()); + assertThat(source.originalDecision().leaseSha256()).isEqualTo(original.originalDecision().leaseSha256()); + assertThat(source.candidate().lifecycle()).isEqualTo(CanonicalGameplayBindingInventoryEntry.Lifecycle.TERMINAL_UNRESOLVED); + assertThat(source.reservation().lifecycle()).isEqualTo(CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING); + // New owner instance and independent repository read recover the same retained source. + assertThat(session.abort().orphanCleanupId()).isEqualTo(result.orphanCleanupId()); + assertThat(session.client.read(session.jwt, session.leaseBytes()).state()).isEqualTo(State.ABORTED); + assertThat(session.client.finalizeLease(session.jwt, session.leaseBytes(), session.gs.transitionId()).state()).isEqualTo(State.ABORTED); + assertThatThrownBy(() -> session.abortWith("invalid-current-caller-token")).isInstanceOf(RuntimeException.class); + assertThat(session.image()).isEqualTo(retainedImage); + + for (String assignment : new String[] { + "admission_orphan_cleanup_id = '34343434-3434-4434-8434-343434343434'", + "status = 'PROVISIONAL', admission_orphan_cleanup_id = NULL", + "admission_lease_id = '45454545-4545-4545-8545-454545454545'", + "admission_lease_digest = '" + "e".repeat(64) + "'", + "admission_lease_evidence = '{}'", + "inventory_revision = inventory_revision - 1" }) { + assertThatThrownBy(() -> session.gs.dsl().execute( + "UPDATE game_session_canonical_binding_transition SET " + assignment + " WHERE transition_id = ?", + session.gs.transitionId())).isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(session.image()).isEqualTo(retainedImage); + } + assertThatThrownBy(() -> session.gs.dsl().execute( + "UPDATE game_session_canonical_issuer_partition_reservation SET lifecycle = 'RELEASED' WHERE transition_id = ?", + session.gs.transitionId())).isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(session.image()).isEqualTo(retainedImage); + // Cleanup is intentionally unresolved. A newer first-NEW candidate must remain fenced; + // this boundary does not fabricate an admitted/newer binding to claim cleanup safety. + assertThatThrownBy(session.gs::prepareNewerCandidate).isInstanceOf(RuntimeException.class); + assertThat(session.abort().orphanCleanupId()).isEqualTo(result.orphanCleanupId()); + assertThat(session.image()).isEqualTo(retainedImage); + } + } + + @Test + void actualAccountAbortWithLostReplyKeepsGsProvisionalThenRecoversSameOriginalAfterRestart() throws Exception { + try (var session = open()) { + var before = session.image(); + var lostReplyClient = mock(AccountGameplayAdmissionLeaseClient.class); + doAnswer(invocation -> { + session.client.abort(session.jwt, session.leaseBytes(), session.gs.transitionId()); + throw new IllegalStateException("controlled loss after actual Account ABORTED reply"); + }).when(lostReplyClient).abort(any(), any(), any()); + var lostReplyOwner = CanonicalGameplayAdmissionAbortManualFactory.createUnregisteredOwner(session.gs.dsl(), lostReplyClient); + assertThatThrownBy(() -> lostReplyOwner.abortFirstNew(session.gs.transitionId(), session.jwt)) + .hasMessage("controlled loss after actual Account ABORTED reply"); + assertThat(session.image()).isEqualTo(before); + var accountAbort = session.client.read(session.jwt, session.leaseBytes()); + assertThat(accountAbort.state()).isEqualTo(State.ABORTED); + session.restartAccount(); + assertThat(session.abort().orphanCleanupId()).isEqualTo(accountAbort.orphanCleanupId()); + assertThat(session.client.finalizeLease(session.jwt, session.leaseBytes(), session.gs.transitionId()).state()).isEqualTo(State.ABORTED); + } + } + + @Test + void unavailableActualReverseReadCannotInferAbortFromAbsenceOrExpiry() throws Exception { + try (var session = open()) { + var before = session.image(); + session.gsServer.shutdownNow(); + assertThat(session.gsServer.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + assertThatThrownBy(session::abort).isInstanceOf(RuntimeException.class); + assertThat(session.client.read(session.jwt, session.leaseBytes()).state()).isEqualTo(State.PENDING); + assertThat(session.image()).isEqualTo(before); + long expiresAt = Long.parseLong((String) session.lease.carrier().get("expiresAt")); + long remaining = expiresAt - System.currentTimeMillis(); + if (remaining >= 0) Thread.sleep(remaining + 5L); + assertThatThrownBy(session::abort).isInstanceOf(RuntimeException.class); + assertThat(session.client.read(session.jwt, session.leaseBytes()).state()).isEqualTo(State.PENDING); + assertThat(session.image()).isEqualTo(before); + } + } + + @Test + void actualConcurrentFinalizeAndAbortHaveOneAccountWinnerWithoutGsCommittedRelabelling() throws Exception { + try (var session = open(); var executor = Executors.newFixedThreadPool(2)) { + var start = new CountDownLatch(1); + var finalize = executor.submit(() -> { + start.await(); + try { return session.client.finalizeLease(session.jwt, session.leaseBytes(), session.gs.transitionId()); } + catch (RuntimeException ambiguous) { return null; } + }); + var abort = executor.submit(() -> { + start.await(); + try { return session.abort(); } catch (RuntimeException ambiguous) { return null; } + }); + start.countDown(); + var finalized = finalize.get(20, TimeUnit.SECONDS); + var aborted = abort.get(20, TimeUnit.SECONDS); + // A missing ACK may make a committed read unavailable. The retained SQL operation still + // decides one winner; no test manufactures a receipt or relabels that winner. + var accountRow = session.accountFixture.dataSource; + var retained = org.jooq.impl.DSL.using(accountRow, org.jooq.SQLDialect.POSTGRES) + .fetchSingle("SELECT status FROM account_gameplay_admission_lease_operations WHERE lease_id = ?", + UUID.fromString((String) session.lease.carrier().get("leaseId"))); + assertThat(retained.get("status", String.class)).isIn("ABORTED", "COMMITTED"); + if ("ABORTED".equals(retained.get("status", String.class))) { + assertThat(session.abort().state()).isEqualTo(CanonicalGameplayAdmissionAbortOutcome.State.ABORTED); + assertThat(session.client.finalizeLease(session.jwt, session.leaseBytes(), session.gs.transitionId()).state()).isEqualTo(State.ABORTED); + if (finalized != null) assertThat(finalized.state()).isEqualTo(State.ABORTED); + } else { + assertThat(session.gs.source().isAccountAborted()).isFalse(); + if (aborted != null) assertThat(aborted.state()).isEqualTo(CanonicalGameplayAdmissionAbortOutcome.State.ACCOUNT_COMMITTED); + } + } + } + + @Test + void actualReverseReadRefusesWrongPeerDecisionAndChangedOriginalTupleWithoutAccountAbort() throws Exception { + try (var session = open()) { + var before = session.image(); + assertThat(session.reverse.read(session.gs.transitionId(), session.lease).bindingDecisionId()) + .isEqualTo(session.gs.transitionId()); + assertThatThrownBy(() -> session.reverse.read(UUID.randomUUID(), session.lease)) + .isInstanceOf(RuntimeException.class); + var changedCarrier = new java.util.LinkedHashMap<>(session.lease.carrier()); + changedCarrier.put("leaseFence", session.lease.leaseFence().add(java.math.BigInteger.ONE).toString()); + var changedLease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changedCarrier); + assertThatThrownBy(() -> session.reverse.read(session.gs.transitionId(), changedLease)) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy(() -> session.client.abort(session.jwt, + changedLease.canonicalJson().getBytes(StandardCharsets.UTF_8), session.gs.transitionId())) + .isInstanceOf(RuntimeException.class); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameSessionService("127.0.0.1:" + session.gsServer.getPort()); + try (var wrongPeer = new CanonicalGameplayAdmissionDecisionReadClient(endpoints, + session.pki.clientProperties(session.pkiDirectory, session.pki.identity("wrong")), + new GrpcChannelFactory(), "test")) { + wrongPeer.init(); + assertThatThrownBy(() -> wrongPeer.read(session.gs.transitionId(), session.lease)) + .isInstanceOf(RuntimeException.class); + } + assertThat(session.client.read(session.jwt, session.leaseBytes()).state()).isEqualTo(State.PENDING); + assertThat(session.image()).isEqualTo(before); + // The runtime owner cannot retire the launch underneath this exact pending decision. + assertThatThrownBy(session.gs::stopRuntime) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("runtime row is fenced by an unresolved lease-bound binding decision"); + assertThat(session.image()).isEqualTo(before); + assertThat(session.abort().state()).isEqualTo(CanonicalGameplayAdmissionAbortOutcome.State.ABORTED); + } + } + + private Session open() throws Exception { + accountFixtures.temporaryDirectory = temporaryDirectory; + return new Session(); + } + + private final class Session implements AutoCloseable { + private final PhysicalRedisFixture redis = PhysicalRedisFixture.start(); + private final AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.Fixture accountFixture; + private final CanonicalGameplayAdmissionAbortCompositionFixture gs; + private final LoopbackMtlsTestPki.Pki pki; + private final Path pkiDirectory; + private final String jwt; + private final CanonicalGameplayAdmissionDecisionReadClient reverse; + private final AccountGameplayAdmissionCallerVerifier verifier; + private Server gsServer; + private Server accountServer; + private AccountGameplayAdmissionLeaseClient client; + private AccountGameplayAdmissionLeaseEvidence lease; + + private Session() throws Exception { + try { + accountFixture = accountFixtures.newFixture(redis.client()); + var issuance = accountFixture.committedCandidate.identity(); + var credential = accountFixture.responseRecoveryOwner.recoverInitialLoginResponse( + issuance.requestId(), issuance.accountId(), new CallerIdentity(issuance.callerWorkload(), issuance.callerContextId())); + jwt = new String(credential.compactJwtBytes(), StandardCharsets.US_ASCII); + gs = new CanonicalGameplayAdmissionAbortCompositionFixture(accountFixture.dataSource, + AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.admissionCandidate(accountFixture)); + pkiDirectory = Files.createTempDirectory(temporaryDirectory, "actual-abort-mtls-"); + pki = LoopbackMtlsTestPki.create(pkiDirectory, "Account GS abort test CA", + new LoopbackMtlsTestPki.IdentitySpec("account", ACCOUNT, true), + new LoopbackMtlsTestPki.IdentitySpec("gs", GS, true), + new LoopbackMtlsTestPki.IdentitySpec("gs-client", GS, false), + new LoopbackMtlsTestPki.IdentitySpec("account-client", ACCOUNT, false), + new LoopbackMtlsTestPki.IdentitySpec("wrong", "spiffe://firemud/ns/test/sa/world-management-service", false)); + gsServer = CanonicalGameplayAdmissionAbortManualFactory.createUnregisteredDecisionReadServer( + "127.0.0.1:0", pki.keyManagerFactory(pki.identity("gs")), pki.trustManagerFactory(), gs.dsl(), "test"); + gsServer.start(); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameSessionService("127.0.0.1:" + gsServer.getPort()); + reverse = spy(new CanonicalGameplayAdmissionDecisionReadClient(endpoints, + pki.clientProperties(pkiDirectory, pki.identity("account-client")), new GrpcChannelFactory(), "test")); + // Only published-target authority is controlled. read(decisionId, originalLease) uses the + // actual mTLS receiver/repository; it is never stubbed or replaced by DTO equality. + reverse.init(); + UUID requestId = UUID.randomUUID(); + doReturn(AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.controlledPublishedTarget(gs.candidate(), gs.target(), requestId)) + .when(reverse).readPublishedRealmAdmissionOwner(any()); + verifier = new AccountGameplayAdmissionCallerVerifier(accountFixture.signerFixture.trustedJwksSource(), + accountFixture.committedIssuanceOwner, Clock.systemUTC()); + restartAccount(); + lease = client.acquire(requestId, jwt, gs.candidate(), gs.target(), gs.generation()).originalLeaseEvidence(); + gs.publish(lease); + } catch (Exception | Error setupFailure) { + try { close(); } catch (Exception cleanupFailure) { setupFailure.addSuppressed(cleanupFailure); } + throw setupFailure; + } + } + + private void restartAccount() throws Exception { + if (client != null) client.close(); + if (accountServer != null) { + accountServer.shutdownNow(); + if (!accountServer.awaitTermination(5, TimeUnit.SECONDS)) throw new IllegalStateException("Account server teardown timed out"); + } + var owner = new AccountGameplayAdmissionLeaseOwner(verifier, reverse, "test", accountFixture.dataSource); + accountServer = AccountGameplayAdmissionLeaseManualFactory.createUnregisteredServer("127.0.0.1:0", + pki.keyManagerFactory(pki.identity("account")), pki.trustManagerFactory(), owner, "test"); + accountServer.start(); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + accountServer.getPort()); + client = new AccountGameplayAdmissionLeaseClient(endpoints, pki.clientProperties(pkiDirectory, pki.identity("gs-client")), new GrpcChannelFactory(), "test"); + client.init(); + } + private String image() { + return java.util.List.of("game_session_canonical_binding_transition", "game_session_canonical_gameplay_binding_inventory", + "game_session_canonical_issuer_partition_reservation").stream() + .map(table -> gs.dsl().fetch("SELECT to_jsonb(t)::text AS image FROM " + table + " t ORDER BY 1").getValues("image").toString()) + .collect(java.util.stream.Collectors.joining("\n")); + } + private byte[] leaseBytes() { return lease.canonicalJson().getBytes(StandardCharsets.UTF_8); } + private CanonicalGameplayAdmissionAbortOutcome abort() { return abortWith(jwt); } + private CanonicalGameplayAdmissionAbortOutcome abortWith(String callerToken) { + return CanonicalGameplayAdmissionAbortManualFactory.createUnregisteredOwner(gs.dsl(), client) + .abortFirstNew(gs.transitionId(), callerToken); + } + @Override public void close() throws Exception { + try { + if (client != null) client.close(); + if (reverse != null) reverse.close(); + } finally { + try { + if (accountServer != null) accountServer.shutdownNow(); + if (gsServer != null) gsServer.shutdownNow(); + if (accountServer != null) assertThat(accountServer.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + if (gsServer != null) assertThat(gsServer.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } finally { try { if (gs != null) gs.close(); } finally { redis.close(); } } + } + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java index c29c6a8b57..359082968e 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java @@ -1146,7 +1146,7 @@ private Fixture newFixture() throws Exception { return newFixture(null); } - private Fixture newFixture(AccountGameplayDelegationRedisClient redisClient) throws Exception { + Fixture newFixture(AccountGameplayDelegationRedisClient redisClient) throws Exception { String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); if (schema.length() > 63) throw new IllegalStateException("Generated schema name is too long"); runOwnedSchemas.add(schema); @@ -1422,7 +1422,7 @@ private static final class AdmissionClockCapture { private DataSource dataSource; } - private static Candidate admissionCandidate(Fixture fixture) { + static Candidate admissionCandidate(Fixture fixture) { var identity = fixture.committedCandidate.identity(); var authority = fixture.committedCandidate.authoritySnapshot(); return new Candidate( @@ -1532,7 +1532,7 @@ private static CanonicalGameplayAdmissionDecisionReadClient controlledPublishedT return decisionClient; } - private static PublishedRealmEvidence controlledPublishedTarget( + static PublishedRealmEvidence controlledPublishedTarget( Candidate candidate, Target target, UUID requestId) { var selector = new CanonicalGameplayRosterOwnerReadEvidence.Request( @@ -1708,9 +1708,9 @@ private record LeaseFenceRow(UUID accountId, long lastFence) {} private record LeaseAllocationState( long allocationCount, long fenceCount, LeaseAllocationRow allocation, LeaseFenceRow fence) {} - private static final class Fixture { + static final class Fixture { private final String schema; - private final DriverManagerDataSource dataSource; + final DriverManagerDataSource dataSource; private final DSLContext dsl; private final DataSourceTransactionManager manager; private final TransactionTemplate transaction; @@ -1732,9 +1732,9 @@ private static final class Fixture { private final AccountGameplayAdmissionLeaseRepository leases; private final AccountGameplayTokenIdentityFenceRepository tokenFences; private final AccountGameplayDelegationIssuanceRepository issuance; - private AccountGameplayDelegationCommitSignerFixture signerFixture; - private AccountGameplayDelegationCommittedIssuanceOwner committedIssuanceOwner; - private AccountGameplayDelegationResponseRecoveryOwner responseRecoveryOwner; + AccountGameplayDelegationCommitSignerFixture signerFixture; + AccountGameplayDelegationCommittedIssuanceOwner committedIssuanceOwner; + AccountGameplayDelegationResponseRecoveryOwner responseRecoveryOwner; private final UUID tenantUuid = UUID.randomUUID(); private final UUID joinRequestId = UUID.randomUUID(); private final String callerBinding = "current-source-fixture-" + UUID.randomUUID(); @@ -1743,7 +1743,7 @@ private static final class Fixture { private final CanonicalJoinScopeV2 joinScope; private final Account account; private final IssuerAccountSourceSnapshot issuanceSource; - private final CommittedCandidateVerificationData committedCandidate; + final CommittedCandidateVerificationData committedCandidate; private Fixture( String schema, @@ -2316,7 +2316,7 @@ private static void writeResponseKeyring(Path root) throws Exception { } /** Run-owned local primary/replica used only for the authenticated Account-owner case. */ - private static final class PhysicalRedisFixture implements AutoCloseable { + static final class PhysicalRedisFixture implements AutoCloseable { private static final int REDIS_PORT = 6379; private static final String ACCOUNT_PASSWORD = UUID.randomUUID().toString().replace("-", ""); private static final String PRIMARY_ALIAS = "account-gameplay-admission-primary"; @@ -2359,7 +2359,7 @@ private static final class PhysicalRedisFixture implements AutoCloseable { private LettuceAccountCoordinationPinnedConnectionProvider accountProvider; private AccountGameplayDelegationRedisClient accountClient; - private static PhysicalRedisFixture start() throws InterruptedException { + static PhysicalRedisFixture start() throws InterruptedException { assumeTrue( DockerClientFactory.instance().isDockerAvailable(), "Docker is unavailable; authenticated Account-owner Redis proof is skipped"); @@ -2402,7 +2402,7 @@ private void startOwnedRedis() throws InterruptedException { classLoader); } - private AccountGameplayDelegationRedisClient client() { + AccountGameplayDelegationRedisClient client() { return Objects.requireNonNull(accountClient, "Owned Account Redis client is unavailable"); } @@ -2625,7 +2625,7 @@ private RedisHarness( resourceClassLoader); } - private AccountGameplayDelegationRedisClient client() { + AccountGameplayDelegationRedisClient client() { return client; } } diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index dcd05e7cae..6ba793a6ec 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -169,6 +169,8 @@ val gameSessionClassesProofJar by tasks.registering(Jar::class) { from(sourceSets.main.get().output.classesDirs) from(sourceSets["integrationTest"].output.classesDirs) { include("integration/net/firedevops/firemud/gamesession/repository/CanonicalHumanPublicationOwnerTestFixtures*.class") + include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures*.class") + include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture*.class") } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAdmissionAbortOutcome.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAdmissionAbortOutcome.java new file mode 100644 index 0000000000..19e47b7533 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAdmissionAbortOutcome.java @@ -0,0 +1,73 @@ +package net.firedevops.firemud.gamesession.binding; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; + +/** Result of reconciling the original Account lease during a first-NEW abort attempt. */ +public record CanonicalGameplayAdmissionAbortOutcome( + UUID transitionId, + State state, + UUID orphanCleanupId, + AccountGameplayAdmissionLeaseGrpcCodec.OperationEvidence accountOperation) { + public CanonicalGameplayAdmissionAbortOutcome { + requireNonNil(transitionId, "transitionId"); + Objects.requireNonNull(state, "state"); + if (accountOperation == null) { + if (state != State.ABORTED) { + throw new IllegalArgumentException("Only a retained ABORTED source may omit an RPC result"); + } + requireNonNil(orphanCleanupId, "orphanCleanupId"); + } else { + State accountState = + switch (accountOperation.state()) { + case ABORTED -> State.ABORTED; + case COMMITTED -> State.ACCOUNT_COMMITTED; + case PENDING -> State.PENDING; + }; + if (accountState != state + || accountOperation.originalLeaseEvidence().leaseKind() + != net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence + .LeaseKind.NEW_BINDING) { + throw new IllegalArgumentException("Account result is not the exact NEW abort operation"); + } + if (state == State.ABORTED) { + requireNonNil(orphanCleanupId, "orphanCleanupId"); + if (!transitionId.equals(accountOperation.bindingDecisionId())) { + throw new IllegalArgumentException( + "ABORTED result changed the exact transition identity"); + } + if (!orphanCleanupId.equals(accountOperation.orphanCleanupId()) + || accountOperation.originalAckReceipt() != null) { + throw new IllegalArgumentException( + "ABORTED result differs from Account cleanup evidence"); + } + } else if (state == State.ACCOUNT_COMMITTED) { + if (orphanCleanupId != null + || !transitionId.equals(accountOperation.bindingDecisionId()) + || accountOperation.originalAckReceipt() == null) { + throw new IllegalArgumentException( + "COMMITTED result must retain its exact ACK receipt"); + } + } else if (orphanCleanupId != null + || accountOperation.bindingDecisionId() != null + || accountOperation.orphanCleanupId() != null + || accountOperation.originalAckReceipt() != null) { + throw new IllegalArgumentException("A non-aborted result cannot claim terminal evidence"); + } + } + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(name + " must not be nil"); + } + } + + public enum State { + ABORTED, + ACCOUNT_COMMITTED, + PENDING + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAdmissionAbortSource.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAdmissionAbortSource.java new file mode 100644 index 0000000000..68654d14f2 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAdmissionAbortSource.java @@ -0,0 +1,81 @@ +package net.firedevops.firemud.gamesession.binding; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; + +/** Exact existing first-NEW transition and its original lease, before or after Account abort. */ +public record CanonicalGameplayAdmissionAbortSource( + CanonicalGameplayBindingTransitionSnapshot transition, + CanonicalGameplayBindingInventoryEntry candidate, + CanonicalIssuerPartitionReservation reservation, + CanonicalGameplayAdmissionDecision originalDecision, + UUID orphanCleanupId) { + public CanonicalGameplayAdmissionAbortSource { + Objects.requireNonNull(transition, "transition"); + Objects.requireNonNull(candidate, "candidate"); + Objects.requireNonNull(reservation, "reservation"); + Objects.requireNonNull(originalDecision, "originalDecision"); + if (transition.expectedPriorBindingRef() != null + || transition.expectedPriorBindingGeneration() != null + || originalDecision.leaseKind() != AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING + || originalDecision.expectedOldBindingGeneration() != null + || !transition.transitionId().equals(originalDecision.bindingDecisionId()) + || !transition.transitionId().equals(candidate.transitionId()) + || !transition.transitionId().equals(reservation.transitionId()) + || !transition.bindingRef().equals(candidate.bindingRef()) + || !transition.bindingRef().equals(reservation.owner().bindingRef()) + || !transition.bindingGeneration().equals(candidate.bindingGeneration()) + || !transition.bindingGeneration().equals(reservation.bindingGeneration()) + || !transition.issuerReservationId().equals(reservation.reservationId()) + || !transition.reservationFence().equals(reservation.reservationFence()) + || !transition.candidateAccountIndexFence().equals(candidate.accountIndexFence()) + || !transition.candidate().equals(candidate.identity()) + || !transition.candidate().equals(reservation.owner()) + || !transition.inventoryRevision().equals(candidate.inventoryRevision()) + || !transition.inventoryRevision().equals(reservation.inventoryRevision())) { + throw new IllegalArgumentException("Abort source does not identify one exact first-NEW owner"); + } + + if (transition.status() == CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL) { + if (candidate.lifecycle() + != CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL + || reservation.lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RESERVED + || orphanCleanupId != null) { + throw new IllegalArgumentException("Provisional abort source has terminal storage state"); + } + } else if (transition.status() == CanonicalGameplayBindingTransitionSnapshot.Status.ABORTED) { + requireNonNil(orphanCleanupId, "orphanCleanupId"); + if (candidate.lifecycle() + != CanonicalGameplayBindingInventoryEntry.Lifecycle.TERMINAL_UNRESOLVED + || reservation.lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING) { + throw new IllegalArgumentException("Aborted source is not retained for exact cleanup"); + } + } else { + throw new IllegalArgumentException("Only a provisional or aborted first-NEW source is valid"); + } + + AccountGameplayAdmissionLeaseEvidence lease = originalDecision.leaseEvidence(); + CanonicalPlayableTarget target = originalDecision.targetEvidence(); + if (!candidate.identity().equals(originalDecision.candidate()) + || !transition.bindingGeneration().equals(originalDecision.bindingGeneration()) + || !target.canonicalTenantId().equals(candidate.identity().tenantId()) + || !target.playableStateNamespaceId().equals(candidate.identity().playableStateNamespaceId()) + || lease.leaseKind() != AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING) { + throw new IllegalArgumentException("Original decision differs from its exact first-NEW source"); + } + } + + public boolean isAccountAborted() { + return transition.status() == CanonicalGameplayBindingTransitionSnapshot.Status.ABORTED; + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(name + " must not be nil"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortManualFactory.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortManualFactory.java new file mode 100644 index 0000000000..8f5b106934 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortManualFactory.java @@ -0,0 +1,72 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.TlsServerCredentials; +import java.util.List; +import java.util.Objects; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.TrustManagerFactory; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; +import net.firedevops.firemud.gamesession.client.AccountGameplayAdmissionLeaseClient; +import net.firedevops.firemud.gamesession.security.CanonicalGameplayAdmissionDecisionReadWorkloadGuard; +import net.firedevops.firemud.gamesession.service.impl.CanonicalGameplayAdmissionDecisionReadGrpcService; +import org.jooq.DSLContext; + +/** Explicit unregistered construction paths for the first-NEW abort owner and reverse read. */ +public final class CanonicalGameplayAdmissionAbortManualFactory { + private CanonicalGameplayAdmissionAbortManualFactory() {} + + public static CanonicalGameplayAdmissionAbortOwner createUnregisteredOwner( + DSLContext dsl, AccountGameplayAdmissionLeaseClient accountClient) { + return new CanonicalGameplayAdmissionAbortOwner( + new CanonicalGameplayBindingInventoryRepository( + Objects.requireNonNull(dsl, "Game Session SQL context required")), + Objects.requireNonNull(accountClient, "Account gameplay lease client required")); + } + + public static CanonicalGameplayAdmissionDecisionReadGrpcService + createUnregisteredDecisionReadReceiver(DSLContext dsl, String workloadNamespace) { + var repository = + new CanonicalGameplayBindingInventoryRepository( + Objects.requireNonNull(dsl, "Game Session SQL context required")); + var guard = new CanonicalGameplayAdmissionDecisionReadWorkloadGuard(workloadNamespace); + return new CanonicalGameplayAdmissionDecisionReadGrpcService( + repository, guard, workloadNamespace); + } + + /** Creates an unstarted mutual-TLS server; production registration remains an explicit owner decision. */ + public static Server createUnregisteredDecisionReadServer( + String address, + KeyManagerFactory keys, + TrustManagerFactory trust, + DSLContext dsl, + String workloadNamespace) { + Objects.requireNonNull(address, "gRPC server address required"); + Objects.requireNonNull(keys, "gRPC server key manager required"); + Objects.requireNonNull(trust, "gRPC server trust manager required"); + var guard = new CanonicalGameplayAdmissionDecisionReadWorkloadGuard(workloadNamespace); + var receiver = + new CanonicalGameplayAdmissionDecisionReadGrpcService( + new CanonicalGameplayBindingInventoryRepository( + Objects.requireNonNull(dsl, "Game Session SQL context required")), + guard, + workloadNamespace); + var factory = + new BoundedGrpcServerFactory( + address, + List.of(), + keys, + trust, + TlsServerCredentials.ClientAuth.REQUIRE, + GrpcRequestBytePolicy.ordinary(), + CanonicalGameplayAdmissionDecisionReadGrpcCodec.MAX_REQUEST_WIRE_BYTES); + factory.addService( + ServerInterceptors.interceptForward( + receiver, new GrpcPeerIdentityInterceptor(), guard)); + return factory.createServer(); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwner.java new file mode 100644 index 0000000000..d9377abc8b --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwner.java @@ -0,0 +1,132 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortOutcome; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortOutcome.State; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; +import net.firedevops.firemud.gamesession.client.AccountGameplayAdmissionLeaseClient; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered first-NEW Account abort composer over the retained Game Session transition owner. + * + *

The original transition identifier selects the durable source. Its complete persisted lease + * is sent to Account for the exact purpose-specific abort. The remote call is always outside SQL; + * only a typed definitive Account ABORTED result can enter the guarded Game Session CAS. + */ +public final class CanonicalGameplayAdmissionAbortOwner { + private final CanonicalGameplayBindingInventoryRepository repository; + private final AccountGameplayAdmissionLeaseClient accountClient; + + CanonicalGameplayAdmissionAbortOwner( + CanonicalGameplayBindingInventoryRepository repository, + AccountGameplayAdmissionLeaseClient accountClient) { + this.repository = Objects.requireNonNull(repository, "Game Session abort source required"); + this.accountClient = Objects.requireNonNull(accountClient, "Account lease client required"); + } + + /** + * Resolves only one existing first-NEW transition. A pending Account response leaves its original + * non-admitting obligation intact; a committed response preserves the receipt and does not + * relabel Game Session state. + */ + public CanonicalGameplayAdmissionAbortOutcome abortFirstNew( + UUID transitionId, String presentedInitialGsACompactJwt) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("First-NEW Account abort requires no ambient SQL scope"); + } + Objects.requireNonNull(transitionId, "transitionId"); + if (presentedInitialGsACompactJwt == null || presentedInitialGsACompactJwt.isBlank()) { + throw new IllegalArgumentException("Original initial GSA credential is required"); + } + + CanonicalGameplayAdmissionAbortSource source = + repository.readFirstNewAdmissionAbortSource(transitionId); + AccountGameplayAdmissionLeaseEvidence originalLease = + source.originalDecision().leaseEvidence(); + byte[] originalLeaseBytes = + source.originalDecision().leaseEvidenceJson().getBytes(StandardCharsets.UTF_8); + if (!Arrays.equals( + originalLeaseBytes, + originalLease.canonicalJson().getBytes(StandardCharsets.UTF_8))) { + throw new IllegalStateException("Retained first-NEW lease bytes are not canonical"); + } + + // Account owns definitive abort and performs its own exact Game Session decision read. This + // RPC must finish before the repository opens its guarded transition transaction. + AccountGameplayAdmissionLeaseGrpcCodec.OperationEvidence accountOperation = + accountClient.abort(presentedInitialGsACompactJwt, originalLeaseBytes, transitionId); + requireExactAccountAbort(source, accountOperation, transitionId); + + if (source.isAccountAborted()) { + if (accountOperation.state() != AccountGameplayAdmissionLeaseGrpcCodec.State.ABORTED + || !source.orphanCleanupId().equals(accountOperation.orphanCleanupId())) { + throw new IllegalStateException("Account replay contradicts the retained definitive abort"); + } + return new CanonicalGameplayAdmissionAbortOutcome( + transitionId, State.ABORTED, source.orphanCleanupId(), accountOperation); + } + + if (accountOperation.state() == AccountGameplayAdmissionLeaseGrpcCodec.State.COMMITTED) { + return new CanonicalGameplayAdmissionAbortOutcome( + transitionId, State.ACCOUNT_COMMITTED, null, accountOperation); + } + if (accountOperation.state() == AccountGameplayAdmissionLeaseGrpcCodec.State.PENDING) { + return new CanonicalGameplayAdmissionAbortOutcome( + transitionId, State.PENDING, null, accountOperation); + } + + UUID cleanupId = accountOperation.orphanCleanupId(); + CanonicalGameplayAdmissionAbortSource terminalSource = + repository.recordFirstNewAccountAbort(source, cleanupId); + if (!terminalSource.isAccountAborted() + || !cleanupId.equals(terminalSource.orphanCleanupId())) { + throw new IllegalStateException("Game Session did not retain Account's exact abort result"); + } + return new CanonicalGameplayAdmissionAbortOutcome( + transitionId, State.ABORTED, cleanupId, accountOperation); + } + + private static void requireExactAccountAbort( + CanonicalGameplayAdmissionAbortSource source, + AccountGameplayAdmissionLeaseGrpcCodec.OperationEvidence operation, + UUID transitionId) { + AccountGameplayAdmissionLeaseEvidence originalLease = + source.originalDecision().leaseEvidence(); + if (!originalLease.hasSameIdentity(operation.originalLeaseEvidence()) + || !source.originalDecision().leaseEvidenceJson() + .equals(operation.originalLeaseEvidence().canonicalJson()) + || operation.originalLeaseEvidence().leaseKind() + != AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING) { + throw new IllegalStateException("Account response changed the complete original NEW lease"); + } + if (operation.bindingDecisionId() != null + && !transitionId.equals(operation.bindingDecisionId())) { + throw new IllegalStateException("Account response changed the original transition identity"); + } + if (operation.state() == AccountGameplayAdmissionLeaseGrpcCodec.State.ABORTED + && (operation.bindingDecisionId() == null + || operation.orphanCleanupId() == null + || operation.originalAckReceipt() != null)) { + throw new IllegalStateException("Account ABORTED result lacks exact cleanup evidence"); + } + if (operation.state() == AccountGameplayAdmissionLeaseGrpcCodec.State.COMMITTED + && (operation.bindingDecisionId() == null + || operation.orphanCleanupId() != null + || operation.originalAckReceipt() == null)) { + throw new IllegalStateException("Account COMMITTED result lacks its original ACK receipt"); + } + if (operation.state() == AccountGameplayAdmissionLeaseGrpcCodec.State.PENDING + && (operation.bindingDecisionId() != null + || operation.orphanCleanupId() != null + || operation.originalAckReceipt() != null)) { + throw new IllegalStateException("Account PENDING result carries contradictory terminal data"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index 88f98af39a..2247f14f4d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -15,6 +15,7 @@ import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountMemberAcknowledgement; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountMemberRepairOperation; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingAccountIndexObligation; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingAccountIndexProjectionReceipt; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; @@ -74,6 +75,77 @@ CanonicalGameplayBindingTransitionSnapshot prepare( configuration -> prepareInTransaction(DSL.using(configuration), request)); } + /** + * Prepares and registers one ordinary NEW candidate while the exact installed initial issuer + * anchor remains current. The inventory clock and issuer control are locked before the request + * factory resolves or allocates owner identities; Account remains the next lock. + */ + CanonicalGameplayBindingTransitionSnapshot prepareAfterInstalledIssuerAnchor( + InstalledAnchorPreparationRequestFactory requestFactory, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentIssuerState, + InstalledAnchorPreparationRecorder registrationRecorder) { + Objects.requireNonNull(requestFactory, "requestFactory"); + Objects.requireNonNull(currentIssuerState, "currentIssuerState"); + Objects.requireNonNull(registrationRecorder, "registrationRecorder"); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger revision = lockInventoryRevision(transaction); + CanonicalGameplayIssuerInstalledAnchor actualAnchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction( + transaction, currentIssuerState); + InstalledAnchorPreparationContext context = + new InstalledAnchorPreparationContext(revision, actualAnchor, currentIssuerState); + CanonicalGameplayBindingTransitionRequest request = + Objects.requireNonNull( + requestFactory.create(transaction, actualAnchor, currentIssuerState), + "installed-anchor request factory returned null"); + validateRequest(request); + if (request.expectedPriorBindingRef() != null + || request.expectedPriorBindingGeneration() != null) { + throw conflict("Installed-anchor local issuer operation accepts only ordinary NEW"); + } + requireCandidateMatchesInstalledAnchor(request.candidate(), actualAnchor); + return prepareInTransaction(transaction, request, context, registrationRecorder); + }); + } + + @FunctionalInterface + interface InstalledAnchorPreparationRequestFactory { + /** + * Resolves an exact retry or allocates new owner identities inside the serialized SQL + * transaction. + */ + CanonicalGameplayBindingTransitionRequest create( + DSLContext transaction, + CanonicalGameplayIssuerInstalledAnchor actualAnchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentIssuerState); + } + + @FunctionalInterface + interface InstalledAnchorPreparationRecorder { + /** Called in the same transaction after candidate preparation or exact retry qualification. */ + void record( + DSLContext transaction, + CanonicalGameplayBindingTransitionRequest request, + CanonicalGameplayIssuerInstalledAnchor actualAnchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentIssuerState, + CanonicalGameplayBindingTransitionSnapshot prepared, + boolean exactRetry); + } + + private record InstalledAnchorPreparationContext( + BigInteger inventoryRevision, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentIssuerState) { + private InstalledAnchorPreparationContext { + Objects.requireNonNull(inventoryRevision, "inventoryRevision"); + Objects.requireNonNull(anchor, "anchor"); + Objects.requireNonNull(currentIssuerState, "currentIssuerState"); + } + } + /** * Reads the complete typed inventory and all retained repair obligations from one DB snapshot. */ @@ -205,7 +277,7 @@ CanonicalGameplayBindingProvisionalCasEvidence readProvisionalCasEvidence(UUID t * The supplied Account lease is only an expected value; all returned decision fields are loaded * from durable Game Session rows and the canonical lease carrier is reparsed and digest-checked. */ - CanonicalGameplayAdmissionDecision readAdmissionDecision( + public CanonicalGameplayAdmissionDecision readAdmissionDecision( UUID bindingDecisionId, AccountGameplayAdmissionLeaseEvidence expectedLeaseEvidence) { Objects.requireNonNull(bindingDecisionId, "bindingDecisionId"); Objects.requireNonNull(expectedLeaseEvidence, "expectedLeaseEvidence"); @@ -230,6 +302,205 @@ CanonicalGameplayAdmissionDecision readAdmissionDecision( }); } + /** + * Reads the retained exact first-NEW lease source for the purpose-specific Account abort path. + * The caller supplies only the existing transition identity; every lease and route field comes + * from the immutable Game Session transition row. + */ + CanonicalGameplayAdmissionAbortSource readFirstNewAdmissionAbortSource(UUID transitionId) { + Objects.requireNonNull(transitionId, "transitionId"); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + return loadFirstNewAdmissionAbortSource(transaction, transitionId, false); + }); + } + + /** + * Commits Account's exact definitive first-NEW abort into the existing transition and retained + * candidate/reservation source. The Account RPC is performed by the caller outside this method. + */ + CanonicalGameplayAdmissionAbortSource recordFirstNewAccountAbort( + CanonicalGameplayAdmissionAbortSource expectedSource, UUID orphanCleanupId) { + Objects.requireNonNull(expectedSource, "expectedSource"); + requireNonNil(orphanCleanupId, "orphanCleanupId"); + if (expectedSource.isAccountAborted()) { + if (!orphanCleanupId.equals(expectedSource.orphanCleanupId())) { + throw conflict("Account abort retry changed the durable cleanup identity"); + } + return readFirstNewAdmissionAbortSource(expectedSource.transition().transitionId()); + } + + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger currentRevision = lockInventoryRevision(transaction); + UUID transitionId = expectedSource.transition().transitionId(); + CanonicalGameplayAdmissionAbortSource beforeRuntimeLock = + loadFirstNewAdmissionAbortSource(transaction, transitionId, false); + if (beforeRuntimeLock.isAccountAborted()) { + requireSameFirstNewAdmissionAbortSource(expectedSource, beforeRuntimeLock); + if (!orphanCleanupId.equals(beforeRuntimeLock.orphanCleanupId())) { + throw conflict("Concurrent Account abort changed the durable cleanup identity"); + } + return beforeRuntimeLock; + } + lockLeaseBoundRuntimeBeforeTransition( + transaction, + transitionId, + expectedSource.transition().bindingRef().bytes(), + expectedSource.originalDecision().targetEvidence()); + CanonicalGameplayAdmissionAbortSource current = + loadFirstNewAdmissionAbortSource(transaction, transitionId, true); + requireSameFirstNewAdmissionAbortSource(expectedSource, current); + requireAccountCoverageEvidenceCurrent( + transaction, + current.candidate().identity().accountId(), + current.transition().accountCoverageEvidence()); + + if (current.isAccountAborted()) { + if (!orphanCleanupId.equals(current.orphanCleanupId())) { + throw conflict("Concurrent Account abort changed the durable cleanup identity"); + } + return current; + } + if (current.transition().status() + != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL) { + throw conflict("Only the exact PROVISIONAL first-NEW transition may abort"); + } + + BigInteger priorRevision = current.transition().inventoryRevision(); + BigInteger nextRevision = currentRevision.add(BigInteger.ONE); + int transitionChanged = + transaction.execute( + "UPDATE " + + TRANSITION + + " SET status = 'ABORTED', admission_orphan_cleanup_id = ?," + + " inventory_revision = ?" + + " WHERE transition_id = ? AND status = 'PROVISIONAL'" + + " AND inventory_revision = ? AND candidate_binding_ref = ?" + + " AND candidate_binding_generation = ?" + + " AND candidate_account_index_fence = ? AND issuer_reservation_id = ?" + + " AND expected_prior_binding_ref IS NULL" + + " AND expected_prior_binding_generation IS NULL" + + " AND admission_lease_kind = 'NEW_BINDING'" + + " AND admission_request_id = ? AND admission_lease_id = ?" + + " AND admission_lease_fence = ? AND admission_lease_digest = ?" + + " AND admission_lease_evidence = ?" + + " AND admission_orphan_cleanup_id IS NULL", + orphanCleanupId, + decimal(nextRevision), + transitionId, + decimal(priorRevision), + current.transition().bindingRef().bytes(), + decimal(current.transition().bindingGeneration()), + current.transition().candidateAccountIndexFence(), + current.transition().issuerReservationId(), + current.originalDecision().requestId(), + current.originalDecision().leaseId(), + decimal(current.originalDecision().leaseFence()), + current.originalDecision().leaseSha256(), + current.originalDecision().leaseEvidenceJson()); + requireOne( + transitionChanged, + "Exact first-NEW Account abort lost its immutable transition compare-and-set"); + + int reservationChanged = + transaction.execute( + "UPDATE " + + RESERVATION + + " SET lifecycle = 'RELEASE_PENDING', inventory_revision = ?" + + " WHERE reservation_id = ? AND transition_id = ?" + + " AND lifecycle = 'RESERVED' AND inventory_revision = ?" + + " AND binding_ref = ? AND binding_generation = ?" + + " AND reservation_fence = ? AND account_id = ? AND tenant_id = ?" + + " AND playable_state_namespace_id = ? AND character_id = ?" + + " AND game_instance_id = ? AND runtime_game_instance_id = ?" + + " AND session_id = ? AND region_id = ? AND region_epoch = ?" + + " AND issuer_id = ? AND issuer_auth_generation = ?", + decimal(nextRevision), + current.reservation().reservationId(), + transitionId, + decimal(priorRevision), + current.transition().bindingRef().bytes(), + decimal(current.transition().bindingGeneration()), + current.reservation().reservationFence(), + current.candidate().identity().accountId(), + current.candidate().identity().tenantId(), + current.candidate().identity().playableStateNamespaceId(), + current.candidate().identity().characterId(), + current.candidate().identity().gameInstanceId(), + current.candidate().identity().runtimeGameInstanceId(), + current.candidate().identity().sessionId(), + current.candidate().identity().regionId(), + decimal(current.candidate().identity().regionEpoch()), + current.candidate().identity().issuerId(), + decimal(current.candidate().identity().issuerAuthGeneration())); + requireOne( + reservationChanged, + "Exact first-NEW Account abort lost its retained reservation compare-and-set"); + + int candidateChanged = + transaction.execute( + "UPDATE " + + INVENTORY + + " SET lifecycle = 'TERMINAL_UNRESOLVED', inventory_revision = ?" + + " WHERE binding_ref = ? AND transition_id = ?" + + " AND lifecycle = 'PROVISIONAL' AND inventory_revision = ?" + + " AND binding_generation = ? AND account_index_fence = ?" + + " AND tenant_id = ? AND playable_state_namespace_id = ?" + + " AND character_id = ? AND account_id = ?", + decimal(nextRevision), + current.transition().bindingRef().bytes(), + transitionId, + decimal(priorRevision), + decimal(current.transition().bindingGeneration()), + current.transition().candidateAccountIndexFence(), + current.candidate().identity().tenantId(), + current.candidate().identity().playableStateNamespaceId(), + current.candidate().identity().characterId(), + current.candidate().identity().accountId()); + requireOne( + candidateChanged, + "Exact first-NEW Account abort lost its retained candidate compare-and-set"); + + requireOne( + transaction.execute( + "UPDATE " + + ACCOUNT_OBLIGATION + + " SET inventory_revision = ? WHERE transition_id = ?" + + " AND inventory_revision = ?", + decimal(nextRevision), transitionId, decimal(priorRevision)), + "First-NEW Account abort lost its required account-index obligation"); + requireOne( + transaction.execute( + "UPDATE " + + ISSUER_OBLIGATION + + " SET inventory_revision = ? WHERE transition_id = ?" + + " AND inventory_revision = ?", + decimal(nextRevision), transitionId, decimal(priorRevision)), + "First-NEW Account abort lost its required issuer-index obligation"); + requireOne( + transaction.execute( + "UPDATE " + + REGION_OBLIGATION + + " SET inventory_revision = ? WHERE transition_id = ?" + + " AND inventory_revision = ?", + decimal(nextRevision), transitionId, decimal(priorRevision)), + "First-NEW Account abort lost its required region-bridge obligation"); + requireOne( + transaction.execute( + "UPDATE game_session_canonical_binding_inventory_clock" + + " SET inventory_revision = ? WHERE singleton_id = 1" + + " AND inventory_revision = ?", + decimal(nextRevision), + decimal(currentRevision)), + "First-NEW Account abort lost its inventory revision compare-and-set"); + return loadFirstNewAdmissionAbortSource(transaction, transitionId, false); + }); + } + /** * Persists exact Redis PRESENT readback for the candidate account member without satisfying the * account-index obligation. Account-wide v2 coverage remains a separate required owner result. @@ -1013,8 +1284,15 @@ private static CanonicalGameplayBindingAccountIndexProjectionReceipt projectionR private static CanonicalGameplayAdmissionDecision toAdmissionDecision( Record row, CanonicalGameplayBindingProvisionalCasEvidence operation) { + return toAdmissionDecision(row, operation.transition(), operation.candidate()); + } + + private static CanonicalGameplayAdmissionDecision toAdmissionDecision( + Record row, + CanonicalGameplayBindingTransitionSnapshot transition, + CanonicalGameplayBindingInventoryEntry candidate) { if (row == null - || !operation.transition().transitionId().equals(row.get("transition_id", UUID.class))) { + || !transition.transitionId().equals(row.get("transition_id", UUID.class))) { throw conflict("Durable binding decision row is missing or changed"); } String canonicalEvidence = row.get("admission_lease_evidence", String.class); @@ -1032,11 +1310,11 @@ private static CanonicalGameplayAdmissionDecision toAdmissionDecision( try { decision = new CanonicalGameplayAdmissionDecision( - operation.transition().transitionId(), + transition.transitionId(), lease, - operation.candidate().identity(), - operation.transition().bindingGeneration(), - operation.transition().expectedPriorBindingGeneration(), + candidate.identity(), + transition.bindingGeneration(), + transition.expectedPriorBindingGeneration(), target); } catch (RuntimeException mismatch) { throw conflict( @@ -1271,6 +1549,240 @@ private static CanonicalGameplayBindingProvisionalCasEvidence loadProvisionalCas return evidence; } + private static CanonicalGameplayAdmissionAbortSource loadFirstNewAdmissionAbortSource( + DSLContext transaction, UUID transitionId, boolean forUpdate) { + String lock = forUpdate ? " FOR UPDATE" : ""; + Record transition = + transaction.fetchOne( + "SELECT * FROM " + TRANSITION + " WHERE transition_id = ?" + lock, transitionId); + if (transition == null) { + throw conflict("First-NEW admission abort source does not exist"); + } + byte[] candidateRef = transition.get("candidate_binding_ref", byte[].class); + Record candidateRow = + transaction.fetchOne( + "SELECT * FROM " + INVENTORY + " WHERE binding_ref = ?" + lock, candidateRef); + UUID reservationId = transition.get("issuer_reservation_id", UUID.class); + Record reservationRow = + transaction.fetchOne( + "SELECT * FROM " + RESERVATION + " WHERE reservation_id = ?" + lock, reservationId); + if (candidateRow == null || reservationRow == null) { + throw conflict("First-NEW admission abort source lost its retained candidate or reservation"); + } + + CanonicalGameplayBindingTransitionSnapshot transitionSnapshot = + toTransitionSnapshot(transition, candidateRow, reservationRow); + if (transitionSnapshot.expectedPriorBindingRef() != null + || transitionSnapshot.expectedPriorBindingGeneration() != null) { + throw conflict("Admission abort owner accepts first-NEW transitions only"); + } + if (transitionSnapshot.status() + != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL + && transitionSnapshot.status() + != CanonicalGameplayBindingTransitionSnapshot.Status.ABORTED) { + throw conflict("First-NEW admission abort source is not provisional or definitively aborted"); + } + + CanonicalGameplayBindingInventoryEntry candidate = toInventoryEntry(candidateRow); + CanonicalIssuerPartitionReservation reservation = toReservation(reservationRow); + if (transitionSnapshot.status() + == CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL) { + CanonicalGameplayBindingProvisionalCasEvidence provisional = + loadProvisionalCasEvidence(transaction, transitionId, forUpdate); + transitionSnapshot = provisional.transition(); + candidate = provisional.candidate(); + reservation = provisional.candidateReservation(); + } else { + requireRetainedFirstNewAbortObligations(transaction, transitionId, transitionSnapshot); + } + + AccountGameplayAdmissionLeaseEvidence lease; + try { + String canonicalEvidence = transition.get("admission_lease_evidence", String.class); + if (canonicalEvidence == null) { + throw conflict("First-NEW transition has no original Account lease evidence"); + } + lease = AccountGameplayAdmissionLeaseEvidence.parseCanonical(canonicalEvidence); + } catch (RuntimeException malformed) { + throw conflict("First-NEW transition has invalid original Account lease evidence"); + } + CanonicalGameplayAdmissionDecision originalDecision = + toAdmissionDecision(transition, transitionSnapshot, candidate); + UUID orphanCleanupId = transition.get("admission_orphan_cleanup_id", UUID.class); + CanonicalGameplayAdmissionAbortSource source; + try { + source = + new CanonicalGameplayAdmissionAbortSource( + transitionSnapshot, candidate, reservation, originalDecision, orphanCleanupId); + } catch (RuntimeException invalidSource) { + throw conflict("Retained first-NEW admission abort source is incomplete or inconsistent"); + } + if (lease.leaseKind() != AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING + || !lease.hasSameIdentity(originalDecision.leaseEvidence())) { + throw conflict("First-NEW transition changed its complete Account lease evidence"); + } + + if (forUpdate) { + requireAccountCoverageEvidenceCurrent( + transaction, + candidate.identity().accountId(), + transitionSnapshot.accountCoverageEvidence()); + } else { + requireReadAccountCoverageEvidenceCurrent( + transaction, + candidate.identity().accountId(), + transitionSnapshot.accountCoverageEvidence()); + } + return source; + } + + private static void requireRetainedFirstNewAbortObligations( + DSLContext transaction, + UUID transitionId, + CanonicalGameplayBindingTransitionSnapshot transition) { + BigInteger revision = transition.inventoryRevision(); + byte[] bindingRef = transition.bindingRef().bytes(); + CanonicalGameplayBindingIdentity candidate = transition.candidate(); + Record account = + transaction.fetchOne( + "SELECT * FROM " + + ACCOUNT_OBLIGATION + + " WHERE transition_id = ? AND obligation_ordinal = 0", + transitionId); + Record issuer = + transaction.fetchOne( + "SELECT * FROM " + ISSUER_OBLIGATION + " WHERE transition_id = ? AND binding_ref = ?", + transitionId, + bindingRef); + Record region = + transaction.fetchOne( + "SELECT * FROM " + REGION_OBLIGATION + " WHERE transition_id = ?", + transitionId); + if (account == null + || issuer == null + || region == null + || !"ADD_OR_RETAIN".equals(account.get("action", String.class)) + || !Arrays.equals(bindingRef, account.get("binding_ref", byte[].class)) + || !"BEFORE_FINAL_CAS".equals(account.get("execution_phase", String.class)) + || !"REQUIRED".equals(account.get("status", String.class)) + || !transition.bindingGeneration() + .equals(readBigInteger(account, "binding_generation")) + || nullableBigInteger(account, "expected_prior_generation") != null + || !transition.candidateAccountIndexFence() + .equals(account.get("account_index_fence", UUID.class)) + || !candidate.accountId().equals(account.get("account_id", UUID.class)) + || !candidate.tenantId().equals(account.get("tenant_id", UUID.class)) + || !revision.equals(readBigInteger(account, "inventory_revision")) + || !"REQUIRED".equals(issuer.get("status", String.class)) + || !Arrays.equals(bindingRef, issuer.get("binding_ref", byte[].class)) + || !transition.issuerReservationId().equals(issuer.get("reservation_id", UUID.class)) + || !transition.bindingGeneration() + .equals(readBigInteger(issuer, "binding_generation")) + || !revision.equals(readBigInteger(issuer, "inventory_revision")) + || !"REQUIRED".equals(region.get("status", String.class)) + || !Arrays.equals(bindingRef, region.get("binding_ref", byte[].class)) + || !transition.bindingGeneration().equals(readBigInteger(region, "binding_generation")) + || !candidate.accountId().equals(region.get("account_id", UUID.class)) + || !candidate.tenantId().equals(region.get("tenant_id", UUID.class)) + || !candidate.gameInstanceId().equals(region.get("game_instance_id", UUID.class)) + || !Objects.equals( + candidate.runtimeGameInstanceId(), region.get("runtime_game_instance_id", Long.class)) + || !candidate.sessionId().equals(region.get("session_id", String.class)) + || !candidate.regionId().equals(region.get("region_id", UUID.class)) + || !candidate.regionEpoch().equals(readBigInteger(region, "region_epoch")) + || !revision.equals(readBigInteger(region, "inventory_revision")) + || transaction.fetchCount( + "SELECT transition_id FROM " + + ACCOUNT_OBLIGATION + + " WHERE transition_id = ?", + transitionId) + != 1 + || transaction.fetchCount( + "SELECT transition_id FROM " + + ISSUER_OBLIGATION + + " WHERE transition_id = ?", + transitionId) + != 1) { + throw conflict("Aborted first-NEW source lost a required retained index obligation"); + } + } + + private static void requireSameFirstNewAdmissionAbortSource( + CanonicalGameplayAdmissionAbortSource expected, + CanonicalGameplayAdmissionAbortSource current) { + var expectedTransition = expected.transition(); + var currentTransition = current.transition(); + if (!expectedTransition.transitionId().equals(currentTransition.transitionId()) + || !expectedTransition.candidate().equals(currentTransition.candidate()) + || !expectedTransition.bindingGeneration().equals(currentTransition.bindingGeneration()) + || !expectedTransition.bindingRef().equals(currentTransition.bindingRef()) + || !expectedTransition.issuerReservationId().equals(currentTransition.issuerReservationId()) + || !expectedTransition.reservationFence().equals(currentTransition.reservationFence()) + || !expectedTransition.candidateAccountIndexFence() + .equals(currentTransition.candidateAccountIndexFence()) + || expectedTransition.expectedPriorBindingRef() != null + || expectedTransition.expectedPriorBindingGeneration() != null + || !expectedTransition.accountCoverageEvidence() + .equals(currentTransition.accountCoverageEvidence()) + || !expected.candidate().identity().equals(current.candidate().identity()) + || !expected.candidate().bindingRef().equals(current.candidate().bindingRef()) + || !expected.candidate().accountIndexFence().equals(current.candidate().accountIndexFence()) + || !expected.reservation().reservationId().equals(current.reservation().reservationId()) + || !expected.reservation().reservationFence().equals(current.reservation().reservationFence()) + || !expected.originalDecision().leaseEvidence().hasSameIdentity( + current.originalDecision().leaseEvidence())) { + throw conflict("First-NEW admission abort source drifted before its guarded CAS"); + } + if (expected.isAccountAborted()) { + if (!current.isAccountAborted() + || !Objects.equals(expected.orphanCleanupId(), current.orphanCleanupId()) + || !expected.candidate().equals(current.candidate()) + || !expected.reservation().equals(current.reservation())) { + throw conflict("Retained first-NEW abort source changed during exact retry"); + } + } else if (!current.isAccountAborted()) { + if (!expectedTransition.equals(currentTransition) + || !expected.candidate().equals(current.candidate()) + || !expected.reservation().equals(current.reservation())) { + throw conflict("First-NEW abort source revision or lifecycle drifted before Account abort"); + } + } else if (currentTransition.status() + != CanonicalGameplayBindingTransitionSnapshot.Status.ABORTED + || currentTransition.inventoryRevision() + .compareTo(expectedTransition.inventoryRevision()) <= 0 + || current.candidate().lifecycle() + != CanonicalGameplayBindingInventoryEntry.Lifecycle.TERMINAL_UNRESOLVED + || !current.candidate().inventoryRevision().equals(currentTransition.inventoryRevision()) + || current.reservation().lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING + || !current.reservation().inventoryRevision().equals(currentTransition.inventoryRevision()) + || !expected.candidate().identity().equals(current.candidate().identity()) + || !expected.candidate().bindingRef().equals(current.candidate().bindingRef()) + || !expected.candidate().bindingGeneration().equals(current.candidate().bindingGeneration()) + || !expected.candidate().accountIndexFence().equals(current.candidate().accountIndexFence()) + || !expected.candidate().issuerReservationId() + .equals(current.candidate().issuerReservationId()) + || !expected.candidate().transitionId().equals(current.candidate().transitionId()) + || expected.candidate().accountIndexState() != current.candidate().accountIndexState() + || expected.candidate().issuerIndexState() != current.candidate().issuerIndexState() + || !expected.reservation().reservationId().equals(current.reservation().reservationId()) + || !expected.reservation().owner().equals(current.reservation().owner()) + || !expected.reservation().bindingGeneration().equals(current.reservation().bindingGeneration()) + || !expected.reservation().transitionId().equals(current.reservation().transitionId()) + || !expected.reservation().partitionId().equals(current.reservation().partitionId()) + || !expected.reservation().reservationFence().equals(current.reservation().reservationFence()) + || !expected.reservation().issuerCoverageOperationId() + .equals(current.reservation().issuerCoverageOperationId()) + || !expected.reservation().issuerCoverageOperationFence() + .equals(current.reservation().issuerCoverageOperationFence()) + || !expected.reservation().coverageFence().equals(current.reservation().coverageFence()) + || !expected.reservation().inventorySnapshotRevision() + .equals(current.reservation().inventorySnapshotRevision())) { + throw conflict("Concurrent first-NEW abort did not preserve the exact retained source"); + } + requireSameAdmissionDecision(expected.originalDecision(), current.originalDecision()); + } + private static void requireCompletedMemberRepairAcknowledgement( DSLContext transaction, CanonicalGameplayBindingProvisionalCasEvidence evidence, @@ -1496,9 +2008,31 @@ private static void requireSameProvisionalOperation( private static CanonicalGameplayBindingTransitionSnapshot prepareInTransaction( DSLContext transaction, CanonicalGameplayBindingTransitionRequest request) { - BigInteger revision = lockInventoryRevision(transaction); - boolean pendingIssuerLayoutBootstrapIntent = - validatePendingIssuerLayoutBootstrapIntent(transaction, request.candidate().issuerId()); + return prepareInTransaction(transaction, request, null, null); + } + + private static CanonicalGameplayBindingTransitionSnapshot prepareInTransaction( + DSLContext transaction, + CanonicalGameplayBindingTransitionRequest request, + InstalledAnchorPreparationContext installedAnchorContext, + InstalledAnchorPreparationRecorder registrationRecorder) { + BigInteger revision; + CanonicalGameplayIssuerInstalledAnchor actualAnchor; + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentIssuerState; + boolean pendingIssuerLayoutBootstrapIntent; + if (installedAnchorContext == null) { + revision = lockInventoryRevision(transaction); + actualAnchor = null; + currentIssuerState = null; + pendingIssuerLayoutBootstrapIntent = + validatePendingIssuerLayoutBootstrapIntent(transaction, request.candidate().issuerId()); + } else { + revision = installedAnchorContext.inventoryRevision(); + actualAnchor = installedAnchorContext.anchor(); + currentIssuerState = installedAnchorContext.currentIssuerState(); + requireCandidateMatchesInstalledAnchor(request.candidate(), actualAnchor); + pendingIssuerLayoutBootstrapIntent = false; + } CanonicalGameplayAccountCoverageEvidence accountCoverageEvidence = lockAccountCoverageEvidence(transaction, request.candidate().accountId()); boolean initialBinding = request.expectedPriorBindingRef() == null; @@ -1512,6 +2046,15 @@ private static CanonicalGameplayBindingTransitionSnapshot prepareInTransaction( if (!retry.accountCoverageEvidence().equals(accountCoverageEvidence)) { throw conflict("Same transition retry carries stale account-wide coverage evidence"); } + if (registrationRecorder != null) { + registrationRecorder.record( + transaction, + request, + Objects.requireNonNull(actualAnchor), + currentIssuerState, + retry, + true); + } return retry; } if (pendingIssuerLayoutBootstrapIntent) { @@ -1548,6 +2091,10 @@ private static CanonicalGameplayBindingTransitionSnapshot prepareInTransaction( throw conflict("An unresolved candidate or repair obligation already fences this controller"); } + if (actualAnchor != null) { + requireIssuerCapacityAvailable(transaction, request.candidate(), actualAnchor); + } + ensureGenerationRow(transaction, candidate); Record generationRow = Objects.requireNonNull( @@ -1612,9 +2159,74 @@ private static CanonicalGameplayBindingTransitionSnapshot prepareInTransaction( decimal(nextRevision), decimal(revision)); requireOne(revisionUpdated, "durable inventory revision compare-and-set lost its locked row"); + if (registrationRecorder != null) { + registrationRecorder.record( + transaction, + request, + Objects.requireNonNull(actualAnchor), + currentIssuerState, + prepared, + false); + } return prepared; } + private static void requireCandidateMatchesInstalledAnchor( + CanonicalGameplayBindingIdentity candidate, CanonicalGameplayIssuerInstalledAnchor anchor) { + if (!candidate.issuerId().equals(anchor.issuerId()) + || !candidate.issuerAuthGeneration().equals(anchor.issuerAuthGeneration()) + || !candidate.issuerIndexLayoutVersion().equals(anchor.layoutVersion()) + || !candidate.issuerIndexPartitionCount().equals(anchor.partitionCount()) + || !candidate.issuerIndexPartitionCapacity().equals(anchor.partitionCapacity())) { + throw conflict( + "Candidate issuer, Account source, or layout differs from the installed anchor"); + } + } + + /** + * Counts the current V29 owner rows under the inventory-clock lock. The initial immutable anchor + * is a baseline; every post-baseline candidate is represented by this same inventory, never by a + * parallel local-operation inventory. + */ + private static void requireIssuerCapacityAvailable( + DSLContext transaction, + CanonicalGameplayBindingIdentity candidate, + CanonicalGameplayIssuerInstalledAnchor anchor) { + BigInteger candidatePartition = candidate.bindingRef().partitionId(anchor.partitionCount()); + BigInteger aggregate = BigInteger.ZERO; + BigInteger partition = BigInteger.ZERO; + List reservations = + transaction.fetch( + "SELECT issuer_index_layout_version, issuer_index_partition_count," + + " issuer_index_partition_capacity, partition_id, lifecycle FROM " + + RESERVATION + + " WHERE issuer_id = ? AND lifecycle <> 'RELEASED' ORDER BY reservation_id FOR UPDATE", + candidate.issuerId()); + for (Record reservation : reservations) { + BigInteger layoutVersion = readBigInteger(reservation, "issuer_index_layout_version"); + BigInteger partitionCount = readBigInteger(reservation, "issuer_index_partition_count"); + BigInteger partitionCapacity = readBigInteger(reservation, "issuer_index_partition_capacity"); + BigInteger partitionId = readBigInteger(reservation, "partition_id"); + if (!layoutVersion.equals(anchor.layoutVersion()) + || !partitionCount.equals(anchor.partitionCount()) + || !partitionCapacity.equals(anchor.partitionCapacity()) + || partitionId.signum() < 0 + || partitionId.compareTo(anchor.partitionCount()) >= 0) { + throw conflict( + "Current issuer inventory contains a reservation outside the installed layout"); + } + aggregate = aggregate.add(BigInteger.ONE); + if (partitionId.equals(candidatePartition)) partition = partition.add(BigInteger.ONE); + } + BigInteger nextPartition = partition.add(BigInteger.ONE); + BigInteger nextAggregate = aggregate.add(BigInteger.ONE); + BigInteger aggregateBound = anchor.partitionCount().multiply(anchor.partitionCapacity()); + if (nextPartition.compareTo(anchor.partitionCapacity()) > 0 + || nextAggregate.compareTo(aggregateBound) > 0) { + throw conflict("Installed issuer partition or aggregate reservation capacity is full"); + } + } + private static boolean validatePendingIssuerLayoutBootstrapIntent( DSLContext transaction, String issuerId) { Record control = @@ -3145,6 +3757,13 @@ private static void requireOne(int changed, String message) { } } + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must not be nil"); + } + } + private static void requireCount(int changed, int expected, String message) { if (changed != expected) { throw conflict(message); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperation.java new file mode 100644 index 0000000000..87b759fd4c --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperation.java @@ -0,0 +1,232 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; + +/** + * Immutable SQL-issued preparation for one ordinary NEW issuer member after the initial installed + * anchor. This operation remains pending physical proof and is not an issuer-wide acknowledgement + * or admission capability. + */ +final class CanonicalGameplayIssuerBindingLocalOperation { + enum Status { + PENDING_PHYSICAL_PROOF + } + + /** Caller correlation and expected candidate identity; it carries no reservation authority. */ + record Request( + UUID requestId, + UUID transitionId, + CanonicalGameplayBindingIdentity candidate, + CanonicalGameplayBindingRef expectedPriorBindingRef, + BigInteger expectedPriorBindingGeneration) { + Request { + requireNonNil(requestId, "requestId"); + requireNonNil(transitionId, "transitionId"); + if (requestId.equals(transitionId)) { + throw new IllegalArgumentException("requestId and transitionId must be distinct"); + } + Objects.requireNonNull(candidate, "candidate"); + if ((expectedPriorBindingRef == null) != (expectedPriorBindingGeneration == null)) { + throw new IllegalArgumentException( + "Expected prior reference and generation must be paired"); + } + if (expectedPriorBindingGeneration != null && expectedPriorBindingGeneration.signum() <= 0) { + throw new IllegalArgumentException("Expected prior generation must be positive"); + } + } + } + + private final Request request; + private final UUID candidateAccountIndexFence; + private final CanonicalGameplayBindingTransitionSnapshot preparedTransition; + private final BigInteger localInventorySnapshotRevision; + private final CanonicalIssuerPartitionReservation reservation; + private final CanonicalGameplayIssuerInstalledAnchor anchor; + private final CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof + baselinePartitionProof; + private final CanonicalGameplayIssuerMemberV2Value memberValue; + private final UUID operationId; + private final BigInteger operationFence; + private final BigInteger localMemberGeneration; + private final byte[] exactMemberValueBytes; + private final String memberValueDigest; + private final Status status; + + CanonicalGameplayIssuerBindingLocalOperation( + Request request, + UUID candidateAccountIndexFence, + CanonicalGameplayBindingTransitionSnapshot preparedTransition, + BigInteger localInventorySnapshotRevision, + CanonicalIssuerPartitionReservation reservation, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof + baselinePartitionProof, + CanonicalGameplayIssuerMemberV2Value memberValue, + UUID operationId, + BigInteger operationFence, + BigInteger localMemberGeneration, + byte[] exactMemberValueBytes, + String memberValueDigest, + Status status) { + this.request = Objects.requireNonNull(request, "request"); + this.candidateAccountIndexFence = + requireNonNil(candidateAccountIndexFence, "candidateAccountIndexFence"); + this.preparedTransition = Objects.requireNonNull(preparedTransition, "preparedTransition"); + this.localInventorySnapshotRevision = + requirePositive(localInventorySnapshotRevision, "localInventorySnapshotRevision"); + this.reservation = Objects.requireNonNull(reservation, "reservation"); + this.anchor = Objects.requireNonNull(anchor, "anchor"); + this.baselinePartitionProof = + Objects.requireNonNull(baselinePartitionProof, "baselinePartitionProof"); + this.memberValue = Objects.requireNonNull(memberValue, "memberValue"); + this.operationId = requireNonNil(operationId, "operationId"); + this.operationFence = requirePositive(operationFence, "operationFence"); + this.localMemberGeneration = requirePositive(localMemberGeneration, "localMemberGeneration"); + this.exactMemberValueBytes = + Objects.requireNonNull(exactMemberValueBytes, "exactMemberValueBytes").clone(); + if (this.exactMemberValueBytes.length == 0 + || this.exactMemberValueBytes.length + > CanonicalGameplayIssuerMemberV2Codec.MAX_VALUE_BYTES) { + throw new IllegalArgumentException("Exact local member bytes are outside their bound"); + } + this.memberValueDigest = requireDigest(memberValueDigest, "memberValueDigest"); + this.status = Objects.requireNonNull(status, "status"); + + if (request.expectedPriorBindingRef() != null + || request.expectedPriorBindingGeneration() != null + || !preparedTransition.transitionId().equals(request.transitionId()) + || !preparedTransition.candidate().equals(request.candidate()) + || !preparedTransition.bindingRef().equals(request.candidate().bindingRef()) + || !reservation.owner().equals(request.candidate()) + || !reservation.transitionId().equals(request.transitionId()) + || !reservation.inventoryRevision().equals(localInventorySnapshotRevision) + || !reservation.bindingGeneration().equals(preparedTransition.bindingGeneration()) + || !reservation.reservationId().equals(preparedTransition.issuerReservationId()) + || !anchor.issuerId().equals(request.candidate().issuerId()) + || !anchor.layoutVersion().equals(request.candidate().issuerIndexLayoutVersion()) + || !anchor.partitionCount().equals(request.candidate().issuerIndexPartitionCount()) + || !anchor.partitionCapacity().equals(request.candidate().issuerIndexPartitionCapacity()) + || !baselinePartitionProof + .partitionId() + .equals(request.candidate().bindingRef().partitionId(anchor.partitionCount())) + || !operationId.equals(memberValue.memberOperation().operationId()) + || !operationFence.equals(memberValue.memberOperation().operationFence()) + || !localMemberGeneration.equals(memberValue.memberOperation().coverageGeneration()) + || !memberValue.owner().equals(request.candidate()) + || !memberValue.bindingGeneration().equals(preparedTransition.bindingGeneration()) + || !memberValue.reservation().equals(reservation) + || !memberValue + .anchor() + .issuerCoverageOperationId() + .equals(anchor.issuerCoverageOperationId()) + || !memberValue.anchor().operationFence().equals(anchor.operationFence()) + || !memberValue.anchor().coverageFence().equals(anchor.coverageFence()) + || !memberValue + .anchor() + .issuerInventorySnapshotRevision() + .equals(anchor.issuerInventorySnapshotRevision()) + || !Arrays.equals( + this.exactMemberValueBytes, CanonicalGameplayIssuerMemberV2Codec.encode(memberValue)) + || !memberValueDigest.equals( + CanonicalGameplayIssuerMemberV2Codec.sha256(this.exactMemberValueBytes)) + || !memberValue.equals( + CanonicalGameplayIssuerMemberV2Codec.decode(this.exactMemberValueBytes)) + || status != Status.PENDING_PHYSICAL_PROOF) { + throw new IllegalArgumentException( + "Local issuer operation differs from its exact prepared NEW tuple"); + } + } + + Request request() { + return request; + } + + UUID candidateAccountIndexFence() { + return candidateAccountIndexFence; + } + + CanonicalGameplayBindingTransitionSnapshot preparedTransition() { + return preparedTransition; + } + + BigInteger localInventorySnapshotRevision() { + return localInventorySnapshotRevision; + } + + CanonicalIssuerPartitionReservation reservation() { + return reservation; + } + + CanonicalGameplayIssuerInstalledAnchor anchor() { + return anchor; + } + + CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof + baselinePartitionProof() { + return baselinePartitionProof; + } + + CanonicalGameplayIssuerMemberV2Value memberValue() { + return memberValue; + } + + UUID operationId() { + return operationId; + } + + BigInteger operationFence() { + return operationFence; + } + + BigInteger localMemberGeneration() { + return localMemberGeneration; + } + + byte[] exactMemberValueBytes() { + return exactMemberValueBytes.clone(); + } + + String memberValueDigest() { + return memberValueDigest; + } + + Status status() { + return status; + } + + /** The exact binding and capacity fields are absent before this pending operation is applied. */ + String expectedOldMemberState() { + return "ABSENT"; + } + + String expectedOldCapacityState() { + return "ABSENT"; + } + + private static UUID requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException(name + " must not be nil"); + return value; + } + + private static BigInteger requirePositive(BigInteger value, String name) { + Objects.requireNonNull(value, name); + if (value.signum() <= 0) throw new IllegalArgumentException(name + " must be positive"); + return value; + } + + private static String requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!value.matches("sha256:[0-9a-f]{64}")) + throw new IllegalArgumentException(name + " must be canonical SHA-256"); + return value; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java new file mode 100644 index 0000000000..cd32f610be --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java @@ -0,0 +1,1118 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountCoverageEvidence; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** SQL owner for an ordinary NEW issuer registration linked to the actual installed anchor. */ +final class CanonicalGameplayIssuerBindingLocalOperationRepository { + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String OPERATION = "game_session_canonical_issuer_binding_local_operation"; + private static final String RESERVATION = "game_session_canonical_issuer_partition_reservation"; + private static final String ACCOUNT_CONTROL = "game_session_canonical_account_coverage_control"; + private static final String MEMBER_COUNTER = + "game_session_canonical_issuer_bootstrap_member_op_counter"; + private static final String BOOTSTRAP_MEMBER_OPERATION = + "game_session_canonical_issuer_bootstrap_member_operation"; + + private final DSLContext dsl; + private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentIssuerStateSource; + + CanonicalGameplayIssuerBindingLocalOperationRepository( + DSLContext dsl, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentIssuerStateSource) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.currentIssuerStateSource = + Objects.requireNonNull(currentIssuerStateSource, "currentIssuerStateSource"); + } + + /** + * Begins or exactly replays one caller-correlated ordinary NEW request. The current Account + * checkpoint and stable incarnation are explicit controlled collaborators; SQL still owns the + * installed anchor, inventory/reservation, local operation identity and exact v2 bytes. + */ + CanonicalGameplayIssuerBindingLocalOperation beginOrResumeOrdinaryNew( + CanonicalGameplayIssuerBindingLocalOperation.Request request) { + Objects.requireNonNull(request, "request"); + requireNoAmbientTransaction(); + if (request.expectedPriorBindingRef() != null + || request.expectedPriorBindingGeneration() != null) { + throw conflict("Local issuer registration is restricted to ordinary NEW"); + } + + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState = + Objects.requireNonNull( + currentIssuerStateSource.readFreshCurrentState(), + "current issuer state source returned null"); + AtomicReference result = new AtomicReference<>(); + new CanonicalGameplayBindingInventoryRepository(dsl) + .prepareAfterInstalledIssuerAnchor( + (transaction, actualAnchor, ignoredCurrentState) -> + resolveTransitionRequestInTransaction(transaction, request, actualAnchor), + currentState, + (transaction, exactRequest, actualAnchor, state, prepared, exactRetry) -> + result.set( + recordOrReplayInTransaction( + request, + transaction, + exactRequest, + actualAnchor, + state, + prepared, + exactRetry))); + if (result.get() == null) { + throw conflict("Local issuer registration did not produce a durable operation"); + } + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState postReadState; + try { + postReadState = + Objects.requireNonNull( + currentIssuerStateSource.readFreshCurrentState(), + "current issuer state source returned null after local registration"); + } catch (RuntimeException sourceFailure) { + throw new IllegalStateException( + "Could not requalify issuer source after SQL registration; the pending local operation remains durable", + sourceFailure); + } + if (!sameCurrentIssuerState(currentState, postReadState)) { + throw conflict( + "Issuer source or incarnation moved during SQL registration; the pending local operation remains durable"); + } + return result.get(); + } + + private CanonicalGameplayBindingTransitionRequest resolveTransitionRequestInTransaction( + DSLContext transaction, + CanonicalGameplayIssuerBindingLocalOperation.Request request, + CanonicalGameplayIssuerInstalledAnchor anchor) { + requireCandidateMatchesAnchor(request.candidate(), anchor); + Record priorByTransition = + transaction.fetchOne( + "SELECT * FROM " + OPERATION + " WHERE issuer_id = ? AND transition_id = ?", + ISSUER, + request.transitionId()); + Record priorByRequest = + transaction.fetchOne( + "SELECT * FROM " + OPERATION + " WHERE issuer_id = ? AND request_id = ?", + ISSUER, + request.requestId()); + if ((priorByTransition == null) != (priorByRequest == null) + || (priorByTransition != null + && !requireUuid(priorByTransition, "operation_id") + .equals(requireUuid(priorByRequest, "operation_id")))) { + throw conflict( + "Request and transition identities refer to different local issuer operations"); + } + + UUID accountIndexFence; + CanonicalIssuerReservationFenceEvidence reservationEvidence; + if (priorByTransition == null) { + accountIndexFence = freshNonNilUuid(); + reservationEvidence = + new CanonicalIssuerReservationFenceEvidence( + freshNonNilUuid(), + freshNonNilUuid(), + anchor.issuerCoverageOperationId(), + anchor.operationFence(), + anchor.coverageFence(), + anchor.issuerInventorySnapshotRevision()); + } else { + requireCallerRequestMatches(priorByTransition, request); + accountIndexFence = requireUuid(priorByTransition, "candidate_account_index_fence"); + reservationEvidence = readOriginalReservationEvidence(priorByTransition); + } + + return new CanonicalGameplayBindingTransitionRequest( + request.transitionId(), + accountIndexFence, + request.candidate(), + reservationEvidence, + null, + null); + } + + private CanonicalGameplayIssuerBindingLocalOperation recordOrReplayInTransaction( + CanonicalGameplayIssuerBindingLocalOperation.Request request, + DSLContext transaction, + CanonicalGameplayBindingTransitionRequest transitionRequest, + CanonicalGameplayIssuerInstalledAnchor actualAnchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState, + CanonicalGameplayBindingTransitionSnapshot prepared, + boolean exactRetry) { + Record operationRow = + transaction.fetchOne( + "SELECT * FROM " + OPERATION + " WHERE issuer_id = ? AND transition_id = ? FOR UPDATE", + ISSUER, + transitionRequest.transitionId()); + if (exactRetry) { + if (operationRow == null) { + throw conflict("Prepared NEW transition has no matching local issuer registration"); + } + requireCallerRequestMatches(operationRow, request); + CanonicalIssuerPartitionReservation reservation = + readAndRequireReservation(transaction, transitionRequest, prepared, operationRow); + var proof = + CanonicalGameplayIssuerBootstrapCoverageRepository.readInstalledAnchorPartitionProof( + transaction, actualAnchor, reservation.partitionId()); + CanonicalGameplayIssuerBootstrapCoverageRepository.requireNewMemberAbsentFromBaseline( + proof, prepared.bindingRef(), reservation.reservationId()); + AccountControlSnapshot accountControl = + readAndRequireAccountControl( + transaction, + transitionRequest.candidate().accountId(), + prepared.accountCoverageEvidence()); + return returnOperation( + request, + prepared, + reservation, + actualAnchor, + proof, + currentState, + accountControl, + operationRow); + } + if (operationRow != null) { + throw conflict("A local issuer operation already exists for a newly prepared transition"); + } + if (operationRequestExists(transaction, transitionRequest.transitionId())) { + throw conflict("A different request already owns this local issuer transition"); + } + + CanonicalIssuerPartitionReservation reservation = + readAndRequireReservation(transaction, transitionRequest, prepared, null); + var proof = + CanonicalGameplayIssuerBootstrapCoverageRepository.readInstalledAnchorPartitionProof( + transaction, actualAnchor, reservation.partitionId()); + CanonicalGameplayIssuerBootstrapCoverageRepository.requireNewMemberAbsentFromBaseline( + proof, prepared.bindingRef(), reservation.reservationId()); + AccountControlSnapshot accountControl = + readAndRequireAccountControl( + transaction, + transitionRequest.candidate().accountId(), + prepared.accountCoverageEvidence()); + + IssuedCounters counters = allocateLocalCounters(transaction, actualAnchor, reservation); + UUID operationId = freshOperationId(request, reservation, actualAnchor); + CanonicalGameplayIssuerMemberV2Value memberValue = + createMemberValue( + request.candidate(), + prepared.bindingGeneration(), + reservation, + actualAnchor, + currentState.incarnation(), + operationId, + counters.operationFence(), + counters.localMemberGeneration()); + byte[] valueBytes = CanonicalGameplayIssuerMemberV2Codec.encode(memberValue); + String valueDigest = CanonicalGameplayIssuerMemberV2Codec.sha256(valueBytes); + insertOperation( + transaction, + request, + transitionRequest, + prepared, + reservation, + actualAnchor, + proof, + accountControl, + operationId, + counters, + valueBytes, + valueDigest); + Record saved = + transaction.fetchOne( + "SELECT * FROM " + OPERATION + " WHERE issuer_id = ? AND transition_id = ? FOR UPDATE", + ISSUER, + transitionRequest.transitionId()); + if (saved == null) throw conflict("Local issuer operation is unreadable after persistence"); + return returnOperation( + request, prepared, reservation, actualAnchor, proof, currentState, accountControl, saved); + } + + private CanonicalGameplayIssuerBindingLocalOperation returnOperation( + CanonicalGameplayIssuerBindingLocalOperation.Request request, + CanonicalGameplayBindingTransitionSnapshot prepared, + CanonicalIssuerPartitionReservation reservation, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof proof, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState, + AccountControlSnapshot accountControl, + Record row) { + requireSameStoredOperation( + row, request, prepared, reservation, anchor, proof, currentState, accountControl); + UUID operationId = requireUuid(row, "operation_id"); + BigInteger operationFence = readPositive(row, "operation_fence"); + BigInteger localMemberGeneration = readPositive(row, "local_member_generation"); + byte[] bytes = requireBytes(row, "member_value_bytes"); + String digest = requireText(row, "member_value_digest"); + CanonicalGameplayIssuerMemberV2Value value; + try { + value = CanonicalGameplayIssuerMemberV2Codec.decode(bytes); + } catch (RuntimeException malformed) { + throw conflict("Stored local issuer value is not canonical schema v2"); + } + CanonicalGameplayIssuerMemberV2Value expected = + createMemberValue( + request.candidate(), + prepared.bindingGeneration(), + reservation, + anchor, + currentState.incarnation(), + operationId, + operationFence, + localMemberGeneration); + if (!expected.equals(value) + || !Arrays.equals(bytes, CanonicalGameplayIssuerMemberV2Codec.encode(expected)) + || !digest.equals(CanonicalGameplayIssuerMemberV2Codec.sha256(bytes))) { + throw conflict( + "Stored local issuer operation differs from its exact anchor, source, or reservation"); + } + try { + return new CanonicalGameplayIssuerBindingLocalOperation( + request, + requireUuid(row, "candidate_account_index_fence"), + prepared, + readPositive(row, "local_inventory_snapshot_revision"), + reservation, + anchor, + proof, + expected, + operationId, + operationFence, + localMemberGeneration, + bytes, + digest, + CanonicalGameplayIssuerBindingLocalOperation.Status.valueOf( + requireText(row, "member_status"))); + } catch (RuntimeException malformed) { + throw conflict("Stored local issuer operation metadata is malformed"); + } + } + + private static CanonicalGameplayIssuerMemberV2Value createMemberValue( + CanonicalGameplayBindingIdentity candidate, + BigInteger bindingGeneration, + CanonicalIssuerPartitionReservation reservation, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation, + UUID operationId, + BigInteger operationFence, + BigInteger localMemberGeneration) { + var layout = + new CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor( + anchor.issuerId(), + anchor.layoutVersion(), + anchor.partitionCount(), + anchor.partitionCapacity(), + anchor.mappingIdentity(), + anchor.layoutDescriptorBytes(), + anchor.layoutDescriptorDigest()); + var source = + new CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint( + anchor.issuerId(), + anchor.issuerAuthGeneration(), + anchor.sourceCheckpointBytes(), + anchor.sourceCheckpointDigest(), + anchor.sourceEventBytes(), + anchor.sourceEventDigest()); + return new CanonicalGameplayIssuerMemberV2Value( + candidate, + bindingGeneration, + reservation, + new CanonicalGameplayIssuerMemberV2Value.Anchor( + anchor.issuerCoverageOperationId(), + anchor.operationFence(), + anchor.coverageFence(), + anchor.issuerInventorySnapshotRevision()), + new CanonicalGameplayIssuerMemberV2Value.LocalMemberOperation( + operationId, operationFence, localMemberGeneration), + anchor.controlEpoch(), + layout, + source, + incarnation); + } + + private static CanonicalIssuerPartitionReservation readAndRequireReservation( + DSLContext transaction, + CanonicalGameplayBindingTransitionRequest request, + CanonicalGameplayBindingTransitionSnapshot prepared, + Record operationRow) { + Record row = + transaction.fetchOne( + "SELECT * FROM " + RESERVATION + " WHERE reservation_id = ? FOR UPDATE", + prepared.issuerReservationId()); + if (row == null) throw conflict("Prepared ordinary NEW reservation is missing"); + CanonicalIssuerPartitionReservation reservation; + try { + if (operationRow == null) { + reservation = + new CanonicalIssuerPartitionReservation( + requireUuid(row, "reservation_id"), + requireIdentityMatchesReservation(request.candidate(), row), + readPositive(row, "binding_generation"), + requireUuid(row, "transition_id"), + readNonNegative(row, "partition_id"), + CanonicalIssuerPartitionReservation.Lifecycle.valueOf( + requireText(row, "lifecycle")), + requireUuid(row, "reservation_fence"), + requireUuid(row, "issuer_coverage_operation_id"), + readPositive(row, "issuer_coverage_operation_fence"), + readPositive(row, "coverage_fence"), + readPositive(row, "inventory_snapshot_revision"), + readPositive(row, "inventory_revision")); + } else { + CanonicalGameplayIssuerMemberV2Value stored = + CanonicalGameplayIssuerMemberV2Codec.decode( + requireBytes(operationRow, "member_value_bytes")); + reservation = stored.reservation(); + requireIdentityMatchesReservation(request.candidate(), row); + if (!reservation.reservationId().equals(requireUuid(row, "reservation_id")) + || !reservation.transitionId().equals(requireUuid(row, "transition_id")) + || !reservation.bindingGeneration().equals(readPositive(row, "binding_generation")) + || !reservation.partitionId().equals(readNonNegative(row, "partition_id")) + || !reservation.lifecycle().name().equals(requireText(row, "lifecycle")) + || !reservation.reservationFence().equals(requireUuid(row, "reservation_fence")) + || !reservation + .issuerCoverageOperationId() + .equals(requireUuid(row, "issuer_coverage_operation_id")) + || !reservation + .issuerCoverageOperationFence() + .equals(readPositive(row, "issuer_coverage_operation_fence")) + || !reservation.coverageFence().equals(readPositive(row, "coverage_fence")) + || !reservation + .inventorySnapshotRevision() + .equals(readPositive(row, "inventory_snapshot_revision")) + || !reservation.inventoryRevision().equals(readPositive(row, "inventory_revision"))) { + throw conflict( + "Current reservation no longer matches its immutable local operation source"); + } + } + } catch (IllegalStateException conflict) { + throw conflict; + } catch (RuntimeException malformed) { + throw conflict("Prepared ordinary NEW reservation is malformed"); + } + if (!reservation.reservationId().equals(prepared.issuerReservationId()) + || !reservation.transitionId().equals(request.transitionId()) + || !reservation.bindingGeneration().equals(prepared.bindingGeneration()) + || !reservation.reservationFence().equals(prepared.reservationFence()) + || !reservation.owner().equals(request.candidate()) + || !reservation + .issuerCoverageOperationId() + .equals(request.issuerReservation().issuerCoverageOperationId()) + || !reservation + .issuerCoverageOperationFence() + .equals(request.issuerReservation().issuerCoverageOperationFence()) + || !reservation.coverageFence().equals(request.issuerReservation().coverageFence()) + || !reservation + .inventorySnapshotRevision() + .equals(request.issuerReservation().inventorySnapshotRevision()) + || (operationRow != null + && (!reservation.reservationId().equals(requireUuid(operationRow, "reservation_id")) + || !reservation + .reservationFence() + .equals(requireUuid(operationRow, "reservation_fence")) + || !reservation + .issuerCoverageOperationId() + .equals(requireUuid(operationRow, "original_issuer_coverage_operation_id")) + || !reservation + .issuerCoverageOperationFence() + .equals(readPositive(operationRow, "original_issuer_coverage_operation_fence")) + || !reservation + .coverageFence() + .equals(readPositive(operationRow, "original_coverage_fence")) + || !reservation + .inventorySnapshotRevision() + .equals(readPositive(operationRow, "original_inventory_snapshot_revision"))))) { + throw conflict("Persisted reservation differs from its exact original local request"); + } + return reservation; + } + + private static CanonicalGameplayBindingIdentity requireIdentityMatchesReservation( + CanonicalGameplayBindingIdentity expected, Record row) { + if (!expected.accountId().equals(row.get("account_id", UUID.class)) + || !expected.tenantId().equals(row.get("tenant_id", UUID.class)) + || !expected.gameInstanceId().equals(row.get("game_instance_id", UUID.class)) + || expected.runtimeGameInstanceId() + != Objects.requireNonNull(row.get("runtime_game_instance_id", Long.class)) + || !expected.sessionId().equals(row.get("session_id", String.class)) + || !expected.issuerId().equals(row.get("issuer_id", String.class)) + || !expected.issuerAuthGeneration().equals(readPositive(row, "issuer_auth_generation")) + || !expected + .playableStateNamespaceId() + .equals(row.get("playable_state_namespace_id", UUID.class)) + || !expected.characterId().equals(row.get("character_id", UUID.class)) + || !expected.playableStateScope().equals(row.get("playable_state_scope", String.class)) + || !expected.regionId().equals(row.get("region_id", UUID.class)) + || !expected.regionEpoch().equals(readPositive(row, "region_epoch")) + || !expected + .issuerIndexLayoutVersion() + .equals(readPositive(row, "issuer_index_layout_version")) + || !expected + .issuerIndexPartitionCount() + .equals(readPositive(row, "issuer_index_partition_count")) + || !expected + .issuerIndexPartitionCapacity() + .equals(readPositive(row, "issuer_index_partition_capacity")) + || !Arrays.equals(expected.bindingRef().bytes(), requireBytes(row, "binding_ref"))) { + throw conflict( + "Persisted issuer reservation owner differs from the exact candidate identity"); + } + return expected; + } + + private static AccountControlSnapshot readAndRequireAccountControl( + DSLContext transaction, + UUID accountId, + CanonicalGameplayAccountCoverageEvidence expectedEvidence) { + Record row = + transaction.fetchOne( + "SELECT * FROM " + ACCOUNT_CONTROL + " WHERE account_id = ?", accountId); + if (row == null) throw conflict("Current Account coverage control row is missing"); + AccountControlSnapshot current = AccountControlSnapshot.from(row, accountId); + if (!current.evidence().equals(expectedEvidence)) { + throw conflict("Current Account coverage control changed during ordinary NEW preparation"); + } + return current; + } + + private static void insertOperation( + DSLContext transaction, + CanonicalGameplayIssuerBindingLocalOperation.Request request, + CanonicalGameplayBindingTransitionRequest transitionRequest, + CanonicalGameplayBindingTransitionSnapshot prepared, + CanonicalIssuerPartitionReservation reservation, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof proof, + AccountControlSnapshot account, + UUID operationId, + IssuedCounters counters, + byte[] valueBytes, + String valueDigest) { + Object[] values = { + operationId, + request.requestId(), + request.transitionId(), + ISSUER, + transitionRequest.candidateAccountIndexFence(), + prepared.bindingRef().bytes(), + decimal(prepared.bindingGeneration()), + reservation.reservationId(), + reservation.reservationFence(), + decimal(reservation.partitionId()), + decimal(prepared.inventoryRevision()), + null, + null, + reservation.issuerCoverageOperationId(), + decimal(reservation.issuerCoverageOperationFence()), + decimal(reservation.coverageFence()), + decimal(reservation.inventorySnapshotRevision()), + anchor.bootstrapOperationId(), + anchor.bootstrapRequestId(), + anchor.buildOperationId(), + anchor.buildPlanDigest(), + decimal(anchor.controlEpoch()), + anchor.issuerCoverageOperationId(), + decimal(anchor.operationFence()), + decimal(anchor.coverageFence()), + decimal(anchor.issuerInventorySnapshotRevision()), + decimal(anchor.layoutVersion()), + decimal(anchor.partitionCount()), + decimal(anchor.partitionCapacity()), + anchor.mappingIdentity(), + anchor.layoutDescriptorBytes(), + anchor.layoutDescriptorDigest(), + decimal(anchor.issuerAuthGeneration()), + anchor.sourceCheckpointBytes(), + anchor.sourceCheckpointDigest(), + anchor.sourceEventBytes(), + anchor.sourceEventDigest(), + anchor.incarnationBytes(), + anchor.incarnationDigest(), + anchor.exactAnchorBytes(), + anchor.exactAnchorDigest(), + decimal(proof.partitionId()), + proof.exactPhysicalFieldSetBytes(), + proof.exactPhysicalFieldSetDigest(), + proof.physicalCountedCapacityCount(), + proof.physicalReservationCount(), + proof.physicalBindingCount(), + account.state(), + decimal(account.epoch()), + account.currentOperationId(), + account.currentFenceIntentId(), + decimalNullable(account.currentOperationFence()), + account.accountAdmissionFence(), + account.historicalAccountAdmissionFence(), + account.coverageFence(), + decimalNullable(account.inventorySnapshotRevision()), + decimalNullable(account.coverageGeneration()), + decimal(counters.operationFence()), + decimal(counters.localMemberGeneration()), + "ABSENT", + "ABSENT", + "PENDING_PHYSICAL_PROOF", + (short) 2, + valueBytes, + valueDigest + }; + String placeholders = String.join(",", java.util.Collections.nCopies(values.length, "?")); + transaction.execute( + "INSERT INTO " + + OPERATION + + " (" + + "operation_id, request_id, transition_id, issuer_id, candidate_account_index_fence," + + "binding_ref, binding_generation, reservation_id, reservation_fence, partition_id," + + "local_inventory_snapshot_revision, expected_prior_binding_ref, expected_prior_binding_generation," + + "original_issuer_coverage_operation_id, original_issuer_coverage_operation_fence," + + "original_coverage_fence, original_inventory_snapshot_revision," + + "anchor_bootstrap_operation_id, anchor_bootstrap_request_id, anchor_build_operation_id," + + "anchor_build_plan_digest, anchor_control_epoch, anchor_issuer_coverage_operation_id," + + "anchor_operation_fence, anchor_coverage_fence, anchor_issuer_inventory_snapshot_revision," + + "anchor_layout_version, anchor_partition_count, anchor_partition_capacity, anchor_mapping_identity," + + "anchor_layout_descriptor_bytes, anchor_layout_descriptor_digest, anchor_issuer_auth_generation," + + "anchor_source_checkpoint_bytes, anchor_source_checkpoint_digest, anchor_source_event_bytes," + + "anchor_source_event_digest, anchor_incarnation_bytes, anchor_incarnation_digest," + + "exact_anchor_bytes, exact_anchor_digest, baseline_partition_id, baseline_field_set_bytes," + + "baseline_field_set_digest, baseline_counted_capacity, baseline_reservation_count, baseline_binding_count," + + "account_control_state, account_control_epoch, account_current_operation_id," + + "account_current_fence_intent_id, account_current_operation_fence, account_admission_fence," + + "account_historical_admission_fence, account_coverage_fence, account_inventory_snapshot_revision," + + "account_coverage_generation, operation_fence, local_member_generation, expected_old_member_state," + + "expected_old_capacity_state, member_status, member_schema_version, member_value_bytes, member_value_digest)" + + " VALUES (" + + placeholders + + ")", + values); + } + + private static IssuedCounters allocateLocalCounters( + DSLContext transaction, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalIssuerPartitionReservation reservation) { + Record counter = + transaction.fetchOne( + "SELECT * FROM " + MEMBER_COUNTER + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (counter == null) { + Record priorBootstrapOperation = + transaction.fetchOne( + "SELECT 1 FROM " + BOOTSTRAP_MEMBER_OPERATION + " WHERE issuer_id = ? LIMIT 1", + ISSUER); + Record priorLocalOperation = + transaction.fetchOne( + "SELECT 1 FROM " + OPERATION + " WHERE issuer_id = ? LIMIT 1", ISSUER); + if (priorBootstrapOperation != null || priorLocalOperation != null) { + throw conflict("Issuer-local operation counter is missing after prior issuance"); + } + transaction.execute( + "INSERT INTO " + + MEMBER_COUNTER + + " (issuer_id, last_issued_operation_fence, last_issued_member_generation, counter_version)" + + " VALUES (?, 0, 0, 0) ON CONFLICT (issuer_id) DO NOTHING", + ISSUER); + counter = + transaction.fetchOne( + "SELECT * FROM " + MEMBER_COUNTER + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (counter == null) throw conflict("Issuer-local operation counter could not initialize"); + } + BigInteger previousFence = readNonNegative(counter, "last_issued_operation_fence"); + BigInteger previousGeneration = readNonNegative(counter, "last_issued_member_generation"); + Long versionValue = counter.get("counter_version", Long.class); + if (versionValue == null + || versionValue < 0 + || (versionValue == 0 && (previousFence.signum() != 0 || previousGeneration.signum() != 0)) + || (versionValue > 0 + && (!previousFence.add(BigInteger.ONE).equals(previousGeneration) + || previousFence.signum() <= 0))) { + throw conflict("Issuer-local member-operation counter state is malformed"); + } + BigInteger seed = + max( + anchor.controlEpoch(), + anchor.operationFence(), + anchor.coverageFence(), + anchor.issuerInventorySnapshotRevision(), + reservation.issuerCoverageOperationFence(), + reservation.coverageFence(), + reservation.inventorySnapshotRevision(), + reservation.inventoryRevision(), + previousFence, + previousGeneration); + BigInteger operationFence = seed.add(BigInteger.ONE); + BigInteger generation = operationFence.add(BigInteger.ONE); + requireCounterLimit(operationFence, "operationFence"); + requireCounterLimit(generation, "localMemberGeneration"); + long nextVersion; + try { + nextVersion = Math.addExact(versionValue, 1L); + } catch (ArithmeticException overflow) { + throw conflict("Issuer-local member-operation counter version is exhausted"); + } + Record updated = + transaction.fetchOne( + "UPDATE " + + MEMBER_COUNTER + + " SET last_issued_operation_fence = ?, last_issued_member_generation = ?, counter_version = ?" + + " WHERE issuer_id = ? AND last_issued_operation_fence = ?" + + " AND last_issued_member_generation = ? AND counter_version = ? RETURNING issuer_id", + decimal(operationFence), + decimal(generation), + nextVersion, + ISSUER, + decimal(previousFence), + decimal(previousGeneration), + versionValue); + if (updated == null) throw conflict("Issuer-local operation counter compare-and-set lost"); + return new IssuedCounters(operationFence, generation); + } + + private static void requireSameStoredOperation( + Record row, + CanonicalGameplayIssuerBindingLocalOperation.Request request, + CanonicalGameplayBindingTransitionSnapshot prepared, + CanonicalIssuerPartitionReservation reservation, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof proof, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState, + AccountControlSnapshot account) { + CanonicalGameplayIssuerMemberV2Value storedMemberValue; + try { + storedMemberValue = + CanonicalGameplayIssuerMemberV2Codec.decode(requireBytes(row, "member_value_bytes")); + } catch (RuntimeException malformed) { + throw conflict("Stored local operation does not contain a canonical v2 member"); + } + if (!requireUuid(row, "request_id").equals(request.requestId()) + || !requireUuid(row, "transition_id").equals(request.transitionId()) + || !ISSUER.equals(requireText(row, "issuer_id")) + || !requireUuid(row, "candidate_account_index_fence") + .equals(prepared.candidateAccountIndexFence()) + || !Arrays.equals(requireBytes(row, "binding_ref"), prepared.bindingRef().bytes()) + || !readPositive(row, "binding_generation").equals(prepared.bindingGeneration()) + || !requireUuid(row, "reservation_id").equals(reservation.reservationId()) + || !requireUuid(row, "reservation_fence").equals(reservation.reservationFence()) + || !readNonNegative(row, "partition_id").equals(reservation.partitionId()) + || row.get("expected_prior_binding_ref", byte[].class) != null + || row.get("expected_prior_binding_generation") != null + || !requireUuid(row, "original_issuer_coverage_operation_id") + .equals(reservation.issuerCoverageOperationId()) + || !readPositive(row, "original_issuer_coverage_operation_fence") + .equals(reservation.issuerCoverageOperationFence()) + || !readPositive(row, "original_coverage_fence").equals(reservation.coverageFence()) + || !readPositive(row, "original_inventory_snapshot_revision") + .equals(reservation.inventorySnapshotRevision()) + || !requireUuid(row, "anchor_bootstrap_operation_id").equals(anchor.bootstrapOperationId()) + || !requireUuid(row, "anchor_bootstrap_request_id").equals(anchor.bootstrapRequestId()) + || !requireUuid(row, "anchor_build_operation_id").equals(anchor.buildOperationId()) + || !anchor.buildPlanDigest().equals(requireText(row, "anchor_build_plan_digest")) + || !readPositive(row, "anchor_control_epoch").equals(anchor.controlEpoch()) + || !requireUuid(row, "anchor_issuer_coverage_operation_id") + .equals(anchor.issuerCoverageOperationId()) + || !readPositive(row, "anchor_operation_fence").equals(anchor.operationFence()) + || !readPositive(row, "anchor_coverage_fence").equals(anchor.coverageFence()) + || !readPositive(row, "anchor_issuer_inventory_snapshot_revision") + .equals(anchor.issuerInventorySnapshotRevision()) + || !readPositive(row, "anchor_layout_version").equals(anchor.layoutVersion()) + || !readPositive(row, "anchor_partition_count").equals(anchor.partitionCount()) + || !readPositive(row, "anchor_partition_capacity").equals(anchor.partitionCapacity()) + || !anchor.mappingIdentity().equals(requireText(row, "anchor_mapping_identity")) + || !Arrays.equals( + requireBytes(row, "anchor_layout_descriptor_bytes"), anchor.layoutDescriptorBytes()) + || !anchor + .layoutDescriptorDigest() + .equals(requireText(row, "anchor_layout_descriptor_digest")) + || !readPositive(row, "anchor_issuer_auth_generation").equals(anchor.issuerAuthGeneration()) + || !Arrays.equals( + requireBytes(row, "anchor_source_checkpoint_bytes"), anchor.sourceCheckpointBytes()) + || !anchor + .sourceCheckpointDigest() + .equals(requireText(row, "anchor_source_checkpoint_digest")) + || !Arrays.equals( + optionalBytes(row, "anchor_source_event_bytes"), anchor.sourceEventBytes()) + || !Objects.equals( + row.get("anchor_source_event_digest", String.class), anchor.sourceEventDigest()) + || !Arrays.equals(requireBytes(row, "anchor_incarnation_bytes"), anchor.incarnationBytes()) + || !anchor.incarnationDigest().equals(requireText(row, "anchor_incarnation_digest")) + || !Arrays.equals(requireBytes(row, "exact_anchor_bytes"), anchor.exactAnchorBytes()) + || !anchor.exactAnchorDigest().equals(requireText(row, "exact_anchor_digest")) + || !readNonNegative(row, "baseline_partition_id").equals(proof.partitionId()) + || !Arrays.equals( + requireBytes(row, "baseline_field_set_bytes"), proof.exactPhysicalFieldSetBytes()) + || !proof + .exactPhysicalFieldSetDigest() + .equals(requireText(row, "baseline_field_set_digest")) + || readInt(row, "baseline_counted_capacity") != proof.physicalCountedCapacityCount() + || readInt(row, "baseline_reservation_count") != proof.physicalReservationCount() + || readInt(row, "baseline_binding_count") != proof.physicalBindingCount() + || !Arrays.equals( + anchor.incarnationBytes(), + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(currentState.incarnation())) + || !account.equals( + AccountControlSnapshot.fromOperation(row, request.candidate().accountId())) + || !readPositive(row, "local_inventory_snapshot_revision") + .equals(storedMemberValue.reservation().inventoryRevision()) + || !readPositive(row, "local_inventory_snapshot_revision") + .equals(prepared.inventoryRevision()) + || !"ABSENT".equals(requireText(row, "expected_old_member_state")) + || !"ABSENT".equals(requireText(row, "expected_old_capacity_state")) + || !"PENDING_PHYSICAL_PROOF".equals(requireText(row, "member_status")) + || !Objects.equals(row.get("member_schema_version", Short.class), (short) 2)) { + throw conflict( + "Stored ordinary NEW operation differs from its current exact anchor, Account, or reservation"); + } + } + + private static void requireCallerRequestMatches( + Record row, CanonicalGameplayIssuerBindingLocalOperation.Request request) { + if (!request.requestId().equals(requireUuid(row, "request_id")) + || !request.transitionId().equals(requireUuid(row, "transition_id")) + || !ISSUER.equals(requireText(row, "issuer_id")) + || !Arrays.equals( + requireBytes(row, "binding_ref"), request.candidate().bindingRef().bytes()) + || request.expectedPriorBindingRef() != null + || request.expectedPriorBindingGeneration() != null) { + throw conflict("Stored local issuer operation is not an ordinary NEW transition"); + } + CanonicalGameplayIssuerMemberV2Value storedValue; + try { + storedValue = + CanonicalGameplayIssuerMemberV2Codec.decode(requireBytes(row, "member_value_bytes")); + } catch (RuntimeException malformed) { + throw conflict("Stored local issuer operation has a malformed candidate identity"); + } + if (!storedValue.owner().equals(request.candidate()) + || !storedValue.reservation().transitionId().equals(request.transitionId())) { + throw conflict("Same request or transition identity was retried with a different candidate"); + } + } + + private static CanonicalIssuerReservationFenceEvidence readOriginalReservationEvidence( + Record operationRow) { + return new CanonicalIssuerReservationFenceEvidence( + requireUuid(operationRow, "reservation_id"), + requireUuid(operationRow, "reservation_fence"), + requireUuid(operationRow, "original_issuer_coverage_operation_id"), + readPositive(operationRow, "original_issuer_coverage_operation_fence"), + readPositive(operationRow, "original_coverage_fence"), + readPositive(operationRow, "original_inventory_snapshot_revision")); + } + + private static void requireCandidateMatchesAnchor( + CanonicalGameplayBindingIdentity candidate, CanonicalGameplayIssuerInstalledAnchor anchor) { + if (!ISSUER.equals(candidate.issuerId()) + || !candidate.issuerId().equals(anchor.issuerId()) + || !candidate.issuerAuthGeneration().equals(anchor.issuerAuthGeneration()) + || !candidate.issuerIndexLayoutVersion().equals(anchor.layoutVersion()) + || !candidate.issuerIndexPartitionCount().equals(anchor.partitionCount()) + || !candidate.issuerIndexPartitionCapacity().equals(anchor.partitionCapacity())) { + throw conflict("Caller candidate differs from the exact installed issuer source or layout"); + } + } + + private static boolean sameCurrentIssuerState( + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState left, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState right) { + var leftCheckpoint = left.accountCheckpoint(); + var rightCheckpoint = right.accountCheckpoint(); + return leftCheckpoint.issuerId().equals(rightCheckpoint.issuerId()) + && leftCheckpoint.issuerAuthGeneration().equals(rightCheckpoint.issuerAuthGeneration()) + && Arrays.equals( + leftCheckpoint.exactCheckpointBytes(), rightCheckpoint.exactCheckpointBytes()) + && leftCheckpoint.checkpointDigest().equals(rightCheckpoint.checkpointDigest()) + && Arrays.equals( + leftCheckpoint.latestIssuerEventBytes(), rightCheckpoint.latestIssuerEventBytes()) + && Objects.equals( + leftCheckpoint.latestIssuerEventDigest(), rightCheckpoint.latestIssuerEventDigest()) + && Arrays.equals( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(left.incarnation()), + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(right.incarnation())); + } + + private static boolean operationRequestExists(DSLContext transaction, UUID transitionId) { + return transaction.fetchOne( + "SELECT 1 FROM " + OPERATION + " WHERE issuer_id = ? AND transition_id = ?", + ISSUER, + transitionId) + != null; + } + + private static UUID freshOperationId( + CanonicalGameplayIssuerBindingLocalOperation.Request request, + CanonicalIssuerPartitionReservation reservation, + CanonicalGameplayIssuerInstalledAnchor anchor) { + UUID result; + do { + result = freshNonNilUuid(); + } while (result.equals(request.requestId()) + || result.equals(request.transitionId()) + || result.equals(reservation.reservationId()) + || result.equals(reservation.reservationFence()) + || result.equals(anchor.bootstrapOperationId()) + || result.equals(anchor.bootstrapRequestId()) + || result.equals(anchor.buildOperationId())); + return result; + } + + private static UUID freshNonNilUuid() { + UUID value; + do { + value = UUID.randomUUID(); + } while (value.equals(new UUID(0L, 0L))); + return value; + } + + private static BigInteger max(BigInteger... values) { + BigInteger result = BigInteger.ZERO; + for (BigInteger value : values) if (value.compareTo(result) > 0) result = value; + return result; + } + + private static void requireCounterLimit(BigInteger value, String name) { + if (value.signum() <= 0 || value.toString().length() > 256) { + throw conflict(name + " exceeds the bounded local issuer counter range"); + } + } + + private static BigDecimal decimal(BigInteger value) { + return new BigDecimal(value); + } + + private static BigDecimal decimalNullable(BigInteger value) { + return value == null ? null : decimal(value); + } + + private static BigInteger readPositive(Record row, String field) { + BigInteger value = readNonNegative(row, field); + if (value.signum() <= 0) throw conflict(field + " must be positive"); + return value; + } + + private static BigInteger readNonNegative(Record row, String field) { + Object value = row.get(field); + if (!(value instanceof Number number)) throw conflict(field + " is missing or nonnumeric"); + BigInteger integer; + try { + integer = + number instanceof BigDecimal decimal + ? decimal.toBigIntegerExact() + : BigInteger.valueOf(number.longValue()); + } catch (ArithmeticException malformed) { + throw conflict(field + " is not an exact integer"); + } + if (integer.signum() < 0 || integer.toString().length() > 256) + throw conflict(field + " is outside its bounded counter range"); + return integer; + } + + private static int readInt(Record row, String field) { + try { + return readNonNegative(row, field).intValueExact(); + } catch (ArithmeticException malformed) { + throw conflict(field + " exceeds its exact integer range"); + } + } + + private static UUID requireUuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null) throw conflict(field + " is missing"); + return value; + } + + private static String requireText(Record row, String field) { + String value = row.get(field, String.class); + if (value == null) throw conflict(field + " is missing"); + return value; + } + + private static byte[] requireBytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + if (value == null || value.length == 0) throw conflict(field + " is missing or empty"); + return value; + } + + private static byte[] optionalBytes(Record row, String field) { + return row.get(field, byte[].class); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw conflict("Issuer local-operation owner cannot join an ambient SQL transaction"); + } + } + + private static IllegalStateException conflict(String message) { + return new IllegalStateException(message); + } + + private record IssuedCounters(BigInteger operationFence, BigInteger localMemberGeneration) {} + + private record AccountControlSnapshot( + String state, + BigInteger epoch, + UUID currentOperationId, + UUID currentFenceIntentId, + BigInteger currentOperationFence, + UUID accountAdmissionFence, + UUID historicalAccountAdmissionFence, + UUID coverageFence, + BigInteger inventorySnapshotRevision, + BigInteger coverageGeneration, + CanonicalGameplayAccountCoverageEvidence evidence) { + private static AccountControlSnapshot from(Record row, UUID accountId) { + String state = requireText(row, "state"); + BigInteger epoch = readNonNegative(row, "last_operation_fence"); + UUID operationId = row.get("current_operation_id", UUID.class); + UUID intentId = row.get("current_fence_intent_id", UUID.class); + BigInteger operationFence = nullableInteger(row, "current_operation_fence"); + UUID admissionFence = row.get("account_admission_fence", UUID.class); + UUID historicalFence = row.get("historical_account_admission_fence", UUID.class); + UUID coverageFence = row.get("coverage_fence", UUID.class); + BigInteger inventoryRevision = nullableInteger(row, "inventory_snapshot_revision"); + BigInteger coverageGeneration = nullableInteger(row, "coverage_generation"); + CanonicalGameplayAccountCoverageEvidence evidence; + if ("NO_ACTIVE_ACCOUNT_WIDE_FLOW".equals(state)) { + if (operationId != null + || intentId != null + || operationFence != null + || admissionFence != null + || historicalFence != null + || coverageFence != null + || inventoryRevision != null + || coverageGeneration != null) { + throw conflict("No-active Account control tuple contains active fence fields"); + } + evidence = CanonicalGameplayAccountCoverageEvidence.noActiveFlow(); + return new AccountControlSnapshot( + state, epoch, null, null, null, null, null, null, null, null, evidence); + } else if ("HISTORICAL".equals(state)) { + if (operationId == null + || intentId != null + || operationFence == null + || admissionFence != null + || historicalFence == null + || coverageFence == null + || inventoryRevision == null + || coverageGeneration == null) { + throw conflict("Historical Account control tuple is incomplete"); + } + evidence = + CanonicalGameplayAccountCoverageEvidence.historical( + operationId, + operationFence, + historicalFence, + coverageFence, + accountId, + inventoryRevision, + coverageGeneration); + return new AccountControlSnapshot( + state, + epoch, + operationId, + null, + operationFence, + null, + historicalFence, + coverageFence, + inventoryRevision, + coverageGeneration, + evidence); + } else { + throw conflict("Active or unknown Account control state blocks ordinary NEW"); + } + } + + private static AccountControlSnapshot fromOperation(Record row, UUID accountId) { + String state = requireText(row, "account_control_state"); + BigInteger epoch = readNonNegative(row, "account_control_epoch"); + UUID operationId = row.get("account_current_operation_id", UUID.class); + UUID intentId = row.get("account_current_fence_intent_id", UUID.class); + BigInteger operationFence = nullableInteger(row, "account_current_operation_fence"); + UUID admissionFence = row.get("account_admission_fence", UUID.class); + UUID historicalFence = row.get("account_historical_admission_fence", UUID.class); + UUID coverageFence = row.get("account_coverage_fence", UUID.class); + BigInteger inventoryRevision = nullableInteger(row, "account_inventory_snapshot_revision"); + BigInteger coverageGeneration = nullableInteger(row, "account_coverage_generation"); + CanonicalGameplayAccountCoverageEvidence evidence; + if ("NO_ACTIVE_ACCOUNT_WIDE_FLOW".equals(state)) { + if (operationId != null + || intentId != null + || operationFence != null + || admissionFence != null + || historicalFence != null + || coverageFence != null + || inventoryRevision != null + || coverageGeneration != null) { + throw conflict("Stored no-active Account tuple contains active fence fields"); + } + evidence = CanonicalGameplayAccountCoverageEvidence.noActiveFlow(); + return new AccountControlSnapshot( + state, epoch, null, null, null, null, null, null, null, null, evidence); + } else if ("HISTORICAL".equals(state)) { + if (operationId == null + || intentId != null + || operationFence == null + || admissionFence != null + || historicalFence == null + || coverageFence == null + || inventoryRevision == null + || coverageGeneration == null) { + throw conflict("Stored historical Account control tuple is incomplete"); + } + evidence = + CanonicalGameplayAccountCoverageEvidence.historical( + operationId, + operationFence, + historicalFence, + coverageFence, + accountId, + inventoryRevision, + coverageGeneration); + return new AccountControlSnapshot( + state, + epoch, + operationId, + null, + operationFence, + null, + historicalFence, + coverageFence, + inventoryRevision, + coverageGeneration, + evidence); + } else { + throw conflict("Stored operation has an active or unknown Account control state"); + } + } + } + + private static BigInteger nullableInteger(Record row, String field) { + Object value = row.get(field); + if (value == null) return null; + if (!(value instanceof Number number)) throw conflict(field + " is not numeric"); + try { + BigInteger result = + number instanceof BigDecimal decimal + ? decimal.toBigIntegerExact() + : BigInteger.valueOf(number.longValue()); + if (result.signum() < 0) throw conflict(field + " must be nonnegative"); + return result; + } catch (ArithmeticException malformed) { + throw conflict(field + " is not an exact integer"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java new file mode 100644 index 0000000000..0bee2ba31c --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java @@ -0,0 +1,1114 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Read-only SQL owner for a current, complete one-partition view of ordinary local issuer work. */ +final class CanonicalGameplayIssuerBindingLocalProjectionRepository { + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String LOCAL_OPERATION = + "game_session_canonical_issuer_binding_local_operation"; + private static final String BOOTSTRAP_OPERATION = + "game_session_canonical_issuer_bootstrap_member_operation"; + private static final String RESERVATION = "game_session_canonical_issuer_partition_reservation"; + private static final String INVENTORY = "game_session_canonical_gameplay_binding_inventory"; + private static final String TRANSITION = "game_session_canonical_binding_transition"; + private static final String ISSUER_OBLIGATION = + "game_session_canonical_binding_issuer_index_obligation"; + private static final String ACCOUNT_CONTROL = "game_session_canonical_account_coverage_control"; + private static final String INVENTORY_CLOCK = "game_session_canonical_binding_inventory_clock"; + private static final int MAX_LOCAL_OPERATIONS_PER_PARTITION = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_MEMBER_OPERATIONS; + + private final DSLContext dsl; + private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentIssuerStateSource; + + CanonicalGameplayIssuerBindingLocalProjectionRepository( + DSLContext dsl, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentIssuerStateSource) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.currentIssuerStateSource = + Objects.requireNonNull(currentIssuerStateSource, "currentIssuerStateSource"); + } + + /** + * Reads only from the installed-anchor owner, the ordinary NEW SQL operation owner, and its + * current V29 rows. There is deliberately no constructor that accepts caller-supplied members. + */ + PreparedPartitionWork readPreparedPartitionWork( + CanonicalGameplayIssuerBindingLocalOperation target) { + Objects.requireNonNull(target, "target"); + requireNoAmbientTransaction(); + var before = readCurrentIssuerState(); + requireCurrentSourceMatches(target.anchor(), before); + PreparedPartitionWork work = + dsl.transactionResult( + configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + lockInventoryClock(transaction); + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, before); + requireSameAnchor(target.anchor(), anchor); + return prepareInTransaction(transaction, target, anchor); + }); + var after = readCurrentIssuerState(); + requireSameCurrentIssuerState(before, after); + requireCurrentSourceMatches(work.anchor(), after); + return work; + } + + /** Re-reads the durable set and all currentness inputs after the Redis round trip. */ + void requireStillCurrent(PreparedPartitionWork expected) { + Objects.requireNonNull(expected, "expected"); + PreparedPartitionWork current = readPreparedPartitionWork(expected.targetOperation()); + if (!Arrays.equals(expected.sqlCurrentnessDigest(), current.sqlCurrentnessDigest())) { + throw unavailable( + "The registered issuer member set or current SQL phase changed during projection"); + } + } + + private PreparedPartitionWork prepareInTransaction( + DSLContext transaction, + CanonicalGameplayIssuerBindingLocalOperation target, + CanonicalGameplayIssuerInstalledAnchor anchor) { + BigInteger targetPartition = target.reservation().partitionId(); + CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof + targetBaseline = + CanonicalGameplayIssuerBootstrapCoverageRepository.readInstalledAnchorPartitionProof( + transaction, anchor, targetPartition); + Map targetBaselineFields = + CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( + targetBaseline.exactPhysicalFieldSetBytes()); + requireQualifiedBaseline(anchor, targetBaseline, targetBaselineFields); + + List operationRows = + transaction.fetch( + "SELECT * FROM " + + LOCAL_OPERATION + + " WHERE issuer_id = ? ORDER BY operation_fence, operation_id", + ISSUER); + List entries = new ArrayList<>(operationRows.size()); + Set localReservationIds = new HashSet<>(); + Set localBindingRefs = new HashSet<>(); + Set localOperationIds = new HashSet<>(); + Map< + BigInteger, + CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof> + proofsByPartition = new HashMap<>(); + proofsByPartition.put(targetPartition, targetBaseline); + + int partitionLocalOperationCount = 0; + BigInteger localAggregateCapacity = BigInteger.ZERO; + BigInteger localPartitionCapacity = BigInteger.ZERO; + boolean foundTarget = false; + for (Record row : operationRows) { + LocalEntry entry = readLocalEntry(transaction, row, anchor, target); + if (!localOperationIds.add(entry.operationId()) + || !localReservationIds.add(entry.memberValue().reservation().reservationId()) + || !localBindingRefs.add( + new String( + entry.memberValue().owner().bindingRef().bytes(), StandardCharsets.UTF_8))) { + throw unavailable("The registered local issuer operations contain duplicate identities"); + } + BigInteger partitionId = entry.memberValue().reservation().partitionId(); + var baseline = proofsByPartition.get(partitionId); + if (baseline == null) { + baseline = + CanonicalGameplayIssuerBootstrapCoverageRepository.readInstalledAnchorPartitionProof( + transaction, anchor, partitionId); + proofsByPartition.put(partitionId, baseline); + Map baselineFields = + CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( + baseline.exactPhysicalFieldSetBytes()); + requireQualifiedBaseline(anchor, baseline, baselineFields); + } + CanonicalGameplayIssuerBootstrapCoverageRepository.requireNewMemberAbsentFromBaseline( + baseline, + entry.memberValue().owner().bindingRef(), + entry.memberValue().reservation().reservationId()); + if (partitionId.equals(targetPartition)) { + partitionLocalOperationCount++; + if (entry.countsTowardCapacity()) + localPartitionCapacity = localPartitionCapacity.add(BigInteger.ONE); + } + if (entry.countsTowardCapacity()) + localAggregateCapacity = localAggregateCapacity.add(BigInteger.ONE); + if (entry.operationId().equals(target.operationId())) { + if (!Arrays.equals(entry.exactMemberValueBytes(), target.exactMemberValueBytes()) + || !entry.memberValue().equals(target.memberValue()) + || !targetPartition.equals(partitionId)) { + throw unavailable("The requested operation differs from its current SQL registration"); + } + foundTarget = true; + } + entries.add(entry); + } + if (!foundTarget) + throw unavailable("The requested ordinary NEW operation is not durably registered"); + if (partitionLocalOperationCount > MAX_LOCAL_OPERATIONS_PER_PARTITION) { + throw unavailable("The local partition operation set exceeds the physical owner bound"); + } + + Set baselineReservationIds = readAndVerifyBootstrapReservationIds(transaction, anchor); + if (baselineReservationIds.size() != anchor.physicalReservationCount()) { + throw unavailable("The installed baseline reservation cohort is incomplete"); + } + Set expectedReservationIds = new HashSet<>(baselineReservationIds); + for (UUID reservationId : localReservationIds) { + if (!expectedReservationIds.add(reservationId)) { + throw unavailable( + "A post-baseline issuer operation reuses an installed reservation identity"); + } + } + Set currentReservationIds = readCurrentReservationIds(transaction); + if (!currentReservationIds.equals(expectedReservationIds)) { + throw unavailable( + "Durable issuer reservations differ from the installed baseline and registered local set"); + } + + BigInteger aggregateCapacity = anchor.aggregateCountedCapacity().add(localAggregateCapacity); + BigInteger aggregateBound = anchor.partitionCount().multiply(anchor.partitionCapacity()); + BigInteger partitionCapacity = + BigInteger.valueOf(targetBaseline.physicalCountedCapacityCount()) + .add(localPartitionCapacity); + if (partitionCapacity.compareTo(anchor.partitionCapacity()) > 0 + || aggregateCapacity.compareTo(aggregateBound) > 0) { + throw unavailable( + "Current SQL issuer reservations exceed the pinned partition or aggregate capacity"); + } + + LocalEntry targetEntry = + entries.stream() + .filter(entry -> entry.operationId().equals(target.operationId())) + .findFirst() + .orElseThrow(() -> unavailable("The requested operation disappeared from its SQL set")); + Map allowedFields = new HashMap<>(targetBaselineFields); + for (LocalEntry entry : entries) { + if (!entry.memberValue().reservation().partitionId().equals(targetPartition)) continue; + putUnique( + allowedFields, + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + entry.memberValue().reservation().reservationId()), + entry.exactMemberValueBytes()); + if (entry.bindingPresent()) { + putUnique( + allowedFields, + new String(entry.memberValue().owner().bindingRef().bytes(), StandardCharsets.UTF_8), + entry.exactMemberValueBytes()); + } + } + if (allowedFields.size() + > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_HASH_FIELDS + + 2 * MAX_LOCAL_OPERATIONS_PER_PARTITION + || totalFieldBytes(allowedFields) + > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_TOTAL_HASH_BYTES) { + throw unavailable("The prepared local issuer partition exceeds its bounded field set"); + } + byte[] currentnessDigest = + currentnessDigest( + anchor, + targetBaseline.exactPhysicalFieldSetBytes(), + entries, + currentReservationIds, + aggregateCapacity, + partitionCapacity); + return new PreparedPartitionWork( + anchor, + target, + targetBaseline, + targetBaselineFields, + allowedFields, + entries, + targetEntry, + aggregateCapacity, + aggregateBound, + partitionCapacity, + currentnessDigest); + } + + private LocalEntry readLocalEntry( + DSLContext transaction, + Record row, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBindingLocalOperation target) { + if (!ISSUER.equals(text(row, "issuer_id")) + || !"PENDING_PHYSICAL_PROOF".equals(text(row, "member_status")) + || !Objects.equals(row.get("member_schema_version", Short.class), (short) 2) + || !"ABSENT".equals(text(row, "expected_old_capacity_state")) + || !"ABSENT".equals(text(row, "expected_old_member_state")) + || row.get("expected_prior_binding_ref", byte[].class) != null + || row.get("expected_prior_binding_generation") != null) { + throw unavailable("A durable local issuer operation is malformed or not an ordinary NEW"); + } + byte[] exactValue = bytes(row, "member_value_bytes"); + String valueDigest = text(row, "member_value_digest"); + if (!valueDigest.equals(CanonicalGameplayIssuerMemberV2Codec.sha256(exactValue))) { + throw unavailable("A durable local issuer member digest does not match its exact bytes"); + } + CanonicalGameplayIssuerMemberV2Value member; + try { + member = CanonicalGameplayIssuerMemberV2Codec.decode(exactValue); + } catch (RuntimeException malformed) { + throw unavailable("A durable local issuer operation is not closed schema v2", malformed); + } + UUID operationId = uuid(row, "operation_id"); + BigInteger operationFence = positive(row, "operation_fence"); + BigInteger localGeneration = positive(row, "local_member_generation"); + if (operationId.equals(target.operationId()) + && (!uuid(row, "request_id").equals(target.request().requestId()) + || !uuid(row, "transition_id").equals(target.request().transitionId()) + || !uuid(row, "candidate_account_index_fence") + .equals(target.candidateAccountIndexFence()) + || !operationFence.equals(target.operationFence()) + || !localGeneration.equals(target.localMemberGeneration()))) { + throw unavailable( + "The requested local issuer operation identity differs from its current SQL row"); + } + CanonicalIssuerPartitionReservation reservation = member.reservation(); + if (reservation.lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RESERVED + || !operationId.equals(member.memberOperation().operationId()) + || !operationFence.equals(member.memberOperation().operationFence()) + || !localGeneration.equals(member.memberOperation().coverageGeneration()) + || !bytesEqual(row, "binding_ref", member.owner().bindingRef().bytes()) + || !positive(row, "binding_generation").equals(member.bindingGeneration()) + || !uuid(row, "transition_id").equals(reservation.transitionId()) + || !uuid(row, "reservation_id").equals(reservation.reservationId()) + || !uuid(row, "reservation_fence").equals(reservation.reservationFence()) + || !nonnegative(row, "partition_id").equals(reservation.partitionId()) + || !positive(row, "local_inventory_snapshot_revision") + .equals(reservation.inventoryRevision()) + || !uuid(row, "original_issuer_coverage_operation_id") + .equals(reservation.issuerCoverageOperationId()) + || !positive(row, "original_issuer_coverage_operation_fence") + .equals(reservation.issuerCoverageOperationFence()) + || !positive(row, "original_coverage_fence").equals(reservation.coverageFence()) + || !positive(row, "original_inventory_snapshot_revision") + .equals(reservation.inventorySnapshotRevision()) + || !member.anchor().issuerCoverageOperationId().equals(anchor.issuerCoverageOperationId()) + || !member.anchor().operationFence().equals(anchor.operationFence()) + || !member.anchor().coverageFence().equals(anchor.coverageFence()) + || !member + .anchor() + .issuerInventorySnapshotRevision() + .equals(anchor.issuerInventorySnapshotRevision()) + || !member.owner().issuerId().equals(anchor.issuerId()) + || !Arrays.equals( + member.layoutDescriptor().exactDescriptorBytes(), anchor.layoutDescriptorBytes()) + || !Arrays.equals( + member.sourceCheckpoint().exactCheckpointBytes(), anchor.sourceCheckpointBytes()) + || !Arrays.equals( + member.sourceCheckpoint().latestIssuerEventBytes(), anchor.sourceEventBytes()) + || !Arrays.equals( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(member.incarnation()), + anchor.incarnationBytes()) + || !Arrays.equals(bytes(row, "exact_anchor_bytes"), anchor.exactAnchorBytes()) + || !text(row, "exact_anchor_digest").equals(anchor.exactAnchorDigest()) + || !bytesEqual(row, "anchor_layout_descriptor_bytes", anchor.layoutDescriptorBytes()) + || !text(row, "anchor_layout_descriptor_digest").equals(anchor.layoutDescriptorDigest()) + || !bytesEqual(row, "anchor_source_checkpoint_bytes", anchor.sourceCheckpointBytes()) + || !text(row, "anchor_source_checkpoint_digest").equals(anchor.sourceCheckpointDigest()) + || !nullableBytesEqual(row, "anchor_source_event_bytes", anchor.sourceEventBytes()) + || !Objects.equals( + row.get("anchor_source_event_digest", String.class), anchor.sourceEventDigest()) + || !bytesEqual(row, "anchor_incarnation_bytes", anchor.incarnationBytes()) + || !text(row, "anchor_incarnation_digest").equals(anchor.incarnationDigest()) + || !text(row, "baseline_field_set_digest") + .equals( + CanonicalGameplayIssuerMemberV2Codec.sha256( + bytes(row, "baseline_field_set_bytes")))) { + throw unavailable( + "A durable local issuer operation differs from its original reservation or installed anchor"); + } + requireAnchorColumns(row, anchor); + + var baseline = + CanonicalGameplayIssuerBootstrapCoverageRepository.readInstalledAnchorPartitionProof( + transaction, anchor, reservation.partitionId()); + if (!Arrays.equals( + bytes(row, "baseline_field_set_bytes"), baseline.exactPhysicalFieldSetBytes()) + || !nonnegative(row, "baseline_partition_id").equals(baseline.partitionId()) + || integer(row, "baseline_counted_capacity") != baseline.physicalCountedCapacityCount() + || integer(row, "baseline_reservation_count") != baseline.physicalReservationCount() + || integer(row, "baseline_binding_count") != baseline.physicalBindingCount()) { + throw unavailable( + "A durable local issuer operation no longer links to its exact immutable baseline partition"); + } + + Record reservationRow = + transaction.fetchOne( + "SELECT * FROM " + RESERVATION + " WHERE reservation_id = ?", + reservation.reservationId()); + Record inventoryRow = + transaction.fetchOne( + "SELECT * FROM " + INVENTORY + " WHERE binding_ref = ?", + member.owner().bindingRef().bytes()); + Record transitionRow = + transaction.fetchOne( + "SELECT * FROM " + TRANSITION + " WHERE transition_id = ?", reservation.transitionId()); + Record issuerObligation = + transaction.fetchOne( + "SELECT * FROM " + ISSUER_OBLIGATION + " WHERE transition_id = ? AND binding_ref = ?", + reservation.transitionId(), + member.owner().bindingRef().bytes()); + if (reservationRow == null + || inventoryRow == null + || transitionRow == null + || issuerObligation == null) { + throw unavailable("The local issuer operation is missing its current V29 source rows"); + } + CurrentPhase phase = + verifyCurrentSourceRows( + row, member, reservationRow, inventoryRow, transitionRow, issuerObligation); + requireAccountControlCurrent(transaction, row, member.owner().accountId()); + return new LocalEntry( + operationId, + exactValue, + member, + phase.bindingPresent(), + phase.countsTowardCapacity(), + phase.lifecycle(), + phase.transitionStatus(), + phase.inventoryRevision()); + } + + private static CurrentPhase verifyCurrentSourceRows( + Record operationRow, + CanonicalGameplayIssuerMemberV2Value member, + Record reservationRow, + Record inventoryRow, + Record transitionRow, + Record issuerObligation) { + CanonicalGameplayBindingIdentity owner = member.owner(); + CanonicalIssuerPartitionReservation original = member.reservation(); + requireOwnerColumns(reservationRow, owner, original.partitionId(), "partition_id"); + requireOwnerColumns(inventoryRow, owner, original.partitionId(), "issuer_partition_id"); + BigInteger currentBindingGeneration = positive(inventoryRow, "binding_generation"); + String candidateLifecycle = text(inventoryRow, "lifecycle"); + String transitionStatus = text(transitionRow, "status"); + String reservationLifecycle = text(reservationRow, "lifecycle"); + BigInteger currentReservationRevision = positive(reservationRow, "inventory_revision"); + if (!uuid(reservationRow, "reservation_id").equals(original.reservationId()) + || !uuid(reservationRow, "transition_id").equals(original.transitionId()) + || !uuid(reservationRow, "reservation_fence").equals(original.reservationFence()) + || !uuid(reservationRow, "issuer_coverage_operation_id") + .equals(original.issuerCoverageOperationId()) + || !positive(reservationRow, "issuer_coverage_operation_fence") + .equals(original.issuerCoverageOperationFence()) + || !positive(reservationRow, "coverage_fence").equals(original.coverageFence()) + || !positive(reservationRow, "inventory_snapshot_revision") + .equals(original.inventorySnapshotRevision()) + || currentReservationRevision.compareTo(original.inventoryRevision()) < 0 + || !bytesEqual(reservationRow, "binding_ref", owner.bindingRef().bytes()) + || !currentBindingGeneration.equals(member.bindingGeneration()) + || !positive(inventoryRow, "inventory_revision") + .equals(positive(transitionRow, "inventory_revision")) + || !uuid(transitionRow, "transition_id").equals(original.transitionId()) + || !bytesEqual(transitionRow, "candidate_binding_ref", owner.bindingRef().bytes()) + || !uuid(transitionRow, "tenant_id").equals(owner.tenantId()) + || !uuid(transitionRow, "playable_state_namespace_id") + .equals(owner.playableStateNamespaceId()) + || !uuid(transitionRow, "character_id").equals(owner.characterId()) + || !positive(transitionRow, "candidate_binding_generation") + .equals(member.bindingGeneration()) + || !uuid(transitionRow, "candidate_account_index_fence") + .equals(uuid(operationRow, "candidate_account_index_fence")) + || !uuid(transitionRow, "issuer_reservation_id").equals(original.reservationId()) + || !uuid(inventoryRow, "transition_id").equals(original.transitionId()) + || !uuid(inventoryRow, "account_index_fence") + .equals(uuid(operationRow, "candidate_account_index_fence")) + || !uuid(inventoryRow, "issuer_reservation_id").equals(original.reservationId()) + || transitionRow.get("expected_prior_binding_ref", byte[].class) != null + || transitionRow.get("expected_prior_binding_generation") != null + || !bytesEqual(issuerObligation, "binding_ref", owner.bindingRef().bytes()) + || !uuid(issuerObligation, "reservation_id").equals(original.reservationId()) + || !positive(issuerObligation, "binding_generation").equals(member.bindingGeneration()) + || !"REQUIRED".equals(text(issuerObligation, "status"))) { + throw unavailable( + "The actual V29 issuer transition no longer matches its immutable local operation"); + } + if (!Arrays.equals(bytes(operationRow, "binding_ref"), owner.bindingRef().bytes()) + || !positive(operationRow, "binding_generation").equals(member.bindingGeneration())) { + throw unavailable( + "The issuer operation's frozen candidate differs from the current V29 source"); + } + + boolean bindingPresent; + boolean counted; + if ("PREPARED".equals(transitionStatus) + && "CANDIDATE_PREPARED".equals(candidateLifecycle) + && "RESERVED".equals(reservationLifecycle)) { + bindingPresent = false; + counted = true; + } else if ("PROVISIONAL".equals(transitionStatus) + && "PROVISIONAL".equals(candidateLifecycle) + && "RESERVED".equals(reservationLifecycle)) { + bindingPresent = true; + counted = true; + } else if ("COMMITTED".equals(transitionStatus) + && "ACTIVE".equals(candidateLifecycle) + && "BOUND".equals(reservationLifecycle)) { + bindingPresent = true; + counted = true; + } else { + throw unavailable( + "The current SQL transition phase does not qualify an issuer reservation/member projection"); + } + if (!positive(inventoryRow, "inventory_revision") + .equals(positive(transitionRow, "inventory_revision")) + || !positive(issuerObligation, "inventory_revision") + .equals(positive(transitionRow, "inventory_revision")) + || !positive(reservationRow, "inventory_revision") + .equals(positive(transitionRow, "inventory_revision"))) { + throw unavailable( + "The V29 candidate, reservation, and issuer obligation revisions are not one current transition"); + } + return new CurrentPhase( + bindingPresent, + counted, + reservationLifecycle, + transitionStatus, + positive(transitionRow, "inventory_revision")); + } + + private static void requireOwnerColumns( + Record row, + CanonicalGameplayBindingIdentity owner, + BigInteger partitionId, + String partitionField) { + if (!uuid(row, "account_id").equals(owner.accountId()) + || !uuid(row, "tenant_id").equals(owner.tenantId()) + || !uuid(row, "game_instance_id").equals(owner.gameInstanceId()) + || !number(row, "runtime_game_instance_id") + .equals(BigInteger.valueOf(owner.runtimeGameInstanceId())) + || !text(row, "session_id").equals(owner.sessionId()) + || !text(row, "issuer_id").equals(owner.issuerId()) + || !positive(row, "issuer_auth_generation").equals(owner.issuerAuthGeneration()) + || !uuid(row, "playable_state_namespace_id").equals(owner.playableStateNamespaceId()) + || !uuid(row, "character_id").equals(owner.characterId()) + || !text(row, "playable_state_scope").equals(owner.playableStateScope()) + || !uuid(row, "region_id").equals(owner.regionId()) + || !positive(row, "region_epoch").equals(owner.regionEpoch()) + || !positive(row, "issuer_index_layout_version").equals(owner.issuerIndexLayoutVersion()) + || !positive(row, "issuer_index_partition_count").equals(owner.issuerIndexPartitionCount()) + || !positive(row, "issuer_index_partition_capacity") + .equals(owner.issuerIndexPartitionCapacity()) + || !nonnegative(row, partitionField).equals(partitionId)) { + throw unavailable( + "The actual issuer reservation or candidate owner differs from the full v2 owner tuple"); + } + } + + private static void requireAccountControlCurrent( + DSLContext transaction, Record operation, UUID accountId) { + Record account = + transaction.fetchOne( + "SELECT * FROM " + ACCOUNT_CONTROL + " WHERE account_id = ? FOR UPDATE", accountId); + if (account == null + || !Objects.equals(text(account, "state"), text(operation, "account_control_state")) + || !number(account, "last_operation_fence") + .equals(number(operation, "account_control_epoch")) + || !Objects.equals( + account.get("current_operation_id", UUID.class), + operation.get("account_current_operation_id", UUID.class)) + || !Objects.equals( + account.get("current_operation_fence", BigDecimal.class), + operation.get("account_current_operation_fence", BigDecimal.class)) + || !Objects.equals( + account.get("account_admission_fence", UUID.class), + operation.get("account_admission_fence", UUID.class)) + || !Objects.equals( + account.get("historical_account_admission_fence", UUID.class), + operation.get("account_historical_admission_fence", UUID.class)) + || !Objects.equals( + account.get("coverage_fence", UUID.class), + operation.get("account_coverage_fence", UUID.class)) + || !Objects.equals( + account.get("inventory_snapshot_revision", BigDecimal.class), + operation.get("account_inventory_snapshot_revision", BigDecimal.class)) + || !Objects.equals( + account.get("coverage_generation", BigDecimal.class), + operation.get("account_coverage_generation", BigDecimal.class))) { + throw unavailable( + "The original Account coverage control changed after local issuer registration"); + } + } + + private static Set readAndVerifyBootstrapReservationIds( + DSLContext transaction, CanonicalGameplayIssuerInstalledAnchor anchor) { + List rows = + transaction.fetch( + "SELECT * FROM " + + BOOTSTRAP_OPERATION + + " WHERE issuer_id = ? AND bootstrap_operation_id = ? ORDER BY work_ordinal", + ISSUER, + anchor.bootstrapOperationId()); + Set reservationIds = new HashSet<>(); + for (Record row : rows) { + byte[] valueBytes = bytes(row, "member_value_bytes"); + if (!text(row, "member_value_digest") + .equals(CanonicalGameplayIssuerMemberV2Codec.sha256(valueBytes)) + || !"PENDING_PHYSICAL_PROOF".equals(text(row, "member_status")) + || !Objects.equals(row.get("member_schema_version", Short.class), (short) 2)) { + throw unavailable("The installed bootstrap member history is malformed"); + } + CanonicalGameplayIssuerMemberV2Value value; + try { + value = CanonicalGameplayIssuerMemberV2Codec.decode(valueBytes); + } catch (RuntimeException malformed) { + throw unavailable( + "The installed bootstrap member history is not closed schema v2", malformed); + } + if (!value.anchor().issuerCoverageOperationId().equals(anchor.issuerCoverageOperationId()) + || !value.anchor().operationFence().equals(anchor.operationFence()) + || !value.anchor().coverageFence().equals(anchor.coverageFence()) + || !value + .anchor() + .issuerInventorySnapshotRevision() + .equals(anchor.issuerInventorySnapshotRevision()) + || !value.owner().issuerId().equals(anchor.issuerId()) + || !value + .reservation() + .partitionId() + .equals(value.owner().bindingRef().partitionId(anchor.partitionCount())) + || !reservationIds.add(value.reservation().reservationId()) + || !uuid(row, "reservation_id").equals(value.reservation().reservationId())) { + throw unavailable( + "The installed bootstrap member history differs from its exact anchor cohort"); + } + } + return reservationIds; + } + + private static Set readCurrentReservationIds(DSLContext transaction) { + List rows = + transaction.fetch( + "SELECT reservation_id FROM " + + RESERVATION + + " WHERE issuer_id = ? ORDER BY reservation_id", + ISSUER); + Set result = new HashSet<>(); + for (Record row : rows) { + if (!result.add(uuid(row, "reservation_id"))) { + throw unavailable("The current issuer reservation inventory contains duplicate identities"); + } + } + return result; + } + + private static void requireQualifiedBaseline( + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof proof, + Map fields) { + String headerField = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.METADATA_FIELD; + byte[] header = fields.get(headerField); + if (header == null || !Arrays.equals(header, proofMetadata(proof))) { + throw unavailable("The installed issuer baseline header is missing or changed"); + } + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.requireExactMetadata(header, header); + Set reservations = new HashSet<>(); + Set bindings = new HashSet<>(); + Map capacityMembers = new HashMap<>(); + Map bindingReservations = new HashMap<>(); + int countedCapacity = 0; + int reservationCount = 0; + int bindingCount = 0; + for (Map.Entry field : fields.entrySet()) { + if (field.getKey().equals(headerField)) continue; + CanonicalGameplayIssuerMemberV2Value value; + try { + value = CanonicalGameplayIssuerMemberV2Codec.decode(field.getValue()); + } catch (RuntimeException malformed) { + throw unavailable( + "The exact issuer baseline contains a malformed or legacy member value", malformed); + } + requireMemberMatchesAnchor(value, anchor); + if (!value.reservation().partitionId().equals(proof.partitionId()) + || !value + .owner() + .bindingRef() + .partitionId(anchor.partitionCount()) + .equals(proof.partitionId())) { + throw unavailable( + "An immutable issuer baseline member is stored under the wrong partition"); + } + String name = field.getKey(); + if (name.startsWith( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.RESERVATION_FIELD_PREFIX)) { + UUID reservationId = parseReservationField(name); + if (!reservationId.equals(value.reservation().reservationId()) + || !reservations.add(reservationId)) { + throw unavailable( + "The immutable issuer baseline has a duplicate or conflicting capacity field"); + } + capacityMembers.put(reservationId, field.getValue()); + reservationCount++; + if (value.reservation().lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED) { + countedCapacity++; + } + } else { + if (name.startsWith("!") + || !Arrays.equals( + name.getBytes(StandardCharsets.UTF_8), value.owner().bindingRef().bytes()) + || !bindings.add(name)) { + throw unavailable("The immutable issuer baseline has an invalid canonical binding field"); + } + UUID reservationId = value.reservation().reservationId(); + if (bindingReservations.putIfAbsent(name, reservationId) != null) { + throw unavailable("The immutable issuer baseline repeats a binding owner"); + } + bindingCount++; + } + } + Set boundReservations = new HashSet<>(); + for (Map.Entry binding : bindingReservations.entrySet()) { + byte[] capacityValue = capacityMembers.get(binding.getValue()); + byte[] bindingValue = fields.get(binding.getKey()); + if (capacityValue == null + || !Arrays.equals(capacityValue, bindingValue) + || !boundReservations.add(binding.getValue())) { + throw unavailable( + "An immutable issuer baseline binding has no exact unique capacity reservation"); + } + } + if (reservationCount != proof.physicalReservationCount() + || bindingCount != proof.physicalBindingCount() + || countedCapacity != proof.physicalCountedCapacityCount() + || fields.size() != 1 + reservationCount + bindingCount) { + throw unavailable( + "The immutable issuer baseline field set does not match its retained counts"); + } + } + + private static byte[] proofMetadata( + CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof proof) { + Map fields = + CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( + proof.exactPhysicalFieldSetBytes()); + byte[] metadata = + fields.get(CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.METADATA_FIELD); + if (metadata == null) throw unavailable("The installed issuer baseline has no metadata header"); + return metadata; + } + + static void requireMemberMatchesAnchor( + CanonicalGameplayIssuerMemberV2Value value, CanonicalGameplayIssuerInstalledAnchor anchor) { + if (!value.owner().issuerId().equals(anchor.issuerId()) + || !value.owner().issuerAuthGeneration().equals(anchor.issuerAuthGeneration()) + || !value.owner().issuerIndexLayoutVersion().equals(anchor.layoutVersion()) + || !value.owner().issuerIndexPartitionCount().equals(anchor.partitionCount()) + || !value.owner().issuerIndexPartitionCapacity().equals(anchor.partitionCapacity()) + || !value.issuerControlEpoch().equals(anchor.controlEpoch()) + || !value.anchor().issuerCoverageOperationId().equals(anchor.issuerCoverageOperationId()) + || !value.anchor().operationFence().equals(anchor.operationFence()) + || !value.anchor().coverageFence().equals(anchor.coverageFence()) + || !value + .anchor() + .issuerInventorySnapshotRevision() + .equals(anchor.issuerInventorySnapshotRevision()) + || !Arrays.equals( + value.layoutDescriptor().exactDescriptorBytes(), anchor.layoutDescriptorBytes()) + || !value.layoutDescriptor().descriptorDigest().equals(anchor.layoutDescriptorDigest()) + || !Arrays.equals( + value.sourceCheckpoint().exactCheckpointBytes(), anchor.sourceCheckpointBytes()) + || !value.sourceCheckpoint().checkpointDigest().equals(anchor.sourceCheckpointDigest()) + || !Arrays.equals( + value.sourceCheckpoint().latestIssuerEventBytes(), anchor.sourceEventBytes()) + || !Objects.equals( + value.sourceCheckpoint().latestIssuerEventDigest(), anchor.sourceEventDigest()) + || !Arrays.equals( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(value.incarnation()), + anchor.incarnationBytes())) { + throw unavailable( + "An issuer member differs from the exact installed anchor, layout, source, or incarnation"); + } + } + + private static void requireAnchorColumns( + Record row, CanonicalGameplayIssuerInstalledAnchor anchor) { + if (!uuid(row, "anchor_bootstrap_operation_id").equals(anchor.bootstrapOperationId()) + || !uuid(row, "anchor_bootstrap_request_id").equals(anchor.bootstrapRequestId()) + || !uuid(row, "anchor_build_operation_id").equals(anchor.buildOperationId()) + || !text(row, "anchor_build_plan_digest").equals(anchor.buildPlanDigest()) + || !positive(row, "anchor_control_epoch").equals(anchor.controlEpoch()) + || !uuid(row, "anchor_issuer_coverage_operation_id") + .equals(anchor.issuerCoverageOperationId()) + || !positive(row, "anchor_operation_fence").equals(anchor.operationFence()) + || !positive(row, "anchor_coverage_fence").equals(anchor.coverageFence()) + || !positive(row, "anchor_issuer_inventory_snapshot_revision") + .equals(anchor.issuerInventorySnapshotRevision()) + || !positive(row, "anchor_layout_version").equals(anchor.layoutVersion()) + || !positive(row, "anchor_partition_count").equals(anchor.partitionCount()) + || !positive(row, "anchor_partition_capacity").equals(anchor.partitionCapacity()) + || !text(row, "anchor_mapping_identity").equals(anchor.mappingIdentity()) + || !positive(row, "anchor_issuer_auth_generation").equals(anchor.issuerAuthGeneration())) { + throw unavailable("A durable local issuer anchor column differs from its immutable anchor"); + } + } + + private static void requireCurrentSourceMatches( + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState state) { + if (!sameCheckpoint(state.accountCheckpoint(), anchor) + || !Arrays.equals( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(state.incarnation()), + anchor.incarnationBytes())) { + throw unavailable( + "Current Account issuer source or storage incarnation differs from the installed anchor"); + } + } + + private CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState + readCurrentIssuerState() { + requireNoAmbientTransaction(); + try { + return Objects.requireNonNull( + currentIssuerStateSource.readFreshCurrentState(), + "current issuer state source returned null"); + } catch (RuntimeException failure) { + throw unavailable( + "The current issuer checkpoint or storage incarnation is unavailable", failure); + } + } + + private static void requireSameCurrentIssuerState( + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState left, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState right) { + var leftCheckpoint = left.accountCheckpoint(); + var rightCheckpoint = right.accountCheckpoint(); + if (!leftCheckpoint.issuerId().equals(rightCheckpoint.issuerId()) + || !leftCheckpoint.issuerAuthGeneration().equals(rightCheckpoint.issuerAuthGeneration()) + || !Arrays.equals( + leftCheckpoint.exactCheckpointBytes(), rightCheckpoint.exactCheckpointBytes()) + || !leftCheckpoint.checkpointDigest().equals(rightCheckpoint.checkpointDigest()) + || !Arrays.equals( + leftCheckpoint.latestIssuerEventBytes(), rightCheckpoint.latestIssuerEventBytes()) + || !Objects.equals( + leftCheckpoint.latestIssuerEventDigest(), rightCheckpoint.latestIssuerEventDigest()) + || !Arrays.equals( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(left.incarnation()), + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(right.incarnation()))) { + throw unavailable("The issuer source or storage incarnation changed during the SQL read"); + } + } + + private static boolean sameCheckpoint( + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint current, + CanonicalGameplayIssuerInstalledAnchor anchor) { + return current != null + && current.issuerId().equals(anchor.issuerId()) + && current.issuerAuthGeneration().equals(anchor.issuerAuthGeneration()) + && Arrays.equals(current.exactCheckpointBytes(), anchor.sourceCheckpointBytes()) + && current.checkpointDigest().equals(anchor.sourceCheckpointDigest()) + && Arrays.equals(current.latestIssuerEventBytes(), anchor.sourceEventBytes()) + && Objects.equals(current.latestIssuerEventDigest(), anchor.sourceEventDigest()); + } + + private static void requireSameAnchor( + CanonicalGameplayIssuerInstalledAnchor expected, + CanonicalGameplayIssuerInstalledAnchor current) { + if (!Arrays.equals(expected.exactAnchorBytes(), current.exactAnchorBytes()) + || !expected.exactAnchorDigest().equals(current.exactAnchorDigest())) { + throw unavailable("The positively installed issuer anchor changed"); + } + } + + private static void lockInventoryClock(DSLContext transaction) { + Record row = + transaction.fetchOne( + "SELECT inventory_revision FROM " + + INVENTORY_CLOCK + + " WHERE singleton_id = 1 FOR UPDATE"); + if (row == null || number(row, "inventory_revision").signum() < 0) { + throw unavailable("The durable binding inventory serialization clock is unavailable"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw unavailable("Issuer physical projection cannot run inside an ambient SQL transaction"); + } + } + + private static void putUnique(Map fields, String field, byte[] value) { + if (fields.putIfAbsent(field, value.clone()) != null) { + throw unavailable("Two SQL owner operations claim the same issuer partition field"); + } + } + + private static long totalFieldBytes(Map fields) { + long total = 0; + for (Map.Entry field : fields.entrySet()) { + total = + Math.addExact( + total, + field.getKey().getBytes(StandardCharsets.UTF_8).length + + (long) field.getValue().length); + } + return total; + } + + private static UUID parseReservationField(String field) { + try { + String suffix = + field.substring( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.RESERVATION_FIELD_PREFIX + .length()); + UUID value = UUID.fromString(suffix); + if (!value.toString().equals(suffix) || value.equals(new UUID(0L, 0L))) + throw unavailable("Capacity field identity is not canonical"); + return value; + } catch (RuntimeException malformed) { + throw unavailable("Capacity field identity is malformed", malformed); + } + } + + private static byte[] currentnessDigest( + CanonicalGameplayIssuerInstalledAnchor anchor, + byte[] baselineBytes, + List entries, + Set reservationIds, + BigInteger aggregateCapacity, + BigInteger partitionCapacity) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + update(digest, anchor.exactAnchorBytes()); + update(digest, baselineBytes); + for (LocalEntry entry : + entries.stream().sorted(Comparator.comparing(LocalEntry::operationId)).toList()) { + update(digest, entry.operationId().toString().getBytes(StandardCharsets.US_ASCII)); + update(digest, entry.exactMemberValueBytes()); + update(digest, entry.transitionStatus().getBytes(StandardCharsets.US_ASCII)); + update(digest, entry.lifecycle().getBytes(StandardCharsets.US_ASCII)); + update(digest, entry.inventoryRevision().toString().getBytes(StandardCharsets.US_ASCII)); + digest.update((byte) (entry.bindingPresent() ? 1 : 0)); + digest.update((byte) (entry.countsTowardCapacity() ? 1 : 0)); + } + for (UUID id : reservationIds.stream().sorted().toList()) { + update(digest, id.toString().getBytes(StandardCharsets.US_ASCII)); + } + update(digest, aggregateCapacity.toString().getBytes(StandardCharsets.US_ASCII)); + update(digest, partitionCapacity.toString().getBytes(StandardCharsets.US_ASCII)); + return digest.digest(); + } catch (Exception impossible) { + throw new IllegalStateException("Could not retain local issuer SQL currentness", impossible); + } + } + + private static void update(MessageDigest digest, byte[] bytes) { + digest.update(BigInteger.valueOf(bytes.length).toByteArray()); + digest.update(bytes); + } + + private static BigInteger number(Record row, String field) { + Object value = row.get(field); + if (!(value instanceof Number number)) throw unavailable(field + " is missing or nonnumeric"); + try { + if (number instanceof BigDecimal decimal) return decimal.toBigIntegerExact(); + return BigInteger.valueOf(number.longValue()); + } catch (ArithmeticException malformed) { + throw unavailable(field + " is not an exact integer", malformed); + } + } + + private static BigInteger positive(Record row, String field) { + BigInteger value = number(row, field); + if (value.signum() <= 0 + || value.toString().length() > CanonicalGameplayIssuerMemberV2Codec.MAX_COUNTER_DIGITS) { + throw unavailable(field + " is not a bounded positive counter"); + } + return value; + } + + private static BigInteger nonnegative(Record row, String field) { + BigInteger value = number(row, field); + if (value.signum() < 0 + || value.toString().length() > CanonicalGameplayIssuerMemberV2Codec.MAX_COUNTER_DIGITS) { + throw unavailable(field + " is not a bounded nonnegative counter"); + } + return value; + } + + private static int integer(Record row, String field) { + try { + return number(row, field).intValueExact(); + } catch (ArithmeticException malformed) { + throw unavailable(field + " is outside its bounded integer range", malformed); + } + } + + private static UUID uuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null) throw unavailable(field + " is missing"); + return value; + } + + private static String text(Record row, String field) { + String value = row.get(field, String.class); + if (value == null) throw unavailable(field + " is missing"); + return value; + } + + private static byte[] bytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + if (value == null || value.length == 0) throw unavailable(field + " is missing or empty"); + return value; + } + + private static boolean bytesEqual(Record row, String field, byte[] expected) { + return Arrays.equals(bytes(row, field), expected); + } + + private static boolean nullableBytesEqual(Record row, String field, byte[] expected) { + return Arrays.equals(row.get(field, byte[].class), expected); + } + + private static IllegalStateException unavailable(String message) { + return new IllegalStateException("Issuer binding-local projection is unavailable: " + message); + } + + private static IllegalStateException unavailable(String message, Throwable cause) { + return new IllegalStateException( + "Issuer binding-local projection is unavailable: " + message, cause); + } + + private record CurrentPhase( + boolean bindingPresent, + boolean countsTowardCapacity, + String lifecycle, + String transitionStatus, + BigInteger inventoryRevision) {} + + record LocalEntry( + UUID operationId, + byte[] exactMemberValueBytes, + CanonicalGameplayIssuerMemberV2Value memberValue, + boolean bindingPresent, + boolean countsTowardCapacity, + String lifecycle, + String transitionStatus, + BigInteger inventoryRevision) { + LocalEntry { + exactMemberValueBytes = exactMemberValueBytes.clone(); + } + + @Override + public byte[] exactMemberValueBytes() { + return exactMemberValueBytes.clone(); + } + } + + /** Private-construction output of the SQL owner; it has no public/raw-list factory. */ + static final class PreparedPartitionWork { + private final CanonicalGameplayIssuerInstalledAnchor anchor; + private final CanonicalGameplayIssuerBindingLocalOperation targetOperation; + private final CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof + baselineProof; + private final Map baselineFields; + private final Map allowedFields; + private final List localEntries; + private final LocalEntry targetEntry; + private final BigInteger aggregateCapacity; + private final BigInteger aggregateBound; + private final BigInteger partitionCapacity; + private final byte[] sqlCurrentnessDigest; + + private PreparedPartitionWork( + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBindingLocalOperation targetOperation, + CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof + baselineProof, + Map baselineFields, + Map allowedFields, + List localEntries, + LocalEntry targetEntry, + BigInteger aggregateCapacity, + BigInteger aggregateBound, + BigInteger partitionCapacity, + byte[] sqlCurrentnessDigest) { + this.anchor = anchor; + this.targetOperation = targetOperation; + this.baselineProof = baselineProof; + this.baselineFields = copyFields(baselineFields); + this.allowedFields = copyFields(allowedFields); + this.localEntries = List.copyOf(localEntries); + this.targetEntry = targetEntry; + this.aggregateCapacity = aggregateCapacity; + this.aggregateBound = aggregateBound; + this.partitionCapacity = partitionCapacity; + this.sqlCurrentnessDigest = sqlCurrentnessDigest.clone(); + } + + CanonicalGameplayIssuerInstalledAnchor anchor() { + return anchor; + } + + CanonicalGameplayIssuerBindingLocalOperation targetOperation() { + return targetOperation; + } + + CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof + baselineProof() { + return baselineProof; + } + + Map baselineFields() { + return copyFields(baselineFields); + } + + Map allowedFields() { + return copyFields(allowedFields); + } + + List localEntries() { + return localEntries; + } + + LocalEntry targetEntry() { + return targetEntry; + } + + BigInteger aggregateCapacity() { + return aggregateCapacity; + } + + BigInteger aggregateBound() { + return aggregateBound; + } + + BigInteger partitionCapacity() { + return partitionCapacity; + } + + byte[] sqlCurrentnessDigest() { + return sqlCurrentnessDigest.clone(); + } + + private static Map copyFields(Map source) { + Map copy = new HashMap<>(); + source.forEach((key, value) -> copy.put(key, value.clone())); + return Map.copyOf(copy); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java new file mode 100644 index 0000000000..811f6627f2 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java @@ -0,0 +1,530 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisFuture; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.async.RedisAsyncCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigInteger; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Explicit, unregistered one-key projection owner for SQL-prepared ordinary issuer NEW work. + * Physical readback is local evidence only and leaves its SQL operation pending. + */ +public final class CanonicalGameplayIssuerBindingLocalRedisOwner { + private static final String PRINCIPAL = "gamesession_coord_app"; + private static final String KEY_PREFIX = "session:game:index:issuer:"; + private static final int MAX_SCRIPT_BYTES = 128 * 1024; + private static final long COMMAND_TIMEOUT_MILLIS = 5_000; + private static final List EXPECTED_KEYS = + List.of( + new RedisScriptDescriptor.KeySpec( + "issuerPartition", KEY_PREFIX, RedisScriptDescriptor.HashTagDeclaration.REQUIRED)); + private static final List EXPECTED_ARGUMENTS = + List.of( + new RedisScriptDescriptor.ArgumentSpec("issuerId"), + new RedisScriptDescriptor.ArgumentSpec("partitionId"), + new RedisScriptDescriptor.ArgumentSpec("partitionCount"), + new RedisScriptDescriptor.ArgumentSpec("partitionCapacity"), + new RedisScriptDescriptor.ArgumentSpec("baselineFieldCountAndExactFieldValuePairs"), + new RedisScriptDescriptor.ArgumentSpec( + "registeredLocalOperationCountAndExactOperationTupleAndCurrentPhase"), + new RedisScriptDescriptor.ArgumentSpec( + "targetOperationAndRequiredFieldsAndCapacityCounts")); + private static final List EXPECTED_OUTCOMES = + List.of( + new RedisScriptDescriptor.OutcomeSpec( + "CAPACITY_RESERVED", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "MEMBER_PROJECTED", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "LOCAL_OPERATION_REPLAY", + RedisScriptDescriptor.OutcomeCategory.REPLAY, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "TYPE_TTL_OR_FIELDSET_REFUSED", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "INVALID_ARGUMENTS_OR_CAPACITY", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING)); + + private final RedisClient redisClient; + private final RedisScriptCatalog catalog; + private final CanonicalGameplayIssuerBindingLocalProjectionRepository projectionRepository; + private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentStateSource; + + /** + * Redis client, passive manual descriptor catalog, actual SQL reader, and current source are + * explicit. + */ + public CanonicalGameplayIssuerBindingLocalRedisOwner( + RedisClient redisClient, + RedisScriptCatalog catalog, + CanonicalGameplayIssuerBindingLocalProjectionRepository projectionRepository, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentStateSource) { + this.redisClient = Objects.requireNonNull(redisClient, "Configured Redis client is required"); + this.catalog = Objects.requireNonNull(catalog, "Manual Redis script catalog is required"); + this.projectionRepository = + Objects.requireNonNull(projectionRepository, "Actual SQL projection reader is required"); + this.currentStateSource = + Objects.requireNonNull(currentStateSource, "Fresh issuer source is required"); + } + + /** Writes only the exact target reservation and SQL-qualified target binding field. */ + public Readback projectAndRead(CanonicalGameplayIssuerBindingLocalOperation operation) { + Objects.requireNonNull(operation, "SQL-issued local issuer operation is required"); + try { + requireNoAmbientTransaction(); + var work = projectionRepository.readPreparedPartitionWork(operation); + requireFreshCurrentState(work); + RedisScriptDescriptor descriptor = requireDescriptor(); + byte[] script = scriptSource(descriptor); + byte[] key = exactPartitionKey(work); + byte[][] arguments = scriptArguments(work); + long result = writeOneKey(script, key, arguments); + if (result < 1 || result > 3) { + throw new IllegalStateException( + "Issuer binding-local projection returned script outcome " + result); + } + byte[] readbackBytes = readExactPhysicalState(key, work); + requireFreshCurrentState(work); + projectionRepository.requireStillCurrent(work); + return new Readback(operation, result, readbackBytes); + } catch (RuntimeException failure) { + if (failure instanceof IllegalStateException state + && state.getMessage() != null + && state.getMessage().contains("issuer binding-local projection is unavailable")) { + throw state; + } + throw unavailable(failure); + } + } + + private long writeOneKey(byte[] script, byte[] key, byte[][] arguments) { + requireNoAmbientTransaction(); + try (StatefulRedisConnection connection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(connection); + requirePrincipal(await(commands.aclWhoami())); + String sha = await(commands.scriptLoad(script)); + if (!digest("SHA-1", script).equals(sha)) throw unavailable(); + Long reply = + await(commands.evalsha(sha, ScriptOutputType.INTEGER, new byte[][] {key}, arguments)); + if (reply == null) throw unavailable(); + return reply; + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private byte[] readExactPhysicalState( + byte[] key, + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work) { + requireNoAmbientTransaction(); + try (StatefulRedisConnection connection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(connection); + requirePrincipal(await(commands.aclWhoami())); + if (!"hash".equals(await(commands.type(key))) + || !Long.valueOf(-1L).equals(await(commands.pttl(key)))) { + throw unavailable(); + } + Long length = await(commands.hlen(key)); + int maxFields = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_HASH_FIELDS + + 2 * CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_MEMBER_OPERATIONS; + if (length == null || length < 1 || length > maxFields) throw unavailable(); + Map raw = await(commands.hgetall(key)); + if (raw == null || raw.size() != length) throw unavailable(); + Map actual = new HashMap<>(); + long totalBytes = 0; + for (Map.Entry entry : raw.entrySet()) { + byte[] field = Objects.requireNonNull(entry.getKey(), "Redis field"); + byte[] value = Objects.requireNonNull(entry.getValue(), "Redis value"); + totalBytes = Math.addExact(totalBytes, field.length + (long) value.length); + if (totalBytes + > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_TOTAL_HASH_BYTES) { + throw unavailable(); + } + String encoded = Base64.getEncoder().encodeToString(field); + if (actual.putIfAbsent(encoded, value.clone()) != null) throw unavailable(); + } + + Map baseline = work.baselineFields(); + Map allowed = work.allowedFields(); + if (actual.size() > allowed.size()) throw unavailable(); + for (Map.Entry field : baseline.entrySet()) { + byte[] redisValue = + actual.get( + Base64.getEncoder() + .encodeToString(field.getKey().getBytes(StandardCharsets.UTF_8))); + if (redisValue == null || !Arrays.equals(redisValue, field.getValue())) throw unavailable(); + } + for (Map.Entry field : actual.entrySet()) { + String decodedField = decodeUtf8(Base64.getDecoder().decode(field.getKey())); + byte[] expected = allowed.get(decodedField); + if (expected == null || !Arrays.equals(expected, field.getValue())) throw unavailable(); + } + + var target = work.targetEntry(); + String capacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + target.memberValue().reservation().reservationId()); + byte[] targetCapacity = + actual.get( + Base64.getEncoder() + .encodeToString(capacityField.getBytes(StandardCharsets.US_ASCII))); + if (!Arrays.equals(targetCapacity, target.exactMemberValueBytes())) throw unavailable(); + String bindingField = + new String(target.memberValue().owner().bindingRef().bytes(), StandardCharsets.UTF_8); + byte[] targetBinding = + actual.get( + Base64.getEncoder().encodeToString(bindingField.getBytes(StandardCharsets.UTF_8))); + if (target.bindingPresent()) { + if (!Arrays.equals(targetBinding, target.exactMemberValueBytes())) throw unavailable(); + } else if (targetBinding != null) { + throw unavailable(); + } + + int physicalCapacityCount = 0; + int physicalReservationCount = 0; + int physicalBindingCount = 0; + int qualifiedLocalBindingCount = 0; + for (var entry : work.localEntries()) { + if (entry + .memberValue() + .reservation() + .partitionId() + .equals(work.targetOperation().memberValue().reservation().partitionId()) + && entry.bindingPresent()) { + qualifiedLocalBindingCount++; + } + } + for (var entry : actual.entrySet()) { + String field = decodeUtf8(Base64.getDecoder().decode(entry.getKey())); + byte[] valueBytes = entry.getValue(); + if (field.startsWith( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.RESERVATION_FIELD_PREFIX)) { + var value = CanonicalGameplayIssuerMemberV2Codec.decode(valueBytes); + if (value.reservation().lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED) { + physicalCapacityCount++; + } + physicalReservationCount++; + } else if (!field.equals( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.METADATA_FIELD)) { + CanonicalGameplayIssuerMemberV2Codec.decode(valueBytes); + physicalBindingCount++; + } + } + int baselineCapacityCount = work.baselineProof().physicalCountedCapacityCount(); + int baselineReservationCount = work.baselineProof().physicalReservationCount(); + int baselineBindingCount = work.baselineProof().physicalBindingCount(); + int registeredCapacityCount = + Math.toIntExact( + work.localEntries().stream() + .filter( + entry -> + entry + .memberValue() + .reservation() + .partitionId() + .equals( + work.targetOperation() + .memberValue() + .reservation() + .partitionId()) + && entry.countsTowardCapacity()) + .count()); + int registeredReservationCount = + Math.toIntExact( + work.localEntries().stream() + .filter( + entry -> + entry + .memberValue() + .reservation() + .partitionId() + .equals( + work.targetOperation().memberValue().reservation().partitionId())) + .count()); + if (BigInteger.valueOf(physicalCapacityCount).compareTo(work.anchor().partitionCapacity()) > 0 + || physicalCapacityCount < baselineCapacityCount + 1 + || physicalCapacityCount > baselineCapacityCount + registeredCapacityCount + || physicalReservationCount < baselineReservationCount + 1 + || physicalReservationCount > baselineReservationCount + registeredReservationCount + || physicalBindingCount < baselineBindingCount + || physicalBindingCount > baselineBindingCount + qualifiedLocalBindingCount + || work.partitionCapacity().compareTo(work.anchor().partitionCapacity()) > 0 + || work.aggregateCapacity().compareTo(work.aggregateBound()) > 0) { + throw unavailable(); + } + return CanonicalGameplayIssuerBootstrapCoverageRepository.encodeFieldSet( + decodePhysicalMap(actual)); + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private static Map decodePhysicalMap(Map encoded) { + Map result = new HashMap<>(); + encoded.forEach( + (field, value) -> result.put(decodeUtf8(Base64.getDecoder().decode(field)), value.clone())); + return result; + } + + private void requireFreshCurrentState( + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work) { + requireNoAmbientTransaction(); + var current = currentStateSource.readFreshCurrentState(); + requireNoAmbientTransaction(); + var anchor = work.anchor(); + if (current == null + || !sameCheckpoint(current.accountCheckpoint(), anchor) + || !Arrays.equals( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(current.incarnation()), + anchor.incarnationBytes())) { + throw unavailable(); + } + } + + private RedisScriptDescriptor requireDescriptor() { + try { + RedisScriptDescriptor descriptor = + catalog.require(CanonicalGameplayIssuerBindingLocalRedisScriptContribution.SCRIPT_ID); + if (!CanonicalGameplayIssuerBindingLocalRedisScriptContribution.SCRIPT_ID.equals( + descriptor.scriptId()) + || !CanonicalGameplayIssuerBindingLocalRedisScriptContribution.RESOURCE_PATH.equals( + descriptor.resourcePath()) + || !"game-session-service".equals(descriptor.owner()) + || !PRINCIPAL.equals(descriptor.principal()) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || !EXPECTED_KEYS.equals(descriptor.keys()) + || !EXPECTED_ARGUMENTS.equals(descriptor.arguments()) + || descriptor.category() != RedisScriptDescriptor.ScriptCategory.SESSION_ISSUER_INDEX + || !EXPECTED_OUTCOMES.equals(descriptor.outcomes()) + || descriptor.resetSensitivity() != RedisScriptDescriptor.ResetSensitivity.CLUSTER + || descriptor.lossClass() + != RedisScriptDescriptor.LossClass.EMPTY_REDIS_COLD_START_OR_RESET + || descriptor.compatibilityLevel() + != RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET + || !descriptor + .supportedCoexistence() + .equals(List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "v2"))) + || descriptor.legacyPayloadShape() != null) { + throw unavailable(); + } + return descriptor; + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private static byte[] scriptSource(RedisScriptDescriptor descriptor) { + try (InputStream input = + CanonicalGameplayIssuerBindingLocalRedisOwner.class + .getClassLoader() + .getResourceAsStream(descriptor.resourcePath())) { + if (input == null) throw unavailable(); + byte[] bytes = input.readNBytes(MAX_SCRIPT_BYTES + 1); + if (bytes.length == 0 + || bytes.length > MAX_SCRIPT_BYTES + || !descriptor.sha256().equals(digest("SHA-256", bytes))) { + throw unavailable(); + } + return bytes; + } catch (IOException | RuntimeException failure) { + throw unavailable(failure); + } + } + + private static byte[] exactPartitionKey( + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work) { + String key = CanonicalGameplayIssuerRedisKeys.forMember(work.targetOperation().memberValue()); + if (!key.startsWith(KEY_PREFIX) || key.length() > 512) throw unavailable(); + return key.getBytes(StandardCharsets.US_ASCII); + } + + private static byte[][] scriptArguments( + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work) { + var anchor = work.anchor(); + Map baseline = work.baselineFields(); + List> baselineEntries = + baseline.entrySet().stream().sorted(Map.Entry.comparingByKey()).toList(); + List arguments = new ArrayList<>(); + arguments.add(ascii(anchor.issuerId())); + arguments.add( + ascii(work.targetOperation().memberValue().reservation().partitionId().toString())); + arguments.add(ascii(anchor.partitionCount().toString())); + arguments.add(ascii(anchor.partitionCapacity().toString())); + arguments.add(ascii(Integer.toString(baselineEntries.size()))); + for (Map.Entry field : baselineEntries) { + arguments.add(field.getKey().getBytes(StandardCharsets.UTF_8)); + arguments.add(field.getValue()); + } + List entries = + work.localEntries().stream() + .filter( + entry -> + entry + .memberValue() + .reservation() + .partitionId() + .equals(work.targetOperation().memberValue().reservation().partitionId())) + .sorted(java.util.Comparator.comparing(entry -> entry.operationId().toString())) + .toList(); + arguments.add(ascii(Integer.toString(entries.size()))); + for (var entry : entries) { + arguments.add(ascii(entry.operationId().toString())); + arguments.add(entry.memberValue().owner().bindingRef().bytes()); + arguments.add(ascii(entry.memberValue().reservation().reservationId().toString())); + arguments.add(entry.exactMemberValueBytes()); + arguments.add(ascii(entry.bindingPresent() ? "1" : "0")); + arguments.add(ascii(entry.countsTowardCapacity() ? "1" : "0")); + } + var target = work.targetEntry(); + arguments.add(ascii(target.operationId().toString())); + arguments.add(ascii(target.memberValue().reservation().reservationId().toString())); + arguments.add(target.memberValue().owner().bindingRef().bytes()); + arguments.add(target.exactMemberValueBytes()); + arguments.add(ascii(target.bindingPresent() ? "1" : "0")); + arguments.add(ascii(work.partitionCapacity().toString())); + arguments.add(ascii(work.aggregateCapacity().toString())); + arguments.add(ascii(work.aggregateBound().toString())); + return arguments.toArray(byte[][]::new); + } + + private static boolean sameCheckpoint( + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint current, + CanonicalGameplayIssuerInstalledAnchor anchor) { + return current != null + && current.issuerId().equals(anchor.issuerId()) + && current.issuerAuthGeneration().equals(anchor.issuerAuthGeneration()) + && Arrays.equals(current.exactCheckpointBytes(), anchor.sourceCheckpointBytes()) + && current.checkpointDigest().equals(anchor.sourceCheckpointDigest()) + && Arrays.equals(current.latestIssuerEventBytes(), anchor.sourceEventBytes()) + && Objects.equals(current.latestIssuerEventDigest(), anchor.sourceEventDigest()); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static String decodeUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw unavailable(malformed); + } + } + + private static RedisAsyncCommands requireCommands( + StatefulRedisConnection connection) { + if (connection == null || !connection.isOpen()) throw unavailable(); + return connection.async(); + } + + private static void requirePrincipal(String principal) { + if (!PRINCIPAL.equals(principal)) throw unavailable(); + } + + private static T await(RedisFuture future) { + try { + return future.get(COMMAND_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + future.cancel(true); + throw unavailable(interrupted); + } catch (ExecutionException | TimeoutException | RuntimeException failure) { + future.cancel(true); + throw unavailable(failure); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + } + + private static String digest(String algorithm, byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(bytes)); + } catch (Exception failure) { + throw unavailable(failure); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Issuer binding-local projection is unavailable"); + } + + private static IllegalStateException unavailable(Throwable cause) { + return new IllegalStateException("Issuer binding-local projection is unavailable", cause); + } + + /** + * Exact SQL operation plus independent physical readback; no acknowledgement or admission claim. + */ + public static final class Readback { + private final CanonicalGameplayIssuerBindingLocalOperation operation; + private final long scriptOutcome; + private final byte[] exactReadbackBytes; + + private Readback( + CanonicalGameplayIssuerBindingLocalOperation operation, + long scriptOutcome, + byte[] exactReadbackBytes) { + this.operation = Objects.requireNonNull(operation, "operation"); + this.scriptOutcome = scriptOutcome; + this.exactReadbackBytes = + Objects.requireNonNull(exactReadbackBytes, "exactReadbackBytes").clone(); + } + + public CanonicalGameplayIssuerBindingLocalOperation operation() { + return operation; + } + + public long scriptOutcome() { + return scriptOutcome; + } + + public byte[] exactReadbackBytes() { + return exactReadbackBytes.clone(); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwner.java index c6aa5d1e03..84169b204d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwner.java @@ -24,8 +24,7 @@ public CanonicalGameplayIssuerBootstrapCoverageOwner( CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource currentStateSource) { this.dsl = Objects.requireNonNull(dsl, "dsl"); - this.partitionRedisOwner = - Objects.requireNonNull(partitionRedisOwner, "partitionRedisOwner"); + this.partitionRedisOwner = Objects.requireNonNull(partitionRedisOwner, "partitionRedisOwner"); this.currentStateSource = Objects.requireNonNull(currentStateSource, "currentStateSource"); } @@ -53,8 +52,7 @@ public CanonicalGameplayIssuerInstalledAnchor completeInitialBootstrap( coverageRepository.readInstalledAnchor( bootstrapOperationId, bootstrapRequestId, initialState); if (installed.isPresent()) { - return readInstalledAnchorPartitions( - plan, installed.get(), coverageRepository, initialState); + return readInstalledAnchorPartitions(plan, installed.get(), coverageRepository, initialState); } CanonicalGameplayIssuerBootstrapMemberOperationRepository memberOperationRepository = @@ -119,7 +117,8 @@ private CanonicalGameplayIssuerInstalledAnchor readInstalledAnchorPartitions( coverageRepository .readInstalledAnchor( installed.bootstrapOperationId(), installed.bootstrapRequestId(), afterReadback) - .orElseThrow(() -> unavailable("Installed issuer anchor disappeared during exact readback")); + .orElseThrow( + () -> unavailable("Installed issuer anchor disappeared during exact readback")); if (!Arrays.equals(installed.exactAnchorBytes(), confirmed.exactAnchorBytes()) || !installed.exactAnchorDigest().equals(confirmed.exactAnchorDigest())) { throw unavailable("Installed issuer anchor changed during physical partition readback"); @@ -145,7 +144,8 @@ private CanonicalGameplayIssuerInstalledAnchor readInstalledAnchorPartitions( CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(current.incarnation()), CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(expected.incarnation())) || !sameCheckpoint(current.accountCheckpoint(), expected.accountCheckpoint())) { - throw unavailable("Current Account source or stable Redis incarnation changed during bootstrap"); + throw unavailable( + "Current Account source or stable Redis incarnation changed during bootstrap"); } return current; } @@ -220,12 +220,14 @@ private static void requireSamePlan( private static void requireNonNil(UUID value, String name) { Objects.requireNonNull(value, name); - if (value.equals(new UUID(0L, 0L))) throw new IllegalArgumentException(name + " must not be nil"); + if (value.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException(name + " must not be nil"); } private static void requireNoAmbientTransaction() { if (TransactionSynchronizationManager.isActualTransactionActive()) { - throw unavailable("Initial issuer bootstrap completion cannot join an ambient SQL transaction"); + throw unavailable( + "Initial issuer bootstrap completion cannot join an ambient SQL transaction"); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java index dee6a30666..69100f7480 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java @@ -22,8 +22,8 @@ import java.util.Set; import java.util.UUID; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; import org.jooq.DSLContext; import org.jooq.Record; @@ -32,7 +32,8 @@ /** SQL owner for exact per-partition proof retention and one local initial anchor installation. */ final class CanonicalGameplayIssuerBootstrapCoverageRepository { private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; - private static final String OPERATION = "game_session_canonical_issuer_bootstrap_member_operation"; + private static final String OPERATION = + "game_session_canonical_issuer_bootstrap_member_operation"; private static final String PROOF = "game_session_canonical_issuer_bootstrap_partition_proof"; private static final String COUNTER = "game_session_canonical_issuer_bootstrap_coverage_counter"; private static final String ANCHOR = "game_session_canonical_issuer_installed_anchor"; @@ -67,7 +68,9 @@ void recordPartitionProof(CanonicalGameplayIssuerBootstrapPartitionRedisOwner.Re requireProofContext(input, currentPlan); Record existing = transaction.fetchOne( - "SELECT * FROM " + PROOF + " WHERE bootstrap_operation_id = ? AND partition_id = ? FOR UPDATE", + "SELECT * FROM " + + PROOF + + " WHERE bootstrap_operation_id = ? AND partition_id = ? FOR UPDATE", currentPlan.bootstrapIntent().operationId(), input.partitionId()); if (existing != null) { @@ -76,7 +79,9 @@ void recordPartitionProof(CanonicalGameplayIssuerBootstrapPartitionRedisOwner.Re } int inserted = transaction.execute( - "INSERT INTO " + PROOF + " (" + "INSERT INTO " + + PROOF + + " (" + "build_operation_id, bootstrap_operation_id, bootstrap_request_id, issuer_id, " + "build_plan_digest, bootstrap_operation_fence, bootstrap_coverage_fence, " + "issuer_inventory_snapshot_revision, layout_version, partition_count, " @@ -120,10 +125,13 @@ void recordPartitionProof(CanonicalGameplayIssuerBootstrapPartitionRedisOwner.Re if (inserted != 1) throw conflict("Exact partition proof did not persist"); Record saved = transaction.fetchOne( - "SELECT * FROM " + PROOF + " WHERE bootstrap_operation_id = ? AND partition_id = ?", + "SELECT * FROM " + + PROOF + + " WHERE bootstrap_operation_id = ? AND partition_id = ?", input.bootstrapOperationId(), input.partitionId()); - if (saved == null) throw conflict("Exact partition proof is unreadable after persistence"); + if (saved == null) + throw conflict("Exact partition proof is unreadable after persistence"); requireSameProof(saved, input); }); } @@ -157,6 +165,163 @@ Optional readInstalledAnchor( }); } + /** + * Requalifies an installed anchor while the binding inventory clock is already locked. The caller + * must acquire that clock before entering this method so the issuer-control lock remains second + * in the shared inventory -> issuer -> account order. + */ + static CanonicalGameplayIssuerInstalledAnchor + readInstalledAnchorForBindingPreparationInTransaction( + DSLContext transaction, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState) { + Objects.requireNonNull(transaction, "transaction"); + Objects.requireNonNull(currentState, "currentState"); + + Record control = + transaction.fetchOne( + "SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (control == null + || !ISSUER.equals(requireText(control, "issuer_id")) + || !"INITIAL_BOOTSTRAP_INTENT".equals(requireText(control, "state"))) { + throw conflict("Ordinary NEW requires the positive current installed issuer-control row"); + } + UUID currentOperationId = requireUuid(control, "current_operation_id"); + BigInteger controlEpoch = readInteger(control, "control_epoch"); + BigInteger operationFence = readInteger(control, "current_operation_fence"); + BigInteger coverageFence = readInteger(control, "current_coverage_fence"); + if (controlEpoch.signum() <= 0 + || !controlEpoch.equals(operationFence) + || coverageFence.signum() <= 0 + || coverageFence.equals(operationFence) + || readInteger(control, "last_issued_fence").compareTo(coverageFence) < 0) { + throw conflict("Current issuer-control tuple is malformed or no longer positive"); + } + + List issuerIntents = + transaction.fetch( + "SELECT operation_id FROM " + + "game_session_canonical_issuer_layout_bootstrap_intent" + + " WHERE issuer_id = ? ORDER BY operation_id FOR UPDATE", + ISSUER); + if (issuerIntents.size() != 1 + || !currentOperationId.equals(requireUuid(issuerIntents.get(0), "operation_id"))) { + throw conflict("A conflicting or unpointed issuer layout intent prevents ordinary NEW"); + } + + Record intentRequest = + transaction.fetchOne( + "SELECT request_id FROM " + + "game_session_canonical_issuer_layout_bootstrap_intent" + + " WHERE operation_id = ? AND issuer_id = ?", + currentOperationId, + ISSUER); + if (intentRequest == null) + throw conflict("Current issuer control points to no durable layout intent"); + CanonicalGameplayIssuerPartitionBuildPlan plan = + new CanonicalGameplayIssuerPartitionBuildRepository(transaction) + .readInstalledPlanForAnchorInTransaction( + transaction, currentOperationId, requireUuid(intentRequest, "request_id")); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); + if (!currentOperationId.equals(intent.operationId()) + || !controlEpoch.equals(intent.controlEpoch()) + || !operationFence.equals(intent.operationFence()) + || !coverageFence.equals(intent.coverageFence())) { + throw conflict("Current issuer control no longer points at its exact initial intent tuple"); + } + requireCurrentState(currentState, intent); + + Record anchorRow = + transaction.fetchOne("SELECT * FROM " + ANCHOR + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (anchorRow == null) { + throw conflict("Ordinary NEW requires an actual immutable installed issuer anchor"); + } + CanonicalGameplayIssuerInstalledAnchor actual = loadAnchor(anchorRow); + requireAnchorMatchesPlan(actual, plan, currentState); + requireProofSummaryMatchesAnchor( + verifyCompleteProof(transaction, plan, actual.incarnationBytes()), actual); + requireCounterCoversAnchor(transaction, actual); + return actual; + } + + /** Exact immutable baseline field set for one partition of the installed initial anchor. */ + static InstalledAnchorPartitionProof readInstalledAnchorPartitionProof( + DSLContext transaction, + CanonicalGameplayIssuerInstalledAnchor anchor, + BigInteger partitionId) { + Objects.requireNonNull(transaction, "transaction"); + Objects.requireNonNull(anchor, "anchor"); + Objects.requireNonNull(partitionId, "partitionId"); + if (partitionId.signum() < 0 || partitionId.compareTo(anchor.partitionCount()) >= 0) { + throw conflict("Candidate partition is outside the exact installed layout"); + } + Record row = + transaction.fetchOne( + "SELECT * FROM " + PROOF + " WHERE bootstrap_operation_id = ? AND partition_id = ?", + anchor.bootstrapOperationId(), + new BigDecimal(partitionId)); + if (row == null + || !"EXACT_PHYSICAL_READBACK".equals(requireText(row, "proof_state")) + || !anchor.operationFence().equals(readInteger(row, "bootstrap_operation_fence")) + || !anchor.coverageFence().equals(readInteger(row, "bootstrap_coverage_fence")) + || !anchor + .issuerInventorySnapshotRevision() + .equals(readInteger(row, "issuer_inventory_snapshot_revision"))) { + throw conflict("Exact installed-anchor partition proof is missing or mismatched"); + } + byte[] fieldSetBytes = requireBytes(row, "exact_physical_field_set_bytes"); + String fieldSetDigest = requireText(row, "exact_physical_field_set_digest"); + if (!fieldSetDigest.equals(CanonicalGameplayIssuerMemberV2Codec.sha256(fieldSetBytes))) { + throw conflict("Installed-anchor partition field set does not match its exact digest"); + } + return new InstalledAnchorPartitionProof( + partitionId, + fieldSetBytes, + fieldSetDigest, + readInt(row, "physical_counted_capacity_count"), + readInt(row, "physical_reservation_count"), + readInt(row, "physical_binding_count")); + } + + /** Refuses a post-anchor candidate whose exact field already exists in the frozen baseline. */ + static void requireNewMemberAbsentFromBaseline( + InstalledAnchorPartitionProof proof, + CanonicalGameplayBindingRef bindingRef, + UUID reservationId) { + Objects.requireNonNull(proof, "proof"); + Objects.requireNonNull(bindingRef, "bindingRef"); + Objects.requireNonNull(reservationId, "reservationId"); + Map fields = decodeFieldSet(proof.exactPhysicalFieldSetBytes()); + if (fields.containsKey(new String(bindingRef.bytes(), StandardCharsets.UTF_8)) + || fields.containsKey(CAPACITY_PREFIX + reservationId)) { + throw conflict( + "Installed issuer baseline already contains the requested NEW member or reservation"); + } + } + + record InstalledAnchorPartitionProof( + BigInteger partitionId, + byte[] exactPhysicalFieldSetBytes, + String exactPhysicalFieldSetDigest, + int physicalCountedCapacityCount, + int physicalReservationCount, + int physicalBindingCount) { + InstalledAnchorPartitionProof { + Objects.requireNonNull(partitionId, "partitionId"); + exactPhysicalFieldSetBytes = Objects.requireNonNull(exactPhysicalFieldSetBytes).clone(); + Objects.requireNonNull(exactPhysicalFieldSetDigest, "exactPhysicalFieldSetDigest"); + if (physicalCountedCapacityCount < 0 + || physicalReservationCount < 0 + || physicalBindingCount < 0) { + throw new IllegalArgumentException("Installed partition proof counts must be nonnegative"); + } + } + + @Override + public byte[] exactPhysicalFieldSetBytes() { + return exactPhysicalFieldSetBytes.clone(); + } + } + void verifyExistingPartitionProof( CanonicalGameplayIssuerBootstrapPartitionRedisOwner.Readback readback) { Objects.requireNonNull(readback, "readback"); @@ -176,7 +341,9 @@ void verifyExistingPartitionProof( requireProofContext(input, currentPlan); Record row = transaction.fetchOne( - "SELECT * FROM " + PROOF + " WHERE bootstrap_operation_id = ? AND partition_id = ?", + "SELECT * FROM " + + PROOF + + " WHERE bootstrap_operation_id = ? AND partition_id = ?", input.bootstrapOperationId(), input.partitionId()); if (row == null) throw conflict("Installed anchor is missing an exact partition proof"); @@ -225,7 +392,9 @@ CanonicalGameplayIssuerInstalledAnchor installInitialAnchor( createAnchor(plan, currentState, generation, proof); int inserted = transaction.execute( - "INSERT INTO " + ANCHOR + " (" + "INSERT INTO " + + ANCHOR + + " (" + "issuer_id, bootstrap_operation_id, bootstrap_request_id, build_operation_id, " + "build_plan_digest, control_epoch, issuer_coverage_operation_id, operation_fence, " + "coverage_fence, issuer_inventory_snapshot_revision, layout_version, partition_count, " @@ -236,10 +405,14 @@ CanonicalGameplayIssuerInstalledAnchor installInitialAnchor( + "physical_binding_count, aggregate_counted_capacity, partition_proof_root_digest, " + "exact_anchor_bytes, exact_anchor_digest, anchor_state) " + "SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'INITIAL_INSTALLED' " - + "FROM " + CONTROL + " c WHERE c.issuer_id = ? AND c.state = 'INITIAL_BOOTSTRAP_INTENT' " + + "FROM " + + CONTROL + + " c WHERE c.issuer_id = ? AND c.state = 'INITIAL_BOOTSTRAP_INTENT' " + "AND c.control_epoch = ? AND c.current_operation_id = ? " + "AND c.current_operation_fence = ? AND c.current_coverage_fence = ? " - + "AND NOT EXISTS (SELECT 1 FROM " + ANCHOR + " a WHERE a.issuer_id = c.issuer_id)", + + "AND NOT EXISTS (SELECT 1 FROM " + + ANCHOR + + " a WHERE a.issuer_id = c.issuer_id)", anchor.issuerId(), anchor.bootstrapOperationId(), anchor.bootstrapRequestId(), @@ -278,8 +451,7 @@ CanonicalGameplayIssuerInstalledAnchor installInitialAnchor( intent.coverageFence()); if (inserted != 1) throw conflict("Exact initial issuer anchor compare-and-set refused"); Record saved = - transaction.fetchOne( - "SELECT * FROM " + ANCHOR + " WHERE issuer_id = ?", ISSUER); + transaction.fetchOne("SELECT * FROM " + ANCHOR + " WHERE issuer_id = ?", ISSUER); if (saved == null) throw conflict("Installed issuer anchor is unreadable after its CAS"); CanonicalGameplayIssuerInstalledAnchor result = loadAnchor(saved); requireSameAnchor(result, anchor); @@ -293,7 +465,8 @@ private CanonicalGameplayIssuerInstalledAnchor createAnchor( BigInteger generation, ProofSummary proof) { CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); - CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor layout = intent.layoutDescriptor(); + CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor layout = + intent.layoutDescriptor(); CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint source = intent.sourceCheckpoint(); byte[] incarnationBytes = @@ -332,7 +505,7 @@ private CanonicalGameplayIssuerInstalledAnchor createAnchor( null); } - private ProofSummary verifyCompleteProof( + private static ProofSummary verifyCompleteProof( DSLContext transaction, CanonicalGameplayIssuerPartitionBuildPlan plan, byte[] expectedIncarnationBytes) { @@ -346,10 +519,12 @@ private ProofSummary verifyCompleteProof( intent.operationId()); BigInteger partitionCount = intent.layoutDescriptor().partitionCount(); if (!BigInteger.valueOf(proofRows.size()).equals(partitionCount)) { - throw conflict("Initial issuer anchor requires one positive physical proof per finite partition"); + throw conflict( + "Initial issuer anchor requires one positive physical proof per finite partition"); } - Map worksByOrdinal = new HashMap<>(); + Map worksByOrdinal = + new HashMap<>(); Map exactOperationValues = new HashMap<>(); Map expectedReservationsByPartition = new HashMap<>(); Map expectedCapacityByPartition = new HashMap<>(); @@ -365,10 +540,13 @@ private ProofSummary verifyCompleteProof( } List operations = transaction.fetch( - "SELECT * FROM " + OPERATION + " WHERE bootstrap_operation_id = ? ORDER BY work_ordinal", + "SELECT * FROM " + + OPERATION + + " WHERE bootstrap_operation_id = ? ORDER BY work_ordinal", intent.operationId()); if (operations.size() != plan.memberWorks().size()) { - throw conflict("Finite coverage cannot complete while any SQL member operation is unresolved"); + throw conflict( + "Finite coverage cannot complete while any SQL member operation is unresolved"); } for (Record operation : operations) { long ordinal = requireNonNegativeLong(operation, "work_ordinal"); @@ -389,7 +567,8 @@ private ProofSummary verifyCompleteProof( if (exactOperationValues.putIfAbsent(work.reservationId(), bytes) != null) { throw conflict("Finite SQL work contains a duplicate reservation identity"); } - if (Boolean.TRUE.equals(operation.get("expected_binding_present", Boolean.class))) expectedBindingCount++; + if (Boolean.TRUE.equals(operation.get("expected_binding_present", Boolean.class))) + expectedBindingCount++; } BigInteger expectedPartition = BigInteger.ZERO; @@ -397,22 +576,27 @@ private ProofSummary verifyCompleteProof( BigInteger bindingCount = BigInteger.ZERO; BigInteger aggregateCountedCapacity = BigInteger.ZERO; BigInteger expectedAggregateCapacity = BigInteger.valueOf(expectedCapacityCount); - BigInteger aggregateBound = partitionCount.multiply(intent.layoutDescriptor().partitionCapacity()); + BigInteger aggregateBound = + partitionCount.multiply(intent.layoutDescriptor().partitionCapacity()); MessageDigest root = sha256Digest(); for (Record row : proofRows) { BigInteger partitionId = readInteger(row, "partition_id"); if (!partitionId.equals(expectedPartition)) { - throw conflict("Initial issuer physical proof set is not the exact contiguous finite range"); + throw conflict( + "Initial issuer physical proof set is not the exact contiguous finite range"); } requireProofMatchesPlan(row, plan, expectedIncarnationBytes, partitionId); - int expectedPartitionReservations = expectedReservationsByPartition.getOrDefault(partitionId, 0); + int expectedPartitionReservations = + expectedReservationsByPartition.getOrDefault(partitionId, 0); int expectedPartitionCapacity = expectedCapacityByPartition.getOrDefault(partitionId, 0); - Map fields = decodeFieldSet(requireBytes(row, "exact_physical_field_set_bytes")); + Map fields = + decodeFieldSet(requireBytes(row, "exact_physical_field_set_bytes")); byte[] metadata = fields.get(METADATA_FIELD); if (metadata == null || !Arrays.equals(metadata, requireBytes(row, "exact_metadata_bytes"))) { throw conflict("Partition proof does not retain its exact common physical metadata"); } - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.requireExactMetadata(metadata, metadata); + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.requireExactMetadata( + metadata, metadata); Set reservationIds = new HashSet<>(); int physicalBindings = 0; int physicalCapacity = 0; @@ -457,7 +641,9 @@ private ProofSummary verifyCompleteProof( } else { CanonicalGameplayBindingRef bindingRef; try { - bindingRef = CanonicalGameplayBindingRef.fromExactBytes(fieldName.getBytes(StandardCharsets.UTF_8)); + bindingRef = + CanonicalGameplayBindingRef.fromExactBytes( + fieldName.getBytes(StandardCharsets.UTF_8)); } catch (RuntimeException malformed) { throw conflict("Physical issuer binding field has invalid canonical identity"); } @@ -469,7 +655,9 @@ private ProofSummary verifyCompleteProof( } } expectedFieldNames.addAll( - reservationIds.stream().map(CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec::reservationField).toList()); + reservationIds.stream() + .map(CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec::reservationField) + .toList()); if (!expectedFieldNames.equals(fields.keySet()) || physicalReservations != expectedPartitionReservations || physicalCapacity != expectedPartitionCapacity @@ -478,18 +666,24 @@ private ProofSummary verifyCompleteProof( || physicalBindings != readInt(row, "physical_binding_count") || physicalCapacity != readInt(row, "physical_counted_capacity_count") || fields.size() != readInt(row, "physical_field_count") - || !expectedAggregateCapacity.equals(readInteger(row, "planned_aggregate_capacity_count"))) { + || !expectedAggregateCapacity.equals( + readInteger(row, "planned_aggregate_capacity_count"))) { throw conflict("Physical partition proof differs from SQL work or capacity expectations"); } - if (BigInteger.valueOf(physicalCapacity).compareTo(intent.layoutDescriptor().partitionCapacity()) > 0) { + if (BigInteger.valueOf(physicalCapacity) + .compareTo(intent.layoutDescriptor().partitionCapacity()) + > 0) { throw conflict("Physical issuer partition exceeds its pinned reservation capacity"); } reservationCount = reservationCount.add(BigInteger.valueOf(physicalReservations)); bindingCount = bindingCount.add(BigInteger.valueOf(physicalBindings)); aggregateCountedCapacity = aggregateCountedCapacity.add(BigInteger.valueOf(physicalCapacity)); updateRoot(root, partitionId.toString().getBytes(StandardCharsets.US_ASCII)); - updateRoot(root, CanonicalGameplayIssuerMemberV2Codec.sha256( - requireBytes(row, "exact_physical_field_set_bytes")).getBytes(StandardCharsets.US_ASCII)); + updateRoot( + root, + CanonicalGameplayIssuerMemberV2Codec.sha256( + requireBytes(row, "exact_physical_field_set_bytes")) + .getBytes(StandardCharsets.US_ASCII)); expectedPartition = expectedPartition.add(BigInteger.ONE); } if (!expectedPartition.equals(partitionCount) @@ -497,7 +691,8 @@ private ProofSummary verifyCompleteProof( || !bindingCount.equals(BigInteger.valueOf(expectedBindingCount)) || !aggregateCountedCapacity.equals(expectedAggregateCapacity) || aggregateCountedCapacity.compareTo(aggregateBound) > 0) { - throw conflict("Initial issuer proof does not cover complete reservation and aggregate capacity"); + throw conflict( + "Initial issuer proof does not cover complete reservation and aggregate capacity"); } return new ProofSummary( proofRows.size(), @@ -531,8 +726,7 @@ private static void requireOperationMatches( var reservation = value.reservation(); var anchor = value.anchor(); var operation = value.memberOperation(); - if (!requireUuid(row, "member_operation_id").equals(work.memberOperationId()) - || !requireUuid(row, "bootstrap_operation_id").equals(intent.operationId()) + if (!requireUuid(row, "bootstrap_operation_id").equals(intent.operationId()) || !requireUuid(row, "bootstrap_request_id").equals(intent.requestId()) || !requireUuid(row, "build_operation_id").equals(plan.buildOperationId()) || !plan.planDigest().equals(requireText(row, "build_plan_digest")) @@ -555,7 +749,9 @@ private static void requireOperationMatches( || !reservation.transitionId().equals(work.transitionId()) || !reservation.partitionId().equals(work.plannedPartitionId()) || !reservation.issuerCoverageOperationId().equals(work.originalIssuerCoverageOperationId()) - || !reservation.issuerCoverageOperationFence().equals(work.originalIssuerCoverageOperationFence()) + || !reservation + .issuerCoverageOperationFence() + .equals(work.originalIssuerCoverageOperationFence()) || !reservation.coverageFence().equals(work.originalCoverageFence()) || !reservation.inventorySnapshotRevision().equals(work.originalInventorySnapshotRevision()) || !work.reservationLifecycle().equals(reservation.lifecycle().name()) @@ -565,21 +761,32 @@ private static void requireOperationMatches( || !anchor.coverageFence().equals(intent.coverageFence()) || !anchor.issuerInventorySnapshotRevision().equals(intent.inventorySnapshotRevision()) || !value.issuerControlEpoch().equals(intent.controlEpoch()) - || !Arrays.equals(value.layoutDescriptor().exactDescriptorBytes(), intent.layoutDescriptor().exactDescriptorBytes()) + || !Arrays.equals( + value.layoutDescriptor().exactDescriptorBytes(), + intent.layoutDescriptor().exactDescriptorBytes()) || !Arrays.equals(work.bindingRef(), value.owner().bindingRef().bytes()) - || !Boolean.valueOf(work.countsTowardCapacity()).equals(row.get("counts_toward_capacity", Boolean.class)) - || !Boolean.valueOf(isBindingPresent(row)).equals(row.get("expected_binding_present", Boolean.class)) + || !Boolean.valueOf(work.countsTowardCapacity()) + .equals(row.get("counts_toward_capacity", Boolean.class)) + || !Boolean.valueOf(isBindingPresent(row)) + .equals(row.get("expected_binding_present", Boolean.class)) || !work.reservationId().equals(requireUuid(row, "reservation_id")) - || !work.reservationSourceRowDigest().equals(requireText(row, "reservation_source_row_digest")) - || !work.originalIssuerCoverageOperationId().equals(requireUuid(row, "original_issuer_coverage_operation_id")) - || !work.originalIssuerCoverageOperationFence().equals(readInteger(row, "original_issuer_coverage_operation_fence")) + || !work.reservationSourceRowDigest() + .equals(requireText(row, "reservation_source_row_digest")) + || !work.originalIssuerCoverageOperationId() + .equals(requireUuid(row, "original_issuer_coverage_operation_id")) + || !work.originalIssuerCoverageOperationFence() + .equals(readInteger(row, "original_issuer_coverage_operation_fence")) || !work.originalCoverageFence().equals(readInteger(row, "original_coverage_fence")) - || !work.originalInventorySnapshotRevision().equals(readInteger(row, "original_inventory_snapshot_revision")) + || !work.originalInventorySnapshotRevision() + .equals(readInteger(row, "original_inventory_snapshot_revision")) || !intent.operationId().equals(requireUuid(row, "bootstrap_anchor_operation_id")) || !intent.operationFence().equals(readInteger(row, "bootstrap_anchor_operation_fence")) || !intent.coverageFence().equals(readInteger(row, "bootstrap_anchor_coverage_fence")) - || !intent.inventorySnapshotRevision().equals(readInteger(row, "bootstrap_anchor_inventory_snapshot_revision"))) { - throw conflict("SQL member operation does not match its exact reservation, anchor, and plan tuple"); + || !intent + .inventorySnapshotRevision() + .equals(readInteger(row, "bootstrap_anchor_inventory_snapshot_revision"))) { + throw conflict( + "SQL member operation does not match its exact reservation, anchor, and plan tuple"); } } @@ -600,19 +807,25 @@ private static void requireProofMatchesPlan( || !plan.planDigest().equals(requireText(row, "build_plan_digest")) || !intent.operationFence().equals(readInteger(row, "bootstrap_operation_fence")) || !intent.coverageFence().equals(readInteger(row, "bootstrap_coverage_fence")) - || !intent.inventorySnapshotRevision().equals(readInteger(row, "issuer_inventory_snapshot_revision")) + || !intent + .inventorySnapshotRevision() + .equals(readInteger(row, "issuer_inventory_snapshot_revision")) || !layout.layoutVersion().equals(readInteger(row, "layout_version")) || !layout.partitionCount().equals(readInteger(row, "partition_count")) || !layout.partitionCapacity().equals(readInteger(row, "partition_capacity")) || !layout.mappingIdentity().equals(requireText(row, "mapping_identity")) - || !Arrays.equals(layout.exactDescriptorBytes(), requireBytes(row, "layout_descriptor_bytes")) + || !Arrays.equals( + layout.exactDescriptorBytes(), requireBytes(row, "layout_descriptor_bytes")) || !layout.descriptorDigest().equals(requireText(row, "layout_descriptor_digest")) - || !Arrays.equals(source.exactCheckpointBytes(), requireBytes(row, "source_checkpoint_bytes")) + || !Arrays.equals( + source.exactCheckpointBytes(), requireBytes(row, "source_checkpoint_bytes")) || !source.checkpointDigest().equals(requireText(row, "source_checkpoint_digest")) || !Arrays.equals(expectedEvent, optionalBytes(row, "source_event_bytes")) - || !Objects.equals(source.latestIssuerEventDigest(), row.get("source_event_digest", String.class)) + || !Objects.equals( + source.latestIssuerEventDigest(), row.get("source_event_digest", String.class)) || !Arrays.equals(expectedIncarnationBytes, exactIncarnation) - || !CanonicalGameplayIssuerMemberV2Codec.sha256(exactIncarnation).equals(requireText(row, "incarnation_digest")) + || !CanonicalGameplayIssuerMemberV2Codec.sha256(exactIncarnation) + .equals(requireText(row, "incarnation_digest")) || !partitionId.equals(readInteger(row, "partition_id")) || !"EXACT_PHYSICAL_READBACK".equals(requireText(row, "proof_state"))) { throw conflict("Persisted physical proof differs from the exact current plan tuple"); @@ -671,7 +884,8 @@ private static void requireAnchorMatchesPlan( || !Objects.equals(anchor.sourceEventDigest(), source.latestIssuerEventDigest()) || !Arrays.equals(anchor.incarnationBytes(), currentIncarnation) || !sameCheckpoint(current.accountCheckpoint(), source)) { - throw conflict("Installed issuer anchor does not match the exact current source and initial layout"); + throw conflict( + "Installed issuer anchor does not match the exact current source and initial layout"); } } @@ -694,7 +908,7 @@ private static void requireCounterCoversAnchor( anchor.issuerId()); if (counter == null || readInteger(counter, "last_issued_coverage_generation") - .compareTo(anchor.globalCoverageGeneration()) + .compareTo(anchor.globalCoverageGeneration()) < 0) { throw conflict("Installed anchor generation is beyond the current global issuer counter"); } @@ -711,7 +925,8 @@ private static void requireSameAnchor( CanonicalGameplayIssuerInstalledAnchor expected) { if (!Arrays.equals(actual.exactAnchorBytes(), expected.exactAnchorBytes()) || !actual.exactAnchorDigest().equals(expected.exactAnchorDigest())) { - throw conflict("Installed issuer anchor readback differs from its exact owner-issued pointer"); + throw conflict( + "Installed issuer anchor readback differs from its exact owner-issued pointer"); } } @@ -756,7 +971,9 @@ private static CanonicalGameplayIssuerInstalledAnchor loadAnchor(Record row) { private BigInteger allocateGlobalCoverageGeneration(DSLContext transaction) { transaction.execute( - "INSERT INTO " + COUNTER + " (issuer_id, last_issued_coverage_generation, counter_version) " + "INSERT INTO " + + COUNTER + + " (issuer_id, last_issued_coverage_generation, counter_version) " + "VALUES (?, 0, 0) ON CONFLICT (issuer_id) DO NOTHING", ISSUER); Record counter = @@ -766,10 +983,12 @@ private BigInteger allocateGlobalCoverageGeneration(DSLContext transaction) { BigInteger previous = readInteger(counter, "last_issued_coverage_generation"); long version = requireNonNegativeLong(counter, "counter_version"); BigInteger next = previous.add(BigInteger.ONE); - if (next.toString().length() > 256) throw conflict("Global issuer coverage generation is outside its bound"); + if (next.toString().length() > 256) + throw conflict("Global issuer coverage generation is outside its bound"); int updated = transaction.execute( - "UPDATE " + COUNTER + "UPDATE " + + COUNTER + " SET last_issued_coverage_generation = ?, counter_version = ?, updated_at = CURRENT_TIMESTAMP " + "WHERE issuer_id = ? AND last_issued_coverage_generation = ? AND counter_version = ?", next, @@ -795,8 +1014,11 @@ private static ProofInput proofInput( || readback.physicalPartitionReservationCount() != physical.reservationCount() || readback.physicalBindingCount() != physical.bindingCount() || readback.physicalCountedCapacityCount() != physical.countedReservationCount() - || !readback.plannedAggregateCapacityCount().equals(physical.plannedAggregateCapacityCount())) { - throw conflict("Physical Redis readback capability differs from its exact prepared field set"); + || !readback + .plannedAggregateCapacityCount() + .equals(physical.plannedAggregateCapacityCount())) { + throw conflict( + "Physical Redis readback capability differs from its exact prepared field set"); } return new ProofInput( plan.buildOperationId(), @@ -878,38 +1100,48 @@ private static void requireSameProof(Record row, ProofInput expected) { || !expected.planDigest().equals(requireText(row, "build_plan_digest")) || !expected.operationFence().equals(readInteger(row, "bootstrap_operation_fence")) || !expected.coverageFence().equals(readInteger(row, "bootstrap_coverage_fence")) - || !expected.snapshotRevision().equals(readInteger(row, "issuer_inventory_snapshot_revision")) + || !expected + .snapshotRevision() + .equals(readInteger(row, "issuer_inventory_snapshot_revision")) || !expected.layoutVersion().equals(readInteger(row, "layout_version")) || !expected.partitionCount().equals(readInteger(row, "partition_count")) || !expected.partitionCapacity().equals(readInteger(row, "partition_capacity")) || !expected.mappingIdentity().equals(requireText(row, "mapping_identity")) - || !Arrays.equals(expected.layoutDescriptorBytes(), requireBytes(row, "layout_descriptor_bytes")) + || !Arrays.equals( + expected.layoutDescriptorBytes(), requireBytes(row, "layout_descriptor_bytes")) || !expected.layoutDescriptorDigest().equals(requireText(row, "layout_descriptor_digest")) - || !Arrays.equals(expected.sourceCheckpointBytes(), requireBytes(row, "source_checkpoint_bytes")) + || !Arrays.equals( + expected.sourceCheckpointBytes(), requireBytes(row, "source_checkpoint_bytes")) || !expected.sourceCheckpointDigest().equals(requireText(row, "source_checkpoint_digest")) || !Arrays.equals(expected.sourceEventBytes(), optionalBytes(row, "source_event_bytes")) - || !Objects.equals(expected.sourceEventDigest(), row.get("source_event_digest", String.class)) + || !Objects.equals( + expected.sourceEventDigest(), row.get("source_event_digest", String.class)) || !Arrays.equals(expected.incarnationBytes(), requireBytes(row, "incarnation_bytes")) || !expected.incarnationDigest().equals(requireText(row, "incarnation_digest")) || !expected.partitionId().equals(readInteger(row, "partition_id")) || !Arrays.equals(expected.metadataBytes(), requireBytes(row, "exact_metadata_bytes")) - || !Arrays.equals(expected.fieldSetBytes(), requireBytes(row, "exact_physical_field_set_bytes")) + || !Arrays.equals( + expected.fieldSetBytes(), requireBytes(row, "exact_physical_field_set_bytes")) || !expected.fieldSetDigest().equals(requireText(row, "exact_physical_field_set_digest")) || expected.fieldCount() != readInt(row, "physical_field_count") || expected.reservationCount() != readInt(row, "physical_reservation_count") || expected.bindingCount() != readInt(row, "physical_binding_count") || expected.countedCapacityCount() != readInt(row, "physical_counted_capacity_count") - || !expected.aggregateCountedCapacity().equals(readInteger(row, "planned_aggregate_capacity_count")) + || !expected + .aggregateCountedCapacity() + .equals(readInteger(row, "planned_aggregate_capacity_count")) || !"EXACT_PHYSICAL_READBACK".equals(requireText(row, "proof_state"))) { throw conflict("Exact partition proof retry changed its original physical bytes or tuple"); } } - private static byte[] encodeFieldSet(Map fields) { + static byte[] encodeFieldSet(Map fields) { List> entries = new ArrayList<>(fields.entrySet()); - entries.sort((left, right) -> compareUnsigned( - left.getKey().getBytes(StandardCharsets.UTF_8), - right.getKey().getBytes(StandardCharsets.UTF_8))); + entries.sort( + (left, right) -> + compareUnsigned( + left.getKey().getBytes(StandardCharsets.UTF_8), + right.getKey().getBytes(StandardCharsets.UTF_8))); try { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); try (DataOutputStream output = new DataOutputStream(bytes)) { @@ -920,34 +1152,44 @@ private static byte[] encodeFieldSet(Map fields) { writeBytes(output, entry.getValue()); } } - if (bytes.size() > 17 * 1024 * 1024) throw conflict("Physical field proof exceeds its bounded storage limit"); + if (bytes.size() > 17 * 1024 * 1024) + throw conflict("Physical field proof exceeds its bounded storage limit"); return bytes.toByteArray(); } catch (IOException impossible) { - throw new IllegalStateException("Could not encode exact issuer physical readback", impossible); + throw new IllegalStateException( + "Could not encode exact issuer physical readback", impossible); } } - private static Map decodeFieldSet(byte[] encoded) { + static Map decodeFieldSet(byte[] encoded) { if (encoded.length == 0 || encoded.length > 17 * 1024 * 1024) { throw conflict("Persisted issuer physical field proof is outside its bound"); } try (DataInputStream input = new DataInputStream(new ByteArrayInputStream(encoded))) { - if (!Arrays.equals(readBytes(input, 256), FIELDSET_MAGIC.getBytes(StandardCharsets.US_ASCII))) { + if (!Arrays.equals( + readBytes(input, 256), FIELDSET_MAGIC.getBytes(StandardCharsets.US_ASCII))) { throw conflict("Persisted issuer physical field proof has an unsupported encoding"); } int count = input.readInt(); - if (count < 1 || count > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_HASH_FIELDS) { + if (count < 1 + || count > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_HASH_FIELDS) { throw conflict("Persisted issuer physical field count is outside its bound"); } Map fields = new HashMap<>(); byte[] previous = null; for (int index = 0; index < count; index++) { - byte[] rawField = readBytes(input, CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_BINDING_REF_BYTES); - if (rawField.length == 0 || (previous != null && compareUnsigned(previous, rawField) >= 0)) { + byte[] rawField = + readBytes( + input, + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_BINDING_REF_BYTES); + if (rawField.length == 0 + || (previous != null && compareUnsigned(previous, rawField) >= 0)) { throw conflict("Persisted issuer physical fields are duplicated or noncanonical"); } String field = decodeUtf8(rawField); - byte[] value = readBytes(input, CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_VALUE_BYTES); + byte[] value = + readBytes( + input, CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_VALUE_BYTES); if (value.length == 0 || fields.putIfAbsent(field, value) != null) { throw conflict("Persisted issuer physical field is empty or duplicated"); } @@ -967,7 +1209,8 @@ private static void writeBytes(DataOutputStream output, byte[] bytes) throws IOE private static byte[] readBytes(DataInputStream input, int maxBytes) throws IOException { int length = input.readInt(); - if (length < 0 || length > maxBytes) throw conflict("Issuer physical proof field exceeds its bound"); + if (length < 0 || length > maxBytes) + throw conflict("Issuer physical proof field exceeds its bound"); byte[] value = input.readNBytes(length); if (value.length != length) throw conflict("Issuer physical proof field is truncated"); return value; @@ -975,7 +1218,8 @@ private static byte[] readBytes(DataInputStream input, int maxBytes) throws IOEx private static String decodeUtf8(byte[] bytes) { try { - return StandardCharsets.UTF_8.newDecoder() + return StandardCharsets.UTF_8 + .newDecoder() .onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT) .decode(java.nio.ByteBuffer.wrap(bytes)) @@ -1113,12 +1357,35 @@ private record ProofInput( fieldSetBytes = fieldSetBytes.clone(); } - @Override public byte[] layoutDescriptorBytes() { return layoutDescriptorBytes.clone(); } - @Override public byte[] sourceCheckpointBytes() { return sourceCheckpointBytes.clone(); } - @Override public byte[] sourceEventBytes() { return sourceEventBytes == null ? null : sourceEventBytes.clone(); } - @Override public byte[] incarnationBytes() { return incarnationBytes.clone(); } - @Override public byte[] metadataBytes() { return metadataBytes.clone(); } - @Override public byte[] fieldSetBytes() { return fieldSetBytes.clone(); } + @Override + public byte[] layoutDescriptorBytes() { + return layoutDescriptorBytes.clone(); + } + + @Override + public byte[] sourceCheckpointBytes() { + return sourceCheckpointBytes.clone(); + } + + @Override + public byte[] sourceEventBytes() { + return sourceEventBytes == null ? null : sourceEventBytes.clone(); + } + + @Override + public byte[] incarnationBytes() { + return incarnationBytes.clone(); + } + + @Override + public byte[] metadataBytes() { + return metadataBytes.clone(); + } + + @Override + public byte[] fieldSetBytes() { + return fieldSetBytes.clone(); + } } private record ProofSummary( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerInstalledAnchor.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerInstalledAnchor.java index 427c587275..e80b4b8124 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerInstalledAnchor.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerInstalledAnchor.java @@ -85,13 +85,15 @@ public final class CanonicalGameplayIssuerInstalledAnchor { this.buildPlanDigest = requireDigest(buildPlanDigest, "buildPlanDigest"); this.issuerId = requireIssuer(issuerId); this.controlEpoch = requirePositive(controlEpoch, "controlEpoch"); - this.issuerCoverageOperationId = requireNonNil(issuerCoverageOperationId, "issuerCoverageOperationId"); + this.issuerCoverageOperationId = + requireNonNil(issuerCoverageOperationId, "issuerCoverageOperationId"); this.operationFence = requirePositive(operationFence, "operationFence"); this.coverageFence = requirePositive(coverageFence, "coverageFence"); if (!this.issuerCoverageOperationId.equals(this.bootstrapOperationId) || !this.controlEpoch.equals(this.operationFence) || this.operationFence.equals(this.coverageFence)) { - throw new IllegalArgumentException("Initial anchor must retain its exact distinct operation tuple"); + throw new IllegalArgumentException( + "Initial anchor must retain its exact distinct operation tuple"); } this.issuerInventorySnapshotRevision = requirePositive(issuerInventorySnapshotRevision, "issuerInventorySnapshotRevision"); @@ -104,13 +106,17 @@ public final class CanonicalGameplayIssuerInstalledAnchor { } this.layoutDescriptorBytes = nonEmpty(layoutDescriptorBytes, "layoutDescriptorBytes"); this.layoutDescriptorDigest = requireDigest(layoutDescriptorDigest, "layoutDescriptorDigest"); - requireDigestMatches(this.layoutDescriptorBytes, this.layoutDescriptorDigest, "layout descriptor"); + requireDigestMatches( + this.layoutDescriptorBytes, this.layoutDescriptorDigest, "layout descriptor"); this.issuerAuthGeneration = requirePositive(issuerAuthGeneration, "issuerAuthGeneration"); this.sourceCheckpointBytes = nonEmpty(sourceCheckpointBytes, "sourceCheckpointBytes"); this.sourceCheckpointDigest = requireDigest(sourceCheckpointDigest, "sourceCheckpointDigest"); - requireDigestMatches(this.sourceCheckpointBytes, this.sourceCheckpointDigest, "source checkpoint"); - this.sourceEventBytes = sourceEventBytes == null ? null : nonEmpty(sourceEventBytes, "sourceEventBytes"); - this.sourceEventDigest = sourceEventDigest == null ? null : requireDigest(sourceEventDigest, "sourceEventDigest"); + requireDigestMatches( + this.sourceCheckpointBytes, this.sourceCheckpointDigest, "source checkpoint"); + this.sourceEventBytes = + sourceEventBytes == null ? null : nonEmpty(sourceEventBytes, "sourceEventBytes"); + this.sourceEventDigest = + sourceEventDigest == null ? null : requireDigest(sourceEventDigest, "sourceEventDigest"); if ((this.sourceEventBytes == null) != (this.sourceEventDigest == null)) { throw new IllegalArgumentException("Account source event bytes and digest must be paired"); } @@ -120,31 +126,37 @@ public final class CanonicalGameplayIssuerInstalledAnchor { this.incarnationBytes = nonEmpty(incarnationBytes, "incarnationBytes"); this.incarnationDigest = requireDigest(incarnationDigest, "incarnationDigest"); requireDigestMatches(this.incarnationBytes, this.incarnationDigest, "stable incarnation"); - this.globalCoverageGeneration = requirePositive(globalCoverageGeneration, "globalCoverageGeneration"); + this.globalCoverageGeneration = + requirePositive(globalCoverageGeneration, "globalCoverageGeneration"); if (partitionProofCount < 1 || !BigInteger.valueOf(partitionProofCount).equals(partitionCount) || physicalReservationCount < 0 || physicalBindingCount < 0 || physicalBindingCount > physicalReservationCount) { - throw new IllegalArgumentException("Installed anchor must retain the complete finite proof counts"); + throw new IllegalArgumentException( + "Installed anchor must retain the complete finite proof counts"); } this.partitionProofCount = partitionProofCount; this.physicalReservationCount = physicalReservationCount; this.physicalBindingCount = physicalBindingCount; - this.aggregateCountedCapacity = Objects.requireNonNull(aggregateCountedCapacity, "aggregateCountedCapacity"); + this.aggregateCountedCapacity = + Objects.requireNonNull(aggregateCountedCapacity, "aggregateCountedCapacity"); if (aggregateCountedCapacity.signum() < 0 || aggregateCountedCapacity.compareTo(partitionCount.multiply(partitionCapacity)) > 0 || aggregateCountedCapacity.compareTo(BigInteger.valueOf(physicalReservationCount)) > 0) { - throw new IllegalArgumentException("Installed anchor aggregate capacity is outside its finite bound"); + throw new IllegalArgumentException( + "Installed anchor aggregate capacity is outside its finite bound"); } - this.partitionProofRootDigest = requireDigest(partitionProofRootDigest, "partitionProofRootDigest"); + this.partitionProofRootDigest = + requireDigest(partitionProofRootDigest, "partitionProofRootDigest"); this.exactAnchorBytes = encodeExactAnchor(); this.exactAnchorDigest = CanonicalGameplayIssuerMemberV2Codec.sha256(this.exactAnchorBytes); if ((storedExactAnchorBytes == null) != (storedExactAnchorDigest == null) || (storedExactAnchorBytes != null && (!java.util.Arrays.equals(this.exactAnchorBytes, storedExactAnchorBytes) || !this.exactAnchorDigest.equals(storedExactAnchorDigest)))) { - throw new IllegalArgumentException("Stored installed-anchor bytes differ from their exact tuple"); + throw new IllegalArgumentException( + "Stored installed-anchor bytes differ from their exact tuple"); } } @@ -209,37 +221,129 @@ private byte[] encodeExactAnchor() { }); } - public UUID bootstrapOperationId() { return bootstrapOperationId; } - public UUID bootstrapRequestId() { return bootstrapRequestId; } - public UUID buildOperationId() { return buildOperationId; } - public String buildPlanDigest() { return buildPlanDigest; } - public String issuerId() { return issuerId; } - public BigInteger controlEpoch() { return controlEpoch; } - public UUID issuerCoverageOperationId() { return issuerCoverageOperationId; } - public BigInteger operationFence() { return operationFence; } - public BigInteger coverageFence() { return coverageFence; } - public BigInteger issuerInventorySnapshotRevision() { return issuerInventorySnapshotRevision; } - public BigInteger layoutVersion() { return layoutVersion; } - public BigInteger partitionCount() { return partitionCount; } - public BigInteger partitionCapacity() { return partitionCapacity; } - public String mappingIdentity() { return mappingIdentity; } - public byte[] layoutDescriptorBytes() { return layoutDescriptorBytes.clone(); } - public String layoutDescriptorDigest() { return layoutDescriptorDigest; } - public BigInteger issuerAuthGeneration() { return issuerAuthGeneration; } - public byte[] sourceCheckpointBytes() { return sourceCheckpointBytes.clone(); } - public String sourceCheckpointDigest() { return sourceCheckpointDigest; } - public byte[] sourceEventBytes() { return sourceEventBytes == null ? null : sourceEventBytes.clone(); } - public String sourceEventDigest() { return sourceEventDigest; } - public byte[] incarnationBytes() { return incarnationBytes.clone(); } - public String incarnationDigest() { return incarnationDigest; } - public BigInteger globalCoverageGeneration() { return globalCoverageGeneration; } - public long partitionProofCount() { return partitionProofCount; } - public long physicalReservationCount() { return physicalReservationCount; } - public long physicalBindingCount() { return physicalBindingCount; } - public BigInteger aggregateCountedCapacity() { return aggregateCountedCapacity; } - public String partitionProofRootDigest() { return partitionProofRootDigest; } - public byte[] exactAnchorBytes() { return exactAnchorBytes.clone(); } - public String exactAnchorDigest() { return exactAnchorDigest; } + public UUID bootstrapOperationId() { + return bootstrapOperationId; + } + + public UUID bootstrapRequestId() { + return bootstrapRequestId; + } + + public UUID buildOperationId() { + return buildOperationId; + } + + public String buildPlanDigest() { + return buildPlanDigest; + } + + public String issuerId() { + return issuerId; + } + + public BigInteger controlEpoch() { + return controlEpoch; + } + + public UUID issuerCoverageOperationId() { + return issuerCoverageOperationId; + } + + public BigInteger operationFence() { + return operationFence; + } + + public BigInteger coverageFence() { + return coverageFence; + } + + public BigInteger issuerInventorySnapshotRevision() { + return issuerInventorySnapshotRevision; + } + + public BigInteger layoutVersion() { + return layoutVersion; + } + + public BigInteger partitionCount() { + return partitionCount; + } + + public BigInteger partitionCapacity() { + return partitionCapacity; + } + + public String mappingIdentity() { + return mappingIdentity; + } + + public byte[] layoutDescriptorBytes() { + return layoutDescriptorBytes.clone(); + } + + public String layoutDescriptorDigest() { + return layoutDescriptorDigest; + } + + public BigInteger issuerAuthGeneration() { + return issuerAuthGeneration; + } + + public byte[] sourceCheckpointBytes() { + return sourceCheckpointBytes.clone(); + } + + public String sourceCheckpointDigest() { + return sourceCheckpointDigest; + } + + public byte[] sourceEventBytes() { + return sourceEventBytes == null ? null : sourceEventBytes.clone(); + } + + public String sourceEventDigest() { + return sourceEventDigest; + } + + public byte[] incarnationBytes() { + return incarnationBytes.clone(); + } + + public String incarnationDigest() { + return incarnationDigest; + } + + public BigInteger globalCoverageGeneration() { + return globalCoverageGeneration; + } + + public long partitionProofCount() { + return partitionProofCount; + } + + public long physicalReservationCount() { + return physicalReservationCount; + } + + public long physicalBindingCount() { + return physicalBindingCount; + } + + public BigInteger aggregateCountedCapacity() { + return aggregateCountedCapacity; + } + + public String partitionProofRootDigest() { + return partitionProofRootDigest; + } + + public byte[] exactAnchorBytes() { + return exactAnchorBytes.clone(); + } + + public String exactAnchorDigest() { + return exactAnchorDigest; + } private static byte[] encode(IoWriter writer) { try { @@ -254,10 +358,14 @@ private static byte[] encode(IoWriter writer) { } private static void writeText(DataOutputStream output, String value) throws IOException { - writeBytes(output, Objects.requireNonNull(value, "exact text").getBytes(java.nio.charset.StandardCharsets.UTF_8)); + writeBytes( + output, + Objects.requireNonNull(value, "exact text") + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); } - private static void writeBigInteger(DataOutputStream output, BigInteger value) throws IOException { + private static void writeBigInteger(DataOutputStream output, BigInteger value) + throws IOException { writeText(output, Objects.requireNonNull(value, "exact counter").toString()); } @@ -278,12 +386,14 @@ private static void writeNullableText(DataOutputStream output, String value) thr private static UUID requireNonNil(UUID value, String name) { Objects.requireNonNull(value, name); - if (value.equals(new UUID(0L, 0L))) throw new IllegalArgumentException(name + " must not be nil"); + if (value.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException(name + " must not be nil"); return value; } private static String requireIssuer(String value) { - if (!net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.ISSUER.equals(value)) { + if (!net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.ISSUER.equals( + value)) { throw new IllegalArgumentException("Installed anchor issuer scope is not canonical"); } return value; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java index 5bc8b97bc4..8c1703afcb 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java @@ -285,6 +285,48 @@ CanonicalGameplayIssuerPartitionBuildPlan readPreparedPlanInTransaction( return plan; } + /** + * Reconstructs the immutable plan retained by an already installed initial anchor. This reads + * only the frozen V1030 cohort and V1031 plan artifacts; it deliberately does not compare them + * with the now-advancing live inventory clock or source rows. + */ + CanonicalGameplayIssuerPartitionBuildPlan readInstalledPlanForAnchorInTransaction( + DSLContext transaction, UUID bootstrapOperationId, UUID bootstrapRequestId) { + requireNonNil(bootstrapOperationId, "bootstrapOperationId"); + requireNonNil(bootstrapRequestId, "bootstrapRequestId"); + if (bootstrapOperationId.equals(bootstrapRequestId)) { + throw conflict("Bootstrap operation and request identities must be distinct"); + } + Record control = lockControl(transaction, ISSUER); + if (control == null) throw conflict("Installed initial anchor lost its issuer control row"); + Record intentRow = lockIntent(transaction, bootstrapOperationId); + if (intentRow == null) throw conflict("Installed initial anchor lost its bootstrap intent row"); + BigInteger frozenRevision = readBigInteger(intentRow, "inventory_snapshot_revision"); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = + loadAndRequireCurrentIntent( + transaction, + control, + intentRow, + bootstrapOperationId, + bootstrapRequestId, + frozenRevision); + List frozenRows = + intent.cohortRows().stream().map(IssuerCohortSourceRow::new).toList(); + DerivedPlan derived = derivePlan(intent, frozenRows); + Record buildPlanRow = + transaction.fetchOne( + "SELECT * FROM " + BUILD_PLAN + " WHERE bootstrap_operation_id = ? FOR UPDATE", + bootstrapOperationId); + if (buildPlanRow == null) + throw conflict("Installed initial anchor lost its immutable build plan"); + CanonicalGameplayIssuerPartitionBuildPlan plan = + loadAndRequireExactPlan(transaction, intent, frozenRows, derived, buildPlanRow); + if (plan.state() != CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED) { + throw conflict("Installed initial anchor plan contains an unresolved blocker"); + } + return plan; + } + /** Extracts typed source only from a plan returned by {@link #readPreparedPlanInTransaction}. */ PreparedMemberWork readPreparedMemberWorkFromVerifiedPlan( CanonicalGameplayIssuerPartitionBuildPlan plan, long workOrdinal) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuard.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuard.java new file mode 100644 index 0000000000..a7b9c0a8e4 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuard.java @@ -0,0 +1,66 @@ +package net.firedevops.firemud.gamesession.security; + +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; + +/** Exact same-namespace Account-only guard for the original lease decision read. */ +public final class CanonicalGameplayAdmissionDecisionReadWorkloadGuard + implements ServerInterceptor { + public static final String METHOD = + "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/" + + "GetCanonicalGameplayAdmissionDecision"; + + private final String workloadNamespace; + + public CanonicalGameplayAdmissionDecisionReadWorkloadGuard(String workloadNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Session workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + public void requireAccountCaller() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified Account workload identity required") + .asRuntimeException(); + } + if (SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService() + || !"account-service".equals(peer.service()) + || !workloadNamespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service") + .equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Account workload required") + .asRuntimeException(); + } + } + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + Objects.requireNonNull(call, "gRPC server call required"); + if (!METHOD.equals(call.getMethodDescriptor().getFullMethodName())) { + call.close( + Status.PERMISSION_DENIED.withDescription("Exact Account decision-read method required"), + new Metadata()); + return new ServerCall.Listener<>() {}; + } + try { + requireAccountCaller(); + } catch (StatusRuntimeException denied) { + call.close(Status.fromCode(denied.getStatus().getCode()), new Metadata()); + return new ServerCall.Listener<>() {}; + } + return next.startCall(call, headers); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/ProtectedGameSessionLoginGrpcInterceptor.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/ProtectedGameSessionLoginGrpcInterceptor.java index a706ae326a..d6f0b48536 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/ProtectedGameSessionLoginGrpcInterceptor.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/ProtectedGameSessionLoginGrpcInterceptor.java @@ -16,8 +16,7 @@ public final class ProtectedGameSessionLoginGrpcInterceptor implements ServerInt "game_session.v1.GameSessionService/Ping", "game_session.v1.GameSessionControlPlaneService/GetInitialAdmissionBindProof", "game_session.v1.GameSessionControlPlaneService/GetRunOwnedFixtureLaunchAssociation", - "game_session.v1.GameSessionControlPlaneService/GetPublishedRealmAdmissionOwnerRead", - "game_session.v1.GameSessionControlPlaneService/GetCanonicalGameplayAdmissionDecision", + CanonicalGameplayAdmissionDecisionReadWorkloadGuard.METHOD, "game_session.v1.GameSessionControlPlaneService/GetCanonicalGameInstanceLaunchAssociation", "game_session.v1.GameSessionControlPlaneService/GetRuntimeRegionInitializationCheckpoint", "game_session.v1.CanonicalInitialAdmissionOwnerProofReadService/GetCanonicalInitialAdmissionOwnerProof", diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRedisScriptContribution.java new file mode 100644 index 0000000000..9c9c71bd5e --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRedisScriptContribution.java @@ -0,0 +1,51 @@ +package net.firedevops.firemud.gamesession.service; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Collection; +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Passive manual-catalog contribution for ordinary binding-local issuer projection. */ +public final class CanonicalGameplayIssuerBindingLocalRedisScriptContribution + implements RedisScriptContribution { + public static final String SCRIPT_ID = "game-session.issuer-binding-local-add.v1"; + public static final String RESOURCE_PATH = "redis/lua/game-session-issuer-binding-local-add.lua"; + private static final String DESCRIPTOR_PATH = + "/redis/scripts/game-session-issuer-binding-local-add.json"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @Override + public String ownerId() { + return "game-session-service"; + } + + @Override + public Collection descriptors() { + try (InputStream input = getClass().getResourceAsStream(DESCRIPTOR_PATH)) { + if (input == null) throw unavailable(); + byte[] bytes = input.readNBytes(16 * 1024 + 1); + if (bytes.length == 0 || bytes.length > 16 * 1024) throw unavailable(); + RedisScriptDescriptor descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); + if (!ownerId().equals(descriptor.owner()) || !SCRIPT_ID.equals(descriptor.scriptId())) { + throw unavailable(); + } + return List.of(descriptor); + } catch (IOException | RuntimeException failure) { + throw unavailable(); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Issuer binding-local Redis descriptor is unavailable"); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java new file mode 100644 index 0000000000..16a5df70eb --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java @@ -0,0 +1,212 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +import java.util.Objects; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayBindingInventoryRepository; +import net.firedevops.firemud.gamesession.security.CanonicalGameplayAdmissionDecisionReadWorkloadGuard; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionDecisionReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayAdmissionDecisionRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayAdmissionDecisionResponse; +import org.jooq.exception.DataAccessException; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.TransientDataAccessException; +import org.springframework.transaction.CannotCreateTransactionException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered, non-admitting Account-only read of one exact retained PROVISIONAL decision. */ +public final class CanonicalGameplayAdmissionDecisionReadGrpcService + extends CanonicalGameplayAdmissionDecisionReadServiceGrpc + .CanonicalGameplayAdmissionDecisionReadServiceImplBase { + private final CanonicalGameplayBindingInventoryRepository repository; + private final CanonicalGameplayAdmissionDecisionReadWorkloadGuard workloadGuard; + private final String workloadNamespace; + + public CanonicalGameplayAdmissionDecisionReadGrpcService( + CanonicalGameplayBindingInventoryRepository repository, + CanonicalGameplayAdmissionDecisionReadWorkloadGuard workloadGuard, + String workloadNamespace) { + this.repository = Objects.requireNonNull(repository, "Game Session decision owner required"); + this.workloadGuard = + Objects.requireNonNull(workloadGuard, "Account-only decision-read guard required"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Session workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + @Override + public void getCanonicalGameplayAdmissionDecision( + GetCanonicalGameplayAdmissionDecisionRequest request, + StreamObserver observer) { + Objects.requireNonNull(observer, "response observer required"); + try { + // Authenticate before parsing or inspecting any request value. + workloadGuard.requireAccountCaller(); + } catch (StatusRuntimeException denied) { + fail(observer, denied.getStatus()); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } + if (request == null + || request.getSerializedSize() + > CanonicalGameplayAdmissionDecisionReadGrpcCodec.MAX_REQUEST_WIRE_BYTES) { + fail(observer, Status.INVALID_ARGUMENT); + return; + } + + final CanonicalGameplayAdmissionDecisionReadGrpcCodec.RequestEvidence selector; + try { + selector = CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest(request); + var lease = selector.expectedLeaseEvidence(); + Object targetNamespace = lease.carrier().get("targetNamespace"); + Object callerWorkload = lease.carrier().get("callerWorkload"); + String expectedCaller = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"; + if (lease.leaseKind() + != net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence + .LeaseKind.NEW_BINDING + || !workloadNamespace.equals(targetNamespace) + || !expectedCaller.equals(callerWorkload)) { + fail(observer, Status.PERMISSION_DENIED); + return; + } + } catch (IllegalArgumentException malformed) { + fail(observer, Status.INVALID_ARGUMENT); + return; + } catch (RuntimeException unexpectedParserFailure) { + fail(observer, Status.INTERNAL); + return; + } + + final GetCanonicalGameplayAdmissionDecisionResponse response; + try { + CanonicalGameplayAdmissionDecision decision = + repository.readAdmissionDecision( + selector.bindingDecisionId(), selector.expectedLeaseEvidence()); + if (decision.leaseKind() + != net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence + .LeaseKind.NEW_BINDING) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } + response = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toResponse( + selector, + decision.bindingDecisionId(), + decision.leaseEvidence(), + decision.bindingGeneration(), + decision.expectedOldBindingGeneration(), + decision.resumeEpisodeId(), + toCandidate(decision), + toTarget(decision)); + } catch (CannotCreateTransactionException + | DataAccessResourceFailureException + | TransientDataAccessException unavailable) { + fail(observer, Status.UNAVAILABLE); + return; + } catch (DataAccessException | org.springframework.dao.DataAccessException failure) { + fail(observer, hasConnectionFailureSqlState(failure) ? Status.UNAVAILABLE : Status.INTERNAL); + return; + } catch (RuntimeException incompleteOrConflicting) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } + + try { + observer.onNext(response); + } catch (RuntimeException observerFailure) { + fail(observer, Status.INTERNAL); + return; + } + // Completion is already terminal: a callback failure must not cause a second terminal signal. + observer.onCompleted(); + } + + private static Candidate toCandidate(CanonicalGameplayAdmissionDecision decision) { + var candidate = decision.candidate(); + return new Candidate( + candidate.accountId(), + candidate.tenantId(), + candidate.playableStateNamespaceId(), + candidate.characterId(), + candidate.playableStateScope(), + candidate.gameInstanceId(), + candidate.runtimeGameInstanceId(), + java.util.UUID.fromString(candidate.sessionId()), + candidate.regionId(), + candidate.regionEpoch(), + candidate.issuerId(), + candidate.issuerAuthGeneration(), + candidate.issuerIndexLayoutVersion(), + candidate.issuerIndexPartitionCount(), + candidate.issuerIndexPartitionCapacity()); + } + + private static Target toTarget(CanonicalGameplayAdmissionDecision decision) { + var target = decision.targetEvidence(); + return new Target( + target.targetNamespace(), + target.tenantSlug(), + target.canonicalTenantId(), + target.worldSlug(), + target.worldDisplayName(), + target.realmId(), + target.realmSlug(), + target.realmDisplayName(), + target.gameSessionTenantId(), + target.gameInstanceId(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.canonicalVersionId(), + target.runtimeVersionId(), + target.catalogRevision(), + target.pointerVersion(), + target.admissionPointerSnapshotDigest(), + target.activeWorldEpoch(), + target.initialAdmissionRequestId(), + target.initialAdmissionRequestDigest(), + CanonicalGameplayAdmissionDecisionReadGrpcCodec.OriginKind.valueOf( + target.initialAdmissionOriginKind().name()), + target.expectedPriorPointerVersion(), + target.holdId(), + target.holdFence(), + target.holdBindingDigest(), + target.auditEventId(), + target.ownerProofDigest(), + OwnerProofOutcome.valueOf(target.ownerProofOutcome().name()), + target.positiveDurableAbort(), + target.ownerProofTerminalAt(), + target.characterCreationPolicy()); + } + + private static boolean hasConnectionFailureSqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException exception) { + String sqlState = exception.getSQLState(); + if (sqlState != null && sqlState.startsWith("08")) return true; + } + } + return false; + } + + private static void fail(StreamObserver observer, Status status) { + observer.onError( + Status.fromCode(status.getCode()) + .withDescription("Canonical Game Session admission decision is unavailable") + .asRuntimeException()); + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V1034__canonical_issuer_binding_local_operation.sql b/services/game-session-service/src/main/resources/db/migration/V1034__canonical_issuer_binding_local_operation.sql new file mode 100644 index 0000000000..4bfb697e58 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1034__canonical_issuer_binding_local_operation.sql @@ -0,0 +1,206 @@ +-- Ordinary NEW operations are registered only after a positive initial installed issuer anchor. +-- This local durable transition is not a new inventory, an issuer-wide coverage acknowledgement, +-- a tenant barrier, or admission authority. + +CREATE TABLE game_session_canonical_issuer_binding_local_operation ( + operation_id uuid NOT NULL, + request_id uuid NOT NULL, + transition_id uuid NOT NULL, + issuer_id character varying(64) NOT NULL, + candidate_account_index_fence uuid NOT NULL, + binding_ref bytea NOT NULL, + binding_generation numeric NOT NULL, + reservation_id uuid NOT NULL, + reservation_fence uuid NOT NULL, + partition_id numeric NOT NULL, + local_inventory_snapshot_revision numeric NOT NULL, + expected_prior_binding_ref bytea, + expected_prior_binding_generation numeric, + + original_issuer_coverage_operation_id uuid NOT NULL, + original_issuer_coverage_operation_fence numeric NOT NULL, + original_coverage_fence numeric NOT NULL, + original_inventory_snapshot_revision numeric NOT NULL, + + anchor_bootstrap_operation_id uuid NOT NULL, + anchor_bootstrap_request_id uuid NOT NULL, + anchor_build_operation_id uuid NOT NULL, + anchor_build_plan_digest character varying(71) NOT NULL, + anchor_control_epoch numeric NOT NULL, + anchor_issuer_coverage_operation_id uuid NOT NULL, + anchor_operation_fence numeric NOT NULL, + anchor_coverage_fence numeric NOT NULL, + anchor_issuer_inventory_snapshot_revision numeric NOT NULL, + anchor_layout_version numeric NOT NULL, + anchor_partition_count numeric NOT NULL, + anchor_partition_capacity numeric NOT NULL, + anchor_mapping_identity character varying(96) NOT NULL, + anchor_layout_descriptor_bytes bytea NOT NULL, + anchor_layout_descriptor_digest character varying(71) NOT NULL, + anchor_issuer_auth_generation numeric NOT NULL, + anchor_source_checkpoint_bytes bytea NOT NULL, + anchor_source_checkpoint_digest character varying(71) NOT NULL, + anchor_source_event_bytes bytea, + anchor_source_event_digest character varying(71), + anchor_incarnation_bytes bytea NOT NULL, + anchor_incarnation_digest character varying(71) NOT NULL, + exact_anchor_bytes bytea NOT NULL, + exact_anchor_digest character varying(71) NOT NULL, + + baseline_partition_id numeric NOT NULL, + baseline_field_set_bytes bytea NOT NULL, + baseline_field_set_digest character varying(71) NOT NULL, + baseline_counted_capacity integer NOT NULL, + baseline_reservation_count integer NOT NULL, + baseline_binding_count integer NOT NULL, + + account_control_state character varying(32) NOT NULL, + account_control_epoch numeric NOT NULL, + account_current_operation_id uuid, + account_current_fence_intent_id uuid, + account_current_operation_fence numeric, + account_admission_fence uuid, + account_historical_admission_fence uuid, + account_coverage_fence uuid, + account_inventory_snapshot_revision numeric, + account_coverage_generation numeric, + + operation_fence numeric NOT NULL, + local_member_generation numeric NOT NULL, + expected_old_member_state character varying(16) NOT NULL, + expected_old_capacity_state character varying(16) NOT NULL, + member_status character varying(32) NOT NULL, + member_schema_version smallint NOT NULL, + member_value_bytes bytea NOT NULL, + member_value_digest character varying(71) NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT pk_gs_issuer_binding_local_operation PRIMARY KEY (operation_id), + CONSTRAINT uq_gs_issuer_binding_local_operation_request UNIQUE (issuer_id, request_id), + CONSTRAINT uq_gs_issuer_binding_local_operation_transition UNIQUE (issuer_id, transition_id), + CONSTRAINT uq_gs_issuer_binding_local_operation_reservation UNIQUE (reservation_id), + CONSTRAINT uq_gs_issuer_binding_local_operation_fence UNIQUE (issuer_id, operation_fence), + CONSTRAINT uq_gs_issuer_binding_local_operation_generation UNIQUE (issuer_id, local_member_generation), + CONSTRAINT fk_gs_issuer_binding_local_operation_transition + FOREIGN KEY (transition_id) REFERENCES game_session_canonical_binding_transition (transition_id), + CONSTRAINT fk_gs_issuer_binding_local_operation_reservation + FOREIGN KEY (reservation_id) REFERENCES game_session_canonical_issuer_partition_reservation (reservation_id), + CONSTRAINT fk_gs_issuer_binding_local_operation_anchor + FOREIGN KEY (anchor_bootstrap_operation_id) + REFERENCES game_session_canonical_issuer_installed_anchor (bootstrap_operation_id), + CONSTRAINT chk_gs_issuer_binding_local_operation CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND transition_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND request_id <> transition_id + AND issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND candidate_account_index_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND octet_length(binding_ref) > 0 + AND binding_generation > 0 + AND reservation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND reservation_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND partition_id >= 0 + AND local_inventory_snapshot_revision > 0 + AND expected_prior_binding_ref IS NULL + AND expected_prior_binding_generation IS NULL + AND original_issuer_coverage_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND original_issuer_coverage_operation_fence > 0 + AND original_coverage_fence > 0 + AND original_inventory_snapshot_revision > 0 + AND anchor_bootstrap_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND anchor_bootstrap_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND anchor_build_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND anchor_build_plan_digest ~ '^sha256:[0-9a-f]{64}$' + AND anchor_control_epoch > 0 + AND anchor_issuer_coverage_operation_id = anchor_bootstrap_operation_id + AND anchor_operation_fence = anchor_control_epoch + AND anchor_operation_fence > 0 + AND anchor_coverage_fence > 0 + AND anchor_coverage_fence <> anchor_operation_fence + AND anchor_issuer_inventory_snapshot_revision > 0 + AND anchor_layout_version > 0 + AND anchor_partition_count > 0 + AND anchor_partition_capacity > 0 + AND partition_id < anchor_partition_count + AND anchor_mapping_identity = 'bindingRef/v1;sha256-u256-mod/v1' + AND octet_length(anchor_layout_descriptor_bytes) > 0 + AND anchor_layout_descriptor_digest ~ '^sha256:[0-9a-f]{64}$' + AND anchor_issuer_auth_generation > 0 + AND octet_length(anchor_source_checkpoint_bytes) > 0 + AND anchor_source_checkpoint_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((anchor_source_event_bytes IS NULL AND anchor_source_event_digest IS NULL) + OR (anchor_source_event_bytes IS NOT NULL + AND octet_length(anchor_source_event_bytes) > 0 + AND anchor_source_event_digest ~ '^sha256:[0-9a-f]{64}$')) + AND octet_length(anchor_incarnation_bytes) > 0 + AND anchor_incarnation_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(exact_anchor_bytes) BETWEEN 1 AND 262144 + AND exact_anchor_digest ~ '^sha256:[0-9a-f]{64}$' + AND baseline_partition_id = partition_id + AND octet_length(baseline_field_set_bytes) BETWEEN 1 AND 17825792 + AND baseline_field_set_digest ~ '^sha256:[0-9a-f]{64}$' + AND baseline_counted_capacity >= 0 + AND baseline_counted_capacity <= anchor_partition_capacity + AND baseline_reservation_count >= 0 + AND baseline_binding_count >= 0 + AND account_control_state IN ('NO_ACTIVE_ACCOUNT_WIDE_FLOW', 'HISTORICAL') + AND account_control_epoch >= 0 + AND ((account_control_state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW' + AND account_current_operation_id IS NULL + AND account_current_fence_intent_id IS NULL + AND account_current_operation_fence IS NULL + AND account_admission_fence IS NULL + AND account_historical_admission_fence IS NULL + AND account_coverage_fence IS NULL + AND account_inventory_snapshot_revision IS NULL + AND account_coverage_generation IS NULL) + OR (account_control_state = 'HISTORICAL' + AND account_current_operation_id IS NOT NULL + AND account_current_fence_intent_id IS NULL + AND account_current_operation_fence > 0 + AND account_admission_fence IS NULL + AND account_historical_admission_fence IS NOT NULL + AND account_coverage_fence IS NOT NULL + AND account_inventory_snapshot_revision > 0 + AND account_coverage_generation > 0)) + AND operation_fence > 0 + AND local_member_generation = operation_fence + 1 + AND expected_old_member_state = 'ABSENT' + AND expected_old_capacity_state = 'ABSENT' + AND member_status = 'PENDING_PHYSICAL_PROOF' + AND member_schema_version = 2 + AND octet_length(member_value_bytes) BETWEEN 1 AND 65536 + AND member_value_digest ~ '^sha256:[0-9a-f]{64}$') +); + +-- V1032 owns the local issuer-member operation counter. The operation below shares that +-- local-only fence/generation domain; neither value advances or substitutes for global coverage. + +-- [jooq ignore start] +-- H2 maps PostgreSQL bytea to an incomparable BLOB and cannot model this foreign key. +-- PostgreSQL still enforces the exact inventory identity; native migration proof is required. +ALTER TABLE game_session_canonical_issuer_binding_local_operation + ADD CONSTRAINT fk_gs_issuer_binding_local_operation_inventory + FOREIGN KEY (binding_ref) + REFERENCES game_session_canonical_gameplay_binding_inventory (binding_ref); + +CREATE FUNCTION game_session_reject_issuer_binding_local_operation_change() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'issuer binding-local operations are immutable' + USING ERRCODE = 'check_violation'; +END; +$$; + +CREATE TRIGGER trg_gs_issuer_binding_local_operation_immutable + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_binding_local_operation + FOR EACH ROW EXECUTE FUNCTION game_session_reject_issuer_binding_local_operation_change(); +CREATE TRIGGER trg_gs_issuer_binding_local_operation_no_truncate + BEFORE TRUNCATE ON game_session_canonical_issuer_binding_local_operation + FOR EACH STATEMENT EXECUTE FUNCTION game_session_reject_issuer_binding_local_operation_change(); +-- [jooq ignore stop] + +COMMENT ON TABLE game_session_canonical_issuer_binding_local_operation IS + 'Immutable ordinary NEW preparation linked to a positively installed initial issuer anchor; pending physical proof only, not global issuer coverage or admission.'; diff --git a/services/game-session-service/src/main/resources/db/migration/V1035__canonical_gameplay_first_new_abort_source.sql b/services/game-session-service/src/main/resources/db/migration/V1035__canonical_gameplay_first_new_abort_source.sql new file mode 100644 index 0000000000..e0bff1b33c --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1035__canonical_gameplay_first_new_abort_source.sql @@ -0,0 +1,660 @@ +-- Retain Account's actual first-NEW ABORTED result on the existing transition. The cleanup UUID +-- is not a parallel decision ledger; the immutable Account lease and existing transition remain +-- the authority source. +ALTER TABLE game_session_canonical_binding_transition + ADD COLUMN admission_orphan_cleanup_id uuid, + ADD CONSTRAINT chk_gs_canonical_binding_transition_abort_cleanup CHECK ( + admission_orphan_cleanup_id IS NULL + OR (status = 'ABORTED' + AND admission_lease_id IS NOT NULL + AND admission_lease_kind = 'NEW_BINDING' + AND expected_prior_binding_ref IS NULL + AND expected_prior_binding_generation IS NULL + AND admission_orphan_cleanup_id <> + '00000000-0000-0000-0000-000000000000'::uuid)); + +CREATE UNIQUE INDEX uq_gs_canonical_binding_abort_cleanup + ON game_session_canonical_binding_transition (admission_orphan_cleanup_id) + WHERE admission_orphan_cleanup_id IS NOT NULL; + +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION require_running_runtime_for_lease_bound_binding_decision() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + runtime_row game_instances%ROWTYPE; + approved_first_new_abort boolean := false; +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.admission_lease_id IS NOT NULL + AND NEW.status IN ('PROVISIONAL', 'AMBIGUOUS') THEN + RAISE EXCEPTION 'Lease-bound runtime fence must be acquired from an existing PREPARED transition' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_requires_prepared_transition'; + END IF; + RETURN NEW; + END IF; + + -- Definitive Account abort is a permanent source, including after cleanup retries. + -- Inventory advancement may retain the source, but may never rewrite its decision. + IF OLD.status = 'ABORTED' AND OLD.admission_orphan_cleanup_id IS NOT NULL THEN + IF (to_jsonb(NEW) - 'inventory_revision') + IS DISTINCT FROM (to_jsonb(OLD) - 'inventory_revision') + OR NEW.inventory_revision < OLD.inventory_revision THEN + RAISE EXCEPTION 'Definitive first-NEW Account abort source is immutable' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_first_new_abort_terminal_source_immutable'; + END IF; + RETURN NEW; + END IF; + + IF OLD.status IN ('PROVISIONAL', 'AMBIGUOUS') + AND OLD.admission_lease_id IS NOT NULL THEN + IF OLD.status = 'PROVISIONAL' + AND NEW.status = 'ABORTED' + AND OLD.admission_lease_kind = 'NEW_BINDING' + AND OLD.expected_prior_binding_ref IS NULL + AND OLD.expected_prior_binding_generation IS NULL + AND OLD.admission_orphan_cleanup_id IS NULL + AND NEW.admission_orphan_cleanup_id IS NOT NULL + AND NEW.admission_orphan_cleanup_id <> + '00000000-0000-0000-0000-000000000000'::uuid + AND NEW.inventory_revision > OLD.inventory_revision THEN + approved_first_new_abort := true; + ELSIF NEW.status NOT IN ('PROVISIONAL', 'AMBIGUOUS') + OR (OLD.status = 'AMBIGUOUS' AND NEW.status <> 'AMBIGUOUS') THEN + RAISE EXCEPTION 'A lease-bound runtime fence cannot be released without definitive first-NEW Account abort evidence' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_terminal_owner_required'; + END IF; + + IF approved_first_new_abort + AND ROW( + NEW.transition_id, NEW.tenant_id, NEW.playable_state_namespace_id, + NEW.character_id, NEW.expected_prior_binding_ref, + NEW.expected_prior_binding_generation, NEW.candidate_binding_ref, + NEW.candidate_binding_generation, NEW.candidate_account_index_fence, + NEW.issuer_reservation_id, NEW.created_at, + NEW.account_coverage_state, NEW.account_coverage_operation_id, + NEW.account_coverage_lifecycle, NEW.account_coverage_operation_fence, + NEW.account_admission_fence_kind, NEW.account_admission_fence, + NEW.historical_account_admission_fence_kind, + NEW.historical_account_admission_fence, NEW.resolved_scope_kind, + NEW.resolved_scope_account_id, NEW.account_coverage_fence, + NEW.account_coverage_generation, NEW.account_inventory_snapshot_revision + ) IS DISTINCT FROM ROW( + OLD.transition_id, OLD.tenant_id, OLD.playable_state_namespace_id, + OLD.character_id, OLD.expected_prior_binding_ref, + OLD.expected_prior_binding_generation, OLD.candidate_binding_ref, + OLD.candidate_binding_generation, OLD.candidate_account_index_fence, + OLD.issuer_reservation_id, OLD.created_at, + OLD.account_coverage_state, OLD.account_coverage_operation_id, + OLD.account_coverage_lifecycle, OLD.account_coverage_operation_fence, + OLD.account_admission_fence_kind, OLD.account_admission_fence, + OLD.historical_account_admission_fence_kind, + OLD.historical_account_admission_fence, OLD.resolved_scope_kind, + OLD.resolved_scope_account_id, OLD.account_coverage_fence, + OLD.account_coverage_generation, OLD.account_inventory_snapshot_revision + ) THEN + RAISE EXCEPTION 'First-NEW abort cannot change its transition, Account-control, or inventory source' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_first_new_abort_transition_source_immutable'; + END IF; + + IF NOT approved_first_new_abort + AND NEW.admission_orphan_cleanup_id IS DISTINCT FROM OLD.admission_orphan_cleanup_id THEN + RAISE EXCEPTION 'A lease-bound cleanup identity requires the exact first-NEW Account abort transition' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_abort_cleanup_identity'; + END IF; + + IF ROW( + NEW.admission_request_id, + NEW.admission_lease_id, + NEW.admission_lease_fence, + NEW.admission_lease_kind, + NEW.admission_lease_digest, + NEW.admission_lease_evidence, + NEW.admission_resume_episode_id, + NEW.admission_expected_old_binding_generation, + NEW.admission_lease_expires_at, + NEW.admission_target_namespace, + NEW.admission_target_tenant_slug, + NEW.admission_target_tenant_id, + NEW.admission_target_world_slug, + NEW.admission_target_world_display_name, + NEW.admission_target_realm_id, + NEW.admission_target_realm_slug, + NEW.admission_target_realm_display_name, + NEW.admission_target_game_session_tenant_id, + NEW.admission_target_game_instance_id, + NEW.admission_target_playable_state_namespace_id, + NEW.admission_target_playable_state_scope, + NEW.admission_target_canonical_game_instance_id, + NEW.admission_target_canonical_version_id, + NEW.admission_target_runtime_version_id, + NEW.admission_target_catalog_revision, + NEW.admission_target_pointer_version, + NEW.admission_target_pointer_snapshot_digest, + NEW.admission_target_active_world_epoch, + NEW.admission_target_initial_admission_request_id, + NEW.admission_target_initial_admission_request_digest, + NEW.admission_target_origin_kind, + NEW.admission_target_expected_prior_pointer_version, + NEW.admission_target_hold_id, + NEW.admission_target_hold_fence, + NEW.admission_target_hold_binding_digest, + NEW.admission_target_audit_event_id, + NEW.admission_target_owner_proof_digest, + NEW.admission_target_owner_proof_outcome, + NEW.admission_target_positive_durable_abort, + NEW.admission_target_terminal_at, + NEW.admission_target_character_creation_policy + ) IS DISTINCT FROM ROW( + OLD.admission_request_id, + OLD.admission_lease_id, + OLD.admission_lease_fence, + OLD.admission_lease_kind, + OLD.admission_lease_digest, + OLD.admission_lease_evidence, + OLD.admission_resume_episode_id, + OLD.admission_expected_old_binding_generation, + OLD.admission_lease_expires_at, + OLD.admission_target_namespace, + OLD.admission_target_tenant_slug, + OLD.admission_target_tenant_id, + OLD.admission_target_world_slug, + OLD.admission_target_world_display_name, + OLD.admission_target_realm_id, + OLD.admission_target_realm_slug, + OLD.admission_target_realm_display_name, + OLD.admission_target_game_session_tenant_id, + OLD.admission_target_game_instance_id, + OLD.admission_target_playable_state_namespace_id, + OLD.admission_target_playable_state_scope, + OLD.admission_target_canonical_game_instance_id, + OLD.admission_target_canonical_version_id, + OLD.admission_target_runtime_version_id, + OLD.admission_target_catalog_revision, + OLD.admission_target_pointer_version, + OLD.admission_target_pointer_snapshot_digest, + OLD.admission_target_active_world_epoch, + OLD.admission_target_initial_admission_request_id, + OLD.admission_target_initial_admission_request_digest, + OLD.admission_target_origin_kind, + OLD.admission_target_expected_prior_pointer_version, + OLD.admission_target_hold_id, + OLD.admission_target_hold_fence, + OLD.admission_target_hold_binding_digest, + OLD.admission_target_audit_event_id, + OLD.admission_target_owner_proof_digest, + OLD.admission_target_owner_proof_outcome, + OLD.admission_target_positive_durable_abort, + OLD.admission_target_terminal_at, + OLD.admission_target_character_creation_policy + ) THEN + RAISE EXCEPTION 'A lease-bound runtime fence decision is immutable' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_decision_immutable'; + END IF; + ELSIF NEW.admission_lease_id IS NOT NULL + AND NEW.status IN ('PROVISIONAL', 'AMBIGUOUS') THEN + IF OLD.status <> 'PREPARED' + OR OLD.admission_lease_id IS NOT NULL + OR OLD.admission_request_id IS NOT NULL THEN + RAISE EXCEPTION 'Lease-bound runtime fence must be acquired from the exact PREPARED transition' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_requires_prepared_transition'; + END IF; + ELSE + RETURN NEW; + END IF; + + -- This SELECT is in the same transaction as markProvisional's transition UPDATE. Its row + -- lock serializes the decision with stop/replacement/deletion and is retained through commit. + SELECT runtime.* + INTO runtime_row + FROM game_instances runtime + JOIN game_session_canonical_instance_launch launch + ON launch.game_session_tenant_id = runtime.tenant_id + AND launch.game_instance_id = runtime.id + AND launch.game_instance_uuid = runtime.game_instance_uuid + JOIN game_session_canonical_gameplay_binding_inventory candidate + ON candidate.binding_ref = NEW.candidate_binding_ref + AND candidate.tenant_id = launch.canonical_tenant_id + AND candidate.runtime_game_instance_id = runtime.id + AND candidate.game_instance_id = runtime.game_instance_uuid + JOIN game_session_canonical_realm_catalog catalog + ON catalog.target_namespace = launch.target_namespace + AND catalog.canonical_tenant_id = launch.canonical_tenant_id + AND catalog.realm_id = launch.canonical_realm_id + AND catalog.world_slug = launch.world_slug + AND catalog.playable_state_namespace_id = launch.playable_state_namespace_id + AND catalog.catalog_revision = NEW.admission_target_catalog_revision + WHERE runtime.tenant_id = NEW.admission_target_game_session_tenant_id + AND runtime.id = NEW.admission_target_game_instance_id + AND runtime.status = 'RUNNING' + -- Match the decision's actual World ACTIVE read to the owner-recorded RUNNING row. V10 + -- independently requires the matching recorded PREPARING epoch to be exactly one lower. + AND runtime.run_owned_start_active_epoch = NEW.admission_target_active_world_epoch + AND runtime.game_instance_uuid = NEW.admission_target_canonical_game_instance_id + AND runtime.version_id = NEW.admission_target_runtime_version_id + AND runtime.game_template_id = launch.game_template_id + AND runtime.launch_descriptor_id = launch.launch_descriptor_id + AND runtime.release_bundle_id = launch.release_bundle_id + AND runtime.generation_config_revision = launch.generation_config_revision + AND runtime.version_state_epoch = launch.version_state_epoch + AND runtime.run_owned_start_request_id = launch.control_plane_request_id + AND runtime.run_owned_start_published_release_bundle_ref = + launch.complete_launch_binding_evidence -> 'descriptor' ->> 'publishedReleaseBundleRef' + AND launch.target_namespace = NEW.admission_target_namespace + AND launch.canonical_tenant_id = NEW.admission_target_tenant_id + AND launch.canonical_realm_id = NEW.admission_target_realm_id + AND catalog.tenant_slug = NEW.admission_target_tenant_slug + AND catalog.world_slug = NEW.admission_target_world_slug + AND catalog.source_world_display_name = NEW.admission_target_world_display_name + AND catalog.realm_slug = NEW.admission_target_realm_slug + AND catalog.realm_display_name = NEW.admission_target_realm_display_name + AND launch.playable_state_namespace_id = NEW.admission_target_playable_state_namespace_id + AND launch.playable_state_scope = NEW.admission_target_playable_state_scope + AND launch.version_id = NEW.admission_target_runtime_version_id + AND launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'canonicalVersionId' + = NEW.admission_target_canonical_version_id::text + AND catalog.visible + AND catalog.public_production + AND catalog.state_scope = 'SHARED' + AND launch.public_production + AND launch.playable_state_scope = 'SHARED' + AND launch.captured_starting_row_version <= runtime.row_version + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'targetNamespace' + = launch.target_namespace + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'controlPlaneRequestId' + = launch.control_plane_request_id + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'canonicalTenantId' + = launch.canonical_tenant_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'worldSlug' + = launch.world_slug + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'gameTemplateId' + = launch.game_template_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'launchDescriptorId' + = launch.launch_descriptor_id + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'versionId' + = launch.version_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'releaseBundleId' + = launch.release_bundle_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'generationConfigRevision' + = launch.generation_config_revision + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'versionStateEpoch' + = launch.version_state_epoch::text + FOR UPDATE OF runtime; + + IF NOT FOUND THEN + RAISE EXCEPTION 'Lease-bound binding decision requires the exact current RUNNING launch row and candidate identity' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_exact_running_launch_required'; + END IF; + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION reject_unowned_lease_bound_binding_release() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + IF (OLD.status IN ('PROVISIONAL', 'AMBIGUOUS') + AND OLD.admission_lease_id IS NOT NULL) + OR (OLD.status = 'ABORTED' + AND OLD.admission_lease_id IS NOT NULL + AND OLD.admission_orphan_cleanup_id IS NOT NULL) THEN + RAISE EXCEPTION 'A retained lease-bound binding source cannot be deleted' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_delete_owner_required'; + END IF; + RETURN OLD; + END IF; + + IF OLD.status IN ('PROVISIONAL', 'AMBIGUOUS') + AND OLD.admission_lease_id IS NOT NULL + AND (NEW.status NOT IN ('PROVISIONAL', 'AMBIGUOUS') + OR (OLD.status = 'AMBIGUOUS' AND NEW.status <> 'AMBIGUOUS')) THEN + IF OLD.status = 'PROVISIONAL' + AND NEW.status = 'ABORTED' + AND OLD.admission_lease_kind = 'NEW_BINDING' + AND OLD.expected_prior_binding_ref IS NULL + AND OLD.expected_prior_binding_generation IS NULL + AND OLD.admission_orphan_cleanup_id IS NULL + AND NEW.admission_orphan_cleanup_id IS NOT NULL + AND NEW.admission_orphan_cleanup_id <> + '00000000-0000-0000-0000-000000000000'::uuid + AND NEW.inventory_revision > OLD.inventory_revision THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'An unresolved lease-bound binding decision requires exact terminal owner reconciliation' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_terminal_owner_required'; + END IF; + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION reject_truncate_unresolved_lease_bound_binding() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM game_session_canonical_binding_transition transition + WHERE (transition.status IN ('PROVISIONAL', 'AMBIGUOUS') + AND transition.admission_lease_id IS NOT NULL) + OR (transition.status = 'ABORTED' + AND transition.admission_lease_id IS NOT NULL + AND transition.admission_orphan_cleanup_id IS NOT NULL) + ) THEN + RAISE EXCEPTION 'TRUNCATE cannot discard unresolved or retained-abort lease-bound binding decisions' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_transition_truncate_guard'; + END IF; + RETURN NULL; +END; +$$; + +CREATE FUNCTION require_first_new_abort_reservation_release() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF OLD.lifecycle = 'RESERVED' AND NEW.lifecycle = 'RELEASE_PENDING' THEN + IF NEW.inventory_revision <= OLD.inventory_revision + OR ROW( + NEW.reservation_id, NEW.binding_ref, NEW.account_id, NEW.tenant_id, + NEW.game_instance_id, NEW.runtime_game_instance_id, NEW.session_id, + NEW.binding_generation, NEW.transition_id, NEW.issuer_id, + NEW.issuer_auth_generation, NEW.playable_state_namespace_id, + NEW.character_id, NEW.playable_state_scope, NEW.region_id, NEW.region_epoch, + NEW.partition_id, NEW.issuer_index_layout_version, + NEW.issuer_index_partition_count, NEW.issuer_index_partition_capacity, + NEW.reservation_fence, NEW.issuer_coverage_operation_id, + NEW.issuer_coverage_operation_fence, NEW.coverage_fence, + NEW.inventory_snapshot_revision, NEW.created_at + ) IS DISTINCT FROM ROW( + OLD.reservation_id, OLD.binding_ref, OLD.account_id, OLD.tenant_id, + OLD.game_instance_id, OLD.runtime_game_instance_id, OLD.session_id, + OLD.binding_generation, OLD.transition_id, OLD.issuer_id, + OLD.issuer_auth_generation, OLD.playable_state_namespace_id, + OLD.character_id, OLD.playable_state_scope, OLD.region_id, OLD.region_epoch, + OLD.partition_id, OLD.issuer_index_layout_version, + OLD.issuer_index_partition_count, OLD.issuer_index_partition_capacity, + OLD.reservation_fence, OLD.issuer_coverage_operation_id, + OLD.issuer_coverage_operation_fence, OLD.coverage_fence, + OLD.inventory_snapshot_revision, OLD.created_at + ) THEN + RAISE EXCEPTION 'First-NEW abort reservation transition changed its retained owner tuple' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_first_new_abort_reservation_immutable'; + END IF; + + IF NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_binding_transition transition + JOIN game_session_canonical_gameplay_binding_inventory candidate + ON candidate.binding_ref = transition.candidate_binding_ref + WHERE transition.transition_id = NEW.transition_id + AND transition.status = 'ABORTED' + AND transition.admission_lease_id IS NOT NULL + AND transition.admission_lease_kind = 'NEW_BINDING' + AND transition.expected_prior_binding_ref IS NULL + AND transition.expected_prior_binding_generation IS NULL + AND transition.admission_orphan_cleanup_id IS NOT NULL + AND transition.admission_orphan_cleanup_id <> + '00000000-0000-0000-0000-000000000000'::uuid + AND transition.inventory_revision = NEW.inventory_revision + AND transition.issuer_reservation_id = NEW.reservation_id + AND transition.candidate_binding_ref = NEW.binding_ref + AND transition.candidate_binding_generation = NEW.binding_generation + AND transition.tenant_id = NEW.tenant_id + AND transition.playable_state_namespace_id = NEW.playable_state_namespace_id + AND transition.character_id = NEW.character_id + AND transition.candidate_account_index_fence = candidate.account_index_fence + AND candidate.lifecycle = 'PROVISIONAL' + AND candidate.inventory_revision = OLD.inventory_revision + AND candidate.transition_id = NEW.transition_id + AND candidate.issuer_reservation_id = NEW.reservation_id + AND candidate.account_id = NEW.account_id + AND candidate.tenant_id = NEW.tenant_id + AND candidate.playable_state_namespace_id = NEW.playable_state_namespace_id + AND candidate.character_id = NEW.character_id + AND candidate.game_instance_id = NEW.game_instance_id + AND candidate.runtime_game_instance_id = NEW.runtime_game_instance_id + AND candidate.session_id = NEW.session_id + AND candidate.region_id = NEW.region_id + AND candidate.region_epoch = NEW.region_epoch + AND candidate.issuer_id = NEW.issuer_id + AND candidate.issuer_auth_generation = NEW.issuer_auth_generation + AND candidate.issuer_index_layout_version = NEW.issuer_index_layout_version + AND candidate.issuer_index_partition_count = NEW.issuer_index_partition_count + AND candidate.issuer_index_partition_capacity = NEW.issuer_index_partition_capacity + AND candidate.binding_generation = NEW.binding_generation + AND candidate.binding_ref = NEW.binding_ref + AND candidate.account_index_fence = transition.candidate_account_index_fence + ) THEN + RAISE EXCEPTION 'Only an exact retained first-NEW Account abort may release its reservation' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_first_new_abort_reservation_source_required'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_first_new_abort_reservation_release + BEFORE UPDATE ON game_session_canonical_issuer_partition_reservation + FOR EACH ROW + EXECUTE FUNCTION require_first_new_abort_reservation_release(); + +CREATE FUNCTION require_first_new_abort_candidate_retention() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF OLD.lifecycle = 'PROVISIONAL' AND NEW.lifecycle = 'TERMINAL_UNRESOLVED' THEN + IF NEW.inventory_revision <= OLD.inventory_revision + OR ROW( + NEW.binding_ref, NEW.account_id, NEW.tenant_id, + NEW.playable_state_namespace_id, NEW.character_id, NEW.playable_state_scope, + NEW.game_instance_id, NEW.runtime_game_instance_id, NEW.session_id, + NEW.binding_generation, NEW.region_id, NEW.region_epoch, NEW.issuer_id, + NEW.issuer_auth_generation, NEW.issuer_index_layout_version, + NEW.issuer_index_partition_count, NEW.issuer_index_partition_capacity, + NEW.issuer_partition_id, NEW.account_index_fence, + NEW.issuer_reservation_id, NEW.transition_id, + NEW.account_index_state, NEW.issuer_index_state, NEW.created_at + ) IS DISTINCT FROM ROW( + OLD.binding_ref, OLD.account_id, OLD.tenant_id, + OLD.playable_state_namespace_id, OLD.character_id, OLD.playable_state_scope, + OLD.game_instance_id, OLD.runtime_game_instance_id, OLD.session_id, + OLD.binding_generation, OLD.region_id, OLD.region_epoch, OLD.issuer_id, + OLD.issuer_auth_generation, OLD.issuer_index_layout_version, + OLD.issuer_index_partition_count, OLD.issuer_index_partition_capacity, + OLD.issuer_partition_id, OLD.account_index_fence, + OLD.issuer_reservation_id, OLD.transition_id, + OLD.account_index_state, OLD.issuer_index_state, OLD.created_at + ) THEN + RAISE EXCEPTION 'First-NEW abort candidate transition changed its retained owner tuple' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_first_new_abort_candidate_immutable'; + END IF; + + IF NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_binding_transition transition + JOIN game_session_canonical_issuer_partition_reservation reservation + ON reservation.reservation_id = transition.issuer_reservation_id + WHERE transition.transition_id = NEW.transition_id + AND transition.status = 'ABORTED' + AND transition.admission_lease_id IS NOT NULL + AND transition.admission_lease_kind = 'NEW_BINDING' + AND transition.expected_prior_binding_ref IS NULL + AND transition.expected_prior_binding_generation IS NULL + AND transition.admission_orphan_cleanup_id IS NOT NULL + AND transition.inventory_revision = NEW.inventory_revision + AND transition.candidate_binding_ref = NEW.binding_ref + AND transition.candidate_binding_generation = NEW.binding_generation + AND transition.candidate_account_index_fence = NEW.account_index_fence + AND transition.issuer_reservation_id = NEW.issuer_reservation_id + AND transition.tenant_id = NEW.tenant_id + AND transition.playable_state_namespace_id = NEW.playable_state_namespace_id + AND transition.character_id = NEW.character_id + AND reservation.lifecycle = 'RELEASE_PENDING' + AND reservation.inventory_revision = NEW.inventory_revision + AND reservation.transition_id = NEW.transition_id + AND reservation.binding_ref = NEW.binding_ref + AND reservation.binding_generation = NEW.binding_generation + AND reservation.account_id = NEW.account_id + AND reservation.tenant_id = NEW.tenant_id + AND reservation.playable_state_namespace_id = NEW.playable_state_namespace_id + AND reservation.character_id = NEW.character_id + AND reservation.game_instance_id = NEW.game_instance_id + AND reservation.runtime_game_instance_id = NEW.runtime_game_instance_id + AND reservation.session_id = NEW.session_id + AND reservation.region_id = NEW.region_id + AND reservation.region_epoch = NEW.region_epoch + AND reservation.issuer_id = NEW.issuer_id + AND reservation.issuer_auth_generation = NEW.issuer_auth_generation + AND reservation.issuer_index_layout_version = NEW.issuer_index_layout_version + AND reservation.issuer_index_partition_count = NEW.issuer_index_partition_count + AND reservation.issuer_index_partition_capacity = NEW.issuer_index_partition_capacity + ) THEN + RAISE EXCEPTION 'Only an exact retained first-NEW Account abort may retain its candidate unresolved' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_first_new_abort_candidate_source_required'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_first_new_abort_candidate_retention + BEFORE UPDATE ON game_session_canonical_gameplay_binding_inventory + FOR EACH ROW + EXECUTE FUNCTION require_first_new_abort_candidate_retention(); + +CREATE FUNCTION require_first_new_abort_source_complete() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_binding_transition transition + JOIN game_session_canonical_gameplay_binding_inventory candidate + ON candidate.binding_ref = transition.candidate_binding_ref + JOIN game_session_canonical_issuer_partition_reservation reservation + ON reservation.reservation_id = transition.issuer_reservation_id + JOIN game_session_canonical_binding_account_index_obligation account_obligation + ON account_obligation.transition_id = transition.transition_id + AND account_obligation.obligation_ordinal = 0 + JOIN game_session_canonical_binding_issuer_index_obligation issuer_obligation + ON issuer_obligation.transition_id = transition.transition_id + AND issuer_obligation.binding_ref = transition.candidate_binding_ref + JOIN game_session_canonical_binding_region_bridge_obligation region_obligation + ON region_obligation.transition_id = transition.transition_id + WHERE transition.transition_id = NEW.transition_id + AND transition.status = 'ABORTED' + AND transition.admission_lease_id IS NOT NULL + AND transition.admission_lease_kind = 'NEW_BINDING' + AND transition.admission_lease_evidence IS NOT NULL + AND transition.admission_lease_digest IS NOT NULL + AND transition.expected_prior_binding_ref IS NULL + AND transition.expected_prior_binding_generation IS NULL + AND transition.admission_orphan_cleanup_id IS NOT NULL + AND transition.admission_orphan_cleanup_id <> + '00000000-0000-0000-0000-000000000000'::uuid + AND transition.inventory_revision = candidate.inventory_revision + AND transition.inventory_revision = reservation.inventory_revision + AND transition.inventory_revision = account_obligation.inventory_revision + AND transition.inventory_revision = issuer_obligation.inventory_revision + AND transition.inventory_revision = region_obligation.inventory_revision + AND transition.candidate_binding_ref = candidate.binding_ref + AND transition.candidate_binding_generation = candidate.binding_generation + AND transition.candidate_account_index_fence = candidate.account_index_fence + AND transition.issuer_reservation_id = candidate.issuer_reservation_id + AND transition.tenant_id = candidate.tenant_id + AND transition.playable_state_namespace_id = candidate.playable_state_namespace_id + AND transition.character_id = candidate.character_id + AND candidate.lifecycle = 'TERMINAL_UNRESOLVED' + AND reservation.lifecycle = 'RELEASE_PENDING' + AND reservation.transition_id = transition.transition_id + AND reservation.binding_ref = candidate.binding_ref + AND reservation.binding_generation = candidate.binding_generation + AND reservation.reservation_fence IS NOT NULL + AND reservation.account_id = candidate.account_id + AND reservation.tenant_id = candidate.tenant_id + AND reservation.playable_state_namespace_id = candidate.playable_state_namespace_id + AND reservation.character_id = candidate.character_id + AND reservation.game_instance_id = candidate.game_instance_id + AND reservation.runtime_game_instance_id = candidate.runtime_game_instance_id + AND reservation.session_id = candidate.session_id + AND reservation.region_id = candidate.region_id + AND reservation.region_epoch = candidate.region_epoch + AND reservation.issuer_id = candidate.issuer_id + AND reservation.issuer_auth_generation = candidate.issuer_auth_generation + AND reservation.issuer_index_layout_version = candidate.issuer_index_layout_version + AND reservation.issuer_index_partition_count = candidate.issuer_index_partition_count + AND reservation.issuer_index_partition_capacity = candidate.issuer_index_partition_capacity + AND account_obligation.binding_ref = candidate.binding_ref + AND account_obligation.account_id = candidate.account_id + AND account_obligation.tenant_id = candidate.tenant_id + AND account_obligation.action = 'ADD_OR_RETAIN' + AND account_obligation.binding_generation = candidate.binding_generation + AND account_obligation.expected_prior_generation IS NULL + AND account_obligation.account_index_fence = candidate.account_index_fence + AND account_obligation.execution_phase = 'BEFORE_FINAL_CAS' + AND account_obligation.status = 'REQUIRED' + AND (SELECT count(*) + FROM game_session_canonical_binding_account_index_obligation extra_account + WHERE extra_account.transition_id = transition.transition_id) = 1 + AND issuer_obligation.reservation_id = reservation.reservation_id + AND issuer_obligation.binding_ref = candidate.binding_ref + AND issuer_obligation.binding_generation = candidate.binding_generation + AND issuer_obligation.status = 'REQUIRED' + AND (SELECT count(*) + FROM game_session_canonical_binding_issuer_index_obligation extra_issuer + WHERE extra_issuer.transition_id = transition.transition_id) = 1 + AND region_obligation.binding_ref = candidate.binding_ref + AND region_obligation.binding_generation = candidate.binding_generation + AND region_obligation.account_id = candidate.account_id + AND region_obligation.tenant_id = candidate.tenant_id + AND region_obligation.game_instance_id = candidate.game_instance_id + AND region_obligation.runtime_game_instance_id = candidate.runtime_game_instance_id + AND region_obligation.session_id = candidate.session_id + AND region_obligation.region_id = candidate.region_id + AND region_obligation.region_epoch = candidate.region_epoch + AND region_obligation.status = 'REQUIRED' + AND NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_gameplay_binding_inventory active + WHERE active.tenant_id = candidate.tenant_id + AND active.playable_state_namespace_id = candidate.playable_state_namespace_id + AND active.character_id = candidate.character_id + AND active.lifecycle = 'ACTIVE') + ) THEN + RAISE EXCEPTION 'First-NEW Account abort requires its exact retained candidate, reservation, and unresolved obligations' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_first_new_abort_source_incomplete'; + END IF; + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER game_session_first_new_abort_source_atomic + AFTER UPDATE ON game_session_canonical_binding_transition + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW + WHEN (NEW.status = 'ABORTED' AND NEW.admission_lease_id IS NOT NULL) + EXECUTE FUNCTION require_first_new_abort_source_complete(); + +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-add.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-add.lua new file mode 100644 index 0000000000..fe79426301 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-add.lua @@ -0,0 +1,404 @@ +-- Project one SQL-registered ordinary issuer reservation and, only after its V29 phase +-- qualifies, its binding member. KEYS[1] is the only issuer partition hash. +local keyPrefix = 'session:game:index:issuer:' +local metadataField = '!issuer-partition-bootstrap/v1' +local capacityPrefix = '!issuer-reservation-capacity/v1:' +local maxDecimalBytes = 256 +local maxBindingRefBytes = 6144 +local maxMemberValueBytes = 65536 +local maxMetadataBytes = 65536 +local maxMemberOperations = 256 +local maxHashFields = 1025 +local maxHashBytes = 16777216 + +local function uuid(value) + return type(value) == 'string' and #value == 36 + and string.match(value, '^%x%x%x%x%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x$') + and value == string.lower(value) + and value ~= '00000000-0000-0000-0000-000000000000' +end + +local function positive(value) + return type(value) == 'string' and #value > 0 and #value <= maxDecimalBytes + and string.match(value, '^[1-9][0-9]*$') ~= nil +end + +local function nonnegative(value) + return value == '0' or positive(value) +end + +local function digest(value) + return type(value) == 'string' and #value == 71 + and string.match(value, '^sha256:[0-9a-f]+$') ~= nil +end + +local function greaterDecimal(left, right) + if #left ~= #right then return #left > #right end + return left > right +end + +local function readSegment(bytes, offset) + local start = offset + while offset <= #bytes do + local char = string.byte(bytes, offset) + if char < 48 or char > 57 then break end + offset = offset + 1 + end + if offset == start or offset > #bytes or string.byte(bytes, offset) ~= 58 then return nil end + if offset - start > 1 and string.byte(bytes, start) == 48 then return nil end + local lengthText = string.sub(bytes, start, offset - 1) + if #lengthText > 5 then return nil end + local length = tonumber(lengthText) + if not length or length > maxBindingRefBytes or offset + length > #bytes then return nil end + local valueStart = offset + 1 + local valueEnd = offset + length + return string.sub(bytes, valueStart, valueEnd), valueEnd + 1 +end + +local function canonicalBindingRef(bytes, member) + if type(bytes) ~= 'string' or #bytes == 0 or #bytes > maxBindingRefBytes then return false end + local domain, offset = readSegment(bytes, 1) + if domain ~= 'bindingRef/v1' or not offset then return false end + local tenant, afterTenant = readSegment(bytes, offset) + local instance, afterInstance = readSegment(bytes, afterTenant) + local session, afterSession = readSegment(bytes, afterInstance) + if not tenant or not instance or not session or not afterSession or afterSession ~= #bytes + 1 then + return false + end + return uuid(tenant) and uuid(instance) and uuid(session) + and tenant == member.tenantId and instance == member.gameInstanceId and session == member.sessionId +end + +local function sameIncarnation(left, right) + if type(left) ~= 'table' or type(right) ~= 'table' + or left.attestorBinding ~= right.attestorBinding + or left.acceptedAttestationDigest ~= right.acceptedAttestationDigest + or left.coordOpsRoAclDigest ~= right.coordOpsRoAclDigest + or left.coordRedisConfigObservedDigest ~= right.coordRedisConfigObservedDigest then return false end + local a = left.targetDeploymentEvidence + local b = right.targetDeploymentEvidence + if type(a) ~= 'table' or type(b) ~= 'table' + or a.deploymentIdentity ~= b.deploymentIdentity + or a.deploymentGeneration ~= b.deploymentGeneration + or a.redisBuildIdentity ~= b.redisBuildIdentity + or a.luaScriptRegistryVersion ~= b.luaScriptRegistryVersion + or a.luaScriptRegistryDigest ~= b.luaScriptRegistryDigest + or a.startupState ~= b.startupState + or a.bootGeneration ~= b.bootGeneration + or a.startupGeneration ~= b.startupGeneration + or a.storageGeneration ~= b.storageGeneration + or a.aofGeneration ~= b.aofGeneration + or type(a.canonicalNodeSet) ~= 'table' + or type(b.canonicalNodeSet) ~= 'table' + or #a.canonicalNodeSet ~= #b.canonicalNodeSet then return false end + for index = 1, #a.canonicalNodeSet do + if a.canonicalNodeSet[index] ~= b.canonicalNodeSet[index] then return false end + end + return true +end + +local function validMember(member, memberBytes, issuerId, partitionId, metadata, bindingRef, operationId, reservationId) + if type(member) ~= 'table' or type(member.layout) ~= 'table' + or type(member.reservation) ~= 'table' or type(member.anchor) ~= 'table' + or type(member.memberOperation) ~= 'table' or type(member.incarnation) ~= 'table' + or member.schemaVersion ~= 2 or member.issuerId ~= issuerId + or member.issuerId ~= metadata.issuerId + or member.issuerAuthGeneration ~= metadata.anchor.issuerAuthGeneration + or member.issuerControlEpoch ~= metadata.issuerControlEpoch + or member.issuerIndexLayoutVersion ~= metadata.layout.version + or member.layout.partitionCount ~= metadata.layout.partitionCount + or member.layout.partitionCapacity ~= metadata.layout.partitionCapacity + or member.layout.mappingIdentity ~= metadata.layout.mappingIdentity + or member.layout.descriptorBytes ~= metadata.layout.descriptorBytes + or member.layout.descriptorDigest ~= metadata.layout.descriptorDigest + or member.anchor.issuerCoverageOperationId ~= metadata.anchor.issuerCoverageOperationId + or member.anchor.operationFence ~= metadata.anchor.operationFence + or member.anchor.coverageFence ~= metadata.anchor.coverageFence + or member.anchor.issuerInventorySnapshotRevision ~= metadata.anchor.issuerInventorySnapshotRevision + or member.anchor.sourceCheckpointBytes ~= metadata.anchor.sourceCheckpointBytes + or member.anchor.sourceCheckpointDigest ~= metadata.anchor.sourceCheckpointDigest + or member.anchor.sourceEventBytes ~= metadata.anchor.sourceEventBytes + or member.anchor.sourceEventDigest ~= metadata.anchor.sourceEventDigest + or member.reservation.reservationId ~= reservationId + or member.reservation.partitionId ~= partitionId + or member.memberOperation.operationId ~= operationId + or (bindingRef ~= nil and not canonicalBindingRef(bindingRef, member)) + or not uuid(member.accountId) or not uuid(member.tenantId) + or not uuid(member.gameInstanceId) or not uuid(member.sessionId) + or not uuid(member.playableStateNamespaceId) or not uuid(member.characterId) + or not uuid(member.regionId) or not uuid(member.reservation.transitionId) + or not uuid(member.reservation.reservationFence) + or not uuid(member.reservation.issuerCoverageOperationId) + or not positive(member.bindingGeneration) or not positive(member.issuerAuthGeneration) + or not positive(member.issuerIndexLayoutVersion) or not positive(member.regionEpoch) + or not positive(member.issuerControlEpoch) + or not positive(member.layout.partitionCount) or not positive(member.layout.partitionCapacity) + or not positive(member.reservation.issuerCoverageOperationFence) + or not positive(member.reservation.coverageFence) + or not positive(member.reservation.inventorySnapshotRevision) + or not positive(member.reservation.inventoryRevision) + or not positive(member.anchor.operationFence) + or not positive(member.anchor.coverageFence) + or not positive(member.anchor.issuerInventorySnapshotRevision) + or not positive(member.memberOperation.operationFence) + or not positive(member.memberOperation.coverageGeneration) + or not digest(member.layout.descriptorDigest) + or not digest(member.anchor.sourceCheckpointDigest) + or (member.anchor.sourceEventDigest ~= cjson.null and not digest(member.anchor.sourceEventDigest)) + or not sameIncarnation(member.incarnation, metadata.incarnation) then return false end + if member.reservation.lifecycle ~= 'RESERVED' and member.reservation.lifecycle ~= 'BOUND' + and member.reservation.lifecycle ~= 'RELEASE_PENDING' and member.reservation.lifecycle ~= 'RELEASED' then + return false + end + return true +end + +if #KEYS ~= 1 or #ARGV < 13 then return -2 end +if type(KEYS[1]) ~= 'string' or #KEYS[1] > 512 or string.sub(KEYS[1], 1, #keyPrefix) ~= keyPrefix then + return -2 +end + +local issuerId = ARGV[1] +local partitionId = ARGV[2] +local partitionCount = ARGV[3] +local partitionCapacity = ARGV[4] +local baselineCountText = ARGV[5] +if issuerId ~= 'firemud-account-service' or not nonnegative(partitionId) + or not positive(partitionCount) or not positive(partitionCapacity) + or not positive(baselineCountText) then return -2 end +local baselineCount = tonumber(baselineCountText) +if not baselineCount or baselineCount > maxHashFields then return -2 end + +local cursor = 6 +local baseline = {} +local baselineCapacity = 0 +local baselineReservations = 0 +local baselineBindings = 0 +local baselineCapacityMembers = {} +local baselineBindingMembers = {} +local metadataBytes = nil +for index = 1, baselineCount do + local field = ARGV[cursor] + local valueBytes = ARGV[cursor + 1] + cursor = cursor + 2 + if type(field) ~= 'string' or #field == 0 or baseline[field] ~= nil + or type(valueBytes) ~= 'string' or #valueBytes == 0 or #valueBytes > maxMemberValueBytes then return -2 end + baseline[field] = valueBytes + if field == metadataField then + metadataBytes = valueBytes + else + local decodedOk, value = pcall(cjson.decode, valueBytes) + if not decodedOk or type(value) ~= 'table' or type(value.reservation) ~= 'table' then return -2 end + if string.sub(field, 1, #capacityPrefix) == capacityPrefix then + local reservationId = string.sub(field, #capacityPrefix + 1) + if not uuid(reservationId) or value.reservation.reservationId ~= reservationId then return -2 end + baselineCapacityMembers[reservationId] = valueBytes + baselineReservations = baselineReservations + 1 + if value.reservation.lifecycle ~= 'RELEASED' then baselineCapacity = baselineCapacity + 1 end + else + if string.sub(field, 1, 1) == '!' + or not canonicalBindingRef(field, value) + or not uuid(value.reservation.reservationId) then return -2 end + if baselineBindingMembers[value.reservation.reservationId] ~= nil then return -2 end + baselineBindingMembers[value.reservation.reservationId] = valueBytes + baselineBindings = baselineBindings + 1 + end + end +end +for reservationId, memberBytes in pairs(baselineBindingMembers) do + if baselineCapacityMembers[reservationId] ~= memberBytes then return -2 end +end +if metadataBytes == nil or #metadataBytes > maxMetadataBytes then return -2 end +local metadataOk, metadata = pcall(cjson.decode, metadataBytes) +if not metadataOk or type(metadata) ~= 'table' or metadata.schemaVersion ~= 1 + or metadata.issuerId ~= issuerId or metadata.partitionId ~= partitionId + or type(metadata.layoutTag) ~= 'string' or #metadata.layoutTag ~= 70 + or not string.match(metadata.layoutTag, '^il%-v1%-%x+$') + or type(metadata.bootstrap) ~= 'table' or type(metadata.build) ~= 'table' + or type(metadata.layout) ~= 'table' or type(metadata.anchor) ~= 'table' + or type(metadata.incarnation) ~= 'table' + or metadata.layout.partitionCount ~= partitionCount + or metadata.layout.partitionCapacity ~= partitionCapacity + or metadata.layout.mappingIdentity ~= 'bindingRef/v1;sha256-u256-mod/v1' + or metadata.anchor.issuerCoverageOperationId ~= metadata.bootstrap.operationId + or metadata.anchor.operationFence ~= metadata.bootstrap.operationFence + or metadata.anchor.coverageFence ~= metadata.bootstrap.coverageFence + or metadata.anchor.issuerInventorySnapshotRevision ~= metadata.bootstrap.issuerInventorySnapshotRevision + or metadata.issuerControlEpoch ~= metadata.bootstrap.controlEpoch + or not uuid(metadata.bootstrap.operationId) or not uuid(metadata.bootstrap.requestId) + or not uuid(metadata.build.operationId) + or not positive(metadata.bootstrap.operationFence) + or not positive(metadata.bootstrap.coverageFence) + or metadata.bootstrap.operationFence == metadata.bootstrap.coverageFence + or not positive(metadata.bootstrap.issuerInventorySnapshotRevision) + or not positive(metadata.issuerControlEpoch) + or not digest(metadata.bootstrap.cohortDigest) + or not digest(metadata.build.planDigest) then return -2 end +local expectedKey = keyPrefix .. '{' .. metadata.layoutTag .. '}:' .. issuerId .. ':' .. partitionId +if KEYS[1] ~= expectedKey or not greaterDecimal(partitionCount, partitionId) then return -2 end + +for field, valueBytes in pairs(baseline) do + if field ~= metadataField then + local decodedOk, member = pcall(cjson.decode, valueBytes) + if not decodedOk or type(member) ~= 'table' or type(member.reservation) ~= 'table' + or type(member.memberOperation) ~= 'table' then return -2 end + if not validMember( + member, + valueBytes, + issuerId, + partitionId, + metadata, + nil, + member.memberOperation.operationId, + member.reservation.reservationId) then return -2 end + if string.sub(field, 1, #capacityPrefix) ~= capacityPrefix + and not canonicalBindingRef(field, member) then return -2 end + end +end + +local allowed = {} +local allowedCount = 0 +local totalExpectedBytes = 0 +local function putAllowed(field, valueBytes) + if type(field) ~= 'string' or #field == 0 or allowed[field] ~= nil then return false end + allowed[field] = valueBytes + allowedCount = allowedCount + 1 + totalExpectedBytes = totalExpectedBytes + #field + #valueBytes + return allowedCount <= maxHashFields and totalExpectedBytes <= maxHashBytes +end +for field, valueBytes in pairs(baseline) do + if not putAllowed(field, valueBytes) then return -2 end +end + +local operationCountText = ARGV[cursor] +cursor = cursor + 1 +if not positive(operationCountText) then return -2 end +local operationCount = tonumber(operationCountText) +if not operationCount or operationCount > maxMemberOperations then return -2 end +local seenOperationIds = {} +local seenReservationIds = {} +local seenBindings = {} +local registeredOperations = {} +local localCapacity = 0 +local localBindingCount = 0 +local targetOperationId = ARGV[cursor + operationCount * 6] +local targetReservationId = ARGV[cursor + operationCount * 6 + 1] +local targetBindingRef = ARGV[cursor + operationCount * 6 + 2] +local targetMemberBytes = ARGV[cursor + operationCount * 6 + 3] +local targetBindingPresent = ARGV[cursor + operationCount * 6 + 4] +local plannedPartitionCapacity = ARGV[cursor + operationCount * 6 + 5] +local plannedAggregateCapacity = ARGV[cursor + operationCount * 6 + 6] +local aggregateBound = ARGV[cursor + operationCount * 6 + 7] +if not uuid(targetOperationId) or not uuid(targetReservationId) + or type(targetBindingRef) ~= 'string' or type(targetMemberBytes) ~= 'string' + or (targetBindingPresent ~= '0' and targetBindingPresent ~= '1') + or not nonnegative(plannedPartitionCapacity) + or not nonnegative(plannedAggregateCapacity) + or not positive(aggregateBound) + or #ARGV ~= cursor + operationCount * 6 + 7 then return -2 end + +local targetFound = false +local position = cursor +for index = 1, operationCount do + local operationId = ARGV[position] + local bindingRef = ARGV[position + 1] + local reservationId = ARGV[position + 2] + local memberBytes = ARGV[position + 3] + local bindingPresent = ARGV[position + 4] + local countsCapacity = ARGV[position + 5] + position = position + 6 + if not uuid(operationId) or not uuid(reservationId) + or (bindingPresent ~= '0' and bindingPresent ~= '1') + or countsCapacity ~= '1' + or type(memberBytes) ~= 'string' or #memberBytes == 0 or #memberBytes > maxMemberValueBytes + or seenOperationIds[operationId] or seenReservationIds[reservationId] + or seenBindings[bindingRef] then return -2 end + local decodedOk, member = pcall(cjson.decode, memberBytes) + if not decodedOk or not validMember(member, memberBytes, issuerId, partitionId, metadata, bindingRef, operationId, reservationId) then return -2 end + if member.reservation.lifecycle == 'RELEASED' then return -2 end + seenOperationIds[operationId] = true + seenReservationIds[reservationId] = true + seenBindings[bindingRef] = true + registeredOperations[#registeredOperations + 1] = { + bindingRef = bindingRef, + reservationId = reservationId, + memberBytes = memberBytes, + bindingPresent = bindingPresent + } + localCapacity = localCapacity + 1 + local capacityField = capacityPrefix .. reservationId + if not putAllowed(capacityField, memberBytes) then return -2 end + if bindingPresent == '1' then + if string.sub(bindingRef, 1, 1) == '!' or not putAllowed(bindingRef, memberBytes) then return -2 end + localBindingCount = localBindingCount + 1 + end + if operationId == targetOperationId then + if reservationId ~= targetReservationId or bindingRef ~= targetBindingRef + or memberBytes ~= targetMemberBytes or bindingPresent ~= targetBindingPresent then return -2 end + targetFound = true + end +end +if not targetFound or not seenOperationIds[targetOperationId] + or tostring(localCapacity + baselineCapacity) ~= plannedPartitionCapacity + or greaterDecimal(plannedPartitionCapacity, partitionCapacity) + or greaterDecimal(plannedAggregateCapacity, aggregateBound) then return -2 end +local targetCapacityField = capacityPrefix .. targetReservationId +if not allowed[targetCapacityField] or allowed[targetCapacityField] ~= targetMemberBytes then return -2 end +if targetBindingPresent == '1' and allowed[targetBindingRef] ~= targetMemberBytes then return -2 end + +-- A missing header, legacy key, wrong type, expiration, omitted baseline field, extra field, +-- or conflicting registered post-baseline value is refused before any write. +local kind = redis.call('TYPE', KEYS[1]).ok +if kind ~= 'hash' or redis.call('PTTL', KEYS[1]) ~= -1 then return -1 end +local actual = redis.call('HGETALL', KEYS[1]) +if #actual % 2 ~= 0 or #actual / 2 > maxHashFields then return -1 end +local actualCapacityCount = 0 +local actualReservationCount = 0 +local actualBindingCount = 0 +local totalActualBytes = 0 +local actualFields = {} +for index = 1, #actual, 2 do + local field = actual[index] + local valueBytes = actual[index + 1] + actualFields[field] = valueBytes + totalActualBytes = totalActualBytes + #field + #valueBytes + if totalActualBytes > maxHashBytes then return -1 end + local expected = allowed[field] + if expected == nil or expected ~= valueBytes then return -1 end + if string.sub(field, 1, #capacityPrefix) == capacityPrefix then + local decodedOk, member = pcall(cjson.decode, valueBytes) + if not decodedOk or type(member) ~= 'table' or type(member.reservation) ~= 'table' then return -1 end + actualReservationCount = actualReservationCount + 1 + if member.reservation.lifecycle ~= 'RELEASED' then actualCapacityCount = actualCapacityCount + 1 end + elseif field ~= metadataField then + actualBindingCount = actualBindingCount + 1 + end +end +for _, operation in ipairs(registeredOperations) do + local capacity = actualFields[capacityPrefix .. operation.reservationId] + local binding = actualFields[operation.bindingRef] + if binding ~= nil and capacity == nil then return -1 end + if capacity ~= nil and capacity ~= operation.memberBytes then return -1 end + if binding ~= nil and binding ~= operation.memberBytes then return -1 end +end +for field, valueBytes in pairs(baseline) do + if redis.call('HGET', KEYS[1], field) ~= valueBytes then return -1 end +end +if actualCapacityCount > tonumber(plannedPartitionCapacity) + or actualReservationCount < baselineReservations + or actualBindingCount < baselineBindings + or actualBindingCount > baselineBindings + localBindingCount then return -1 end + +local capacityBefore = redis.call('HGET', KEYS[1], targetCapacityField) +local bindingBefore = redis.call('HGET', KEYS[1], targetBindingRef) +if capacityBefore ~= nil and capacityBefore ~= false and capacityBefore ~= targetMemberBytes then return -1 end +if bindingBefore ~= nil and bindingBefore ~= false and targetBindingPresent == '1' + and bindingBefore ~= targetMemberBytes then return -1 end +if targetBindingPresent == '0' and bindingBefore ~= nil and bindingBefore ~= false then return -1 end +local changedCapacity = capacityBefore == false or capacityBefore == nil +local changedBinding = targetBindingPresent == '1' and (bindingBefore == false or bindingBefore == nil) +if changedCapacity then redis.call('HSET', KEYS[1], targetCapacityField, targetMemberBytes) end +if changedBinding then redis.call('HSET', KEYS[1], targetBindingRef, targetMemberBytes) end +if changedBinding then return 2 end +if changedCapacity then return 1 end +return 3 diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-add.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-add.json new file mode 100644 index 0000000000..8e090902a7 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-add.json @@ -0,0 +1,40 @@ +{ + "scriptId": "game-session.issuer-binding-local-add.v1", + "resourcePath": "redis/lua/game-session-issuer-binding-local-add.lua", + "sha256": "af4673f3218afb68d6730a5aea901a551c24a128fc86a6e6412a6dc37ad845cf", + "owner": "game-session-service", + "principal": "gamesession_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "issuerPartition", + "ownedPrefix": "session:game:index:issuer:", + "hashTagDeclaration": "REQUIRED" + } + ], + "arguments": [ + {"name": "issuerId"}, + {"name": "partitionId"}, + {"name": "partitionCount"}, + {"name": "partitionCapacity"}, + {"name": "baselineFieldCountAndExactFieldValuePairs"}, + {"name": "registeredLocalOperationCountAndExactOperationTupleAndCurrentPhase"}, + {"name": "targetOperationAndRequiredFieldsAndCapacityCounts"} + ], + "category": "SESSION_ISSUER_INDEX", + "outcomes": [ + {"code": "CAPACITY_RESERVED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "MEMBER_PROJECTED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "LOCAL_OPERATION_REPLAY", "category": "REPLAY", "effect": "NON_MUTATING"}, + {"code": "TYPE_TTL_OR_FIELDSET_REFUSED", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, + {"code": "INVALID_ARGUMENTS_OR_CAPACITY", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} + ], + "resetSensitivity": "CLUSTER", + "tailLossBehavior": "This local one-key projection requires the exact positively installed issuer anchor, complete immutable partition baseline, and complete SQL-registered post-baseline reservation set. Existing baseline fields must all remain present and exact. A locally registered pending field may be absent or exact, while the physical owner mutates only the target original capacity field and its SQL-qualified target binding field. Missing baseline/header, legacy or malformed values, unknown fields, current source or incarnation movement, or incomplete SQL accounting leaves the operation unqualified. The result is physical readback evidence only; it does not acknowledge issuer-wide coverage, open a barrier, or authorize admission.", + "lossClass": "EMPTY_REDIS_COLD_START_OR_RESET", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [ + {"callerVersion": "v1", "payloadVersion": "v2"} + ], + "legacyPayloadShape": null +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java new file mode 100644 index 0000000000..96854568b9 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java @@ -0,0 +1,182 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.nio.file.Path; +import java.util.UUID; +import java.util.EnumSet; +import java.util.List; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventorySnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.springframework.jdbc.datasource.DriverManagerDataSource; + +/** + * Actual GS durable decision owner for the Account/GS abort composition test. Launch producers, + * initial admission target and empty-cohort/storage/index collaborators remain controlled fixtures. + * The actual migration owner publishes VERIFIED; no collaborator supplies an Account terminal + * result or replaces the GS reverse decision read. + */ +public final class CanonicalGameplayAdmissionAbortCompositionFixture implements AutoCloseable { + private final DriverManagerDataSource dataSource; + private final String schema = "gs_abort_composition_" + UUID.randomUUID().toString().replace("-", ""); + private final CanonicalGameplayBindingInventoryRepository repository; + private final CanonicalPlayableTarget target; + private final CanonicalGameplayBindingIdentity identity; + private final UUID transitionId = UUID.randomUUID(); + private final BigInteger generation; + private final DSLContext dsl; + + public CanonicalGameplayAdmissionAbortCompositionFixture( + DriverManagerDataSource accountDataSource, Candidate accountCandidate) { + dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl(accountDataSource.getUrl().replaceAll("currentSchema=[^&]+", "currentSchema=" + schema)); + dataSource.setUsername(accountDataSource.getUsername()); + dataSource.setPassword(accountDataSource.getPassword()); + Flyway.configure().dataSource(dataSource).schemas(schema).defaultSchema(schema) + .placeholders(java.util.Map.of("serviceSchema", schema)) + .locations("filesystem:" + Path.of("../game-session-service/src/main/resources/db/migration").toAbsolutePath().normalize()) + .load().migrate(); + dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + var runtime = CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource, accountCandidate.tenantId(), "test"); + target = runtime.playableTarget(); + identity = new CanonicalGameplayBindingIdentity( + accountCandidate.accountId(), accountCandidate.tenantId(), target.playableStateNamespaceId(), + accountCandidate.characterId(), target.playableStateScope(), target.canonicalGameInstanceId(), + target.gameInstanceId(), accountCandidate.sessionId().toString(), accountCandidate.regionId(), + accountCandidate.regionEpoch(), accountCandidate.issuerId(), accountCandidate.issuerAuthGeneration(), + accountCandidate.issuerIndexLayoutVersion(), accountCandidate.issuerIndexPartitionCount(), + accountCandidate.issuerIndexPartitionCapacity()); + establishActualLegacyDisposition(dsl); + repository = new CanonicalGameplayBindingInventoryRepository(dsl); + repository.prepare(new CanonicalGameplayBindingTransitionRequest( + transitionId, UUID.randomUUID(), identity, + new CanonicalIssuerReservationFenceEvidence(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), + BigInteger.ONE, BigInteger.ONE, BigInteger.ONE), null, null)); + generation = repository.readProvisionalCasEvidence(transitionId).transition().bindingGeneration(); + } + + /** Actual migration state machine over explicitly controlled empty-cohort collaborators. */ + private static void establishActualLegacyDisposition(DSLContext dsl) { + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); + UUID cohortId = UUID.randomUUID(); + UUID writerFence = UUID.randomUUID(); + var storageIdentity = new CanonicalGameplayLegacyMigrationStorageIdentity( + "controlled-cluster-uid", "controlled-namespace-uid", "controlled-producer-pod-uid", + "controlled-container-id", "controlled-node-uid", "123456789", 42L, + "controlled-postgres-volume-uid", "controlled-redis-run-id", "controlled-redis-volume-uid"); + var fencedCohort = new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { + @Override public UUID cohortId() { return cohortId; } + @Override public UUID legacyWriterFence() { return writerFence; } + @Override public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + return storageIdentity; + } + @Override public void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity expected) { + if (!storageIdentity.equals(expected)) { + throw new IllegalStateException("Controlled test storage identity changed"); + } + } + }; + var operation = new CanonicalGameplayLegacyMigrationOwner( + migration, inventory, () -> fencedCohort, + ignored -> new CanonicalGameplayLegacyMigrationSourceSnapshot( + EnumSet.of(Family.TENANT_SESSION_CONTEXT, Family.SESSION_ALIAS_CONTEXT, + Family.GAMEPLAY_IDENTITY_CONTEXT, Family.GAMEPLAY_NAME_CONTEXT, + Family.MOVEMENT_EFFECT, Family.DURABLE_EFFECT), List.of()), + new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { + @Override public void rebuildExact(CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + CanonicalGameplayLegacyMigrationSourceSnapshot source, + CanonicalGameplayBindingInventorySnapshot canonical) { + requireEmptyCanonical(canonical); + } + @Override public CanonicalGameplayLegacyMigrationReadback readBackExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + CanonicalGameplayBindingInventorySnapshot canonical) { + requireEmptyCanonical(canonical); + return new CanonicalGameplayLegacyMigrationReadback(List.of(), List.of(), List.of(), List.of()); + } + }).migrate(); + if (operation.state() != CanonicalGameplayLegacyMigrationOperation.State.VERIFIED) { + throw new IllegalStateException("Actual legacy migration owner did not publish VERIFIED"); + } + } + + private static void requireEmptyCanonical(CanonicalGameplayBindingInventorySnapshot canonical) { + if (!canonical.bindings().isEmpty() || !canonical.reservations().isEmpty() + || !canonical.transitions().isEmpty() || !canonical.accountIndexObligations().isEmpty() + || !canonical.issuerIndexObligations().isEmpty() || !canonical.regionBridgeObligations().isEmpty()) { + throw new IllegalStateException("Controlled empty-cohort collaborator found canonical state"); + } + } + + public Candidate candidate() { + return new Candidate(identity.accountId(), identity.tenantId(), identity.playableStateNamespaceId(), + identity.characterId(), identity.playableStateScope(), identity.gameInstanceId(), identity.runtimeGameInstanceId(), + UUID.fromString(identity.sessionId()), identity.regionId(), identity.regionEpoch(), identity.issuerId(), + identity.issuerAuthGeneration(), identity.issuerIndexLayoutVersion(), identity.issuerIndexPartitionCount(), + identity.issuerIndexPartitionCapacity()); + } + + public Target target() { + return new Target(target.targetNamespace(), target.tenantSlug(), target.canonicalTenantId(), target.worldSlug(), + target.worldDisplayName(), target.realmId(), target.realmSlug(), target.realmDisplayName(), target.gameSessionTenantId(), + target.gameInstanceId(), target.playableStateNamespaceId(), target.playableStateScope(), target.canonicalGameInstanceId(), + target.canonicalVersionId(), target.runtimeVersionId(), target.catalogRevision(), target.pointerVersion(), + target.admissionPointerSnapshotDigest(), target.activeWorldEpoch(), target.initialAdmissionRequestId(), + target.initialAdmissionRequestDigest(), CanonicalGameplayAdmissionDecisionReadGrpcCodec.OriginKind.NO_PRIOR_POINTER, + null, target.holdId(), target.holdFence(), target.holdBindingDigest(), target.auditEventId(), target.ownerProofDigest(), + CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome.COMMITTED, false, + target.ownerProofTerminalAt(), target.characterCreationPolicy()); + } + + public void publish(AccountGameplayAdmissionLeaseEvidence lease) { + repository.markProvisional(repository.readProvisionalCasEvidence(transitionId), + new CanonicalGameplayAdmissionDecision(transitionId, lease, identity, generation, null, target)); + } + + /** Attempts a newer candidate; the retained unresolved original must fence preparation. */ + public BigInteger prepareNewerCandidate() { + var newer = new CanonicalGameplayBindingIdentity(identity.accountId(), identity.tenantId(), + identity.playableStateNamespaceId(), identity.characterId(), identity.playableStateScope(), + identity.gameInstanceId(), identity.runtimeGameInstanceId(), UUID.randomUUID().toString(), + identity.regionId(), identity.regionEpoch(), identity.issuerId(), identity.issuerAuthGeneration(), + identity.issuerIndexLayoutVersion(), identity.issuerIndexPartitionCount(), identity.issuerIndexPartitionCapacity()); + return repository.prepare(new CanonicalGameplayBindingTransitionRequest(UUID.randomUUID(), UUID.randomUUID(), newer, + new CanonicalIssuerReservationFenceEvidence(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), + BigInteger.ONE, BigInteger.ONE, BigInteger.ONE), null, null)).bindingGeneration(); + } + + /** Uses the actual runtime repository; a retained pending lease must fence this mutation. */ + public void stopRuntime() { + var runtimeRepository = new GameInstanceRepository(dsl); + var runtime = runtimeRepository.findById(target.gameInstanceId()).orElseThrow(); + runtime.setStatus("STOPPED"); + runtimeRepository.save(runtime); + } + + public UUID transitionId() { return transitionId; } + public BigInteger generation() { return generation; } + public DSLContext dsl() { return dsl; } + public CanonicalGameplayAdmissionAbortSource source() { return repository.readFirstNewAdmissionAbortSource(transitionId); } + + @Override public void close() { + dsl.execute("DROP SCHEMA \"" + schema + "\" CASCADE"); + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java index 3b764958f8..dd7f716fe4 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java @@ -48,13 +48,19 @@ public static RuntimeTarget seedRunningLaunch(DataSource dataSource) { * inputs; this path proves neither a live producer nor initial-admission terminal authority. */ public static RuntimeTarget seedRunningLaunch(DataSource dataSource, UUID canonicalTenantId) { + return seedRunningLaunch(dataSource, canonicalTenantId, null); + } + + /** Fixed test namespace for authenticated cross-owner composition; upstream evidence is controlled. */ + public static RuntimeTarget seedRunningLaunch( + DataSource dataSource, UUID canonicalTenantId, String fixedNamespace) { if (canonicalTenantId == null || new UUID(0L, 0L).equals(canonicalTenantId)) { throw new IllegalArgumentException("Canonical tenant UUID must be non-nil"); } String token = UUID.randomUUID().toString().replace("-", ""); String shortToken = token.substring(0, 10); - String targetNamespace = "fixture-" + shortToken; + String targetNamespace = fixedNamespace == null ? "fixture-" + shortToken : fixedNamespace; String tenantSlug = "tenant-" + shortToken; String worldSlug = "world-" + shortToken; String worldDisplayName = "Fixture World " + shortToken; 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 new file mode 100644 index 0000000000..2a4c14a406 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java @@ -0,0 +1,803 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.SQLException; +import java.time.Duration; +import java.util.EnumSet; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutorService; +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.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; +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.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Actual PostgreSQL/Redis proof for local ordinary NEW registration after the installed anchor. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String OWNER_PRINCIPAL = "gamesession_coord_app"; + private static final String ISSUER_KEY_PREFIX = "session:game:index:issuer:"; + private static final BigInteger LAYOUT_VERSION = BigInteger.valueOf(3); + private static final BigInteger PARTITION_COUNT = BigInteger.ONE; + private static final BigInteger PARTITION_CAPACITY = BigInteger.valueOf(2); + + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + private static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + private TestSchema schema; + private RedisClient administrator; + private RedisClient ownerClient; + private StatefulRedisConnection administratorConnection; + private RedisCommands administratorCommands; + + @BeforeEach + void setUp() { + String password = UUID.randomUUID().toString(); + administrator = createRedisClient(null, null); + administratorConnection = administrator.connect(ByteArrayCodec.INSTANCE); + administratorCommands = administratorConnection.sync(); + administratorCommands.flushdb(); + administratorCommands.aclSetuser( + OWNER_PRINCIPAL, + new AclSetuserArgs() + .reset() + .on() + .addPassword(password) + .keyPattern(ISSUER_KEY_PREFIX + "*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.HLEN) + .addCommand(CommandType.HGETALL) + .addCommand(CommandType.HSET)); + ownerClient = createRedisClient(OWNER_PRINCIPAL, password); + schema = newTestSchemaAtVersion("gs_issuer_local_new_"); + } + + @AfterEach + void tearDown() { + if (administratorConnection != null) administratorConnection.close(); + if (ownerClient != null) ownerClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + if (administrator != null) administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + if (schema != null) dropSchema(schema.schema()); + } + + @Test + void registersOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() throws Exception { + DSLContext dsl = schema.dsl(); + establishActualLegacyDisposition(dsl); + var layout = descriptor(); + UUID bootstrapRequestId = UUID.randomUUID(); + var source = sourceCheckpoint(BigInteger.valueOf(7)); + var intent = + new CanonicalGameplayIssuerLayoutBootstrapRepository(dsl) + .beginInitialBootstrapIntent(bootstrapRequestId, layout, source); + migrateRemaining(schema); + + var incarnation = stableIncarnation("local-new-anchor"); + var initialState = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + intent.sourceCheckpoint(), incarnation); + AtomicReference + currentState = new AtomicReference<>(initialState); + var operationRepository = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, currentState::get); + var firstCandidate = identity("first-new"); + var firstRequest = request("first-new-request", "first-new-transition", firstCandidate); + + assertThatThrownBy(() -> operationRepository.beginOrResumeOrdinaryNew(firstRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("anchor"); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isZero(); + assertThat(count(dsl, "game_session_canonical_gameplay_binding_inventory")).isZero(); + + CanonicalGameplayIssuerInstalledAnchor anchor = + initialCoverageOwner(dsl, currentState::get) + .completeInitialBootstrap(intent.operationId(), bootstrapRequestId); + String installedAnchorImage = anchorImage(dsl); + String installedProofImage = proofImage(dsl); + String initialReservationImage = reservationImage(dsl); + BigInteger initialGlobalCoverageGeneration = anchor.globalCoverageGeneration(); + + AtomicInteger sourceReads = new AtomicInteger(); + CyclicBarrier concurrentPreReadBarrier = new CyclicBarrier(2); + var concurrentSource = + (CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource) + () -> { + if (sourceReads.incrementAndGet() <= 2) { + try { + concurrentPreReadBarrier.await(30, TimeUnit.SECONDS); + } catch (Exception failure) { + throw new IllegalStateException( + "Concurrent source pre-reads did not rendezvous", failure); + } + } + return currentState.get(); + }; + var concurrentRepository = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, concurrentSource); + ExecutorService concurrentCallers = Executors.newFixedThreadPool(2); + CanonicalGameplayIssuerBindingLocalOperation first; + CanonicalGameplayIssuerBindingLocalOperation concurrentReplay; + try { + var firstCall = + concurrentCallers.submit( + () -> concurrentRepository.beginOrResumeOrdinaryNew(firstRequest)); + var secondCall = + concurrentCallers.submit( + () -> concurrentRepository.beginOrResumeOrdinaryNew(firstRequest)); + first = firstCall.get(30, TimeUnit.SECONDS); + concurrentReplay = secondCall.get(30, TimeUnit.SECONDS); + } finally { + concurrentCallers.shutdownNow(); + } + assertThat(sourceReads.get()).isEqualTo(4); + assertThat(concurrentReplay.operationId()).isEqualTo(first.operationId()); + assertThat(concurrentReplay.reservation().reservationId()) + .isEqualTo(first.reservation().reservationId()); + assertThat(concurrentReplay.reservation().reservationFence()) + .isEqualTo(first.reservation().reservationFence()); + assertThat(concurrentReplay.candidateAccountIndexFence()) + .isEqualTo(first.candidateAccountIndexFence()); + assertThat(concurrentReplay.operationFence()).isEqualTo(first.operationFence()); + assertThat(concurrentReplay.localMemberGeneration()).isEqualTo(first.localMemberGeneration()); + assertThat(concurrentReplay.localInventorySnapshotRevision()) + .isEqualTo(first.localInventorySnapshotRevision()); + assertThat(concurrentReplay.exactMemberValueBytes()) + .containsExactly(first.exactMemberValueBytes()); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isEqualTo(1L); + assertThat(count(dsl, "game_session_canonical_issuer_partition_reservation")).isEqualTo(1L); + assertThat(first.status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalOperation.Status.PENDING_PHYSICAL_PROOF); + assertThat(first.request()).isEqualTo(firstRequest); + assertThat(first.preparedTransition().status()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot + .Status.PREPARED); + assertThat(first.reservation().lifecycle()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation.Lifecycle + .RESERVED); + assertThat(first.reservation().issuerCoverageOperationId()) + .isEqualTo(first.anchor().issuerCoverageOperationId()); + assertThat(first.reservation().issuerCoverageOperationFence()) + .isEqualTo(first.anchor().operationFence()); + assertThat(first.reservation().coverageFence()).isEqualTo(first.anchor().coverageFence()); + assertThat(first.reservation().inventorySnapshotRevision()) + .isEqualTo(first.anchor().issuerInventorySnapshotRevision()); + assertThat(first.localInventorySnapshotRevision()) + .isEqualTo(first.reservation().inventoryRevision()); + assertThat(first.memberValue().anchor().issuerCoverageOperationId()) + .isEqualTo(anchor.issuerCoverageOperationId()); + assertThat(first.anchor().exactAnchorBytes()).containsExactly(anchor.exactAnchorBytes()); + assertThat(first.memberValue().issuerControlEpoch()).isEqualTo(anchor.controlEpoch()); + assertThat(first.memberValue().layoutDescriptor().exactDescriptorBytes()) + .containsExactly(anchor.layoutDescriptorBytes()); + assertThat(first.memberValue().layoutDescriptor().descriptorDigest()) + .isEqualTo(anchor.layoutDescriptorDigest()); + assertThat(first.memberValue().sourceCheckpoint().exactCheckpointBytes()) + .containsExactly(anchor.sourceCheckpointBytes()); + assertThat(first.memberValue().sourceCheckpoint().latestIssuerEventBytes()) + .containsExactly(anchor.sourceEventBytes()); + assertThat(first.memberValue().incarnation()).isEqualTo(incarnation); + assertThat(first.memberValue().memberOperation().coverageGeneration()) + .isEqualTo(first.localMemberGeneration()); + assertThat(first.expectedOldMemberState()).isEqualTo("ABSENT"); + assertThat(first.expectedOldCapacityState()).isEqualTo("ABSENT"); + assertThat(first.exactMemberValueBytes()) + .containsExactly(CanonicalGameplayIssuerMemberV2Codec.encode(first.memberValue())); + assertThat(first.memberValueDigest()) + .isEqualTo(CanonicalGameplayIssuerMemberV2Codec.sha256(first.exactMemberValueBytes())); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT member_status, member_schema_version FROM" + + " game_session_canonical_issuer_binding_local_operation WHERE transition_id = ?", + firstRequest.transitionId()), + "Expected local operation row") + .get("member_status", String.class)) + .isEqualTo("PENDING_PHYSICAL_PROOF"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT member_schema_version FROM" + + " game_session_canonical_issuer_binding_local_operation WHERE transition_id = ?", + firstRequest.transitionId()), + "Expected local operation row") + .get("member_schema_version", Short.class)) + .isEqualTo((short) 2); + assertThat(count(dsl, "game_session_canonical_binding_issuer_index_obligation")).isEqualTo(1L); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isEqualTo(1L); + assertThat(count(dsl, "game_session_canonical_gameplay_binding_inventory")).isEqualTo(1L); + assertThat(count(dsl, "game_session_canonical_binding_generation")).isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT last_issued_coverage_generation FROM" + + " game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", + ISSUER), + "Expected issuer coverage counter row") + .get("last_issued_coverage_generation", BigDecimal.class)) + .isEqualTo(new BigDecimal(initialGlobalCoverageGeneration)); + assertThat(anchorImage(dsl)).isEqualTo(installedAnchorImage); + assertThat(proofImage(dsl)).isEqualTo(installedProofImage); + assertThat( + administratorCommands.hlen( + CanonicalGameplayIssuerRedisKeys.forPartition( + intent.layoutDescriptor(), BigInteger.ZERO) + .getBytes(StandardCharsets.US_ASCII))) + .isEqualTo(1L); + + String afterFirstRegistration = localRegistrationImage(dsl); + CanonicalGameplayIssuerBindingLocalOperation replay = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, currentState::get) + .beginOrResumeOrdinaryNew(firstRequest); + assertThat(replay.operationId()).isEqualTo(first.operationId()); + assertThat(replay.operationFence()).isEqualTo(first.operationFence()); + assertThat(replay.localMemberGeneration()).isEqualTo(first.localMemberGeneration()); + assertThat(replay.exactMemberValueBytes()).containsExactly(first.exactMemberValueBytes()); + assertThat(localRegistrationImage(dsl)).isEqualTo(afterFirstRegistration); + assertThat(anchorImage(dsl)).isEqualTo(installedAnchorImage); + assertThat(proofImage(dsl)).isEqualTo(installedProofImage); + + String beforeRefusals = localRegistrationImage(dsl); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request("changed-first-request", "first-new-transition", firstCandidate))) + .isInstanceOf(IllegalStateException.class); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request("first-new-request", "other-transition", identity("changed-first")))) + .isInstanceOf(IllegalStateException.class); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); + + currentState.set( + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + checkpointShape(BigInteger.valueOf(8)), incarnation)); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request( + "moved-source-request", + "moved-source-transition", + identity("moved-source")))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source"); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); + currentState.set(initialState); + + currentState.set( + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + intent.sourceCheckpoint(), stableIncarnation("moved-incarnation"))); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request( + "moved-incarnation-request", + "moved-incarnation-transition", + identity("moved-incarnation")))) + .isInstanceOf(IllegalStateException.class); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); + currentState.set(initialState); + + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request( + "wrong-layout-request", + "wrong-layout-transition", + identityWithLayout("wrong-layout", BigInteger.TWO)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("layout"); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); + + var sameController = sameControllerDifferentBinding(firstCandidate, "same-controller"); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request("controller-request", "controller-transition", sameController))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("controller"); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); + + var fencedCandidate = identityForAccount("account-fenced", firstCandidate.accountId()); + new CanonicalGameplayAccountAdmissionBarrierRepository(dsl) + .beginFenceIntent(firstCandidate.accountId(), UUID.randomUUID()); + String accountFencedImage = localRegistrationImage(dsl); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request( + "account-fenced-request", "account-fenced-transition", fencedCandidate))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("Account"); + assertThat(localRegistrationImage(dsl)).isEqualTo(accountFencedImage); + + var secondCandidate = identity("second-new"); + var secondRequest = request("second-new-request", "second-new-transition", secondCandidate); + var movedAfterRegistrationState = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + checkpointShape(BigInteger.valueOf(8)), incarnation); + AtomicInteger movementReadCount = new AtomicInteger(); + var movingSource = + (CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource) + () -> + movementReadCount.incrementAndGet() == 1 + ? initialState + : movedAfterRegistrationState; + var movingRepository = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, movingSource); + assertThatThrownBy(() -> movingRepository.beginOrResumeOrdinaryNew(secondRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("pending local operation remains durable"); + UUID persistedSecondOperationId = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT operation_id FROM game_session_canonical_issuer_binding_local_operation" + + " WHERE transition_id = ?", + secondRequest.transitionId()), + "Expected local operation row") + .get("operation_id", UUID.class); + var second = operationRepository.beginOrResumeOrdinaryNew(secondRequest); + assertThat(second.operationId()).isEqualTo(persistedSecondOperationId); + assertThat(second.localMemberGeneration()).isGreaterThan(first.localMemberGeneration()); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isEqualTo(2L); + assertThat(count(dsl, "game_session_canonical_issuer_partition_reservation")).isEqualTo(2L); + assertThat(anchorImage(dsl)).isEqualTo(installedAnchorImage); + assertThat(proofImage(dsl)).isEqualTo(installedProofImage); + + String beforeCapacityRefusal = localRegistrationImage(dsl); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request("capacity-request", "capacity-transition", identity("capacity-new")))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("capacity"); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeCapacityRefusal); + assertThat(anchorImage(dsl)).isEqualTo(installedAnchorImage); + assertThat(proofImage(dsl)).isEqualTo(installedProofImage); + assertThat(reservationImage(dsl)).isNotEqualTo(initialReservationImage); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isEqualTo(2L); + assertThat( + administratorCommands.hlen( + CanonicalGameplayIssuerRedisKeys.forPartition( + intent.layoutDescriptor(), BigInteger.ZERO) + .getBytes(StandardCharsets.US_ASCII))) + .isEqualTo(1L); + } + + private CanonicalGameplayIssuerBootstrapCoverageOwner initialCoverageOwner( + DSLContext dsl, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource source) { + var partitionOwner = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner( + ownerClient, + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution())), + source); + return new CanonicalGameplayIssuerBootstrapCoverageOwner(dsl, partitionOwner, source); + } + + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor + descriptor() { + String exact = + "issuer-layout-descriptor/v1|" + + ISSUER + + "|" + + LAYOUT_VERSION + + "|" + + PARTITION_COUNT + + "|" + + PARTITION_CAPACITY + + "|" + + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY; + return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor( + ISSUER, + LAYOUT_VERSION, + PARTITION_COUNT, + PARTITION_CAPACITY, + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY, + exact.getBytes(StandardCharsets.UTF_8)); + } + + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + sourceCheckpoint(BigInteger generation) { + long sequence = generation.longValueExact() - 1; + var event = + AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + UUID.randomUUID().toString(), + UUID.randomUUID().toString(), + AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + ISSUER, + Long.toString(sequence), + ISSUER, + generation.toString(), + generation.toString(), + "ISSUER_SECURITY_CHANGE")); + byte[] bytes = event.canonicalJsonUtf8(); + return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint( + ISSUER, generation, bytes, bytes); + } + + private static CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint + checkpointShape(BigInteger generation) { + var trusted = sourceCheckpoint(generation); + byte[] checkpoint = trusted.checkpointBytes(); + byte[] event = trusted.latestEventBytes(); + return new CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint( + trusted.issuerId(), + trusted.issuerAuthGeneration(), + checkpoint, + CanonicalGameplayIssuerMemberV2Codec.sha256(checkpoint), + event, + CanonicalGameplayIssuerMemberV2Codec.sha256(event)); + } + + private static CanonicalGameplayIssuerMemberV2Value.Incarnation stableIncarnation(String seed) { + String digest = digest(seed.getBytes(StandardCharsets.UTF_8)); + var deployment = + new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "controlled-deployment-" + seed, + "deployment-generation-" + seed, + List.of("controlled-node-" + seed), + "controlled-redis-build-" + seed, + "controlled-lua-registry-" + seed, + digest, + "READY", + "boot-" + seed, + "startup-" + seed, + "storage-" + seed, + "aof-" + seed); + return new CanonicalGameplayIssuerMemberV2Value.Incarnation( + "controlled-attestor-" + seed, digest, deployment, digest, digest); + } + + private static CanonicalGameplayIssuerBindingLocalOperation.Request request( + String requestSeed, String transitionSeed, CanonicalGameplayBindingIdentity candidate) { + return new CanonicalGameplayIssuerBindingLocalOperation.Request( + UUID.nameUUIDFromBytes(requestSeed.getBytes(StandardCharsets.UTF_8)), + UUID.nameUUIDFromBytes(transitionSeed.getBytes(StandardCharsets.UTF_8)), + candidate, + null, + null); + } + + private static CanonicalGameplayBindingIdentity identity(String seed) { + return identityWithLayout(seed, LAYOUT_VERSION); + } + + private static CanonicalGameplayBindingIdentity identityForAccount(String seed, UUID accountId) { + CanonicalGameplayBindingIdentity identity = identity(seed); + return new CanonicalGameplayBindingIdentity( + accountId, + identity.tenantId(), + identity.playableStateNamespaceId(), + identity.characterId(), + identity.playableStateScope(), + identity.gameInstanceId(), + identity.runtimeGameInstanceId(), + identity.sessionId(), + identity.regionId(), + identity.regionEpoch(), + identity.issuerId(), + identity.issuerAuthGeneration(), + identity.issuerIndexLayoutVersion(), + identity.issuerIndexPartitionCount(), + identity.issuerIndexPartitionCapacity()); + } + + private static CanonicalGameplayBindingIdentity identityWithLayout( + String seed, BigInteger layoutVersion) { + return new CanonicalGameplayBindingIdentity( + uuid(seed + "-account"), + uuid(seed + "-tenant"), + uuid(seed + "-namespace"), + uuid(seed + "-character"), + "SHARED", + uuid(seed + "-game"), + 90_000L + Math.abs((long) seed.hashCode()), + uuid(seed + "-session").toString(), + uuid(seed + "-region"), + BigInteger.valueOf(12), + ISSUER, + BigInteger.valueOf(7), + layoutVersion, + PARTITION_COUNT, + PARTITION_CAPACITY); + } + + private static CanonicalGameplayBindingIdentity sameControllerDifferentBinding( + CanonicalGameplayBindingIdentity original, String seed) { + return new CanonicalGameplayBindingIdentity( + original.accountId(), + original.tenantId(), + original.playableStateNamespaceId(), + original.characterId(), + original.playableStateScope(), + uuid(seed + "-game"), + original.runtimeGameInstanceId() + 1, + uuid(seed + "-session").toString(), + original.regionId(), + original.regionEpoch(), + original.issuerId(), + original.issuerAuthGeneration(), + original.issuerIndexLayoutVersion(), + original.issuerIndexPartitionCount(), + original.issuerIndexPartitionCapacity()); + } + + private static UUID uuid(String value) { + return UUID.nameUUIDFromBytes(value.getBytes(StandardCharsets.UTF_8)); + } + + private void establishActualLegacyDisposition(DSLContext dsl) { + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); + UUID cohortId = UUID.randomUUID(); + UUID writerFence = UUID.randomUUID(); + var storageIdentity = + new CanonicalGameplayLegacyMigrationStorageIdentity( + "controlled-cluster-uid", + "controlled-namespace-uid", + "controlled-producer-pod-uid", + "controlled-container-id", + "controlled-node-uid", + "123456789", + 42L, + "controlled-postgres-volume-uid", + "controlled-redis-run-id", + "controlled-redis-volume-uid"); + var fencedCohort = + new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { + @Override + public UUID cohortId() { + return cohortId; + } + + @Override + public UUID legacyWriterFence() { + return writerFence; + } + + @Override + public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + return storageIdentity; + } + + @Override + public void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity expected) { + if (!storageIdentity.equals(expected)) { + throw new IllegalStateException("Controlled test storage identity changed"); + } + } + }; + new CanonicalGameplayLegacyMigrationOwner( + migration, + inventory, + () -> fencedCohort, + ignored -> + new CanonicalGameplayLegacyMigrationSourceSnapshot( + EnumSet.of( + Family.TENANT_SESSION_CONTEXT, + Family.SESSION_ALIAS_CONTEXT, + Family.GAMEPLAY_IDENTITY_CONTEXT, + Family.GAMEPLAY_NAME_CONTEXT, + Family.MOVEMENT_EFFECT, + Family.DURABLE_EFFECT), + List.of()), + new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { + @Override + public void rebuildExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + CanonicalGameplayLegacyMigrationSourceSnapshot source, + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot + canonical) { + assertThat(canonical.bindings()).isEmpty(); + assertThat(canonical.reservations()).isEmpty(); + } + + @Override + public CanonicalGameplayLegacyMigrationReadback readBackExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot + canonical) { + assertThat(canonical.bindings()).isEmpty(); + return new CanonicalGameplayLegacyMigrationReadback( + List.of(), List.of(), List.of(), List.of()); + } + }) + .migrate(); + } + + private TestSchema newTestSchemaAtVersion(String prefix) { + String schema = prefix + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("1030")) + .load() + .migrate(); + return new TestSchema(schema, dataSource, DSL.using(dataSource, SQLDialect.POSTGRES)); + } + + private static void migrateRemaining(TestSchema schema) { + Flyway.configure() + .dataSource(schema.dataSource()) + .schemas(schema.schema()) + .defaultSchema(schema.schema()) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + } + + private DriverManagerDataSource dataSource(String schemaName) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + String jdbcUrl = POSTGRES.getJdbcUrl(); + dataSource.setUrl( + jdbcUrl + (jdbcUrl.contains("?") ? "&" : "?") + "currentSchema=" + schemaName); + dataSource.setUsername(POSTGRES.getUsername()); + dataSource.setPassword(POSTGRES.getPassword()); + return dataSource; + } + + private void dropSchema(String schemaName) { + try (Connection connection = dataSource("public").getConnection()) { + DSL.using(connection, SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + schemaName + "\" CASCADE"); + } catch (SQLException failure) { + throw new IllegalStateException( + "Could not drop the owned issuer local-operation test schema", failure); + } + } + + private static RedisClient createRedisClient(String username, String password) { + RedisURI.Builder builder = RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(6379)); + if (username != null) builder.withAuthentication(username, password); + RedisURI uri = builder.build(); + uri.setTimeout(Duration.ofSeconds(5)); + RedisClient client = RedisClient.create(uri); + client.setOptions( + ClientOptions.builder() + .autoReconnect(false) + .protocolVersion(io.lettuce.core.protocol.ProtocolVersion.RESP2) + .build()); + return client; + } + + private static long count(DSLContext dsl, String table) { + return Objects.requireNonNull( + dsl.fetchOne("SELECT count(*) AS row_count FROM " + table), "Expected count row") + .get("row_count", Long.class); + } + + private static String anchorImage(DSLContext dsl) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT encode(exact_anchor_bytes, 'base64') || ':' || exact_anchor_digest || ':'" + + " || global_coverage_generation::text FROM" + + " game_session_canonical_issuer_installed_anchor WHERE issuer_id = ?", + ISSUER), + "Expected installed anchor row") + .get(0, String.class); + } + + private static String proofImage(DSLContext dsl) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT coalesce(string_agg(partition_id::text || ':'" + + " || encode(exact_physical_field_set_bytes, 'base64') || ':'" + + " || exact_physical_field_set_digest, '|' ORDER BY partition_id), '')" + + " FROM game_session_canonical_issuer_bootstrap_partition_proof"), + "Expected proof aggregate row") + .get(0, String.class); + } + + private static String reservationImage(DSLContext dsl) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT coalesce(jsonb_agg(to_jsonb(r) ORDER BY reservation_id), '[]'::jsonb)::text" + + " FROM game_session_canonical_issuer_partition_reservation r"), + "Expected reservation aggregate row") + .get(0, String.class); + } + + private static String localRegistrationImage(DSLContext dsl) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT" + + " (SELECT coalesce(jsonb_agg(to_jsonb(i) ORDER BY binding_ref), '[]'::jsonb)::text" + + " FROM game_session_canonical_gameplay_binding_inventory i) || ':'" + + " || (SELECT coalesce(jsonb_agg(to_jsonb(t) ORDER BY transition_id), '[]'::jsonb)::text" + + " FROM game_session_canonical_binding_transition t) || ':'" + + " || (SELECT coalesce(jsonb_agg(to_jsonb(r) ORDER BY reservation_id), '[]'::jsonb)::text" + + " FROM game_session_canonical_issuer_partition_reservation r) || ':'" + + " || (SELECT coalesce(jsonb_agg(to_jsonb(o) ORDER BY operation_id), '[]'::jsonb)::text" + + " FROM game_session_canonical_issuer_binding_local_operation o) || ':'" + + " || (SELECT coalesce(jsonb_agg(to_jsonb(g) ORDER BY tenant_id, playable_state_namespace_id, character_id), '[]'::jsonb)::text" + + " FROM game_session_canonical_binding_generation g) || ':'" + + " || (SELECT inventory_revision::text FROM game_session_canonical_binding_inventory_clock WHERE singleton_id = 1) || ':'" + + " || (SELECT coalesce(to_jsonb(c)::text, 'missing') FROM game_session_canonical_issuer_bootstrap_member_op_counter c WHERE issuer_id = '" + + ISSUER + + "')"), + "Expected local registration aggregate row") + .get(0, String.class); + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private record TestSchema(String schema, DriverManagerDataSource dataSource, DSLContext dsl) {} +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java new file mode 100644 index 0000000000..14b24ee0b5 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java @@ -0,0 +1,1085 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.SQLException; +import java.time.Duration; +import java.util.EnumSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutorService; +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.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; +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.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Actual PostgreSQL/Redis proof for local ordinary NEW registration after the installed anchor. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String OWNER_PRINCIPAL = "gamesession_coord_app"; + private static final String ISSUER_KEY_PREFIX = "session:game:index:issuer:"; + private static final BigInteger LAYOUT_VERSION = BigInteger.valueOf(3); + private static final BigInteger PARTITION_COUNT = BigInteger.ONE; + private static final BigInteger PARTITION_CAPACITY = BigInteger.valueOf(2); + + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + private static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + private TestSchema schema; + private RedisClient administrator; + private RedisClient ownerClient; + private StatefulRedisConnection administratorConnection; + private RedisCommands administratorCommands; + + @BeforeEach + void setUp() { + String password = UUID.randomUUID().toString(); + administrator = createRedisClient(null, null); + administratorConnection = administrator.connect(ByteArrayCodec.INSTANCE); + administratorCommands = administratorConnection.sync(); + administratorCommands.flushdb(); + administratorCommands.aclSetuser( + OWNER_PRINCIPAL, + new AclSetuserArgs() + .reset() + .on() + .addPassword(password) + .keyPattern(ISSUER_KEY_PREFIX + "*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.HGET) + .addCommand(CommandType.HLEN) + .addCommand(CommandType.HGETALL) + .addCommand(CommandType.HSET)); + ownerClient = createRedisClient(OWNER_PRINCIPAL, password); + schema = newTestSchemaAtVersion("gs_issuer_local_new_"); + } + + @AfterEach + void tearDown() { + if (administratorConnection != null) administratorConnection.close(); + if (ownerClient != null) ownerClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + if (administrator != null) administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + if (schema != null) dropSchema(schema.schema()); + } + + @Test + void registersOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() throws Exception { + DSLContext dsl = schema.dsl(); + establishActualLegacyDisposition(dsl); + var layout = descriptor(); + UUID bootstrapRequestId = UUID.randomUUID(); + var source = sourceCheckpoint(BigInteger.valueOf(7)); + var intent = + new CanonicalGameplayIssuerLayoutBootstrapRepository(dsl) + .beginInitialBootstrapIntent(bootstrapRequestId, layout, source); + migrateRemaining(schema); + + var incarnation = stableIncarnation("local-new-anchor"); + var initialState = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + intent.sourceCheckpoint(), incarnation); + AtomicReference + currentState = new AtomicReference<>(initialState); + var operationRepository = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, currentState::get); + var runtimeTarget = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( + schema.dataSource(), uuid("local-projection-tenant")); + var firstCandidate = identity("first-new", runtimeTarget); + var firstRequest = request("first-new-request", "first-new-transition", firstCandidate); + + assertThatThrownBy(() -> operationRepository.beginOrResumeOrdinaryNew(firstRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("anchor"); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isZero(); + assertThat(count(dsl, "game_session_canonical_gameplay_binding_inventory")).isZero(); + + CanonicalGameplayIssuerInstalledAnchor anchor = + initialCoverageOwner(dsl, currentState::get) + .completeInitialBootstrap(intent.operationId(), bootstrapRequestId); + String installedAnchorImage = anchorImage(dsl); + String installedProofImage = proofImage(dsl); + String initialReservationImage = reservationImage(dsl); + BigInteger initialGlobalCoverageGeneration = anchor.globalCoverageGeneration(); + + AtomicInteger sourceReads = new AtomicInteger(); + CyclicBarrier concurrentPreReadBarrier = new CyclicBarrier(2); + var concurrentSource = + (CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource) + () -> { + if (sourceReads.incrementAndGet() <= 2) { + try { + concurrentPreReadBarrier.await(30, TimeUnit.SECONDS); + } catch (Exception failure) { + throw new IllegalStateException( + "Concurrent source pre-reads did not rendezvous", failure); + } + } + return currentState.get(); + }; + var concurrentRepository = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, concurrentSource); + ExecutorService concurrentCallers = Executors.newFixedThreadPool(2); + CanonicalGameplayIssuerBindingLocalOperation first; + CanonicalGameplayIssuerBindingLocalOperation concurrentReplay; + try { + var firstCall = + concurrentCallers.submit( + () -> concurrentRepository.beginOrResumeOrdinaryNew(firstRequest)); + var secondCall = + concurrentCallers.submit( + () -> concurrentRepository.beginOrResumeOrdinaryNew(firstRequest)); + first = firstCall.get(30, TimeUnit.SECONDS); + concurrentReplay = secondCall.get(30, TimeUnit.SECONDS); + } finally { + concurrentCallers.shutdownNow(); + } + assertThat(sourceReads.get()).isEqualTo(4); + assertThat(concurrentReplay.operationId()).isEqualTo(first.operationId()); + assertThat(concurrentReplay.reservation().reservationId()) + .isEqualTo(first.reservation().reservationId()); + assertThat(concurrentReplay.reservation().reservationFence()) + .isEqualTo(first.reservation().reservationFence()); + assertThat(concurrentReplay.candidateAccountIndexFence()) + .isEqualTo(first.candidateAccountIndexFence()); + assertThat(concurrentReplay.operationFence()).isEqualTo(first.operationFence()); + assertThat(concurrentReplay.localMemberGeneration()).isEqualTo(first.localMemberGeneration()); + assertThat(concurrentReplay.localInventorySnapshotRevision()) + .isEqualTo(first.localInventorySnapshotRevision()); + assertThat(concurrentReplay.exactMemberValueBytes()) + .containsExactly(first.exactMemberValueBytes()); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isEqualTo(1L); + assertThat(count(dsl, "game_session_canonical_issuer_partition_reservation")).isEqualTo(1L); + assertThat(first.status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalOperation.Status.PENDING_PHYSICAL_PROOF); + assertThat(first.request()).isEqualTo(firstRequest); + assertThat(first.preparedTransition().status()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot + .Status.PREPARED); + assertThat(first.reservation().lifecycle()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation.Lifecycle + .RESERVED); + assertThat(first.reservation().issuerCoverageOperationId()) + .isEqualTo(first.anchor().issuerCoverageOperationId()); + assertThat(first.reservation().issuerCoverageOperationFence()) + .isEqualTo(first.anchor().operationFence()); + assertThat(first.reservation().coverageFence()).isEqualTo(first.anchor().coverageFence()); + assertThat(first.reservation().inventorySnapshotRevision()) + .isEqualTo(first.anchor().issuerInventorySnapshotRevision()); + assertThat(first.localInventorySnapshotRevision()) + .isEqualTo(first.reservation().inventoryRevision()); + assertThat(first.memberValue().anchor().issuerCoverageOperationId()) + .isEqualTo(anchor.issuerCoverageOperationId()); + assertThat(first.anchor().exactAnchorBytes()).containsExactly(anchor.exactAnchorBytes()); + assertThat(first.memberValue().issuerControlEpoch()).isEqualTo(anchor.controlEpoch()); + assertThat(first.memberValue().layoutDescriptor().exactDescriptorBytes()) + .containsExactly(anchor.layoutDescriptorBytes()); + assertThat(first.memberValue().layoutDescriptor().descriptorDigest()) + .isEqualTo(anchor.layoutDescriptorDigest()); + assertThat(first.memberValue().sourceCheckpoint().exactCheckpointBytes()) + .containsExactly(anchor.sourceCheckpointBytes()); + assertThat(first.memberValue().sourceCheckpoint().latestIssuerEventBytes()) + .containsExactly(anchor.sourceEventBytes()); + assertThat(first.memberValue().incarnation()).isEqualTo(incarnation); + assertThat(first.memberValue().memberOperation().coverageGeneration()) + .isEqualTo(first.localMemberGeneration()); + assertThat(first.expectedOldMemberState()).isEqualTo("ABSENT"); + assertThat(first.expectedOldCapacityState()).isEqualTo("ABSENT"); + assertThat(first.exactMemberValueBytes()) + .containsExactly(CanonicalGameplayIssuerMemberV2Codec.encode(first.memberValue())); + assertThat(first.memberValueDigest()) + .isEqualTo(CanonicalGameplayIssuerMemberV2Codec.sha256(first.exactMemberValueBytes())); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT member_status, member_schema_version FROM" + + " game_session_canonical_issuer_binding_local_operation WHERE transition_id = ?", + firstRequest.transitionId()), + "Expected local operation row") + .get("member_status", String.class)) + .isEqualTo("PENDING_PHYSICAL_PROOF"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT member_schema_version FROM" + + " game_session_canonical_issuer_binding_local_operation WHERE transition_id = ?", + firstRequest.transitionId()), + "Expected local operation row") + .get("member_schema_version", Short.class)) + .isEqualTo((short) 2); + assertThat(count(dsl, "game_session_canonical_binding_issuer_index_obligation")).isEqualTo(1L); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isEqualTo(1L); + assertThat(count(dsl, "game_session_canonical_gameplay_binding_inventory")).isEqualTo(1L); + assertThat(count(dsl, "game_session_canonical_binding_generation")).isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT last_issued_coverage_generation FROM" + + " game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", + ISSUER), + "Expected issuer coverage counter row") + .get("last_issued_coverage_generation", BigDecimal.class)) + .isEqualTo(new BigDecimal(initialGlobalCoverageGeneration)); + assertThat(anchorImage(dsl)).isEqualTo(installedAnchorImage); + assertThat(proofImage(dsl)).isEqualTo(installedProofImage); + assertThat( + administratorCommands.hlen( + CanonicalGameplayIssuerRedisKeys.forPartition( + intent.layoutDescriptor(), BigInteger.ZERO) + .getBytes(StandardCharsets.US_ASCII))) + .isEqualTo(1L); + + var projectionOwner = projectionOwner(dsl, currentState::get); + var firstCapacityOnly = projectionOwner.projectAndRead(first); + assertThat(firstCapacityOnly.operation()).isSameAs(first); + assertThat(firstCapacityOnly.scriptOutcome()).isEqualTo(1L); + var firstCapacityFields = + CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( + firstCapacityOnly.exactReadbackBytes()); + String firstCapacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + first.reservation().reservationId()); + assertThat(firstCapacityFields) + .containsEntry(firstCapacityField, first.exactMemberValueBytes()); + assertThat(firstCapacityFields) + .doesNotContainKey(new String(firstCandidate.bindingRef().bytes(), StandardCharsets.UTF_8)); + assertThat(projectionOwner.projectAndRead(first).scriptOutcome()).isEqualTo(3L); + assertThat(anchorImage(dsl)).isEqualTo(installedAnchorImage); + assertThat(proofImage(dsl)).isEqualTo(installedProofImage); + + String afterFirstRegistration = localRegistrationImage(dsl); + CanonicalGameplayIssuerBindingLocalOperation replay = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, currentState::get) + .beginOrResumeOrdinaryNew(firstRequest); + assertThat(replay.operationId()).isEqualTo(first.operationId()); + assertThat(replay.operationFence()).isEqualTo(first.operationFence()); + assertThat(replay.localMemberGeneration()).isEqualTo(first.localMemberGeneration()); + assertThat(replay.exactMemberValueBytes()).containsExactly(first.exactMemberValueBytes()); + assertThat(localRegistrationImage(dsl)).isEqualTo(afterFirstRegistration); + assertThat(anchorImage(dsl)).isEqualTo(installedAnchorImage); + assertThat(proofImage(dsl)).isEqualTo(installedProofImage); + + String beforeRefusals = localRegistrationImage(dsl); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request("changed-first-request", "first-new-transition", firstCandidate))) + .isInstanceOf(IllegalStateException.class); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request("first-new-request", "other-transition", identity("changed-first")))) + .isInstanceOf(IllegalStateException.class); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); + + currentState.set( + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + checkpointShape(BigInteger.valueOf(8)), incarnation)); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request( + "moved-source-request", + "moved-source-transition", + identity("moved-source")))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source"); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); + currentState.set(initialState); + + currentState.set( + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + intent.sourceCheckpoint(), stableIncarnation("moved-incarnation"))); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request( + "moved-incarnation-request", + "moved-incarnation-transition", + identity("moved-incarnation")))) + .isInstanceOf(IllegalStateException.class); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); + currentState.set(initialState); + + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request( + "wrong-layout-request", + "wrong-layout-transition", + identityWithLayout("wrong-layout", BigInteger.TWO)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("layout"); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); + + var sameController = sameControllerDifferentBinding(firstCandidate, "same-controller"); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request("controller-request", "controller-transition", sameController))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("controller"); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); + + var secondCandidate = identity("second-new"); + var secondRequest = request("second-new-request", "second-new-transition", secondCandidate); + var movedAfterRegistrationState = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + checkpointShape(BigInteger.valueOf(8)), incarnation); + AtomicInteger movementReadCount = new AtomicInteger(); + var movingSource = + (CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource) + () -> + movementReadCount.incrementAndGet() == 1 + ? initialState + : movedAfterRegistrationState; + var movingRepository = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, movingSource); + assertThatThrownBy(() -> movingRepository.beginOrResumeOrdinaryNew(secondRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("pending local operation remains durable"); + UUID persistedSecondOperationId = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT operation_id FROM game_session_canonical_issuer_binding_local_operation" + + " WHERE transition_id = ?", + secondRequest.transitionId()), + "Expected local operation row") + .get("operation_id", UUID.class); + var second = operationRepository.beginOrResumeOrdinaryNew(secondRequest); + assertThat(second.operationId()).isEqualTo(persistedSecondOperationId); + assertThat(second.localMemberGeneration()).isGreaterThan(first.localMemberGeneration()); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isEqualTo(2L); + assertThat(count(dsl, "game_session_canonical_issuer_partition_reservation")).isEqualTo(2L); + assertThat(anchorImage(dsl)).isEqualTo(installedAnchorImage); + assertThat(proofImage(dsl)).isEqualTo(installedProofImage); + + var concurrentProjectionResults = concurrentProjection(projectionOwner, first, second); + assertThat(concurrentProjectionResults.first().scriptOutcome()).isEqualTo(3L); + assertThat(concurrentProjectionResults.second().scriptOutcome()).isEqualTo(1L); + var provisionalEvidence = + new CanonicalGameplayBindingInventoryRepository(dsl) + .readProvisionalCasEvidence(firstRequest.transitionId()); + var firstLease = + controlledLeaseEvidence( + firstCandidate, + provisionalEvidence.transition().bindingGeneration(), + runtimeTarget.playableTarget()); + var firstDecision = + new CanonicalGameplayAdmissionDecision( + firstRequest.transitionId(), + firstLease, + firstCandidate, + provisionalEvidence.transition().bindingGeneration(), + null, + runtimeTarget.playableTarget()); + new CanonicalGameplayBindingInventoryRepository(dsl) + .markProvisional(provisionalEvidence, firstDecision); + var firstWithBinding = projectionOwner.projectAndRead(first); + assertThat(firstWithBinding.scriptOutcome()).isEqualTo(2L); + var firstProjectedFields = + CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( + firstWithBinding.exactReadbackBytes()); + assertThat(firstProjectedFields) + .containsEntry( + new String(firstCandidate.bindingRef().bytes(), StandardCharsets.UTF_8), + first.exactMemberValueBytes()); + assertThat(firstProjectedFields) + .containsEntry(firstCapacityField, first.exactMemberValueBytes()); + assertThat(projectionOwner.projectAndRead(first).scriptOutcome()).isEqualTo(3L); + + String beforeCapacityRefusal = localRegistrationImage(dsl); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request("capacity-request", "capacity-transition", identity("capacity-new")))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("capacity"); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeCapacityRefusal); + assertThat(anchorImage(dsl)).isEqualTo(installedAnchorImage); + assertThat(proofImage(dsl)).isEqualTo(installedProofImage); + assertThat(reservationImage(dsl)).isNotEqualTo(initialReservationImage); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isEqualTo(2L); + + byte[] key = + CanonicalGameplayIssuerRedisKeys.forPartition(intent.layoutDescriptor(), BigInteger.ZERO) + .getBytes(StandardCharsets.US_ASCII); + String secondCapacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + second.reservation().reservationId()); + byte[] secondCapacityFieldBytes = secondCapacityField.getBytes(StandardCharsets.US_ASCII); + assertThat(administratorCommands.hlen(key)).isEqualTo(4L); + assertThat(firstProjectedFields) + .containsEntry(secondCapacityField, second.exactMemberValueBytes()); + + var incarnationMovedState = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + intent.sourceCheckpoint(), stableIncarnation("moved-after-install")); + currentState.set(incarnationMovedState); + assertThatThrownBy(() -> projectionOwner.projectAndRead(second)) + .isInstanceOf(IllegalStateException.class); + currentState.set(initialState); + + administratorCommands.hset(key, secondCapacityFieldBytes, first.exactMemberValueBytes()); + assertThatThrownBy(() -> projectionOwner.projectAndRead(second)) + .isInstanceOf(IllegalStateException.class); + assertThat(administratorCommands.hget(key, secondCapacityFieldBytes)) + .containsExactly(first.exactMemberValueBytes()); + administratorCommands.hset(key, secondCapacityFieldBytes, second.exactMemberValueBytes()); + + var secondValue = second.memberValue(); + var wrongAnchorValue = + new CanonicalGameplayIssuerMemberV2Value( + secondValue.owner(), + secondValue.bindingGeneration(), + secondValue.reservation(), + new CanonicalGameplayIssuerMemberV2Value.Anchor( + UUID.randomUUID(), + secondValue.anchor().operationFence(), + secondValue.anchor().coverageFence(), + secondValue.anchor().issuerInventorySnapshotRevision()), + secondValue.memberOperation(), + secondValue.issuerControlEpoch(), + secondValue.layoutDescriptor(), + secondValue.sourceCheckpoint(), + secondValue.incarnation()); + byte[] wrongAnchorBytes = CanonicalGameplayIssuerMemberV2Codec.encode(wrongAnchorValue); + administratorCommands.hset(key, secondCapacityFieldBytes, wrongAnchorBytes); + assertThatThrownBy(() -> projectionOwner.projectAndRead(second)) + .isInstanceOf(IllegalStateException.class); + assertThat(administratorCommands.hget(key, secondCapacityFieldBytes)) + .containsExactly(wrongAnchorBytes); + administratorCommands.hset(key, secondCapacityFieldBytes, second.exactMemberValueBytes()); + + byte[] unknownField = "unregistered-issuer-member".getBytes(StandardCharsets.UTF_8); + byte[] unknownValue = "newer-v2-value".getBytes(StandardCharsets.UTF_8); + administratorCommands.hset(key, unknownField, unknownValue); + assertThatThrownBy(() -> projectionOwner.projectAndRead(second)) + .isInstanceOf(IllegalStateException.class); + assertThat(administratorCommands.hget(key, unknownField)).containsExactly(unknownValue); + byte[][] unknownFields = {unknownField}; + administratorCommands.hdel(key, unknownFields); + + byte[] headerField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.METADATA_FIELD.getBytes( + StandardCharsets.US_ASCII); + byte[] headerValue = + firstCapacityFields.get( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.METADATA_FIELD); + byte[][] headerFields = {headerField}; + administratorCommands.hdel(key, headerFields); + assertThatThrownBy(() -> projectionOwner.projectAndRead(second)) + .isInstanceOf(IllegalStateException.class); + administratorCommands.hset(key, headerField, headerValue); + + administratorCommands.hset( + key, secondCapacityFieldBytes, "{\"schemaVersion\":1}".getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy(() -> projectionOwner.projectAndRead(second)) + .isInstanceOf(IllegalStateException.class); + administratorCommands.hset(key, secondCapacityFieldBytes, second.exactMemberValueBytes()); + + assertThat(administratorCommands.pexpire(key, 60_000L)).isTrue(); + assertThatThrownBy(() -> projectionOwner.projectAndRead(second)) + .isInstanceOf(IllegalStateException.class); + assertThat(administratorCommands.persist(key)).isTrue(); + assertThat(administratorCommands.hlen(key)).isEqualTo(4L); + + var fencedCandidate = identityForAccount("account-fenced", firstCandidate.accountId()); + new CanonicalGameplayAccountAdmissionBarrierRepository(dsl) + .beginFenceIntent(firstCandidate.accountId(), UUID.randomUUID()); + String accountFencedImage = localRegistrationImage(dsl); + assertThatThrownBy( + () -> + operationRepository.beginOrResumeOrdinaryNew( + request( + "account-fenced-request", "account-fenced-transition", fencedCandidate))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("Account"); + assertThat(localRegistrationImage(dsl)).isEqualTo(accountFencedImage); + } + + private static ConcurrentProjections concurrentProjection( + CanonicalGameplayIssuerBindingLocalRedisOwner owner, + CanonicalGameplayIssuerBindingLocalOperation first, + CanonicalGameplayIssuerBindingLocalOperation second) + throws Exception { + ExecutorService callers = Executors.newFixedThreadPool(2); + try { + var firstCall = callers.submit(() -> owner.projectAndRead(first)); + var secondCall = callers.submit(() -> owner.projectAndRead(second)); + return new ConcurrentProjections( + firstCall.get(30, TimeUnit.SECONDS), secondCall.get(30, TimeUnit.SECONDS)); + } finally { + callers.shutdownNow(); + } + } + + private CanonicalGameplayIssuerBootstrapCoverageOwner initialCoverageOwner( + DSLContext dsl, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource source) { + var partitionOwner = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner( + ownerClient, + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution())), + source); + return new CanonicalGameplayIssuerBootstrapCoverageOwner(dsl, partitionOwner, source); + } + + private CanonicalGameplayIssuerBindingLocalRedisOwner projectionOwner( + DSLContext dsl, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource source) { + return new CanonicalGameplayIssuerBindingLocalRedisOwner( + ownerClient, + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayIssuerBindingLocalRedisScriptContribution())), + new CanonicalGameplayIssuerBindingLocalProjectionRepository(dsl, source), + source); + } + + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor + descriptor() { + String exact = + "issuer-layout-descriptor/v1|" + + ISSUER + + "|" + + LAYOUT_VERSION + + "|" + + PARTITION_COUNT + + "|" + + PARTITION_CAPACITY + + "|" + + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY; + return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor( + ISSUER, + LAYOUT_VERSION, + PARTITION_COUNT, + PARTITION_CAPACITY, + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY, + exact.getBytes(StandardCharsets.UTF_8)); + } + + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + sourceCheckpoint(BigInteger generation) { + long sequence = generation.longValueExact() - 1; + var event = + AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + UUID.randomUUID().toString(), + UUID.randomUUID().toString(), + AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + ISSUER, + Long.toString(sequence), + ISSUER, + generation.toString(), + generation.toString(), + "ISSUER_SECURITY_CHANGE")); + byte[] bytes = event.canonicalJsonUtf8(); + return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint( + ISSUER, generation, bytes, bytes); + } + + private static CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint + checkpointShape(BigInteger generation) { + var trusted = sourceCheckpoint(generation); + byte[] checkpoint = trusted.checkpointBytes(); + byte[] event = trusted.latestEventBytes(); + return new CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint( + trusted.issuerId(), + trusted.issuerAuthGeneration(), + checkpoint, + CanonicalGameplayIssuerMemberV2Codec.sha256(checkpoint), + event, + CanonicalGameplayIssuerMemberV2Codec.sha256(event)); + } + + private static CanonicalGameplayIssuerMemberV2Value.Incarnation stableIncarnation(String seed) { + String digest = digest(seed.getBytes(StandardCharsets.UTF_8)); + var deployment = + new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "controlled-deployment-" + seed, + "deployment-generation-" + seed, + List.of("controlled-node-" + seed), + "controlled-redis-build-" + seed, + "controlled-lua-registry-" + seed, + digest, + "READY", + "boot-" + seed, + "startup-" + seed, + "storage-" + seed, + "aof-" + seed); + return new CanonicalGameplayIssuerMemberV2Value.Incarnation( + "controlled-attestor-" + seed, digest, deployment, digest, digest); + } + + private static CanonicalGameplayIssuerBindingLocalOperation.Request request( + String requestSeed, String transitionSeed, CanonicalGameplayBindingIdentity candidate) { + return new CanonicalGameplayIssuerBindingLocalOperation.Request( + UUID.nameUUIDFromBytes(requestSeed.getBytes(StandardCharsets.UTF_8)), + UUID.nameUUIDFromBytes(transitionSeed.getBytes(StandardCharsets.UTF_8)), + candidate, + null, + null); + } + + private static CanonicalGameplayBindingIdentity identity(String seed) { + return identityWithLayout(seed, LAYOUT_VERSION); + } + + private static CanonicalGameplayBindingIdentity identityForAccount(String seed, UUID accountId) { + CanonicalGameplayBindingIdentity identity = identity(seed); + return new CanonicalGameplayBindingIdentity( + accountId, + identity.tenantId(), + identity.playableStateNamespaceId(), + identity.characterId(), + identity.playableStateScope(), + identity.gameInstanceId(), + identity.runtimeGameInstanceId(), + identity.sessionId(), + identity.regionId(), + identity.regionEpoch(), + identity.issuerId(), + identity.issuerAuthGeneration(), + identity.issuerIndexLayoutVersion(), + identity.issuerIndexPartitionCount(), + identity.issuerIndexPartitionCapacity()); + } + + private static CanonicalGameplayBindingIdentity identity( + String seed, CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget runtimeTarget) { + return new CanonicalGameplayBindingIdentity( + uuid(seed + "-account"), + runtimeTarget.canonicalTenantId(), + runtimeTarget.playableStateNamespaceId(), + uuid(seed + "-character"), + runtimeTarget.playableStateScope(), + runtimeTarget.gameInstanceUuid(), + runtimeTarget.gameInstanceId(), + uuid(seed + "-session").toString(), + uuid(seed + "-region"), + BigInteger.valueOf(12), + ISSUER, + BigInteger.valueOf(7), + LAYOUT_VERSION, + PARTITION_COUNT, + PARTITION_CAPACITY); + } + + private static CanonicalGameplayBindingIdentity identityWithLayout( + String seed, BigInteger layoutVersion) { + return new CanonicalGameplayBindingIdentity( + uuid(seed + "-account"), + uuid(seed + "-tenant"), + uuid(seed + "-namespace"), + uuid(seed + "-character"), + "SHARED", + uuid(seed + "-game"), + 90_000L + Math.abs((long) seed.hashCode()), + uuid(seed + "-session").toString(), + uuid(seed + "-region"), + BigInteger.valueOf(12), + ISSUER, + BigInteger.valueOf(7), + layoutVersion, + PARTITION_COUNT, + PARTITION_CAPACITY); + } + + private static CanonicalGameplayBindingIdentity sameControllerDifferentBinding( + CanonicalGameplayBindingIdentity original, String seed) { + return new CanonicalGameplayBindingIdentity( + original.accountId(), + original.tenantId(), + original.playableStateNamespaceId(), + original.characterId(), + original.playableStateScope(), + uuid(seed + "-game"), + original.runtimeGameInstanceId() + 1, + uuid(seed + "-session").toString(), + original.regionId(), + original.regionEpoch(), + original.issuerId(), + original.issuerAuthGeneration(), + original.issuerIndexLayoutVersion(), + original.issuerIndexPartitionCount(), + original.issuerIndexPartitionCapacity()); + } + + private static UUID uuid(String value) { + return UUID.nameUUIDFromBytes(value.getBytes(StandardCharsets.UTF_8)); + } + + /** Controlled upstream lease input; the SQL transition owner remains the phase authority. */ + private static AccountGameplayAdmissionLeaseEvidence controlledLeaseEvidence( + CanonicalGameplayBindingIdentity candidate, + BigInteger bindingGeneration, + CanonicalPlayableTarget target) { + long now = System.currentTimeMillis(); + String nowSeconds = Long.toString(now / 1000L); + Map carrier = new LinkedHashMap<>(); + carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + carrier.put("schemaVersion", "1"); + carrier.put("mode", "PUBLIC_PRODUCTION"); + carrier.put("leaseKind", AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING.name()); + carrier.put("targetNamespace", target.targetNamespace()); + carrier.put( + "callerWorkload", + "spiffe://firemud/ns/" + target.targetNamespace() + "/sa/game-session-service"); + carrier.put("requestId", "10101010-1010-4010-8010-101010101010"); + carrier.put("leaseId", "20202020-2020-4020-8020-202020202020"); + carrier.put("leaseFence", "1"); + Map scope = new LinkedHashMap<>(); + scope.put("accountId", candidate.accountId().toString()); + scope.put("tenantId", candidate.tenantId().toString()); + scope.put("realmId", target.realmId().toString()); + scope.put("worldSlug", target.worldSlug()); + scope.put("realmSlug", target.realmSlug()); + scope.put("playableStateNamespaceId", target.playableStateNamespaceId().toString()); + scope.put("playableStateScope", target.playableStateScope()); + scope.put("gameInstanceId", target.canonicalGameInstanceId().toString()); + scope.put("characterId", candidate.characterId().toString()); + scope.put("sessionId", candidate.sessionId()); + scope.put("bindingGeneration", bindingGeneration.toString()); + scope.put("catalogRevision", Long.toString(target.catalogRevision())); + scope.put("pointerVersion", Long.toString(target.pointerVersion())); + scope.put("regionId", candidate.regionId().toString()); + scope.put("regionEpoch", candidate.regionEpoch().toString()); + carrier.put("bindingScope", scope); + Map authority = new LinkedHashMap<>(); + authority.put("issuerAuthGeneration", candidate.issuerAuthGeneration().toString()); + authority.put("accountAuthorityGeneration", "1"); + authority.put("tenantAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1")); + authority.put("membershipAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1")); + authority.put("privateRealmGrantVersions", List.of()); + carrier.put("authorityTuple", authority); + carrier.put("issuanceFence", "1"); + carrier.put( + "membershipBaseline", + new LinkedHashMap<>( + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + Map.of(candidate.tenantId().toString(), "1"), + "membershipAuthorityGeneration", + "1"))); + String prefix = "account:auth-authority:v1:"; + List> checkpoints = new java.util.ArrayList<>(); + for (String stream : + List.of( + "account/" + candidate.accountId(), + "issuer/" + ISSUER, + "membership/" + candidate.accountId() + "/" + candidate.tenantId(), + "tenant/" + candidate.tenantId())) { + checkpoints.add( + new LinkedHashMap<>( + Map.of( + "outboxStreamKey", + prefix + stream, + "outboxSequence", + stream.startsWith("membership/") || stream.startsWith("tenant/") ? "1" : "0"))); + } + carrier.put("outboxCheckpoints", checkpoints); + Map tokenIdentity = new LinkedHashMap<>(); + tokenIdentity.put("accountId", candidate.accountId().toString()); + tokenIdentity.put("operationId", "40404040-4040-4040-8040-404040404040"); + tokenIdentity.put("issuanceRequestId", "50505050-5050-4050-8050-505050505050"); + tokenIdentity.put("tokenJti", "60606060-6060-4060-8060-606060606060"); + tokenIdentity.put("tokenSHA256", "a".repeat(64)); + tokenIdentity.put("tokenProfile", "game-session-account-delegation"); + tokenIdentity.put("tokenGeneration", "1"); + tokenIdentity.put("issuanceFence", "1"); + tokenIdentity.put("tokenIdentityFence", "1"); + tokenIdentity.put("issuedAt", nowSeconds); + tokenIdentity.put("notBefore", nowSeconds); + tokenIdentity.put("expiresAt", Long.toString(now / 1000L + 60L)); + carrier.put("tokenIdentityEvidence", tokenIdentity); + carrier.put("evaluatedAt", Long.toString(now)); + carrier.put( + "expiresAt", + Long.toString(now + AccountGameplayAdmissionLeaseEvidence.MAX_DURATION_MILLIS)); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + } + + private void establishActualLegacyDisposition(DSLContext dsl) { + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); + UUID cohortId = UUID.randomUUID(); + UUID writerFence = UUID.randomUUID(); + var storageIdentity = + new CanonicalGameplayLegacyMigrationStorageIdentity( + "controlled-cluster-uid", + "controlled-namespace-uid", + "controlled-producer-pod-uid", + "controlled-container-id", + "controlled-node-uid", + "123456789", + 42L, + "controlled-postgres-volume-uid", + "controlled-redis-run-id", + "controlled-redis-volume-uid"); + var fencedCohort = + new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { + @Override + public UUID cohortId() { + return cohortId; + } + + @Override + public UUID legacyWriterFence() { + return writerFence; + } + + @Override + public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + return storageIdentity; + } + + @Override + public void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity expected) { + if (!storageIdentity.equals(expected)) { + throw new IllegalStateException("Controlled test storage identity changed"); + } + } + }; + new CanonicalGameplayLegacyMigrationOwner( + migration, + inventory, + () -> fencedCohort, + ignored -> + new CanonicalGameplayLegacyMigrationSourceSnapshot( + EnumSet.of( + Family.TENANT_SESSION_CONTEXT, + Family.SESSION_ALIAS_CONTEXT, + Family.GAMEPLAY_IDENTITY_CONTEXT, + Family.GAMEPLAY_NAME_CONTEXT, + Family.MOVEMENT_EFFECT, + Family.DURABLE_EFFECT), + List.of()), + new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { + @Override + public void rebuildExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + CanonicalGameplayLegacyMigrationSourceSnapshot source, + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot + canonical) { + assertThat(canonical.bindings()).isEmpty(); + assertThat(canonical.reservations()).isEmpty(); + } + + @Override + public CanonicalGameplayLegacyMigrationReadback readBackExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot + canonical) { + assertThat(canonical.bindings()).isEmpty(); + return new CanonicalGameplayLegacyMigrationReadback( + List.of(), List.of(), List.of(), List.of()); + } + }) + .migrate(); + } + + private TestSchema newTestSchemaAtVersion(String prefix) { + String schema = prefix + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("1030")) + .load() + .migrate(); + return new TestSchema(schema, dataSource, DSL.using(dataSource, SQLDialect.POSTGRES)); + } + + private static void migrateRemaining(TestSchema schema) { + Flyway.configure() + .dataSource(schema.dataSource()) + .schemas(schema.schema()) + .defaultSchema(schema.schema()) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + } + + private DriverManagerDataSource dataSource(String schemaName) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + String jdbcUrl = POSTGRES.getJdbcUrl(); + dataSource.setUrl( + jdbcUrl + (jdbcUrl.contains("?") ? "&" : "?") + "currentSchema=" + schemaName); + dataSource.setUsername(POSTGRES.getUsername()); + dataSource.setPassword(POSTGRES.getPassword()); + return dataSource; + } + + private void dropSchema(String schemaName) { + try (Connection connection = dataSource("public").getConnection()) { + DSL.using(connection, SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + schemaName + "\" CASCADE"); + } catch (SQLException failure) { + throw new IllegalStateException( + "Could not drop the owned issuer local-operation test schema", failure); + } + } + + private static RedisClient createRedisClient(String username, String password) { + RedisURI.Builder builder = RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(6379)); + if (username != null) builder.withAuthentication(username, password); + RedisURI uri = builder.build(); + uri.setTimeout(Duration.ofSeconds(5)); + RedisClient client = RedisClient.create(uri); + client.setOptions( + ClientOptions.builder() + .autoReconnect(false) + .protocolVersion(io.lettuce.core.protocol.ProtocolVersion.RESP2) + .build()); + return client; + } + + private static long count(DSLContext dsl, String table) { + return Objects.requireNonNull( + dsl.fetchOne("SELECT count(*) AS row_count FROM " + table), "Expected count row") + .get("row_count", Long.class); + } + + private static String anchorImage(DSLContext dsl) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT encode(exact_anchor_bytes, 'base64') || ':' || exact_anchor_digest || ':'" + + " || global_coverage_generation::text FROM" + + " game_session_canonical_issuer_installed_anchor WHERE issuer_id = ?", + ISSUER), + "Expected installed anchor row") + .get(0, String.class); + } + + private static String proofImage(DSLContext dsl) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT coalesce(string_agg(partition_id::text || ':'" + + " || encode(exact_physical_field_set_bytes, 'base64') || ':'" + + " || exact_physical_field_set_digest, '|' ORDER BY partition_id), '')" + + " FROM game_session_canonical_issuer_bootstrap_partition_proof"), + "Expected proof aggregate row") + .get(0, String.class); + } + + private static String reservationImage(DSLContext dsl) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT coalesce(jsonb_agg(to_jsonb(r) ORDER BY reservation_id), '[]'::jsonb)::text" + + " FROM game_session_canonical_issuer_partition_reservation r"), + "Expected reservation aggregate row") + .get(0, String.class); + } + + private static String localRegistrationImage(DSLContext dsl) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT" + + " (SELECT coalesce(jsonb_agg(to_jsonb(i) ORDER BY binding_ref), '[]'::jsonb)::text" + + " FROM game_session_canonical_gameplay_binding_inventory i) || ':'" + + " || (SELECT coalesce(jsonb_agg(to_jsonb(t) ORDER BY transition_id), '[]'::jsonb)::text" + + " FROM game_session_canonical_binding_transition t) || ':'" + + " || (SELECT coalesce(jsonb_agg(to_jsonb(r) ORDER BY reservation_id), '[]'::jsonb)::text" + + " FROM game_session_canonical_issuer_partition_reservation r) || ':'" + + " || (SELECT coalesce(jsonb_agg(to_jsonb(o) ORDER BY operation_id), '[]'::jsonb)::text" + + " FROM game_session_canonical_issuer_binding_local_operation o) || ':'" + + " || (SELECT coalesce(jsonb_agg(to_jsonb(g) ORDER BY tenant_id, playable_state_namespace_id, character_id), '[]'::jsonb)::text" + + " FROM game_session_canonical_binding_generation g) || ':'" + + " || (SELECT inventory_revision::text FROM game_session_canonical_binding_inventory_clock WHERE singleton_id = 1) || ':'" + + " || (SELECT coalesce(to_jsonb(c)::text, 'missing') FROM game_session_canonical_issuer_bootstrap_member_op_counter c WHERE issuer_id = '" + + ISSUER + + "')"), + "Expected local registration aggregate row") + .get(0, String.class); + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private record TestSchema(String schema, DriverManagerDataSource dataSource, DSLContext dsl) {} + + private record ConcurrentProjections( + CanonicalGameplayIssuerBindingLocalRedisOwner.Readback first, + CanonicalGameplayIssuerBindingLocalRedisOwner.Readback second) {} +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java index 248424f121..b4a323197f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java @@ -39,6 +39,7 @@ import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; +import org.jooq.Record; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.AfterEach; @@ -131,12 +132,11 @@ void installsOnlyAfterEveryPopulatedAndEmptyPartitionHasExactPhysicalProofAndRep assertThat(first.physicalBindingCount()).isEqualTo(1L); CanonicalGameplayIssuerBootstrapPartitionWork originalWork = partitionWork( - fixture, - fixture.activePartition(), - trustedIncarnation(current.incarnation())); + fixture, fixture.activePartition(), trustedIncarnation(current.incarnation())); var physicalValue = originalWork.memberOperations().getFirst().expectedMemberValue(); var originalReservationRow = - fixture.dsl().fetchOne( + fetchRequired( + fixture.dsl(), "SELECT issuer_coverage_operation_id, issuer_coverage_operation_fence, coverage_fence," + " inventory_snapshot_revision, inventory_revision" + " FROM game_session_canonical_issuer_partition_reservation WHERE reservation_id = ?", @@ -145,41 +145,59 @@ void installsOnlyAfterEveryPopulatedAndEmptyPartitionHasExactPhysicalProofAndRep .isEqualTo(originalReservationRow.get("issuer_coverage_operation_id", UUID.class)) .isNotEqualTo(physicalValue.anchor().issuerCoverageOperationId()); assertThat(physicalValue.reservation().issuerCoverageOperationFence()) - .isEqualTo(originalReservationRow.get("issuer_coverage_operation_fence", BigDecimal.class).toBigIntegerExact()); + .isEqualTo( + originalReservationRow + .get("issuer_coverage_operation_fence", BigDecimal.class) + .toBigIntegerExact()); assertThat(physicalValue.reservation().coverageFence()) - .isEqualTo(originalReservationRow.get("coverage_fence", BigDecimal.class).toBigIntegerExact()); + .isEqualTo( + originalReservationRow.get("coverage_fence", BigDecimal.class).toBigIntegerExact()); assertThat(physicalValue.reservation().inventorySnapshotRevision()) - .isEqualTo(originalReservationRow.get("inventory_snapshot_revision", BigDecimal.class).toBigIntegerExact()); + .isEqualTo( + originalReservationRow + .get("inventory_snapshot_revision", BigDecimal.class) + .toBigIntegerExact()); assertThat(physicalValue.reservation().inventoryRevision()) - .isEqualTo(originalReservationRow.get("inventory_revision", BigDecimal.class).toBigIntegerExact()); + .isEqualTo( + originalReservationRow.get("inventory_revision", BigDecimal.class).toBigIntegerExact()); assertThat(physicalValue.anchor().issuerCoverageOperationId()) .isEqualTo(first.issuerCoverageOperationId()); assertThat(physicalValue.anchor().operationFence()).isEqualTo(first.operationFence()); assertThat(physicalValue.anchor().coverageFence()).isEqualTo(first.coverageFence()); assertThat(physicalValue.anchor().issuerInventorySnapshotRevision()) .isEqualTo(first.issuerInventorySnapshotRevision()); - assertThat(fixture.dsl().fetchOne( - "SELECT count(*) AS proof_count FROM game_session_canonical_issuer_bootstrap_partition_proof") - .get("proof_count", Long.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT count(*) AS proof_count FROM game_session_canonical_issuer_bootstrap_partition_proof") + .get("proof_count", Long.class)) .isEqualTo(PARTITION_COUNT.longValueExact()); - assertThat(fixture.dsl().fetchOne( - "SELECT count(*) AS anchor_count FROM game_session_canonical_issuer_installed_anchor") - .get("anchor_count", Long.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT count(*) AS anchor_count FROM game_session_canonical_issuer_installed_anchor") + .get("anchor_count", Long.class)) .isEqualTo(1L); - assertThat(fixture.dsl().fetchOne( - "SELECT count(*) AS pending_count FROM game_session_canonical_issuer_bootstrap_member_operation" - + " WHERE member_status = 'PENDING_PHYSICAL_PROOF'") - .get("pending_count", Long.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT count(*) AS pending_count FROM game_session_canonical_issuer_bootstrap_member_operation" + + " WHERE member_status = 'PENDING_PHYSICAL_PROOF'") + .get("pending_count", Long.class)) .isEqualTo((long) fixture.plan().memberWorks().size()); - assertThat(fixture.dsl().fetchOne( - "SELECT last_issued_coverage_generation FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", - ISSUER) - .get("last_issued_coverage_generation", BigDecimal.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT last_issued_coverage_generation FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", + ISSUER) + .get("last_issued_coverage_generation", BigDecimal.class)) .isEqualTo(new BigDecimal(first.globalCoverageGeneration())); - assertThat(fixture.dsl().fetchOne( - "SELECT state FROM game_session_canonical_issuer_layout_bootstrap_control WHERE issuer_id = ?", - ISSUER) - .get("state", String.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT state FROM game_session_canonical_issuer_layout_bootstrap_control WHERE issuer_id = ?", + ISSUER) + .get("state", String.class)) .isEqualTo("INITIAL_BOOTSTRAP_INTENT"); for (BigInteger partitionId = BigInteger.ZERO; @@ -199,14 +217,17 @@ void installsOnlyAfterEveryPopulatedAndEmptyPartitionHasExactPhysicalProofAndRep byte[] exactAnchorBeforeCounterAdvance = first.exactAnchorBytes(); String anchorStorageBeforeCounterAdvance = anchorStorageImage(fixture.dsl()); String proofStorageBeforeCounterAdvance = proofStorageImage(fixture.dsl()); - BigInteger laterCoverageGeneration = first.globalCoverageGeneration().add(BigInteger.valueOf(4)); - fixture.dsl().execute( - "UPDATE game_session_canonical_issuer_bootstrap_coverage_counter" - + " SET last_issued_coverage_generation = ?, counter_version = 2" - + " WHERE issuer_id = ? AND last_issued_coverage_generation = ? AND counter_version = 1", - laterCoverageGeneration, - ISSUER, - first.globalCoverageGeneration()); + BigInteger laterCoverageGeneration = + first.globalCoverageGeneration().add(BigInteger.valueOf(4)); + fixture + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_bootstrap_coverage_counter" + + " SET last_issued_coverage_generation = ?, counter_version = 2" + + " WHERE issuer_id = ? AND last_issued_coverage_generation = ? AND counter_version = 1", + laterCoverageGeneration, + ISSUER, + first.globalCoverageGeneration()); assertThat(originalReservationImage(fixture.dsl())).isEqualTo(originalReservationImage); assertThat(anchorStorageImage(fixture.dsl())).isEqualTo(anchorStorageBeforeCounterAdvance); assertThat(proofStorageImage(fixture.dsl())).isEqualTo(proofStorageBeforeCounterAdvance); @@ -218,15 +239,19 @@ void installsOnlyAfterEveryPopulatedAndEmptyPartitionHasExactPhysicalProofAndRep assertThat(replay.exactAnchorBytes()).containsExactly(first.exactAnchorBytes()); assertThat(replay.exactAnchorBytes()).containsExactly(exactAnchorBeforeCounterAdvance); assertThat(replay.globalCoverageGeneration()).isEqualTo(first.globalCoverageGeneration()); - assertThat(fixture.dsl().fetchOne( - "SELECT counter_version FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", - ISSUER) - .get("counter_version", Long.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT counter_version FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", + ISSUER) + .get("counter_version", Long.class)) .isEqualTo(2L); - assertThat(fixture.dsl().fetchOne( - "SELECT last_issued_coverage_generation FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", - ISSUER) - .get("last_issued_coverage_generation", BigDecimal.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT last_issued_coverage_generation FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", + ISSUER) + .get("last_issued_coverage_generation", BigDecimal.class)) .isEqualTo(new BigDecimal(laterCoverageGeneration)); assertThat(originalReservationImage(fixture.dsl())).isEqualTo(originalReservationImage); } @@ -239,7 +264,9 @@ void installedReplayRefusesMissingPartitionWithoutRebuildingOrAllocatingAnotherG owner(fixture, () -> current) .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId()); byte[] missingKey = key(fixture, fixture.activePartition()); - administratorCommands.del(missingKey); + byte[][] missingKeyArguments = new byte[1][]; + missingKeyArguments[0] = missingKey; + administratorCommands.del(missingKeyArguments); assertThatThrownBy( () -> @@ -247,15 +274,19 @@ void installedReplayRefusesMissingPartitionWithoutRebuildingOrAllocatingAnotherG .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId())) .isInstanceOf(IllegalStateException.class); assertThat(administratorCommands.type(missingKey)).isEqualTo("none"); - assertThat(fixture.dsl().fetchOne( - "SELECT global_coverage_generation FROM game_session_canonical_issuer_installed_anchor WHERE issuer_id = ?", - ISSUER) - .get("global_coverage_generation", BigDecimal.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT global_coverage_generation FROM game_session_canonical_issuer_installed_anchor WHERE issuer_id = ?", + ISSUER) + .get("global_coverage_generation", BigDecimal.class)) .isEqualTo(new BigDecimal(installed.globalCoverageGeneration())); - assertThat(fixture.dsl().fetchOne( - "SELECT counter_version FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", - ISSUER) - .get("counter_version", Long.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT counter_version FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", + ISSUER) + .get("counter_version", Long.class)) .isEqualTo(1L); } @@ -265,13 +296,14 @@ void movedAccountCheckpointOrStorageIncarnationLeavesNoCoverageGenerationOrPoint var sourceIncarnation = stableIncarnation("source-movement"); var changedCheckpoint = checkpointShape(BigInteger.valueOf(8)); AtomicInteger sourceCalls = new AtomicInteger(); - var changedAfterReadback = - () -> - new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( - sourceCalls.incrementAndGet() == 5 - ? changedCheckpoint - : sourceFixture.intent().sourceCheckpoint(), - sourceIncarnation); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + changedAfterReadback = + () -> + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + sourceCalls.incrementAndGet() == 5 + ? changedCheckpoint + : sourceFixture.intent().sourceCheckpoint(), + sourceIncarnation); assertThatThrownBy( () -> owner(sourceFixture, changedAfterReadback) @@ -285,11 +317,14 @@ void movedAccountCheckpointOrStorageIncarnationLeavesNoCoverageGenerationOrPoint var initialIncarnation = stableIncarnation("incarnation-movement"); var changedIncarnation = changedIncarnation(initialIncarnation); AtomicInteger incarnationCalls = new AtomicInteger(); - var changedIncarnationAfterReadback = - () -> - new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( - incarnationFixture.intent().sourceCheckpoint(), - incarnationCalls.incrementAndGet() == 5 ? changedIncarnation : initialIncarnation); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + changedIncarnationAfterReadback = + () -> + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + incarnationFixture.intent().sourceCheckpoint(), + incarnationCalls.incrementAndGet() == 5 + ? changedIncarnation + : initialIncarnation); assertThatThrownBy( () -> owner(incarnationFixture, changedIncarnationAfterReadback) @@ -337,15 +372,18 @@ void finitePlanCapacityConflictDoesNotCreateAnyPartitionOrCoverageGeneration() { .isInstanceOf(IllegalStateException.class) .hasMessageContaining("blockers"); assertNoInstalledCoverage(fixture); - assertThat(fixture.dsl().fetchOne( - "SELECT count(*) AS proof_count FROM game_session_canonical_issuer_bootstrap_partition_proof") - .get("proof_count", Long.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT count(*) AS proof_count FROM game_session_canonical_issuer_bootstrap_partition_proof") + .get("proof_count", Long.class)) .isZero(); assertThat(administratorCommands.type(key(fixture, BigInteger.ZERO))).isEqualTo("none"); } private void assertPhysicalTupleConflict(boolean wrongNewAnchor) { Fixture fixture = fixture(BigInteger.ONE, PARTITION_CAPACITY, 1); + administratorCommands.del(new byte[][] {key(fixture, BigInteger.ZERO)}); var incarnation = stableIncarnation(wrongNewAnchor ? "wrong-anchor" : "wrong-original"); CanonicalGameplayIssuerBootstrapPartitionWork work = partitionWork(fixture, BigInteger.ZERO, trustedIncarnation(incarnation)); @@ -381,14 +419,12 @@ private void assertPhysicalTupleConflict(boolean wrongNewAnchor) { expected.incarnation()); byte[] changedBytes = CanonicalGameplayIssuerMemberV2Codec.encode(changed); byte[] key = key(fixture, BigInteger.ZERO); + administratorCommands.hset(key, expected.owner().bindingRef().bytes(), changedBytes); administratorCommands.hset( key, - expected.owner().bindingRef().bytes(), - changedBytes); - administratorCommands.hset( - key, - ascii(CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( - expected.reservation().reservationId())), + ascii( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + expected.reservation().reservationId())), changedBytes); assertThatThrownBy( @@ -444,7 +480,8 @@ private CanonicalGameplayIssuerBootstrapPartitionRedisOwner partitionRedisOwner( private CanonicalGameplayIssuerBootstrapPartitionWork partitionWork( Fixture fixture, BigInteger partitionId, - CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation incarnation) { + CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation + incarnation) { return new CanonicalGameplayIssuerBootstrapMemberOperationRepository(fixture.dsl()) .preparePartitionWork( fixture.intent().operationId(), @@ -515,15 +552,10 @@ private CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState c CanonicalGameplayIssuerMemberV2Codec.sha256(event)); } - private static CanonicalGameplayIssuerMemberV2Value.Incarnation - stableIncarnation(String seed) { + private static CanonicalGameplayIssuerMemberV2Value.Incarnation stableIncarnation(String seed) { String digest = digest(seed.getBytes(StandardCharsets.UTF_8)); return new CanonicalGameplayIssuerMemberV2Value.Incarnation( - "controlled-attestor-" + seed, - digest, - deploymentEvidence(seed, digest), - digest, - digest); + "controlled-attestor-" + seed, digest, deploymentEvidence(seed, digest), digest, digest); } private static CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation @@ -606,13 +638,14 @@ private static CanonicalGameplayBindingIdentity identityInPartition( identity(partitions, capacity, "coverage-active-" + seed + "-" + candidate); if (identity.bindingRef().partitionId(partitions).equals(partitionId)) return identity; } - throw new IllegalStateException("Could not create a second reservation in the target partition"); + throw new IllegalStateException( + "Could not create a second reservation in the target partition"); } - private static void seedActiveSource( - DSLContext dsl, CanonicalGameplayBindingIdentity identity) { + private static void seedActiveSource(DSLContext dsl, CanonicalGameplayBindingIdentity identity) { byte[] bindingRef = identity.bindingRef().bytes(); - BigInteger partitionId = identity.bindingRef().partitionId(identity.issuerIndexPartitionCount()); + BigInteger partitionId = + identity.bindingRef().partitionId(identity.issuerIndexPartitionCount()); UUID accountIndexFence = UUID.randomUUID(); UUID reservationId = UUID.randomUUID(); UUID transitionId = UUID.randomUUID(); @@ -709,14 +742,16 @@ private static void seedActiveSource( } private static String originalReservationImage(DSLContext dsl) { - return dsl.fetchOne( + return fetchRequired( + dsl, "SELECT coalesce(jsonb_agg(to_jsonb(r) ORDER BY reservation_id), '[]'::jsonb)::text AS image " + "FROM game_session_canonical_issuer_partition_reservation r") .get("image", String.class); } private static String anchorStorageImage(DSLContext dsl) { - return dsl.fetchOne( + return fetchRequired( + dsl, "SELECT encode(exact_anchor_bytes, 'base64') || ':' || exact_anchor_digest || ':'" + " || global_coverage_generation::text AS image" + " FROM game_session_canonical_issuer_installed_anchor WHERE issuer_id = ?", @@ -725,7 +760,8 @@ private static String anchorStorageImage(DSLContext dsl) { } private static String proofStorageImage(DSLContext dsl) { - return dsl.fetchOne( + return fetchRequired( + dsl, "SELECT coalesce(string_agg(partition_id::text || ':'" + " || encode(exact_metadata_bytes, 'base64') || ':'" + " || encode(exact_physical_field_set_bytes, 'base64') || ':'" @@ -735,23 +771,33 @@ private static String proofStorageImage(DSLContext dsl) { } private static long fixtureProofCount(Fixture fixture) { - return fixture.dsl() - .fetchOne( + return fetchRequired( + fixture.dsl(), "SELECT count(*) AS proof_count FROM game_session_canonical_issuer_bootstrap_partition_proof") .get("proof_count", Long.class); } private static void assertNoInstalledCoverage(Fixture fixture) { - assertThat(fixture.dsl().fetchOne( - "SELECT count(*) AS anchor_count FROM game_session_canonical_issuer_installed_anchor") - .get("anchor_count", Long.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT count(*) AS anchor_count FROM game_session_canonical_issuer_installed_anchor") + .get("anchor_count", Long.class)) .isZero(); - assertThat(fixture.dsl().fetchOne( - "SELECT count(*) AS counter_count FROM game_session_canonical_issuer_bootstrap_coverage_counter") - .get("counter_count", Long.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT count(*) AS counter_count FROM game_session_canonical_issuer_bootstrap_coverage_counter") + .get("counter_count", Long.class)) .isZero(); } + private static Record fetchRequired(DSLContext dsl, String sql, Object... bindings) { + Record record = dsl.fetchOne(sql, bindings); + if (record == null) throw new IllegalStateException("Required focused query returned no row"); + return record; + } + private static byte[] key(Fixture fixture, BigInteger partitionId) { return CanonicalGameplayIssuerRedisKeys.forPartition( fixture.intent().layoutDescriptor(), partitionId) @@ -777,13 +823,23 @@ private void establishActualLegacyDisposition(DSLContext dsl) { "controlled-redis-volume-uid"); var fencedCohort = new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { - @Override public UUID cohortId() { return cohortId; } - @Override public UUID legacyWriterFence() { return writerFence; } - @Override public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + @Override + public UUID cohortId() { + return cohortId; + } + + @Override + public UUID legacyWriterFence() { + return writerFence; + } + + @Override + public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { return storageIdentity; } - @Override public void requireStillFenced( - CanonicalGameplayLegacyMigrationStorageIdentity expected) { + + @Override + public void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity expected) { if (!storageIdentity.equals(expected)) { throw new IllegalStateException("Controlled test storage identity changed"); } @@ -804,17 +860,22 @@ private void establishActualLegacyDisposition(DSLContext dsl) { Family.DURABLE_EFFECT), List.of()), new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { - @Override public void rebuildExact( + @Override + public void rebuildExact( CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, CanonicalGameplayLegacyMigrationSourceSnapshot source, - net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventorySnapshot + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot canonical) { assertThat(canonical.bindings()).isEmpty(); assertThat(canonical.reservations()).isEmpty(); } - @Override public CanonicalGameplayLegacyMigrationReadback readBackExact( + + @Override + public CanonicalGameplayLegacyMigrationReadback readBackExact( CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, - net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventorySnapshot + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot canonical) { assertThat(canonical.bindings()).isEmpty(); return new CanonicalGameplayLegacyMigrationReadback( @@ -865,7 +926,8 @@ private void dropSchema(String schema) { DSL.using(connection, SQLDialect.POSTGRES) .execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); } catch (SQLException failure) { - throw new IllegalStateException("Could not drop the owned issuer coverage test schema", failure); + throw new IllegalStateException( + "Could not drop the owned issuer coverage test schema", failure); } } @@ -904,7 +966,9 @@ private record Fixture( CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint currentAccountCheckpoint, CanonicalGameplayIssuerPartitionBuildPlan plan) { - DSLContext dsl() { return schema.dsl(); } + DSLContext dsl() { + return schema.dsl(); + } } private record TestSchema(String schema, DriverManagerDataSource dataSource, DSLContext dsl) {} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java index f9aa136284..a1c6c491aa 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java @@ -87,13 +87,17 @@ void actualPreparedPlanIssuesExactPendingV2OperationAndPreservesV1031RowsAcrossR assertThat(fixture.plan().state()) .isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED); Map> retainedBefore = rowSnapshots(fixture.testSchema().dsl()); + Map> retainedWithXminBefore = + rowSnapshotsWithXmin(fixture.testSchema().dsl()); List historyBefore = historySnapshot(fixture.testSchema().dsl()); - migrateRemaining(fixture.testSchema()); + migrateThrough1032(fixture.testSchema()); assertThat(rowSnapshots(fixture.testSchema().dsl())).isEqualTo(retainedBefore); - List historyAfterMigration = historySnapshot(fixture.testSchema().dsl()); - assertThat(historyAfterMigration).hasSize(historyBefore.size() + 1); - assertThat(historyAfterMigration.subList(0, historyBefore.size())) + assertThat(rowSnapshotsWithXmin(fixture.testSchema().dsl())) + .isEqualTo(retainedWithXminBefore); + List historyAfter1032 = historySnapshot(fixture.testSchema().dsl()); + assertThat(historyAfter1032).hasSize(historyBefore.size() + 1); + assertThat(historyAfter1032.subList(0, historyBefore.size())) .containsExactlyElementsOf(historyBefore); assertThat( fixture @@ -102,6 +106,28 @@ void actualPreparedPlanIssuesExactPendingV2OperationAndPreservesV1031RowsAcrossR .fetchSingle("SELECT script FROM flyway_schema_history WHERE version = '1032'") .get(0, String.class)) .isEqualTo("V1032__canonical_issuer_bootstrap_member_operation.sql"); + + migrateRemaining(fixture.testSchema()); + assertThat(rowSnapshots(fixture.testSchema().dsl())).isEqualTo(retainedBefore); + assertThat(rowSnapshotsWithXmin(fixture.testSchema().dsl())) + .isEqualTo(retainedWithXminBefore); + List historyAfterMigration = historySnapshot(fixture.testSchema().dsl()); + assertThat(historyAfterMigration.subList(0, historyAfter1032.size())) + .containsExactlyElementsOf(historyAfter1032); + assertThat( + fixture + .testSchema() + .dsl() + .fetchSingle("SELECT script FROM flyway_schema_history WHERE version = '1032'") + .get(0, String.class)) + .isEqualTo("V1032__canonical_issuer_bootstrap_member_operation.sql"); + assertThat( + fixture + .testSchema() + .dsl() + .fetchSingle("SELECT script FROM flyway_schema_history WHERE version = '1033'") + .get(0, String.class)) + .isEqualTo("V1033__canonical_issuer_bootstrap_coverage.sql"); assertThat( fixture .testSchema() @@ -863,6 +889,18 @@ private static void migrateThrough1031(TestSchema testSchema) { .migrate(); } + private static void migrateThrough1032(TestSchema testSchema) { + Flyway.configure() + .dataSource(testSchema.dataSource()) + .schemas(testSchema.schema()) + .defaultSchema(testSchema.schema()) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("1032")) + .load() + .migrate(); + } + private static void migrateRemaining(TestSchema testSchema) { Flyway.configure() .dataSource(testSchema.dataSource()) @@ -895,6 +933,12 @@ private static Map> rowSnapshots(DSLContext dsl) { return Map.copyOf(snapshots); } + private static Map> rowSnapshotsWithXmin(DSLContext dsl) { + Map> snapshots = new LinkedHashMap<>(); + for (String table : RETAINED_TABLES) snapshots.put(table, rowImagesWithXmin(dsl, table)); + return Map.copyOf(snapshots); + } + private static List historySnapshot(DSLContext dsl) { return dsl.fetch( "SELECT to_jsonb(history_row)::text AS row_image FROM flyway_schema_history history_row" @@ -910,6 +954,14 @@ private static List rowImages(DSLContext dsl, String tableName) { .getValues("row_image", String.class); } + private static List rowImagesWithXmin(DSLContext dsl, String tableName) { + return dsl.fetch( + "SELECT xmin::text || ':' || to_jsonb(retained_row)::text AS row_image FROM " + + tableName + + " retained_row ORDER BY to_jsonb(retained_row)::text, xmin::text") + .getValues("row_image", String.class); + } + private static void assertNoIssuedRows(DSLContext dsl) { assertThat(rowImages(dsl, "game_session_canonical_issuer_bootstrap_member_operation")) .isEmpty(); 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 539de03fac..b27c2e5441 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 @@ -106,7 +106,7 @@ void populatedPendingIntentRetainsCompleteCohortAndBothCoverageTuplesAcrossConcu rowImages(testSchema.dsl(), "game_session_canonical_binding_region_bridge_obligation"); List inventoryClockBefore = rowImages(testSchema.dsl(), "game_session_canonical_binding_inventory_clock"); - List migrationHistoryBefore = rowImages(testSchema.dsl(), "flyway_schema_history"); + List migrationHistoryBefore = migrationHistorySnapshot(testSchema.dsl()); List retainedSourceTables = List.of( "game_session_canonical_gameplay_binding_inventory", @@ -125,10 +125,10 @@ void populatedPendingIntentRetainsCompleteCohortAndBothCoverageTuplesAcrossConcu .toList(); migrateThrough1031(testSchema); - List migrationHistoryAfter1031 = rowImages(testSchema.dsl(), "flyway_schema_history"); - assertThat(migrationHistoryAfter1031) - .hasSize(migrationHistoryBefore.size() + 1) - .containsAll(migrationHistoryBefore); + List migrationHistoryAfter1031 = migrationHistorySnapshot(testSchema.dsl()); + assertThat(migrationHistoryAfter1031).hasSize(migrationHistoryBefore.size() + 1); + assertThat(migrationHistoryAfter1031.subList(0, migrationHistoryBefore.size())) + .containsExactlyElementsOf(migrationHistoryBefore); assertThat( testSchema .dsl() @@ -141,18 +141,43 @@ void populatedPendingIntentRetainsCompleteCohortAndBothCoverageTuplesAcrossConcu .toList()) .isEqualTo(retainedRowsWithXminBefore); + List> retainedRowsWithXminAt1031 = + retainedSourceTables.stream() + .map(table -> rowImagesWithXmin(testSchema.dsl(), table)) + .toList(); + migrateThrough1032(testSchema); + List migrationHistoryAfter1032 = migrationHistorySnapshot(testSchema.dsl()); + assertThat(migrationHistoryAfter1032).hasSize(migrationHistoryAfter1031.size() + 1); + assertThat(migrationHistoryAfter1032.subList(0, migrationHistoryAfter1031.size())) + .containsExactlyElementsOf(migrationHistoryAfter1031); + assertThat( + testSchema + .dsl() + .fetchSingle("SELECT script FROM flyway_schema_history WHERE version = '1032'") + .get(0, String.class)) + .isEqualTo("V1032__canonical_issuer_bootstrap_member_operation.sql"); + assertThat( + retainedSourceTables.stream() + .map(table -> rowImagesWithXmin(testSchema.dsl(), table)) + .toList()) + .isEqualTo(retainedRowsWithXminAt1031); + migrateRemaining(testSchema); - List migrationHistoryAfterCurrent = - rowImages(testSchema.dsl(), "flyway_schema_history"); - assertThat(migrationHistoryAfterCurrent) - .hasSize(migrationHistoryAfter1031.size() + 1) - .containsAll(migrationHistoryAfter1031); + List migrationHistoryAfterCurrent = migrationHistorySnapshot(testSchema.dsl()); + assertThat(migrationHistoryAfterCurrent.subList(0, migrationHistoryAfter1032.size())) + .containsExactlyElementsOf(migrationHistoryAfter1032); assertThat( testSchema .dsl() .fetchSingle("SELECT script FROM flyway_schema_history WHERE version = '1032'") .get(0, String.class)) .isEqualTo("V1032__canonical_issuer_bootstrap_member_operation.sql"); + assertThat( + testSchema + .dsl() + .fetchSingle("SELECT script FROM flyway_schema_history WHERE version = '1033'") + .get(0, String.class)) + .isEqualTo("V1033__canonical_issuer_bootstrap_coverage.sql"); var ready = new CountDownLatch(2); var start = new CountDownLatch(1); @@ -276,7 +301,7 @@ void populatedPendingIntentRetainsCompleteCohortAndBothCoverageTuplesAcrossConcu .containsExactlyElementsOf(regionObligationsBefore); assertThat(rowImages(testSchema.dsl(), "game_session_canonical_binding_inventory_clock")) .containsExactlyElementsOf(inventoryClockBefore); - List migrationHistoryAfter = rowImages(testSchema.dsl(), "flyway_schema_history"); + List migrationHistoryAfter = migrationHistorySnapshot(testSchema.dsl()); assertThat(migrationHistoryAfter).containsExactlyElementsOf(migrationHistoryAfterCurrent); assertThat( retainedSourceTables.stream() @@ -1268,6 +1293,18 @@ private static void migrateThrough1031(TestSchema testSchema) { .migrate(); } + private static void migrateThrough1032(TestSchema testSchema) { + Flyway.configure() + .dataSource(testSchema.dataSource()) + .schemas(testSchema.schema()) + .defaultSchema(testSchema.schema()) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("1032")) + .load() + .migrate(); + } + private static void migrateRemaining(TestSchema testSchema) { Flyway.configure() .dataSource(testSchema.dataSource()) @@ -1385,6 +1422,13 @@ private static List rowImagesWithXmin(DSLContext dsl, String tableName) .getValues("row_image", String.class); } + private static List migrationHistorySnapshot(DSLContext dsl) { + return dsl.fetch( + "SELECT to_jsonb(history_row)::text AS row_image FROM flyway_schema_history history_row" + + " ORDER BY installed_rank") + .getValues("row_image", String.class); + } + private static void dropSchema(String schema) { try (Connection connection = dataSource("public").getConnection()) { DSL.using(connection, SQLDialect.POSTGRES) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwnerTest.java new file mode 100644 index 0000000000..e890e4776d --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwnerTest.java @@ -0,0 +1,240 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.math.BigInteger; +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountCoverageEvidence; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +import net.firedevops.firemud.gamesession.client.AccountGameplayAdmissionLeaseClient; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import org.junit.jupiter.api.Test; + +class CanonicalGameplayAdmissionAbortOwnerTest { + private static final UUID TRANSITION_ID = + UUID.fromString("88888888-8888-4888-8888-888888888888"); + private static final String ORIGINAL_LEASE = "canonical-original-lease-evidence"; + + @Test + void accountTimeoutRetainsTheOriginalNonAdmittingObligation() { + var repository = mock(CanonicalGameplayBindingInventoryRepository.class); + var accountClient = mock(AccountGameplayAdmissionLeaseClient.class); + var source = source(false); + when(repository.readFirstNewAdmissionAbortSource(TRANSITION_ID)).thenReturn(source); + when(accountClient.abort( + eq("presented-initial-gsa"), + any(byte[].class), + eq(TRANSITION_ID))) + .thenThrow(new IllegalStateException("Account abort response unavailable")); + + var owner = new CanonicalGameplayAdmissionAbortOwner(repository, accountClient); + assertThatThrownBy(() -> owner.abortFirstNew(TRANSITION_ID, "presented-initial-gsa")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account abort response unavailable"); + + verify(accountClient) + .abort( + eq("presented-initial-gsa"), + org.mockito.ArgumentMatchers.argThat( + bytes -> + java.util.Arrays.equals( + ORIGINAL_LEASE.getBytes(StandardCharsets.UTF_8), bytes)), + eq(TRANSITION_ID)); + verify(repository, never()).recordFirstNewAccountAbort(any(), any()); + } + + private static final UUID CLEANUP_ID = UUID.fromString("abababab-abab-4bab-8bab-abababababab"); + + @Test + void retainedTerminalReplayStillAuthenticatesTheCurrentCallerAndCannotCasOnFailure() { + var repository = mock(CanonicalGameplayBindingInventoryRepository.class); + var client = mock(AccountGameplayAdmissionLeaseClient.class); + when(repository.readFirstNewAdmissionAbortSource(TRANSITION_ID)).thenReturn(source(true)); + when(client.abort(eq("expired-or-revoked-caller"), any(byte[].class), eq(TRANSITION_ID))) + .thenThrow(new IllegalStateException("current caller refused")); + assertThatThrownBy(() -> new CanonicalGameplayAdmissionAbortOwner(repository, client) + .abortFirstNew(TRANSITION_ID, "expired-or-revoked-caller")) + .hasMessage("current caller refused"); + verify(client).abort(eq("expired-or-revoked-caller"), any(byte[].class), eq(TRANSITION_ID)); + verify(repository, never()).recordFirstNewAccountAbort(any(), any()); + } + + @Test + void ambientTransactionOrSynchronizationRefusesBeforeAnyOwnerInteraction() { + for (boolean actualTransaction : new boolean[] {false, true}) { + var repository = mock(CanonicalGameplayBindingInventoryRepository.class); + var client = mock(AccountGameplayAdmissionLeaseClient.class); + org.springframework.transaction.support.TransactionSynchronizationManager.initSynchronization(); + org.springframework.transaction.support.TransactionSynchronizationManager.setActualTransactionActive(actualTransaction); + try { + assertThatThrownBy(() -> new CanonicalGameplayAdmissionAbortOwner(repository, client) + .abortFirstNew(TRANSITION_ID, "presented-initial-gsa")) + .hasMessage("First-NEW Account abort requires no ambient SQL scope"); + org.mockito.Mockito.verifyNoInteractions(repository, client); + } finally { + org.springframework.transaction.support.TransactionSynchronizationManager.clear(); + } + } + } + + @Test + void retainedAbortRejectsContradictoryAccountStatesOrChangedCleanupWithoutCas() { + for (var state : net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.State.values()) { + var repository = mock(CanonicalGameplayBindingInventoryRepository.class); + var client = mock(AccountGameplayAdmissionLeaseClient.class); + var retained = source(true); + var lease = retained.originalDecision().leaseEvidence(); + when(lease.hasSameIdentity(lease)).thenReturn(true); + var operation = mock(net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OperationEvidence.class); + when(operation.originalLeaseEvidence()).thenReturn(lease); + when(operation.state()).thenReturn(state); + switch (state) { + case ABORTED -> { + when(operation.bindingDecisionId()).thenReturn(TRANSITION_ID); + when(operation.orphanCleanupId()).thenReturn(UUID.randomUUID()); + } + case COMMITTED -> { + when(operation.bindingDecisionId()).thenReturn(TRANSITION_ID); + when(operation.originalAckReceipt()).thenReturn(mock(net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalAckReceiptEvidence.class)); + } + case PENDING -> { } + } + when(repository.readFirstNewAdmissionAbortSource(TRANSITION_ID)).thenReturn(retained); + when(client.abort(any(), any(), any())).thenReturn(operation); + assertThatThrownBy(() -> new CanonicalGameplayAdmissionAbortOwner(repository, client) + .abortFirstNew(TRANSITION_ID, "presented-initial-gsa")) + .hasMessage("Account replay contradicts the retained definitive abort"); + verify(repository, never()).recordFirstNewAccountAbort(any(), any()); + } + } + + static CanonicalGameplayAdmissionAbortSource source(boolean aborted) { + var decision = mock(CanonicalGameplayAdmissionDecision.class); + var lease = mock(AccountGameplayAdmissionLeaseEvidence.class); + var identity = + new CanonicalGameplayBindingIdentity( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + UUID.fromString("33333333-3333-4333-8333-333333333333"), + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "SHARED", + UUID.fromString("55555555-5555-4555-8555-555555555555"), + 23L, + "66666666-6666-4666-8666-666666666666", + UUID.fromString("77777777-7777-4777-8777-777777777777"), + BigInteger.ONE, + GameSessionAccountDelegationProfile.ISSUER, + BigInteger.ONE, + BigInteger.ONE, + BigInteger.ONE, + BigInteger.TEN); + CanonicalGameplayBindingRef bindingRef = identity.bindingRef(); + CanonicalPlayableTarget target = + new CanonicalPlayableTarget( + "game-session-admission-test", + "tenant", + identity.tenantId(), + "world", + "World", + UUID.fromString("99999999-9999-4999-8999-999999999999"), + "realm", + "Realm", + 1L, + 23L, + identity.playableStateNamespaceId(), + "SHARED", + identity.gameInstanceId(), + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + 1L, + 1L, + 1L, + "a".repeat(64), + 1L, + "original-request", + "b".repeat(64), + CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER, + null, + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + "sha256:" + "d".repeat(64), + 1L, + "sha256:" + "e".repeat(64), + CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + false, + Instant.parse("2026-10-01T00:00:00Z"), + "ALLOW"); + var transition = + new CanonicalGameplayBindingTransitionSnapshot( + TRANSITION_ID, + identity, + BigInteger.ONE, + bindingRef, + BigInteger.ONE, + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"), + null, + null, + aborted ? CanonicalGameplayBindingTransitionSnapshot.Status.ABORTED : CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL, + CanonicalGameplayAccountCoverageEvidence.noActiveFlow()); + var candidate = + new CanonicalGameplayBindingInventoryEntry( + identity, + bindingRef, + BigInteger.ONE, + transition.candidateAccountIndexFence(), + transition.issuerReservationId(), + TRANSITION_ID, + aborted ? CanonicalGameplayBindingInventoryEntry.Lifecycle.TERMINAL_UNRESOLVED : CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL, + CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED, + CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED, + BigInteger.ONE); + var reservation = + new CanonicalIssuerPartitionReservation( + transition.issuerReservationId(), + identity, + BigInteger.ONE, + TRANSITION_ID, + BigInteger.ZERO, + aborted ? CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING : CanonicalIssuerPartitionReservation.Lifecycle.RESERVED, + transition.reservationFence(), + UUID.fromString("12121212-1212-4212-8212-121212121212"), + BigInteger.ONE, + BigInteger.ONE, + BigInteger.ONE, + BigInteger.ONE); + when(decision.bindingDecisionId()).thenReturn(TRANSITION_ID); + when(decision.leaseEvidence()).thenReturn(lease); + when(decision.candidate()).thenReturn(identity); + when(decision.bindingGeneration()).thenReturn(BigInteger.ONE); + when(decision.expectedOldBindingGeneration()).thenReturn(null); + when(decision.targetEvidence()).thenReturn(target); + when(decision.leaseKind()) + .thenReturn(AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING); + when(lease.leaseKind()) + .thenReturn(AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING); + when(decision.leaseEvidenceJson()).thenReturn(ORIGINAL_LEASE); + when(lease.canonicalJson()).thenReturn(ORIGINAL_LEASE); + return + new CanonicalGameplayAdmissionAbortSource( + transition, candidate, reservation, decision, aborted ? CLEANUP_ID : null); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java new file mode 100644 index 0000000000..9be7858d5b --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java @@ -0,0 +1,91 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Map; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.gamesession.security.CanonicalGameplayAdmissionDecisionReadWorkloadGuard; +import net.firedevops.firemud.gamesession.service.impl.CanonicalGameplayAdmissionDecisionReadGrpcService; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayAdmissionDecisionRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayAdmissionDecisionResponse; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +/** Controlled callback/parser failure tests; native owner composition is a separate PostgreSQL test. */ +class CanonicalGameplayAdmissionDecisionReadGrpcServiceTest { + @Test + void unexpectedParserFailureTerminatesOnceWithSanitizedInternalBeforeRepositoryRead() { + var repository = mock(CanonicalGameplayBindingInventoryRepository.class); + var guard = mock(CanonicalGameplayAdmissionDecisionReadWorkloadGuard.class); + var observer = observer(); + var request = GetCanonicalGameplayAdmissionDecisionRequest.getDefaultInstance(); + try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { + codec.when(() -> CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest(request)) + .thenThrow(new IllegalStateException("private parser details")); + new CanonicalGameplayAdmissionDecisionReadGrpcService(repository, guard, "test") + .getCanonicalGameplayAdmissionDecision(request, observer); + } + var failure = ArgumentCaptor.forClass(Throwable.class); + verify(observer).onError(failure.capture()); + assertThat(Status.fromThrowable(failure.getValue()).getCode()).isEqualTo(Status.Code.INTERNAL); + assertThat(failure.getValue()).hasMessageNotContaining("private parser details"); + verify(observer, never()).onNext(any()); + verify(observer, never()).onCompleted(); + verifyNoInteractions(repository); + } + + @Test + void onNextFailureSignalsOneErrorButCompletionFailureEscapesWithoutSecondTerminal() { + for (boolean completionFailure : new boolean[] {false, true}) { + var repository = mock(CanonicalGameplayBindingInventoryRepository.class); + var guard = mock(CanonicalGameplayAdmissionDecisionReadWorkloadGuard.class); + var observer = observer(); + var request = GetCanonicalGameplayAdmissionDecisionRequest.getDefaultInstance(); + var source = CanonicalGameplayAdmissionAbortOwnerTest.source(false); + var decision = source.originalDecision(); + var lease = decision.leaseEvidence(); + when(lease.carrier()).thenReturn(Map.of("targetNamespace", "test", "callerWorkload", "spiffe://firemud/ns/test/sa/game-session-service")); + var selector = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.RequestEvidence.class); + when(selector.expectedLeaseEvidence()).thenReturn(lease); + when(selector.bindingDecisionId()).thenReturn(decision.bindingDecisionId()); + when(repository.readAdmissionDecision(decision.bindingDecisionId(), lease)).thenReturn(decision); + var response = GetCanonicalGameplayAdmissionDecisionResponse.getDefaultInstance(); + var callbackFailure = new IllegalStateException("observer callback failed"); + if (completionFailure) doThrow(callbackFailure).when(observer).onCompleted(); + else doThrow(callbackFailure).when(observer).onNext(response); + try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { + codec.when(() -> CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest(request)).thenReturn(selector); + codec.when(() -> CanonicalGameplayAdmissionDecisionReadGrpcCodec.toResponse(any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(response); + Runnable receive = () -> new CanonicalGameplayAdmissionDecisionReadGrpcService(repository, guard, "test") + .getCanonicalGameplayAdmissionDecision(request, observer); + if (completionFailure) assertThatThrownBy(receive::run).isSameAs(callbackFailure); + else receive.run(); + } + verify(observer).onNext(response); + if (completionFailure) { + verify(observer).onCompleted(); + verify(observer, never()).onError(any()); + } else { + verify(observer).onError(any()); + verify(observer, never()).onCompleted(); + } + } + } + + @SuppressWarnings("unchecked") + private static StreamObserver observer() { + return mock(StreamObserver.class); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuardTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuardTest.java new file mode 100644 index 0000000000..2fff6f1044 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuardTest.java @@ -0,0 +1,110 @@ +package net.firedevops.firemud.gamesession.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; + +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.Status; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionDecisionReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GameSessionServiceGrpc; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +class CanonicalGameplayAdmissionDecisionReadWorkloadGuardTest { + private static final String NAMESPACE = "game-session-admission-test"; + private final CanonicalGameplayAdmissionDecisionReadWorkloadGuard guard = + new CanonicalGameplayAdmissionDecisionReadWorkloadGuard(NAMESPACE); + + @AfterEach + void clearSessionContext() { + SessionContext.clear(); + } + + @Test + void acceptsOnlyTheExactSameNamespaceAccountMethod() { + Invocation accepted = + invoke( + CanonicalGameplayAdmissionDecisionReadServiceGrpc + .getGetCanonicalGameplayAdmissionDecisionMethod(), + peer(NAMESPACE, "account-service")); + assertThat(accepted.nextStarts()).isEqualTo(1); + assertThat(accepted.status()).isNull(); + + for (var method : + List.of( + GameSessionServiceGrpc.getStartSessionMethod(), + CanonicalGameplayAdmissionDecisionReadServiceGrpc + .getGetCanonicalGameplayAdmissionDecisionMethod() + .toBuilder() + .setFullMethodName( + "game_session.v1.GameSessionControlPlaneService/GetCanonicalGameplayAdmissionDecision") + .build())) { + Invocation rejected = invoke(method, peer(NAMESPACE, "account-service")); + assertThat(rejected.nextStarts()).isZero(); + assertThat(rejected.status().getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); + } + } + + @Test + void rejectsMissingForeignOrSessionContextIdentityBeforeHandler() { + var method = + CanonicalGameplayAdmissionDecisionReadServiceGrpc + .getGetCanonicalGameplayAdmissionDecisionMethod(); + assertRejected(invoke(method, null), Status.Code.UNAUTHENTICATED); + assertRejected( + invoke(method, peer(NAMESPACE, "world-management-service")), + Status.Code.PERMISSION_DENIED); + assertRejected(invoke(method, peer("other", "account-service")), Status.Code.PERMISSION_DENIED); + + SessionContext.setContext("account-1", List.of(), Map.of()); + assertRejected(invoke(method, peer(NAMESPACE, "account-service")), Status.Code.PERMISSION_DENIED); + SessionContext.setContext(null, List.of(), Map.of(), true, "account-service", "instance"); + assertRejected(invoke(method, peer(NAMESPACE, "account-service")), Status.Code.PERMISSION_DENIED); + } + + private void assertRejected(Invocation invocation, Status.Code code) { + assertThat(invocation.nextStarts()).isZero(); + assertThat(invocation.status().getCode()).isEqualTo(code); + } + + private Invocation invoke(MethodDescriptor method, GrpcPeerIdentity peer) { + return invokeTyped(method, peer); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + private Invocation invokeTyped(MethodDescriptor method, GrpcPeerIdentity peer) { + ServerCall call = mock(ServerCall.class); + org.mockito.Mockito.when(call.getMethodDescriptor()).thenReturn(method); + AtomicInteger starts = new AtomicInteger(); + ServerCallHandler next = + (ignoredCall, ignoredHeaders) -> { + starts.incrementAndGet(); + return new ServerCall.Listener() {}; + }; + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run(() -> guard.interceptCall(call, new Metadata(), next)); + ArgumentCaptor status = ArgumentCaptor.forClass(Status.class); + org.mockito.Mockito.verify(call, org.mockito.Mockito.atMostOnce()) + .close(status.capture(), any(Metadata.class)); + return new Invocation(starts.get(), status.getAllValues().isEmpty() ? null : status.getValue()); + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow(); + } + + private record Invocation(int nextStarts, Status status) {} +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/ProtectedGameSessionLoginGrpcInterceptorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/ProtectedGameSessionLoginGrpcInterceptorTest.java index 76c3bd0b98..a960a64be7 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/ProtectedGameSessionLoginGrpcInterceptorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/ProtectedGameSessionLoginGrpcInterceptorTest.java @@ -12,6 +12,7 @@ import io.grpc.ServerCall; import io.grpc.ServerCallHandler; import io.grpc.Status; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionDecisionReadServiceGrpc; import net.firedevops.firemud.gamesession.v1.CanonicalInitialAdmissionOwnerProofReadServiceGrpc; import net.firedevops.firemud.gamesession.v1.GameSessionServiceGrpc; import org.junit.jupiter.api.Test; @@ -26,6 +27,30 @@ void passesActualDedicatedTerminalProofMethodToItsOwnerGuard() { true); } + @Test + void passesOnlyTheActualPurposeSpecificAdmissionDecisionReadMethod() { + verifyBoundary( + CanonicalGameplayAdmissionDecisionReadServiceGrpc + .getGetCanonicalGameplayAdmissionDecisionMethod(), + true); + verifyBoundary( + CanonicalGameplayAdmissionDecisionReadServiceGrpc + .getGetCanonicalGameplayAdmissionDecisionMethod() + .toBuilder() + .setFullMethodName( + "game_session.v1.GameSessionControlPlaneService/GetCanonicalGameplayAdmissionDecision") + .build(), + false); + verifyBoundary( + CanonicalGameplayAdmissionDecisionReadServiceGrpc + .getGetCanonicalGameplayAdmissionDecisionMethod() + .toBuilder() + .setFullMethodName( + "game_session.v1.GameSessionControlPlaneService/GetPublishedRealmAdmissionOwnerRead") + .build(), + false); + } + @Test void deniesUndeclaredControlPlaneAliasAndPlayerStartMethod() { verifyBoundary( From f5f7c132f58538785625334dfea1faf073f0234a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:13:03 +1300 Subject: [PATCH 11/34] Qualify actual first-NEW abort composition and retained member ACK --- ...nitiveAbortCompositionIntegrationTest.java | 452 ++++++++++++---- .../game-session-service/build.gradle.kts | 7 +- ...anonicalGameplayAdmissionAbortOutcome.java | 7 +- ...CanonicalGameplayAdmissionAbortSource.java | 16 +- ...alGameplayAdmissionAbortManualFactory.java | 8 +- .../CanonicalGameplayAdmissionAbortOwner.java | 22 +- ...calGameplayBindingInventoryRepository.java | 133 +++-- ...meplayIssuerLayoutBootstrapRepository.java | 7 +- ...ameplayIssuerPartitionBuildRepository.java | 7 +- ...eplayAdmissionDecisionReadGrpcService.java | 4 +- ...onical_gameplay_first_new_abort_source.sql | 131 ++++- ...eplayAdmissionAbortCompositionFixture.java | 501 +++++++++++++++--- ...calGameplayBindingRuntimeTestFixtures.java | 5 +- ...rtitionBuildRepositoryIntegrationTest.java | 26 +- ...onicalGameplayAdmissionAbortOwnerTest.java | 77 ++- ...yAdmissionDecisionReadGrpcServiceTest.java | 37 +- ...dmissionDecisionReadWorkloadGuardTest.java | 9 +- 17 files changed, 1133 insertions(+), 316 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java index f29d23367a..83f7d71b8b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java @@ -23,7 +23,6 @@ import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionLeaseManualFactory; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; -import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.State; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; @@ -56,12 +55,24 @@ class AccountGameSessionDefinitiveAbortCompositionIntegrationTest { new AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest(); @TempDir Path temporaryDirectory; - @BeforeAll static void startPostgres() { AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.startPostgres(); } - @AfterAll static void stopPostgres() { AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.stopPostgres(); } - @AfterEach void cleanupAccountSchemas() { accountFixtures.dropRunOwnedSchemas(); } + @BeforeAll + static void startPostgres() { + AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.startPostgres(); + } + + @AfterAll + static void stopPostgres() { + AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.stopPostgres(); + } + + @AfterEach + void cleanupAccountSchemas() { + accountFixtures.dropRunOwnedSchemas(); + } @Test - void actualAbortExactRetryAndRestartRetainOriginalLeaseAndRejectTerminalRewrites() throws Exception { + void actualAbortExactRetryAndRestartRetainOriginalLeaseAndRejectTerminalRewrites() + throws Exception { try (var session = open()) { var original = session.gs.source(); var result = session.abort(); @@ -70,33 +81,72 @@ void actualAbortExactRetryAndRestartRetainOriginalLeaseAndRejectTerminalRewrites var retainedImage = session.image(); assertThat(source.isAccountAborted()).isTrue(); assertThat(source.orphanCleanupId()).isEqualTo(result.orphanCleanupId()); - assertThat(source.originalDecision().leaseEvidenceJson()).isEqualTo(original.originalDecision().leaseEvidenceJson()); - assertThat(source.originalDecision().leaseSha256()).isEqualTo(original.originalDecision().leaseSha256()); - assertThat(source.candidate().lifecycle()).isEqualTo(CanonicalGameplayBindingInventoryEntry.Lifecycle.TERMINAL_UNRESOLVED); - assertThat(source.reservation().lifecycle()).isEqualTo(CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING); + assertThat(source.originalDecision().leaseEvidenceJson()) + .isEqualTo(original.originalDecision().leaseEvidenceJson()); + assertThat(source.originalDecision().leaseSha256()) + .isEqualTo(original.originalDecision().leaseSha256()); + assertThat(source.candidate().lifecycle()) + .isEqualTo(CanonicalGameplayBindingInventoryEntry.Lifecycle.TERMINAL_UNRESOLVED); + assertThat(source.reservation().lifecycle()) + .isEqualTo(CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING); // New owner instance and independent repository read recover the same retained source. assertThat(session.abort().orphanCleanupId()).isEqualTo(result.orphanCleanupId()); - assertThat(session.client.read(session.jwt, session.leaseBytes()).state()).isEqualTo(State.ABORTED); - assertThat(session.client.finalizeLease(session.jwt, session.leaseBytes(), session.gs.transitionId()).state()).isEqualTo(State.ABORTED); - assertThatThrownBy(() -> session.abortWith("invalid-current-caller-token")).isInstanceOf(RuntimeException.class); + assertThat(session.client.read(session.jwt, session.leaseBytes()).state()) + .isEqualTo(State.ABORTED); + assertThat( + session + .client + .finalizeLease(session.jwt, session.leaseBytes(), session.gs.transitionId()) + .state()) + .isEqualTo(State.ABORTED); + assertThatThrownBy(() -> session.abortWith("invalid-current-caller-token")) + .isInstanceOf(RuntimeException.class); assertThat(session.image()).isEqualTo(retainedImage); - for (String assignment : new String[] { - "admission_orphan_cleanup_id = '34343434-3434-4434-8434-343434343434'", - "status = 'PROVISIONAL', admission_orphan_cleanup_id = NULL", - "admission_lease_id = '45454545-4545-4545-8545-454545454545'", - "admission_lease_digest = '" + "e".repeat(64) + "'", - "admission_lease_evidence = '{}'", - "inventory_revision = inventory_revision - 1" }) { - assertThatThrownBy(() -> session.gs.dsl().execute( - "UPDATE game_session_canonical_binding_transition SET " + assignment + " WHERE transition_id = ?", - session.gs.transitionId())).isInstanceOf(org.jooq.exception.DataAccessException.class); + for (String assignment : + new String[] { + "admission_orphan_cleanup_id = '34343434-3434-4434-8434-343434343434'", + "status = 'PROVISIONAL', admission_orphan_cleanup_id = NULL", + "admission_lease_id = '45454545-4545-4545-8545-454545454545'", + "admission_lease_digest = '" + "e".repeat(64) + "'", + "admission_lease_evidence = '{}'", + "inventory_revision = inventory_revision - 1" + }) { + assertThatThrownBy( + () -> + session + .gs + .dsl() + .execute( + "UPDATE game_session_canonical_binding_transition SET " + + assignment + + " WHERE transition_id = ?", + session.gs.transitionId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(session.image()).isEqualTo(retainedImage); } - assertThatThrownBy(() -> session.gs.dsl().execute( - "UPDATE game_session_canonical_issuer_partition_reservation SET lifecycle = 'RELEASED' WHERE transition_id = ?", - session.gs.transitionId())).isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy( + () -> + session + .gs + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_partition_reservation SET lifecycle = 'RELEASED' WHERE transition_id = ?", + session.gs.transitionId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(session.image()).isEqualTo(retainedImage); + for (String statement : + new String[] { + "UPDATE game_session_canonical_issuer_partition_reservation SET reservation_fence = '56565656-5656-4656-8656-565656565656' WHERE transition_id = ?", + "UPDATE game_session_canonical_gameplay_binding_inventory SET lifecycle = 'ACTIVE' WHERE transition_id = ?", + "UPDATE game_session_canonical_gameplay_binding_inventory SET session_id = '67676767-6767-4767-8767-676767676767' WHERE transition_id = ?", + "DELETE FROM game_session_canonical_issuer_partition_reservation WHERE transition_id = ?", + "DELETE FROM game_session_canonical_gameplay_binding_inventory WHERE transition_id = ?" + }) { + assertThatThrownBy(() -> session.gs.dsl().execute(statement, session.gs.transitionId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(session.image()).isEqualTo(retainedImage); + } // Cleanup is intentionally unresolved. A newer first-NEW candidate must remain fenced; // this boundary does not fabricate an admitted/newer binding to claim cleanup safety. assertThatThrownBy(session.gs::prepareNewerCandidate).isInstanceOf(RuntimeException.class); @@ -106,15 +156,22 @@ void actualAbortExactRetryAndRestartRetainOriginalLeaseAndRejectTerminalRewrites } @Test - void actualAccountAbortWithLostReplyKeepsGsProvisionalThenRecoversSameOriginalAfterRestart() throws Exception { + void actualAccountAbortWithLostReplyKeepsGsProvisionalThenRecoversSameOriginalAfterRestart() + throws Exception { try (var session = open()) { var before = session.image(); var lostReplyClient = mock(AccountGameplayAdmissionLeaseClient.class); - doAnswer(invocation -> { - session.client.abort(session.jwt, session.leaseBytes(), session.gs.transitionId()); - throw new IllegalStateException("controlled loss after actual Account ABORTED reply"); - }).when(lostReplyClient).abort(any(), any(), any()); - var lostReplyOwner = CanonicalGameplayAdmissionAbortManualFactory.createUnregisteredOwner(session.gs.dsl(), lostReplyClient); + doAnswer( + invocation -> { + session.client.abort(session.jwt, session.leaseBytes(), session.gs.transitionId()); + throw new IllegalStateException( + "controlled loss after actual Account ABORTED reply"); + }) + .when(lostReplyClient) + .abort(any(), any(), any()); + var lostReplyOwner = + CanonicalGameplayAdmissionAbortManualFactory.createUnregisteredOwner( + session.gs.dsl(), lostReplyClient); assertThatThrownBy(() -> lostReplyOwner.abortFirstNew(session.gs.transitionId(), session.jwt)) .hasMessage("controlled loss after actual Account ABORTED reply"); assertThat(session.image()).isEqualTo(before); @@ -122,7 +179,12 @@ void actualAccountAbortWithLostReplyKeepsGsProvisionalThenRecoversSameOriginalAf assertThat(accountAbort.state()).isEqualTo(State.ABORTED); session.restartAccount(); assertThat(session.abort().orphanCleanupId()).isEqualTo(accountAbort.orphanCleanupId()); - assertThat(session.client.finalizeLease(session.jwt, session.leaseBytes(), session.gs.transitionId()).state()).isEqualTo(State.ABORTED); + assertThat( + session + .client + .finalizeLease(session.jwt, session.leaseBytes(), session.gs.transitionId()) + .state()) + .isEqualTo(State.ABORTED); } } @@ -133,53 +195,83 @@ void unavailableActualReverseReadCannotInferAbortFromAbsenceOrExpiry() throws Ex session.gsServer.shutdownNow(); assertThat(session.gsServer.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); assertThatThrownBy(session::abort).isInstanceOf(RuntimeException.class); - assertThat(session.client.read(session.jwt, session.leaseBytes()).state()).isEqualTo(State.PENDING); + assertThat(session.client.read(session.jwt, session.leaseBytes()).state()) + .isEqualTo(State.PENDING); assertThat(session.image()).isEqualTo(before); long expiresAt = Long.parseLong((String) session.lease.carrier().get("expiresAt")); long remaining = expiresAt - System.currentTimeMillis(); if (remaining >= 0) Thread.sleep(remaining + 5L); assertThatThrownBy(session::abort).isInstanceOf(RuntimeException.class); - assertThat(session.client.read(session.jwt, session.leaseBytes()).state()).isEqualTo(State.PENDING); + assertThat(session.client.read(session.jwt, session.leaseBytes()).state()) + .isEqualTo(State.PENDING); assertThat(session.image()).isEqualTo(before); } } @Test - void actualConcurrentFinalizeAndAbortHaveOneAccountWinnerWithoutGsCommittedRelabelling() throws Exception { - try (var session = open(); var executor = Executors.newFixedThreadPool(2)) { + void actualConcurrentFinalizeAndAbortHaveOneAccountWinnerWithoutGsCommittedRelabelling() + throws Exception { + try (var session = open(); + var executor = Executors.newFixedThreadPool(2)) { var start = new CountDownLatch(1); - var finalize = executor.submit(() -> { - start.await(); - try { return session.client.finalizeLease(session.jwt, session.leaseBytes(), session.gs.transitionId()); } - catch (RuntimeException ambiguous) { return null; } - }); - var abort = executor.submit(() -> { - start.await(); - try { return session.abort(); } catch (RuntimeException ambiguous) { return null; } - }); + var finalize = + executor.submit( + () -> { + start.await(); + try { + return session.client.finalizeLease( + session.jwt, session.leaseBytes(), session.gs.transitionId()); + } catch (RuntimeException ambiguous) { + return null; + } + }); + var abort = + executor.submit( + () -> { + start.await(); + try { + return session.abort(); + } catch (RuntimeException ambiguous) { + return null; + } + }); start.countDown(); var finalized = finalize.get(20, TimeUnit.SECONDS); var aborted = abort.get(20, TimeUnit.SECONDS); // A missing ACK may make a committed read unavailable. The retained SQL operation still // decides one winner; no test manufactures a receipt or relabels that winner. var accountRow = session.accountFixture.dataSource; - var retained = org.jooq.impl.DSL.using(accountRow, org.jooq.SQLDialect.POSTGRES) - .fetchSingle("SELECT status FROM account_gameplay_admission_lease_operations WHERE lease_id = ?", - UUID.fromString((String) session.lease.carrier().get("leaseId"))); + var retained = + org.jooq + .impl + .DSL + .using(accountRow, org.jooq.SQLDialect.POSTGRES) + .fetchSingle( + "SELECT status FROM account_gameplay_admission_lease_operations WHERE lease_id = ?", + UUID.fromString((String) session.lease.carrier().get("leaseId"))); assertThat(retained.get("status", String.class)).isIn("ABORTED", "COMMITTED"); if ("ABORTED".equals(retained.get("status", String.class))) { - assertThat(session.abort().state()).isEqualTo(CanonicalGameplayAdmissionAbortOutcome.State.ABORTED); - assertThat(session.client.finalizeLease(session.jwt, session.leaseBytes(), session.gs.transitionId()).state()).isEqualTo(State.ABORTED); + assertThat(session.abort().state()) + .isEqualTo(CanonicalGameplayAdmissionAbortOutcome.State.ABORTED); + assertThat( + session + .client + .finalizeLease(session.jwt, session.leaseBytes(), session.gs.transitionId()) + .state()) + .isEqualTo(State.ABORTED); if (finalized != null) assertThat(finalized.state()).isEqualTo(State.ABORTED); } else { assertThat(session.gs.source().isAccountAborted()).isFalse(); - if (aborted != null) assertThat(aborted.state()).isEqualTo(CanonicalGameplayAdmissionAbortOutcome.State.ACCOUNT_COMMITTED); + if (aborted != null) + assertThat(aborted.state()) + .isEqualTo(CanonicalGameplayAdmissionAbortOutcome.State.ACCOUNT_COMMITTED); } } } @Test - void actualReverseReadRefusesWrongPeerDecisionAndChangedOriginalTupleWithoutAccountAbort() throws Exception { + void actualReverseReadRefusesWrongPeerDecisionAndChangedOriginalTupleWithoutAccountAbort() + throws Exception { try (var session = open()) { var before = session.image(); assertThat(session.reverse.read(session.gs.transitionId(), session.lease).bindingDecisionId()) @@ -187,41 +279,109 @@ void actualReverseReadRefusesWrongPeerDecisionAndChangedOriginalTupleWithoutAcco assertThatThrownBy(() -> session.reverse.read(UUID.randomUUID(), session.lease)) .isInstanceOf(RuntimeException.class); var changedCarrier = new java.util.LinkedHashMap<>(session.lease.carrier()); - changedCarrier.put("leaseFence", session.lease.leaseFence().add(java.math.BigInteger.ONE).toString()); + changedCarrier.put( + "leaseFence", session.lease.leaseFence().add(java.math.BigInteger.ONE).toString()); var changedLease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changedCarrier); assertThatThrownBy(() -> session.reverse.read(session.gs.transitionId(), changedLease)) .isInstanceOf(RuntimeException.class); - assertThatThrownBy(() -> session.client.abort(session.jwt, - changedLease.canonicalJson().getBytes(StandardCharsets.UTF_8), session.gs.transitionId())) + assertThatThrownBy( + () -> + session.client.abort( + session.jwt, + changedLease.canonicalJson().getBytes(StandardCharsets.UTF_8), + session.gs.transitionId())) .isInstanceOf(RuntimeException.class); var endpoints = new ServiceEndpointsProperties(); endpoints.setGameSessionService("127.0.0.1:" + session.gsServer.getPort()); - try (var wrongPeer = new CanonicalGameplayAdmissionDecisionReadClient(endpoints, - session.pki.clientProperties(session.pkiDirectory, session.pki.identity("wrong")), - new GrpcChannelFactory(), "test")) { + try (var wrongPeer = + new CanonicalGameplayAdmissionDecisionReadClient( + endpoints, + session.pki.clientProperties(session.pkiDirectory, session.pki.identity("wrong")), + new GrpcChannelFactory(), + "test")) { wrongPeer.init(); assertThatThrownBy(() -> wrongPeer.read(session.gs.transitionId(), session.lease)) .isInstanceOf(RuntimeException.class); } - assertThat(session.client.read(session.jwt, session.leaseBytes()).state()).isEqualTo(State.PENDING); + assertThat(session.client.read(session.jwt, session.leaseBytes()).state()) + .isEqualTo(State.PENDING); assertThat(session.image()).isEqualTo(before); // The runtime owner cannot retire the launch underneath this exact pending decision. assertThatThrownBy(session.gs::stopRuntime) .isInstanceOf(org.jooq.exception.DataAccessException.class) - .hasMessageContaining("runtime row is fenced by an unresolved lease-bound binding decision"); + .hasMessageContaining( + "runtime row is fenced by an unresolved lease-bound binding decision"); assertThat(session.image()).isEqualTo(before); - assertThat(session.abort().state()).isEqualTo(CanonicalGameplayAdmissionAbortOutcome.State.ABORTED); + assertThat(session.abort().state()) + .isEqualTo(CanonicalGameplayAdmissionAbortOutcome.State.ABORTED); + } + } + + @Test + void actualCompletedMemberAckSurvivesAccountAbortAndRetainsUnresolvedPhysicalCleanup() + throws Exception { + try (var session = open(true)) { + var acknowledgement = session.gs.repairAccountMember(); + assertThat(acknowledgement.schemaVersion()).isEqualTo(2); + assertThat(acknowledgement.transitionId()).isEqualTo(session.gs.transitionId()); + assertThat(session.gs.source().candidate().accountIndexState()) + .isEqualTo(CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED); + assertThat(session.gs.hasExactAccountMember()).isTrue(); + var originalAck = session.gs.memberAcknowledgementImage(); + var originalPhase = session.gs.accountObligationPhaseImage(); + var result = session.abort(); + assertThat(result.state()).isEqualTo(CanonicalGameplayAdmissionAbortOutcome.State.ABORTED); + assertThat(session.client.read(session.jwt, session.leaseBytes()).state()) + .isEqualTo(State.ABORTED); + assertThat( + session + .client + .finalizeLease(session.jwt, session.leaseBytes(), session.gs.transitionId()) + .state()) + .isEqualTo(State.ABORTED); + var retained = session.gs.source(); + assertThat(retained.candidate().lifecycle()) + .isEqualTo(CanonicalGameplayBindingInventoryEntry.Lifecycle.TERMINAL_UNRESOLVED); + assertThat(retained.candidate().accountIndexState()) + .isEqualTo(CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED); + assertThat(retained.reservation().lifecycle()) + .isEqualTo(CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING); + assertThat(session.gs.memberAcknowledgementImage()).isEqualTo(originalAck); + assertThat(session.gs.accountObligationPhaseImage()).isEqualTo(originalPhase); + assertThat(session.gs.hasExactAccountMember()).isTrue(); + session.restartAccount(); + assertThat(session.abort().orphanCleanupId()).isEqualTo(result.orphanCleanupId()); + assertThat(session.gs.memberAcknowledgementImage()).isEqualTo(originalAck); + assertThat(session.gs.accountObligationPhaseImage()).isEqualTo(originalPhase); + assertThat(session.gs.hasExactAccountMember()).isTrue(); + for (String statement : + new String[] { + "UPDATE game_session_canonical_account_member_repair_operation SET readback_member = 'invented' WHERE transition_id = ?", + "DELETE FROM game_session_canonical_account_member_repair_operation WHERE transition_id = ?", + "UPDATE game_session_canonical_binding_account_index_obligation SET status = 'REQUIRED' WHERE transition_id = ?" + }) { + assertThatThrownBy(() -> session.gs.dsl().execute(statement, session.gs.transitionId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(session.gs.memberAcknowledgementImage()).isEqualTo(originalAck); + assertThat(session.gs.accountObligationPhaseImage()).isEqualTo(originalPhase); + } } } private Session open() throws Exception { accountFixtures.temporaryDirectory = temporaryDirectory; - return new Session(); + return new Session(false); + } + + private Session open(boolean prepareMemberRepair) throws Exception { + accountFixtures.temporaryDirectory = temporaryDirectory; + return new Session(prepareMemberRepair); } private final class Session implements AutoCloseable { private final PhysicalRedisFixture redis = PhysicalRedisFixture.start(); - private final AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.Fixture accountFixture; + private final AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.Fixture + accountFixture; private final CanonicalGameplayAdmissionAbortCompositionFixture gs; private final LoopbackMtlsTestPki.Pki pki; private final Path pkiDirectory; @@ -233,42 +393,76 @@ private final class Session implements AutoCloseable { private AccountGameplayAdmissionLeaseClient client; private AccountGameplayAdmissionLeaseEvidence lease; - private Session() throws Exception { + private Session(boolean prepareMemberRepair) throws Exception { try { - accountFixture = accountFixtures.newFixture(redis.client()); - var issuance = accountFixture.committedCandidate.identity(); - var credential = accountFixture.responseRecoveryOwner.recoverInitialLoginResponse( - issuance.requestId(), issuance.accountId(), new CallerIdentity(issuance.callerWorkload(), issuance.callerContextId())); - jwt = new String(credential.compactJwtBytes(), StandardCharsets.US_ASCII); - gs = new CanonicalGameplayAdmissionAbortCompositionFixture(accountFixture.dataSource, - AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.admissionCandidate(accountFixture)); - pkiDirectory = Files.createTempDirectory(temporaryDirectory, "actual-abort-mtls-"); - pki = LoopbackMtlsTestPki.create(pkiDirectory, "Account GS abort test CA", - new LoopbackMtlsTestPki.IdentitySpec("account", ACCOUNT, true), - new LoopbackMtlsTestPki.IdentitySpec("gs", GS, true), - new LoopbackMtlsTestPki.IdentitySpec("gs-client", GS, false), - new LoopbackMtlsTestPki.IdentitySpec("account-client", ACCOUNT, false), - new LoopbackMtlsTestPki.IdentitySpec("wrong", "spiffe://firemud/ns/test/sa/world-management-service", false)); - gsServer = CanonicalGameplayAdmissionAbortManualFactory.createUnregisteredDecisionReadServer( - "127.0.0.1:0", pki.keyManagerFactory(pki.identity("gs")), pki.trustManagerFactory(), gs.dsl(), "test"); - gsServer.start(); - var endpoints = new ServiceEndpointsProperties(); - endpoints.setGameSessionService("127.0.0.1:" + gsServer.getPort()); - reverse = spy(new CanonicalGameplayAdmissionDecisionReadClient(endpoints, - pki.clientProperties(pkiDirectory, pki.identity("account-client")), new GrpcChannelFactory(), "test")); - // Only published-target authority is controlled. read(decisionId, originalLease) uses the - // actual mTLS receiver/repository; it is never stubbed or replaced by DTO equality. - reverse.init(); - UUID requestId = UUID.randomUUID(); - doReturn(AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.controlledPublishedTarget(gs.candidate(), gs.target(), requestId)) - .when(reverse).readPublishedRealmAdmissionOwner(any()); - verifier = new AccountGameplayAdmissionCallerVerifier(accountFixture.signerFixture.trustedJwksSource(), - accountFixture.committedIssuanceOwner, Clock.systemUTC()); - restartAccount(); - lease = client.acquire(requestId, jwt, gs.candidate(), gs.target(), gs.generation()).originalLeaseEvidence(); - gs.publish(lease); + accountFixture = accountFixtures.newFixture(redis.client()); + var issuance = accountFixture.committedCandidate.identity(); + var credential = + accountFixture.responseRecoveryOwner.recoverInitialLoginResponse( + issuance.requestId(), + issuance.accountId(), + new CallerIdentity(issuance.callerWorkload(), issuance.callerContextId())); + jwt = new String(credential.compactJwtBytes(), StandardCharsets.US_ASCII); + gs = + new CanonicalGameplayAdmissionAbortCompositionFixture( + accountFixture.dataSource, + AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.admissionCandidate( + accountFixture)); + if (prepareMemberRepair) gs.prepareMemberRepairRedis(); + pkiDirectory = Files.createTempDirectory(temporaryDirectory, "actual-abort-mtls-"); + pki = + LoopbackMtlsTestPki.create( + pkiDirectory, + "Account GS abort test CA", + new LoopbackMtlsTestPki.IdentitySpec("account", ACCOUNT, true), + new LoopbackMtlsTestPki.IdentitySpec("gs", GS, true), + new LoopbackMtlsTestPki.IdentitySpec("gs-client", GS, false), + new LoopbackMtlsTestPki.IdentitySpec("account-client", ACCOUNT, false), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong", "spiffe://firemud/ns/test/sa/world-management-service", false)); + gsServer = + CanonicalGameplayAdmissionAbortManualFactory.createUnregisteredDecisionReadServer( + "127.0.0.1:0", + pki.keyManagerFactory(pki.identity("gs")), + pki.trustManagerFactory(), + gs.dsl(), + "test"); + gsServer.start(); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameSessionService("127.0.0.1:" + gsServer.getPort()); + reverse = + spy( + new CanonicalGameplayAdmissionDecisionReadClient( + endpoints, + pki.clientProperties(pkiDirectory, pki.identity("account-client")), + new GrpcChannelFactory(), + "test")); + // Only published-target authority is controlled. read(decisionId, originalLease) uses the + // actual mTLS receiver/repository; it is never stubbed or replaced by DTO equality. + reverse.init(); + UUID requestId = UUID.randomUUID(); + doReturn( + AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest + .controlledPublishedTarget(gs.candidate(), gs.target(), requestId)) + .when(reverse) + .readPublishedRealmAdmissionOwner(any()); + verifier = + new AccountGameplayAdmissionCallerVerifier( + accountFixture.signerFixture.trustedJwksSource(), + accountFixture.committedIssuanceOwner, + Clock.systemUTC()); + restartAccount(); + lease = + client + .acquire(requestId, jwt, gs.candidate(), gs.target(), gs.generation()) + .originalLeaseEvidence(); + gs.publish(lease); } catch (Exception | Error setupFailure) { - try { close(); } catch (Exception cleanupFailure) { setupFailure.addSuppressed(cleanupFailure); } + try { + close(); + } catch (Exception cleanupFailure) { + setupFailure.addSuppressed(cleanupFailure); + } throw setupFailure; } } @@ -277,30 +471,61 @@ private void restartAccount() throws Exception { if (client != null) client.close(); if (accountServer != null) { accountServer.shutdownNow(); - if (!accountServer.awaitTermination(5, TimeUnit.SECONDS)) throw new IllegalStateException("Account server teardown timed out"); + if (!accountServer.awaitTermination(5, TimeUnit.SECONDS)) + throw new IllegalStateException("Account server teardown timed out"); } - var owner = new AccountGameplayAdmissionLeaseOwner(verifier, reverse, "test", accountFixture.dataSource); - accountServer = AccountGameplayAdmissionLeaseManualFactory.createUnregisteredServer("127.0.0.1:0", - pki.keyManagerFactory(pki.identity("account")), pki.trustManagerFactory(), owner, "test"); + var owner = + new AccountGameplayAdmissionLeaseOwner( + verifier, reverse, "test", accountFixture.dataSource); + accountServer = + AccountGameplayAdmissionLeaseManualFactory.createUnregisteredServer( + "127.0.0.1:0", + pki.keyManagerFactory(pki.identity("account")), + pki.trustManagerFactory(), + owner, + "test"); accountServer.start(); var endpoints = new ServiceEndpointsProperties(); endpoints.setAccountService("127.0.0.1:" + accountServer.getPort()); - client = new AccountGameplayAdmissionLeaseClient(endpoints, pki.clientProperties(pkiDirectory, pki.identity("gs-client")), new GrpcChannelFactory(), "test"); + client = + new AccountGameplayAdmissionLeaseClient( + endpoints, + pki.clientProperties(pkiDirectory, pki.identity("gs-client")), + new GrpcChannelFactory(), + "test"); client.init(); } + private String image() { - return java.util.List.of("game_session_canonical_binding_transition", "game_session_canonical_gameplay_binding_inventory", - "game_session_canonical_issuer_partition_reservation").stream() - .map(table -> gs.dsl().fetch("SELECT to_jsonb(t)::text AS image FROM " + table + " t ORDER BY 1").getValues("image").toString()) + return java.util.List.of( + "game_session_canonical_binding_transition", + "game_session_canonical_gameplay_binding_inventory", + "game_session_canonical_issuer_partition_reservation") + .stream() + .map( + table -> + gs.dsl() + .fetch("SELECT to_jsonb(t)::text AS image FROM " + table + " t ORDER BY 1") + .getValues("image") + .toString()) .collect(java.util.stream.Collectors.joining("\n")); } - private byte[] leaseBytes() { return lease.canonicalJson().getBytes(StandardCharsets.UTF_8); } - private CanonicalGameplayAdmissionAbortOutcome abort() { return abortWith(jwt); } + + private byte[] leaseBytes() { + return lease.canonicalJson().getBytes(StandardCharsets.UTF_8); + } + + private CanonicalGameplayAdmissionAbortOutcome abort() { + return abortWith(jwt); + } + private CanonicalGameplayAdmissionAbortOutcome abortWith(String callerToken) { return CanonicalGameplayAdmissionAbortManualFactory.createUnregisteredOwner(gs.dsl(), client) .abortFirstNew(gs.transitionId(), callerToken); } - @Override public void close() throws Exception { + + @Override + public void close() throws Exception { try { if (client != null) client.close(); if (reverse != null) reverse.close(); @@ -308,9 +533,16 @@ private CanonicalGameplayAdmissionAbortOutcome abortWith(String callerToken) { try { if (accountServer != null) accountServer.shutdownNow(); if (gsServer != null) gsServer.shutdownNow(); - if (accountServer != null) assertThat(accountServer.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + if (accountServer != null) + assertThat(accountServer.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); if (gsServer != null) assertThat(gsServer.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - } finally { try { if (gs != null) gs.close(); } finally { redis.close(); } } + } finally { + try { + if (gs != null) gs.close(); + } finally { + redis.close(); + } + } } } } diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index 6ba793a6ec..d3f7fe450c 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -162,11 +162,16 @@ val gameSessionMigrationDriverDist = } } -// Cross-service owner proof exports classes without application or Flyway resources. +// Cross-service proof exports owner classes and the exact member-repair script/descriptor. +// Application configuration, service registration and Flyway resources remain excluded. val gameSessionClassesProofJar by tasks.registering(Jar::class) { archiveClassifier.set("classes-proof") dependsOn(tasks.named("classes"), tasks.named("compileIntegrationTestJava")) from(sourceSets.main.get().output.classesDirs) + from("src/main/resources") { + include("redis/lua/game-session-account-member-repair-add.lua") + include("redis/scripts/game-session-account-member-repair-add.json") + } from(sourceSets["integrationTest"].output.classesDirs) { include("integration/net/firedevops/firemud/gamesession/repository/CanonicalHumanPublicationOwnerTestFixtures*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures*.class") diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAdmissionAbortOutcome.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAdmissionAbortOutcome.java index 19e47b7533..fd2ff4cd7b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAdmissionAbortOutcome.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAdmissionAbortOutcome.java @@ -27,8 +27,8 @@ public record CanonicalGameplayAdmissionAbortOutcome( }; if (accountState != state || accountOperation.originalLeaseEvidence().leaseKind() - != net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence - .LeaseKind.NEW_BINDING) { + != net.firedevops.firemud.common.account.admission + .AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING) { throw new IllegalArgumentException("Account result is not the exact NEW abort operation"); } if (state == State.ABORTED) { @@ -46,8 +46,7 @@ public record CanonicalGameplayAdmissionAbortOutcome( if (orphanCleanupId != null || !transitionId.equals(accountOperation.bindingDecisionId()) || accountOperation.originalAckReceipt() == null) { - throw new IllegalArgumentException( - "COMMITTED result must retain its exact ACK receipt"); + throw new IllegalArgumentException("COMMITTED result must retain its exact ACK receipt"); } } else if (orphanCleanupId != null || accountOperation.bindingDecisionId() != null diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAdmissionAbortSource.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAdmissionAbortSource.java index 68654d14f2..7df65fe1c1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAdmissionAbortSource.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAdmissionAbortSource.java @@ -19,7 +19,8 @@ public record CanonicalGameplayAdmissionAbortSource( Objects.requireNonNull(originalDecision, "originalDecision"); if (transition.expectedPriorBindingRef() != null || transition.expectedPriorBindingGeneration() != null - || originalDecision.leaseKind() != AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING + || originalDecision.leaseKind() + != AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING || originalDecision.expectedOldBindingGeneration() != null || !transition.transitionId().equals(originalDecision.bindingDecisionId()) || !transition.transitionId().equals(candidate.transitionId()) @@ -35,12 +36,12 @@ public record CanonicalGameplayAdmissionAbortSource( || !transition.candidate().equals(reservation.owner()) || !transition.inventoryRevision().equals(candidate.inventoryRevision()) || !transition.inventoryRevision().equals(reservation.inventoryRevision())) { - throw new IllegalArgumentException("Abort source does not identify one exact first-NEW owner"); + throw new IllegalArgumentException( + "Abort source does not identify one exact first-NEW owner"); } if (transition.status() == CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL) { - if (candidate.lifecycle() - != CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL + if (candidate.lifecycle() != CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL || reservation.lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RESERVED || orphanCleanupId != null) { throw new IllegalArgumentException("Provisional abort source has terminal storage state"); @@ -62,9 +63,12 @@ public record CanonicalGameplayAdmissionAbortSource( if (!candidate.identity().equals(originalDecision.candidate()) || !transition.bindingGeneration().equals(originalDecision.bindingGeneration()) || !target.canonicalTenantId().equals(candidate.identity().tenantId()) - || !target.playableStateNamespaceId().equals(candidate.identity().playableStateNamespaceId()) + || !target + .playableStateNamespaceId() + .equals(candidate.identity().playableStateNamespaceId()) || lease.leaseKind() != AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING) { - throw new IllegalArgumentException("Original decision differs from its exact first-NEW source"); + throw new IllegalArgumentException( + "Original decision differs from its exact first-NEW source"); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortManualFactory.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortManualFactory.java index 8f5b106934..ef24263cdc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortManualFactory.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortManualFactory.java @@ -38,7 +38,10 @@ public static CanonicalGameplayAdmissionAbortOwner createUnregisteredOwner( repository, guard, workloadNamespace); } - /** Creates an unstarted mutual-TLS server; production registration remains an explicit owner decision. */ + /** + * Creates an unstarted mutual-TLS server; production registration remains an explicit owner + * decision. + */ public static Server createUnregisteredDecisionReadServer( String address, KeyManagerFactory keys, @@ -65,8 +68,7 @@ public static Server createUnregisteredDecisionReadServer( GrpcRequestBytePolicy.ordinary(), CanonicalGameplayAdmissionDecisionReadGrpcCodec.MAX_REQUEST_WIRE_BYTES); factory.addService( - ServerInterceptors.interceptForward( - receiver, new GrpcPeerIdentityInterceptor(), guard)); + ServerInterceptors.interceptForward(receiver, new GrpcPeerIdentityInterceptor(), guard)); return factory.createServer(); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwner.java index d9377abc8b..f57387d056 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwner.java @@ -15,9 +15,9 @@ /** * Unregistered first-NEW Account abort composer over the retained Game Session transition owner. * - *

The original transition identifier selects the durable source. Its complete persisted lease - * is sent to Account for the exact purpose-specific abort. The remote call is always outside SQL; - * only a typed definitive Account ABORTED result can enter the guarded Game Session CAS. + *

The original transition identifier selects the durable source. Its complete persisted lease is + * sent to Account for the exact purpose-specific abort. The remote call is always outside SQL; only + * a typed definitive Account ABORTED result can enter the guarded Game Session CAS. */ public final class CanonicalGameplayAdmissionAbortOwner { private final CanonicalGameplayBindingInventoryRepository repository; @@ -48,13 +48,11 @@ public CanonicalGameplayAdmissionAbortOutcome abortFirstNew( CanonicalGameplayAdmissionAbortSource source = repository.readFirstNewAdmissionAbortSource(transitionId); - AccountGameplayAdmissionLeaseEvidence originalLease = - source.originalDecision().leaseEvidence(); + AccountGameplayAdmissionLeaseEvidence originalLease = source.originalDecision().leaseEvidence(); byte[] originalLeaseBytes = source.originalDecision().leaseEvidenceJson().getBytes(StandardCharsets.UTF_8); if (!Arrays.equals( - originalLeaseBytes, - originalLease.canonicalJson().getBytes(StandardCharsets.UTF_8))) { + originalLeaseBytes, originalLease.canonicalJson().getBytes(StandardCharsets.UTF_8))) { throw new IllegalStateException("Retained first-NEW lease bytes are not canonical"); } @@ -85,8 +83,7 @@ public CanonicalGameplayAdmissionAbortOutcome abortFirstNew( UUID cleanupId = accountOperation.orphanCleanupId(); CanonicalGameplayAdmissionAbortSource terminalSource = repository.recordFirstNewAccountAbort(source, cleanupId); - if (!terminalSource.isAccountAborted() - || !cleanupId.equals(terminalSource.orphanCleanupId())) { + if (!terminalSource.isAccountAborted() || !cleanupId.equals(terminalSource.orphanCleanupId())) { throw new IllegalStateException("Game Session did not retain Account's exact abort result"); } return new CanonicalGameplayAdmissionAbortOutcome( @@ -97,10 +94,11 @@ private static void requireExactAccountAbort( CanonicalGameplayAdmissionAbortSource source, AccountGameplayAdmissionLeaseGrpcCodec.OperationEvidence operation, UUID transitionId) { - AccountGameplayAdmissionLeaseEvidence originalLease = - source.originalDecision().leaseEvidence(); + AccountGameplayAdmissionLeaseEvidence originalLease = source.originalDecision().leaseEvidence(); if (!originalLease.hasSameIdentity(operation.originalLeaseEvidence()) - || !source.originalDecision().leaseEvidenceJson() + || !source + .originalDecision() + .leaseEvidenceJson() .equals(operation.originalLeaseEvidence().canonicalJson()) || operation.originalLeaseEvidence().leaseKind() != AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index 0dffa02300..d91cc63718 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -14,8 +14,8 @@ import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountIndexMember; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountMemberAcknowledgement; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountMemberRepairOperation; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingAccountIndexObligation; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingAccountIndexProjectionReceipt; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; @@ -471,7 +471,9 @@ CanonicalGameplayAdmissionAbortSource recordFirstNewAccountAbort( + ACCOUNT_OBLIGATION + " SET inventory_revision = ? WHERE transition_id = ?" + " AND inventory_revision = ?", - decimal(nextRevision), transitionId, decimal(priorRevision)), + decimal(nextRevision), + transitionId, + decimal(priorRevision)), "First-NEW Account abort lost its required account-index obligation"); requireOne( transaction.execute( @@ -479,7 +481,9 @@ CanonicalGameplayAdmissionAbortSource recordFirstNewAccountAbort( + ISSUER_OBLIGATION + " SET inventory_revision = ? WHERE transition_id = ?" + " AND inventory_revision = ?", - decimal(nextRevision), transitionId, decimal(priorRevision)), + decimal(nextRevision), + transitionId, + decimal(priorRevision)), "First-NEW Account abort lost its required issuer-index obligation"); requireOne( transaction.execute( @@ -487,7 +491,9 @@ CanonicalGameplayAdmissionAbortSource recordFirstNewAccountAbort( + REGION_OBLIGATION + " SET inventory_revision = ? WHERE transition_id = ?" + " AND inventory_revision = ?", - decimal(nextRevision), transitionId, decimal(priorRevision)), + decimal(nextRevision), + transitionId, + decimal(priorRevision)), "First-NEW Account abort lost its required region-bridge obligation"); requireOne( transaction.execute( @@ -1291,8 +1297,7 @@ private static CanonicalGameplayAdmissionDecision toAdmissionDecision( Record row, CanonicalGameplayBindingTransitionSnapshot transition, CanonicalGameplayBindingInventoryEntry candidate) { - if (row == null - || !transition.transitionId().equals(row.get("transition_id", UUID.class))) { + if (row == null || !transition.transitionId().equals(row.get("transition_id", UUID.class))) { throw conflict("Durable binding decision row is missing or changed"); } String canonicalEvidence = row.get("admission_lease_evidence", String.class); @@ -1576,8 +1581,7 @@ private static CanonicalGameplayAdmissionAbortSource loadFirstNewAdmissionAbortS || transitionSnapshot.expectedPriorBindingGeneration() != null) { throw conflict("Admission abort owner accepts first-NEW transitions only"); } - if (transitionSnapshot.status() - != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL + if (transitionSnapshot.status() != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL && transitionSnapshot.status() != CanonicalGameplayBindingTransitionSnapshot.Status.ABORTED) { throw conflict("First-NEW admission abort source is not provisional or definitively aborted"); @@ -1593,7 +1597,8 @@ private static CanonicalGameplayAdmissionAbortSource loadFirstNewAdmissionAbortS candidate = provisional.candidate(); reservation = provisional.candidateReservation(); } else { - requireRetainedFirstNewAbortObligations(transaction, transitionId, transitionSnapshot); + requireRetainedFirstNewAbortObligations( + transaction, transitionId, transitionSnapshot, candidate); } AccountGameplayAdmissionLeaseEvidence lease; @@ -1639,7 +1644,8 @@ private static CanonicalGameplayAdmissionAbortSource loadFirstNewAdmissionAbortS private static void requireRetainedFirstNewAbortObligations( DSLContext transaction, UUID transitionId, - CanonicalGameplayBindingTransitionSnapshot transition) { + CanonicalGameplayBindingTransitionSnapshot transition, + CanonicalGameplayBindingInventoryEntry retainedCandidate) { BigInteger revision = transition.inventoryRevision(); byte[] bindingRef = transition.bindingRef().bytes(); CanonicalGameplayBindingIdentity candidate = transition.candidate(); @@ -1656,19 +1662,19 @@ private static void requireRetainedFirstNewAbortObligations( bindingRef); Record region = transaction.fetchOne( - "SELECT * FROM " + REGION_OBLIGATION + " WHERE transition_id = ?", - transitionId); + "SELECT * FROM " + REGION_OBLIGATION + " WHERE transition_id = ?", transitionId); if (account == null || issuer == null || region == null || !"ADD_OR_RETAIN".equals(account.get("action", String.class)) || !Arrays.equals(bindingRef, account.get("binding_ref", byte[].class)) || !"BEFORE_FINAL_CAS".equals(account.get("execution_phase", String.class)) - || !"REQUIRED".equals(account.get("status", String.class)) - || !transition.bindingGeneration() - .equals(readBigInteger(account, "binding_generation")) + || !("REQUIRED".equals(account.get("status", String.class)) + || "ACKNOWLEDGED".equals(account.get("status", String.class))) + || !transition.bindingGeneration().equals(readBigInteger(account, "binding_generation")) || nullableBigInteger(account, "expected_prior_generation") != null - || !transition.candidateAccountIndexFence() + || !transition + .candidateAccountIndexFence() .equals(account.get("account_index_fence", UUID.class)) || !candidate.accountId().equals(account.get("account_id", UUID.class)) || !candidate.tenantId().equals(account.get("tenant_id", UUID.class)) @@ -1676,8 +1682,7 @@ private static void requireRetainedFirstNewAbortObligations( || !"REQUIRED".equals(issuer.get("status", String.class)) || !Arrays.equals(bindingRef, issuer.get("binding_ref", byte[].class)) || !transition.issuerReservationId().equals(issuer.get("reservation_id", UUID.class)) - || !transition.bindingGeneration() - .equals(readBigInteger(issuer, "binding_generation")) + || !transition.bindingGeneration().equals(readBigInteger(issuer, "binding_generation")) || !revision.equals(readBigInteger(issuer, "inventory_revision")) || !"REQUIRED".equals(region.get("status", String.class)) || !Arrays.equals(bindingRef, region.get("binding_ref", byte[].class)) @@ -1692,19 +1697,48 @@ private static void requireRetainedFirstNewAbortObligations( || !candidate.regionEpoch().equals(readBigInteger(region, "region_epoch")) || !revision.equals(readBigInteger(region, "inventory_revision")) || transaction.fetchCount( - "SELECT transition_id FROM " - + ACCOUNT_OBLIGATION - + " WHERE transition_id = ?", - transitionId) + DSL.table(ACCOUNT_OBLIGATION), + DSL.field("transition_id", UUID.class).eq(transitionId)) != 1 || transaction.fetchCount( - "SELECT transition_id FROM " - + ISSUER_OBLIGATION - + " WHERE transition_id = ?", - transitionId) + DSL.table(ISSUER_OBLIGATION), + DSL.field("transition_id", UUID.class).eq(transitionId)) != 1) { throw conflict("Aborted first-NEW source lost a required retained index obligation"); } + if ("ACKNOWLEDGED".equals(account.get("status", String.class))) { + // This is historical ADD/readback evidence, never account-member removal or cleanup proof. + Record repair = findMemberRepairOperation(transaction, transitionId, false); + if (repair == null) throw conflict("Retained abort lost its completed account-member repair"); + var acknowledgement = toMemberAcknowledgement(repair); + var operation = acknowledgement.operation(); + var obligation = loadAccountIndexObligations(transaction, transitionId, false).getFirst(); + requireMemberRepairObligationCurrent(operation, retainedCandidate, obligation, true); + BigInteger completedRevision = readBigInteger(repair, "completed_inventory_revision"); + if (!CanonicalGameplayAccountIndexMember.of(retainedCandidate) + .value() + .equals(operation.member()) + || completedRevision.compareTo(operation.inventorySnapshotRevision()) <= 0 + || completedRevision.compareTo(revision) >= 0 + || (operation.originalObligation().projectionState() + == CanonicalGameplayBindingAccountIndexObligation.ProjectionState.REQUIRED + && !completedRevision.equals(obligation.projectionInventoryRevision()))) { + throw conflict("Retained abort changed the original completed account-member readback"); + } + Record control = + transaction.fetchOne( + "SELECT * FROM game_session_canonical_account_coverage_control WHERE account_id = ?", + operation.accountId()); + if (control == null + || !"NO_ACTIVE_ACCOUNT_WIDE_FLOW".equals(control.get("state", String.class)) + || !readBigInteger(control, "last_operation_fence") + .equals(operation.accountControlEpoch())) { + throw conflict("Retained account-member acknowledgement has a different control epoch"); + } + } else if (retainedCandidate.accountIndexState() + != CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED) { + throw conflict("Unacknowledged retained abort has contradictory account-index state"); + } } private static void requireSameFirstNewAdmissionAbortSource( @@ -1718,19 +1752,26 @@ private static void requireSameFirstNewAdmissionAbortSource( || !expectedTransition.bindingRef().equals(currentTransition.bindingRef()) || !expectedTransition.issuerReservationId().equals(currentTransition.issuerReservationId()) || !expectedTransition.reservationFence().equals(currentTransition.reservationFence()) - || !expectedTransition.candidateAccountIndexFence() + || !expectedTransition + .candidateAccountIndexFence() .equals(currentTransition.candidateAccountIndexFence()) || expectedTransition.expectedPriorBindingRef() != null || expectedTransition.expectedPriorBindingGeneration() != null - || !expectedTransition.accountCoverageEvidence() + || !expectedTransition + .accountCoverageEvidence() .equals(currentTransition.accountCoverageEvidence()) || !expected.candidate().identity().equals(current.candidate().identity()) || !expected.candidate().bindingRef().equals(current.candidate().bindingRef()) || !expected.candidate().accountIndexFence().equals(current.candidate().accountIndexFence()) || !expected.reservation().reservationId().equals(current.reservation().reservationId()) - || !expected.reservation().reservationFence().equals(current.reservation().reservationFence()) - || !expected.originalDecision().leaseEvidence().hasSameIdentity( - current.originalDecision().leaseEvidence())) { + || !expected + .reservation() + .reservationFence() + .equals(current.reservation().reservationFence()) + || !expected + .originalDecision() + .leaseEvidence() + .hasSameIdentity(current.originalDecision().leaseEvidence())) { throw conflict("First-NEW admission abort source drifted before its guarded CAS"); } if (expected.isAccountAborted()) { @@ -1748,8 +1789,8 @@ private static void requireSameFirstNewAdmissionAbortSource( } } else if (currentTransition.status() != CanonicalGameplayBindingTransitionSnapshot.Status.ABORTED - || currentTransition.inventoryRevision() - .compareTo(expectedTransition.inventoryRevision()) <= 0 + || currentTransition.inventoryRevision().compareTo(expectedTransition.inventoryRevision()) + <= 0 || current.candidate().lifecycle() != CanonicalGameplayBindingInventoryEntry.Lifecycle.TERMINAL_UNRESOLVED || !current.candidate().inventoryRevision().equals(currentTransition.inventoryRevision()) @@ -1760,23 +1801,37 @@ private static void requireSameFirstNewAdmissionAbortSource( || !expected.candidate().bindingRef().equals(current.candidate().bindingRef()) || !expected.candidate().bindingGeneration().equals(current.candidate().bindingGeneration()) || !expected.candidate().accountIndexFence().equals(current.candidate().accountIndexFence()) - || !expected.candidate().issuerReservationId() + || !expected + .candidate() + .issuerReservationId() .equals(current.candidate().issuerReservationId()) || !expected.candidate().transitionId().equals(current.candidate().transitionId()) || expected.candidate().accountIndexState() != current.candidate().accountIndexState() || expected.candidate().issuerIndexState() != current.candidate().issuerIndexState() || !expected.reservation().reservationId().equals(current.reservation().reservationId()) || !expected.reservation().owner().equals(current.reservation().owner()) - || !expected.reservation().bindingGeneration().equals(current.reservation().bindingGeneration()) + || !expected + .reservation() + .bindingGeneration() + .equals(current.reservation().bindingGeneration()) || !expected.reservation().transitionId().equals(current.reservation().transitionId()) || !expected.reservation().partitionId().equals(current.reservation().partitionId()) - || !expected.reservation().reservationFence().equals(current.reservation().reservationFence()) - || !expected.reservation().issuerCoverageOperationId() + || !expected + .reservation() + .reservationFence() + .equals(current.reservation().reservationFence()) + || !expected + .reservation() + .issuerCoverageOperationId() .equals(current.reservation().issuerCoverageOperationId()) - || !expected.reservation().issuerCoverageOperationFence() + || !expected + .reservation() + .issuerCoverageOperationFence() .equals(current.reservation().issuerCoverageOperationFence()) || !expected.reservation().coverageFence().equals(current.reservation().coverageFence()) - || !expected.reservation().inventorySnapshotRevision() + || !expected + .reservation() + .inventorySnapshotRevision() .equals(current.reservation().inventorySnapshotRevision())) { throw conflict("Concurrent first-NEW abort did not preserve the exact retained source"); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java index 5dbd6843b3..757dc82e74 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java @@ -51,7 +51,12 @@ final class CanonicalGameplayIssuerLayoutBootstrapRepository { + " to_jsonb(i)::text AS source_row_json FROM game_session_canonical_gameplay_binding_inventory i" + " WHERE i.inventory_revision <= ?" + " UNION ALL SELECT 'TRANSITION' AS source_kind, t.transition_id::text AS source_key," - + " t.inventory_revision AS source_revision, to_jsonb(t)::text AS source_row_json" + + " t.inventory_revision AS source_revision," + // Preserve frozen pre-V1035 transition bytes for the absence-equivalent new NULL field. + // A definitive abort UUID remains part of the full captured source. + + " CASE WHEN to_jsonb(t)->'admission_orphan_cleanup_id' = 'null'::jsonb" + + " THEN (to_jsonb(t) - 'admission_orphan_cleanup_id')::text" + + " ELSE to_jsonb(t)::text END AS source_row_json" + " FROM game_session_canonical_binding_transition t WHERE t.inventory_revision <= ?" + " UNION ALL SELECT CASE WHEN r.issuer_id = ? THEN 'RESERVATION'" + " ELSE 'UNRESOLVED_LEGACY_RESERVATION' END AS source_kind," diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java index 8c1703afcb..415d194e7c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java @@ -73,7 +73,12 @@ final class CanonicalGameplayIssuerPartitionBuildRepository { + " to_jsonb(i)::text AS source_row_json FROM game_session_canonical_gameplay_binding_inventory i" + " WHERE i.inventory_revision <= ?" + " UNION ALL SELECT 'TRANSITION' AS source_kind, t.transition_id::text AS source_key," - + " t.inventory_revision AS source_revision, to_jsonb(t)::text AS source_row_json" + + " t.inventory_revision AS source_revision," + // Preserve frozen pre-V1035 transition bytes for the absence-equivalent new NULL field. + // A definitive abort UUID remains part of the full captured source. + + " CASE WHEN to_jsonb(t)->'admission_orphan_cleanup_id' = 'null'::jsonb" + + " THEN (to_jsonb(t) - 'admission_orphan_cleanup_id')::text" + + " ELSE to_jsonb(t)::text END AS source_row_json" + " FROM game_session_canonical_binding_transition t WHERE t.inventory_revision <= ?" + " UNION ALL SELECT CASE WHEN r.issuer_id = ? THEN 'RESERVATION'" + " ELSE 'UNRESOLVED_LEGACY_RESERVATION' END AS source_kind," diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java index 16a5df70eb..0cbdca4e19 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java @@ -76,8 +76,8 @@ public void getCanonicalGameplayAdmissionDecision( String expectedCaller = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"; if (lease.leaseKind() - != net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence - .LeaseKind.NEW_BINDING + != net.firedevops.firemud.common.account.admission + .AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING || !workloadNamespace.equals(targetNamespace) || !expectedCaller.equals(callerWorkload)) { fail(observer, Status.PERMISSION_DENIED); diff --git a/services/game-session-service/src/main/resources/db/migration/V1035__canonical_gameplay_first_new_abort_source.sql b/services/game-session-service/src/main/resources/db/migration/V1035__canonical_gameplay_first_new_abort_source.sql index e0bff1b33c..28d8557845 100644 --- a/services/game-session-service/src/main/resources/db/migration/V1035__canonical_gameplay_first_new_abort_source.sql +++ b/services/game-session-service/src/main/resources/db/migration/V1035__canonical_gameplay_first_new_abort_source.sql @@ -367,6 +367,28 @@ RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN + IF OLD.lifecycle = 'RELEASE_PENDING' AND EXISTS ( + SELECT 1 FROM game_session_canonical_binding_transition transition + WHERE transition.transition_id = OLD.transition_id + AND transition.issuer_reservation_id = OLD.reservation_id + AND transition.status = 'ABORTED' + AND transition.admission_orphan_cleanup_id IS NOT NULL + ) THEN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Retained first-NEW abort reservation requires qualified release proof' + USING ERRCODE = '23514', CONSTRAINT = 'gs_first_new_abort_reservation_retained'; + END IF; + IF (to_jsonb(NEW) - 'inventory_revision') IS DISTINCT FROM (to_jsonb(OLD) - 'inventory_revision') + OR NEW.inventory_revision < OLD.inventory_revision THEN + RAISE EXCEPTION 'Retained first-NEW abort reservation is immutable without qualified release proof' + USING ERRCODE = '23514', CONSTRAINT = 'gs_first_new_abort_reservation_retained'; + END IF; + RETURN NEW; + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + IF OLD.lifecycle = 'RESERVED' AND NEW.lifecycle = 'RELEASE_PENDING' THEN IF NEW.inventory_revision <= OLD.inventory_revision OR ROW( @@ -451,7 +473,7 @@ END; $$; CREATE TRIGGER game_session_first_new_abort_reservation_release - BEFORE UPDATE ON game_session_canonical_issuer_partition_reservation + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_partition_reservation FOR EACH ROW EXECUTE FUNCTION require_first_new_abort_reservation_release(); @@ -460,6 +482,28 @@ RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN + IF OLD.lifecycle = 'TERMINAL_UNRESOLVED' AND EXISTS ( + SELECT 1 FROM game_session_canonical_binding_transition transition + WHERE transition.transition_id = OLD.transition_id + AND transition.candidate_binding_ref = OLD.binding_ref + AND transition.status = 'ABORTED' + AND transition.admission_orphan_cleanup_id IS NOT NULL + ) THEN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Retained first-NEW abort candidate requires qualified cleanup proof' + USING ERRCODE = '23514', CONSTRAINT = 'gs_first_new_abort_candidate_retained'; + END IF; + IF (to_jsonb(NEW) - 'inventory_revision') IS DISTINCT FROM (to_jsonb(OLD) - 'inventory_revision') + OR NEW.inventory_revision < OLD.inventory_revision THEN + RAISE EXCEPTION 'Retained first-NEW abort candidate is immutable without qualified cleanup proof' + USING ERRCODE = '23514', CONSTRAINT = 'gs_first_new_abort_candidate_retained'; + END IF; + RETURN NEW; + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + IF OLD.lifecycle = 'PROVISIONAL' AND NEW.lifecycle = 'TERMINAL_UNRESOLVED' THEN IF NEW.inventory_revision <= OLD.inventory_revision OR ROW( @@ -538,7 +582,7 @@ END; $$; CREATE TRIGGER game_session_first_new_abort_candidate_retention - BEFORE UPDATE ON game_session_canonical_gameplay_binding_inventory + BEFORE UPDATE OR DELETE ON game_session_canonical_gameplay_binding_inventory FOR EACH ROW EXECUTE FUNCTION require_first_new_abort_candidate_retention(); @@ -546,7 +590,17 @@ CREATE FUNCTION require_first_new_abort_source_complete() RETURNS trigger LANGUAGE plpgsql AS $$ +DECLARE + affected_transition_id uuid; BEGIN + IF TG_OP = 'DELETE' THEN affected_transition_id := OLD.transition_id; + ELSE affected_transition_id := NEW.transition_id; + END IF; + IF NOT EXISTS (SELECT 1 FROM game_session_canonical_binding_transition + WHERE transition_id = affected_transition_id AND status = 'ABORTED' + AND admission_orphan_cleanup_id IS NOT NULL) THEN + RETURN NULL; + END IF; IF NOT EXISTS ( SELECT 1 FROM game_session_canonical_binding_transition transition @@ -562,7 +616,7 @@ BEGIN AND issuer_obligation.binding_ref = transition.candidate_binding_ref JOIN game_session_canonical_binding_region_bridge_obligation region_obligation ON region_obligation.transition_id = transition.transition_id - WHERE transition.transition_id = NEW.transition_id + WHERE transition.transition_id = affected_transition_id AND transition.status = 'ABORTED' AND transition.admission_lease_id IS NOT NULL AND transition.admission_lease_kind = 'NEW_BINDING' @@ -613,7 +667,47 @@ BEGIN AND account_obligation.expected_prior_generation IS NULL AND account_obligation.account_index_fence = candidate.account_index_fence AND account_obligation.execution_phase = 'BEFORE_FINAL_CAS' - AND account_obligation.status = 'REQUIRED' + AND ( + (account_obligation.status = 'REQUIRED' AND candidate.account_index_state = 'REPAIR_REQUIRED') + OR (account_obligation.status = 'ACKNOWLEDGED' + AND candidate.account_index_state = 'ACKNOWLEDGED' + AND account_obligation.projection_state = 'PRESENT_AWAITING_COVERAGE' + AND EXISTS ( + SELECT 1 FROM game_session_canonical_account_member_repair_operation repair + JOIN game_session_canonical_account_coverage_control control + ON control.account_id = repair.account_id + WHERE repair.transition_id = transition.transition_id + AND repair.obligation_ordinal = 0 + AND repair.status = 'ACKNOWLEDGED' + AND repair.binding_ref = candidate.binding_ref + AND repair.account_id = candidate.account_id + AND repair.tenant_id = candidate.tenant_id + AND repair.binding_generation = candidate.binding_generation + AND repair.account_index_fence = candidate.account_index_fence + AND repair.original_action = 'ADD_OR_RETAIN' + AND repair.original_expected_prior_generation IS NULL + AND repair.original_execution_phase = 'BEFORE_FINAL_CAS' + AND repair.original_status = 'REQUIRED' + AND repair.desired_action = 'ADD_OR_RETAIN' + AND repair.account_control_state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW' + AND control.state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW' + AND control.last_operation_fence = repair.account_control_epoch + AND repair.coverage_generation > repair.inventory_snapshot_revision + AND repair.completed_inventory_revision > repair.inventory_snapshot_revision + AND repair.completed_inventory_revision < transition.inventory_revision + AND repair.readback_state = 'PRESENT' + AND repair.readback_member = repair.member + AND repair.member = account_obligation.projection_member + AND repair.member = 'accountIndexMember/v1:' + || rtrim(translate(replace(encode(candidate.binding_ref, 'base64'), E'\n', ''), '+/', '-_'), '=') + || ':' || candidate.binding_generation::text || ':' || candidate.account_index_fence::text + AND ((repair.original_projection_state = 'REQUIRED' + AND account_obligation.projection_inventory_revision = repair.completed_inventory_revision) + OR (repair.original_projection_state = 'PRESENT_AWAITING_COVERAGE' + AND repair.original_projection_member = repair.member + AND account_obligation.projection_inventory_revision = repair.original_projection_inventory_revision)) + )) + ) AND (SELECT count(*) FROM game_session_canonical_binding_account_index_obligation extra_account WHERE extra_account.transition_id = transition.transition_id) = 1 @@ -657,4 +751,33 @@ CREATE CONSTRAINT TRIGGER game_session_first_new_abort_source_atomic WHEN (NEW.status = 'ABORTED' AND NEW.admission_lease_id IS NOT NULL) EXECUTE FUNCTION require_first_new_abort_source_complete(); + +-- Retain the actual completed member-repair history. This does not authorize member removal. +CREATE FUNCTION retain_first_new_abort_member_repair_history() +RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM game_session_canonical_binding_transition transition + WHERE transition.transition_id = OLD.transition_id AND transition.status = 'ABORTED' + AND transition.admission_orphan_cleanup_id IS NOT NULL) THEN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Retained abort account-member repair history is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'gs_first_new_abort_member_history_retained'; + END IF; + IF to_jsonb(NEW) IS DISTINCT FROM to_jsonb(OLD) THEN + RAISE EXCEPTION 'Retained abort account-member repair history is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'gs_first_new_abort_member_history_retained'; + END IF; + END IF; + IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER game_session_first_new_abort_member_history + BEFORE UPDATE OR DELETE ON game_session_canonical_account_member_repair_operation + FOR EACH ROW EXECUTE FUNCTION retain_first_new_abort_member_repair_history(); +CREATE CONSTRAINT TRIGGER game_session_first_new_abort_account_phase_atomic + AFTER UPDATE OR DELETE ON game_session_canonical_binding_account_index_obligation + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION require_first_new_abort_source_complete(); + -- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java index 96854568b9..f831d260f3 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java @@ -1,30 +1,47 @@ package net.firedevops.firemud.gamesession.repository; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import io.lettuce.core.protocol.ProtocolVersion; import java.math.BigInteger; import java.nio.file.Path; -import java.util.UUID; +import java.time.Duration; import java.util.EnumSet; import java.util.List; +import java.util.Objects; +import java.util.UUID; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountMemberAcknowledgement; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventorySnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; 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; import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.GenericContainer; /** * Actual GS durable decision owner for the Account/GS abort composition test. Launch producers, @@ -34,42 +51,139 @@ */ public final class CanonicalGameplayAdmissionAbortCompositionFixture implements AutoCloseable { private final DriverManagerDataSource dataSource; - private final String schema = "gs_abort_composition_" + UUID.randomUUID().toString().replace("-", ""); + private final String schema = + "gs_abort_composition_" + UUID.randomUUID().toString().replace("-", ""); private final CanonicalGameplayBindingInventoryRepository repository; private final CanonicalPlayableTarget target; private final CanonicalGameplayBindingIdentity identity; private final UUID transitionId = UUID.randomUUID(); private final BigInteger generation; private final DSLContext dsl; + private GenericContainer memberRedis; + private RedisClient memberRedisApplication; + private CanonicalGameplayAccountMemberAcknowledgement memberAcknowledgement; public CanonicalGameplayAdmissionAbortCompositionFixture( DriverManagerDataSource accountDataSource, Candidate accountCandidate) { dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); - dataSource.setUrl(accountDataSource.getUrl().replaceAll("currentSchema=[^&]+", "currentSchema=" + schema)); + dataSource.setUrl( + Objects.requireNonNull(accountDataSource.getUrl(), "Account fixture JDBC URL") + .replaceAll("currentSchema=[^&]+", "currentSchema=" + schema)); dataSource.setUsername(accountDataSource.getUsername()); dataSource.setPassword(accountDataSource.getPassword()); - Flyway.configure().dataSource(dataSource).schemas(schema).defaultSchema(schema) + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) .placeholders(java.util.Map.of("serviceSchema", schema)) - .locations("filesystem:" + Path.of("../game-session-service/src/main/resources/db/migration").toAbsolutePath().normalize()) - .load().migrate(); + .locations( + "filesystem:" + + Path.of("../game-session-service/src/main/resources/db/migration") + .toAbsolutePath() + .normalize()) + .load() + .migrate(); dsl = DSL.using(dataSource, SQLDialect.POSTGRES); - var runtime = CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource, accountCandidate.tenantId(), "test"); - target = runtime.playableTarget(); - identity = new CanonicalGameplayBindingIdentity( - accountCandidate.accountId(), accountCandidate.tenantId(), target.playableStateNamespaceId(), - accountCandidate.characterId(), target.playableStateScope(), target.canonicalGameInstanceId(), - target.gameInstanceId(), accountCandidate.sessionId().toString(), accountCandidate.regionId(), - accountCandidate.regionEpoch(), accountCandidate.issuerId(), accountCandidate.issuerAuthGeneration(), - accountCandidate.issuerIndexLayoutVersion(), accountCandidate.issuerIndexPartitionCount(), - accountCandidate.issuerIndexPartitionCapacity()); + var runtime = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( + dataSource, accountCandidate.tenantId(), "test"); + target = sealControlledInitialTarget(runtime.playableTarget()); + identity = + new CanonicalGameplayBindingIdentity( + accountCandidate.accountId(), + accountCandidate.tenantId(), + target.playableStateNamespaceId(), + accountCandidate.characterId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.gameInstanceId(), + accountCandidate.sessionId().toString(), + accountCandidate.regionId(), + accountCandidate.regionEpoch(), + accountCandidate.issuerId(), + accountCandidate.issuerAuthGeneration(), + accountCandidate.issuerIndexLayoutVersion(), + accountCandidate.issuerIndexPartitionCount(), + accountCandidate.issuerIndexPartitionCapacity()); establishActualLegacyDisposition(dsl); repository = new CanonicalGameplayBindingInventoryRepository(dsl); - repository.prepare(new CanonicalGameplayBindingTransitionRequest( - transitionId, UUID.randomUUID(), identity, - new CanonicalIssuerReservationFenceEvidence(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), - BigInteger.ONE, BigInteger.ONE, BigInteger.ONE), null, null)); - generation = repository.readProvisionalCasEvidence(transitionId).transition().bindingGeneration(); + repository.prepare( + new CanonicalGameplayBindingTransitionRequest( + transitionId, + UUID.randomUUID(), + identity, + new CanonicalIssuerReservationFenceEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + BigInteger.ONE, + BigInteger.ONE, + BigInteger.ONE), + null, + null)); + generation = + repository.readProvisionalCasEvidence(transitionId).transition().bindingGeneration(); + } + + /** + * Tuple-consistent controlled upstream target; it does not claim a live initial-admission + * producer. + */ + private static CanonicalPlayableTarget sealControlledInitialTarget( + CanonicalPlayableTarget original) { + var request = + new WorldCanonicalInitialAdmissionHold.Request( + original.targetNamespace(), + original.canonicalTenantId(), + original.worldSlug(), + original.realmId(), + original.playableStateNamespaceId(), + original.playableStateScope(), + original.canonicalGameInstanceId(), + original.canonicalVersionId(), + original.activeWorldEpoch(), + original.initialAdmissionRequestId(), + original.initialAdmissionRequestDigest(), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + original.catalogRevision(), + null); + var hold = + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + request, original.holdId(), original.holdFence()); + return new CanonicalPlayableTarget( + original.targetNamespace(), + original.tenantSlug(), + original.canonicalTenantId(), + original.worldSlug(), + original.worldDisplayName(), + original.realmId(), + original.realmSlug(), + original.realmDisplayName(), + original.gameSessionTenantId(), + original.gameInstanceId(), + original.playableStateNamespaceId(), + original.playableStateScope(), + original.canonicalGameInstanceId(), + original.canonicalVersionId(), + original.runtimeVersionId(), + original.catalogRevision(), + original.pointerVersion(), + original.admissionPointerSnapshotDigest(), + original.activeWorldEpoch(), + original.initialAdmissionRequestId(), + original.initialAdmissionRequestDigest(), + original.initialAdmissionOriginKind(), + original.expectedPriorPointerVersion(), + original.holdId(), + original.holdFence(), + hold.holdBindingDigest(), + original.auditEventId(), + original.ownerProofDigest(), + original.ownerProofOutcome(), + original.positiveDurableAbort(), + original.ownerProofTerminalAt(), + original.characterCreationPolicy()); } /** Actual migration state machine over explicitly controlled empty-cohort collaborators. */ @@ -78,89 +192,280 @@ private static void establishActualLegacyDisposition(DSLContext dsl) { var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); UUID cohortId = UUID.randomUUID(); UUID writerFence = UUID.randomUUID(); - var storageIdentity = new CanonicalGameplayLegacyMigrationStorageIdentity( - "controlled-cluster-uid", "controlled-namespace-uid", "controlled-producer-pod-uid", - "controlled-container-id", "controlled-node-uid", "123456789", 42L, - "controlled-postgres-volume-uid", "controlled-redis-run-id", "controlled-redis-volume-uid"); - var fencedCohort = new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { - @Override public UUID cohortId() { return cohortId; } - @Override public UUID legacyWriterFence() { return writerFence; } - @Override public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { - return storageIdentity; - } - @Override public void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity expected) { - if (!storageIdentity.equals(expected)) { - throw new IllegalStateException("Controlled test storage identity changed"); - } - } - }; - var operation = new CanonicalGameplayLegacyMigrationOwner( - migration, inventory, () -> fencedCohort, - ignored -> new CanonicalGameplayLegacyMigrationSourceSnapshot( - EnumSet.of(Family.TENANT_SESSION_CONTEXT, Family.SESSION_ALIAS_CONTEXT, - Family.GAMEPLAY_IDENTITY_CONTEXT, Family.GAMEPLAY_NAME_CONTEXT, - Family.MOVEMENT_EFFECT, Family.DURABLE_EFFECT), List.of()), - new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { - @Override public void rebuildExact(CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, - CanonicalGameplayLegacyMigrationSourceSnapshot source, - CanonicalGameplayBindingInventorySnapshot canonical) { - requireEmptyCanonical(canonical); + var storageIdentity = + new CanonicalGameplayLegacyMigrationStorageIdentity( + "controlled-cluster-uid", + "controlled-namespace-uid", + "controlled-producer-pod-uid", + "controlled-container-id", + "controlled-node-uid", + "123456789", + 42L, + "controlled-postgres-volume-uid", + "controlled-redis-run-id", + "controlled-redis-volume-uid"); + var fencedCohort = + new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { + @Override + public UUID cohortId() { + return cohortId; + } + + @Override + public UUID legacyWriterFence() { + return writerFence; } - @Override public CanonicalGameplayLegacyMigrationReadback readBackExact( - CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, - CanonicalGameplayBindingInventorySnapshot canonical) { - requireEmptyCanonical(canonical); - return new CanonicalGameplayLegacyMigrationReadback(List.of(), List.of(), List.of(), List.of()); + + @Override + public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + return storageIdentity; } - }).migrate(); + + @Override + public void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity expected) { + if (!storageIdentity.equals(expected)) { + throw new IllegalStateException("Controlled test storage identity changed"); + } + } + }; + var operation = + new CanonicalGameplayLegacyMigrationOwner( + migration, + inventory, + () -> fencedCohort, + ignored -> + new CanonicalGameplayLegacyMigrationSourceSnapshot( + EnumSet.of( + Family.TENANT_SESSION_CONTEXT, + Family.SESSION_ALIAS_CONTEXT, + Family.GAMEPLAY_IDENTITY_CONTEXT, + Family.GAMEPLAY_NAME_CONTEXT, + Family.MOVEMENT_EFFECT, + Family.DURABLE_EFFECT), + List.of()), + new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { + @Override + public void rebuildExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + CanonicalGameplayLegacyMigrationSourceSnapshot source, + CanonicalGameplayBindingInventorySnapshot canonical) { + requireEmptyCanonical(canonical); + } + + @Override + public CanonicalGameplayLegacyMigrationReadback readBackExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + CanonicalGameplayBindingInventorySnapshot canonical) { + requireEmptyCanonical(canonical); + return new CanonicalGameplayLegacyMigrationReadback( + List.of(), List.of(), List.of(), List.of()); + } + }) + .migrate(); if (operation.state() != CanonicalGameplayLegacyMigrationOperation.State.VERIFIED) { throw new IllegalStateException("Actual legacy migration owner did not publish VERIFIED"); } } private static void requireEmptyCanonical(CanonicalGameplayBindingInventorySnapshot canonical) { - if (!canonical.bindings().isEmpty() || !canonical.reservations().isEmpty() - || !canonical.transitions().isEmpty() || !canonical.accountIndexObligations().isEmpty() - || !canonical.issuerIndexObligations().isEmpty() || !canonical.regionBridgeObligations().isEmpty()) { + if (!canonical.bindings().isEmpty() + || !canonical.reservations().isEmpty() + || !canonical.transitions().isEmpty() + || !canonical.accountIndexObligations().isEmpty() + || !canonical.issuerIndexObligations().isEmpty() + || !canonical.regionBridgeObligations().isEmpty()) { throw new IllegalStateException("Controlled empty-cohort collaborator found canonical state"); } } public Candidate candidate() { - return new Candidate(identity.accountId(), identity.tenantId(), identity.playableStateNamespaceId(), - identity.characterId(), identity.playableStateScope(), identity.gameInstanceId(), identity.runtimeGameInstanceId(), - UUID.fromString(identity.sessionId()), identity.regionId(), identity.regionEpoch(), identity.issuerId(), - identity.issuerAuthGeneration(), identity.issuerIndexLayoutVersion(), identity.issuerIndexPartitionCount(), + return new Candidate( + identity.accountId(), + identity.tenantId(), + identity.playableStateNamespaceId(), + identity.characterId(), + identity.playableStateScope(), + identity.gameInstanceId(), + identity.runtimeGameInstanceId(), + UUID.fromString(identity.sessionId()), + identity.regionId(), + identity.regionEpoch(), + identity.issuerId(), + identity.issuerAuthGeneration(), + identity.issuerIndexLayoutVersion(), + identity.issuerIndexPartitionCount(), identity.issuerIndexPartitionCapacity()); } public Target target() { - return new Target(target.targetNamespace(), target.tenantSlug(), target.canonicalTenantId(), target.worldSlug(), - target.worldDisplayName(), target.realmId(), target.realmSlug(), target.realmDisplayName(), target.gameSessionTenantId(), - target.gameInstanceId(), target.playableStateNamespaceId(), target.playableStateScope(), target.canonicalGameInstanceId(), - target.canonicalVersionId(), target.runtimeVersionId(), target.catalogRevision(), target.pointerVersion(), - target.admissionPointerSnapshotDigest(), target.activeWorldEpoch(), target.initialAdmissionRequestId(), - target.initialAdmissionRequestDigest(), CanonicalGameplayAdmissionDecisionReadGrpcCodec.OriginKind.NO_PRIOR_POINTER, - null, target.holdId(), target.holdFence(), target.holdBindingDigest(), target.auditEventId(), target.ownerProofDigest(), - CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome.COMMITTED, false, - target.ownerProofTerminalAt(), target.characterCreationPolicy()); + return new Target( + target.targetNamespace(), + target.tenantSlug(), + target.canonicalTenantId(), + target.worldSlug(), + target.worldDisplayName(), + target.realmId(), + target.realmSlug(), + target.realmDisplayName(), + target.gameSessionTenantId(), + target.gameInstanceId(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.canonicalVersionId(), + target.runtimeVersionId(), + target.catalogRevision(), + target.pointerVersion(), + target.admissionPointerSnapshotDigest(), + target.activeWorldEpoch(), + target.initialAdmissionRequestId(), + target.initialAdmissionRequestDigest(), + CanonicalGameplayAdmissionDecisionReadGrpcCodec.OriginKind.NO_PRIOR_POINTER, + null, + target.holdId(), + target.holdFence(), + target.holdBindingDigest(), + target.auditEventId(), + target.ownerProofDigest(), + CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome.COMMITTED, + false, + target.ownerProofTerminalAt(), + target.characterCreationPolicy()); } public void publish(AccountGameplayAdmissionLeaseEvidence lease) { - repository.markProvisional(repository.readProvisionalCasEvidence(transitionId), - new CanonicalGameplayAdmissionDecision(transitionId, lease, identity, generation, null, target)); + repository.markProvisional( + repository.readProvisionalCasEvidence(transitionId), + new CanonicalGameplayAdmissionDecision( + transitionId, lease, identity, generation, null, target)); + } + + /** + * Start the disposable GS role before lease allocation so container startup consumes no lease + * lifetime. + */ + public void prepareMemberRepairRedis() { + memberRedis = new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + memberRedis.start(); + String password = UUID.randomUUID().toString(); + var bootstrap = + RedisClient.create( + RedisURI.Builder.redis(memberRedis.getHost(), memberRedis.getMappedPort(6379)).build()); + try { + try (var connection = bootstrap.connect(ByteArrayCodec.INSTANCE)) { + connection + .sync() + .aclSetuser( + "gamesession_coord_app", + new AclSetuserArgs() + .reset() + .on() + .addPassword(password) + .keyPattern("session:game:index:account:*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.SADD) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.SISMEMBER)); + } + } finally { + bootstrap.shutdown(); + } + var uri = + RedisURI.Builder.redis(memberRedis.getHost(), memberRedis.getMappedPort(6379)) + .withAuthentication("gamesession_coord_app", password) + .build(); + uri.setTimeout(Duration.ofSeconds(5)); + memberRedisApplication = RedisClient.create(uri); + memberRedisApplication.setOptions( + ClientOptions.builder() + .autoReconnect(false) + .protocolVersion(ProtocolVersion.RESP2) + .build()); + } + + /** + * Actual SQL allocation -> role-authenticated physical Redis projection/read -> durable SQL ACK. + */ + public CanonicalGameplayAccountMemberAcknowledgement repairAccountMember() { + memberAcknowledgement = + new CanonicalGameplayAccountMemberRepairOwner( + dsl, + Objects.requireNonNull( + memberRedisApplication, "GS member role must be prepared before acquire"), + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayAccountMemberRepairRedisScriptContribution()))) + .repair(transitionId); + return memberAcknowledgement; + } + + public String memberAcknowledgementImage() { + return dsl.fetchSingle( + "SELECT to_jsonb(repair)::text FROM game_session_canonical_account_member_repair_operation repair WHERE transition_id = ?", + transitionId) + .get(0, String.class); + } + + public String accountObligationPhaseImage() { + return dsl.fetchSingle( + "SELECT (to_jsonb(obligation) - 'inventory_revision')::text FROM game_session_canonical_binding_account_index_obligation obligation WHERE transition_id = ? AND obligation_ordinal = 0", + transitionId) + .get(0, String.class); + } + + /** Independent read under the same real GS role; retained ACK never implies physical removal. */ + public boolean hasExactAccountMember() { + var acknowledgement = + Objects.requireNonNull(memberAcknowledgement, "Actual completed member repair required"); + try (var connection = Objects.requireNonNull(memberRedisApplication).connect()) { + String key = "session:game:index:account:" + identity.accountId(); + return "gamesession_coord_app".equals(connection.sync().aclWhoami()) + && "set".equals(connection.sync().type(key)) + && connection.sync().pttl(key) == -1L + && connection.sync().sismember(key, acknowledgement.member()); + } } /** Attempts a newer candidate; the retained unresolved original must fence preparation. */ public BigInteger prepareNewerCandidate() { - var newer = new CanonicalGameplayBindingIdentity(identity.accountId(), identity.tenantId(), - identity.playableStateNamespaceId(), identity.characterId(), identity.playableStateScope(), - identity.gameInstanceId(), identity.runtimeGameInstanceId(), UUID.randomUUID().toString(), - identity.regionId(), identity.regionEpoch(), identity.issuerId(), identity.issuerAuthGeneration(), - identity.issuerIndexLayoutVersion(), identity.issuerIndexPartitionCount(), identity.issuerIndexPartitionCapacity()); - return repository.prepare(new CanonicalGameplayBindingTransitionRequest(UUID.randomUUID(), UUID.randomUUID(), newer, - new CanonicalIssuerReservationFenceEvidence(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), - BigInteger.ONE, BigInteger.ONE, BigInteger.ONE), null, null)).bindingGeneration(); + var newer = + new CanonicalGameplayBindingIdentity( + identity.accountId(), + identity.tenantId(), + identity.playableStateNamespaceId(), + identity.characterId(), + identity.playableStateScope(), + identity.gameInstanceId(), + identity.runtimeGameInstanceId(), + UUID.randomUUID().toString(), + identity.regionId(), + identity.regionEpoch(), + identity.issuerId(), + identity.issuerAuthGeneration(), + identity.issuerIndexLayoutVersion(), + identity.issuerIndexPartitionCount(), + identity.issuerIndexPartitionCapacity()); + return repository + .prepare( + new CanonicalGameplayBindingTransitionRequest( + UUID.randomUUID(), + UUID.randomUUID(), + newer, + new CanonicalIssuerReservationFenceEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + BigInteger.ONE, + BigInteger.ONE, + BigInteger.ONE), + null, + null)) + .bindingGeneration(); } /** Uses the actual runtime repository; a retained pending lease must fence this mutation. */ @@ -171,12 +476,36 @@ public void stopRuntime() { runtimeRepository.save(runtime); } - public UUID transitionId() { return transitionId; } - public BigInteger generation() { return generation; } - public DSLContext dsl() { return dsl; } - public CanonicalGameplayAdmissionAbortSource source() { return repository.readFirstNewAdmissionAbortSource(transitionId); } + public UUID transitionId() { + return transitionId; + } + + public BigInteger generation() { + return generation; + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "Test fixture deliberately shares its actual SQL context with unregistered owner factories") + public DSLContext dsl() { + return dsl; + } - @Override public void close() { - dsl.execute("DROP SCHEMA \"" + schema + "\" CASCADE"); + public CanonicalGameplayAdmissionAbortSource source() { + return repository.readFirstNewAdmissionAbortSource(transitionId); + } + + @Override + public void close() { + try { + if (memberRedisApplication != null) memberRedisApplication.shutdown(); + } finally { + try { + if (memberRedis != null) memberRedis.stop(); + } finally { + dsl.execute("DROP SCHEMA \"" + schema + "\" CASCADE"); + } + } } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java index dd7f716fe4..3674a45168 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java @@ -51,7 +51,10 @@ public static RuntimeTarget seedRunningLaunch(DataSource dataSource, UUID canoni return seedRunningLaunch(dataSource, canonicalTenantId, null); } - /** Fixed test namespace for authenticated cross-owner composition; upstream evidence is controlled. */ + /** + * Fixed test namespace for authenticated cross-owner composition; upstream evidence is + * controlled. + */ public static RuntimeTarget seedRunningLaunch( DataSource dataSource, UUID canonicalTenantId, String fixedNamespace) { if (canonicalTenantId == null || new UUID(0L, 0L).equals(canonicalTenantId)) { 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 b27c2e5441..04a0fc6a93 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 @@ -1407,18 +1407,36 @@ private static DriverManagerDataSource dataSource(String schema) { } private static List rowImages(DSLContext dsl, String tableName) { + String image = "to_jsonb(retained_row)"; + if (tableName.equals("game_session_canonical_binding_transition")) { + // V1035 adds only this nullable field. Keep every other source value and non-null abort UUID. + image = + "CASE WHEN to_jsonb(retained_row)->'admission_orphan_cleanup_id' = 'null'::jsonb" + + " THEN to_jsonb(retained_row) - 'admission_orphan_cleanup_id' ELSE to_jsonb(retained_row) END"; + } return dsl.fetch( - "SELECT to_jsonb(retained_row)::text AS row_image FROM " + "SELECT (" + + image + + ")::text AS row_image FROM " + tableName - + " retained_row ORDER BY to_jsonb(retained_row)::text") + + " retained_row ORDER BY 1") .getValues("row_image", String.class); } private static List rowImagesWithXmin(DSLContext dsl, String tableName) { + String image = "to_jsonb(retained_row)"; + if (tableName.equals("game_session_canonical_binding_transition")) { + // Preserve xmin and all source data while comparing the one absent-equivalent V1035 field. + image = + "CASE WHEN to_jsonb(retained_row)->'admission_orphan_cleanup_id' = 'null'::jsonb" + + " THEN to_jsonb(retained_row) - 'admission_orphan_cleanup_id' ELSE to_jsonb(retained_row) END"; + } return dsl.fetch( - "SELECT xmin::text || ':' || to_jsonb(retained_row)::text AS row_image FROM " + "SELECT xmin::text || ':' || (" + + image + + ")::text AS row_image FROM " + tableName - + " retained_row ORDER BY to_jsonb(retained_row)::text, xmin::text") + + " retained_row ORDER BY 1") .getValues("row_image", String.class); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwnerTest.java index e890e4776d..ff6874c91a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwnerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwnerTest.java @@ -8,15 +8,15 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import java.nio.charset.StandardCharsets; import java.math.BigInteger; +import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.UUID; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountCoverageEvidence; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountCoverageEvidence; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; @@ -29,8 +29,7 @@ import org.junit.jupiter.api.Test; class CanonicalGameplayAdmissionAbortOwnerTest { - private static final UUID TRANSITION_ID = - UUID.fromString("88888888-8888-4888-8888-888888888888"); + private static final UUID TRANSITION_ID = UUID.fromString("88888888-8888-4888-8888-888888888888"); private static final String ORIGINAL_LEASE = "canonical-original-lease-evidence"; @Test @@ -39,10 +38,7 @@ void accountTimeoutRetainsTheOriginalNonAdmittingObligation() { var accountClient = mock(AccountGameplayAdmissionLeaseClient.class); var source = source(false); when(repository.readFirstNewAdmissionAbortSource(TRANSITION_ID)).thenReturn(source); - when(accountClient.abort( - eq("presented-initial-gsa"), - any(byte[].class), - eq(TRANSITION_ID))) + when(accountClient.abort(eq("presented-initial-gsa"), any(byte[].class), eq(TRANSITION_ID))) .thenThrow(new IllegalStateException("Account abort response unavailable")); var owner = new CanonicalGameplayAdmissionAbortOwner(repository, accountClient); @@ -67,11 +63,14 @@ void accountTimeoutRetainsTheOriginalNonAdmittingObligation() { void retainedTerminalReplayStillAuthenticatesTheCurrentCallerAndCannotCasOnFailure() { var repository = mock(CanonicalGameplayBindingInventoryRepository.class); var client = mock(AccountGameplayAdmissionLeaseClient.class); - when(repository.readFirstNewAdmissionAbortSource(TRANSITION_ID)).thenReturn(source(true)); + var terminalSource = source(true); + when(repository.readFirstNewAdmissionAbortSource(TRANSITION_ID)).thenReturn(terminalSource); when(client.abort(eq("expired-or-revoked-caller"), any(byte[].class), eq(TRANSITION_ID))) .thenThrow(new IllegalStateException("current caller refused")); - assertThatThrownBy(() -> new CanonicalGameplayAdmissionAbortOwner(repository, client) - .abortFirstNew(TRANSITION_ID, "expired-or-revoked-caller")) + assertThatThrownBy( + () -> + new CanonicalGameplayAdmissionAbortOwner(repository, client) + .abortFirstNew(TRANSITION_ID, "expired-or-revoked-caller")) .hasMessage("current caller refused"); verify(client).abort(eq("expired-or-revoked-caller"), any(byte[].class), eq(TRANSITION_ID)); verify(repository, never()).recordFirstNewAccountAbort(any(), any()); @@ -82,11 +81,15 @@ void ambientTransactionOrSynchronizationRefusesBeforeAnyOwnerInteraction() { for (boolean actualTransaction : new boolean[] {false, true}) { var repository = mock(CanonicalGameplayBindingInventoryRepository.class); var client = mock(AccountGameplayAdmissionLeaseClient.class); - org.springframework.transaction.support.TransactionSynchronizationManager.initSynchronization(); - org.springframework.transaction.support.TransactionSynchronizationManager.setActualTransactionActive(actualTransaction); + org.springframework.transaction.support.TransactionSynchronizationManager + .initSynchronization(); + org.springframework.transaction.support.TransactionSynchronizationManager + .setActualTransactionActive(actualTransaction); try { - assertThatThrownBy(() -> new CanonicalGameplayAdmissionAbortOwner(repository, client) - .abortFirstNew(TRANSITION_ID, "presented-initial-gsa")) + assertThatThrownBy( + () -> + new CanonicalGameplayAdmissionAbortOwner(repository, client) + .abortFirstNew(TRANSITION_ID, "presented-initial-gsa")) .hasMessage("First-NEW Account abort requires no ambient SQL scope"); org.mockito.Mockito.verifyNoInteractions(repository, client); } finally { @@ -97,13 +100,18 @@ void ambientTransactionOrSynchronizationRefusesBeforeAnyOwnerInteraction() { @Test void retainedAbortRejectsContradictoryAccountStatesOrChangedCleanupWithoutCas() { - for (var state : net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.State.values()) { + for (var state : + net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.State + .values()) { var repository = mock(CanonicalGameplayBindingInventoryRepository.class); var client = mock(AccountGameplayAdmissionLeaseClient.class); var retained = source(true); var lease = retained.originalDecision().leaseEvidence(); when(lease.hasSameIdentity(lease)).thenReturn(true); - var operation = mock(net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OperationEvidence.class); + var operation = + mock( + net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec + .OperationEvidence.class); when(operation.originalLeaseEvidence()).thenReturn(lease); when(operation.state()).thenReturn(state); switch (state) { @@ -113,14 +121,21 @@ void retainedAbortRejectsContradictoryAccountStatesOrChangedCleanupWithoutCas() } case COMMITTED -> { when(operation.bindingDecisionId()).thenReturn(TRANSITION_ID); - when(operation.originalAckReceipt()).thenReturn(mock(net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalAckReceiptEvidence.class)); + when(operation.originalAckReceipt()) + .thenReturn( + mock( + net.firedevops.firemud.common.account.admission + .AccountGameplayAdmissionLeaseGrpcCodec.OriginalAckReceiptEvidence + .class)); } - case PENDING -> { } + case PENDING -> {} } when(repository.readFirstNewAdmissionAbortSource(TRANSITION_ID)).thenReturn(retained); when(client.abort(any(), any(), any())).thenReturn(operation); - assertThatThrownBy(() -> new CanonicalGameplayAdmissionAbortOwner(repository, client) - .abortFirstNew(TRANSITION_ID, "presented-initial-gsa")) + assertThatThrownBy( + () -> + new CanonicalGameplayAdmissionAbortOwner(repository, client) + .abortFirstNew(TRANSITION_ID, "presented-initial-gsa")) .hasMessage("Account replay contradicts the retained definitive abort"); verify(repository, never()).recordFirstNewAccountAbort(any(), any()); } @@ -193,7 +208,9 @@ static CanonicalGameplayAdmissionAbortSource source(boolean aborted) { UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"), null, null, - aborted ? CanonicalGameplayBindingTransitionSnapshot.Status.ABORTED : CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL, + aborted + ? CanonicalGameplayBindingTransitionSnapshot.Status.ABORTED + : CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL, CanonicalGameplayAccountCoverageEvidence.noActiveFlow()); var candidate = new CanonicalGameplayBindingInventoryEntry( @@ -203,7 +220,9 @@ static CanonicalGameplayAdmissionAbortSource source(boolean aborted) { transition.candidateAccountIndexFence(), transition.issuerReservationId(), TRANSITION_ID, - aborted ? CanonicalGameplayBindingInventoryEntry.Lifecycle.TERMINAL_UNRESOLVED : CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL, + aborted + ? CanonicalGameplayBindingInventoryEntry.Lifecycle.TERMINAL_UNRESOLVED + : CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL, CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED, CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED, BigInteger.ONE); @@ -214,7 +233,9 @@ static CanonicalGameplayAdmissionAbortSource source(boolean aborted) { BigInteger.ONE, TRANSITION_ID, BigInteger.ZERO, - aborted ? CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING : CanonicalIssuerPartitionReservation.Lifecycle.RESERVED, + aborted + ? CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING + : CanonicalIssuerPartitionReservation.Lifecycle.RESERVED, transition.reservationFence(), UUID.fromString("12121212-1212-4212-8212-121212121212"), BigInteger.ONE, @@ -229,12 +250,10 @@ static CanonicalGameplayAdmissionAbortSource source(boolean aborted) { when(decision.targetEvidence()).thenReturn(target); when(decision.leaseKind()) .thenReturn(AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING); - when(lease.leaseKind()) - .thenReturn(AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING); + when(lease.leaseKind()).thenReturn(AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING); when(decision.leaseEvidenceJson()).thenReturn(ORIGINAL_LEASE); when(lease.canonicalJson()).thenReturn(ORIGINAL_LEASE); - return - new CanonicalGameplayAdmissionAbortSource( - transition, candidate, reservation, decision, aborted ? CLEANUP_ID : null); + return new CanonicalGameplayAdmissionAbortSource( + transition, candidate, reservation, decision, aborted ? CLEANUP_ID : null); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java index 9be7858d5b..43c2d7d18a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java @@ -22,7 +22,9 @@ import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; -/** Controlled callback/parser failure tests; native owner composition is a separate PostgreSQL test. */ +/** + * Controlled callback/parser failure tests; native owner composition is a separate PostgreSQL test. + */ class CanonicalGameplayAdmissionDecisionReadGrpcServiceTest { @Test void unexpectedParserFailureTerminatesOnceWithSanitizedInternalBeforeRepositoryRead() { @@ -31,7 +33,8 @@ void unexpectedParserFailureTerminatesOnceWithSanitizedInternalBeforeRepositoryR var observer = observer(); var request = GetCanonicalGameplayAdmissionDecisionRequest.getDefaultInstance(); try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { - codec.when(() -> CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest(request)) + codec + .when(() -> CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest(request)) .thenThrow(new IllegalStateException("private parser details")); new CanonicalGameplayAdmissionDecisionReadGrpcService(repository, guard, "test") .getCanonicalGameplayAdmissionDecision(request, observer); @@ -55,21 +58,37 @@ void onNextFailureSignalsOneErrorButCompletionFailureEscapesWithoutSecondTermina var source = CanonicalGameplayAdmissionAbortOwnerTest.source(false); var decision = source.originalDecision(); var lease = decision.leaseEvidence(); - when(lease.carrier()).thenReturn(Map.of("targetNamespace", "test", "callerWorkload", "spiffe://firemud/ns/test/sa/game-session-service")); + when(lease.carrier()) + .thenReturn( + Map.of( + "targetNamespace", + "test", + "callerWorkload", + "spiffe://firemud/ns/test/sa/game-session-service")); var selector = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.RequestEvidence.class); when(selector.expectedLeaseEvidence()).thenReturn(lease); - when(selector.bindingDecisionId()).thenReturn(decision.bindingDecisionId()); - when(repository.readAdmissionDecision(decision.bindingDecisionId(), lease)).thenReturn(decision); + var decisionId = decision.bindingDecisionId(); + when(selector.bindingDecisionId()).thenReturn(decisionId); + when(repository.readAdmissionDecision(decision.bindingDecisionId(), lease)) + .thenReturn(decision); var response = GetCanonicalGameplayAdmissionDecisionResponse.getDefaultInstance(); var callbackFailure = new IllegalStateException("observer callback failed"); if (completionFailure) doThrow(callbackFailure).when(observer).onCompleted(); else doThrow(callbackFailure).when(observer).onNext(response); try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { - codec.when(() -> CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest(request)).thenReturn(selector); - codec.when(() -> CanonicalGameplayAdmissionDecisionReadGrpcCodec.toResponse(any(), any(), any(), any(), any(), any(), any(), any())) + codec + .when(() -> CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest(request)) + .thenReturn(selector); + codec + .when( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toResponse( + any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(response); - Runnable receive = () -> new CanonicalGameplayAdmissionDecisionReadGrpcService(repository, guard, "test") - .getCanonicalGameplayAdmissionDecision(request, observer); + Runnable receive = + () -> + new CanonicalGameplayAdmissionDecisionReadGrpcService(repository, guard, "test") + .getCanonicalGameplayAdmissionDecision(request, observer); if (completionFailure) assertThatThrownBy(receive::run).isSameAs(callbackFailure); else receive.run(); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuardTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuardTest.java index 2fff6f1044..5a428fefda 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuardTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuardTest.java @@ -63,14 +63,15 @@ void rejectsMissingForeignOrSessionContextIdentityBeforeHandler() { .getGetCanonicalGameplayAdmissionDecisionMethod(); assertRejected(invoke(method, null), Status.Code.UNAUTHENTICATED); assertRejected( - invoke(method, peer(NAMESPACE, "world-management-service")), - Status.Code.PERMISSION_DENIED); + invoke(method, peer(NAMESPACE, "world-management-service")), Status.Code.PERMISSION_DENIED); assertRejected(invoke(method, peer("other", "account-service")), Status.Code.PERMISSION_DENIED); SessionContext.setContext("account-1", List.of(), Map.of()); - assertRejected(invoke(method, peer(NAMESPACE, "account-service")), Status.Code.PERMISSION_DENIED); + assertRejected( + invoke(method, peer(NAMESPACE, "account-service")), Status.Code.PERMISSION_DENIED); SessionContext.setContext(null, List.of(), Map.of(), true, "account-service", "instance"); - assertRejected(invoke(method, peer(NAMESPACE, "account-service")), Status.Code.PERMISSION_DENIED); + assertRejected( + invoke(method, peer(NAMESPACE, "account-service")), Status.Code.PERMISSION_DENIED); } private void assertRejected(Invocation invocation, Status.Code code) { From 325334c0c381970c311f66da88809a6db01cce20 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:15:21 +1300 Subject: [PATCH 12/34] Define issuer release provenance and record actual abort proof --- design/architecture/system-architecture-redis.md | 10 +++++++++- .../player-access-and-session.md | 6 +++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/design/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index d1a17addc8..e781f0c9ae 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -369,7 +369,7 @@ value: { The value is a closed, bounded RFC 8785 canonical JSON object. Except for the literal numeric `schemaVersion: 2`, counters use canonical unsigned decimal strings; every counter is positive except the zero-based `partitionId`. Implementations preserve values beyond binary floating-point precision. UUIDs and identifiers retain their exact canonical spelling, and bytes use canonical padded Base64. `sourceEventBytes` and `sourceEventDigest` are both explicit `null` only when the exact qualified Account checkpoint has no corresponding event. Unknown or duplicate fields, unsupported versions, malformed UTF-8, noncanonical bytes, inconsistent owner/partition/layout references, and resource-bound violations fail closed; parser limits never authorize normalization or truncation. -The value preserves two distinct issuer-coverage tuples. `reservation.issuerCoverageOperationId`, `issuerCoverageOperationFence`, `coverageFence`, and `inventorySnapshotRevision` are copied unchanged from the original durable reservation. The four coverage-tuple fields under `anchor` (`issuerCoverageOperationId`, `operationFence`, `coverageFence`, and `issuerInventorySnapshotRevision`) identify the issuer coverage anchor carried by this v2 value. Together with the anchor's exact Account source fields, they are independent from the original reservation tuple and never replace or reconstruct it. No equality between those tuples is required. `anchor.issuerInventorySnapshotRevision` is the complete immutable issuer inventory revision; `reservation.inventoryRevision` is that reservation's durable transition revision, and they are not interchangeable. The full owner identity, immutable authorized layout descriptor, and Account source bytes must match the exact binding and anchor evidence; the reservation must independently match its original durable source. Before a physical bootstrap write, the owner proves that this original reservation belongs to the frozen complete issuer cohort and links it to the exact bootstrap operation and fences. Shape parsing alone grants no authority. +The value preserves two distinct issuer-coverage tuples. `reservation.issuerCoverageOperationId`, `issuerCoverageOperationFence`, `coverageFence`, and `inventorySnapshotRevision` are copied unchanged from the original durable reservation. The four coverage-tuple fields under `anchor` (`issuerCoverageOperationId`, `operationFence`, `coverageFence`, and `issuerInventorySnapshotRevision`) identify the issuer coverage anchor carried by this v2 value. Together with the anchor's exact Account source fields, they are independent from the original reservation tuple and never replace or reconstruct it. No equality between those tuples is required. `anchor.issuerInventorySnapshotRevision` is the complete immutable issuer inventory revision. For an ordinary retained reservation projection, `reservation.inventoryRevision` is its durable transition revision. For the owner-issued `RELEASED` physical projection, it is the frozen durable release-preparation source revision defined below; neither meaning is interchangeable with the anchor revision. The full owner identity, immutable authorized layout descriptor, and Account source bytes must match the exact binding and anchor evidence; the reservation must independently match its original durable source. Before a physical bootstrap write, the owner proves that this original reservation belongs to the frozen complete issuer cohort and links it to the exact bootstrap operation and fences. Shape parsing alone grants no authority. Mutation, retry, readback, and cleanup preserve and exact-compare both complete coverage tuples, the original reservation identity, owner, transition, layout, partition, lifecycle, fence and revision, and the local member-operation linkage. Same binding identity with different original reservation provenance, anchor, or operation linkage is a conflict. The owner never reconstructs the original tuple from the anchor, rewrites or re-anchors the original SQL reservation, or invents a member generation. The anchor operation fence, coverage fence, binding-local member-operation fence and `issuerControlEpoch` retain separate evidence domains. The anchor operation and coverage fences retain their distinct values. Equality between counters from different domains does not merge their authority or imply an ordering. `memberOperation.coverageGeneration` is concrete only after its issuing owner allocates it; a parser, bootstrap preparation, or caller cannot invent it. The local SQL owner issues and persists this member-operation identity before the physical member write; allocation alone proves neither readback nor completion. It is distinct from the issuer-wide acknowledgement generation, which remains `NOT_YET_ISSUED` until complete finite physical coverage is proven. The value retains the complete stable incarnation binding, including every field of accepted `targetDeploymentEvidence/v1`, not only its digest. Fresh observation nonces, observation times, and signing-key selection are not stable row identity; the protected current-observation owner validates them at each decisive boundary. See [Redis Operations and Access](./system-architecture-redis-ops-access.md) for protected evidence ownership. @@ -379,6 +379,14 @@ Capacity evidence shares that same owned partition HASH and atomic boundary. Res The versioned reserved field `!issuer-partition-bootstrap/v1` retains the exact common bootstrap/layout/source/incarnation context, and `!issuer-reservation-capacity/v1:` retains the complete schema-v2 value for that original reservation and issued local operation. Both names are disjoint from the length-prefixed `bindingRef/v1` field grammar. A partition build compares the complete existing field set before mutation and refuses unknown, legacy, conflicting, expiring or partially decoded state without rewriting it. Full member and reservation values retain their original provenance; a header digest never replaces them. Complete per-partition readback remains a separate input to the later finite issuer-wide coverage proof, and its frozen aggregate expectation is not proof that other partitions have been built. +### Binding-Local Issuer Release Provenance + +A binding-local issuer release requires the actual terminal Account abort and the exact retained Game Session `RELEASE_PENDING` reservation. Before contacting Redis, the release owner persists its operation identity, fence, local generation and exact expected schema-v2 `RELEASED` postimage under an actual inventory-clock preparation revision `P`. In that physical postimage, `reservation.inventoryRevision` is the frozen release-preparation source revision `P`. The complete original pre-release reservation and physical value remain retained separately, including their immutable original coverage tuple, identity, anchor and local-operation linkage. The prepared terminal projection is intent, not SQL completion or issuer-wide coverage. + +The one-key release compares the complete original member and capacity evidence, removes only that exact old binding member, and retains a positive `RELEASED` capacity value for independent complete readback. Absence alone cannot release capacity or establish cleanup. After successful mutation and independent exact readback, SQL completion reloads the current owner, source, incarnation, reservation and anchor guards and allocates a fresh actual inventory-clock revision `R`. The completion receipt links `P`, the frozen physical postimage and readback, the original release operation and the actual `R` of the current `RELEASED` reservation. `R` must exceed `P` within that same clock domain; intervening writers may advance the clock, so adjacency is not required. No transaction is held over Redis, and no future revision is reserved or guessed. + +Consumers require both the exact frozen physical provenance and the matching durable completion receipt and current row. They never require the physical `reservation.inventoryRevision` to equal `R`, rewrite the physical value after SQL merely to equalize revisions, or reuse one snapshot revision for two states. A crash, lost reply or exact retry reuses the original prepared bytes, `P` and operation; a completed retry reads its committed receipt without issuing a second release. Ambiguous readback, changed source/incarnation/reservation/anchor or a newer member refuses completion and preserves the pending obligation. Only that binding-local issuer repair obligation may be settled by this proof; Account cleanup, region cleanup, issuer-wide coverage and final admission retain their separate owners. + ### Canonical Issuer Partition Mapping The target `bindingRef` encoding is one exact versioned UTF-8 byte sequence, consistent with the repository's length-prefixed identity convention. For `segment(bytes) = ascii(canonical_decimal_count(byte_length(bytes))) + ":" + bytes`, where the count has no leading zero, the complete binding identity is encoded in this fixed order: diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 813db4e4bf..d7bcd36157 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -24,7 +24,11 @@ The local member-repair acknowledgement also retains its original account-contro The current local issuer source extends the retained V1030 cohort through immutable V1031 plan/work/blocker rows and V1032 SQL-issued member operations. The original reservation coverage tuple remains distinct from the new bootstrap anchor; equal numeric counters across those separate domains are permissible and do not equate their full identities. R569 passes seven PostgreSQL plan cases, including source/control/layout refusal, original retry, retained-row and TRUNCATE guards, and per-partition/aggregate nonterminal reservation bounds with RELEASED exclusion. R575 passes four operation-producer and seven plan-regression cases. The owner allocates the local member-operation fence and generation before projection; those values confer no global coverage generation or completion. -R578 freshly passes the composed four SQL-producer, seven plan-regression and seven physical Redis-owner cases on local checkpoint `a5c2b1c69151029a5be203c720c2618f0866f71a` plus its qualified formatter and test corrections. The actual owner builds or exactly replays one canonical partition HASH, independently reads the complete field set through a separate connection, and brackets the remote phase with controlled current Account checkpoint and stable-incarnation reads. Proof includes populated and positively prepared empty partitions, full original/new tuple conflict, retained terminal reservations, capacity refusal, wrong type/TTL/foreign/v1 evidence, original lost-reply retry and source/incarnation movement. Enabled affected Checkstyle, SpotBugs and formatting pass; all five exact R578 containers are independently confirmed absent. R577 remains a failed aggregate: a fixture incorrectly required independent numeric fences to differ and its status-query helper failed null-safety static analysis; the correction preserves full tuple comparison and exact stored bytes. These results prove local partition projection/readback under controlled collaborators, not operational source or incarnation custody. R579 separately passes all nine PostgreSQL bootstrap-owner cases with enabled affected static analysis and formatting, including the accepted exact pre-intent replay correction, conflicting retry refusal and unchanged durable row/counter images; its exact PostgreSQL container is independently confirmed absent. R583 subsequently passes 33 focused actual PostgreSQL/Redis cases with enabled generation, static analysis and formatting, qualifying the finite initial coverage owner under controlled descriptor, current-source and incarnation collaborators. It retains every partition’s exact proof before allocating the global coverage generation and installing the immutable initial anchor. Exact installed replay reads existing physical state without rebuilding it, and a later counter-head advance preserves the retained anchor. All eight exact containers are independently confirmed absent. These component results do not establish operational source custody or tenant admission. The ordinary post-baseline SQL/Redis path and real Account-abort/issuer-cleanup consequence remain under local implementation and qualification; issuer/region acknowledgements, barrier OPEN, final CAS and playable admission remain unfinished. The complete combined owner scope stays in #3310; the published prefix and unpublished source are not green successor runway. +R578 freshly passes the composed four SQL-producer, seven plan-regression and seven physical Redis-owner cases on local checkpoint `a5c2b1c69151029a5be203c720c2618f0866f71a` plus its qualified formatter and test corrections. The actual owner builds or exactly replays one canonical partition HASH, independently reads the complete field set through a separate connection, and brackets the remote phase with controlled current Account checkpoint and stable-incarnation reads. Proof includes populated and positively prepared empty partitions, full original/new tuple conflict, retained terminal reservations, capacity refusal, wrong type/TTL/foreign/v1 evidence, original lost-reply retry and source/incarnation movement. Enabled affected Checkstyle, SpotBugs and formatting pass; all five exact R578 containers are independently confirmed absent. R577 remains a failed aggregate: a fixture incorrectly required independent numeric fences to differ and its status-query helper failed null-safety static analysis; the correction preserves full tuple comparison and exact stored bytes. These results prove local partition projection/readback under controlled collaborators, not operational source or incarnation custody. R579 separately passes all nine PostgreSQL bootstrap-owner cases with enabled affected static analysis and formatting, including the accepted exact pre-intent replay correction, conflicting retry refusal and unchanged durable row/counter images; its exact PostgreSQL container is independently confirmed absent. R583 subsequently passes 33 focused actual PostgreSQL/Redis cases with enabled generation, static analysis and formatting, qualifying the finite initial coverage owner under controlled descriptor, current-source and incarnation collaborators. It retains every partition’s exact proof before allocating the global coverage generation and installing the immutable initial anchor. Exact installed replay reads existing physical state without rebuilding it, and a later counter-head advance preserves the retained anchor. All eight exact containers are independently confirmed absent. These component results do not establish operational source custody or tenant admission. The ordinary post-baseline SQL/Redis path has the focused local qualification below; terminal issuer cleanup remains under implementation. Issuer/region acknowledgements, barrier OPEN, final CAS and playable admission remain unfinished. The complete combined owner scope stays in #3310; the published prefix and unpublished source are not green successor runway. + +R600 freshly qualifies the ordinary post-baseline SQL-issued local operation and actual one-key Redis member/capacity projection under an installed anchor, with separate complete readback and current-source bracketing. Two native case methods cover the original operation, refusal and retry scenarios; enabled affected static analysis and formatting pass, and all five exact containers are independently confirmed absent. This proves pending physical projection, not a final issuer acknowledgement or admission. + +The manually composed first-NEW abort path now joins actual Account current-caller verification, issuance, physical Redis and PostgreSQL abort to the actual Game Session provisional-decision reverse read and guarded retained abort. At local checkpoint `f5f7c132f58538785625334dfea1faf073f0234a`, R607 freshly passes all 52 selected cases: 11 units, 35 issuer PostgreSQL/Redis cases and six actual Account–Game Session composition cases; zero failures, errors or skips. Enabled affected static analysis and formatting pass, and R608 documentation checks pass. All 27 exact R607 containers are independently confirmed absent. The composition uses bidirectional manual mTLS and controlled upstream launch, World/initial-target and test-PKI inputs. It proves exact original lease retention, current-caller and purpose refusal, terminal retry/restart, finalize/abort contention and immutable terminal evidence. The allowed pre-abort account-member ACK case invokes the actual Redis repair owner and SQL acknowledgement, then preserves that exact ADD/readback history through Account abort and restarted retry; it does not relabel the ACK as removal proof. The physical member remains, the candidate is `TERMINAL_UNRESOLVED`, and the issuer reservation is `RELEASE_PENDING`. Physical issuer release, Account cleanup delivery, region cleanup, final controller admission, operational custody and activation remain unproved. The original end-to-end gameplay testing assignment remains parked independently of this focused train proof. ### Player-created roster consumer preparation From 95e0d0dc224fcde21698033e8d2f71b1be247704 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:51:17 +1300 Subject: [PATCH 13/34] Implement retained first-NEW issuer release with exact physical proof --- ...nitiveAbortCompositionIntegrationTest.java | 188 +++- ...CurrentSourcesPostgresIntegrationTest.java | 47 + .../game-session-service/build.gradle.kts | 8 + ...CanonicalGameplayAdmissionAbortSource.java | 6 +- ...lGameplayBindingIssuerIndexObligation.java | 22 +- ...calGameplayBindingInventoryRepository.java | 197 ++++- ...IssuerBindingLocalOperationRepository.java | 132 ++- ...ssuerBindingLocalProjectionRepository.java | 112 ++- ...lGameplayIssuerBindingLocalRedisOwner.java | 7 + ...layIssuerBindingLocalReleaseOperation.java | 244 +++++ ...indingLocalReleaseOperationRepository.java | 836 ++++++++++++++++++ ...ayIssuerBindingLocalReleaseRedisOwner.java | 448 ++++++++++ ...ngLocalReleaseRedisScriptContribution.java | 51 ++ ...nonical_issuer_first_new_release_proof.sql | 586 ++++++++++++ .../game-session-issuer-binding-local-add.lua | 8 +- ...e-session-issuer-binding-local-release.lua | 387 ++++++++ ...game-session-issuer-binding-local-add.json | 4 +- ...-session-issuer-binding-local-release.json | 39 + ...eplayAdmissionAbortCompositionFixture.java | 270 +++++- 19 files changed, 3540 insertions(+), 52 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperation.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V1036__canonical_issuer_first_new_release_proof.sql create mode 100644 services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-release.lua create mode 100644 services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-release.json diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java index f29d23367a..f73298e839 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java @@ -25,6 +25,7 @@ import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.State; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortOutcome; @@ -45,8 +46,9 @@ /** * Actual Account acquisition/current caller/physical token and abort owner, real GS durable * PROVISIONAL reverse read and guarded abort CAS, physical PostgreSQL/Redis and manual mTLS. - * Launch/publication/initial-target and test PKI inputs remain controlled. This proves neither - * physical issuer release nor runtime registration, admission, production PKI or terminal cleanup. + * Launch/publication/initial-target and test PKI inputs remain controlled. The physical issuer + * proof is binding-local only; it does not prove runtime registration, admission, production PKI, + * or completion of the remaining Account and region terminal obligations. */ @Execution(ExecutionMode.SAME_THREAD) class AccountGameSessionDefinitiveAbortCompositionIntegrationTest { @@ -178,6 +180,170 @@ void actualConcurrentFinalizeAndAbortHaveOneAccountWinnerWithoutGsCommittedRelab } } + @Test + void actualAccountAbortedOrdinaryIssuerMemberReleaseHasExactReadbackRetryAndFreesCapacity() throws Exception { + try (var session = open()) { + UUID originalOperationId = session.gs.originalOperationId(); + byte[] originalMemberBytes = session.gs.originalMemberValueBytes(); + + var abort = session.abort(); + assertThat(abort.state()).isEqualTo(CanonicalGameplayAdmissionAbortOutcome.State.ABORTED); + var aborted = session.gs.source(); + assertThat(aborted.isAccountAborted()).isTrue(); + assertThat(aborted.reservation().lifecycle()) + .isEqualTo(CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING); + + var pending = session.gs.prepareIssuerRelease(); + assertThat(pending.originalOperationId()).isEqualTo(originalOperationId); + assertThat(pending.exactOriginalMemberValueBytes()).containsExactly(originalMemberBytes); + assertThat(pending.sourceInventoryRevision()).isGreaterThan(aborted.transition().inventoryRevision()); + assertThat(session.gs.source().transition().inventoryRevision()).isEqualTo(pending.sourceInventoryRevision()); + + UUID secondOperationId = session.gs.prepareOtherControllerNew("second-controller"); + assertThat(secondOperationId).isNotEqualTo(originalOperationId); + var clockAfterOtherWriter = session.gs.dsl().fetchSingle( + "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock WHERE singleton_id = 1") + .get("inventory_revision", java.math.BigDecimal.class).toBigIntegerExact(); + assertThat(clockAfterOtherWriter).isGreaterThan(pending.sourceInventoryRevision()); + assertThat(session.gs.source().transition().inventoryRevision()).isEqualTo(pending.sourceInventoryRevision()); + assertThat(session.gs.preparedLocalCountedReservations()).isEqualTo(java.math.BigInteger.TWO); + assertThatThrownBy(() -> session.gs.prepareOtherControllerNew("full-before-release")) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("capacity"); + + String preparedImage = session.image(); + assertThatThrownBy(() -> session.gs.dsl().execute( + "UPDATE game_session_canonical_issuer_binding_local_release_operation" + + " SET original_member_value_bytes = ? WHERE operation_id = ?", + new byte[] {1}, pending.operationId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(session.image()).isEqualTo(preparedImage); + assertThatThrownBy(() -> session.gs.dsl().execute( + "UPDATE game_session_canonical_issuer_binding_local_release_operation" + + " SET original_reservation_fence = ? WHERE operation_id = ?", + UUID.randomUUID(), pending.operationId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(session.image()).isEqualTo(preparedImage); + assertThatThrownBy(() -> session.gs.dsl().execute( + "UPDATE game_session_canonical_issuer_binding_local_release_operation" + + " SET anchor_operation_fence = anchor_operation_fence + 1 WHERE operation_id = ?", + pending.operationId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(session.image()).isEqualTo(preparedImage); + assertThatThrownBy(() -> session.gs.dsl().execute( + "UPDATE game_session_canonical_issuer_partition_reservation" + + " SET lifecycle = 'RELEASED', inventory_revision = inventory_revision + 1" + + " WHERE reservation_id = ?", + pending.abortSource().reservation().reservationId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(session.image()).isEqualTo(preparedImage); + + assertThatThrownBy(() -> session.gs.prepareOtherControllerNew("still-full-during-release")) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("capacity"); + + session.gs.moveIssuerSourceCheckpoint(); + assertThatThrownBy(() -> session.gs.projectIssuerRelease(pending)) + .isInstanceOf(RuntimeException.class); + session.gs.restoreIssuerState(); + assertThat(session.gs.readReleaseCapacityValue(pending)).containsExactly(originalMemberBytes); + assertThat(session.gs.readReleaseBindingValue(pending)).containsExactly(originalMemberBytes); + + session.gs.moveIssuerIncarnation(); + assertThatThrownBy(() -> session.gs.projectIssuerRelease(pending)) + .isInstanceOf(RuntimeException.class); + session.gs.restoreIssuerState(); + assertThat(session.gs.readReleaseCapacityValue(pending)).containsExactly(originalMemberBytes); + assertThat(session.gs.readReleaseBindingValue(pending)).containsExactly(originalMemberBytes); + + byte[] wrongReservationValue = session.gs.otherMemberValueBytes("second-controller"); + session.gs.installConflictingReleaseCapacity(pending, wrongReservationValue); + assertThatThrownBy(() -> session.gs.projectIssuerRelease(pending)) + .isInstanceOf(RuntimeException.class); + assertThat(session.gs.readReleaseCapacityValue(pending)).containsExactly(wrongReservationValue); + assertThat(session.gs.readReleaseBindingValue(pending)).containsExactly(originalMemberBytes); + session.gs.restoreOriginalReleaseCapacity(pending); + + session.gs.installConflictingReleaseBinding(pending); + byte[] conflictingBinding = session.gs.readReleaseBindingValue(pending); + byte[] originalCapacity = session.gs.readReleaseCapacityValue(pending); + assertThatThrownBy(() -> session.gs.projectIssuerRelease(pending)) + .isInstanceOf(RuntimeException.class); + assertThat(session.gs.readReleaseBindingValue(pending)).containsExactly(conflictingBinding); + assertThat(session.gs.readReleaseCapacityValue(pending)).containsExactly(originalCapacity); + session.gs.restoreOriginalReleaseBinding(pending); + assertThat(session.gs.readReleaseBindingValue(pending)).containsExactly(originalMemberBytes); + assertThat(session.gs.readReleaseCapacityValue(pending)).containsExactly(originalMemberBytes); + + assertThatThrownBy(() -> session.gs.projectIssuerReleaseAndLoseReply(pending)) + .hasMessage("controlled lost issuer release reply after physical readback"); + var resumed = session.gs.prepareIssuerRelease(); + assertThat(resumed.operationId()).isEqualTo(pending.operationId()); + assertThat(resumed.sourceInventoryRevision()).isEqualTo(pending.sourceInventoryRevision()); + assertThat(resumed.exactReleasedMemberValueBytes()).containsExactly(pending.exactReleasedMemberValueBytes()); + var physicalReadback = session.gs.projectIssuerRelease(resumed); + assertThat(physicalReadback.scriptOutcome()).isEqualTo(2L); + assertThat(session.gs.readbackHasExactReleasedMember(resumed, physicalReadback)).isTrue(); + var clockBeforeCompletion = session.gs.dsl().fetchSingle( + "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock WHERE singleton_id = 1") + .get("inventory_revision", java.math.BigDecimal.class).toBigIntegerExact(); + assertThat(clockBeforeCompletion).isEqualTo(clockAfterOtherWriter); + var afterPhysicalReadback = session.gs.source(); + assertThat(afterPhysicalReadback.reservation().lifecycle()) + .isEqualTo(CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING); + var released = session.gs.completeIssuerRelease(resumed, physicalReadback); + assertThat(released.status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); + assertThat(released.completionInventoryRevision()) + .isGreaterThan(released.sourceInventoryRevision()); + assertThat(released.completionInventoryRevision()).isGreaterThan(clockBeforeCompletion); + assertThat(released.exactOriginalMemberValueBytes()).containsExactly(originalMemberBytes); + assertThat(released.releasedMemberValue().reservation().lifecycle()) + .isEqualTo(CanonicalIssuerPartitionReservation.Lifecycle.RELEASED); + assertThat(released.releasedMemberValue().reservation().inventoryRevision()) + .isEqualTo(released.sourceInventoryRevision()); + assertThat(session.gs.preparedLocalCountedReservations()).isEqualTo(java.math.BigInteger.ONE); + + var source = session.gs.source(); + assertThat(source.reservation().lifecycle()) + .isEqualTo(CanonicalIssuerPartitionReservation.Lifecycle.RELEASED); + assertThat(source.candidate().lifecycle()) + .isEqualTo(CanonicalGameplayBindingInventoryEntry.Lifecycle.TERMINAL_UNRESOLVED); + var issuer = session.gs.dsl().fetchSingle( + "SELECT status, local_release_operation_id, inventory_revision" + + " FROM game_session_canonical_binding_issuer_index_obligation WHERE transition_id = ?", + session.gs.transitionId()); + assertThat(issuer.get("status", String.class)).isEqualTo("RELEASED"); + assertThat(issuer.get("local_release_operation_id", UUID.class)).isEqualTo(released.operationId()); + assertThat(issuer.get("inventory_revision", java.math.BigDecimal.class)) + .isEqualTo(new java.math.BigDecimal(released.completionInventoryRevision())); + assertThat(session.gs.dsl().fetchSingle( + "SELECT status FROM game_session_canonical_binding_account_index_obligation" + + " WHERE transition_id = ? AND obligation_ordinal = 0", + session.gs.transitionId()).get("status", String.class)).isIn("REQUIRED", "ACKNOWLEDGED"); + assertThat(session.gs.dsl().fetchSingle( + "SELECT status FROM game_session_canonical_binding_region_bridge_obligation WHERE transition_id = ?", + session.gs.transitionId()).get("status", String.class)).isEqualTo("REQUIRED"); + + UUID thirdOperationId = session.gs.prepareOtherControllerNew("freed-capacity-other-controller"); + assertThat(session.gs.preparedLocalCountedReservations()).isEqualTo(java.math.BigInteger.TWO); + var thirdReadback = session.gs.projectOtherControllerNew("freed-capacity-other-controller"); + assertThat(thirdReadback.operationId()).isEqualTo(thirdOperationId); + assertThat(thirdReadback.scriptOutcome()).isIn(1L, 2L, 3L); + + byte[] retainedReadback = released.exactPhysicalReadbackFieldSetBytes(); + var releaseReplay = session.gs.prepareIssuerRelease(); + assertThat(releaseReplay.operationId()).isEqualTo(released.operationId()); + assertThat(releaseReplay.exactReleasedMemberValueBytes()).containsExactly(released.exactReleasedMemberValueBytes()); + var replayReadback = session.gs.projectIssuerRelease(releaseReplay); + assertThat(replayReadback.scriptOutcome()).isEqualTo(2L); + var completedReplay = session.gs.completeIssuerRelease(releaseReplay, replayReadback); + assertThat(completedReplay.completionInventoryRevision()).isEqualTo(released.completionInventoryRevision()); + assertThat(completedReplay.exactPhysicalReadbackFieldSetBytes()).containsExactly(retainedReadback); + assertThat(session.abort().orphanCleanupId()).isEqualTo(abort.orphanCleanupId()); + } + } + @Test void actualReverseReadRefusesWrongPeerDecisionAndChangedOriginalTupleWithoutAccountAbort() throws Exception { try (var session = open()) { @@ -240,8 +406,17 @@ private Session() throws Exception { var credential = accountFixture.responseRecoveryOwner.recoverInitialLoginResponse( issuance.requestId(), issuance.accountId(), new CallerIdentity(issuance.callerWorkload(), issuance.callerContextId())); jwt = new String(credential.compactJwtBytes(), StandardCharsets.US_ASCII); - gs = new CanonicalGameplayAdmissionAbortCompositionFixture(accountFixture.dataSource, - AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.admissionCandidate(accountFixture)); + Candidate candidate = + AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.admissionCandidate(accountFixture); + Candidate capacityCandidate = new Candidate( + candidate.accountId(), candidate.tenantId(), candidate.playableStateNamespaceId(), + candidate.characterId(), candidate.playableStateScope(), candidate.gameInstanceId(), + candidate.runtimeGameInstanceId(), candidate.sessionId(), candidate.regionId(), + candidate.regionEpoch(), candidate.issuerId(), candidate.issuerAuthGeneration(), + candidate.issuerIndexLayoutVersion(), candidate.issuerIndexPartitionCount(), + java.math.BigInteger.valueOf(2)); + gs = new CanonicalGameplayAdmissionAbortCompositionFixture( + accountFixture.dataSource, capacityCandidate, redis.issuerOwnerClient()); pkiDirectory = Files.createTempDirectory(temporaryDirectory, "actual-abort-mtls-"); pki = LoopbackMtlsTestPki.create(pkiDirectory, "Account GS abort test CA", new LoopbackMtlsTestPki.IdentitySpec("account", ACCOUNT, true), @@ -290,7 +465,10 @@ private void restartAccount() throws Exception { } private String image() { return java.util.List.of("game_session_canonical_binding_transition", "game_session_canonical_gameplay_binding_inventory", - "game_session_canonical_issuer_partition_reservation").stream() + "game_session_canonical_issuer_partition_reservation", + "game_session_canonical_binding_issuer_index_obligation", + "game_session_canonical_issuer_binding_local_operation", + "game_session_canonical_issuer_binding_local_release_operation").stream() .map(table -> gs.dsl().fetch("SELECT to_jsonb(t)::text AS image FROM " + table + " t ORDER BY 1").getValues("image").toString()) .collect(java.util.stream.Collectors.joining("\n")); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java index 359082968e..724f8d67a2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java @@ -2320,6 +2320,8 @@ static final class PhysicalRedisFixture implements AutoCloseable { private static final int REDIS_PORT = 6379; private static final String ACCOUNT_PASSWORD = UUID.randomUUID().toString().replace("-", ""); private static final String PRIMARY_ALIAS = "account-gameplay-admission-primary"; + private static final String ISSUER_OWNER = "gamesession_coord_app"; + private static final String ISSUER_OWNER_PASSWORD = UUID.randomUUID().toString().replace("-", ""); private final Network network = Network.newNetwork(); private final GenericContainer primary = @@ -2356,6 +2358,7 @@ static final class PhysicalRedisFixture implements AutoCloseable { Integer.toString(REDIS_PORT)); private RedisClient bootstrapClient; + private RedisClient issuerOwnerClient; private LettuceAccountCoordinationPinnedConnectionProvider accountProvider; private AccountGameplayDelegationRedisClient accountClient; @@ -2381,9 +2384,18 @@ private void startOwnedRedis() throws InterruptedException { try (var connection = bootstrapClient.connect(ByteArrayCodec.INSTANCE)) { RedisCommands commands = connection.sync(); configureAccountUser(commands); + configureIssuerOwner(commands); awaitLocalAndReplicaAof(commands); } + RedisURI issuerUri = + RedisURI.Builder.redis("127.0.0.1", primaryPort) + .withAuthentication(ISSUER_OWNER, ISSUER_OWNER_PASSWORD) + .build(); + issuerUri.setTimeout(Duration.ofSeconds(5)); + issuerOwnerClient = RedisClient.create(issuerUri); + issuerOwnerClient.setOptions(ClientOptions.builder().autoReconnect(false).build()); + RedisURI accountUri = RedisURI.Builder.redis("127.0.0.1", primaryPort) .withAuthentication( @@ -2406,6 +2418,10 @@ AccountGameplayDelegationRedisClient client() { return Objects.requireNonNull(accountClient, "Owned Account Redis client is unavailable"); } + RedisClient issuerOwnerClient() { + return Objects.requireNonNull(issuerOwnerClient, "Owned issuer Redis client is unavailable"); + } + private static RedisClient redisClient(String host, int port, String password) { RedisURI.Builder uri = RedisURI.Builder.redis(host, port); if (password != null) { @@ -2449,6 +2465,29 @@ private static void configureAccountUser(RedisCommands commands) .add("+waitaof")); } + private static void configureIssuerOwner(RedisCommands commands) { + commands.aclSetuser( + ISSUER_OWNER, + new AclSetuserArgs() + .reset() + .on() + .addPassword(ISSUER_OWNER_PASSWORD) + .keyPattern("session:game:index:issuer:*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.HGET) + .addCommand(CommandType.HLEN) + .addCommand(CommandType.HGETALL) + .addCommand(CommandType.HSET) + .addCommand(CommandType.HDEL)); + } + private static void awaitLocalAndReplicaAof(RedisCommands commands) throws InterruptedException { byte[] probeKey = @@ -2499,6 +2538,14 @@ public void close() { else cleanupFailure.addSuppressed(failure); } } + if (issuerOwnerClient != null) { + try { + issuerOwnerClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } catch (RuntimeException failure) { + if (cleanupFailure == null) cleanupFailure = failure; + else cleanupFailure.addSuppressed(failure); + } + } if (replica.isRunning()) { try { replica.stop(); diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index 6ba793a6ec..fcf26851a2 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -172,6 +172,14 @@ val gameSessionClassesProofJar by tasks.registering(Jar::class) { include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture*.class") } + from("src/main/resources") { + include("redis/lua/game-session-issuer-bootstrap-partition-build.lua") + include("redis/scripts/game-session-issuer-bootstrap-partition-build.json") + include("redis/lua/game-session-issuer-binding-local-add.lua") + include("redis/scripts/game-session-issuer-binding-local-add.json") + include("redis/lua/game-session-issuer-binding-local-release.lua") + include("redis/scripts/game-session-issuer-binding-local-release.json") + } } val gameSessionClassesProof by configurations.creating { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAdmissionAbortSource.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAdmissionAbortSource.java index 68654d14f2..ead226cf5d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAdmissionAbortSource.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAdmissionAbortSource.java @@ -49,8 +49,10 @@ public record CanonicalGameplayAdmissionAbortSource( requireNonNil(orphanCleanupId, "orphanCleanupId"); if (candidate.lifecycle() != CanonicalGameplayBindingInventoryEntry.Lifecycle.TERMINAL_UNRESOLVED - || reservation.lifecycle() - != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING) { + || (reservation.lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING + && reservation.lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED)) { throw new IllegalArgumentException("Aborted source is not retained for exact cleanup"); } } else { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingIssuerIndexObligation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingIssuerIndexObligation.java index 55cd2f72fb..32d54d1032 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingIssuerIndexObligation.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingIssuerIndexObligation.java @@ -11,7 +11,18 @@ public record CanonicalGameplayBindingIssuerIndexObligation( BigInteger bindingGeneration, UUID reservationId, Status status, - BigInteger inventoryRevision) { + BigInteger inventoryRevision, + UUID localReleaseOperationId) { + public CanonicalGameplayBindingIssuerIndexObligation( + UUID transitionId, + CanonicalGameplayBindingRef bindingRef, + BigInteger bindingGeneration, + UUID reservationId, + Status status, + BigInteger inventoryRevision) { + this(transitionId, bindingRef, bindingGeneration, reservationId, status, inventoryRevision, null); + } + public CanonicalGameplayBindingIssuerIndexObligation { requireNonNil(transitionId, "transitionId"); Objects.requireNonNull(bindingRef, "bindingRef"); @@ -19,6 +30,12 @@ public record CanonicalGameplayBindingIssuerIndexObligation( requireNonNil(reservationId, "reservationId"); Objects.requireNonNull(status, "status"); requirePositive(inventoryRevision, "inventoryRevision"); + if ((status == Status.REQUIRED && localReleaseOperationId != null) + || (status == Status.RELEASED + && (localReleaseOperationId == null + || localReleaseOperationId.equals(new UUID(0L, 0L))))) { + throw new IllegalArgumentException("Issuer release linkage must match its obligation status"); + } } private static void requireNonNil(UUID value, String name) { @@ -36,6 +53,7 @@ private static void requirePositive(BigInteger value, String name) { } public enum Status { - REQUIRED + REQUIRED, + RELEASED } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index 0dffa02300..f7a5f53e98 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -7,6 +7,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; @@ -52,6 +53,8 @@ public final class CanonicalGameplayBindingInventoryRepository { "game_session_canonical_binding_account_index_obligation"; private static final String ISSUER_OBLIGATION = "game_session_canonical_binding_issuer_index_obligation"; + private static final String ISSUER_LOCAL_RELEASE = + "game_session_canonical_issuer_binding_local_release_operation"; private static final String REGION_OBLIGATION = "game_session_canonical_binding_region_bridge_obligation"; private static final String GENERATION = "game_session_canonical_binding_generation"; @@ -317,6 +320,14 @@ CanonicalGameplayAdmissionAbortSource readFirstNewAdmissionAbortSource(UUID tran }); } + /** Read-only package seam for the local issuer release owner inside its guarded SQL transaction. */ + static CanonicalGameplayAdmissionAbortSource readFirstNewAdmissionAbortSourceInTransaction( + DSLContext transaction, UUID transitionId, boolean forUpdate) { + Objects.requireNonNull(transaction, "transaction"); + Objects.requireNonNull(transitionId, "transitionId"); + return loadFirstNewAdmissionAbortSource(transaction, transitionId, forUpdate); + } + /** * Commits Account's exact definitive first-NEW abort into the existing transition and retained * candidate/reservation source. The Account RPC is performed by the caller outside this method. @@ -1643,6 +1654,9 @@ private static void requireRetainedFirstNewAbortObligations( BigInteger revision = transition.inventoryRevision(); byte[] bindingRef = transition.bindingRef().bytes(); CanonicalGameplayBindingIdentity candidate = transition.candidate(); + Record candidateRow = + transaction.fetchOne( + "SELECT * FROM " + INVENTORY + " WHERE binding_ref = ?", bindingRef); Record account = transaction.fetchOne( "SELECT * FROM " @@ -1664,7 +1678,8 @@ private static void requireRetainedFirstNewAbortObligations( || !"ADD_OR_RETAIN".equals(account.get("action", String.class)) || !Arrays.equals(bindingRef, account.get("binding_ref", byte[].class)) || !"BEFORE_FINAL_CAS".equals(account.get("execution_phase", String.class)) - || !"REQUIRED".equals(account.get("status", String.class)) + || !("REQUIRED".equals(account.get("status", String.class)) + || "ACKNOWLEDGED".equals(account.get("status", String.class))) || !transition.bindingGeneration() .equals(readBigInteger(account, "binding_generation")) || nullableBigInteger(account, "expected_prior_generation") != null @@ -1673,7 +1688,8 @@ private static void requireRetainedFirstNewAbortObligations( || !candidate.accountId().equals(account.get("account_id", UUID.class)) || !candidate.tenantId().equals(account.get("tenant_id", UUID.class)) || !revision.equals(readBigInteger(account, "inventory_revision")) - || !"REQUIRED".equals(issuer.get("status", String.class)) + || !("REQUIRED".equals(issuer.get("status", String.class)) + || "RELEASED".equals(issuer.get("status", String.class))) || !Arrays.equals(bindingRef, issuer.get("binding_ref", byte[].class)) || !transition.issuerReservationId().equals(issuer.get("reservation_id", UUID.class)) || !transition.bindingGeneration() @@ -1705,6 +1721,178 @@ private static void requireRetainedFirstNewAbortObligations( != 1) { throw conflict("Aborted first-NEW source lost a required retained index obligation"); } + if (candidateRow == null) { + throw conflict("Aborted first-NEW source lost its retained candidate row"); + } + CanonicalGameplayBindingInventoryEntry retainedCandidate = toInventoryEntry(candidateRow); + String accountStatus = account.get("status", String.class); + if ("REQUIRED".equals(accountStatus)) { + if (retainedCandidate.accountIndexState() + != CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED) { + throw conflict("Unacknowledged retained abort has contradictory account-index state"); + } + } else { + Record repair = findMemberRepairOperation(transaction, transitionId, false); + if (repair == null) throw conflict("Retained abort lost its completed account-member repair"); + var acknowledgement = toMemberAcknowledgement(repair); + var operation = acknowledgement.operation(); + var accountObligation = toAccountObligation(account); + requireMemberRepairObligationCurrent(operation, retainedCandidate, accountObligation, true); + BigInteger completedRevision = readBigInteger(repair, "completed_inventory_revision"); + if (retainedCandidate.accountIndexState() + != CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED + || accountObligation.projectionState() + != CanonicalGameplayBindingAccountIndexObligation.ProjectionState.PRESENT_AWAITING_COVERAGE + || !CanonicalGameplayAccountIndexMember.of(retainedCandidate) + .value() + .equals(operation.member()) + || completedRevision.compareTo(operation.inventorySnapshotRevision()) <= 0 + || completedRevision.compareTo(revision) >= 0 + || (accountObligation.projectionState() + == CanonicalGameplayBindingAccountIndexObligation.ProjectionState.PRESENT_AWAITING_COVERAGE + && !accountObligation.projectionMember().equals(operation.member()))) { + throw conflict("Retained abort changed its original completed account-member readback"); + } + Record control = + transaction.fetchOne( + "SELECT * FROM game_session_canonical_account_coverage_control WHERE account_id = ?", + operation.accountId()); + if (control == null + || !"NO_ACTIVE_ACCOUNT_WIDE_FLOW".equals(control.get("state", String.class)) + || !readBigInteger(control, "last_operation_fence").equals(operation.accountControlEpoch())) { + throw conflict("Retained account-member acknowledgement has a different control epoch"); + } + } + + String issuerStatus = issuer.get("status", String.class); + UUID releaseOperationId = issuer.get("local_release_operation_id", UUID.class); + if ("REQUIRED".equals(issuerStatus)) { + if (releaseOperationId != null) { + throw conflict("Pending issuer obligation contains an unearned release operation id"); + } + Record pendingRelease = + transaction.fetchOne( + "SELECT * FROM " + ISSUER_LOCAL_RELEASE + " WHERE transition_id = ?", transitionId); + if (pendingRelease != null + && (!"PENDING_PHYSICAL_PROOF".equals(pendingRelease.get("status", String.class)) + || !revision.equals(readBigInteger(pendingRelease, "source_inventory_revision")))) { + throw conflict("Pending issuer release differs from its retained abort source revision"); + } + } else { + if (releaseOperationId == null + || !CanonicalIssuerPartitionReservation.Lifecycle.RELEASED.equals( + toReservation( + transaction.fetchOne( + "SELECT * FROM " + RESERVATION + " WHERE reservation_id = ?", + transition.issuerReservationId())) + .lifecycle())) { + throw conflict("Released issuer obligation lacks its exact terminal reservation"); + } + requireCompletedIssuerLocalRelease(transaction, transitionId, bindingRef, revision, releaseOperationId); + } + } + + static void requireCompletedIssuerLocalRelease( + DSLContext transaction, + UUID transitionId, + byte[] bindingRef, + BigInteger completionRevision, + UUID releaseOperationId) { + Record release = + transaction.fetchOne( + "SELECT * FROM " + ISSUER_LOCAL_RELEASE + " WHERE operation_id = ? AND transition_id = ?", + releaseOperationId, + transitionId); + if (release == null + || !"RELEASED".equals(release.get("status", String.class)) + || !completionRevision.equals(readBigInteger(release, "completion_inventory_revision")) + || readBigInteger(release, "source_inventory_revision").compareTo(completionRevision) >= 0 + || !Arrays.equals(bindingRef, release.get("binding_ref", byte[].class)) + || !releaseOperationId.equals(release.get("operation_id", UUID.class))) { + throw conflict("Released issuer obligation lacks an exact fresh local-release receipt"); + } + byte[] originalBytes = release.get("original_member_value_bytes", byte[].class); + byte[] releasedBytes = release.get("released_member_value_bytes", byte[].class); + byte[] readbackBytes = release.get("physical_readback_field_set_bytes", byte[].class); + String originalDigest = release.get("original_member_value_digest", String.class); + String releasedDigest = release.get("released_member_value_digest", String.class); + String readbackDigest = release.get("physical_readback_field_set_digest", String.class); + if (originalBytes == null + || releasedBytes == null + || readbackBytes == null + || !CanonicalGameplayIssuerMemberV2Codec.sha256(originalBytes).equals(originalDigest) + || !CanonicalGameplayIssuerMemberV2Codec.sha256(releasedBytes).equals(releasedDigest) + || !CanonicalGameplayIssuerMemberV2Codec.sha256(readbackBytes).equals(readbackDigest)) { + throw conflict("Released issuer receipt contains malformed exact-value digests"); + } + Record original = + transaction.fetchOne( + "SELECT * FROM game_session_canonical_issuer_binding_local_operation" + + " WHERE operation_id = ? AND transition_id = ?", + release.get("original_local_operation_id", UUID.class), + transitionId); + if (original == null + || !Arrays.equals(originalBytes, original.get("member_value_bytes", byte[].class)) + || !Objects.equals(originalDigest, original.get("member_value_digest", String.class)) + || !Objects.equals( + original.get("reservation_id", UUID.class), release.get("reservation_id", UUID.class)) + || !Arrays.equals(original.get("binding_ref", byte[].class), bindingRef)) { + throw conflict("Released issuer receipt no longer retains its immutable original V1034 operation"); + } + CanonicalGameplayIssuerMemberV2Value originalValue; + CanonicalGameplayIssuerMemberV2Value releasedValue; + try { + originalValue = CanonicalGameplayIssuerMemberV2Codec.decode(originalBytes); + releasedValue = CanonicalGameplayIssuerMemberV2Codec.decode(releasedBytes); + } catch (RuntimeException malformed) { + throw conflict("Released issuer receipt contains a malformed schema-v2 member"); + } + BigInteger sourceRevision = readBigInteger(release, "source_inventory_revision"); + BigInteger operationFence = readBigInteger(release, "release_operation_fence"); + BigInteger generation = readBigInteger(release, "release_local_member_generation"); + UUID operationId = release.get("operation_id", UUID.class); + CanonicalGameplayIssuerMemberV2Value expectedValue = + new CanonicalGameplayIssuerMemberV2Value( + originalValue.owner(), + originalValue.bindingGeneration(), + new CanonicalIssuerPartitionReservation( + originalValue.reservation().reservationId(), + originalValue.reservation().owner(), + originalValue.reservation().bindingGeneration(), + originalValue.reservation().transitionId(), + originalValue.reservation().partitionId(), + CanonicalIssuerPartitionReservation.Lifecycle.RELEASED, + originalValue.reservation().reservationFence(), + originalValue.reservation().issuerCoverageOperationId(), + originalValue.reservation().issuerCoverageOperationFence(), + originalValue.reservation().coverageFence(), + originalValue.reservation().inventorySnapshotRevision(), + sourceRevision), + originalValue.anchor(), + new CanonicalGameplayIssuerMemberV2Value.LocalMemberOperation( + operationId, operationFence, generation), + originalValue.issuerControlEpoch(), + originalValue.layoutDescriptor(), + originalValue.sourceCheckpoint(), + originalValue.incarnation()); + if (!expectedValue.equals(releasedValue) + || !operationFence.add(BigInteger.ONE).equals(generation) + || !operationFence.equals(readBigInteger(release, "release_operation_fence"))) { + throw conflict("Released issuer receipt rewrites its original owner or anchor provenance"); + } + Map readback; + try { + readback = CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet(readbackBytes); + } catch (RuntimeException malformed) { + throw conflict("Released issuer receipt contains malformed physical field-set bytes"); + } + String capacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + releasedValue.reservation().reservationId()); + String memberField = new String(bindingRef, java.nio.charset.StandardCharsets.UTF_8); + if (!Arrays.equals(readback.get(capacityField), releasedBytes) || readback.containsKey(memberField)) { + throw conflict("Released issuer receipt lacks its exact positive terminal capacity field"); + } } private static void requireSameFirstNewAdmissionAbortSource( @@ -2304,7 +2492,7 @@ private static void ensureGenerationRow( candidate.characterId()); } - private static BigInteger lockInventoryRevision(DSLContext transaction) { + static BigInteger lockInventoryRevision(DSLContext transaction) { return readBigInteger( Objects.requireNonNull( transaction.fetchOne( @@ -3669,7 +3857,8 @@ private static CanonicalGameplayBindingIssuerIndexObligation toIssuerObligation( row.get("reservation_id", UUID.class), CanonicalGameplayBindingIssuerIndexObligation.Status.valueOf( row.get("status", String.class)), - readBigInteger(row, "inventory_revision")); + readBigInteger(row, "inventory_revision"), + row.get("local_release_operation_id", UUID.class)); } private static CanonicalGameplayBindingRegionBridgeObligation toRegionObligation(Record row) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java index cd32f610be..6100a3bc89 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java @@ -11,6 +11,7 @@ import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; import org.jooq.DSLContext; @@ -96,6 +97,123 @@ CanonicalGameplayIssuerBindingLocalOperation beginOrResumeOrdinaryNew( return result.get(); } + /** Reloads the immutable original registration only from the actual retained Account abort. */ + CanonicalGameplayIssuerBindingLocalOperation readOriginalForIssuerRelease( + CanonicalGameplayAdmissionAbortSource abortSource) { + Objects.requireNonNull(abortSource, "Actual Account-aborted source required"); + requireNoAmbientTransaction(); + if (!abortSource.isAccountAborted() + || (abortSource.reservation().lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING + && abortSource.reservation().lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED)) { + throw conflict("Issuer release requires the actual retained first-NEW Account abort source"); + } + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState = + Objects.requireNonNull( + currentIssuerStateSource.readFreshCurrentState(), + "current issuer state source returned null"); + CanonicalGameplayIssuerBindingLocalOperation operation = + dsl.transactionResult( + configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + // This reader invokes the installed-anchor source loader, whose snapshot contract + // starts with the global inventory clock. Keep the same clock-before-source order + // used by ordinary registration, abort retry, and release completion. + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + Record operationRow = + transaction.fetchOne( + "SELECT * FROM " + + OPERATION + + " WHERE issuer_id = ? AND transition_id = ?", + ISSUER, + abortSource.transition().transitionId()); + if (operationRow == null) { + throw conflict("Account-aborted first-NEW source has no original local issuer operation"); + } + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction( + transaction, currentState); + byte[] exactOriginal = requireBytes(operationRow, "member_value_bytes"); + CanonicalGameplayIssuerMemberV2Value original; + try { + original = CanonicalGameplayIssuerMemberV2Codec.decode(exactOriginal); + } catch (RuntimeException malformed) { + throw conflict("Original local issuer operation is not canonical schema v2"); + } + CanonicalIssuerPartitionReservation reservation = original.reservation(); + var proof = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorPartitionProof( + transaction, anchor, reservation.partitionId()); + AccountControlSnapshot accountControl = + readAndRequireAccountControl( + transaction, + abortSource.candidate().identity().accountId(), + abortSource.transition().accountCoverageEvidence()); + Request request = + new Request( + requireUuid(operationRow, "request_id"), + abortSource.transition().transitionId(), + abortSource.candidate().identity(), + null, + null); + requireSameStoredOperation( + operationRow, + request, + abortSource.transition(), + reservation, + anchor, + proof, + currentState, + accountControl, + true); + CanonicalGameplayIssuerMemberV2Value expected = + createMemberValue( + request.candidate(), + abortSource.transition().bindingGeneration(), + reservation, + anchor, + currentState.incarnation(), + requireUuid(operationRow, "operation_id"), + readPositive(operationRow, "operation_fence"), + readPositive(operationRow, "local_member_generation")); + if (!expected.equals(original) + || !Arrays.equals(exactOriginal, CanonicalGameplayIssuerMemberV2Codec.encode(expected))) { + throw conflict("Original issuer member differs from its exact aborted source or anchor"); + } + try { + return new CanonicalGameplayIssuerBindingLocalOperation( + request, + requireUuid(operationRow, "candidate_account_index_fence"), + abortSource.transition(), + readPositive(operationRow, "local_inventory_snapshot_revision"), + reservation, + anchor, + proof, + expected, + requireUuid(operationRow, "operation_id"), + readPositive(operationRow, "operation_fence"), + readPositive(operationRow, "local_member_generation"), + exactOriginal, + requireText(operationRow, "member_value_digest"), + CanonicalGameplayIssuerBindingLocalOperation.Status.valueOf( + requireText(operationRow, "member_status"))); + } catch (RuntimeException malformed) { + throw conflict("Original local issuer operation metadata is malformed"); + } + }); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState after = + Objects.requireNonNull( + currentIssuerStateSource.readFreshCurrentState(), + "current issuer state source returned null after original-operation read"); + if (!sameCurrentIssuerState(currentState, after)) { + throw conflict("Issuer source or incarnation moved while reloading the original local operation"); + } + return operation; + } + private CanonicalGameplayBindingTransitionRequest resolveTransitionRequestInTransaction( DSLContext transaction, CanonicalGameplayIssuerBindingLocalOperation.Request request, @@ -253,7 +371,7 @@ private CanonicalGameplayIssuerBindingLocalOperation returnOperation( AccountControlSnapshot accountControl, Record row) { requireSameStoredOperation( - row, request, prepared, reservation, anchor, proof, currentState, accountControl); + row, request, prepared, reservation, anchor, proof, currentState, accountControl, false); UUID operationId = requireUuid(row, "operation_id"); BigInteger operationFence = readPositive(row, "operation_fence"); BigInteger localMemberGeneration = readPositive(row, "local_member_generation"); @@ -601,7 +719,7 @@ private static void insertOperation( values); } - private static IssuedCounters allocateLocalCounters( + static IssuedCounters allocateLocalCounters( DSLContext transaction, CanonicalGameplayIssuerInstalledAnchor anchor, CanonicalIssuerPartitionReservation reservation) { @@ -689,7 +807,8 @@ private static void requireSameStoredOperation( CanonicalGameplayIssuerInstalledAnchor anchor, CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof proof, CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState, - AccountControlSnapshot account) { + AccountControlSnapshot account, + boolean allowHistoricalPreparedRevision) { CanonicalGameplayIssuerMemberV2Value storedMemberValue; try { storedMemberValue = @@ -766,8 +885,9 @@ private static void requireSameStoredOperation( AccountControlSnapshot.fromOperation(row, request.candidate().accountId())) || !readPositive(row, "local_inventory_snapshot_revision") .equals(storedMemberValue.reservation().inventoryRevision()) - || !readPositive(row, "local_inventory_snapshot_revision") - .equals(prepared.inventoryRevision()) + || (!allowHistoricalPreparedRevision + && !readPositive(row, "local_inventory_snapshot_revision") + .equals(prepared.inventoryRevision())) || !"ABSENT".equals(requireText(row, "expected_old_member_state")) || !"ABSENT".equals(requireText(row, "expected_old_capacity_state")) || !"PENDING_PHYSICAL_PROOF".equals(requireText(row, "member_status")) @@ -959,7 +1079,7 @@ private static IllegalStateException conflict(String message) { return new IllegalStateException(message); } - private record IssuedCounters(BigInteger operationFence, BigInteger localMemberGeneration) {} + record IssuedCounters(BigInteger operationFence, BigInteger localMemberGeneration) {} private record AccountControlSnapshot( String state, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java index 0bee2ba31c..ddf984dcbf 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java @@ -33,6 +33,8 @@ final class CanonicalGameplayIssuerBindingLocalProjectionRepository { private static final String TRANSITION = "game_session_canonical_binding_transition"; private static final String ISSUER_OBLIGATION = "game_session_canonical_binding_issuer_index_obligation"; + private static final String ISSUER_LOCAL_RELEASE = + "game_session_canonical_issuer_binding_local_release_operation"; private static final String ACCOUNT_CONTROL = "game_session_canonical_account_coverage_control"; private static final String INVENTORY_CLOCK = "game_session_canonical_binding_inventory_clock"; private static final int MAX_LOCAL_OPERATIONS_PER_PARTITION = @@ -125,6 +127,8 @@ private PreparedPartitionWork prepareInTransaction( for (Record row : operationRows) { LocalEntry entry = readLocalEntry(transaction, row, anchor, target); if (!localOperationIds.add(entry.operationId()) + || (!entry.registeredOperationId().equals(entry.operationId()) + && !localOperationIds.add(entry.registeredOperationId())) || !localReservationIds.add(entry.memberValue().reservation().reservationId()) || !localBindingRefs.add( new String( @@ -154,9 +158,9 @@ private PreparedPartitionWork prepareInTransaction( } if (entry.countsTowardCapacity()) localAggregateCapacity = localAggregateCapacity.add(BigInteger.ONE); - if (entry.operationId().equals(target.operationId())) { - if (!Arrays.equals(entry.exactMemberValueBytes(), target.exactMemberValueBytes()) - || !entry.memberValue().equals(target.memberValue()) + if (entry.registeredOperationId().equals(target.operationId())) { + if (!Arrays.equals(entry.exactRegisteredMemberValueBytes(), target.exactMemberValueBytes()) + || !entry.registeredMemberValue().equals(target.memberValue()) || !targetPartition.equals(partitionId)) { throw unavailable("The requested operation differs from its current SQL registration"); } @@ -200,7 +204,7 @@ private PreparedPartitionWork prepareInTransaction( LocalEntry targetEntry = entries.stream() - .filter(entry -> entry.operationId().equals(target.operationId())) + .filter(entry -> entry.registeredOperationId().equals(target.operationId())) .findFirst() .orElseThrow(() -> unavailable("The requested operation disappeared from its SQL set")); Map allowedFields = new HashMap<>(targetBaselineFields); @@ -379,12 +383,15 @@ private LocalEntry readLocalEntry( } CurrentPhase phase = verifyCurrentSourceRows( - row, member, reservationRow, inventoryRow, transitionRow, issuerObligation); + transaction, row, member, reservationRow, inventoryRow, transitionRow, issuerObligation); requireAccountControlCurrent(transaction, row, member.owner().accountId()); return new LocalEntry( operationId, + phase.operationId(), exactValue, + phase.memberValueBytes(), member, + phase.memberValue(), phase.bindingPresent(), phase.countsTowardCapacity(), phase.lifecycle(), @@ -393,6 +400,7 @@ private LocalEntry readLocalEntry( } private static CurrentPhase verifyCurrentSourceRows( + DSLContext transaction, Record operationRow, CanonicalGameplayIssuerMemberV2Value member, Record reservationRow, @@ -408,6 +416,12 @@ private static CurrentPhase verifyCurrentSourceRows( String transitionStatus = text(transitionRow, "status"); String reservationLifecycle = text(reservationRow, "lifecycle"); BigInteger currentReservationRevision = positive(reservationRow, "inventory_revision"); + BigInteger currentRevision = positive(transitionRow, "inventory_revision"); + String issuerStatus = text(issuerObligation, "status"); + UUID releaseOperationId = issuerObligation.get("local_release_operation_id", UUID.class); + if (!"REQUIRED".equals(issuerStatus) && !"RELEASED".equals(issuerStatus)) { + throw unavailable("The current local issuer obligation has an unsupported terminal state"); + } if (!uuid(reservationRow, "reservation_id").equals(original.reservationId()) || !uuid(reservationRow, "transition_id").equals(original.transitionId()) || !uuid(reservationRow, "reservation_fence").equals(original.reservationFence()) @@ -442,8 +456,7 @@ private static CurrentPhase verifyCurrentSourceRows( || transitionRow.get("expected_prior_binding_generation") != null || !bytesEqual(issuerObligation, "binding_ref", owner.bindingRef().bytes()) || !uuid(issuerObligation, "reservation_id").equals(original.reservationId()) - || !positive(issuerObligation, "binding_generation").equals(member.bindingGeneration()) - || !"REQUIRED".equals(text(issuerObligation, "status"))) { + || !positive(issuerObligation, "binding_generation").equals(member.bindingGeneration())) { throw unavailable( "The actual V29 issuer transition no longer matches its immutable local operation"); } @@ -455,31 +468,75 @@ private static CurrentPhase verifyCurrentSourceRows( boolean bindingPresent; boolean counted; + UUID projectedOperationId = uuid(operationRow, "operation_id"); + byte[] projectedBytes = bytes(operationRow, "member_value_bytes"); + CanonicalGameplayIssuerMemberV2Value projectedMember = member; if ("PREPARED".equals(transitionStatus) && "CANDIDATE_PREPARED".equals(candidateLifecycle) - && "RESERVED".equals(reservationLifecycle)) { + && "RESERVED".equals(reservationLifecycle) + && "REQUIRED".equals(issuerStatus) + && releaseOperationId == null) { bindingPresent = false; counted = true; } else if ("PROVISIONAL".equals(transitionStatus) && "PROVISIONAL".equals(candidateLifecycle) - && "RESERVED".equals(reservationLifecycle)) { + && "RESERVED".equals(reservationLifecycle) + && "REQUIRED".equals(issuerStatus) + && releaseOperationId == null) { bindingPresent = true; counted = true; } else if ("COMMITTED".equals(transitionStatus) && "ACTIVE".equals(candidateLifecycle) - && "BOUND".equals(reservationLifecycle)) { + && "BOUND".equals(reservationLifecycle) + && "REQUIRED".equals(issuerStatus) + && releaseOperationId == null) { + bindingPresent = true; + counted = true; + } else if ("ABORTED".equals(transitionStatus) + && "TERMINAL_UNRESOLVED".equals(candidateLifecycle) + && "RELEASE_PENDING".equals(reservationLifecycle) + && "REQUIRED".equals(issuerStatus) + && releaseOperationId == null) { + CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.readProjection( + transaction, + operationRow, + member, + currentRevision, + transitionStatus, + candidateLifecycle, + reservationLifecycle, + issuerStatus, + releaseOperationId); bindingPresent = true; counted = true; + } else if ("ABORTED".equals(transitionStatus) + && "TERMINAL_UNRESOLVED".equals(candidateLifecycle) + && "RELEASED".equals(reservationLifecycle) + && "RELEASED".equals(issuerStatus) + && releaseOperationId != null) { + var release = CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.readProjection( + transaction, + operationRow, + member, + currentRevision, + transitionStatus, + candidateLifecycle, + reservationLifecycle, + issuerStatus, + releaseOperationId); + if (release == null) throw unavailable("Released issuer reservation lacks its durable exact successor"); + projectedOperationId = release.operationId(); + projectedBytes = release.exactMemberValueBytes(); + projectedMember = release.memberValue(); + bindingPresent = false; + counted = false; } else { throw unavailable( "The current SQL transition phase does not qualify an issuer reservation/member projection"); } - if (!positive(inventoryRow, "inventory_revision") - .equals(positive(transitionRow, "inventory_revision")) - || !positive(issuerObligation, "inventory_revision") - .equals(positive(transitionRow, "inventory_revision")) - || !positive(reservationRow, "inventory_revision") - .equals(positive(transitionRow, "inventory_revision"))) { + if (!positive(inventoryRow, "inventory_revision").equals(currentRevision) + || !positive(issuerObligation, "inventory_revision").equals(currentRevision) + || !positive(reservationRow, "inventory_revision").equals(currentRevision)) { throw unavailable( "The V29 candidate, reservation, and issuer obligation revisions are not one current transition"); } @@ -488,7 +545,10 @@ private static CurrentPhase verifyCurrentSourceRows( counted, reservationLifecycle, transitionStatus, - positive(transitionRow, "inventory_revision")); + currentRevision, + projectedOperationId, + projectedBytes, + projectedMember); } private static void requireOwnerColumns( @@ -898,6 +958,10 @@ private static byte[] currentnessDigest( for (LocalEntry entry : entries.stream().sorted(Comparator.comparing(LocalEntry::operationId)).toList()) { update(digest, entry.operationId().toString().getBytes(StandardCharsets.US_ASCII)); + update( + digest, + entry.registeredOperationId().toString().getBytes(StandardCharsets.US_ASCII)); + update(digest, entry.exactRegisteredMemberValueBytes()); update(digest, entry.exactMemberValueBytes()); update(digest, entry.transitionStatus().getBytes(StandardCharsets.US_ASCII)); update(digest, entry.lifecycle().getBytes(StandardCharsets.US_ASCII)); @@ -998,11 +1062,17 @@ private record CurrentPhase( boolean countsTowardCapacity, String lifecycle, String transitionStatus, - BigInteger inventoryRevision) {} + BigInteger inventoryRevision, + UUID operationId, + byte[] memberValueBytes, + CanonicalGameplayIssuerMemberV2Value memberValue) {} record LocalEntry( + UUID registeredOperationId, UUID operationId, + byte[] exactRegisteredMemberValueBytes, byte[] exactMemberValueBytes, + CanonicalGameplayIssuerMemberV2Value registeredMemberValue, CanonicalGameplayIssuerMemberV2Value memberValue, boolean bindingPresent, boolean countsTowardCapacity, @@ -1010,9 +1080,15 @@ record LocalEntry( String transitionStatus, BigInteger inventoryRevision) { LocalEntry { + exactRegisteredMemberValueBytes = exactRegisteredMemberValueBytes.clone(); exactMemberValueBytes = exactMemberValueBytes.clone(); } + @Override + public byte[] exactRegisteredMemberValueBytes() { + return exactRegisteredMemberValueBytes.clone(); + } + @Override public byte[] exactMemberValueBytes() { return exactMemberValueBytes.clone(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java index 811f6627f2..3560bc6560 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java @@ -108,6 +108,9 @@ public Readback projectAndRead(CanonicalGameplayIssuerBindingLocalOperation oper requireNoAmbientTransaction(); var work = projectionRepository.readPreparedPartitionWork(operation); requireFreshCurrentState(work); + if (!work.targetEntry().operationId().equals(operation.operationId())) { + throw unavailable(); + } RedisScriptDescriptor descriptor = requireDescriptor(); byte[] script = scriptSource(descriptor); byte[] key = exactPartitionKey(work); @@ -519,6 +522,10 @@ public CanonicalGameplayIssuerBindingLocalOperation operation() { return operation; } + public UUID operationId() { + return operation.operationId(); + } + public long scriptOutcome() { return scriptOutcome; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperation.java new file mode 100644 index 0000000000..4755ea086f --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperation.java @@ -0,0 +1,244 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; + +/** SQL-issued exact terminal successor for one retained first-NEW issuer reservation. */ +public final class CanonicalGameplayIssuerBindingLocalReleaseOperation { + public enum Status { + PENDING_PHYSICAL_PROOF, + RELEASED + } + + private final CanonicalGameplayAdmissionAbortSource abortSource; + private final CanonicalGameplayIssuerBindingLocalOperation originalOperation; + private final UUID operationId; + private final BigInteger operationFence; + private final BigInteger localMemberGeneration; + private final BigInteger sourceInventoryRevision; + private final BigInteger completionInventoryRevision; + private final CanonicalGameplayIssuerMemberV2Value releasedMemberValue; + private final byte[] exactOriginalMemberValueBytes; + private final byte[] exactReleasedMemberValueBytes; + private final byte[] exactPhysicalReadbackFieldSetBytes; + private final String physicalReadbackDigest; + private final Status status; + + CanonicalGameplayIssuerBindingLocalReleaseOperation( + CanonicalGameplayAdmissionAbortSource abortSource, + CanonicalGameplayIssuerBindingLocalOperation originalOperation, + UUID operationId, + BigInteger operationFence, + BigInteger localMemberGeneration, + BigInteger sourceInventoryRevision, + BigInteger completionInventoryRevision, + CanonicalGameplayIssuerMemberV2Value releasedMemberValue, + byte[] exactOriginalMemberValueBytes, + byte[] exactReleasedMemberValueBytes, + byte[] exactPhysicalReadbackFieldSetBytes, + String physicalReadbackDigest, + Status status) { + this.abortSource = Objects.requireNonNull(abortSource, "Account-aborted source required"); + this.originalOperation = Objects.requireNonNull(originalOperation, "Original SQL operation required"); + this.operationId = requireNonNil(operationId, "operationId"); + this.operationFence = requirePositive(operationFence, "operationFence"); + this.localMemberGeneration = requirePositive(localMemberGeneration, "localMemberGeneration"); + this.sourceInventoryRevision = requirePositive(sourceInventoryRevision, "sourceInventoryRevision"); + this.completionInventoryRevision = + completionInventoryRevision == null + ? null + : requirePositive(completionInventoryRevision, "completionInventoryRevision"); + this.releasedMemberValue = Objects.requireNonNull(releasedMemberValue, "releasedMemberValue"); + this.exactOriginalMemberValueBytes = copyBounded(exactOriginalMemberValueBytes, "original bytes"); + this.exactReleasedMemberValueBytes = copyBounded(exactReleasedMemberValueBytes, "released bytes"); + this.exactPhysicalReadbackFieldSetBytes = + exactPhysicalReadbackFieldSetBytes == null + ? null + : exactPhysicalReadbackFieldSetBytes.clone(); + this.physicalReadbackDigest = physicalReadbackDigest; + this.status = Objects.requireNonNull(status, "status"); + + CanonicalGameplayIssuerMemberV2Value original = originalOperation.memberValue(); + CanonicalIssuerPartitionReservation sourceReservation = abortSource.reservation(); + CanonicalIssuerPartitionReservation releasedReservation = releasedMemberValue.reservation(); + CanonicalGameplayIssuerMemberV2Value expectedReleased = + new CanonicalGameplayIssuerMemberV2Value( + original.owner(), + original.bindingGeneration(), + new CanonicalIssuerPartitionReservation( + original.reservation().reservationId(), + original.reservation().owner(), + original.reservation().bindingGeneration(), + original.reservation().transitionId(), + original.reservation().partitionId(), + CanonicalIssuerPartitionReservation.Lifecycle.RELEASED, + original.reservation().reservationFence(), + original.reservation().issuerCoverageOperationId(), + original.reservation().issuerCoverageOperationFence(), + original.reservation().coverageFence(), + original.reservation().inventorySnapshotRevision(), + sourceInventoryRevision), + original.anchor(), + new CanonicalGameplayIssuerMemberV2Value.LocalMemberOperation( + operationId, operationFence, localMemberGeneration), + original.issuerControlEpoch(), + original.layoutDescriptor(), + original.sourceCheckpoint(), + original.incarnation()); + + if (!abortSource.isAccountAborted() + || abortSource.transition().status() + != net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot.Status.ABORTED + || abortSource.candidate().lifecycle() + != net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry.Lifecycle.TERMINAL_UNRESOLVED + || !abortSource.transition().transitionId().equals(originalOperation.request().transitionId()) + || !sourceReservation.reservationId().equals(original.reservation().reservationId()) + || !sourceReservation.transitionId().equals(original.reservation().transitionId()) + || !sourceReservation.owner().equals(original.owner()) + || !sourceReservation.bindingGeneration().equals(original.bindingGeneration()) + || !sourceReservation.reservationFence().equals(original.reservation().reservationFence()) + || !sourceReservation.issuerCoverageOperationId().equals(original.reservation().issuerCoverageOperationId()) + || !sourceReservation.issuerCoverageOperationFence().equals(original.reservation().issuerCoverageOperationFence()) + || !sourceReservation.coverageFence().equals(original.reservation().coverageFence()) + || !sourceReservation.inventorySnapshotRevision().equals(original.reservation().inventorySnapshotRevision()) + || (status == Status.PENDING_PHYSICAL_PROOF + && (sourceReservation.lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING + || !sourceReservation.inventoryRevision().equals(sourceInventoryRevision) + || this.completionInventoryRevision != null)) + || (status == Status.RELEASED + && (sourceReservation.lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED + || this.completionInventoryRevision == null + || !sourceReservation.inventoryRevision().equals(this.completionInventoryRevision) + || this.completionInventoryRevision.compareTo(sourceInventoryRevision) <= 0)) + || !operationId.equals(releasedMemberValue.memberOperation().operationId()) + || !operationFence.equals(releasedMemberValue.memberOperation().operationFence()) + || !localMemberGeneration.equals(releasedMemberValue.memberOperation().coverageGeneration()) + || !expectedReleased.equals(releasedMemberValue) + || !Arrays.equals( + this.exactOriginalMemberValueBytes, + originalOperation.exactMemberValueBytes()) + || !Arrays.equals( + this.exactOriginalMemberValueBytes, + CanonicalGameplayIssuerMemberV2Codec.encode(original)) + || !Arrays.equals( + this.exactReleasedMemberValueBytes, + CanonicalGameplayIssuerMemberV2Codec.encode(expectedReleased)) + || operationId.equals(originalOperation.operationId()) + || operationFence.compareTo(originalOperation.operationFence()) <= 0 + || localMemberGeneration.compareTo(originalOperation.localMemberGeneration()) <= 0 + || !operationFence.add(BigInteger.ONE).equals(localMemberGeneration)) { + throw new IllegalArgumentException("Release operation differs from its exact Account-aborted source"); + } + + if (status == Status.PENDING_PHYSICAL_PROOF) { + if (this.exactPhysicalReadbackFieldSetBytes != null || physicalReadbackDigest != null) { + throw new IllegalArgumentException("Pending release cannot contain physical completion proof"); + } + } else { + if (this.exactPhysicalReadbackFieldSetBytes == null + || this.exactPhysicalReadbackFieldSetBytes.length == 0 + || this.exactPhysicalReadbackFieldSetBytes.length > 17_825_792 + || physicalReadbackDigest == null + || !physicalReadbackDigest.equals( + CanonicalGameplayIssuerMemberV2Codec.sha256(this.exactPhysicalReadbackFieldSetBytes))) { + throw new IllegalArgumentException("Released operation lacks its exact physical readback proof"); + } + Map readback = + CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( + this.exactPhysicalReadbackFieldSetBytes); + String capacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + releasedReservation.reservationId()); + String bindingField = + new String(releasedMemberValue.owner().bindingRef().bytes(), StandardCharsets.UTF_8); + if (!Arrays.equals(readback.get(capacityField), this.exactReleasedMemberValueBytes) + || readback.containsKey(bindingField)) { + throw new IllegalArgumentException("Released proof does not contain its exact terminal capacity postimage"); + } + } + } + + public CanonicalGameplayAdmissionAbortSource abortSource() { + return abortSource; + } + + CanonicalGameplayIssuerBindingLocalOperation originalOperation() { + return originalOperation; + } + + public UUID originalOperationId() { + return originalOperation.operationId(); + } + + public UUID operationId() { + return operationId; + } + + public BigInteger operationFence() { + return operationFence; + } + + public BigInteger localMemberGeneration() { + return localMemberGeneration; + } + + public BigInteger sourceInventoryRevision() { + return sourceInventoryRevision; + } + + public BigInteger completionInventoryRevision() { + return completionInventoryRevision; + } + + public CanonicalGameplayIssuerMemberV2Value releasedMemberValue() { + return releasedMemberValue; + } + + public byte[] exactOriginalMemberValueBytes() { + return exactOriginalMemberValueBytes.clone(); + } + + public byte[] exactReleasedMemberValueBytes() { + return exactReleasedMemberValueBytes.clone(); + } + + public byte[] exactPhysicalReadbackFieldSetBytes() { + return exactPhysicalReadbackFieldSetBytes == null + ? null + : exactPhysicalReadbackFieldSetBytes.clone(); + } + + public String physicalReadbackDigest() { + return physicalReadbackDigest; + } + + public Status status() { + return status; + } + + private static byte[] copyBounded(byte[] value, String name) { + Objects.requireNonNull(value, name); + if (value.length == 0 || value.length > CanonicalGameplayIssuerMemberV2Codec.MAX_VALUE_BYTES) { + throw new IllegalArgumentException("Exact " + name + " are outside the schema-v2 bound"); + } + return value.clone(); + } + + private static UUID requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) throw new IllegalArgumentException(name + " must not be nil"); + return value; + } + + private static BigInteger requirePositive(BigInteger value, String name) { + Objects.requireNonNull(value, name); + if (value.signum() <= 0) throw new IllegalArgumentException(name + " must be positive"); + return value; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.java new file mode 100644 index 0000000000..fafc30b2f6 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.java @@ -0,0 +1,836 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** SQL owner for one immutable, source-linked physical terminal release successor. */ +final class CanonicalGameplayIssuerBindingLocalReleaseOperationRepository { + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String RELEASE = "game_session_canonical_issuer_binding_local_release_operation"; + private static final String RESERVATION = "game_session_canonical_issuer_partition_reservation"; + private static final String INVENTORY = "game_session_canonical_gameplay_binding_inventory"; + private static final String TRANSITION = "game_session_canonical_binding_transition"; + private static final String ISSUER_OBLIGATION = "game_session_canonical_binding_issuer_index_obligation"; + private static final String ACCOUNT_OBLIGATION = "game_session_canonical_binding_account_index_obligation"; + private static final String REGION_OBLIGATION = "game_session_canonical_binding_region_bridge_obligation"; + private static final String INVENTORY_CLOCK = "game_session_canonical_binding_inventory_clock"; + + private final DSLContext dsl; + private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource currentIssuerStateSource; + private final CanonicalGameplayBindingInventoryRepository inventoryRepository; + private final CanonicalGameplayIssuerBindingLocalOperationRepository localOperationRepository; + + CanonicalGameplayIssuerBindingLocalReleaseOperationRepository(DSLContext dsl, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource currentIssuerStateSource) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.currentIssuerStateSource = Objects.requireNonNull(currentIssuerStateSource, "currentIssuerStateSource"); + this.inventoryRepository = new CanonicalGameplayBindingInventoryRepository(dsl); + this.localOperationRepository = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, currentIssuerStateSource); + } + + /** Creates one SQL operation only from the current durable Account-aborted source. */ + CanonicalGameplayIssuerBindingLocalReleaseOperation prepareOrResume(UUID transitionId) { + Objects.requireNonNull(transitionId, "transitionId"); + requireNoAmbientTransaction(); + var sourceBefore = inventoryRepository.readFirstNewAdmissionAbortSource(transitionId); + requireAbortedSource(sourceBefore); + var issuerStateBefore = readCurrentIssuerState(); + var original = localOperationRepository.readOriginalForIssuerRelease(sourceBefore); + var operation = dsl.transactionResult(configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + BigInteger currentRevision = CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + var source = CanonicalGameplayBindingInventoryRepository + .readFirstNewAdmissionAbortSourceInTransaction(transaction, transitionId, true); + requireSameAbortSource(sourceBefore, source); + Record existing = transaction.fetchOne("SELECT * FROM " + RELEASE + " WHERE transition_id = ? FOR UPDATE", transitionId); + if (existing != null) return readOperation(existing, source, original); + if (source.reservation().lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING + || !sameOperationSource(original, source)) { + throw conflict("Issuer release requires its exact pending local registration"); + } + BigInteger priorRevision = source.transition().inventoryRevision(); + if (currentRevision.compareTo(priorRevision) < 0) { + throw conflict("Inventory clock regressed behind the retained Account-abort source"); + } + BigInteger sourceRevision = currentRevision.add(BigInteger.ONE); + requireCounterLimit(sourceRevision, "releasePreparationInventoryRevision"); + advanceAbortSourceRevision(transaction, source, priorRevision, sourceRevision, currentRevision); + source = CanonicalGameplayBindingInventoryRepository + .readFirstNewAdmissionAbortSourceInTransaction(transaction, transitionId, false); + var counters = CanonicalGameplayIssuerBindingLocalOperationRepository.allocateLocalCounters( + transaction, original.anchor(), + withLifecycleAndRevision(original.reservation(), + CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING, sourceRevision)); + UUID releaseId = freshNonNilUuid(); + var releasedValue = createReleasedValue(original.memberValue(), sourceRevision, releaseId, + counters.operationFence(), counters.localMemberGeneration()); + byte[] releasedBytes = CanonicalGameplayIssuerMemberV2Codec.encode(releasedValue); + byte[] originalBytes = original.exactMemberValueBytes(); + insertRelease(transaction, source, original, releaseId, counters.operationFence(), + counters.localMemberGeneration(), sourceRevision, originalBytes, releasedBytes); + Record saved = transaction.fetchOne("SELECT * FROM " + RELEASE + " WHERE operation_id = ? FOR UPDATE", releaseId); + if (saved == null) throw conflict("Issuer release operation was not retained"); + return readOperation(saved, source, original); + }); + requireSameCurrentIssuerState(issuerStateBefore, readCurrentIssuerState()); + requireSameAbortIdentity(sourceBefore, inventoryRepository.readFirstNewAdmissionAbortSource(transitionId)); + return operation; + } + + /** Completes only the exact private physical-owner readback and returns its durable receipt. */ + CanonicalGameplayIssuerBindingLocalReleaseOperation completeWithReadback( + CanonicalGameplayIssuerBindingLocalReleaseOperation expected, + CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.Readback readback) { + Objects.requireNonNull(expected, "expected"); + Objects.requireNonNull(readback, "readback"); + requireNoAmbientTransaction(); + if (!expected.operationId().equals(readback.operationId())) { + throw conflict("Issuer release readback belongs to a different SQL operation"); + } + byte[] readbackBytes = readback.exactPhysicalFieldSetBytes(); + String readbackDigest = CanonicalGameplayIssuerMemberV2Codec.sha256(readbackBytes); + var issuerStateBefore = readCurrentIssuerState(); + var completed = dsl.transactionResult(configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + BigInteger currentRevision = + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + UUID transitionId = expected.abortSource().transition().transitionId(); + var source = CanonicalGameplayBindingInventoryRepository + .readFirstNewAdmissionAbortSourceInTransaction(transaction, transitionId, true); + requireExactReleaseSource(expected, source); + Record releaseRow = + transaction.fetchOne("SELECT * FROM " + RELEASE + " WHERE operation_id = ? FOR UPDATE", + expected.operationId()); + if (releaseRow == null) throw conflict("SQL issuer release operation disappeared"); + var current = readOperation(releaseRow, source, expected.originalOperation()); + requireSameOperation(expected, current); + if (current.status() == CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED) { + verifyReadbackMatchesOperation(current, readbackBytes, readbackDigest); + return current; + } + if (source.reservation().lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING) { + throw conflict("Pending issuer release no longer has its exact RELEASE_PENDING source"); + } + if (currentRevision.compareTo(current.sourceInventoryRevision()) < 0) { + throw conflict("Inventory clock regressed behind the durable issuer release preparation"); + } + verifyReadbackMatchesOperation(current, readbackBytes, readbackDigest); + BigInteger completionRevision = currentRevision.add(BigInteger.ONE); + requireCounterLimit(completionRevision, "completionInventoryRevision"); + requireOne(transaction.execute( + "UPDATE " + RELEASE + + " SET status = 'RELEASED', physical_readback_field_set_bytes = ?," + + " physical_readback_field_set_digest = ?, completion_inventory_revision = ?," + + " completed_at = CURRENT_TIMESTAMP WHERE operation_id = ?" + + " AND status = 'PENDING_PHYSICAL_PROOF' AND source_inventory_revision = ?", + readbackBytes, readbackDigest, decimal(completionRevision), current.operationId(), + decimal(current.sourceInventoryRevision())), + "Issuer release completion lost its guarded SQL operation compare-and-set"); + requireOne(transaction.execute( + "UPDATE " + ISSUER_OBLIGATION + + " SET status = 'RELEASED', local_release_operation_id = ?, inventory_revision = ?" + + " WHERE transition_id = ? AND binding_ref = ? AND reservation_id = ?" + + " AND status = 'REQUIRED' AND local_release_operation_id IS NULL" + + " AND inventory_revision = ?", + current.operationId(), decimal(completionRevision), transitionId, + source.transition().bindingRef().bytes(), source.reservation().reservationId(), + decimal(current.sourceInventoryRevision())), + "Physical issuer release lost its exact local V29 obligation compare-and-set"); + requireOne(transaction.execute( + "UPDATE " + RESERVATION + " SET lifecycle = 'RELEASED', inventory_revision = ?" + + " WHERE reservation_id = ? AND transition_id = ? AND lifecycle = 'RELEASE_PENDING'" + + " AND inventory_revision = ? AND binding_ref = ? AND binding_generation = ?" + + " AND reservation_fence = ? AND issuer_coverage_operation_id = ?" + + " AND issuer_coverage_operation_fence = ? AND coverage_fence = ?" + + " AND inventory_snapshot_revision = ? AND account_id = ? AND tenant_id = ?" + + " AND playable_state_namespace_id = ? AND character_id = ?" + + " AND game_instance_id = ? AND runtime_game_instance_id = ? AND session_id = ?" + + " AND region_id = ? AND region_epoch = ? AND issuer_id = ? AND issuer_auth_generation = ?", + decimal(completionRevision), source.reservation().reservationId(), transitionId, + decimal(current.sourceInventoryRevision()), source.transition().bindingRef().bytes(), + decimal(source.transition().bindingGeneration()), source.reservation().reservationFence(), + source.reservation().issuerCoverageOperationId(), + decimal(source.reservation().issuerCoverageOperationFence()), + decimal(source.reservation().coverageFence()), + decimal(source.reservation().inventorySnapshotRevision()), + source.candidate().identity().accountId(), source.candidate().identity().tenantId(), + source.candidate().identity().playableStateNamespaceId(), + source.candidate().identity().characterId(), source.candidate().identity().gameInstanceId(), + source.candidate().identity().runtimeGameInstanceId(), source.candidate().identity().sessionId(), + source.candidate().identity().regionId(), decimal(source.candidate().identity().regionEpoch()), + source.candidate().identity().issuerId(), + decimal(source.candidate().identity().issuerAuthGeneration())), + "Issuer release lost its exact original reservation compare-and-set"); + requireOne(transaction.execute( + "UPDATE " + INVENTORY + " SET inventory_revision = ?" + + " WHERE binding_ref = ? AND transition_id = ?" + + " AND lifecycle = 'TERMINAL_UNRESOLVED' AND inventory_revision = ?" + + " AND binding_generation = ? AND issuer_reservation_id = ?", + decimal(completionRevision), source.transition().bindingRef().bytes(), transitionId, + decimal(current.sourceInventoryRevision()), decimal(source.transition().bindingGeneration()), + source.reservation().reservationId()), + "Issuer release lost its retained unresolved candidate compare-and-set"); + requireOne(transaction.execute( + "UPDATE " + TRANSITION + " SET inventory_revision = ?" + + " WHERE transition_id = ? AND status = 'ABORTED'" + + " AND admission_orphan_cleanup_id = ? AND inventory_revision = ?" + + " AND candidate_binding_ref = ? AND candidate_binding_generation = ?" + + " AND issuer_reservation_id = ?", + decimal(completionRevision), transitionId, source.orphanCleanupId(), + decimal(current.sourceInventoryRevision()), source.transition().bindingRef().bytes(), + decimal(source.transition().bindingGeneration()), source.reservation().reservationId()), + "Issuer release lost its immutable Account-abort source revision compare-and-set"); + requireOne(transaction.execute( + "UPDATE " + ACCOUNT_OBLIGATION + " SET inventory_revision = ?" + + " WHERE transition_id = ? AND inventory_revision = ?", + decimal(completionRevision), transitionId, decimal(current.sourceInventoryRevision())), + "Issuer release lost its retained Account obligation revision compare-and-set"); + requireOne(transaction.execute( + "UPDATE " + REGION_OBLIGATION + " SET inventory_revision = ?" + + " WHERE transition_id = ? AND inventory_revision = ?", + decimal(completionRevision), transitionId, decimal(current.sourceInventoryRevision())), + "Issuer release lost its retained region obligation revision compare-and-set"); + requireOne(transaction.execute( + "UPDATE " + INVENTORY_CLOCK + " SET inventory_revision = ?" + + " WHERE singleton_id = 1 AND inventory_revision = ?", + decimal(completionRevision), decimal(currentRevision)), + "Issuer release lost the current inventory-clock compare-and-set"); + var completedSource = CanonicalGameplayBindingInventoryRepository + .readFirstNewAdmissionAbortSourceInTransaction(transaction, transitionId, false); + Record completedRow = transaction.fetchOne( + "SELECT * FROM " + RELEASE + " WHERE operation_id = ?", expected.operationId()); + if (completedRow == null) throw conflict("Released issuer operation disappeared after completion"); + return readOperation(completedRow, completedSource, expected.originalOperation()); + }); + requireSameCurrentIssuerState(issuerStateBefore, readCurrentIssuerState()); + CanonicalGameplayAdmissionAbortSource sourceAfter = inventoryRepository.readFirstNewAdmissionAbortSource( + completed.abortSource().transition().transitionId()); + if (!completed.abortSource().equals(sourceAfter)) { + throw conflict("Completed issuer release source changed after its guarded SQL receipt"); + } + return completed; + } + + private CanonicalGameplayIssuerBindingLocalReleaseOperation readOperation( + Record row, + CanonicalGameplayAdmissionAbortSource source, + CanonicalGameplayIssuerBindingLocalOperation original) { + if (!ISSUER.equals(text(row, "issuer_id")) + || !uuid(row, "transition_id").equals(source.transition().transitionId()) + || !uuid(row, "orphan_cleanup_id").equals(source.orphanCleanupId()) + || !uuid(row, "reservation_id").equals(source.reservation().reservationId()) + || !uuid(row, "original_local_operation_id").equals(original.operationId()) + || !Arrays.equals(bytes(row, "binding_ref"), source.transition().bindingRef().bytes()) + || !positive(row, "binding_generation").equals(source.transition().bindingGeneration()) + || !nonnegative(row, "partition_id").equals(source.reservation().partitionId()) + || !uuid(row, "original_reservation_fence").equals(original.reservation().reservationFence()) + || !uuid(row, "original_issuer_coverage_operation_id").equals(original.reservation().issuerCoverageOperationId()) + || !positive(row, "original_issuer_coverage_operation_fence").equals(original.reservation().issuerCoverageOperationFence()) + || !positive(row, "original_coverage_fence").equals(original.reservation().coverageFence()) + || !positive(row, "original_inventory_snapshot_revision").equals(original.reservation().inventorySnapshotRevision()) + || !positive(row, "original_reservation_inventory_revision").equals(original.reservation().inventoryRevision()) + || !positive(row, "original_local_operation_fence").equals(original.operationFence()) + || !positive(row, "original_local_member_generation").equals(original.localMemberGeneration()) + || !uuid(row, "anchor_issuer_coverage_operation_id").equals(original.anchor().issuerCoverageOperationId()) + || !positive(row, "anchor_operation_fence").equals(original.anchor().operationFence()) + || !positive(row, "anchor_coverage_fence").equals(original.anchor().coverageFence()) + || !positive(row, "anchor_inventory_snapshot_revision").equals(original.anchor().issuerInventorySnapshotRevision()) + || !Arrays.equals(bytes(row, "original_member_value_bytes"), original.exactMemberValueBytes()) + || !text(row, "original_member_value_digest").equals(original.memberValueDigest()) + || !text(row, "original_member_value_digest").equals( + CanonicalGameplayIssuerMemberV2Codec.sha256(bytes(row, "original_member_value_bytes"))) + || !text(row, "released_member_value_digest").equals( + CanonicalGameplayIssuerMemberV2Codec.sha256(bytes(row, "released_member_value_bytes")))) { + throw conflict("Stored issuer release differs from its immutable original registration or abort source"); + } + UUID operationId = uuid(row, "operation_id"); + BigInteger sourceRevision = positive(row, "source_inventory_revision"); + CanonicalGameplayIssuerMemberV2Value releasedValue; + try { + releasedValue = CanonicalGameplayIssuerMemberV2Codec.decode(bytes(row, "released_member_value_bytes")); + } catch (RuntimeException malformed) { + throw conflict("Stored issuer release postimage is not canonical schema v2"); + } + CanonicalGameplayIssuerBindingLocalReleaseOperation.Status status; + try { + status = CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.valueOf(text(row, "status")); + } catch (RuntimeException malformed) { + throw conflict("Stored issuer release status is malformed"); + } + byte[] physicalReadback = optionalBytes(row, "physical_readback_field_set_bytes"); + String physicalDigest = row.get("physical_readback_field_set_digest", String.class); + BigInteger completionRevision = nullablePositive(row, "completion_inventory_revision"); + if ((status == CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.PENDING_PHYSICAL_PROOF + && (source.reservation().lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING + || !source.reservation().inventoryRevision().equals(sourceRevision))) + || (status == CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED + && (source.reservation().lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED + || !Objects.equals(source.reservation().inventoryRevision(), completionRevision) + || completionRevision == null + || completionRevision.compareTo(sourceRevision) <= 0))) { + throw conflict("Stored issuer release phase differs from its current V29 reservation"); + } + try { + return new CanonicalGameplayIssuerBindingLocalReleaseOperation( + source, + original, + operationId, + positive(row, "release_operation_fence"), + positive(row, "release_local_member_generation"), + sourceRevision, + completionRevision, + releasedValue, + bytes(row, "original_member_value_bytes"), + bytes(row, "released_member_value_bytes"), + physicalReadback, + physicalDigest, + status); + } catch (RuntimeException malformed) { + throw conflict("Stored SQL issuer release operation is malformed"); + } + } + + /** Read-only physical postimage used by ordinary partition readers after verified completion. */ + static ReleaseProjection readProjection( + DSLContext transaction, + Record originalOperationRow, + CanonicalGameplayIssuerMemberV2Value originalValue, + BigInteger currentInventoryRevision, + String currentTransitionStatus, + String currentCandidateLifecycle, + String currentReservationLifecycle, + String currentIssuerObligationStatus, + UUID currentReleaseOperationId) { + UUID originalOperationId = uuid(originalOperationRow, "operation_id"); + Record row = + transaction.fetchOne( + "SELECT * FROM " + RELEASE + " WHERE original_local_operation_id = ?", + originalOperationId); + if (row == null) return null; + byte[] originalBytes = bytes(row, "original_member_value_bytes"); + byte[] releasedBytes = bytes(row, "released_member_value_bytes"); + BigInteger sourceRevision = positive(row, "source_inventory_revision"); + UUID releaseId = uuid(row, "operation_id"); + String status = text(row, "status"); + Record transition = + transaction.fetchOne( + "SELECT admission_orphan_cleanup_id, candidate_binding_ref," + + " candidate_binding_generation FROM " + TRANSITION + " WHERE transition_id = ?", + uuid(row, "transition_id")); + if (!originalOperationId.equals(uuid(row, "original_local_operation_id")) + || !uuid(row, "transition_id").equals(uuid(originalOperationRow, "transition_id")) + || !uuid(row, "reservation_id").equals(originalValue.reservation().reservationId()) + || !Arrays.equals(bytes(row, "binding_ref"), originalValue.owner().bindingRef().bytes()) + || !positive(row, "binding_generation").equals(originalValue.bindingGeneration()) + || !nonnegative(row, "partition_id").equals(originalValue.reservation().partitionId()) + || !uuid(row, "original_reservation_fence").equals(originalValue.reservation().reservationFence()) + || !uuid(row, "original_issuer_coverage_operation_id") + .equals(originalValue.reservation().issuerCoverageOperationId()) + || !positive(row, "original_issuer_coverage_operation_fence") + .equals(originalValue.reservation().issuerCoverageOperationFence()) + || !positive(row, "original_coverage_fence").equals(originalValue.reservation().coverageFence()) + || !positive(row, "original_inventory_snapshot_revision") + .equals(originalValue.reservation().inventorySnapshotRevision()) + || !positive(row, "original_reservation_inventory_revision") + .equals(originalValue.reservation().inventoryRevision()) + || !positive(row, "original_local_operation_fence") + .equals(positive(originalOperationRow, "operation_fence")) + || !positive(row, "original_local_member_generation") + .equals(positive(originalOperationRow, "local_member_generation")) + || !uuid(row, "anchor_issuer_coverage_operation_id") + .equals(originalValue.anchor().issuerCoverageOperationId()) + || !positive(row, "anchor_operation_fence").equals(originalValue.anchor().operationFence()) + || !positive(row, "anchor_coverage_fence").equals(originalValue.anchor().coverageFence()) + || !positive(row, "anchor_inventory_snapshot_revision") + .equals(originalValue.anchor().issuerInventorySnapshotRevision()) + || transition == null + || !uuid(row, "orphan_cleanup_id").equals(transition.get("admission_orphan_cleanup_id", UUID.class)) + || !Arrays.equals(bytes(row, "binding_ref"), transition.get("candidate_binding_ref", byte[].class)) + || !positive(row, "binding_generation") + .equals(number(transition, "candidate_binding_generation")) + || !Arrays.equals(originalBytes, bytes(originalOperationRow, "member_value_bytes")) + || !text(row, "original_member_value_digest").equals( + CanonicalGameplayIssuerMemberV2Codec.sha256(originalBytes)) + || !text(row, "released_member_value_digest").equals( + CanonicalGameplayIssuerMemberV2Codec.sha256(releasedBytes))) { + throw conflict("Registered issuer release differs from its immutable original local operation"); + } + CanonicalGameplayIssuerMemberV2Value released; + try { + released = CanonicalGameplayIssuerMemberV2Codec.decode(releasedBytes); + } catch (RuntimeException malformed) { + throw conflict("Registered issuer release postimage is not canonical schema v2"); + } + BigInteger fence = positive(row, "release_operation_fence"); + BigInteger generation = positive(row, "release_local_member_generation"); + CanonicalGameplayIssuerMemberV2Value expected = createReleasedValue( + originalValue, sourceRevision, releaseId, fence, generation); + if (!expected.equals(released) + || !Arrays.equals(releasedBytes, CanonicalGameplayIssuerMemberV2Codec.encode(expected)) + || !originalValue.owner().issuerId().equals(text(row, "issuer_id"))) { + throw conflict("Registered issuer release changes the original owner or anchor provenance"); + } + if ("PENDING_PHYSICAL_PROOF".equals(status)) { + if (!currentTransitionStatus.equals("ABORTED") + || !currentCandidateLifecycle.equals("TERMINAL_UNRESOLVED") + || !currentReservationLifecycle.equals("RELEASE_PENDING") + || !currentIssuerObligationStatus.equals("REQUIRED") + || currentReleaseOperationId != null + || !currentInventoryRevision.equals(sourceRevision) + || nullablePositive(row, "completion_inventory_revision") != null + || optionalBytes(row, "physical_readback_field_set_bytes") != null) { + throw conflict("Pending issuer release differs from its retained abort source"); + } + return null; + } + if (!"RELEASED".equals(status) + || !currentTransitionStatus.equals("ABORTED") + || !currentCandidateLifecycle.equals("TERMINAL_UNRESOLVED") + || !currentReservationLifecycle.equals("RELEASED") + || !currentIssuerObligationStatus.equals("RELEASED") + || !releaseId.equals(currentReleaseOperationId) + || !Objects.equals(nullablePositive(row, "completion_inventory_revision"), currentInventoryRevision) + || currentInventoryRevision.compareTo(sourceRevision) <= 0) { + throw conflict("Completed issuer release lacks its current V29 completion linkage"); + } + CanonicalGameplayBindingInventoryRepository.requireCompletedIssuerLocalRelease( + transaction, + uuid(row, "transition_id"), + bytes(row, "binding_ref"), + currentInventoryRevision, + releaseId); + return new ReleaseProjection(releaseId, releasedBytes, released); + } + + record ReleaseProjection( + UUID operationId, + byte[] exactMemberValueBytes, + CanonicalGameplayIssuerMemberV2Value memberValue) { + ReleaseProjection { + exactMemberValueBytes = exactMemberValueBytes.clone(); + } + + @Override + public byte[] exactMemberValueBytes() { + return exactMemberValueBytes.clone(); + } + } + + private static void insertRelease( + DSLContext transaction, + CanonicalGameplayAdmissionAbortSource source, + CanonicalGameplayIssuerBindingLocalOperation original, + UUID operationId, + BigInteger operationFence, + BigInteger localGeneration, + BigInteger sourceRevision, + byte[] originalBytes, + byte[] releasedBytes) { + var reservation = original.reservation(); + var anchor = original.anchor(); + transaction.execute( + "INSERT INTO " + RELEASE + + " (operation_id, issuer_id, transition_id, orphan_cleanup_id, reservation_id," + + " original_local_operation_id, binding_ref, binding_generation, partition_id," + + " original_reservation_fence, original_issuer_coverage_operation_id," + + " original_issuer_coverage_operation_fence, original_coverage_fence," + + " original_inventory_snapshot_revision, original_reservation_inventory_revision," + + " original_local_operation_fence, original_local_member_generation," + + " anchor_issuer_coverage_operation_id, anchor_operation_fence, anchor_coverage_fence," + + " anchor_inventory_snapshot_revision, source_inventory_revision, release_operation_fence," + + " release_local_member_generation, original_member_value_bytes, original_member_value_digest," + + " released_member_value_bytes, released_member_value_digest, status)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + + " 'PENDING_PHYSICAL_PROOF')", + operationId, + ISSUER, + source.transition().transitionId(), + source.orphanCleanupId(), + source.reservation().reservationId(), + original.operationId(), + source.transition().bindingRef().bytes(), + decimal(source.transition().bindingGeneration()), + decimal(source.reservation().partitionId()), + reservation.reservationFence(), + reservation.issuerCoverageOperationId(), + decimal(reservation.issuerCoverageOperationFence()), + decimal(reservation.coverageFence()), + decimal(reservation.inventorySnapshotRevision()), + decimal(reservation.inventoryRevision()), + decimal(original.operationFence()), + decimal(original.localMemberGeneration()), + anchor.issuerCoverageOperationId(), + decimal(anchor.operationFence()), + decimal(anchor.coverageFence()), + decimal(anchor.issuerInventorySnapshotRevision()), + decimal(sourceRevision), + decimal(operationFence), + decimal(localGeneration), + originalBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(originalBytes), + releasedBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(releasedBytes)); + } + + private static void advanceAbortSourceRevision( + DSLContext transaction, + CanonicalGameplayAdmissionAbortSource source, + BigInteger priorRevision, + BigInteger nextRevision, + BigInteger clockRevision) { + UUID transitionId = source.transition().transitionId(); + byte[] bindingRef = source.transition().bindingRef().bytes(); + CanonicalIssuerPartitionReservation reservation = source.reservation(); + requireOne(transaction.execute( + "UPDATE " + TRANSITION + " SET inventory_revision = ?" + + " WHERE transition_id = ? AND status = 'ABORTED'" + + " AND admission_orphan_cleanup_id = ? AND inventory_revision = ?" + + " AND candidate_binding_ref = ? AND candidate_binding_generation = ?" + + " AND issuer_reservation_id = ? AND expected_prior_binding_ref IS NULL" + + " AND expected_prior_binding_generation IS NULL", + decimal(nextRevision), transitionId, source.orphanCleanupId(), decimal(priorRevision), + bindingRef, decimal(source.transition().bindingGeneration()), reservation.reservationId()), + "Issuer release preparation lost its immutable Account-abort transition source"); + requireOne(transaction.execute( + "UPDATE " + INVENTORY + " SET inventory_revision = ?" + + " WHERE binding_ref = ? AND transition_id = ? AND lifecycle = 'TERMINAL_UNRESOLVED'" + + " AND inventory_revision = ? AND binding_generation = ? AND issuer_reservation_id = ?", + decimal(nextRevision), bindingRef, transitionId, decimal(priorRevision), + decimal(source.transition().bindingGeneration()), reservation.reservationId()), + "Issuer release preparation lost its retained candidate source"); + requireOne(transaction.execute( + "UPDATE " + RESERVATION + " SET inventory_revision = ?" + + " WHERE reservation_id = ? AND transition_id = ? AND lifecycle = 'RELEASE_PENDING'" + + " AND inventory_revision = ? AND binding_ref = ? AND binding_generation = ?" + + " AND reservation_fence = ? AND issuer_coverage_operation_id = ?" + + " AND issuer_coverage_operation_fence = ? AND coverage_fence = ?" + + " AND inventory_snapshot_revision = ?", + decimal(nextRevision), reservation.reservationId(), transitionId, decimal(priorRevision), + bindingRef, decimal(source.transition().bindingGeneration()), reservation.reservationFence(), + reservation.issuerCoverageOperationId(), decimal(reservation.issuerCoverageOperationFence()), + decimal(reservation.coverageFence()), decimal(reservation.inventorySnapshotRevision())), + "Issuer release preparation lost its original pending-reservation source"); + requireOne(transaction.execute( + "UPDATE " + ACCOUNT_OBLIGATION + " SET inventory_revision = ?" + + " WHERE transition_id = ? AND inventory_revision = ?" + + " AND status IN ('REQUIRED', 'ACKNOWLEDGED')", + decimal(nextRevision), transitionId, decimal(priorRevision)), + "Issuer release preparation lost its retained Account-obligation source"); + requireOne(transaction.execute( + "UPDATE " + ISSUER_OBLIGATION + " SET inventory_revision = ?" + + " WHERE transition_id = ? AND binding_ref = ? AND status = 'REQUIRED'" + + " AND local_release_operation_id IS NULL AND inventory_revision = ?", + decimal(nextRevision), transitionId, bindingRef, decimal(priorRevision)), + "Issuer release preparation lost its retained issuer-obligation source"); + requireOne(transaction.execute( + "UPDATE " + REGION_OBLIGATION + " SET inventory_revision = ?" + + " WHERE transition_id = ? AND status = 'REQUIRED' AND inventory_revision = ?", + decimal(nextRevision), transitionId, decimal(priorRevision)), + "Issuer release preparation lost its retained region-obligation source"); + requireOne(transaction.execute( + "UPDATE " + INVENTORY_CLOCK + " SET inventory_revision = ?" + + " WHERE singleton_id = 1 AND inventory_revision = ?", + decimal(nextRevision), decimal(clockRevision)), + "Issuer release preparation lost the current inventory-clock compare-and-set"); + } + + private static CanonicalGameplayIssuerMemberV2Value createReleasedValue( + CanonicalGameplayIssuerMemberV2Value original, + BigInteger sourceRevision, + UUID operationId, + BigInteger operationFence, + BigInteger localGeneration) { + return new CanonicalGameplayIssuerMemberV2Value( + original.owner(), + original.bindingGeneration(), + withLifecycleAndRevision( + original.reservation(), CanonicalIssuerPartitionReservation.Lifecycle.RELEASED, sourceRevision), + original.anchor(), + new CanonicalGameplayIssuerMemberV2Value.LocalMemberOperation( + operationId, operationFence, localGeneration), + original.issuerControlEpoch(), + original.layoutDescriptor(), + original.sourceCheckpoint(), + original.incarnation()); + } + + private static CanonicalIssuerPartitionReservation withLifecycleAndRevision( + CanonicalIssuerPartitionReservation source, + CanonicalIssuerPartitionReservation.Lifecycle lifecycle, + BigInteger revision) { + return new CanonicalIssuerPartitionReservation( + source.reservationId(), + source.owner(), + source.bindingGeneration(), + source.transitionId(), + source.partitionId(), + lifecycle, + source.reservationFence(), + source.issuerCoverageOperationId(), + source.issuerCoverageOperationFence(), + source.coverageFence(), + source.inventorySnapshotRevision(), + revision); + } + + private static void verifyReadbackMatchesOperation( + CanonicalGameplayIssuerBindingLocalReleaseOperation operation, + byte[] readbackBytes, + String readbackDigest) { + if (readbackBytes.length == 0 + || readbackBytes.length > 17_825_792 + || !CanonicalGameplayIssuerMemberV2Codec.sha256(readbackBytes).equals(readbackDigest)) { + throw conflict("Issuer release exact readback is malformed"); + } + var fields = CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet(readbackBytes); + String capacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + operation.releasedMemberValue().reservation().reservationId()); + String bindingField = + new String(operation.releasedMemberValue().owner().bindingRef().bytes(), StandardCharsets.UTF_8); + if (!Arrays.equals(fields.get(capacityField), operation.exactReleasedMemberValueBytes()) + || fields.containsKey(bindingField)) { + throw conflict("Issuer release readback does not prove the exact RELEASED capacity postimage"); + } + } + + private static void requireExactReleaseSource( + CanonicalGameplayIssuerBindingLocalReleaseOperation expected, + CanonicalGameplayAdmissionAbortSource current) { + requireAbortedSource(current); + var originalSource = expected.abortSource(); + var originalReservation = originalSource.reservation(); + var currentReservation = current.reservation(); + boolean currentMatchesPending = + currentReservation.lifecycle() == CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING + && originalSource.transition().inventoryRevision().equals(current.transition().inventoryRevision()) + && originalReservation.equals(currentReservation); + boolean currentMatchesReleased = + currentReservation.lifecycle() == CanonicalIssuerPartitionReservation.Lifecycle.RELEASED + && current.transition().inventoryRevision().compareTo(expected.sourceInventoryRevision()) > 0 + && currentReservation.inventoryRevision().equals(current.transition().inventoryRevision()) + && originalReservation.reservationId().equals(currentReservation.reservationId()) + && originalReservation.owner().equals(currentReservation.owner()) + && originalReservation.bindingGeneration().equals(currentReservation.bindingGeneration()) + && originalReservation.transitionId().equals(currentReservation.transitionId()) + && originalReservation.partitionId().equals(currentReservation.partitionId()) + && originalReservation.reservationFence().equals(currentReservation.reservationFence()) + && originalReservation.issuerCoverageOperationId().equals(currentReservation.issuerCoverageOperationId()) + && originalReservation.issuerCoverageOperationFence().equals(currentReservation.issuerCoverageOperationFence()) + && originalReservation.coverageFence().equals(currentReservation.coverageFence()) + && originalReservation.inventorySnapshotRevision().equals(currentReservation.inventorySnapshotRevision()); + if (!originalSource.transition().transitionId().equals(current.transition().transitionId()) + || !originalSource.orphanCleanupId().equals(current.orphanCleanupId()) + || !originalSource.candidate().identity().equals(current.candidate().identity()) + || !originalSource.transition().bindingRef().equals(current.transition().bindingRef()) + || !originalSource.transition().bindingGeneration().equals(current.transition().bindingGeneration()) + || !(currentMatchesPending || currentMatchesReleased)) { + throw conflict("Current first-NEW abort source differs from the SQL-issued release operation"); + } + } + + private static boolean sameOperationSource( + CanonicalGameplayIssuerBindingLocalOperation original, + CanonicalGameplayAdmissionAbortSource source) { + return original.request().transitionId().equals(source.transition().transitionId()) + && original.request().candidate().equals(source.candidate().identity()) + && original.reservation().reservationId().equals(source.reservation().reservationId()) + && original.reservation().reservationFence().equals(source.reservation().reservationFence()) + && original.reservation().owner().equals(source.reservation().owner()) + && original.reservation().bindingGeneration().equals(source.reservation().bindingGeneration()) + && original.reservation().issuerCoverageOperationId().equals(source.reservation().issuerCoverageOperationId()) + && original.reservation().issuerCoverageOperationFence().equals(source.reservation().issuerCoverageOperationFence()) + && original.reservation().coverageFence().equals(source.reservation().coverageFence()) + && original.reservation().inventorySnapshotRevision().equals(source.reservation().inventorySnapshotRevision()); + } + + private static void requireSameOperation( + CanonicalGameplayIssuerBindingLocalReleaseOperation expected, + CanonicalGameplayIssuerBindingLocalReleaseOperation current) { + if (!expected.operationId().equals(current.operationId()) + || !expected.operationFence().equals(current.operationFence()) + || !expected.localMemberGeneration().equals(current.localMemberGeneration()) + || !expected.sourceInventoryRevision().equals(current.sourceInventoryRevision()) + || !Arrays.equals(expected.exactOriginalMemberValueBytes(), current.exactOriginalMemberValueBytes()) + || !Arrays.equals(expected.exactReleasedMemberValueBytes(), current.exactReleasedMemberValueBytes())) { + throw conflict("SQL issuer release operation changed across its physical proof boundary"); + } + } + + private static void requireSameAbortSource( + CanonicalGameplayAdmissionAbortSource expected, + CanonicalGameplayAdmissionAbortSource current) { + if (!expected.transition().transitionId().equals(current.transition().transitionId()) + || expected.transition().status() != current.transition().status() + || !expected.transition().inventoryRevision().equals(current.transition().inventoryRevision()) + || !expected.orphanCleanupId().equals(current.orphanCleanupId()) + || !expected.transition().bindingRef().equals(current.transition().bindingRef()) + || !expected.transition().bindingGeneration().equals(current.transition().bindingGeneration()) + || !expected.transition().reservationFence().equals(current.transition().reservationFence()) + || !expected.transition().candidateAccountIndexFence().equals(current.transition().candidateAccountIndexFence()) + || !expected.reservation().equals(current.reservation()) + || !expected.candidate().identity().equals(current.candidate().identity()) + || !expected.candidate().bindingRef().equals(current.candidate().bindingRef()) + || !expected.candidate().bindingGeneration().equals(current.candidate().bindingGeneration()) + || !expected.candidate().accountIndexFence().equals(current.candidate().accountIndexFence()) + || expected.candidate().lifecycle() != current.candidate().lifecycle() + || expected.candidate().accountIndexState() != current.candidate().accountIndexState() + || expected.candidate().issuerIndexState() != current.candidate().issuerIndexState() + || !expected.originalDecision().leaseEvidenceJson().equals(current.originalDecision().leaseEvidenceJson())) { + throw conflict("Actual Account abort source changed during issuer release"); + } + } + + private static void requireSameAbortIdentity( + CanonicalGameplayAdmissionAbortSource expected, + CanonicalGameplayAdmissionAbortSource current) { + if (!expected.transition().transitionId().equals(current.transition().transitionId()) + || expected.transition().status() != current.transition().status() + || !expected.orphanCleanupId().equals(current.orphanCleanupId()) + || !expected.transition().bindingRef().equals(current.transition().bindingRef()) + || !expected.transition().bindingGeneration().equals(current.transition().bindingGeneration()) + || !expected.transition().reservationFence().equals(current.transition().reservationFence()) + || !expected.transition().candidateAccountIndexFence().equals(current.transition().candidateAccountIndexFence()) + || !expected.reservation().reservationId().equals(current.reservation().reservationId()) + || expected.reservation().lifecycle() != current.reservation().lifecycle() + || !expected.reservation().owner().equals(current.reservation().owner()) + || !expected.reservation().reservationFence().equals(current.reservation().reservationFence()) + || !expected.reservation().issuerCoverageOperationId().equals(current.reservation().issuerCoverageOperationId()) + || !expected.reservation().issuerCoverageOperationFence().equals(current.reservation().issuerCoverageOperationFence()) + || !expected.reservation().coverageFence().equals(current.reservation().coverageFence()) + || !expected.reservation().inventorySnapshotRevision().equals(current.reservation().inventorySnapshotRevision()) + || !expected.candidate().identity().equals(current.candidate().identity()) + || !expected.candidate().bindingRef().equals(current.candidate().bindingRef()) + || !expected.candidate().bindingGeneration().equals(current.candidate().bindingGeneration()) + || !expected.candidate().accountIndexFence().equals(current.candidate().accountIndexFence()) + || expected.candidate().lifecycle() != current.candidate().lifecycle() + || expected.candidate().accountIndexState() != current.candidate().accountIndexState() + || expected.candidate().issuerIndexState() != current.candidate().issuerIndexState() + || !expected.originalDecision().leaseEvidenceJson().equals(current.originalDecision().leaseEvidenceJson())) { + throw conflict("Actual first-NEW abort identity changed while preparing issuer release"); + } + } + + private static void requireAbortedSource(CanonicalGameplayAdmissionAbortSource source) { + if (!source.isAccountAborted() + || source.transition().status() != CanonicalGameplayBindingTransitionSnapshot.Status.ABORTED + || source.candidate().lifecycle() + != net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry.Lifecycle.TERMINAL_UNRESOLVED + || (source.reservation().lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING + && source.reservation().lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED)) { + throw conflict("Issuer release requires the actual Account ABORTED and retained GS source"); + } + } + + private static void requireSameCurrentIssuerState( + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState expected, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current) { + if (!CanonicalGameplayIssuerBindingLocalOperationRepository.sameCurrentIssuerState(expected, current)) { + throw conflict("Issuer source or incarnation moved during local release"); + } + } + + private CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState readCurrentIssuerState() { + return Objects.requireNonNull(currentIssuerStateSource.readFreshCurrentState(), + "current issuer state source returned null"); + } + + private static UUID freshNonNilUuid() { + UUID value; + do { + value = UUID.randomUUID(); + } while (value.equals(new UUID(0L, 0L))); + return value; + } + + private static UUID uuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null || value.equals(new UUID(0L, 0L))) throw conflict("Issuer release SQL " + field + " is unavailable"); + return value; + } + + private static String text(Record row, String field) { + String value = row.get(field, String.class); + if (value == null || value.isBlank()) throw conflict("Issuer release SQL " + field + " is unavailable"); + return value; + } + + private static byte[] bytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + if (value == null) throw conflict("Issuer release SQL " + field + " is unavailable"); + return value.clone(); + } + + private static byte[] optionalBytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + return value == null ? null : value.clone(); + } + + private static BigInteger positive(Record row, String field) { + BigInteger value = number(row, field); + if (value.signum() <= 0) throw conflict("Issuer release SQL " + field + " is not positive"); + return value; + } + + private static BigInteger nonnegative(Record row, String field) { + BigInteger value = number(row, field); + if (value.signum() < 0) throw conflict("Issuer release SQL " + field + " is negative"); + return value; + } + + private static BigInteger nullablePositive(Record row, String field) { + BigDecimal raw = row.get(field, BigDecimal.class); + BigInteger value = raw == null ? null : number(row, field); + if (value != null && value.signum() <= 0) throw conflict("Issuer release SQL " + field + " is not positive"); + return value; + } + + private static BigInteger number(Record row, String field) { + BigDecimal value = row.get(field, BigDecimal.class); + if (value == null) throw conflict("Issuer release SQL " + field + " is unavailable"); + try { + return value.toBigIntegerExact(); + } catch (ArithmeticException malformed) { + throw conflict("Issuer release SQL " + field + " is not an integer"); + } + } + + private static BigDecimal decimal(BigInteger value) { + return new BigDecimal(value); + } + + private static void requireCounterLimit(BigInteger value, String name) { + if (value.signum() <= 0 + || value.toString().length() > CanonicalGameplayIssuerMemberV2Codec.MAX_COUNTER_DIGITS) { + throw conflict(name + " is outside the canonical issuer-operation counter bound"); + } + } + + private static void requireOne(int changed, String message) { + if (changed != 1) throw conflict(message); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw conflict("Issuer release requires its own SQL boundary outside Redis calls"); + } + } + + private static IllegalStateException conflict(String message) { + return new IllegalStateException("Issuer binding-local release is unavailable: " + message); + } +} + diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.java new file mode 100644 index 0000000000..3c5389f009 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.java @@ -0,0 +1,448 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisFuture; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.async.RedisAsyncCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigInteger; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Manual one-key physical owner for an SQL-issued first-NEW issuer release successor. */ +public final class CanonicalGameplayIssuerBindingLocalReleaseRedisOwner { + private static final String PRINCIPAL = "gamesession_coord_app"; + private static final String KEY_PREFIX = "session:game:index:issuer:"; + private static final int MAX_SCRIPT_BYTES = 128 * 1024; + private static final long COMMAND_TIMEOUT_MILLIS = 5_000; + private static final List EXPECTED_KEYS = + List.of( + new RedisScriptDescriptor.KeySpec( + "issuerPartition", KEY_PREFIX, RedisScriptDescriptor.HashTagDeclaration.REQUIRED)); + private static final List EXPECTED_ARGUMENTS = + List.of( + new RedisScriptDescriptor.ArgumentSpec("issuerId"), + new RedisScriptDescriptor.ArgumentSpec("partitionId"), + new RedisScriptDescriptor.ArgumentSpec("partitionCount"), + new RedisScriptDescriptor.ArgumentSpec("partitionCapacity"), + new RedisScriptDescriptor.ArgumentSpec("baselineFieldCountAndExactFieldValuePairs"), + new RedisScriptDescriptor.ArgumentSpec("registeredLocalOperationCountAndExactOperationTupleAndCurrentPhase"), + new RedisScriptDescriptor.ArgumentSpec("originalAndReleasedMemberOperationAndCapacityProof")); + private static final List EXPECTED_OUTCOMES = + List.of( + new RedisScriptDescriptor.OutcomeSpec( + "RELEASED_CAPACITY_PROJECTED", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "RELEASED_MEMBER_REPLAY", + RedisScriptDescriptor.OutcomeCategory.REPLAY, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "TYPE_TTL_OR_FIELDSET_REFUSED", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "INVALID_ARGUMENTS_OR_CAPACITY", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING)); + + private final RedisClient redisClient; + private final RedisScriptCatalog catalog; + private final CanonicalGameplayIssuerBindingLocalProjectionRepository projectionRepository; + private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentStateSource; + + public CanonicalGameplayIssuerBindingLocalReleaseRedisOwner( + RedisClient redisClient, + RedisScriptCatalog catalog, + CanonicalGameplayIssuerBindingLocalProjectionRepository projectionRepository, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentStateSource) { + this.redisClient = Objects.requireNonNull(redisClient, "Configured Redis client is required"); + this.catalog = Objects.requireNonNull(catalog, "Manual Redis script catalog is required"); + this.projectionRepository = + Objects.requireNonNull(projectionRepository, "Actual SQL projection reader is required"); + this.currentStateSource = + Objects.requireNonNull(currentStateSource, "Fresh issuer source is required"); + } + + /** Applies the retained SQL postimage, then proves it through an independent Redis connection. */ + public Readback releaseAndRead(CanonicalGameplayIssuerBindingLocalReleaseOperation operation) { + Objects.requireNonNull(operation, "SQL-issued issuer release is required"); + try { + requireNoAmbientTransaction(); + var original = operation.originalOperation(); + var work = projectionRepository.readPreparedPartitionWork(original); + requireFreshCurrentState(work); + RedisScriptDescriptor descriptor = requireDescriptor(); + byte[] script = scriptSource(descriptor); + byte[] key = exactPartitionKey(work); + long outcome = writeOneKey(script, key, scriptArguments(work, operation)); + if (outcome != 1 && outcome != 2) { + throw unavailable("Issuer local release Lua refused the exact prepared partition"); + } + byte[] readback = readExactPhysicalState(key, work, operation); + requireFreshCurrentState(work); + projectionRepository.requireStillCurrent(work); + return new Readback(operation.operationId(), outcome, readback); + } catch (RuntimeException failure) { + if (failure instanceof IllegalStateException state + && state.getMessage() != null + && state.getMessage().contains("Issuer binding-local release is unavailable")) { + throw state; + } + throw unavailable("Physical issuer release did not obtain exact source and readback proof", failure); + } + } + + private long writeOneKey(byte[] script, byte[] key, byte[][] arguments) { + requireNoAmbientTransaction(); + try (StatefulRedisConnection connection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(connection); + requirePrincipal(await(commands.aclWhoami())); + String sha = await(commands.scriptLoad(script)); + if (!digest("SHA-1", script).equals(sha)) throw unavailable("Redis loaded a different script"); + Long reply = await(commands.evalsha(sha, ScriptOutputType.INTEGER, new byte[][] {key}, arguments)); + if (reply == null) throw unavailable("Redis returned no release result"); + return reply; + } catch (RuntimeException failure) { + throw unavailable("One-key issuer release command failed", failure); + } + } + + private byte[] readExactPhysicalState( + byte[] key, + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work, + CanonicalGameplayIssuerBindingLocalReleaseOperation operation) { + requireNoAmbientTransaction(); + try (StatefulRedisConnection connection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(connection); + requirePrincipal(await(commands.aclWhoami())); + if (!"hash".equals(await(commands.type(key))) + || !Long.valueOf(-1L).equals(await(commands.pttl(key)))) { + throw unavailable("Issuer partition type or TTL is not canonical"); + } + Long count = await(commands.hlen(key)); + int maxFields = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_HASH_FIELDS + + 2 * CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_MEMBER_OPERATIONS; + if (count == null || count < 1 || count > maxFields) throw unavailable("Issuer partition field count is invalid"); + Map raw = await(commands.hgetall(key)); + if (raw == null || raw.size() != count) throw unavailable("Issuer partition readback is incomplete"); + Map actual = new HashMap<>(); + long bytes = 0; + for (Map.Entry field : raw.entrySet()) { + byte[] name = Objects.requireNonNull(field.getKey(), "Redis field"); + byte[] value = Objects.requireNonNull(field.getValue(), "Redis value"); + bytes = Math.addExact(bytes, name.length + (long) value.length); + if (bytes > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_TOTAL_HASH_BYTES) { + throw unavailable("Issuer partition readback exceeds its bounded field set"); + } + String encodedName = Base64.getEncoder().encodeToString(name); + if (actual.putIfAbsent(encodedName, value.clone()) != null) { + throw unavailable("Issuer partition readback repeats a physical field"); + } + } + Map baseline = work.baselineFields(); + Map allowed = work.allowedFields(); + if (actual.size() > allowed.size()) throw unavailable("Issuer partition contains an unknown field"); + for (Map.Entry field : baseline.entrySet()) { + byte[] value = actual.get(b64(field.getKey().getBytes(StandardCharsets.UTF_8))); + if (value == null || !Arrays.equals(value, field.getValue())) { + throw unavailable("Exact installed issuer baseline field changed"); + } + } + var target = operation.releasedMemberValue(); + String capacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + target.reservation().reservationId()); + String bindingField = new String(target.owner().bindingRef().bytes(), StandardCharsets.UTF_8); + byte[] targetCapacity = actual.get(b64(capacityField.getBytes(StandardCharsets.US_ASCII))); + byte[] targetBinding = actual.get(b64(bindingField.getBytes(StandardCharsets.UTF_8))); + if (!Arrays.equals(targetCapacity, operation.exactReleasedMemberValueBytes()) || targetBinding != null) { + throw unavailable("Exact RELEASED capacity field or binding-field removal is absent"); + } + for (Map.Entry field : actual.entrySet()) { + String decoded = decodeUtf8(Base64.getDecoder().decode(field.getKey())); + if (decoded.equals(capacityField)) continue; + byte[] expected = allowed.get(decoded); + if (expected == null || !Arrays.equals(expected, field.getValue())) { + throw unavailable("Issuer partition contains an unregistered or changed field"); + } + } + int physicalCapacity = 0; + int physicalReservations = 0; + int physicalBindings = 0; + for (Map.Entry field : actual.entrySet()) { + String decoded = decodeUtf8(Base64.getDecoder().decode(field.getKey())); + if (decoded.startsWith( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.RESERVATION_FIELD_PREFIX)) { + var value = CanonicalGameplayIssuerMemberV2Codec.decode(field.getValue()); + physicalReservations++; + if (value.reservation().lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED) { + physicalCapacity++; + } + } else if (!decoded.equals(CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.METADATA_FIELD)) { + CanonicalGameplayIssuerMemberV2Codec.decode(field.getValue()); + physicalBindings++; + } + } + int baselineReservations = work.baselineProof().physicalReservationCount(); + int baselineBindings = work.baselineProof().physicalBindingCount(); + int registeredReservations = Math.toIntExact(work.localEntries().stream() + .filter(entry -> entry.memberValue().reservation().partitionId() + .equals(operation.releasedMemberValue().reservation().partitionId())) + .count()); + int registeredBindings = Math.toIntExact(work.localEntries().stream() + .filter(entry -> entry.memberValue().reservation().partitionId() + .equals(operation.releasedMemberValue().reservation().partitionId()) + && entry.bindingPresent()) + .count()); + if (BigInteger.valueOf(physicalCapacity).compareTo(work.anchor().partitionCapacity()) > 0 + || BigInteger.valueOf(physicalCapacity).compareTo(work.partitionCapacity()) > 0 + || physicalReservations < baselineReservations + 1 + || physicalReservations > baselineReservations + registeredReservations + || physicalBindings < baselineBindings + || physicalBindings > baselineBindings + registeredBindings + || work.aggregateCapacity().compareTo(work.aggregateBound()) > 0) { + throw unavailable("Issuer release readback violates physical or SQL capacity bounds"); + } + return CanonicalGameplayIssuerBootstrapCoverageRepository.encodeFieldSet(decodePhysicalMap(actual)); + } catch (RuntimeException failure) { + throw unavailable("Independent issuer release readback was not exact", failure); + } + } + + private static byte[][] scriptArguments( + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work, + CanonicalGameplayIssuerBindingLocalReleaseOperation operation) { + var anchor = work.anchor(); + List args = new ArrayList<>(); + args.add(ascii(anchor.issuerId())); + args.add(ascii(operation.releasedMemberValue().reservation().partitionId().toString())); + args.add(ascii(anchor.partitionCount().toString())); + args.add(ascii(anchor.partitionCapacity().toString())); + Map baseline = work.baselineFields(); + List> sortedBaseline = baseline.entrySet().stream() + .sorted(Map.Entry.comparingByKey()).toList(); + args.add(ascii(Integer.toString(sortedBaseline.size()))); + for (Map.Entry field : sortedBaseline) { + args.add(field.getKey().getBytes(StandardCharsets.UTF_8)); + args.add(field.getValue()); + } + List entries = + work.localEntries().stream() + .filter(entry -> entry.memberValue().reservation().partitionId() + .equals(operation.releasedMemberValue().reservation().partitionId())) + .sorted(java.util.Comparator.comparing(entry -> entry.operationId().toString())) + .toList(); + args.add(ascii(Integer.toString(entries.size()))); + for (var entry : entries) { + args.add(ascii(entry.operationId().toString())); + args.add(entry.memberValue().owner().bindingRef().bytes()); + args.add(ascii(entry.memberValue().reservation().reservationId().toString())); + args.add(entry.exactMemberValueBytes()); + args.add(ascii(entry.bindingPresent() ? "1" : "0")); + args.add(ascii(entry.countsTowardCapacity() ? "1" : "0")); + } + args.add(ascii(operation.originalOperation().operationId().toString())); + args.add(ascii(operation.operationId().toString())); + args.add(ascii(operation.releasedMemberValue().reservation().reservationId().toString())); + args.add(operation.releasedMemberValue().owner().bindingRef().bytes()); + args.add(operation.exactOriginalMemberValueBytes()); + args.add(operation.exactReleasedMemberValueBytes()); + args.add(ascii(operation.sourceInventoryRevision().toString())); + args.add(ascii(work.partitionCapacity().toString())); + args.add(ascii(work.aggregateCapacity().toString())); + args.add(ascii(work.aggregateBound().toString())); + return args.toArray(byte[][]::new); + } + + private static byte[] exactPartitionKey( + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work) { + String key = CanonicalGameplayIssuerRedisKeys.forMember(work.targetOperation().memberValue()); + if (!key.startsWith(KEY_PREFIX) || key.length() > 512) throw unavailable("Issuer key is not canonical"); + return key.getBytes(StandardCharsets.US_ASCII); + } + + private void requireFreshCurrentState( + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work) { + requireNoAmbientTransaction(); + var state = currentStateSource.readFreshCurrentState(); + requireNoAmbientTransaction(); + var checkpoint = state == null ? null : state.accountCheckpoint(); + var anchor = work.anchor(); + if (checkpoint == null + || !checkpoint.issuerId().equals(anchor.issuerId()) + || !checkpoint.issuerAuthGeneration().equals(anchor.issuerAuthGeneration()) + || !Arrays.equals(checkpoint.exactCheckpointBytes(), anchor.sourceCheckpointBytes()) + || !checkpoint.checkpointDigest().equals(anchor.sourceCheckpointDigest()) + || !Arrays.equals(checkpoint.latestIssuerEventBytes(), anchor.sourceEventBytes()) + || !Objects.equals(checkpoint.latestIssuerEventDigest(), anchor.sourceEventDigest()) + || !Arrays.equals( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(state.incarnation()), + anchor.incarnationBytes())) { + throw unavailable("Issuer source checkpoint or incarnation changed"); + } + } + + private RedisScriptDescriptor requireDescriptor() { + RedisScriptDescriptor descriptor; + try { + descriptor = catalog.require(CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.SCRIPT_ID); + } catch (RuntimeException missing) { + throw unavailable("Manual issuer release descriptor is not installed", missing); + } + if (!CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.SCRIPT_ID.equals(descriptor.scriptId()) + || !CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.RESOURCE_PATH.equals(descriptor.resourcePath()) + || !"game-session-service".equals(descriptor.owner()) + || !PRINCIPAL.equals(descriptor.principal()) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || !EXPECTED_KEYS.equals(descriptor.keys()) + || !EXPECTED_ARGUMENTS.equals(descriptor.arguments()) + || descriptor.category() != RedisScriptDescriptor.ScriptCategory.SESSION_ISSUER_INDEX + || !EXPECTED_OUTCOMES.equals(descriptor.outcomes()) + || descriptor.resetSensitivity() != RedisScriptDescriptor.ResetSensitivity.CLUSTER + || descriptor.lossClass() != RedisScriptDescriptor.LossClass.EMPTY_REDIS_COLD_START_OR_RESET + || descriptor.compatibilityLevel() != RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET + || !descriptor.supportedCoexistence().equals(List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "v2"))) + || descriptor.legacyPayloadShape() != null) { + throw unavailable("Manual issuer release descriptor differs from its exact owner contract"); + } + return descriptor; + } + + private static byte[] scriptSource(RedisScriptDescriptor descriptor) { + try (InputStream input = CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.class + .getClassLoader().getResourceAsStream(descriptor.resourcePath())) { + if (input == null) throw unavailable("Issuer release Lua resource is missing"); + byte[] bytes = input.readNBytes(MAX_SCRIPT_BYTES + 1); + if (bytes.length == 0 || bytes.length > MAX_SCRIPT_BYTES + || !descriptor.sha256().equals(digest("SHA-256", bytes))) { + throw unavailable("Issuer release Lua differs from its exact descriptor digest"); + } + return bytes; + } catch (IOException | RuntimeException failure) { + throw unavailable("Issuer release Lua is unavailable", failure); + } + } + + private static Map decodePhysicalMap(Map encoded) { + Map result = new HashMap<>(); + encoded.forEach((field, value) -> result.put(decodeUtf8(Base64.getDecoder().decode(field)), value.clone())); + return result; + } + + private static String b64(byte[] value) { + return Base64.getEncoder().encodeToString(value); + } + + private static String decodeUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8.newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(bytes)).toString(); + } catch (CharacterCodingException malformed) { + throw unavailable("Issuer hash field is not valid UTF-8", malformed); + } + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static RedisAsyncCommands requireCommands( + StatefulRedisConnection connection) { + if (connection == null || !connection.isOpen()) throw unavailable("Redis connection is unavailable"); + return connection.async(); + } + + private static void requirePrincipal(String principal) { + if (!PRINCIPAL.equals(principal)) throw unavailable("Redis principal is not the exact coordination owner"); + } + + private static T await(RedisFuture future) { + try { + return future.get(COMMAND_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + future.cancel(true); + throw unavailable("Redis issuer release command was interrupted", interrupted); + } catch (ExecutionException | TimeoutException | RuntimeException failure) { + future.cancel(true); + throw unavailable("Redis issuer release command failed", failure); + } + } + + private static String digest(String algorithm, byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(bytes)); + } catch (Exception failure) { + throw unavailable("Could not verify issuer release Lua digest", failure); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw unavailable("Physical issuer release cannot run inside an ambient SQL transaction"); + } + } + + private static IllegalStateException unavailable(String message) { + return new IllegalStateException("Issuer binding-local release is unavailable: " + message); + } + + private static IllegalStateException unavailable(String message, Throwable cause) { + return new IllegalStateException("Issuer binding-local release is unavailable: " + message, cause); + } + + /** Exact private physical readback; SQL completion must consume this value in a new transaction. */ + public static final class Readback { + private final UUID operationId; + private final long scriptOutcome; + private final byte[] exactPhysicalFieldSetBytes; + + private Readback(UUID operationId, long scriptOutcome, byte[] exactPhysicalFieldSetBytes) { + this.operationId = Objects.requireNonNull(operationId, "operationId"); + this.scriptOutcome = scriptOutcome; + this.exactPhysicalFieldSetBytes = exactPhysicalFieldSetBytes.clone(); + } + + public UUID operationId() { + return operationId; + } + + public long scriptOutcome() { + return scriptOutcome; + } + + byte[] exactPhysicalFieldSetBytes() { + return exactPhysicalFieldSetBytes.clone(); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.java new file mode 100644 index 0000000000..fa1834e164 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.java @@ -0,0 +1,51 @@ +package net.firedevops.firemud.gamesession.service; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Collection; +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Passive manual-catalog contribution for the purpose-specific issuer release operation. */ +public final class CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution + implements RedisScriptContribution { + public static final String SCRIPT_ID = "game-session.issuer-binding-local-release.v1"; + public static final String RESOURCE_PATH = "redis/lua/game-session-issuer-binding-local-release.lua"; + private static final String DESCRIPTOR_PATH = + "/redis/scripts/game-session-issuer-binding-local-release.json"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @Override + public String ownerId() { + return "game-session-service"; + } + + @Override + public Collection descriptors() { + try (InputStream input = getClass().getResourceAsStream(DESCRIPTOR_PATH)) { + if (input == null) throw unavailable(); + byte[] bytes = input.readNBytes(16 * 1024 + 1); + if (bytes.length == 0 || bytes.length > 16 * 1024) throw unavailable(); + RedisScriptDescriptor descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); + if (!ownerId().equals(descriptor.owner()) || !SCRIPT_ID.equals(descriptor.scriptId())) { + throw unavailable(); + } + return List.of(descriptor); + } catch (IOException | RuntimeException failure) { + throw unavailable(); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Issuer binding-local release Redis descriptor is unavailable"); + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V1036__canonical_issuer_first_new_release_proof.sql b/services/game-session-service/src/main/resources/db/migration/V1036__canonical_issuer_first_new_release_proof.sql new file mode 100644 index 0000000000..797650982f --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1036__canonical_issuer_first_new_release_proof.sql @@ -0,0 +1,586 @@ +-- One proof-backed terminal successor for an actual first-NEW Account abort. The immutable V1034 +-- registration remains the old physical compare; this row retains the exact successor and its +-- later positive one-key readback/completion without rewriting that original operation. + +ALTER TABLE game_session_canonical_binding_issuer_index_obligation + DROP CONSTRAINT chk_gs_canonical_binding_issuer_index_obligation; + +ALTER TABLE game_session_canonical_binding_issuer_index_obligation + ADD COLUMN local_release_operation_id uuid; + +ALTER TABLE game_session_canonical_binding_issuer_index_obligation + ADD CONSTRAINT chk_gs_canonical_binding_issuer_index_obligation CHECK ( + binding_generation > 0 + AND inventory_revision > 0 + AND ((status = 'REQUIRED' AND local_release_operation_id IS NULL) + OR (status = 'RELEASED' AND local_release_operation_id IS NOT NULL + AND local_release_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid))); + +CREATE TABLE game_session_canonical_issuer_binding_local_release_operation ( + operation_id uuid NOT NULL, + issuer_id character varying(64) NOT NULL, + transition_id uuid NOT NULL, + orphan_cleanup_id uuid NOT NULL, + reservation_id uuid NOT NULL, + original_local_operation_id uuid NOT NULL, + binding_ref bytea NOT NULL, + binding_generation numeric NOT NULL, + partition_id numeric NOT NULL, + + original_reservation_fence uuid NOT NULL, + original_issuer_coverage_operation_id uuid NOT NULL, + original_issuer_coverage_operation_fence numeric NOT NULL, + original_coverage_fence numeric NOT NULL, + original_inventory_snapshot_revision numeric NOT NULL, + original_reservation_inventory_revision numeric NOT NULL, + original_local_operation_fence numeric NOT NULL, + original_local_member_generation numeric NOT NULL, + + anchor_issuer_coverage_operation_id uuid NOT NULL, + anchor_operation_fence numeric NOT NULL, + anchor_coverage_fence numeric NOT NULL, + anchor_inventory_snapshot_revision numeric NOT NULL, + source_inventory_revision numeric NOT NULL, + + release_operation_fence numeric NOT NULL, + release_local_member_generation numeric NOT NULL, + original_member_value_bytes bytea NOT NULL, + original_member_value_digest character varying(71) NOT NULL, + released_member_value_bytes bytea NOT NULL, + released_member_value_digest character varying(71) NOT NULL, + + status character varying(32) NOT NULL, + physical_readback_field_set_bytes bytea, + physical_readback_field_set_digest character varying(71), + completion_inventory_revision numeric, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + completed_at timestamp with time zone, + + CONSTRAINT pk_gs_issuer_binding_local_release_operation PRIMARY KEY (operation_id), + CONSTRAINT uq_gs_issuer_binding_local_release_transition UNIQUE (transition_id), + CONSTRAINT uq_gs_issuer_binding_local_release_reservation UNIQUE (reservation_id), + CONSTRAINT uq_gs_issuer_binding_local_release_original UNIQUE (original_local_operation_id), + CONSTRAINT uq_gs_issuer_binding_local_release_fence UNIQUE (issuer_id, release_operation_fence), + CONSTRAINT uq_gs_issuer_binding_local_release_generation UNIQUE (issuer_id, release_local_member_generation), + CONSTRAINT fk_gs_issuer_binding_local_release_transition + FOREIGN KEY (transition_id) REFERENCES game_session_canonical_binding_transition (transition_id), + CONSTRAINT fk_gs_issuer_binding_local_release_reservation + FOREIGN KEY (reservation_id) REFERENCES game_session_canonical_issuer_partition_reservation (reservation_id), + CONSTRAINT fk_gs_issuer_binding_local_release_original + FOREIGN KEY (original_local_operation_id) + REFERENCES game_session_canonical_issuer_binding_local_operation (operation_id), + CONSTRAINT chk_gs_issuer_binding_local_release_operation CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND orphan_cleanup_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND binding_generation > 0 + AND partition_id >= 0 + AND original_reservation_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND original_issuer_coverage_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND original_issuer_coverage_operation_fence > 0 + AND original_coverage_fence > 0 + AND original_inventory_snapshot_revision > 0 + AND original_reservation_inventory_revision > 0 + AND original_local_operation_fence > 0 + AND original_local_member_generation > 0 + AND anchor_issuer_coverage_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND anchor_operation_fence > 0 + AND anchor_coverage_fence > 0 + AND anchor_inventory_snapshot_revision > 0 + AND source_inventory_revision > 0 + AND release_operation_fence > 0 + AND release_local_member_generation = release_operation_fence + 1 + AND release_operation_fence > original_local_operation_fence + AND release_local_member_generation > original_local_member_generation + AND octet_length(original_member_value_bytes) BETWEEN 1 AND 65536 + AND original_member_value_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(released_member_value_bytes) BETWEEN 1 AND 65536 + AND released_member_value_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((status = 'PENDING_PHYSICAL_PROOF' + AND physical_readback_field_set_bytes IS NULL + AND physical_readback_field_set_digest IS NULL + AND completion_inventory_revision IS NULL + AND completed_at IS NULL) + OR (status = 'RELEASED' + AND physical_readback_field_set_bytes IS NOT NULL + AND octet_length(physical_readback_field_set_bytes) BETWEEN 1 AND 17825792 + AND physical_readback_field_set_digest ~ '^sha256:[0-9a-f]{64}$' + AND completion_inventory_revision > source_inventory_revision + AND completed_at IS NOT NULL)) + ) +); + +-- Preserve the exact bytea identity in PostgreSQL while keeping jOOQ's H2 schema parser bounded. +-- [jooq ignore start] +ALTER TABLE game_session_canonical_issuer_binding_local_release_operation + ADD CONSTRAINT fk_gs_issuer_binding_local_release_issuer_obligation + FOREIGN KEY (transition_id, binding_ref) + REFERENCES game_session_canonical_binding_issuer_index_obligation (transition_id, binding_ref); + +ALTER TABLE game_session_canonical_binding_issuer_index_obligation + ADD CONSTRAINT fk_gs_issuer_binding_local_release_obligation + FOREIGN KEY (local_release_operation_id) + REFERENCES game_session_canonical_issuer_binding_local_release_operation (operation_id); +-- [jooq ignore stop] + +CREATE INDEX ix_gs_issuer_binding_local_release_status + ON game_session_canonical_issuer_binding_local_release_operation (issuer_id, status, partition_id); + +CREATE FUNCTION require_first_new_issuer_release_source() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_binding_transition transition + JOIN game_session_canonical_gameplay_binding_inventory candidate + ON candidate.binding_ref = transition.candidate_binding_ref + JOIN game_session_canonical_issuer_partition_reservation reservation + ON reservation.reservation_id = transition.issuer_reservation_id + JOIN game_session_canonical_binding_issuer_index_obligation issuer_obligation + ON issuer_obligation.transition_id = transition.transition_id + AND issuer_obligation.binding_ref = transition.candidate_binding_ref + JOIN game_session_canonical_issuer_binding_local_operation original_operation + ON original_operation.operation_id = NEW.original_local_operation_id + WHERE transition.transition_id = NEW.transition_id + AND transition.status = 'ABORTED' + AND transition.admission_lease_kind = 'NEW_BINDING' + AND transition.expected_prior_binding_ref IS NULL + AND transition.expected_prior_binding_generation IS NULL + AND transition.admission_orphan_cleanup_id = NEW.orphan_cleanup_id + AND transition.inventory_revision = NEW.source_inventory_revision + AND candidate.lifecycle = 'TERMINAL_UNRESOLVED' + AND candidate.inventory_revision = NEW.source_inventory_revision + AND candidate.binding_ref = NEW.binding_ref + AND candidate.binding_generation = NEW.binding_generation + AND candidate.issuer_reservation_id = NEW.reservation_id + AND reservation.lifecycle = 'RELEASE_PENDING' + AND reservation.inventory_revision = NEW.source_inventory_revision + AND reservation.reservation_id = NEW.reservation_id + AND reservation.transition_id = NEW.transition_id + AND reservation.binding_ref = NEW.binding_ref + AND reservation.binding_generation = NEW.binding_generation + AND reservation.partition_id = NEW.partition_id + AND reservation.reservation_fence = NEW.original_reservation_fence + AND reservation.issuer_coverage_operation_id = NEW.original_issuer_coverage_operation_id + AND reservation.issuer_coverage_operation_fence = NEW.original_issuer_coverage_operation_fence + AND reservation.coverage_fence = NEW.original_coverage_fence + AND reservation.inventory_snapshot_revision = NEW.original_inventory_snapshot_revision + AND issuer_obligation.status = 'REQUIRED' + AND issuer_obligation.local_release_operation_id IS NULL + AND issuer_obligation.inventory_revision = NEW.source_inventory_revision + AND original_operation.transition_id = NEW.transition_id + AND original_operation.reservation_id = NEW.reservation_id + AND original_operation.binding_ref = NEW.binding_ref + AND original_operation.binding_generation = NEW.binding_generation + AND original_operation.operation_fence = NEW.original_local_operation_fence + AND original_operation.local_member_generation = NEW.original_local_member_generation + AND original_operation.member_status = 'PENDING_PHYSICAL_PROOF' + AND original_operation.member_schema_version = 2 + AND original_operation.member_value_bytes = NEW.original_member_value_bytes + AND original_operation.member_value_digest = NEW.original_member_value_digest + AND NEW.issuer_id = original_operation.issuer_id + AND NEW.original_reservation_inventory_revision = original_operation.local_inventory_snapshot_revision + ) THEN + RAISE EXCEPTION 'Issuer release requires the actual retained first-NEW Account abort and its exact original local operation' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_first_new_issuer_release_source_required'; + END IF; + RETURN NEW; +END; +$$; + +-- The only RELEASE_PENDING -> RELEASED edge is the durable successor that already has +-- exact positive Redis readback. Its physical value carries preparation revision P; the +-- guarded current-state receipt and all V29 rows advance together at fresh revision R. +CREATE FUNCTION require_first_new_issuer_release_reservation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF OLD.lifecycle = 'RELEASE_PENDING' AND NEW.lifecycle = 'RELEASED' THEN + IF (to_jsonb(NEW) - 'lifecycle' - 'inventory_revision') + IS DISTINCT FROM (to_jsonb(OLD) - 'lifecycle' - 'inventory_revision') + OR NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_binding_transition transition + JOIN game_session_canonical_gameplay_binding_inventory candidate + ON candidate.binding_ref = transition.candidate_binding_ref + JOIN game_session_canonical_binding_issuer_index_obligation issuer_obligation + ON issuer_obligation.transition_id = transition.transition_id + AND issuer_obligation.binding_ref = transition.candidate_binding_ref + JOIN game_session_canonical_issuer_binding_local_release_operation release + ON release.operation_id = issuer_obligation.local_release_operation_id + WHERE transition.transition_id = NEW.transition_id + AND transition.status = 'ABORTED' + AND transition.admission_orphan_cleanup_id = release.orphan_cleanup_id + AND transition.inventory_revision = OLD.inventory_revision + AND candidate.lifecycle = 'TERMINAL_UNRESOLVED' + AND candidate.inventory_revision = OLD.inventory_revision + AND candidate.binding_ref = OLD.binding_ref + AND candidate.binding_generation = OLD.binding_generation + AND candidate.issuer_reservation_id = OLD.reservation_id + AND issuer_obligation.status = 'RELEASED' + AND issuer_obligation.inventory_revision = NEW.inventory_revision + AND issuer_obligation.local_release_operation_id = release.operation_id + AND release.status = 'RELEASED' + AND release.transition_id = NEW.transition_id + AND release.reservation_id = NEW.reservation_id + AND release.binding_ref = NEW.binding_ref + AND release.binding_generation = NEW.binding_generation + AND release.source_inventory_revision = OLD.inventory_revision + AND release.completion_inventory_revision = NEW.inventory_revision + AND NEW.inventory_revision > OLD.inventory_revision + AND release.physical_readback_field_set_bytes IS NOT NULL + AND release.physical_readback_field_set_digest ~ '^sha256:[0-9a-f]{64}$' + ) THEN + RAISE EXCEPTION 'First-NEW reservation release requires its exact completed physical issuer proof' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_first_new_issuer_release_reservation_source'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_first_new_issuer_release_reservation + BEFORE UPDATE ON game_session_canonical_issuer_partition_reservation + FOR EACH ROW EXECUTE FUNCTION require_first_new_issuer_release_reservation(); + +CREATE FUNCTION require_first_new_issuer_release_obligation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF OLD.status = 'RELEASED' + AND (TG_OP = 'DELETE' OR to_jsonb(NEW) IS DISTINCT FROM to_jsonb(OLD)) THEN + RAISE EXCEPTION 'Completed first-NEW issuer release obligation is retained' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_first_new_issuer_release_obligation_retained'; + END IF; + IF OLD.status = 'REQUIRED' AND NEW.status = 'RELEASED' THEN + IF (to_jsonb(NEW) - 'status' - 'local_release_operation_id' - 'inventory_revision') + IS DISTINCT FROM + (to_jsonb(OLD) - 'status' - 'local_release_operation_id' - 'inventory_revision') + OR NEW.local_release_operation_id IS NULL + OR NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_binding_transition transition + JOIN game_session_canonical_gameplay_binding_inventory candidate + ON candidate.binding_ref = transition.candidate_binding_ref + JOIN game_session_canonical_issuer_partition_reservation reservation + ON reservation.reservation_id = transition.issuer_reservation_id + JOIN game_session_canonical_issuer_binding_local_release_operation release + ON release.operation_id = NEW.local_release_operation_id + WHERE transition.transition_id = NEW.transition_id + AND transition.status = 'ABORTED' + AND transition.admission_orphan_cleanup_id = release.orphan_cleanup_id + AND transition.inventory_revision = OLD.inventory_revision + AND candidate.lifecycle = 'TERMINAL_UNRESOLVED' + AND candidate.inventory_revision = OLD.inventory_revision + AND reservation.lifecycle = 'RELEASE_PENDING' + AND reservation.inventory_revision = OLD.inventory_revision + AND reservation.reservation_id = NEW.reservation_id + AND candidate.binding_ref = NEW.binding_ref + AND candidate.binding_generation = NEW.binding_generation + AND release.status = 'RELEASED' + AND release.transition_id = NEW.transition_id + AND release.reservation_id = reservation.reservation_id + AND release.binding_ref = NEW.binding_ref + AND release.binding_generation = NEW.binding_generation + AND release.source_inventory_revision = OLD.inventory_revision + AND release.completion_inventory_revision = NEW.inventory_revision + AND NEW.inventory_revision > OLD.inventory_revision + AND release.physical_readback_field_set_bytes IS NOT NULL + AND release.physical_readback_field_set_digest ~ '^sha256:[0-9a-f]{64}$' + ) THEN + RAISE EXCEPTION 'Issuer obligation release requires exact completed local physical proof' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_first_new_issuer_release_obligation_source'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_first_new_issuer_release_obligation + BEFORE UPDATE OR DELETE ON game_session_canonical_binding_issuer_index_obligation + FOR EACH ROW EXECUTE FUNCTION require_first_new_issuer_release_obligation(); + +-- Any durable-source change rechecks the complete retained first-NEW tuple at commit. +CREATE CONSTRAINT TRIGGER game_session_first_new_issuer_release_reservation_atomic + AFTER UPDATE ON game_session_canonical_issuer_partition_reservation + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION require_first_new_abort_source_complete(); +CREATE CONSTRAINT TRIGGER game_session_first_new_issuer_release_obligation_atomic + AFTER UPDATE ON game_session_canonical_binding_issuer_index_obligation + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION require_first_new_abort_source_complete(); +CREATE CONSTRAINT TRIGGER game_session_first_new_issuer_release_candidate_atomic + AFTER UPDATE ON game_session_canonical_gameplay_binding_inventory + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION require_first_new_abort_source_complete(); +CREATE CONSTRAINT TRIGGER game_session_first_new_issuer_release_region_atomic + AFTER UPDATE ON game_session_canonical_binding_region_bridge_obligation + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION require_first_new_abort_source_complete(); +CREATE CONSTRAINT TRIGGER game_session_first_new_issuer_release_account_atomic + AFTER UPDATE ON game_session_canonical_binding_account_index_obligation + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION require_first_new_abort_source_complete(); +CREATE CONSTRAINT TRIGGER game_session_first_new_issuer_release_artifact_atomic + AFTER INSERT OR UPDATE ON game_session_canonical_issuer_binding_local_release_operation + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION require_first_new_abort_source_complete(); + +CREATE TRIGGER game_session_first_new_issuer_release_source + BEFORE INSERT ON game_session_canonical_issuer_binding_local_release_operation + FOR EACH ROW EXECUTE FUNCTION require_first_new_issuer_release_source(); + +CREATE FUNCTION retain_first_new_issuer_release_operation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'DELETE' OR OLD.status = 'RELEASED' + OR NEW.status <> 'RELEASED' + OR (to_jsonb(NEW) - 'status' - 'physical_readback_field_set_bytes' + - 'physical_readback_field_set_digest' - 'completion_inventory_revision' - 'completed_at') + IS DISTINCT FROM + (to_jsonb(OLD) - 'status' - 'physical_readback_field_set_bytes' + - 'physical_readback_field_set_digest' - 'completion_inventory_revision' - 'completed_at') + OR NEW.physical_readback_field_set_bytes IS NULL + OR NEW.physical_readback_field_set_digest IS NULL + OR NEW.completion_inventory_revision IS NULL + OR NEW.completed_at IS NULL + OR NEW.completion_inventory_revision <= NEW.source_inventory_revision + OR NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_binding_transition transition + JOIN game_session_canonical_gameplay_binding_inventory candidate + ON candidate.binding_ref = transition.candidate_binding_ref + JOIN game_session_canonical_issuer_partition_reservation reservation + ON reservation.reservation_id = transition.issuer_reservation_id + JOIN game_session_canonical_binding_issuer_index_obligation issuer_obligation + ON issuer_obligation.transition_id = transition.transition_id + AND issuer_obligation.binding_ref = transition.candidate_binding_ref + JOIN game_session_canonical_binding_inventory_clock inventory_clock + ON inventory_clock.singleton_id = 1 + WHERE transition.transition_id = OLD.transition_id + AND transition.status = 'ABORTED' + AND transition.admission_orphan_cleanup_id = OLD.orphan_cleanup_id + AND transition.inventory_revision = OLD.source_inventory_revision + AND candidate.lifecycle = 'TERMINAL_UNRESOLVED' + AND candidate.inventory_revision = OLD.source_inventory_revision + AND reservation.lifecycle = 'RELEASE_PENDING' + AND reservation.inventory_revision = OLD.source_inventory_revision + AND issuer_obligation.status = 'REQUIRED' + AND issuer_obligation.local_release_operation_id IS NULL + AND issuer_obligation.inventory_revision = OLD.source_inventory_revision + AND inventory_clock.inventory_revision + 1 = NEW.completion_inventory_revision + ) THEN + RAISE EXCEPTION 'Issuer release completion requires its exact pending source and fresh inventory revision' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_first_new_issuer_release_completion_source'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_first_new_issuer_release_immutable + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_binding_local_release_operation + FOR EACH ROW EXECUTE FUNCTION retain_first_new_issuer_release_operation(); +CREATE TRIGGER game_session_first_new_issuer_release_no_truncate + BEFORE TRUNCATE ON game_session_canonical_issuer_binding_local_release_operation + FOR EACH STATEMENT EXECUTE FUNCTION game_session_reject_issuer_binding_local_operation_change(); + +COMMENT ON TABLE game_session_canonical_issuer_binding_local_release_operation IS + 'Immutable original-operation-linked first-NEW issuer release successor; RELEASED requires exact one-key physical readback and a fresh guarded completion revision.'; + + +-- Retain the latest abort/account-repair source checks while permitting only a proof-backed +-- issuer-local release. Account and region obligations remain unresolved. +CREATE OR REPLACE FUNCTION require_first_new_abort_source_complete() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + affected_transition_id uuid; +BEGIN + IF TG_OP = 'DELETE' THEN affected_transition_id := OLD.transition_id; + ELSE affected_transition_id := NEW.transition_id; + END IF; + IF NOT EXISTS (SELECT 1 FROM game_session_canonical_binding_transition + WHERE transition_id = affected_transition_id AND status = 'ABORTED' + AND admission_orphan_cleanup_id IS NOT NULL) THEN + RETURN NULL; + END IF; + IF NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_binding_transition transition + JOIN game_session_canonical_gameplay_binding_inventory candidate + ON candidate.binding_ref = transition.candidate_binding_ref + JOIN game_session_canonical_issuer_partition_reservation reservation + ON reservation.reservation_id = transition.issuer_reservation_id + JOIN game_session_canonical_binding_account_index_obligation account_obligation + ON account_obligation.transition_id = transition.transition_id + AND account_obligation.obligation_ordinal = 0 + JOIN game_session_canonical_binding_issuer_index_obligation issuer_obligation + ON issuer_obligation.transition_id = transition.transition_id + AND issuer_obligation.binding_ref = transition.candidate_binding_ref + JOIN game_session_canonical_binding_region_bridge_obligation region_obligation + ON region_obligation.transition_id = transition.transition_id + WHERE transition.transition_id = affected_transition_id + AND transition.status = 'ABORTED' + AND transition.admission_lease_id IS NOT NULL + AND transition.admission_lease_kind = 'NEW_BINDING' + AND transition.admission_lease_evidence IS NOT NULL + AND transition.admission_lease_digest IS NOT NULL + AND transition.expected_prior_binding_ref IS NULL + AND transition.expected_prior_binding_generation IS NULL + AND transition.admission_orphan_cleanup_id IS NOT NULL + AND transition.admission_orphan_cleanup_id <> + '00000000-0000-0000-0000-000000000000'::uuid + AND transition.inventory_revision = candidate.inventory_revision + AND transition.inventory_revision = reservation.inventory_revision + AND transition.inventory_revision = account_obligation.inventory_revision + AND transition.inventory_revision = issuer_obligation.inventory_revision + AND transition.inventory_revision = region_obligation.inventory_revision + AND transition.candidate_binding_ref = candidate.binding_ref + AND transition.candidate_binding_generation = candidate.binding_generation + AND transition.candidate_account_index_fence = candidate.account_index_fence + AND transition.issuer_reservation_id = candidate.issuer_reservation_id + AND transition.tenant_id = candidate.tenant_id + AND transition.playable_state_namespace_id = candidate.playable_state_namespace_id + AND transition.character_id = candidate.character_id + AND candidate.lifecycle = 'TERMINAL_UNRESOLVED' + AND reservation.lifecycle IN ('RELEASE_PENDING', 'RELEASED') + AND reservation.transition_id = transition.transition_id + AND reservation.binding_ref = candidate.binding_ref + AND reservation.binding_generation = candidate.binding_generation + AND reservation.reservation_fence IS NOT NULL + AND reservation.account_id = candidate.account_id + AND reservation.tenant_id = candidate.tenant_id + AND reservation.playable_state_namespace_id = candidate.playable_state_namespace_id + AND reservation.character_id = candidate.character_id + AND reservation.game_instance_id = candidate.game_instance_id + AND reservation.runtime_game_instance_id = candidate.runtime_game_instance_id + AND reservation.session_id = candidate.session_id + AND reservation.region_id = candidate.region_id + AND reservation.region_epoch = candidate.region_epoch + AND reservation.issuer_id = candidate.issuer_id + AND reservation.issuer_auth_generation = candidate.issuer_auth_generation + AND reservation.issuer_index_layout_version = candidate.issuer_index_layout_version + AND reservation.issuer_index_partition_count = candidate.issuer_index_partition_count + AND reservation.issuer_index_partition_capacity = candidate.issuer_index_partition_capacity + AND account_obligation.binding_ref = candidate.binding_ref + AND account_obligation.account_id = candidate.account_id + AND account_obligation.tenant_id = candidate.tenant_id + AND account_obligation.action = 'ADD_OR_RETAIN' + AND account_obligation.binding_generation = candidate.binding_generation + AND account_obligation.expected_prior_generation IS NULL + AND account_obligation.account_index_fence = candidate.account_index_fence + AND account_obligation.execution_phase = 'BEFORE_FINAL_CAS' + AND ( + (account_obligation.status = 'REQUIRED' AND candidate.account_index_state = 'REPAIR_REQUIRED') + OR (account_obligation.status = 'ACKNOWLEDGED' + AND candidate.account_index_state = 'ACKNOWLEDGED' + AND account_obligation.projection_state = 'PRESENT_AWAITING_COVERAGE' + AND EXISTS ( + SELECT 1 FROM game_session_canonical_account_member_repair_operation repair + JOIN game_session_canonical_account_coverage_control control + ON control.account_id = repair.account_id + WHERE repair.transition_id = transition.transition_id + AND repair.obligation_ordinal = 0 + AND repair.status = 'ACKNOWLEDGED' + AND repair.binding_ref = candidate.binding_ref + AND repair.account_id = candidate.account_id + AND repair.tenant_id = candidate.tenant_id + AND repair.binding_generation = candidate.binding_generation + AND repair.account_index_fence = candidate.account_index_fence + AND repair.original_action = 'ADD_OR_RETAIN' + AND repair.original_expected_prior_generation IS NULL + AND repair.original_execution_phase = 'BEFORE_FINAL_CAS' + AND repair.original_status = 'REQUIRED' + AND repair.desired_action = 'ADD_OR_RETAIN' + AND repair.account_control_state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW' + AND control.state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW' + AND control.last_operation_fence = repair.account_control_epoch + AND repair.coverage_generation > repair.inventory_snapshot_revision + AND repair.completed_inventory_revision > repair.inventory_snapshot_revision + AND repair.completed_inventory_revision < transition.inventory_revision + AND repair.readback_state = 'PRESENT' + AND repair.readback_member = repair.member + AND repair.member = account_obligation.projection_member + AND repair.member = 'accountIndexMember/v1:' + || rtrim(translate(replace(encode(candidate.binding_ref, 'base64'), E'\n', ''), '+/', '-_'), '=') + || ':' || candidate.binding_generation::text || ':' || candidate.account_index_fence::text + AND ((repair.original_projection_state = 'REQUIRED' + AND account_obligation.projection_inventory_revision = repair.completed_inventory_revision) + OR (repair.original_projection_state = 'PRESENT_AWAITING_COVERAGE' + AND repair.original_projection_member = repair.member + AND account_obligation.projection_inventory_revision = repair.original_projection_inventory_revision)) + )) + ) + AND (SELECT count(*) + FROM game_session_canonical_binding_account_index_obligation extra_account + WHERE extra_account.transition_id = transition.transition_id) = 1 + AND issuer_obligation.reservation_id = reservation.reservation_id + AND issuer_obligation.binding_ref = candidate.binding_ref + AND issuer_obligation.binding_generation = candidate.binding_generation + AND ( + (issuer_obligation.status = 'REQUIRED' + AND issuer_obligation.local_release_operation_id IS NULL + AND reservation.lifecycle = 'RELEASE_PENDING' + AND NOT EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_binding_local_release_operation pending_release + WHERE pending_release.transition_id = transition.transition_id + AND pending_release.status <> 'PENDING_PHYSICAL_PROOF')) + OR (issuer_obligation.status = 'RELEASED' + AND issuer_obligation.local_release_operation_id IS NOT NULL + AND reservation.lifecycle = 'RELEASED' + AND EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_binding_local_release_operation released + WHERE released.operation_id = issuer_obligation.local_release_operation_id + AND released.transition_id = transition.transition_id + AND released.orphan_cleanup_id = transition.admission_orphan_cleanup_id + AND released.reservation_id = reservation.reservation_id + AND released.binding_ref = candidate.binding_ref + AND released.binding_generation = candidate.binding_generation + AND released.status = 'RELEASED' + AND released.source_inventory_revision < transition.inventory_revision + AND released.completion_inventory_revision = transition.inventory_revision + AND released.physical_readback_field_set_bytes IS NOT NULL + AND released.physical_readback_field_set_digest ~ '^sha256:[0-9a-f]{64}$' + AND released.released_member_value_bytes IS NOT NULL + AND released.released_member_value_digest ~ '^sha256:[0-9a-f]{64}$')) + ) + AND (SELECT count(*) + FROM game_session_canonical_binding_issuer_index_obligation extra_issuer + WHERE extra_issuer.transition_id = transition.transition_id) = 1 + AND region_obligation.binding_ref = candidate.binding_ref + AND region_obligation.binding_generation = candidate.binding_generation + AND region_obligation.account_id = candidate.account_id + AND region_obligation.tenant_id = candidate.tenant_id + AND region_obligation.game_instance_id = candidate.game_instance_id + AND region_obligation.runtime_game_instance_id = candidate.runtime_game_instance_id + AND region_obligation.session_id = candidate.session_id + AND region_obligation.region_id = candidate.region_id + AND region_obligation.region_epoch = candidate.region_epoch + AND region_obligation.status = 'REQUIRED' + AND NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_gameplay_binding_inventory active + WHERE active.tenant_id = candidate.tenant_id + AND active.playable_state_namespace_id = candidate.playable_state_namespace_id + AND active.character_id = candidate.character_id + AND active.lifecycle = 'ACTIVE') + ) THEN + RAISE EXCEPTION 'First-NEW Account abort requires its exact retained candidate, reservation, and unresolved obligations' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_first_new_abort_source_incomplete'; + END IF; + RETURN NULL; +END; +$$; diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-add.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-add.lua index fe79426301..4a313dc707 100644 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-add.lua +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-add.lua @@ -309,13 +309,15 @@ for index = 1, operationCount do position = position + 6 if not uuid(operationId) or not uuid(reservationId) or (bindingPresent ~= '0' and bindingPresent ~= '1') - or countsCapacity ~= '1' + or (countsCapacity ~= '0' and countsCapacity ~= '1') or type(memberBytes) ~= 'string' or #memberBytes == 0 or #memberBytes > maxMemberValueBytes or seenOperationIds[operationId] or seenReservationIds[reservationId] or seenBindings[bindingRef] then return -2 end local decodedOk, member = pcall(cjson.decode, memberBytes) if not decodedOk or not validMember(member, memberBytes, issuerId, partitionId, metadata, bindingRef, operationId, reservationId) then return -2 end - if member.reservation.lifecycle == 'RELEASED' then return -2 end + if (countsCapacity == '1' and member.reservation.lifecycle == 'RELEASED') + or (countsCapacity == '0' + and (member.reservation.lifecycle ~= 'RELEASED' or bindingPresent ~= '0')) then return -2 end seenOperationIds[operationId] = true seenReservationIds[reservationId] = true seenBindings[bindingRef] = true @@ -325,7 +327,7 @@ for index = 1, operationCount do memberBytes = memberBytes, bindingPresent = bindingPresent } - localCapacity = localCapacity + 1 + if countsCapacity == '1' then localCapacity = localCapacity + 1 end local capacityField = capacityPrefix .. reservationId if not putAllowed(capacityField, memberBytes) then return -2 end if bindingPresent == '1' then diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-release.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-release.lua new file mode 100644 index 0000000000..17a0aa2aa4 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-release.lua @@ -0,0 +1,387 @@ +-- Project one SQL-issued terminal successor and remove only its exact original binding. +-- KEYS[1] is the sole canonical issuer partition hash. +local keyPrefix = 'session:game:index:issuer:' +local metadataField = '!issuer-partition-bootstrap/v1' +local capacityPrefix = '!issuer-reservation-capacity/v1:' +local maxMemberValueBytes = 65536 +local maxMetadataBytes = 65536 +local maxMemberOperations = 256 +local maxHashFields = 1025 +local maxHashBytes = 16777216 + +local function uuid(value) + return type(value) == 'string' and #value == 36 + and string.match(value, '^%x%x%x%x%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x$') + and value == string.lower(value) + and value ~= '00000000-0000-0000-0000-000000000000' +end +local function positive(value) + return type(value) == 'string' and #value > 0 and #value <= 256 + and string.match(value, '^[1-9][0-9]*$') ~= nil +end +local function nonnegative(value) + return value == '0' or positive(value) +end +local function digest(value) + return type(value) == 'string' and #value == 71 + and string.match(value, '^sha256:[0-9a-f]+$') ~= nil +end +local function greaterDecimal(left, right) + if #left ~= #right then return #left > #right end + return left > right +end +local function countKeys(value) + local result = 0 + for _ in pairs(value) do result = result + 1 end + return result +end +local function sameIncarnation(left, right) + if type(left) ~= 'table' or type(right) ~= 'table' + or left.attestorBinding ~= right.attestorBinding + or left.acceptedAttestationDigest ~= right.acceptedAttestationDigest + or left.coordOpsRoAclDigest ~= right.coordOpsRoAclDigest + or left.coordRedisConfigObservedDigest ~= right.coordRedisConfigObservedDigest then return false end + local a = left.targetDeploymentEvidence + local b = right.targetDeploymentEvidence + if type(a) ~= 'table' or type(b) ~= 'table' + or countKeys(a) ~= 11 or countKeys(b) ~= 11 + or a.deploymentIdentity ~= b.deploymentIdentity + or a.deploymentGeneration ~= b.deploymentGeneration + or a.redisBuildIdentity ~= b.redisBuildIdentity + or a.luaScriptRegistryVersion ~= b.luaScriptRegistryVersion + or a.luaScriptRegistryDigest ~= b.luaScriptRegistryDigest + or a.startupState ~= b.startupState + or a.bootGeneration ~= b.bootGeneration + or a.startupGeneration ~= b.startupGeneration + or a.storageGeneration ~= b.storageGeneration + or a.aofGeneration ~= b.aofGeneration + or type(a.canonicalNodeSet) ~= 'table' + or type(b.canonicalNodeSet) ~= 'table' + or #a.canonicalNodeSet ~= #b.canonicalNodeSet then return false end + for index = 1, #a.canonicalNodeSet do + if a.canonicalNodeSet[index] ~= b.canonicalNodeSet[index] then return false end + end + return true +end +local function memberShape(member, issuerId, partitionId, metadata, bindingRef, operationId, reservationId) + if type(member) ~= 'table' or countKeys(member) ~= 21 + or type(member.layout) ~= 'table' or countKeys(member.layout) ~= 5 + or type(member.reservation) ~= 'table' or countKeys(member.reservation) ~= 11 + or type(member.anchor) ~= 'table' or countKeys(member.anchor) ~= 8 + or type(member.memberOperation) ~= 'table' or countKeys(member.memberOperation) ~= 3 + or type(member.incarnation) ~= 'table' or countKeys(member.incarnation) ~= 5 + or type(member.incarnation.targetDeploymentEvidence) ~= 'table' + or member.schemaVersion ~= 2 or member.issuerId ~= issuerId + or member.issuerId ~= metadata.issuerId + or member.issuerAuthGeneration ~= metadata.anchor.issuerAuthGeneration + or member.issuerControlEpoch ~= metadata.issuerControlEpoch + or member.issuerIndexLayoutVersion ~= metadata.layout.version + or member.layout.partitionCount ~= partitionId.partitionCount + or member.layout.partitionCapacity ~= partitionId.partitionCapacity + or member.layout.mappingIdentity ~= metadata.layout.mappingIdentity + or member.layout.descriptorBytes ~= metadata.layout.descriptorBytes + or member.layout.descriptorDigest ~= metadata.layout.descriptorDigest + or member.anchor.issuerCoverageOperationId ~= metadata.anchor.issuerCoverageOperationId + or member.anchor.operationFence ~= metadata.anchor.operationFence + or member.anchor.coverageFence ~= metadata.anchor.coverageFence + or member.anchor.issuerInventorySnapshotRevision ~= metadata.anchor.issuerInventorySnapshotRevision + or member.anchor.sourceCheckpointBytes ~= metadata.anchor.sourceCheckpointBytes + or member.anchor.sourceCheckpointDigest ~= metadata.anchor.sourceCheckpointDigest + or member.anchor.sourceEventBytes ~= metadata.anchor.sourceEventBytes + or member.anchor.sourceEventDigest ~= metadata.anchor.sourceEventDigest + or member.reservation.reservationId ~= reservationId + or member.reservation.partitionId ~= partitionId.partitionId + or member.memberOperation.operationId ~= operationId + or (bindingRef ~= nil and member.reservation.bindingRef ~= bindingRef) + or not uuid(member.accountId) or not uuid(member.tenantId) + or not uuid(member.gameInstanceId) or not uuid(member.sessionId) + or not uuid(member.playableStateNamespaceId) or not uuid(member.characterId) + or not uuid(member.regionId) or not uuid(member.reservation.transitionId) + or not uuid(member.reservation.reservationFence) + or not uuid(member.reservation.issuerCoverageOperationId) + or not positive(member.bindingGeneration) or not positive(member.issuerAuthGeneration) + or not positive(member.issuerIndexLayoutVersion) or not positive(member.regionEpoch) + or not positive(member.issuerControlEpoch) + or not positive(member.layout.partitionCount) or not positive(member.layout.partitionCapacity) + or not positive(member.reservation.issuerCoverageOperationFence) + or not positive(member.reservation.coverageFence) + or not positive(member.reservation.inventorySnapshotRevision) + or not positive(member.reservation.inventoryRevision) + or not positive(member.anchor.operationFence) + or not positive(member.anchor.coverageFence) + or not positive(member.anchor.issuerInventorySnapshotRevision) + or not positive(member.memberOperation.operationFence) + or not positive(member.memberOperation.coverageGeneration) + or not digest(member.layout.descriptorDigest) + or not digest(member.anchor.sourceCheckpointDigest) + or (member.anchor.sourceEventDigest ~= cjson.null and not digest(member.anchor.sourceEventDigest)) + or not sameIncarnation(member.incarnation, metadata.incarnation) then return false end + return member.reservation.lifecycle == 'RESERVED' + or member.reservation.lifecycle == 'BOUND' + or member.reservation.lifecycle == 'RELEASE_PENDING' + or member.reservation.lifecycle == 'RELEASED' +end +local function sameReleaseSource(old, released, originalOperationId, releaseOperationId, sourceRevision) + if type(old) ~= 'table' or type(released) ~= 'table' + or old.schemaVersion ~= 2 or released.schemaVersion ~= 2 + or old.reservation.lifecycle ~= 'RESERVED' + or released.reservation.lifecycle ~= 'RELEASED' + or released.reservation.inventoryRevision ~= sourceRevision + or old.memberOperation.operationId ~= originalOperationId + or released.memberOperation.operationId ~= releaseOperationId + or not positive(old.memberOperation.operationFence) + or not positive(old.memberOperation.coverageGeneration) + or not positive(released.memberOperation.operationFence) + or not positive(released.memberOperation.coverageGeneration) + or not greaterDecimal(released.memberOperation.operationFence, old.memberOperation.operationFence) + or not greaterDecimal(released.memberOperation.coverageGeneration, old.memberOperation.coverageGeneration) + or not greaterDecimal(released.reservation.inventoryRevision, old.reservation.inventoryRevision) then return false end + local sameRoot = { + 'issuerId','accountId','tenantId','gameInstanceId','sessionId','bindingGeneration', + 'issuerAuthGeneration','issuerIndexLayoutVersion','playableStateNamespaceId','characterId', + 'playableStateScope','runtimeGameInstanceId','regionId','regionEpoch','issuerControlEpoch' + } + for _, field in ipairs(sameRoot) do if old[field] ~= released[field] then return false end end + local ol = old.layout; local nl = released.layout + for _, field in ipairs({'partitionCount','partitionCapacity','mappingIdentity','descriptorBytes','descriptorDigest'}) do + if ol[field] ~= nl[field] then return false end + end + local oa = old.anchor; local na = released.anchor + for _, field in ipairs({'issuerCoverageOperationId','operationFence','coverageFence', + 'issuerInventorySnapshotRevision','sourceCheckpointBytes','sourceCheckpointDigest', + 'sourceEventBytes','sourceEventDigest'}) do + if oa[field] ~= na[field] then return false end + end + local orv = old.reservation; local nrv = released.reservation + for _, field in ipairs({'reservationId','bindingRef','transitionId','partitionId','reservationFence', + 'issuerCoverageOperationId','issuerCoverageOperationFence','coverageFence', + 'inventorySnapshotRevision'}) do + if orv[field] ~= nrv[field] then return false end + end + return sameIncarnation(old.incarnation, released.incarnation) +end + +if #KEYS ~= 1 or #ARGV < 16 then return -2 end +if type(KEYS[1]) ~= 'string' or #KEYS[1] > 512 or string.sub(KEYS[1], 1, #keyPrefix) ~= keyPrefix then return -2 end +local issuerId = ARGV[1] +local partitionId = ARGV[2] +local partitionCount = ARGV[3] +local partitionCapacity = ARGV[4] +local baselineCount = tonumber(ARGV[5]) +if issuerId ~= 'firemud-account-service' or not nonnegative(partitionId) + or not positive(partitionCount) or not positive(partitionCapacity) + or not baselineCount or baselineCount < 1 or baselineCount > maxHashFields then return -2 end +local cursor = 6 +local baseline = {} +local baselineCapacity = 0 +local baselineReservations = 0 +local baselineBindings = 0 +local baselineCapacityMembers = {} +local baselineBindingMembers = {} +local metadataBytes = nil +for index = 1, baselineCount do + local field = ARGV[cursor] + local valueBytes = ARGV[cursor + 1] + cursor = cursor + 2 + if type(field) ~= 'string' or #field == 0 or baseline[field] ~= nil + or type(valueBytes) ~= 'string' or #valueBytes == 0 or #valueBytes > maxMemberValueBytes then return -2 end + baseline[field] = valueBytes + if field == metadataField then + metadataBytes = valueBytes + elseif string.sub(field, 1, #capacityPrefix) == capacityPrefix then + local ok, value = pcall(cjson.decode, valueBytes) + local reservationId = string.sub(field, #capacityPrefix + 1) + if not ok or type(value) ~= 'table' or type(value.reservation) ~= 'table' + or not uuid(reservationId) or value.reservation.reservationId ~= reservationId + or not nonnegative(value.reservation.partitionId) then return -2 end + baselineCapacityMembers[reservationId] = valueBytes + baselineReservations = baselineReservations + 1 + if value.reservation.lifecycle ~= 'RELEASED' then baselineCapacity = baselineCapacity + 1 end + else + local ok, value = pcall(cjson.decode, valueBytes) + if not ok or type(value) ~= 'table' or type(value.reservation) ~= 'table' + or string.sub(field, 1, 1) == '!' or value.reservation.bindingRef ~= field then return -2 end + if baselineBindingMembers[value.reservation.reservationId] ~= nil then return -2 end + baselineBindingMembers[value.reservation.reservationId] = valueBytes + baselineBindings = baselineBindings + 1 + end +end +for reservationId, memberBytes in pairs(baselineBindingMembers) do + if baselineCapacityMembers[reservationId] ~= memberBytes then return -2 end +end +if metadataBytes == nil or #metadataBytes > maxMetadataBytes then return -2 end +local metadataOk, metadata = pcall(cjson.decode, metadataBytes) +if not metadataOk or type(metadata) ~= 'table' or metadata.schemaVersion ~= 1 + or metadata.issuerId ~= issuerId or metadata.partitionId ~= partitionId + or type(metadata.layoutTag) ~= 'string' or #metadata.layoutTag ~= 70 + or not string.match(metadata.layoutTag, '^il%-v1%-%x+$') + or type(metadata.bootstrap) ~= 'table' or type(metadata.build) ~= 'table' + or type(metadata.layout) ~= 'table' or type(metadata.anchor) ~= 'table' + or type(metadata.incarnation) ~= 'table' + or metadata.layout.partitionCount ~= partitionCount + or metadata.layout.partitionCapacity ~= partitionCapacity + or metadata.layout.mappingIdentity ~= 'bindingRef/v1;sha256-u256-mod/v1' + or metadata.anchor.issuerCoverageOperationId ~= metadata.bootstrap.operationId + or metadata.anchor.operationFence ~= metadata.bootstrap.operationFence + or metadata.anchor.coverageFence ~= metadata.bootstrap.coverageFence + or metadata.anchor.issuerInventorySnapshotRevision ~= metadata.bootstrap.issuerInventorySnapshotRevision + or metadata.issuerControlEpoch ~= metadata.bootstrap.controlEpoch + or not uuid(metadata.bootstrap.operationId) or not uuid(metadata.bootstrap.requestId) + or not uuid(metadata.build.operationId) + or not positive(metadata.bootstrap.operationFence) + or not positive(metadata.bootstrap.coverageFence) + or not positive(metadata.bootstrap.issuerInventorySnapshotRevision) + or not positive(metadata.issuerControlEpoch) + or not digest(metadata.bootstrap.cohortDigest) + or not digest(metadata.build.planDigest) then return -2 end +local expectedKey = keyPrefix .. '{' .. metadata.layoutTag .. '}:' .. issuerId .. ':' .. partitionId +if KEYS[1] ~= expectedKey or not greaterDecimal(partitionCount, partitionId) then return -2 end +local partition = {partitionId=partitionId, partitionCount=partitionCount, partitionCapacity=partitionCapacity} +for field, valueBytes in pairs(baseline) do + if field ~= metadataField then + local ok, member = pcall(cjson.decode, valueBytes) + if not ok or not memberShape(member, issuerId, partition, metadata, nil, + member.memberOperation.operationId, member.reservation.reservationId) then return -2 end + end +end + +local allowed = {} +local allowedCount = 0 +local allowedBytes = 0 +local function put(field, value) + if type(field) ~= 'string' or #field == 0 or allowed[field] ~= nil then return false end + allowed[field] = value; allowedCount = allowedCount + 1; allowedBytes = allowedBytes + #field + #value + return allowedCount <= maxHashFields and allowedBytes <= maxHashBytes +end +for field, value in pairs(baseline) do if not put(field, value) then return -2 end end +local operationCount = tonumber(ARGV[cursor]) +cursor = cursor + 1 +if not operationCount or operationCount < 1 or operationCount > maxMemberOperations then return -2 end +local operations = {} +local seenOperations = {}; local seenReservations = {}; local seenBindings = {} +local registeredCapacity = 0; local registeredBindings = 0 +for index = 1, operationCount do + local operationId = ARGV[cursor] + local bindingRef = ARGV[cursor + 1] + local reservationId = ARGV[cursor + 2] + local memberBytes = ARGV[cursor + 3] + local bindingPresent = ARGV[cursor + 4] + local countsCapacity = ARGV[cursor + 5] + cursor = cursor + 6 + if not uuid(operationId) or not uuid(reservationId) + or type(bindingRef) ~= 'string' or #bindingRef == 0 + or type(memberBytes) ~= 'string' or #memberBytes == 0 or #memberBytes > maxMemberValueBytes + or (bindingPresent ~= '0' and bindingPresent ~= '1') + or (countsCapacity ~= '0' and countsCapacity ~= '1') + or seenOperations[operationId] or seenReservations[reservationId] or seenBindings[bindingRef] then return -2 end + local ok, member = pcall(cjson.decode, memberBytes) + if not ok or not memberShape(member, issuerId, partition, metadata, bindingRef, operationId, reservationId) then return -2 end + if countsCapacity == '1' and member.reservation.lifecycle == 'RELEASED' then return -2 end + if countsCapacity == '0' and (member.reservation.lifecycle ~= 'RELEASED' or bindingPresent ~= '0') then return -2 end + seenOperations[operationId] = true; seenReservations[reservationId] = true; seenBindings[bindingRef] = true + operations[#operations + 1] = {operationId=operationId, bindingRef=bindingRef, + reservationId=reservationId, memberBytes=memberBytes, + bindingPresent=bindingPresent, countsCapacity=countsCapacity} + if countsCapacity == '1' then registeredCapacity = registeredCapacity + 1 end + if bindingPresent == '1' then registeredBindings = registeredBindings + 1 end + if not put(capacityPrefix .. reservationId, memberBytes) then return -2 end + if bindingPresent == '1' and not put(bindingRef, memberBytes) then return -2 end +end + +local originalOperationId = ARGV[cursor] +local releaseOperationId = ARGV[cursor + 1] +local targetReservationId = ARGV[cursor + 2] +local targetBindingRef = ARGV[cursor + 3] +local originalBytes = ARGV[cursor + 4] +local releasedBytes = ARGV[cursor + 5] +local sourceRevision = ARGV[cursor + 6] +local plannedPartition = ARGV[cursor + 7] +local plannedAggregate = ARGV[cursor + 8] +local aggregateBound = ARGV[cursor + 9] +if #ARGV ~= cursor + 9 or not uuid(originalOperationId) or not uuid(releaseOperationId) + or originalOperationId == releaseOperationId or not uuid(targetReservationId) + or type(targetBindingRef) ~= 'string' or type(originalBytes) ~= 'string' + or type(releasedBytes) ~= 'string' or #originalBytes == 0 or #releasedBytes == 0 + or #originalBytes > maxMemberValueBytes or #releasedBytes > maxMemberValueBytes + or not positive(sourceRevision) or not nonnegative(plannedPartition) + or not nonnegative(plannedAggregate) or not positive(aggregateBound) + or greaterDecimal(plannedPartition, partitionCapacity) + or greaterDecimal(plannedAggregate, aggregateBound) then return -2 end +local oldOk, oldMember = pcall(cjson.decode, originalBytes) +local newOk, newMember = pcall(cjson.decode, releasedBytes) +if not oldOk or not newOk + or not memberShape(oldMember, issuerId, partition, metadata, targetBindingRef, originalOperationId, targetReservationId) + or not memberShape(newMember, issuerId, partition, metadata, targetBindingRef, releaseOperationId, targetReservationId) + or not sameReleaseSource(oldMember, newMember, originalOperationId, releaseOperationId, sourceRevision) then return -2 end +local targetRegistered = false +local targetRegisteredReleased = false +for _, operation in ipairs(operations) do + if operation.reservationId == targetReservationId then + if operation.bindingRef ~= targetBindingRef then return -2 end + if operation.operationId == originalOperationId and operation.memberBytes == originalBytes + and operation.countsCapacity == '1' then targetRegistered = true + elseif operation.operationId == releaseOperationId and operation.memberBytes == releasedBytes + and operation.countsCapacity == '0' and operation.bindingPresent == '0' then + targetRegistered = true + targetRegisteredReleased = true + else return -2 end + elseif operation.operationId == originalOperationId or operation.operationId == releaseOperationId then + return -2 + end +end +if not targetRegistered then return -2 end +local targetCapacityField = capacityPrefix .. targetReservationId +if allowed[targetCapacityField] == nil then + if not put(targetCapacityField, releasedBytes) then return -2 end +else + allowed[targetCapacityField] = releasedBytes +end +-- Keep the original binding in the allowed set only as a permitted preimage; the postimage removes it. +if allowed[targetBindingRef] == nil and not put(targetBindingRef, originalBytes) then return -2 end + +local kind = redis.call('TYPE', KEYS[1]).ok +if kind ~= 'hash' or redis.call('PTTL', KEYS[1]) ~= -1 then return -1 end +local actual = redis.call('HGETALL', KEYS[1]) +if #actual % 2 ~= 0 or #actual / 2 > maxHashFields then return -1 end +local actualFields = {}; local actualCapacity = 0; local actualReservations = 0; local actualBindings = 0 +local actualBytes = 0 +for index = 1, #actual, 2 do + local field = actual[index]; local valueBytes = actual[index + 1] + actualFields[field] = valueBytes; actualBytes = actualBytes + #field + #valueBytes + if actualBytes > maxHashBytes then return -1 end + local expected = allowed[field] + if field == targetCapacityField then + if valueBytes ~= originalBytes and valueBytes ~= releasedBytes then return -1 end + elseif field == targetBindingRef then + if valueBytes ~= originalBytes then return -1 end + elseif expected == nil or expected ~= valueBytes then return -1 end + if string.sub(field, 1, #capacityPrefix) == capacityPrefix then + local ok, member = pcall(cjson.decode, valueBytes) + if not ok or type(member) ~= 'table' or type(member.reservation) ~= 'table' then return -1 end + actualReservations = actualReservations + 1 + if member.reservation.lifecycle ~= 'RELEASED' then actualCapacity = actualCapacity + 1 end + elseif field ~= metadataField then actualBindings = actualBindings + 1 end +end +for field, valueBytes in pairs(baseline) do + if redis.call('HGET', KEYS[1], field) ~= valueBytes then return -1 end +end +local targetCapacityBefore = actualFields[targetCapacityField] +local targetBindingBefore = actualFields[targetBindingRef] +if targetBindingBefore ~= nil and targetCapacityBefore ~= originalBytes then return -1 end +if targetCapacityBefore == releasedBytes and targetBindingBefore ~= nil then return -1 end +if targetCapacityBefore ~= nil and targetCapacityBefore ~= originalBytes and targetCapacityBefore ~= releasedBytes then return -1 end +if targetRegisteredReleased + and (targetCapacityBefore ~= releasedBytes or targetBindingBefore ~= nil) then return -1 end +if actualCapacity > tonumber(plannedPartition) + or actualReservations < baselineReservations + or actualReservations > baselineReservations + operationCount + or actualBindings < baselineBindings + or actualBindings > baselineBindings + registeredBindings then return -1 end + +local alreadyReleased = targetCapacityBefore == releasedBytes and targetBindingBefore == nil +if not alreadyReleased then + redis.call('HSET', KEYS[1], targetCapacityField, releasedBytes) + redis.call('HDEL', KEYS[1], targetBindingRef) + return 1 +end +return 2 diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-add.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-add.json index 8e090902a7..c6da22a71d 100644 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-add.json +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-add.json @@ -1,7 +1,7 @@ { "scriptId": "game-session.issuer-binding-local-add.v1", "resourcePath": "redis/lua/game-session-issuer-binding-local-add.lua", - "sha256": "af4673f3218afb68d6730a5aea901a551c24a128fc86a6e6412a6dc37ad845cf", + "sha256": "a02489c42e6001a8f80340a5d037dfeb10cb30e045dc997eb289700500c1da18", "owner": "game-session-service", "principal": "gamesession_coord_app", "role": "COORDINATION", @@ -30,7 +30,7 @@ {"code": "INVALID_ARGUMENTS_OR_CAPACITY", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} ], "resetSensitivity": "CLUSTER", - "tailLossBehavior": "This local one-key projection requires the exact positively installed issuer anchor, complete immutable partition baseline, and complete SQL-registered post-baseline reservation set. Existing baseline fields must all remain present and exact. A locally registered pending field may be absent or exact, while the physical owner mutates only the target original capacity field and its SQL-qualified target binding field. Missing baseline/header, legacy or malformed values, unknown fields, current source or incarnation movement, or incomplete SQL accounting leaves the operation unqualified. The result is physical readback evidence only; it does not acknowledge issuer-wide coverage, open a barrier, or authorize admission.", + "tailLossBehavior": "This local one-key projection requires the exact positively installed issuer anchor, complete immutable partition baseline, and complete SQL-registered post-baseline reservation set. Existing baseline fields must all remain present and exact. A locally registered pending field may be absent or exact; a completed SQL issuer-local release may appear only as its retained exact RELEASED capacity postimage with its binding absent. The physical owner mutates only the target original capacity field and its SQL-qualified target binding field. Missing baseline/header, legacy or malformed values, unknown fields, current source or incarnation movement, or incomplete SQL accounting leaves the operation unqualified. The result is physical readback evidence only; it does not acknowledge issuer-wide coverage, open a barrier, or authorize admission.", "lossClass": "EMPTY_REDIS_COLD_START_OR_RESET", "compatibilityLevel": "REQUIRES_CLUSTER_RESET", "supportedCoexistence": [ diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-release.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-release.json new file mode 100644 index 0000000000..0d39ded90f --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-release.json @@ -0,0 +1,39 @@ +{ + "scriptId": "game-session.issuer-binding-local-release.v1", + "resourcePath": "redis/lua/game-session-issuer-binding-local-release.lua", + "sha256": "82a94b421725ff3fa4a7e77a16755c929700ea68c13e7b6437e7f1ae472b9b22", + "owner": "game-session-service", + "principal": "gamesession_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "issuerPartition", + "ownedPrefix": "session:game:index:issuer:", + "hashTagDeclaration": "REQUIRED" + } + ], + "arguments": [ + {"name": "issuerId"}, + {"name": "partitionId"}, + {"name": "partitionCount"}, + {"name": "partitionCapacity"}, + {"name": "baselineFieldCountAndExactFieldValuePairs"}, + {"name": "registeredLocalOperationCountAndExactOperationTupleAndCurrentPhase"}, + {"name": "originalAndReleasedMemberOperationAndCapacityProof"} + ], + "category": "SESSION_ISSUER_INDEX", + "outcomes": [ + {"code": "RELEASED_CAPACITY_PROJECTED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "RELEASED_MEMBER_REPLAY", "category": "REPLAY", "effect": "NON_MUTATING"}, + {"code": "TYPE_TTL_OR_FIELDSET_REFUSED", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, + {"code": "INVALID_ARGUMENTS_OR_CAPACITY", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} + ], + "resetSensitivity": "CLUSTER", + "tailLossBehavior": "The one-key release requires the exact installed v2 anchor, complete immutable baseline, current SQL registered local operations, and a genuine Account-aborted first-NEW source. It writes only the SQL-issued RELEASED reservation bytes and removes only that operation's exact original binding field. The terminal V2 value retains its original reservation coverage tuple and installed anchor; its inventoryRevision is the frozen SQL release-preparation source revision P. A later durable SQL receipt advances the current inventory clock to fresh revision R and links P, exact postimage, independent readback, and the original operation. Missing baseline/header, legacy or malformed values, unknown fields, conflicting or newer members, wrong reservation/anchor/incarnation, or changed source fail closed. RELEASE_PENDING remains capacity-counted until exact readback and the guarded SQL completion; only a retained completed RELEASED postimage is excluded from ordinary capacity. No coverage acknowledgement, barrier, or admission authority is produced.", + "lossClass": "EMPTY_REDIS_COLD_START_OR_RESET", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [ + {"callerVersion": "v1", "payloadVersion": "v2"} + ], + "legacyPayloadShape": null +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java index 96854568b9..f9125d4501 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java @@ -1,14 +1,21 @@ package net.firedevops.firemud.gamesession.repository; import java.math.BigInteger; +import java.nio.charset.StandardCharsets; import java.nio.file.Path; -import java.util.UUID; +import java.util.Arrays; import java.util.EnumSet; +import java.util.HashMap; import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; @@ -20,6 +27,10 @@ import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution; +import io.lettuce.core.RedisClient; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -28,9 +39,10 @@ /** * Actual GS durable decision owner for the Account/GS abort composition test. Launch producers, - * initial admission target and empty-cohort/storage/index collaborators remain controlled fixtures. - * The actual migration owner publishes VERIFIED; no collaborator supplies an Account terminal - * result or replaces the GS reverse decision read. + * initial admission target, trusted issuer layout/checkpoint/incarnation, and empty-cohort/storage + * collaborators remain controlled fixtures. The actual bootstrap and migration owners install the + * physical anchor and publish VERIFIED; no collaborator supplies an Account terminal result or + * replaces the GS reverse decision read. */ public final class CanonicalGameplayAdmissionAbortCompositionFixture implements AutoCloseable { private final DriverManagerDataSource dataSource; @@ -41,9 +53,18 @@ public final class CanonicalGameplayAdmissionAbortCompositionFixture implements private final UUID transitionId = UUID.randomUUID(); private final BigInteger generation; private final DSLContext dsl; + private final AtomicReference issuerState; + private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource issuerSource; + private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState initialIssuerState; + private final CanonicalGameplayIssuerBindingLocalOperation localOperation; + private final CanonicalGameplayIssuerBindingLocalProjectionRepository localProjectionRepository; + private final RedisClient issuerRedisClient; + private final RedisScriptCatalog issuerCatalog; + private final Map otherOperations = new HashMap<>(); public CanonicalGameplayAdmissionAbortCompositionFixture( - DriverManagerDataSource accountDataSource, Candidate accountCandidate) { + DriverManagerDataSource accountDataSource, Candidate accountCandidate, RedisClient issuerRedisClient) { + this.issuerRedisClient = java.util.Objects.requireNonNull(issuerRedisClient, "issuerRedisClient"); dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); dataSource.setUrl(accountDataSource.getUrl().replaceAll("currentSchema=[^&]+", "currentSchema=" + schema)); @@ -65,11 +86,42 @@ public CanonicalGameplayAdmissionAbortCompositionFixture( accountCandidate.issuerIndexPartitionCapacity()); establishActualLegacyDisposition(dsl); repository = new CanonicalGameplayBindingInventoryRepository(dsl); - repository.prepare(new CanonicalGameplayBindingTransitionRequest( - transitionId, UUID.randomUUID(), identity, - new CanonicalIssuerReservationFenceEvidence(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), - BigInteger.ONE, BigInteger.ONE, BigInteger.ONE), null, null)); - generation = repository.readProvisionalCasEvidence(transitionId).transition().bindingGeneration(); + BigInteger layoutVersion = identity.issuerIndexLayoutVersion(); + BigInteger partitionCount = identity.issuerIndexPartitionCount(); + BigInteger partitionCapacity = identity.issuerIndexPartitionCapacity(); + String mapping = CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY; + String exactDescriptor = "issuer-layout-descriptor/v1|" + identity.issuerId() + "|" + + layoutVersion + "|" + partitionCount + "|" + partitionCapacity + "|" + mapping; + var trustedLayout = + new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor( + identity.issuerId(), layoutVersion, partitionCount, partitionCapacity, mapping, + exactDescriptor.getBytes(StandardCharsets.UTF_8)); + var sourceCheckpoint = trustedSourceCheckpoint(identity.issuerId(), identity.issuerAuthGeneration()); + UUID bootstrapRequestId = UUID.randomUUID(); + var bootstrapIntent = + new CanonicalGameplayIssuerLayoutBootstrapRepository(dsl) + .beginInitialBootstrapIntent(bootstrapRequestId, trustedLayout, sourceCheckpoint); + initialIssuerState = new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + bootstrapIntent.sourceCheckpoint(), stableIncarnation()); + issuerState = new AtomicReference<>(initialIssuerState); + issuerSource = issuerState::get; + issuerCatalog = RedisScriptCatalog.fromContributions(List.of( + new CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution(), + new CanonicalGameplayIssuerBindingLocalRedisScriptContribution(), + new CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution())); + var partitionOwner = new CanonicalGameplayIssuerBootstrapPartitionRedisOwner( + issuerRedisClient, issuerCatalog, issuerSource); + new CanonicalGameplayIssuerBootstrapCoverageOwner(dsl, partitionOwner, issuerSource) + .completeInitialBootstrap(bootstrapIntent.operationId(), bootstrapRequestId); + var request = new CanonicalGameplayIssuerBindingLocalOperation.Request( + UUID.randomUUID(), transitionId, identity, null, null); + localOperation = new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, issuerSource) + .beginOrResumeOrdinaryNew(request); + generation = localOperation.preparedTransition().bindingGeneration(); + localProjectionRepository = new CanonicalGameplayIssuerBindingLocalProjectionRepository(dsl, issuerSource); + new CanonicalGameplayIssuerBindingLocalRedisOwner( + issuerRedisClient, issuerCatalog, localProjectionRepository, issuerSource) + .projectAndRead(localOperation); } /** Actual migration state machine over explicitly controlled empty-cohort collaborators. */ @@ -149,6 +201,172 @@ public Target target() { public void publish(AccountGameplayAdmissionLeaseEvidence lease) { repository.markProvisional(repository.readProvisionalCasEvidence(transitionId), new CanonicalGameplayAdmissionDecision(transitionId, lease, identity, generation, null, target)); + new CanonicalGameplayIssuerBindingLocalRedisOwner( + issuerRedisClient, issuerCatalog, localProjectionRepository, issuerSource) + .projectAndRead(localOperation); + } + + public CanonicalGameplayIssuerBindingLocalReleaseOperation prepareIssuerRelease() { + return new CanonicalGameplayIssuerBindingLocalReleaseOperationRepository(dsl, issuerSource) + .prepareOrResume(transitionId); + } + + public CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.Readback projectIssuerRelease( + CanonicalGameplayIssuerBindingLocalReleaseOperation operation) { + return new CanonicalGameplayIssuerBindingLocalReleaseRedisOwner( + issuerRedisClient, issuerCatalog, localProjectionRepository, issuerSource) + .releaseAndRead(operation); + } + + /** Models a lost caller response after the real owner has written and independently read back. */ + public void projectIssuerReleaseAndLoseReply( + CanonicalGameplayIssuerBindingLocalReleaseOperation operation) { + var readback = projectIssuerRelease(operation); + if (!readbackHasExactReleasedMember(operation, readback)) { + throw new IllegalStateException("Actual issuer release did not produce its exact terminal readback"); + } + throw new IllegalStateException("controlled lost issuer release reply after physical readback"); + } + + public CanonicalGameplayIssuerBindingLocalReleaseOperation completeIssuerRelease( + CanonicalGameplayIssuerBindingLocalReleaseOperation operation, + CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.Readback readback) { + return new CanonicalGameplayIssuerBindingLocalReleaseOperationRepository(dsl, issuerSource) + .completeWithReadback(operation, readback); + } + + public UUID prepareOtherControllerNew(String seed) { + CanonicalGameplayBindingIdentity other; + do { + other = new CanonicalGameplayBindingIdentity( + identity.accountId(), identity.tenantId(), identity.playableStateNamespaceId(), UUID.randomUUID(), + identity.playableStateScope(), identity.gameInstanceId(), identity.runtimeGameInstanceId(), + UUID.randomUUID().toString(), identity.regionId(), identity.regionEpoch(), identity.issuerId(), + identity.issuerAuthGeneration(), identity.issuerIndexLayoutVersion(), + identity.issuerIndexPartitionCount(), identity.issuerIndexPartitionCapacity()); + } while (!other.bindingRef().partitionId(identity.issuerIndexPartitionCount()) + .equals(localOperation.reservation().partitionId())); + var operation = new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, issuerSource) + .beginOrResumeOrdinaryNew(new CanonicalGameplayIssuerBindingLocalOperation.Request( + UUID.nameUUIDFromBytes((seed + "-request").getBytes(StandardCharsets.UTF_8)), + UUID.nameUUIDFromBytes((seed + "-transition").getBytes(StandardCharsets.UTF_8)), other, null, null)); + otherOperations.put(seed, operation); + return operation.operationId(); + } + + public BigInteger preparedLocalCountedReservations() { + var work = localProjectionRepository.readPreparedPartitionWork(localOperation); + return BigInteger.valueOf(work.localEntries().stream() + .filter(entry -> entry.memberValue().reservation().partitionId() + .equals(localOperation.reservation().partitionId())) + .filter(CanonicalGameplayIssuerBindingLocalProjectionRepository.LocalEntry::countsTowardCapacity) + .count()); + } + + public void moveIssuerIncarnation() { + var current = issuerState.get(); + issuerState.set(new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + current.accountCheckpoint(), stableIncarnation("moved-release-incarnation"))); + } + + public void moveIssuerSourceCheckpoint() { + var current = issuerState.get(); + issuerState.set(new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + trustedSourceCheckpoint(identity.issuerId(), identity.issuerAuthGeneration().add(BigInteger.ONE)), + current.incarnation())); + } + + public void restoreIssuerState() { + issuerState.set(initialIssuerState); + } + + public boolean readbackHasExactReleasedMember( + CanonicalGameplayIssuerBindingLocalReleaseOperation operation, + CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.Readback readback) { + Map fields = CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( + readback.exactPhysicalFieldSetBytes()); + String capacityField = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + operation.releasedMemberValue().reservation().reservationId()); + String bindingField = new String(operation.releasedMemberValue().owner().bindingRef().bytes(), StandardCharsets.UTF_8); + return readback.operationId().equals(operation.operationId()) + && Arrays.equals(fields.get(capacityField), operation.exactReleasedMemberValueBytes()) + && !fields.containsKey(bindingField); + } + + public byte[] readReleaseCapacityValue(CanonicalGameplayIssuerBindingLocalReleaseOperation operation) { + byte[] key = CanonicalGameplayIssuerRedisKeys.forMember(localOperation.memberValue()) + .getBytes(StandardCharsets.US_ASCII); + String field = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + operation.releasedMemberValue().reservation().reservationId()); + try (var connection = issuerRedisClient.connect(io.lettuce.core.codec.ByteArrayCodec.INSTANCE)) { + return connection.sync().hget(key, field.getBytes(StandardCharsets.US_ASCII)); + } + } + + public byte[] readReleaseBindingValue(CanonicalGameplayIssuerBindingLocalReleaseOperation operation) { + byte[] key = CanonicalGameplayIssuerRedisKeys.forMember(localOperation.memberValue()) + .getBytes(StandardCharsets.US_ASCII); + byte[] field = operation.releasedMemberValue().owner().bindingRef().bytes(); + try (var connection = issuerRedisClient.connect(io.lettuce.core.codec.ByteArrayCodec.INSTANCE)) { + return connection.sync().hget(key, field); + } + } + + public byte[] otherMemberValueBytes(String seed) { + var operation = otherOperations.get(seed); + if (operation == null) throw new IllegalArgumentException("Other NEW operation was not prepared"); + return operation.exactMemberValueBytes(); + } + + /** Places another real SQL operation's exact value under this reservation's field as a conflict. */ + public void installConflictingReleaseCapacity( + CanonicalGameplayIssuerBindingLocalReleaseOperation operation, byte[] conflictingBytes) { + byte[] key = CanonicalGameplayIssuerRedisKeys.forMember(localOperation.memberValue()) + .getBytes(StandardCharsets.US_ASCII); + byte[] field = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + operation.releasedMemberValue().reservation().reservationId()).getBytes(StandardCharsets.US_ASCII); + try (var connection = issuerRedisClient.connect(io.lettuce.core.codec.ByteArrayCodec.INSTANCE)) { + connection.sync().hset(key, field, conflictingBytes); + } + } + + public void restoreOriginalReleaseCapacity(CanonicalGameplayIssuerBindingLocalReleaseOperation operation) { + byte[] key = CanonicalGameplayIssuerRedisKeys.forMember(localOperation.memberValue()) + .getBytes(StandardCharsets.US_ASCII); + byte[] field = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + operation.releasedMemberValue().reservation().reservationId()).getBytes(StandardCharsets.US_ASCII); + try (var connection = issuerRedisClient.connect(io.lettuce.core.codec.ByteArrayCodec.INSTANCE)) { + connection.sync().hset(key, field, operation.exactOriginalMemberValueBytes()); + } + } + + /** Injects a conflicting newer member postimage for the negative physical-owner proof. */ + public void installConflictingReleaseBinding( + CanonicalGameplayIssuerBindingLocalReleaseOperation operation) { + byte[] key = CanonicalGameplayIssuerRedisKeys.forMember(localOperation.memberValue()) + .getBytes(StandardCharsets.US_ASCII); + byte[] field = operation.releasedMemberValue().owner().bindingRef().bytes(); + try (var connection = issuerRedisClient.connect(io.lettuce.core.codec.ByteArrayCodec.INSTANCE)) { + connection.sync().hset(key, field, operation.exactReleasedMemberValueBytes()); + } + } + + /** Restores the saved exact preimage after the conflict-preservation assertion. */ + public void restoreOriginalReleaseBinding( + CanonicalGameplayIssuerBindingLocalReleaseOperation operation) { + byte[] key = CanonicalGameplayIssuerRedisKeys.forMember(localOperation.memberValue()) + .getBytes(StandardCharsets.US_ASCII); + byte[] field = operation.originalOperation().memberValue().owner().bindingRef().bytes(); + try (var connection = issuerRedisClient.connect(io.lettuce.core.codec.ByteArrayCodec.INSTANCE)) { + connection.sync().hset(key, field, operation.exactOriginalMemberValueBytes()); + } + } + + public CanonicalGameplayIssuerBindingLocalRedisOwner.Readback projectOtherControllerNew(String seed) { + var operation = otherOperations.get(seed); + if (operation == null) throw new IllegalArgumentException("Other NEW operation was not prepared"); + return new CanonicalGameplayIssuerBindingLocalRedisOwner( + issuerRedisClient, issuerCatalog, localProjectionRepository, issuerSource).projectAndRead(operation); } /** Attempts a newer candidate; the retained unresolved original must fence preparation. */ @@ -174,8 +392,40 @@ public void stopRuntime() { public UUID transitionId() { return transitionId; } public BigInteger generation() { return generation; } public DSLContext dsl() { return dsl; } + public UUID originalOperationId() { return localOperation.operationId(); } + public byte[] originalMemberValueBytes() { return localOperation.exactMemberValueBytes(); } public CanonicalGameplayAdmissionAbortSource source() { return repository.readFirstNewAdmissionAbortSource(transitionId); } + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + trustedSourceCheckpoint(String issuerId, BigInteger generation) { + long sequence = generation.longValueExact() - 1; + var event = AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + UUID.randomUUID().toString(), UUID.randomUUID().toString(), + AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + issuerId, + Long.toString(sequence), issuerId, generation.toString(), generation.toString(), + "ISSUER_SECURITY_CHANGE")); + byte[] bytes = event.canonicalJsonUtf8(); + return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint( + issuerId, generation, bytes, bytes); + } + + private static CanonicalGameplayIssuerMemberV2Value.Incarnation stableIncarnation() { + return stableIncarnation("controlled-release-composition"); + } + + private static CanonicalGameplayIssuerMemberV2Value.Incarnation stableIncarnation(String seed) { + String digest = CanonicalGameplayIssuerMemberV2Codec.sha256( + seed.getBytes(StandardCharsets.UTF_8)); + var deployment = new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "controlled-release-deployment-" + seed, "controlled-release-generation-" + seed, + List.of("controlled-release-node-" + seed), "controlled-release-redis-build-" + seed, + "controlled-release-registry-" + seed, digest, "READY", "controlled-release-boot-" + seed, + "controlled-release-startup-" + seed, "controlled-release-storage-" + seed, "controlled-release-aof-" + seed); + return new CanonicalGameplayIssuerMemberV2Value.Incarnation( + "controlled-release-attestor-" + seed, digest, deployment, digest, digest); + } + @Override public void close() { dsl.execute("DROP SCHEMA \"" + schema + "\" CASCADE"); } From 15ec7c4e0f5b3420ab8a1184375a5e9f7e66cf7f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:36:08 +1300 Subject: [PATCH 14/34] Qualify issuer release and retained original-source recovery --- .../game-session-service/api-contracts.md | 2 +- design/project-management/ai-observations.md | 5 + .../player-access-and-session.md | 6 +- ...nitiveAbortCompositionIntegrationTest.java | 244 ++++-- ...CurrentSourcesPostgresIntegrationTest.java | 3 +- ...lGameplayBindingIssuerIndexObligation.java | 9 +- ...calGameplayBindingInventoryRepository.java | 30 +- ...IssuerBindingLocalOperationRepository.java | 21 +- ...ssuerBindingLocalProjectionRepository.java | 37 +- ...lGameplayIssuerBindingLocalRedisOwner.java | 1 + ...layIssuerBindingLocalReleaseOperation.java | 62 +- ...indingLocalReleaseOperationRepository.java | 822 ++++++++++++------ ...ayIssuerBindingLocalReleaseRedisOwner.java | 134 ++- ...ngLocalReleaseRedisScriptContribution.java | 6 +- ...nonical_issuer_first_new_release_proof.sql | 158 ++++ ...eplayAdmissionAbortCompositionFixture.java | 344 +++++--- ...rtitionBuildRepositoryIntegrationTest.java | 10 + 17 files changed, 1335 insertions(+), 559 deletions(-) diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index fc55dc08ce..e454565fa5 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -8,7 +8,7 @@ Target state makes Game Session the authoritative owner of region/tick coordinat ## Implementation Status -The local issuer-index source carries the selected physical member schema v2 and manually composed SQL, partition and finite initial-coverage owners. Decoding alone validates shape, not current source, anchor, capacity or incarnation authority. Component qualification and the unfinished ordinary-operation and cleanup composition are recorded in the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components); this source is unregistered and supplies no player admission. Retained physical v1 artifacts remain unqualified without fallback, and Account acknowledgement schema v2 remains account-only. The separate owner-qualified issuer acknowledgement and final guarded controller CAS remain required before manual NEW consumers can admit; the [issuer-index owner](../../system-architecture-redis.md#issuer-active-binding-index) owns that contract. +The local issuer-index source carries the selected physical member schema v2 and manually composed SQL, partition and finite initial-coverage owners. Decoding alone validates shape, not current source, anchor, capacity or incarnation authority. Qualified local bootstrap, ordinary physical projection and definitive-abort issuer-local cleanup, together with the remaining admitting acknowledgement and final-CAS gaps, are recorded in the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components); this source is unregistered and supplies no player admission. Retained physical v1 artifacts remain unqualified without fallback, and Account acknowledgement schema v2 remains account-only. The separate owner-qualified issuer acknowledgement and final guarded controller CAS remain required before manual NEW consumers can admit; the [issuer-index owner](../../system-architecture-redis.md#issuer-active-binding-index) owns that contract. The local [canonical NEW admission lease contract](../../system-architecture-session-behavior.md#canonical-public-production-new-admission) now has generated transport carriers and a manually composed `AccountGameplayAdmissionLeaseClient` for Account’s four purpose-specific methods. Its narrow candidate uses the exact Account issuer string at the original string wire tag; shape validation supplies no issuer authority. The [Account API](../account-service/api-contracts.md#canonical-public-production-new-admission-lease-source) owns caller authentication, acquisition, original finalization and read/abort recovery. The prepared Account-only reverse-read proto and closed codec preserve separate current published-target and exact provisional-decision purposes, with their finite transport bounds; this prerequisite does not supply their genuine Game Session owner composition or register a source receiver. The Account receiver’s focused physical-COMMIT and durable-ACK proof uses explicitly controlled reverse responses. These local components do not acknowledge issuer/region obligations or admit a binding; the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) records component proof and remaining composition. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 8a0f63bdf6..782cb9a229 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -411,3 +411,8 @@ Entry format: - Context: `staleSerializableGenuineAckCreatorRetriesAndRetainsOneExactWinner` failed in `finalized()` after 1.292 seconds, before the serializable race began. - Observation: The SQL guard message `storage deadline expired` covers either `evaluatedAt >` the database clock or `expiresAt <=` the database clock, so the branch and clock cause are unknown. Retain the failed result; an unchanged future retry cannot recover the original failure-time clock evidence. - Expected pattern: Capture the original evidence timestamps, JVM and database wall clocks, and monotonic elapsed time only after a failure, without delaying the original COMMIT or changing its lifetime or guard. + +- `2026-10-26`: Adding a nullable column can change frozen complete-row JSON without changing retained data + - Context: In the combined issuer owner, V1035 added a nullable abort identifier and V1036 added a nullable release linkage. Existing `to_jsonb(row)` cohort captures and retained-row assertions then included a new NULL field, so unchanged historical rows appeared to differ from their frozen source bytes. The focused native checks reproduced both cases. + - Observation: Whole-row JSON implicitly includes the database schema. A forward additive column can therefore break byte identity even when every pre-existing value and applied migration is unchanged. This is distinct from a changed non-null owner identity or receipt. + - Expected pattern: Preserve original frozen bytes and applied history. Where the owner contract makes the newly added NULL explicitly absence-equivalent, project out only that named field when NULL in current capture and retained-image comparison; keep non-null values and every other field significant. Prove the populated retained upgrade and exact retry, rather than using generic null stripping or rewriting old evidence. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index d7bcd36157..5ec6719b88 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -24,11 +24,13 @@ The local member-repair acknowledgement also retains its original account-contro The current local issuer source extends the retained V1030 cohort through immutable V1031 plan/work/blocker rows and V1032 SQL-issued member operations. The original reservation coverage tuple remains distinct from the new bootstrap anchor; equal numeric counters across those separate domains are permissible and do not equate their full identities. R569 passes seven PostgreSQL plan cases, including source/control/layout refusal, original retry, retained-row and TRUNCATE guards, and per-partition/aggregate nonterminal reservation bounds with RELEASED exclusion. R575 passes four operation-producer and seven plan-regression cases. The owner allocates the local member-operation fence and generation before projection; those values confer no global coverage generation or completion. -R578 freshly passes the composed four SQL-producer, seven plan-regression and seven physical Redis-owner cases on local checkpoint `a5c2b1c69151029a5be203c720c2618f0866f71a` plus its qualified formatter and test corrections. The actual owner builds or exactly replays one canonical partition HASH, independently reads the complete field set through a separate connection, and brackets the remote phase with controlled current Account checkpoint and stable-incarnation reads. Proof includes populated and positively prepared empty partitions, full original/new tuple conflict, retained terminal reservations, capacity refusal, wrong type/TTL/foreign/v1 evidence, original lost-reply retry and source/incarnation movement. Enabled affected Checkstyle, SpotBugs and formatting pass; all five exact R578 containers are independently confirmed absent. R577 remains a failed aggregate: a fixture incorrectly required independent numeric fences to differ and its status-query helper failed null-safety static analysis; the correction preserves full tuple comparison and exact stored bytes. These results prove local partition projection/readback under controlled collaborators, not operational source or incarnation custody. R579 separately passes all nine PostgreSQL bootstrap-owner cases with enabled affected static analysis and formatting, including the accepted exact pre-intent replay correction, conflicting retry refusal and unchanged durable row/counter images; its exact PostgreSQL container is independently confirmed absent. R583 subsequently passes 33 focused actual PostgreSQL/Redis cases with enabled generation, static analysis and formatting, qualifying the finite initial coverage owner under controlled descriptor, current-source and incarnation collaborators. It retains every partition’s exact proof before allocating the global coverage generation and installing the immutable initial anchor. Exact installed replay reads existing physical state without rebuilding it, and a later counter-head advance preserves the retained anchor. All eight exact containers are independently confirmed absent. These component results do not establish operational source custody or tenant admission. The ordinary post-baseline SQL/Redis path has the focused local qualification below; terminal issuer cleanup remains under implementation. Issuer/region acknowledgements, barrier OPEN, final CAS and playable admission remain unfinished. The complete combined owner scope stays in #3310; the published prefix and unpublished source are not green successor runway. +R578 freshly passes the composed four SQL-producer, seven plan-regression and seven physical Redis-owner cases on local checkpoint `a5c2b1c69151029a5be203c720c2618f0866f71a` plus its qualified formatter and test corrections. The actual owner builds or exactly replays one canonical partition HASH, independently reads the complete field set through a separate connection, and brackets the remote phase with controlled current Account checkpoint and stable-incarnation reads. Proof includes populated and positively prepared empty partitions, full original/new tuple conflict, retained terminal reservations, capacity refusal, wrong type/TTL/foreign/v1 evidence, original lost-reply retry and source/incarnation movement. Enabled affected Checkstyle, SpotBugs and formatting pass; all five exact R578 containers are independently confirmed absent. R577 remains a failed aggregate: a fixture incorrectly required independent numeric fences to differ and its status-query helper failed null-safety static analysis; the correction preserves full tuple comparison and exact stored bytes. These results prove local partition projection/readback under controlled collaborators, not operational source or incarnation custody. R579 separately passes all nine PostgreSQL bootstrap-owner cases with enabled affected static analysis and formatting, including the accepted exact pre-intent replay correction, conflicting retry refusal and unchanged durable row/counter images; its exact PostgreSQL container is independently confirmed absent. R583 subsequently passes 33 focused actual PostgreSQL/Redis cases with enabled generation, static analysis and formatting, qualifying the finite initial coverage owner under controlled descriptor, current-source and incarnation collaborators. It retains every partition’s exact proof before allocating the global coverage generation and installing the immutable initial anchor. Exact installed replay reads existing physical state without rebuilding it, and a later counter-head advance preserves the retained anchor. All eight exact containers are independently confirmed absent. These component results do not establish operational source custody or tenant admission. The ordinary post-baseline SQL/Redis path and first-NEW issuer-local cleanup have the focused qualification below. Separate admitting issuer/region acknowledgements, barrier OPEN, final CAS and playable admission remain unfinished. The complete combined owner scope stays in #3310; the published prefix and unpublished source are not green successor runway. R600 freshly qualifies the ordinary post-baseline SQL-issued local operation and actual one-key Redis member/capacity projection under an installed anchor, with separate complete readback and current-source bracketing. Two native case methods cover the original operation, refusal and retry scenarios; enabled affected static analysis and formatting pass, and all five exact containers are independently confirmed absent. This proves pending physical projection, not a final issuer acknowledgement or admission. -The manually composed first-NEW abort path now joins actual Account current-caller verification, issuance, physical Redis and PostgreSQL abort to the actual Game Session provisional-decision reverse read and guarded retained abort. At local checkpoint `f5f7c132f58538785625334dfea1faf073f0234a`, R607 freshly passes all 52 selected cases: 11 units, 35 issuer PostgreSQL/Redis cases and six actual Account–Game Session composition cases; zero failures, errors or skips. Enabled affected static analysis and formatting pass, and R608 documentation checks pass. All 27 exact R607 containers are independently confirmed absent. The composition uses bidirectional manual mTLS and controlled upstream launch, World/initial-target and test-PKI inputs. It proves exact original lease retention, current-caller and purpose refusal, terminal retry/restart, finalize/abort contention and immutable terminal evidence. The allowed pre-abort account-member ACK case invokes the actual Redis repair owner and SQL acknowledgement, then preserves that exact ADD/readback history through Account abort and restarted retry; it does not relabel the ACK as removal proof. The physical member remains, the candidate is `TERMINAL_UNRESOLVED`, and the issuer reservation is `RELEASE_PENDING`. Physical issuer release, Account cleanup delivery, region cleanup, final controller admission, operational custody and activation remain unproved. The original end-to-end gameplay testing assignment remains parked independently of this focused train proof. +The manually composed first-NEW abort path now joins actual Account current-caller verification, issuance, physical Redis and PostgreSQL abort to the actual Game Session provisional-decision reverse read and guarded retained abort. At local checkpoint `f5f7c132f58538785625334dfea1faf073f0234a`, R607 freshly passes all 52 selected cases: 11 units, 35 issuer PostgreSQL/Redis cases and six actual Account–Game Session composition cases; zero failures, errors or skips. Enabled affected static analysis and formatting pass, and R608 documentation checks pass. All 27 exact R607 containers are independently confirmed absent. The composition uses bidirectional manual mTLS and controlled upstream launch, World/initial-target and test-PKI inputs. It proves exact original lease retention, current-caller and purpose refusal, terminal retry/restart, finalize/abort contention and immutable terminal evidence. The allowed pre-abort account-member ACK case invokes the actual Redis repair owner and SQL acknowledgement, then preserves that exact ADD/readback history through Account abort and restarted retry; it does not relabel the ACK as removal proof. The physical member remains, the candidate is `TERMINAL_UNRESOLVED`, and the issuer reservation is `RELEASE_PENDING`. That checkpoint did not prove physical issuer release; the later combined proof below qualifies the bounded issuer-local consequence. Account cleanup delivery, region cleanup, final controller admission, operational custody and activation remain unproved. The original end-to-end gameplay testing assignment remains parked independently of this focused train proof. + +R625 freshly passes the combined owner gate: 11 unit cases, 35 issuer PostgreSQL/Redis cases and seven actual Account–Game Session cases, with zero failures, errors or skips. Enabled affected Checkstyle, SpotBugs and formatting pass; R626 documentation checks pass. The new release case drives the actual Account abort and retained Game Session source through SQL release preparation, exact one-key Redis mutation and independent complete readback, then a fresh SQL completion. Another registered transition advances the real inventory clock between preparation and completion. Proof preserves the original operation, reservation and anchor bytes, rejects bare terminal flags and conflicting or newer physical members, replays a lost response without new identities, excludes only completed release capacity for subsequent ordinary NEW, and retains exact Account member history through issuer release and a physical post-abort runtime retirement. The [canonical issuer release owner](../../architecture/system-architecture-redis.md#binding-local-issuer-release-provenance) defines the separate preparation and completion revisions. This settles only the binding-local issuer obligation; it does not remove the Account member, settle region cleanup, acknowledge admitting issuer/region membership or make the candidate playable. Earlier failed R617–R624 attempts remain retained evidence. Descriptor, launch/World, current-source/incarnation and test-PKI collaborators remain controlled; operational authority and production activation are not established. ### Player-created roster consumer preparation diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java index 4a7c152879..f3b2aca83b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java @@ -24,8 +24,8 @@ import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionLeaseManualFactory; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.State; -import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortOutcome; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; @@ -273,7 +273,8 @@ void actualConcurrentFinalizeAndAbortHaveOneAccountWinnerWithoutGsCommittedRelab } @Test - void actualAccountAbortedOrdinaryIssuerMemberReleaseHasExactReadbackRetryAndFreesCapacity() throws Exception { + void actualAccountAbortedOrdinaryIssuerMemberReleaseHasExactReadbackRetryAndFreesCapacity() + throws Exception { try (var session = open()) { UUID originalOperationId = session.gs.originalOperationId(); byte[] originalMemberBytes = session.gs.originalMemberValueBytes(); @@ -288,45 +289,75 @@ void actualAccountAbortedOrdinaryIssuerMemberReleaseHasExactReadbackRetryAndFree var pending = session.gs.prepareIssuerRelease(); assertThat(pending.originalOperationId()).isEqualTo(originalOperationId); assertThat(pending.exactOriginalMemberValueBytes()).containsExactly(originalMemberBytes); - assertThat(pending.sourceInventoryRevision()).isGreaterThan(aborted.transition().inventoryRevision()); - assertThat(session.gs.source().transition().inventoryRevision()).isEqualTo(pending.sourceInventoryRevision()); + assertThat(pending.sourceInventoryRevision()) + .isGreaterThan(aborted.transition().inventoryRevision()); + assertThat(session.gs.source().transition().inventoryRevision()) + .isEqualTo(pending.sourceInventoryRevision()); UUID secondOperationId = session.gs.prepareOtherControllerNew("second-controller"); assertThat(secondOperationId).isNotEqualTo(originalOperationId); - var clockAfterOtherWriter = session.gs.dsl().fetchSingle( - "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock WHERE singleton_id = 1") - .get("inventory_revision", java.math.BigDecimal.class).toBigIntegerExact(); + var clockAfterOtherWriter = + session + .gs + .dsl() + .fetchSingle( + "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock WHERE singleton_id = 1") + .get("inventory_revision", java.math.BigDecimal.class) + .toBigIntegerExact(); assertThat(clockAfterOtherWriter).isGreaterThan(pending.sourceInventoryRevision()); - assertThat(session.gs.source().transition().inventoryRevision()).isEqualTo(pending.sourceInventoryRevision()); + assertThat(session.gs.source().transition().inventoryRevision()) + .isEqualTo(pending.sourceInventoryRevision()); assertThat(session.gs.preparedLocalCountedReservations()).isEqualTo(java.math.BigInteger.TWO); assertThatThrownBy(() -> session.gs.prepareOtherControllerNew("full-before-release")) .isInstanceOf(RuntimeException.class) .hasMessageContaining("capacity"); String preparedImage = session.image(); - assertThatThrownBy(() -> session.gs.dsl().execute( - "UPDATE game_session_canonical_issuer_binding_local_release_operation" - + " SET original_member_value_bytes = ? WHERE operation_id = ?", - new byte[] {1}, pending.operationId())) + assertThatThrownBy( + () -> + session + .gs + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_binding_local_release_operation" + + " SET original_member_value_bytes = ? WHERE operation_id = ?", + new byte[] {1}, + pending.operationId())) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(session.image()).isEqualTo(preparedImage); - assertThatThrownBy(() -> session.gs.dsl().execute( - "UPDATE game_session_canonical_issuer_binding_local_release_operation" - + " SET original_reservation_fence = ? WHERE operation_id = ?", - UUID.randomUUID(), pending.operationId())) + assertThatThrownBy( + () -> + session + .gs + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_binding_local_release_operation" + + " SET original_reservation_fence = ? WHERE operation_id = ?", + UUID.randomUUID(), + pending.operationId())) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(session.image()).isEqualTo(preparedImage); - assertThatThrownBy(() -> session.gs.dsl().execute( - "UPDATE game_session_canonical_issuer_binding_local_release_operation" - + " SET anchor_operation_fence = anchor_operation_fence + 1 WHERE operation_id = ?", - pending.operationId())) + assertThatThrownBy( + () -> + session + .gs + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_binding_local_release_operation" + + " SET anchor_operation_fence = anchor_operation_fence + 1 WHERE operation_id = ?", + pending.operationId())) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(session.image()).isEqualTo(preparedImage); - assertThatThrownBy(() -> session.gs.dsl().execute( - "UPDATE game_session_canonical_issuer_partition_reservation" - + " SET lifecycle = 'RELEASED', inventory_revision = inventory_revision + 1" - + " WHERE reservation_id = ?", - pending.abortSource().reservation().reservationId())) + assertThatThrownBy( + () -> + session + .gs + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_partition_reservation" + + " SET lifecycle = 'RELEASED', inventory_revision = inventory_revision + 1" + + " WHERE reservation_id = ?", + pending.abortSource().reservation().reservationId())) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(session.image()).isEqualTo(preparedImage); @@ -352,7 +383,8 @@ void actualAccountAbortedOrdinaryIssuerMemberReleaseHasExactReadbackRetryAndFree session.gs.installConflictingReleaseCapacity(pending, wrongReservationValue); assertThatThrownBy(() -> session.gs.projectIssuerRelease(pending)) .isInstanceOf(RuntimeException.class); - assertThat(session.gs.readReleaseCapacityValue(pending)).containsExactly(wrongReservationValue); + assertThat(session.gs.readReleaseCapacityValue(pending)) + .containsExactly(wrongReservationValue); assertThat(session.gs.readReleaseBindingValue(pending)).containsExactly(originalMemberBytes); session.gs.restoreOriginalReleaseCapacity(pending); @@ -372,13 +404,19 @@ void actualAccountAbortedOrdinaryIssuerMemberReleaseHasExactReadbackRetryAndFree var resumed = session.gs.prepareIssuerRelease(); assertThat(resumed.operationId()).isEqualTo(pending.operationId()); assertThat(resumed.sourceInventoryRevision()).isEqualTo(pending.sourceInventoryRevision()); - assertThat(resumed.exactReleasedMemberValueBytes()).containsExactly(pending.exactReleasedMemberValueBytes()); + assertThat(resumed.exactReleasedMemberValueBytes()) + .containsExactly(pending.exactReleasedMemberValueBytes()); var physicalReadback = session.gs.projectIssuerRelease(resumed); assertThat(physicalReadback.scriptOutcome()).isEqualTo(2L); assertThat(session.gs.readbackHasExactReleasedMember(resumed, physicalReadback)).isTrue(); - var clockBeforeCompletion = session.gs.dsl().fetchSingle( - "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock WHERE singleton_id = 1") - .get("inventory_revision", java.math.BigDecimal.class).toBigIntegerExact(); + var clockBeforeCompletion = + session + .gs + .dsl() + .fetchSingle( + "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock WHERE singleton_id = 1") + .get("inventory_revision", java.math.BigDecimal.class) + .toBigIntegerExact(); assertThat(clockBeforeCompletion).isEqualTo(clockAfterOtherWriter); var afterPhysicalReadback = session.gs.source(); assertThat(afterPhysicalReadback.reservation().lifecycle()) @@ -390,9 +428,9 @@ void actualAccountAbortedOrdinaryIssuerMemberReleaseHasExactReadbackRetryAndFree .isGreaterThan(released.sourceInventoryRevision()); assertThat(released.completionInventoryRevision()).isGreaterThan(clockBeforeCompletion); assertThat(released.exactOriginalMemberValueBytes()).containsExactly(originalMemberBytes); - assertThat(released.releasedMemberValue().reservation().lifecycle()) + assertThat(session.gs.releasedReservation(released).lifecycle()) .isEqualTo(CanonicalIssuerPartitionReservation.Lifecycle.RELEASED); - assertThat(released.releasedMemberValue().reservation().inventoryRevision()) + assertThat(session.gs.releasedReservation(released).inventoryRevision()) .isEqualTo(released.sourceInventoryRevision()); assertThat(session.gs.preparedLocalCountedReservations()).isEqualTo(java.math.BigInteger.ONE); @@ -401,23 +439,41 @@ void actualAccountAbortedOrdinaryIssuerMemberReleaseHasExactReadbackRetryAndFree .isEqualTo(CanonicalIssuerPartitionReservation.Lifecycle.RELEASED); assertThat(source.candidate().lifecycle()) .isEqualTo(CanonicalGameplayBindingInventoryEntry.Lifecycle.TERMINAL_UNRESOLVED); - var issuer = session.gs.dsl().fetchSingle( - "SELECT status, local_release_operation_id, inventory_revision" - + " FROM game_session_canonical_binding_issuer_index_obligation WHERE transition_id = ?", - session.gs.transitionId()); + var issuer = + session + .gs + .dsl() + .fetchSingle( + "SELECT status, local_release_operation_id, inventory_revision" + + " FROM game_session_canonical_binding_issuer_index_obligation WHERE transition_id = ?", + session.gs.transitionId()); assertThat(issuer.get("status", String.class)).isEqualTo("RELEASED"); - assertThat(issuer.get("local_release_operation_id", UUID.class)).isEqualTo(released.operationId()); + assertThat(issuer.get("local_release_operation_id", UUID.class)) + .isEqualTo(released.operationId()); assertThat(issuer.get("inventory_revision", java.math.BigDecimal.class)) .isEqualTo(new java.math.BigDecimal(released.completionInventoryRevision())); - assertThat(session.gs.dsl().fetchSingle( - "SELECT status FROM game_session_canonical_binding_account_index_obligation" - + " WHERE transition_id = ? AND obligation_ordinal = 0", - session.gs.transitionId()).get("status", String.class)).isIn("REQUIRED", "ACKNOWLEDGED"); - assertThat(session.gs.dsl().fetchSingle( - "SELECT status FROM game_session_canonical_binding_region_bridge_obligation WHERE transition_id = ?", - session.gs.transitionId()).get("status", String.class)).isEqualTo("REQUIRED"); - - UUID thirdOperationId = session.gs.prepareOtherControllerNew("freed-capacity-other-controller"); + assertThat( + session + .gs + .dsl() + .fetchSingle( + "SELECT status FROM game_session_canonical_binding_account_index_obligation" + + " WHERE transition_id = ? AND obligation_ordinal = 0", + session.gs.transitionId()) + .get("status", String.class)) + .isIn("REQUIRED", "ACKNOWLEDGED"); + assertThat( + session + .gs + .dsl() + .fetchSingle( + "SELECT status FROM game_session_canonical_binding_region_bridge_obligation WHERE transition_id = ?", + session.gs.transitionId()) + .get("status", String.class)) + .isEqualTo("REQUIRED"); + + UUID thirdOperationId = + session.gs.prepareOtherControllerNew("freed-capacity-other-controller"); assertThat(session.gs.preparedLocalCountedReservations()).isEqualTo(java.math.BigInteger.TWO); var thirdReadback = session.gs.projectOtherControllerNew("freed-capacity-other-controller"); assertThat(thirdReadback.operationId()).isEqualTo(thirdOperationId); @@ -426,18 +482,22 @@ void actualAccountAbortedOrdinaryIssuerMemberReleaseHasExactReadbackRetryAndFree byte[] retainedReadback = released.exactPhysicalReadbackFieldSetBytes(); var releaseReplay = session.gs.prepareIssuerRelease(); assertThat(releaseReplay.operationId()).isEqualTo(released.operationId()); - assertThat(releaseReplay.exactReleasedMemberValueBytes()).containsExactly(released.exactReleasedMemberValueBytes()); + assertThat(releaseReplay.exactReleasedMemberValueBytes()) + .containsExactly(released.exactReleasedMemberValueBytes()); var replayReadback = session.gs.projectIssuerRelease(releaseReplay); assertThat(replayReadback.scriptOutcome()).isEqualTo(2L); var completedReplay = session.gs.completeIssuerRelease(releaseReplay, replayReadback); - assertThat(completedReplay.completionInventoryRevision()).isEqualTo(released.completionInventoryRevision()); - assertThat(completedReplay.exactPhysicalReadbackFieldSetBytes()).containsExactly(retainedReadback); + assertThat(completedReplay.completionInventoryRevision()) + .isEqualTo(released.completionInventoryRevision()); + assertThat(completedReplay.exactPhysicalReadbackFieldSetBytes()) + .containsExactly(retainedReadback); assertThat(session.abort().orphanCleanupId()).isEqualTo(abort.orphanCleanupId()); } } @Test - void actualReverseReadRefusesWrongPeerDecisionAndChangedOriginalTupleWithoutAccountAbort() throws Exception { + void actualReverseReadRefusesWrongPeerDecisionAndChangedOriginalTupleWithoutAccountAbort() + throws Exception { try (var session = open()) { var before = session.image(); assertThat(session.reverse.read(session.gs.transitionId(), session.lease).bindingDecisionId()) @@ -531,15 +591,31 @@ void actualCompletedMemberAckSurvivesAccountAbortAndRetainsUnresolvedPhysicalCle assertThat(session.gs.memberAcknowledgementImage()).isEqualTo(originalAck); assertThat(session.gs.accountObligationPhaseImage()).isEqualTo(originalPhase); } + // Definitive abort permits the actual runtime owner to retire this instance. Cleanup + // must still use the retained original operation, without reopening admission. + session.gs.stopRuntime(); + assertThat( + session + .gs + .dsl() + .fetchSingle( + "SELECT status FROM game_instances WHERE id = ?", + session.gs.target().gameInstanceId()) + .get("status", String.class)) + .isEqualTo("STOPPED"); // Issuer release is independent of the historical account ADD acknowledgement. // The physical account member and its cleanup obligation remain retained throughout. var pendingIssuerRelease = session.gs.prepareIssuerRelease(); var issuerReadback = session.gs.projectIssuerRelease(pendingIssuerRelease); var issuerRelease = session.gs.completeIssuerRelease(pendingIssuerRelease, issuerReadback); - assertThat(issuerRelease.status()).isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); - assertThat(session.gs.source().reservation().lifecycle()).isEqualTo(CanonicalIssuerPartitionReservation.Lifecycle.RELEASED); - assertThat(session.gs.source().candidate().accountIndexState()).isEqualTo(CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED); - assertThat(session.gs.source().candidate().lifecycle()).isEqualTo(CanonicalGameplayBindingInventoryEntry.Lifecycle.TERMINAL_UNRESOLVED); + assertThat(issuerRelease.status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); + assertThat(session.gs.source().reservation().lifecycle()) + .isEqualTo(CanonicalIssuerPartitionReservation.Lifecycle.RELEASED); + assertThat(session.gs.source().candidate().accountIndexState()) + .isEqualTo(CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED); + assertThat(session.gs.source().candidate().lifecycle()) + .isEqualTo(CanonicalGameplayBindingInventoryEntry.Lifecycle.TERMINAL_UNRESOLVED); assertThat(session.gs.memberAcknowledgementImage()).isEqualTo(originalAck); assertThat(session.gs.accountObligationPhaseImage()).isEqualTo(originalPhase); assertThat(session.gs.hasExactAccountMember()).isTrue(); @@ -547,7 +623,11 @@ void actualCompletedMemberAckSurvivesAccountAbortAndRetainsUnresolvedPhysicalCle assertThat(session.abort().orphanCleanupId()).isEqualTo(result.orphanCleanupId()); var replayIssuerRelease = session.gs.prepareIssuerRelease(); var replayIssuerReadback = session.gs.projectIssuerRelease(replayIssuerRelease); - assertThat(session.gs.completeIssuerRelease(replayIssuerRelease, replayIssuerReadback).completionInventoryRevision()) + assertThat( + session + .gs + .completeIssuerRelease(replayIssuerRelease, replayIssuerReadback) + .completionInventoryRevision()) .isEqualTo(issuerRelease.completionInventoryRevision()); assertThat(session.gs.memberAcknowledgementImage()).isEqualTo(originalAck); assertThat(session.gs.accountObligationPhaseImage()).isEqualTo(originalPhase); @@ -590,17 +670,29 @@ private Session(boolean prepareMemberRepair) throws Exception { issuance.accountId(), new CallerIdentity(issuance.callerWorkload(), issuance.callerContextId())); jwt = new String(credential.compactJwtBytes(), StandardCharsets.US_ASCII); - Candidate candidate = - AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.admissionCandidate(accountFixture); - Candidate capacityCandidate = new Candidate( - candidate.accountId(), candidate.tenantId(), candidate.playableStateNamespaceId(), - candidate.characterId(), candidate.playableStateScope(), candidate.gameInstanceId(), - candidate.runtimeGameInstanceId(), candidate.sessionId(), candidate.regionId(), - candidate.regionEpoch(), candidate.issuerId(), candidate.issuerAuthGeneration(), - candidate.issuerIndexLayoutVersion(), candidate.issuerIndexPartitionCount(), - java.math.BigInteger.valueOf(2)); - gs = new CanonicalGameplayAdmissionAbortCompositionFixture( - accountFixture.dataSource, capacityCandidate, redis.issuerOwnerClient()); + Candidate candidate = + AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.admissionCandidate( + accountFixture); + Candidate capacityCandidate = + new Candidate( + candidate.accountId(), + candidate.tenantId(), + candidate.playableStateNamespaceId(), + candidate.characterId(), + candidate.playableStateScope(), + candidate.gameInstanceId(), + candidate.runtimeGameInstanceId(), + candidate.sessionId(), + candidate.regionId(), + candidate.regionEpoch(), + candidate.issuerId(), + candidate.issuerAuthGeneration(), + candidate.issuerIndexLayoutVersion(), + candidate.issuerIndexPartitionCount(), + java.math.BigInteger.valueOf(2)); + gs = + new CanonicalGameplayAdmissionAbortCompositionFixture( + accountFixture.dataSource, capacityCandidate, redis.issuerOwnerClient()); if (prepareMemberRepair) gs.prepareMemberRepairRedis(); pkiDirectory = Files.createTempDirectory(temporaryDirectory, "actual-abort-mtls-"); pki = @@ -690,12 +782,20 @@ private void restartAccount() throws Exception { } private String image() { - return java.util.List.of("game_session_canonical_binding_transition", "game_session_canonical_gameplay_binding_inventory", - "game_session_canonical_issuer_partition_reservation", - "game_session_canonical_binding_issuer_index_obligation", - "game_session_canonical_issuer_binding_local_operation", - "game_session_canonical_issuer_binding_local_release_operation").stream() - .map(table -> gs.dsl().fetch("SELECT to_jsonb(t)::text AS image FROM " + table + " t ORDER BY 1").getValues("image").toString()) + return java.util.List.of( + "game_session_canonical_binding_transition", + "game_session_canonical_gameplay_binding_inventory", + "game_session_canonical_issuer_partition_reservation", + "game_session_canonical_binding_issuer_index_obligation", + "game_session_canonical_issuer_binding_local_operation", + "game_session_canonical_issuer_binding_local_release_operation") + .stream() + .map( + table -> + gs.dsl() + .fetch("SELECT to_jsonb(t)::text AS image FROM " + table + " t ORDER BY 1") + .getValues("image") + .toString()) .collect(java.util.stream.Collectors.joining("\n")); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java index 724f8d67a2..9ec9d15bf8 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java @@ -2321,7 +2321,8 @@ static final class PhysicalRedisFixture implements AutoCloseable { private static final String ACCOUNT_PASSWORD = UUID.randomUUID().toString().replace("-", ""); private static final String PRIMARY_ALIAS = "account-gameplay-admission-primary"; private static final String ISSUER_OWNER = "gamesession_coord_app"; - private static final String ISSUER_OWNER_PASSWORD = UUID.randomUUID().toString().replace("-", ""); + private static final String ISSUER_OWNER_PASSWORD = + UUID.randomUUID().toString().replace("-", ""); private final Network network = Network.newNetwork(); private final GenericContainer primary = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingIssuerIndexObligation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingIssuerIndexObligation.java index 32d54d1032..34288a4aef 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingIssuerIndexObligation.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingIssuerIndexObligation.java @@ -20,7 +20,14 @@ public CanonicalGameplayBindingIssuerIndexObligation( UUID reservationId, Status status, BigInteger inventoryRevision) { - this(transitionId, bindingRef, bindingGeneration, reservationId, status, inventoryRevision, null); + this( + transitionId, + bindingRef, + bindingGeneration, + reservationId, + status, + inventoryRevision, + null); } public CanonicalGameplayBindingIssuerIndexObligation { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index 21238b4ec8..004a6027e6 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -320,7 +320,9 @@ CanonicalGameplayAdmissionAbortSource readFirstNewAdmissionAbortSource(UUID tran }); } - /** Read-only package seam for the local issuer release owner inside its guarded SQL transaction. */ + /** + * Read-only package seam for the local issuer release owner inside its guarded SQL transaction. + */ static CanonicalGameplayAdmissionAbortSource readFirstNewAdmissionAbortSourceInTransaction( DSLContext transaction, UUID transitionId, boolean forUpdate) { Objects.requireNonNull(transaction, "transaction"); @@ -1767,16 +1769,18 @@ private static void requireRetainedFirstNewAbortObligations( throw conflict("Pending issuer release differs from its retained abort source revision"); } } else { + Record releasedReservation = + transaction.fetchOne( + "SELECT * FROM " + RESERVATION + " WHERE reservation_id = ?", + transition.issuerReservationId()); if (releaseOperationId == null - || !CanonicalIssuerPartitionReservation.Lifecycle.RELEASED.equals( - toReservation( - transaction.fetchOne( - "SELECT * FROM " + RESERVATION + " WHERE reservation_id = ?", - transition.issuerReservationId())) - .lifecycle())) { + || releasedReservation == null + || toReservation(releasedReservation).lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED) { throw conflict("Released issuer obligation lacks its exact terminal reservation"); } - requireCompletedIssuerLocalRelease(transaction, transitionId, bindingRef, revision, releaseOperationId); + requireCompletedIssuerLocalRelease( + transaction, transitionId, bindingRef, revision, releaseOperationId); } } @@ -1788,7 +1792,9 @@ static void requireCompletedIssuerLocalRelease( UUID releaseOperationId) { Record release = transaction.fetchOne( - "SELECT * FROM " + ISSUER_LOCAL_RELEASE + " WHERE operation_id = ? AND transition_id = ?", + "SELECT * FROM " + + ISSUER_LOCAL_RELEASE + + " WHERE operation_id = ? AND transition_id = ?", releaseOperationId, transitionId); if (release == null @@ -1825,7 +1831,8 @@ static void requireCompletedIssuerLocalRelease( || !Objects.equals( original.get("reservation_id", UUID.class), release.get("reservation_id", UUID.class)) || !Arrays.equals(original.get("binding_ref", byte[].class), bindingRef)) { - throw conflict("Released issuer receipt no longer retains its immutable original V1034 operation"); + throw conflict( + "Released issuer receipt no longer retains its immutable original V1034 operation"); } CanonicalGameplayIssuerMemberV2Value originalValue; CanonicalGameplayIssuerMemberV2Value releasedValue; @@ -1878,7 +1885,8 @@ static void requireCompletedIssuerLocalRelease( CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( releasedValue.reservation().reservationId()); String memberField = new String(bindingRef, java.nio.charset.StandardCharsets.UTF_8); - if (!Arrays.equals(readback.get(capacityField), releasedBytes) || readback.containsKey(memberField)) { + if (!Arrays.equals(readback.get(capacityField), releasedBytes) + || readback.containsKey(memberField)) { throw conflict("Released issuer receipt lacks its exact positive terminal capacity field"); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java index 6100a3bc89..9c56c8fc67 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java @@ -8,12 +8,13 @@ import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountCoverageEvidence; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerBindingLocalOperation.Request; import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -123,13 +124,12 @@ CanonicalGameplayIssuerBindingLocalOperation readOriginalForIssuerRelease( CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); Record operationRow = transaction.fetchOne( - "SELECT * FROM " - + OPERATION - + " WHERE issuer_id = ? AND transition_id = ?", + "SELECT * FROM " + OPERATION + " WHERE issuer_id = ? AND transition_id = ?", ISSUER, abortSource.transition().transitionId()); if (operationRow == null) { - throw conflict("Account-aborted first-NEW source has no original local issuer operation"); + throw conflict( + "Account-aborted first-NEW source has no original local issuer operation"); } CanonicalGameplayIssuerInstalledAnchor anchor = CanonicalGameplayIssuerBootstrapCoverageRepository @@ -180,8 +180,10 @@ CanonicalGameplayIssuerBindingLocalOperation readOriginalForIssuerRelease( readPositive(operationRow, "operation_fence"), readPositive(operationRow, "local_member_generation")); if (!expected.equals(original) - || !Arrays.equals(exactOriginal, CanonicalGameplayIssuerMemberV2Codec.encode(expected))) { - throw conflict("Original issuer member differs from its exact aborted source or anchor"); + || !Arrays.equals( + exactOriginal, CanonicalGameplayIssuerMemberV2Codec.encode(expected))) { + throw conflict( + "Original issuer member differs from its exact aborted source or anchor"); } try { return new CanonicalGameplayIssuerBindingLocalOperation( @@ -209,7 +211,8 @@ CanonicalGameplayIssuerBindingLocalOperation readOriginalForIssuerRelease( currentIssuerStateSource.readFreshCurrentState(), "current issuer state source returned null after original-operation read"); if (!sameCurrentIssuerState(currentState, after)) { - throw conflict("Issuer source or incarnation moved while reloading the original local operation"); + throw conflict( + "Issuer source or incarnation moved while reloading the original local operation"); } return operation; } @@ -944,7 +947,7 @@ private static void requireCandidateMatchesAnchor( } } - private static boolean sameCurrentIssuerState( + static boolean sameCurrentIssuerState( CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState left, CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState right) { var leftCheckpoint = left.accountCheckpoint(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java index ddf984dcbf..bb3963e250 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java @@ -383,7 +383,13 @@ private LocalEntry readLocalEntry( } CurrentPhase phase = verifyCurrentSourceRows( - transaction, row, member, reservationRow, inventoryRow, transitionRow, issuerObligation); + transaction, + row, + member, + reservationRow, + inventoryRow, + transitionRow, + issuerObligation); requireAccountControlCurrent(transaction, row, member.owner().accountId()); return new LocalEntry( operationId, @@ -506,7 +512,7 @@ private static CurrentPhase verifyCurrentSourceRows( candidateLifecycle, reservationLifecycle, issuerStatus, - releaseOperationId); + null); bindingPresent = true; counted = true; } else if ("ABORTED".equals(transitionStatus) @@ -514,17 +520,19 @@ private static CurrentPhase verifyCurrentSourceRows( && "RELEASED".equals(reservationLifecycle) && "RELEASED".equals(issuerStatus) && releaseOperationId != null) { - var release = CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.readProjection( - transaction, - operationRow, - member, - currentRevision, - transitionStatus, - candidateLifecycle, - reservationLifecycle, - issuerStatus, - releaseOperationId); - if (release == null) throw unavailable("Released issuer reservation lacks its durable exact successor"); + var release = + CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.readProjection( + transaction, + operationRow, + member, + currentRevision, + transitionStatus, + candidateLifecycle, + reservationLifecycle, + issuerStatus, + releaseOperationId); + if (release == null) + throw unavailable("Released issuer reservation lacks its durable exact successor"); projectedOperationId = release.operationId(); projectedBytes = release.exactMemberValueBytes(); projectedMember = release.memberValue(); @@ -959,8 +967,7 @@ private static byte[] currentnessDigest( entries.stream().sorted(Comparator.comparing(LocalEntry::operationId)).toList()) { update(digest, entry.operationId().toString().getBytes(StandardCharsets.US_ASCII)); update( - digest, - entry.registeredOperationId().toString().getBytes(StandardCharsets.US_ASCII)); + digest, entry.registeredOperationId().toString().getBytes(StandardCharsets.US_ASCII)); update(digest, entry.exactRegisteredMemberValueBytes()); update(digest, entry.exactMemberValueBytes()); update(digest, entry.transitionStatus().getBytes(StandardCharsets.US_ASCII)); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java index 3560bc6560..6aeec1e0d5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java @@ -21,6 +21,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperation.java index 4755ea086f..6a25fd5225 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperation.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperation.java @@ -45,18 +45,22 @@ public enum Status { String physicalReadbackDigest, Status status) { this.abortSource = Objects.requireNonNull(abortSource, "Account-aborted source required"); - this.originalOperation = Objects.requireNonNull(originalOperation, "Original SQL operation required"); + this.originalOperation = + Objects.requireNonNull(originalOperation, "Original SQL operation required"); this.operationId = requireNonNil(operationId, "operationId"); this.operationFence = requirePositive(operationFence, "operationFence"); this.localMemberGeneration = requirePositive(localMemberGeneration, "localMemberGeneration"); - this.sourceInventoryRevision = requirePositive(sourceInventoryRevision, "sourceInventoryRevision"); + this.sourceInventoryRevision = + requirePositive(sourceInventoryRevision, "sourceInventoryRevision"); this.completionInventoryRevision = completionInventoryRevision == null ? null : requirePositive(completionInventoryRevision, "completionInventoryRevision"); this.releasedMemberValue = Objects.requireNonNull(releasedMemberValue, "releasedMemberValue"); - this.exactOriginalMemberValueBytes = copyBounded(exactOriginalMemberValueBytes, "original bytes"); - this.exactReleasedMemberValueBytes = copyBounded(exactReleasedMemberValueBytes, "released bytes"); + this.exactOriginalMemberValueBytes = + copyBounded(exactOriginalMemberValueBytes, "original bytes"); + this.exactReleasedMemberValueBytes = + copyBounded(exactReleasedMemberValueBytes, "released bytes"); this.exactPhysicalReadbackFieldSetBytes = exactPhysicalReadbackFieldSetBytes == null ? null @@ -94,25 +98,38 @@ public enum Status { if (!abortSource.isAccountAborted() || abortSource.transition().status() - != net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot.Status.ABORTED + != net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot + .Status.ABORTED || abortSource.candidate().lifecycle() - != net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry.Lifecycle.TERMINAL_UNRESOLVED - || !abortSource.transition().transitionId().equals(originalOperation.request().transitionId()) + != net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry + .Lifecycle.TERMINAL_UNRESOLVED + || !abortSource + .transition() + .transitionId() + .equals(originalOperation.request().transitionId()) || !sourceReservation.reservationId().equals(original.reservation().reservationId()) || !sourceReservation.transitionId().equals(original.reservation().transitionId()) || !sourceReservation.owner().equals(original.owner()) || !sourceReservation.bindingGeneration().equals(original.bindingGeneration()) || !sourceReservation.reservationFence().equals(original.reservation().reservationFence()) - || !sourceReservation.issuerCoverageOperationId().equals(original.reservation().issuerCoverageOperationId()) - || !sourceReservation.issuerCoverageOperationFence().equals(original.reservation().issuerCoverageOperationFence()) + || !sourceReservation + .issuerCoverageOperationId() + .equals(original.reservation().issuerCoverageOperationId()) + || !sourceReservation + .issuerCoverageOperationFence() + .equals(original.reservation().issuerCoverageOperationFence()) || !sourceReservation.coverageFence().equals(original.reservation().coverageFence()) - || !sourceReservation.inventorySnapshotRevision().equals(original.reservation().inventorySnapshotRevision()) + || !sourceReservation + .inventorySnapshotRevision() + .equals(original.reservation().inventorySnapshotRevision()) || (status == Status.PENDING_PHYSICAL_PROOF - && (sourceReservation.lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING + && (sourceReservation.lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING || !sourceReservation.inventoryRevision().equals(sourceInventoryRevision) || this.completionInventoryRevision != null)) || (status == Status.RELEASED - && (sourceReservation.lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED + && (sourceReservation.lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED || this.completionInventoryRevision == null || !sourceReservation.inventoryRevision().equals(this.completionInventoryRevision) || this.completionInventoryRevision.compareTo(sourceInventoryRevision) <= 0)) @@ -121,8 +138,7 @@ public enum Status { || !localMemberGeneration.equals(releasedMemberValue.memberOperation().coverageGeneration()) || !expectedReleased.equals(releasedMemberValue) || !Arrays.equals( - this.exactOriginalMemberValueBytes, - originalOperation.exactMemberValueBytes()) + this.exactOriginalMemberValueBytes, originalOperation.exactMemberValueBytes()) || !Arrays.equals( this.exactOriginalMemberValueBytes, CanonicalGameplayIssuerMemberV2Codec.encode(original)) @@ -133,12 +149,14 @@ public enum Status { || operationFence.compareTo(originalOperation.operationFence()) <= 0 || localMemberGeneration.compareTo(originalOperation.localMemberGeneration()) <= 0 || !operationFence.add(BigInteger.ONE).equals(localMemberGeneration)) { - throw new IllegalArgumentException("Release operation differs from its exact Account-aborted source"); + throw new IllegalArgumentException( + "Release operation differs from its exact Account-aborted source"); } if (status == Status.PENDING_PHYSICAL_PROOF) { if (this.exactPhysicalReadbackFieldSetBytes != null || physicalReadbackDigest != null) { - throw new IllegalArgumentException("Pending release cannot contain physical completion proof"); + throw new IllegalArgumentException( + "Pending release cannot contain physical completion proof"); } } else { if (this.exactPhysicalReadbackFieldSetBytes == null @@ -146,8 +164,10 @@ public enum Status { || this.exactPhysicalReadbackFieldSetBytes.length > 17_825_792 || physicalReadbackDigest == null || !physicalReadbackDigest.equals( - CanonicalGameplayIssuerMemberV2Codec.sha256(this.exactPhysicalReadbackFieldSetBytes))) { - throw new IllegalArgumentException("Released operation lacks its exact physical readback proof"); + CanonicalGameplayIssuerMemberV2Codec.sha256( + this.exactPhysicalReadbackFieldSetBytes))) { + throw new IllegalArgumentException( + "Released operation lacks its exact physical readback proof"); } Map readback = CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( @@ -159,7 +179,8 @@ public enum Status { new String(releasedMemberValue.owner().bindingRef().bytes(), StandardCharsets.UTF_8); if (!Arrays.equals(readback.get(capacityField), this.exactReleasedMemberValueBytes) || readback.containsKey(bindingField)) { - throw new IllegalArgumentException("Released proof does not contain its exact terminal capacity postimage"); + throw new IllegalArgumentException( + "Released proof does not contain its exact terminal capacity postimage"); } } } @@ -232,7 +253,8 @@ private static byte[] copyBounded(byte[] value, String name) { private static UUID requireNonNil(UUID value, String name) { Objects.requireNonNull(value, name); - if (value.equals(new UUID(0L, 0L))) throw new IllegalArgumentException(name + " must not be nil"); + if (value.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException(name + " must not be nil"); return value; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.java index fafc30b2f6..9dd0814ef5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.java @@ -17,24 +17,32 @@ /** SQL owner for one immutable, source-linked physical terminal release successor. */ final class CanonicalGameplayIssuerBindingLocalReleaseOperationRepository { private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; - private static final String RELEASE = "game_session_canonical_issuer_binding_local_release_operation"; + private static final String RELEASE = + "game_session_canonical_issuer_binding_local_release_operation"; private static final String RESERVATION = "game_session_canonical_issuer_partition_reservation"; private static final String INVENTORY = "game_session_canonical_gameplay_binding_inventory"; private static final String TRANSITION = "game_session_canonical_binding_transition"; - private static final String ISSUER_OBLIGATION = "game_session_canonical_binding_issuer_index_obligation"; - private static final String ACCOUNT_OBLIGATION = "game_session_canonical_binding_account_index_obligation"; - private static final String REGION_OBLIGATION = "game_session_canonical_binding_region_bridge_obligation"; + private static final String ISSUER_OBLIGATION = + "game_session_canonical_binding_issuer_index_obligation"; + private static final String ACCOUNT_OBLIGATION = + "game_session_canonical_binding_account_index_obligation"; + private static final String REGION_OBLIGATION = + "game_session_canonical_binding_region_bridge_obligation"; private static final String INVENTORY_CLOCK = "game_session_canonical_binding_inventory_clock"; private final DSLContext dsl; - private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource currentIssuerStateSource; + private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentIssuerStateSource; private final CanonicalGameplayBindingInventoryRepository inventoryRepository; private final CanonicalGameplayIssuerBindingLocalOperationRepository localOperationRepository; - CanonicalGameplayIssuerBindingLocalReleaseOperationRepository(DSLContext dsl, - CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource currentIssuerStateSource) { + CanonicalGameplayIssuerBindingLocalReleaseOperationRepository( + DSLContext dsl, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentIssuerStateSource) { this.dsl = Objects.requireNonNull(dsl, "dsl"); - this.currentIssuerStateSource = Objects.requireNonNull(currentIssuerStateSource, "currentIssuerStateSource"); + this.currentIssuerStateSource = + Objects.requireNonNull(currentIssuerStateSource, "currentIssuerStateSource"); this.inventoryRepository = new CanonicalGameplayBindingInventoryRepository(dsl); this.localOperationRepository = new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, currentIssuerStateSource); @@ -48,44 +56,77 @@ CanonicalGameplayIssuerBindingLocalReleaseOperation prepareOrResume(UUID transit requireAbortedSource(sourceBefore); var issuerStateBefore = readCurrentIssuerState(); var original = localOperationRepository.readOriginalForIssuerRelease(sourceBefore); - var operation = dsl.transactionResult(configuration -> { - DSLContext transaction = org.jooq.impl.DSL.using(configuration); - BigInteger currentRevision = CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - var source = CanonicalGameplayBindingInventoryRepository - .readFirstNewAdmissionAbortSourceInTransaction(transaction, transitionId, true); - requireSameAbortSource(sourceBefore, source); - Record existing = transaction.fetchOne("SELECT * FROM " + RELEASE + " WHERE transition_id = ? FOR UPDATE", transitionId); - if (existing != null) return readOperation(existing, source, original); - if (source.reservation().lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING - || !sameOperationSource(original, source)) { - throw conflict("Issuer release requires its exact pending local registration"); - } - BigInteger priorRevision = source.transition().inventoryRevision(); - if (currentRevision.compareTo(priorRevision) < 0) { - throw conflict("Inventory clock regressed behind the retained Account-abort source"); - } - BigInteger sourceRevision = currentRevision.add(BigInteger.ONE); - requireCounterLimit(sourceRevision, "releasePreparationInventoryRevision"); - advanceAbortSourceRevision(transaction, source, priorRevision, sourceRevision, currentRevision); - source = CanonicalGameplayBindingInventoryRepository - .readFirstNewAdmissionAbortSourceInTransaction(transaction, transitionId, false); - var counters = CanonicalGameplayIssuerBindingLocalOperationRepository.allocateLocalCounters( - transaction, original.anchor(), - withLifecycleAndRevision(original.reservation(), - CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING, sourceRevision)); - UUID releaseId = freshNonNilUuid(); - var releasedValue = createReleasedValue(original.memberValue(), sourceRevision, releaseId, - counters.operationFence(), counters.localMemberGeneration()); - byte[] releasedBytes = CanonicalGameplayIssuerMemberV2Codec.encode(releasedValue); - byte[] originalBytes = original.exactMemberValueBytes(); - insertRelease(transaction, source, original, releaseId, counters.operationFence(), - counters.localMemberGeneration(), sourceRevision, originalBytes, releasedBytes); - Record saved = transaction.fetchOne("SELECT * FROM " + RELEASE + " WHERE operation_id = ? FOR UPDATE", releaseId); - if (saved == null) throw conflict("Issuer release operation was not retained"); - return readOperation(saved, source, original); - }); + var operation = + dsl.transactionResult( + configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + BigInteger currentRevision = + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + var source = + CanonicalGameplayBindingInventoryRepository + .readFirstNewAdmissionAbortSourceInTransaction( + transaction, transitionId, true); + requireSameAbortSource(sourceBefore, source); + Record existing = + transaction.fetchOne( + "SELECT * FROM " + RELEASE + " WHERE transition_id = ? FOR UPDATE", + transitionId); + if (existing != null) return readOperation(existing, source, original); + if (source.reservation().lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING + || !sameOperationSource(original, source)) { + throw conflict("Issuer release requires its exact pending local registration"); + } + BigInteger priorRevision = source.transition().inventoryRevision(); + if (currentRevision.compareTo(priorRevision) < 0) { + throw conflict( + "Inventory clock regressed behind the retained Account-abort source"); + } + BigInteger sourceRevision = currentRevision.add(BigInteger.ONE); + requireCounterLimit(sourceRevision, "releasePreparationInventoryRevision"); + advanceAbortSourceRevision( + transaction, source, priorRevision, sourceRevision, currentRevision); + source = + CanonicalGameplayBindingInventoryRepository + .readFirstNewAdmissionAbortSourceInTransaction( + transaction, transitionId, false); + var counters = + CanonicalGameplayIssuerBindingLocalOperationRepository.allocateLocalCounters( + transaction, + original.anchor(), + withLifecycleAndRevision( + original.reservation(), + CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING, + sourceRevision)); + UUID releaseId = freshNonNilUuid(); + var releasedValue = + createReleasedValue( + original.memberValue(), + sourceRevision, + releaseId, + counters.operationFence(), + counters.localMemberGeneration()); + byte[] releasedBytes = CanonicalGameplayIssuerMemberV2Codec.encode(releasedValue); + byte[] originalBytes = original.exactMemberValueBytes(); + insertRelease( + transaction, + source, + original, + releaseId, + counters.operationFence(), + counters.localMemberGeneration(), + sourceRevision, + originalBytes, + releasedBytes); + Record saved = + transaction.fetchOne( + "SELECT * FROM " + RELEASE + " WHERE operation_id = ? FOR UPDATE", releaseId); + if (saved == null) throw conflict("Issuer release operation was not retained"); + return readOperation(saved, source, original); + }); requireSameCurrentIssuerState(issuerStateBefore, readCurrentIssuerState()); - requireSameAbortIdentity(sourceBefore, inventoryRepository.readFirstNewAdmissionAbortSource(transitionId)); + requireSameAbortIdentity( + sourceBefore, inventoryRepository.readFirstNewAdmissionAbortSource(transitionId)); return operation; } @@ -102,125 +143,187 @@ CanonicalGameplayIssuerBindingLocalReleaseOperation completeWithReadback( byte[] readbackBytes = readback.exactPhysicalFieldSetBytes(); String readbackDigest = CanonicalGameplayIssuerMemberV2Codec.sha256(readbackBytes); var issuerStateBefore = readCurrentIssuerState(); - var completed = dsl.transactionResult(configuration -> { - DSLContext transaction = org.jooq.impl.DSL.using(configuration); - BigInteger currentRevision = - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - UUID transitionId = expected.abortSource().transition().transitionId(); - var source = CanonicalGameplayBindingInventoryRepository - .readFirstNewAdmissionAbortSourceInTransaction(transaction, transitionId, true); - requireExactReleaseSource(expected, source); - Record releaseRow = - transaction.fetchOne("SELECT * FROM " + RELEASE + " WHERE operation_id = ? FOR UPDATE", - expected.operationId()); - if (releaseRow == null) throw conflict("SQL issuer release operation disappeared"); - var current = readOperation(releaseRow, source, expected.originalOperation()); - requireSameOperation(expected, current); - if (current.status() == CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED) { - verifyReadbackMatchesOperation(current, readbackBytes, readbackDigest); - return current; - } - if (source.reservation().lifecycle() - != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING) { - throw conflict("Pending issuer release no longer has its exact RELEASE_PENDING source"); - } - if (currentRevision.compareTo(current.sourceInventoryRevision()) < 0) { - throw conflict("Inventory clock regressed behind the durable issuer release preparation"); - } - verifyReadbackMatchesOperation(current, readbackBytes, readbackDigest); - BigInteger completionRevision = currentRevision.add(BigInteger.ONE); - requireCounterLimit(completionRevision, "completionInventoryRevision"); - requireOne(transaction.execute( - "UPDATE " + RELEASE - + " SET status = 'RELEASED', physical_readback_field_set_bytes = ?," - + " physical_readback_field_set_digest = ?, completion_inventory_revision = ?," - + " completed_at = CURRENT_TIMESTAMP WHERE operation_id = ?" - + " AND status = 'PENDING_PHYSICAL_PROOF' AND source_inventory_revision = ?", - readbackBytes, readbackDigest, decimal(completionRevision), current.operationId(), - decimal(current.sourceInventoryRevision())), - "Issuer release completion lost its guarded SQL operation compare-and-set"); - requireOne(transaction.execute( - "UPDATE " + ISSUER_OBLIGATION - + " SET status = 'RELEASED', local_release_operation_id = ?, inventory_revision = ?" - + " WHERE transition_id = ? AND binding_ref = ? AND reservation_id = ?" - + " AND status = 'REQUIRED' AND local_release_operation_id IS NULL" - + " AND inventory_revision = ?", - current.operationId(), decimal(completionRevision), transitionId, - source.transition().bindingRef().bytes(), source.reservation().reservationId(), - decimal(current.sourceInventoryRevision())), - "Physical issuer release lost its exact local V29 obligation compare-and-set"); - requireOne(transaction.execute( - "UPDATE " + RESERVATION + " SET lifecycle = 'RELEASED', inventory_revision = ?" - + " WHERE reservation_id = ? AND transition_id = ? AND lifecycle = 'RELEASE_PENDING'" - + " AND inventory_revision = ? AND binding_ref = ? AND binding_generation = ?" - + " AND reservation_fence = ? AND issuer_coverage_operation_id = ?" - + " AND issuer_coverage_operation_fence = ? AND coverage_fence = ?" - + " AND inventory_snapshot_revision = ? AND account_id = ? AND tenant_id = ?" - + " AND playable_state_namespace_id = ? AND character_id = ?" - + " AND game_instance_id = ? AND runtime_game_instance_id = ? AND session_id = ?" - + " AND region_id = ? AND region_epoch = ? AND issuer_id = ? AND issuer_auth_generation = ?", - decimal(completionRevision), source.reservation().reservationId(), transitionId, - decimal(current.sourceInventoryRevision()), source.transition().bindingRef().bytes(), - decimal(source.transition().bindingGeneration()), source.reservation().reservationFence(), - source.reservation().issuerCoverageOperationId(), - decimal(source.reservation().issuerCoverageOperationFence()), - decimal(source.reservation().coverageFence()), - decimal(source.reservation().inventorySnapshotRevision()), - source.candidate().identity().accountId(), source.candidate().identity().tenantId(), - source.candidate().identity().playableStateNamespaceId(), - source.candidate().identity().characterId(), source.candidate().identity().gameInstanceId(), - source.candidate().identity().runtimeGameInstanceId(), source.candidate().identity().sessionId(), - source.candidate().identity().regionId(), decimal(source.candidate().identity().regionEpoch()), - source.candidate().identity().issuerId(), - decimal(source.candidate().identity().issuerAuthGeneration())), - "Issuer release lost its exact original reservation compare-and-set"); - requireOne(transaction.execute( - "UPDATE " + INVENTORY + " SET inventory_revision = ?" - + " WHERE binding_ref = ? AND transition_id = ?" - + " AND lifecycle = 'TERMINAL_UNRESOLVED' AND inventory_revision = ?" - + " AND binding_generation = ? AND issuer_reservation_id = ?", - decimal(completionRevision), source.transition().bindingRef().bytes(), transitionId, - decimal(current.sourceInventoryRevision()), decimal(source.transition().bindingGeneration()), - source.reservation().reservationId()), - "Issuer release lost its retained unresolved candidate compare-and-set"); - requireOne(transaction.execute( - "UPDATE " + TRANSITION + " SET inventory_revision = ?" - + " WHERE transition_id = ? AND status = 'ABORTED'" - + " AND admission_orphan_cleanup_id = ? AND inventory_revision = ?" - + " AND candidate_binding_ref = ? AND candidate_binding_generation = ?" - + " AND issuer_reservation_id = ?", - decimal(completionRevision), transitionId, source.orphanCleanupId(), - decimal(current.sourceInventoryRevision()), source.transition().bindingRef().bytes(), - decimal(source.transition().bindingGeneration()), source.reservation().reservationId()), - "Issuer release lost its immutable Account-abort source revision compare-and-set"); - requireOne(transaction.execute( - "UPDATE " + ACCOUNT_OBLIGATION + " SET inventory_revision = ?" - + " WHERE transition_id = ? AND inventory_revision = ?", - decimal(completionRevision), transitionId, decimal(current.sourceInventoryRevision())), - "Issuer release lost its retained Account obligation revision compare-and-set"); - requireOne(transaction.execute( - "UPDATE " + REGION_OBLIGATION + " SET inventory_revision = ?" - + " WHERE transition_id = ? AND inventory_revision = ?", - decimal(completionRevision), transitionId, decimal(current.sourceInventoryRevision())), - "Issuer release lost its retained region obligation revision compare-and-set"); - requireOne(transaction.execute( - "UPDATE " + INVENTORY_CLOCK + " SET inventory_revision = ?" - + " WHERE singleton_id = 1 AND inventory_revision = ?", - decimal(completionRevision), decimal(currentRevision)), - "Issuer release lost the current inventory-clock compare-and-set"); - var completedSource = CanonicalGameplayBindingInventoryRepository - .readFirstNewAdmissionAbortSourceInTransaction(transaction, transitionId, false); - Record completedRow = transaction.fetchOne( - "SELECT * FROM " + RELEASE + " WHERE operation_id = ?", expected.operationId()); - if (completedRow == null) throw conflict("Released issuer operation disappeared after completion"); - return readOperation(completedRow, completedSource, expected.originalOperation()); - }); + var completed = + dsl.transactionResult( + configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + BigInteger currentRevision = + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + UUID transitionId = expected.abortSource().transition().transitionId(); + var source = + CanonicalGameplayBindingInventoryRepository + .readFirstNewAdmissionAbortSourceInTransaction( + transaction, transitionId, true); + requireExactReleaseSource(expected, source); + Record releaseRow = + transaction.fetchOne( + "SELECT * FROM " + RELEASE + " WHERE operation_id = ? FOR UPDATE", + expected.operationId()); + if (releaseRow == null) throw conflict("SQL issuer release operation disappeared"); + var current = readOperation(releaseRow, source, expected.originalOperation()); + requireSameOperation(expected, current); + if (current.status() + == CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED) { + verifyReadbackMatchesOperation(current, readbackBytes, readbackDigest); + return current; + } + if (source.reservation().lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING) { + throw conflict( + "Pending issuer release no longer has its exact RELEASE_PENDING source"); + } + if (currentRevision.compareTo(current.sourceInventoryRevision()) < 0) { + throw conflict( + "Inventory clock regressed behind the durable issuer release preparation"); + } + verifyReadbackMatchesOperation(current, readbackBytes, readbackDigest); + BigInteger completionRevision = currentRevision.add(BigInteger.ONE); + requireCounterLimit(completionRevision, "completionInventoryRevision"); + requireOne( + transaction.execute( + "UPDATE " + + RELEASE + + " SET status = 'RELEASED', physical_readback_field_set_bytes = ?," + + " physical_readback_field_set_digest = ?, completion_inventory_revision = ?," + + " completed_at = CURRENT_TIMESTAMP WHERE operation_id = ?" + + " AND status = 'PENDING_PHYSICAL_PROOF' AND source_inventory_revision = ?", + readbackBytes, + readbackDigest, + decimal(completionRevision), + current.operationId(), + decimal(current.sourceInventoryRevision())), + "Issuer release completion lost its guarded SQL operation compare-and-set"); + requireOne( + transaction.execute( + "UPDATE " + + ISSUER_OBLIGATION + + " SET status = 'RELEASED', local_release_operation_id = ?, inventory_revision = ?" + + " WHERE transition_id = ? AND binding_ref = ? AND reservation_id = ?" + + " AND status = 'REQUIRED' AND local_release_operation_id IS NULL" + + " AND inventory_revision = ?", + current.operationId(), + decimal(completionRevision), + transitionId, + source.transition().bindingRef().bytes(), + source.reservation().reservationId(), + decimal(current.sourceInventoryRevision())), + "Physical issuer release lost its exact local V29 obligation compare-and-set"); + requireOne( + transaction.execute( + "UPDATE " + + RESERVATION + + " SET lifecycle = 'RELEASED', inventory_revision = ?" + + " WHERE reservation_id = ? AND transition_id = ? AND lifecycle = 'RELEASE_PENDING'" + + " AND inventory_revision = ? AND binding_ref = ? AND binding_generation = ?" + + " AND reservation_fence = ? AND issuer_coverage_operation_id = ?" + + " AND issuer_coverage_operation_fence = ? AND coverage_fence = ?" + + " AND inventory_snapshot_revision = ? AND account_id = ? AND tenant_id = ?" + + " AND playable_state_namespace_id = ? AND character_id = ?" + + " AND game_instance_id = ? AND runtime_game_instance_id = ? AND session_id = ?" + + " AND region_id = ? AND region_epoch = ? AND issuer_id = ? AND issuer_auth_generation = ?", + decimal(completionRevision), + source.reservation().reservationId(), + transitionId, + decimal(current.sourceInventoryRevision()), + source.transition().bindingRef().bytes(), + decimal(source.transition().bindingGeneration()), + source.reservation().reservationFence(), + source.reservation().issuerCoverageOperationId(), + decimal(source.reservation().issuerCoverageOperationFence()), + decimal(source.reservation().coverageFence()), + decimal(source.reservation().inventorySnapshotRevision()), + source.candidate().identity().accountId(), + source.candidate().identity().tenantId(), + source.candidate().identity().playableStateNamespaceId(), + source.candidate().identity().characterId(), + source.candidate().identity().gameInstanceId(), + source.candidate().identity().runtimeGameInstanceId(), + source.candidate().identity().sessionId(), + source.candidate().identity().regionId(), + decimal(source.candidate().identity().regionEpoch()), + source.candidate().identity().issuerId(), + decimal(source.candidate().identity().issuerAuthGeneration())), + "Issuer release lost its exact original reservation compare-and-set"); + requireOne( + transaction.execute( + "UPDATE " + + INVENTORY + + " SET inventory_revision = ?" + + " WHERE binding_ref = ? AND transition_id = ?" + + " AND lifecycle = 'TERMINAL_UNRESOLVED' AND inventory_revision = ?" + + " AND binding_generation = ? AND issuer_reservation_id = ?", + decimal(completionRevision), + source.transition().bindingRef().bytes(), + transitionId, + decimal(current.sourceInventoryRevision()), + decimal(source.transition().bindingGeneration()), + source.reservation().reservationId()), + "Issuer release lost its retained unresolved candidate compare-and-set"); + requireOne( + transaction.execute( + "UPDATE " + + TRANSITION + + " SET inventory_revision = ?" + + " WHERE transition_id = ? AND status = 'ABORTED'" + + " AND admission_orphan_cleanup_id = ? AND inventory_revision = ?" + + " AND candidate_binding_ref = ? AND candidate_binding_generation = ?" + + " AND issuer_reservation_id = ?", + decimal(completionRevision), + transitionId, + source.orphanCleanupId(), + decimal(current.sourceInventoryRevision()), + source.transition().bindingRef().bytes(), + decimal(source.transition().bindingGeneration()), + source.reservation().reservationId()), + "Issuer release lost its immutable Account-abort source revision compare-and-set"); + requireOne( + transaction.execute( + "UPDATE " + + ACCOUNT_OBLIGATION + + " SET inventory_revision = ?" + + " WHERE transition_id = ? AND inventory_revision = ?", + decimal(completionRevision), + transitionId, + decimal(current.sourceInventoryRevision())), + "Issuer release lost its retained Account obligation revision compare-and-set"); + requireOne( + transaction.execute( + "UPDATE " + + REGION_OBLIGATION + + " SET inventory_revision = ?" + + " WHERE transition_id = ? AND inventory_revision = ?", + decimal(completionRevision), + transitionId, + decimal(current.sourceInventoryRevision())), + "Issuer release lost its retained region obligation revision compare-and-set"); + requireOne( + transaction.execute( + "UPDATE " + + INVENTORY_CLOCK + + " SET inventory_revision = ?" + + " WHERE singleton_id = 1 AND inventory_revision = ?", + decimal(completionRevision), + decimal(currentRevision)), + "Issuer release lost the current inventory-clock compare-and-set"); + var completedSource = + CanonicalGameplayBindingInventoryRepository + .readFirstNewAdmissionAbortSourceInTransaction( + transaction, transitionId, false); + Record completedRow = + transaction.fetchOne( + "SELECT * FROM " + RELEASE + " WHERE operation_id = ?", + expected.operationId()); + if (completedRow == null) + throw conflict("Released issuer operation disappeared after completion"); + return readOperation(completedRow, completedSource, expected.originalOperation()); + }); requireSameCurrentIssuerState(issuerStateBefore, readCurrentIssuerState()); - CanonicalGameplayAdmissionAbortSource sourceAfter = inventoryRepository.readFirstNewAdmissionAbortSource( - completed.abortSource().transition().transitionId()); - if (!completed.abortSource().equals(sourceAfter)) { - throw conflict("Completed issuer release source changed after its guarded SQL receipt"); - } + CanonicalGameplayAdmissionAbortSource sourceAfter = + inventoryRepository.readFirstNewAdmissionAbortSource( + completed.abortSource().transition().transitionId()); + // The decision is reparsed on each read and deliberately has no object-identity equality. + // Compare the complete durable value source and its exact original lease/target instead. + requireSameAbortSource(completed.abortSource(), sourceAfter); return completed; } @@ -236,37 +339,53 @@ private CanonicalGameplayIssuerBindingLocalReleaseOperation readOperation( || !Arrays.equals(bytes(row, "binding_ref"), source.transition().bindingRef().bytes()) || !positive(row, "binding_generation").equals(source.transition().bindingGeneration()) || !nonnegative(row, "partition_id").equals(source.reservation().partitionId()) - || !uuid(row, "original_reservation_fence").equals(original.reservation().reservationFence()) - || !uuid(row, "original_issuer_coverage_operation_id").equals(original.reservation().issuerCoverageOperationId()) - || !positive(row, "original_issuer_coverage_operation_fence").equals(original.reservation().issuerCoverageOperationFence()) + || !uuid(row, "original_reservation_fence") + .equals(original.reservation().reservationFence()) + || !uuid(row, "original_issuer_coverage_operation_id") + .equals(original.reservation().issuerCoverageOperationId()) + || !positive(row, "original_issuer_coverage_operation_fence") + .equals(original.reservation().issuerCoverageOperationFence()) || !positive(row, "original_coverage_fence").equals(original.reservation().coverageFence()) - || !positive(row, "original_inventory_snapshot_revision").equals(original.reservation().inventorySnapshotRevision()) - || !positive(row, "original_reservation_inventory_revision").equals(original.reservation().inventoryRevision()) + || !positive(row, "original_inventory_snapshot_revision") + .equals(original.reservation().inventorySnapshotRevision()) + || !positive(row, "original_reservation_inventory_revision") + .equals(original.reservation().inventoryRevision()) || !positive(row, "original_local_operation_fence").equals(original.operationFence()) - || !positive(row, "original_local_member_generation").equals(original.localMemberGeneration()) - || !uuid(row, "anchor_issuer_coverage_operation_id").equals(original.anchor().issuerCoverageOperationId()) + || !positive(row, "original_local_member_generation") + .equals(original.localMemberGeneration()) + || !uuid(row, "anchor_issuer_coverage_operation_id") + .equals(original.anchor().issuerCoverageOperationId()) || !positive(row, "anchor_operation_fence").equals(original.anchor().operationFence()) || !positive(row, "anchor_coverage_fence").equals(original.anchor().coverageFence()) - || !positive(row, "anchor_inventory_snapshot_revision").equals(original.anchor().issuerInventorySnapshotRevision()) - || !Arrays.equals(bytes(row, "original_member_value_bytes"), original.exactMemberValueBytes()) + || !positive(row, "anchor_inventory_snapshot_revision") + .equals(original.anchor().issuerInventorySnapshotRevision()) + || !Arrays.equals( + bytes(row, "original_member_value_bytes"), original.exactMemberValueBytes()) || !text(row, "original_member_value_digest").equals(original.memberValueDigest()) - || !text(row, "original_member_value_digest").equals( - CanonicalGameplayIssuerMemberV2Codec.sha256(bytes(row, "original_member_value_bytes"))) - || !text(row, "released_member_value_digest").equals( - CanonicalGameplayIssuerMemberV2Codec.sha256(bytes(row, "released_member_value_bytes")))) { - throw conflict("Stored issuer release differs from its immutable original registration or abort source"); + || !text(row, "original_member_value_digest") + .equals( + CanonicalGameplayIssuerMemberV2Codec.sha256( + bytes(row, "original_member_value_bytes"))) + || !text(row, "released_member_value_digest") + .equals( + CanonicalGameplayIssuerMemberV2Codec.sha256( + bytes(row, "released_member_value_bytes")))) { + throw conflict( + "Stored issuer release differs from its immutable original registration or abort source"); } UUID operationId = uuid(row, "operation_id"); BigInteger sourceRevision = positive(row, "source_inventory_revision"); CanonicalGameplayIssuerMemberV2Value releasedValue; try { - releasedValue = CanonicalGameplayIssuerMemberV2Codec.decode(bytes(row, "released_member_value_bytes")); + releasedValue = + CanonicalGameplayIssuerMemberV2Codec.decode(bytes(row, "released_member_value_bytes")); } catch (RuntimeException malformed) { throw conflict("Stored issuer release postimage is not canonical schema v2"); } CanonicalGameplayIssuerBindingLocalReleaseOperation.Status status; try { - status = CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.valueOf(text(row, "status")); + status = + CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.valueOf(text(row, "status")); } catch (RuntimeException malformed) { throw conflict("Stored issuer release status is malformed"); } @@ -274,10 +393,12 @@ private CanonicalGameplayIssuerBindingLocalReleaseOperation readOperation( String physicalDigest = row.get("physical_readback_field_set_digest", String.class); BigInteger completionRevision = nullablePositive(row, "completion_inventory_revision"); if ((status == CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.PENDING_PHYSICAL_PROOF - && (source.reservation().lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING + && (source.reservation().lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING || !source.reservation().inventoryRevision().equals(sourceRevision))) || (status == CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED - && (source.reservation().lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED + && (source.reservation().lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED || !Objects.equals(source.reservation().inventoryRevision(), completionRevision) || completionRevision == null || completionRevision.compareTo(sourceRevision) <= 0))) { @@ -328,7 +449,9 @@ static ReleaseProjection readProjection( Record transition = transaction.fetchOne( "SELECT admission_orphan_cleanup_id, candidate_binding_ref," - + " candidate_binding_generation FROM " + TRANSITION + " WHERE transition_id = ?", + + " candidate_binding_generation FROM " + + TRANSITION + + " WHERE transition_id = ?", uuid(row, "transition_id")); if (!originalOperationId.equals(uuid(row, "original_local_operation_id")) || !uuid(row, "transition_id").equals(uuid(originalOperationRow, "transition_id")) @@ -336,12 +459,14 @@ static ReleaseProjection readProjection( || !Arrays.equals(bytes(row, "binding_ref"), originalValue.owner().bindingRef().bytes()) || !positive(row, "binding_generation").equals(originalValue.bindingGeneration()) || !nonnegative(row, "partition_id").equals(originalValue.reservation().partitionId()) - || !uuid(row, "original_reservation_fence").equals(originalValue.reservation().reservationFence()) + || !uuid(row, "original_reservation_fence") + .equals(originalValue.reservation().reservationFence()) || !uuid(row, "original_issuer_coverage_operation_id") .equals(originalValue.reservation().issuerCoverageOperationId()) || !positive(row, "original_issuer_coverage_operation_fence") .equals(originalValue.reservation().issuerCoverageOperationFence()) - || !positive(row, "original_coverage_fence").equals(originalValue.reservation().coverageFence()) + || !positive(row, "original_coverage_fence") + .equals(originalValue.reservation().coverageFence()) || !positive(row, "original_inventory_snapshot_revision") .equals(originalValue.reservation().inventorySnapshotRevision()) || !positive(row, "original_reservation_inventory_revision") @@ -357,16 +482,19 @@ static ReleaseProjection readProjection( || !positive(row, "anchor_inventory_snapshot_revision") .equals(originalValue.anchor().issuerInventorySnapshotRevision()) || transition == null - || !uuid(row, "orphan_cleanup_id").equals(transition.get("admission_orphan_cleanup_id", UUID.class)) - || !Arrays.equals(bytes(row, "binding_ref"), transition.get("candidate_binding_ref", byte[].class)) + || !uuid(row, "orphan_cleanup_id") + .equals(transition.get("admission_orphan_cleanup_id", UUID.class)) + || !Arrays.equals( + bytes(row, "binding_ref"), transition.get("candidate_binding_ref", byte[].class)) || !positive(row, "binding_generation") .equals(number(transition, "candidate_binding_generation")) || !Arrays.equals(originalBytes, bytes(originalOperationRow, "member_value_bytes")) - || !text(row, "original_member_value_digest").equals( - CanonicalGameplayIssuerMemberV2Codec.sha256(originalBytes)) - || !text(row, "released_member_value_digest").equals( - CanonicalGameplayIssuerMemberV2Codec.sha256(releasedBytes))) { - throw conflict("Registered issuer release differs from its immutable original local operation"); + || !text(row, "original_member_value_digest") + .equals(CanonicalGameplayIssuerMemberV2Codec.sha256(originalBytes)) + || !text(row, "released_member_value_digest") + .equals(CanonicalGameplayIssuerMemberV2Codec.sha256(releasedBytes))) { + throw conflict( + "Registered issuer release differs from its immutable original local operation"); } CanonicalGameplayIssuerMemberV2Value released; try { @@ -376,8 +504,8 @@ static ReleaseProjection readProjection( } BigInteger fence = positive(row, "release_operation_fence"); BigInteger generation = positive(row, "release_local_member_generation"); - CanonicalGameplayIssuerMemberV2Value expected = createReleasedValue( - originalValue, sourceRevision, releaseId, fence, generation); + CanonicalGameplayIssuerMemberV2Value expected = + createReleasedValue(originalValue, sourceRevision, releaseId, fence, generation); if (!expected.equals(released) || !Arrays.equals(releasedBytes, CanonicalGameplayIssuerMemberV2Codec.encode(expected)) || !originalValue.owner().issuerId().equals(text(row, "issuer_id"))) { @@ -402,7 +530,8 @@ static ReleaseProjection readProjection( || !currentReservationLifecycle.equals("RELEASED") || !currentIssuerObligationStatus.equals("RELEASED") || !releaseId.equals(currentReleaseOperationId) - || !Objects.equals(nullablePositive(row, "completion_inventory_revision"), currentInventoryRevision) + || !Objects.equals( + nullablePositive(row, "completion_inventory_revision"), currentInventoryRevision) || currentInventoryRevision.compareTo(sourceRevision) <= 0) { throw conflict("Completed issuer release lacks its current V29 completion linkage"); } @@ -442,7 +571,8 @@ private static void insertRelease( var reservation = original.reservation(); var anchor = original.anchor(); transaction.execute( - "INSERT INTO " + RELEASE + "INSERT INTO " + + RELEASE + " (operation_id, issuer_id, transition_id, orphan_cleanup_id, reservation_id," + " original_local_operation_id, binding_ref, binding_generation, partition_id," + " original_reservation_fence, original_issuer_coverage_operation_id," @@ -494,56 +624,101 @@ private static void advanceAbortSourceRevision( UUID transitionId = source.transition().transitionId(); byte[] bindingRef = source.transition().bindingRef().bytes(); CanonicalIssuerPartitionReservation reservation = source.reservation(); - requireOne(transaction.execute( - "UPDATE " + TRANSITION + " SET inventory_revision = ?" - + " WHERE transition_id = ? AND status = 'ABORTED'" - + " AND admission_orphan_cleanup_id = ? AND inventory_revision = ?" - + " AND candidate_binding_ref = ? AND candidate_binding_generation = ?" - + " AND issuer_reservation_id = ? AND expected_prior_binding_ref IS NULL" - + " AND expected_prior_binding_generation IS NULL", - decimal(nextRevision), transitionId, source.orphanCleanupId(), decimal(priorRevision), - bindingRef, decimal(source.transition().bindingGeneration()), reservation.reservationId()), + requireOne( + transaction.execute( + "UPDATE " + + TRANSITION + + " SET inventory_revision = ?" + + " WHERE transition_id = ? AND status = 'ABORTED'" + + " AND admission_orphan_cleanup_id = ? AND inventory_revision = ?" + + " AND candidate_binding_ref = ? AND candidate_binding_generation = ?" + + " AND issuer_reservation_id = ? AND expected_prior_binding_ref IS NULL" + + " AND expected_prior_binding_generation IS NULL", + decimal(nextRevision), + transitionId, + source.orphanCleanupId(), + decimal(priorRevision), + bindingRef, + decimal(source.transition().bindingGeneration()), + reservation.reservationId()), "Issuer release preparation lost its immutable Account-abort transition source"); - requireOne(transaction.execute( - "UPDATE " + INVENTORY + " SET inventory_revision = ?" - + " WHERE binding_ref = ? AND transition_id = ? AND lifecycle = 'TERMINAL_UNRESOLVED'" - + " AND inventory_revision = ? AND binding_generation = ? AND issuer_reservation_id = ?", - decimal(nextRevision), bindingRef, transitionId, decimal(priorRevision), - decimal(source.transition().bindingGeneration()), reservation.reservationId()), + requireOne( + transaction.execute( + "UPDATE " + + INVENTORY + + " SET inventory_revision = ?" + + " WHERE binding_ref = ? AND transition_id = ? AND lifecycle = 'TERMINAL_UNRESOLVED'" + + " AND inventory_revision = ? AND binding_generation = ? AND issuer_reservation_id = ?", + decimal(nextRevision), + bindingRef, + transitionId, + decimal(priorRevision), + decimal(source.transition().bindingGeneration()), + reservation.reservationId()), "Issuer release preparation lost its retained candidate source"); - requireOne(transaction.execute( - "UPDATE " + RESERVATION + " SET inventory_revision = ?" - + " WHERE reservation_id = ? AND transition_id = ? AND lifecycle = 'RELEASE_PENDING'" - + " AND inventory_revision = ? AND binding_ref = ? AND binding_generation = ?" - + " AND reservation_fence = ? AND issuer_coverage_operation_id = ?" - + " AND issuer_coverage_operation_fence = ? AND coverage_fence = ?" - + " AND inventory_snapshot_revision = ?", - decimal(nextRevision), reservation.reservationId(), transitionId, decimal(priorRevision), - bindingRef, decimal(source.transition().bindingGeneration()), reservation.reservationFence(), - reservation.issuerCoverageOperationId(), decimal(reservation.issuerCoverageOperationFence()), - decimal(reservation.coverageFence()), decimal(reservation.inventorySnapshotRevision())), + requireOne( + transaction.execute( + "UPDATE " + + RESERVATION + + " SET inventory_revision = ?" + + " WHERE reservation_id = ? AND transition_id = ? AND lifecycle = 'RELEASE_PENDING'" + + " AND inventory_revision = ? AND binding_ref = ? AND binding_generation = ?" + + " AND reservation_fence = ? AND issuer_coverage_operation_id = ?" + + " AND issuer_coverage_operation_fence = ? AND coverage_fence = ?" + + " AND inventory_snapshot_revision = ?", + decimal(nextRevision), + reservation.reservationId(), + transitionId, + decimal(priorRevision), + bindingRef, + decimal(source.transition().bindingGeneration()), + reservation.reservationFence(), + reservation.issuerCoverageOperationId(), + decimal(reservation.issuerCoverageOperationFence()), + decimal(reservation.coverageFence()), + decimal(reservation.inventorySnapshotRevision())), "Issuer release preparation lost its original pending-reservation source"); - requireOne(transaction.execute( - "UPDATE " + ACCOUNT_OBLIGATION + " SET inventory_revision = ?" - + " WHERE transition_id = ? AND inventory_revision = ?" - + " AND status IN ('REQUIRED', 'ACKNOWLEDGED')", - decimal(nextRevision), transitionId, decimal(priorRevision)), + requireOne( + transaction.execute( + "UPDATE " + + ACCOUNT_OBLIGATION + + " SET inventory_revision = ?" + + " WHERE transition_id = ? AND inventory_revision = ?" + + " AND status IN ('REQUIRED', 'ACKNOWLEDGED')", + decimal(nextRevision), + transitionId, + decimal(priorRevision)), "Issuer release preparation lost its retained Account-obligation source"); - requireOne(transaction.execute( - "UPDATE " + ISSUER_OBLIGATION + " SET inventory_revision = ?" - + " WHERE transition_id = ? AND binding_ref = ? AND status = 'REQUIRED'" - + " AND local_release_operation_id IS NULL AND inventory_revision = ?", - decimal(nextRevision), transitionId, bindingRef, decimal(priorRevision)), + requireOne( + transaction.execute( + "UPDATE " + + ISSUER_OBLIGATION + + " SET inventory_revision = ?" + + " WHERE transition_id = ? AND binding_ref = ? AND status = 'REQUIRED'" + + " AND local_release_operation_id IS NULL AND inventory_revision = ?", + decimal(nextRevision), + transitionId, + bindingRef, + decimal(priorRevision)), "Issuer release preparation lost its retained issuer-obligation source"); - requireOne(transaction.execute( - "UPDATE " + REGION_OBLIGATION + " SET inventory_revision = ?" - + " WHERE transition_id = ? AND status = 'REQUIRED' AND inventory_revision = ?", - decimal(nextRevision), transitionId, decimal(priorRevision)), + requireOne( + transaction.execute( + "UPDATE " + + REGION_OBLIGATION + + " SET inventory_revision = ?" + + " WHERE transition_id = ? AND status = 'REQUIRED' AND inventory_revision = ?", + decimal(nextRevision), + transitionId, + decimal(priorRevision)), "Issuer release preparation lost its retained region-obligation source"); - requireOne(transaction.execute( - "UPDATE " + INVENTORY_CLOCK + " SET inventory_revision = ?" - + " WHERE singleton_id = 1 AND inventory_revision = ?", - decimal(nextRevision), decimal(clockRevision)), + requireOne( + transaction.execute( + "UPDATE " + + INVENTORY_CLOCK + + " SET inventory_revision = ?" + + " WHERE singleton_id = 1 AND inventory_revision = ?", + decimal(nextRevision), + decimal(clockRevision)), "Issuer release preparation lost the current inventory-clock compare-and-set"); } @@ -557,7 +732,9 @@ private static CanonicalGameplayIssuerMemberV2Value createReleasedValue( original.owner(), original.bindingGeneration(), withLifecycleAndRevision( - original.reservation(), CanonicalIssuerPartitionReservation.Lifecycle.RELEASED, sourceRevision), + original.reservation(), + CanonicalIssuerPartitionReservation.Lifecycle.RELEASED, + sourceRevision), original.anchor(), new CanonicalGameplayIssuerMemberV2Value.LocalMemberOperation( operationId, operationFence, localGeneration), @@ -600,10 +777,12 @@ private static void verifyReadbackMatchesOperation( CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( operation.releasedMemberValue().reservation().reservationId()); String bindingField = - new String(operation.releasedMemberValue().owner().bindingRef().bytes(), StandardCharsets.UTF_8); + new String( + operation.releasedMemberValue().owner().bindingRef().bytes(), StandardCharsets.UTF_8); if (!Arrays.equals(fields.get(capacityField), operation.exactReleasedMemberValueBytes()) || fields.containsKey(bindingField)) { - throw conflict("Issuer release readback does not prove the exact RELEASED capacity postimage"); + throw conflict( + "Issuer release readback does not prove the exact RELEASED capacity postimage"); } } @@ -615,30 +794,52 @@ private static void requireExactReleaseSource( var originalReservation = originalSource.reservation(); var currentReservation = current.reservation(); boolean currentMatchesPending = - currentReservation.lifecycle() == CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING - && originalSource.transition().inventoryRevision().equals(current.transition().inventoryRevision()) + currentReservation.lifecycle() + == CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING + && originalSource + .transition() + .inventoryRevision() + .equals(current.transition().inventoryRevision()) && originalReservation.equals(currentReservation); boolean currentMatchesReleased = currentReservation.lifecycle() == CanonicalIssuerPartitionReservation.Lifecycle.RELEASED - && current.transition().inventoryRevision().compareTo(expected.sourceInventoryRevision()) > 0 - && currentReservation.inventoryRevision().equals(current.transition().inventoryRevision()) + && current + .transition() + .inventoryRevision() + .compareTo(expected.sourceInventoryRevision()) + > 0 + && currentReservation + .inventoryRevision() + .equals(current.transition().inventoryRevision()) && originalReservation.reservationId().equals(currentReservation.reservationId()) && originalReservation.owner().equals(currentReservation.owner()) - && originalReservation.bindingGeneration().equals(currentReservation.bindingGeneration()) + && originalReservation + .bindingGeneration() + .equals(currentReservation.bindingGeneration()) && originalReservation.transitionId().equals(currentReservation.transitionId()) && originalReservation.partitionId().equals(currentReservation.partitionId()) && originalReservation.reservationFence().equals(currentReservation.reservationFence()) - && originalReservation.issuerCoverageOperationId().equals(currentReservation.issuerCoverageOperationId()) - && originalReservation.issuerCoverageOperationFence().equals(currentReservation.issuerCoverageOperationFence()) + && originalReservation + .issuerCoverageOperationId() + .equals(currentReservation.issuerCoverageOperationId()) + && originalReservation + .issuerCoverageOperationFence() + .equals(currentReservation.issuerCoverageOperationFence()) && originalReservation.coverageFence().equals(currentReservation.coverageFence()) - && originalReservation.inventorySnapshotRevision().equals(currentReservation.inventorySnapshotRevision()); + && originalReservation + .inventorySnapshotRevision() + .equals(currentReservation.inventorySnapshotRevision()); if (!originalSource.transition().transitionId().equals(current.transition().transitionId()) || !originalSource.orphanCleanupId().equals(current.orphanCleanupId()) || !originalSource.candidate().identity().equals(current.candidate().identity()) || !originalSource.transition().bindingRef().equals(current.transition().bindingRef()) - || !originalSource.transition().bindingGeneration().equals(current.transition().bindingGeneration()) + || !originalSource + .transition() + .bindingGeneration() + .equals(current.transition().bindingGeneration()) || !(currentMatchesPending || currentMatchesReleased)) { - throw conflict("Current first-NEW abort source differs from the SQL-issued release operation"); + throw conflict( + "Current first-NEW abort source differs from the SQL-issued release operation"); } } @@ -650,11 +851,23 @@ private static boolean sameOperationSource( && original.reservation().reservationId().equals(source.reservation().reservationId()) && original.reservation().reservationFence().equals(source.reservation().reservationFence()) && original.reservation().owner().equals(source.reservation().owner()) - && original.reservation().bindingGeneration().equals(source.reservation().bindingGeneration()) - && original.reservation().issuerCoverageOperationId().equals(source.reservation().issuerCoverageOperationId()) - && original.reservation().issuerCoverageOperationFence().equals(source.reservation().issuerCoverageOperationFence()) + && original + .reservation() + .bindingGeneration() + .equals(source.reservation().bindingGeneration()) + && original + .reservation() + .issuerCoverageOperationId() + .equals(source.reservation().issuerCoverageOperationId()) + && original + .reservation() + .issuerCoverageOperationFence() + .equals(source.reservation().issuerCoverageOperationFence()) && original.reservation().coverageFence().equals(source.reservation().coverageFence()) - && original.reservation().inventorySnapshotRevision().equals(source.reservation().inventorySnapshotRevision()); + && original + .reservation() + .inventorySnapshotRevision() + .equals(source.reservation().inventorySnapshotRevision()); } private static void requireSameOperation( @@ -664,8 +877,10 @@ private static void requireSameOperation( || !expected.operationFence().equals(current.operationFence()) || !expected.localMemberGeneration().equals(current.localMemberGeneration()) || !expected.sourceInventoryRevision().equals(current.sourceInventoryRevision()) - || !Arrays.equals(expected.exactOriginalMemberValueBytes(), current.exactOriginalMemberValueBytes()) - || !Arrays.equals(expected.exactReleasedMemberValueBytes(), current.exactReleasedMemberValueBytes())) { + || !Arrays.equals( + expected.exactOriginalMemberValueBytes(), current.exactOriginalMemberValueBytes()) + || !Arrays.equals( + expected.exactReleasedMemberValueBytes(), current.exactReleasedMemberValueBytes())) { throw conflict("SQL issuer release operation changed across its physical proof boundary"); } } @@ -673,14 +888,29 @@ private static void requireSameOperation( private static void requireSameAbortSource( CanonicalGameplayAdmissionAbortSource expected, CanonicalGameplayAdmissionAbortSource current) { - if (!expected.transition().transitionId().equals(current.transition().transitionId()) + if (!expected.transition().equals(current.transition()) + || !expected.candidate().equals(current.candidate()) + || !expected + .originalDecision() + .targetEvidence() + .equals(current.originalDecision().targetEvidence()) + || !expected.transition().transitionId().equals(current.transition().transitionId()) || expected.transition().status() != current.transition().status() - || !expected.transition().inventoryRevision().equals(current.transition().inventoryRevision()) + || !expected + .transition() + .inventoryRevision() + .equals(current.transition().inventoryRevision()) || !expected.orphanCleanupId().equals(current.orphanCleanupId()) || !expected.transition().bindingRef().equals(current.transition().bindingRef()) - || !expected.transition().bindingGeneration().equals(current.transition().bindingGeneration()) + || !expected + .transition() + .bindingGeneration() + .equals(current.transition().bindingGeneration()) || !expected.transition().reservationFence().equals(current.transition().reservationFence()) - || !expected.transition().candidateAccountIndexFence().equals(current.transition().candidateAccountIndexFence()) + || !expected + .transition() + .candidateAccountIndexFence() + .equals(current.transition().candidateAccountIndexFence()) || !expected.reservation().equals(current.reservation()) || !expected.candidate().identity().equals(current.candidate().identity()) || !expected.candidate().bindingRef().equals(current.candidate().bindingRef()) @@ -689,7 +919,10 @@ private static void requireSameAbortSource( || expected.candidate().lifecycle() != current.candidate().lifecycle() || expected.candidate().accountIndexState() != current.candidate().accountIndexState() || expected.candidate().issuerIndexState() != current.candidate().issuerIndexState() - || !expected.originalDecision().leaseEvidenceJson().equals(current.originalDecision().leaseEvidenceJson())) { + || !expected + .originalDecision() + .leaseEvidenceJson() + .equals(current.originalDecision().leaseEvidenceJson())) { throw conflict("Actual Account abort source changed during issuer release"); } } @@ -701,17 +934,35 @@ private static void requireSameAbortIdentity( || expected.transition().status() != current.transition().status() || !expected.orphanCleanupId().equals(current.orphanCleanupId()) || !expected.transition().bindingRef().equals(current.transition().bindingRef()) - || !expected.transition().bindingGeneration().equals(current.transition().bindingGeneration()) + || !expected + .transition() + .bindingGeneration() + .equals(current.transition().bindingGeneration()) || !expected.transition().reservationFence().equals(current.transition().reservationFence()) - || !expected.transition().candidateAccountIndexFence().equals(current.transition().candidateAccountIndexFence()) + || !expected + .transition() + .candidateAccountIndexFence() + .equals(current.transition().candidateAccountIndexFence()) || !expected.reservation().reservationId().equals(current.reservation().reservationId()) || expected.reservation().lifecycle() != current.reservation().lifecycle() || !expected.reservation().owner().equals(current.reservation().owner()) - || !expected.reservation().reservationFence().equals(current.reservation().reservationFence()) - || !expected.reservation().issuerCoverageOperationId().equals(current.reservation().issuerCoverageOperationId()) - || !expected.reservation().issuerCoverageOperationFence().equals(current.reservation().issuerCoverageOperationFence()) + || !expected + .reservation() + .reservationFence() + .equals(current.reservation().reservationFence()) + || !expected + .reservation() + .issuerCoverageOperationId() + .equals(current.reservation().issuerCoverageOperationId()) + || !expected + .reservation() + .issuerCoverageOperationFence() + .equals(current.reservation().issuerCoverageOperationFence()) || !expected.reservation().coverageFence().equals(current.reservation().coverageFence()) - || !expected.reservation().inventorySnapshotRevision().equals(current.reservation().inventorySnapshotRevision()) + || !expected + .reservation() + .inventorySnapshotRevision() + .equals(current.reservation().inventorySnapshotRevision()) || !expected.candidate().identity().equals(current.candidate().identity()) || !expected.candidate().bindingRef().equals(current.candidate().bindingRef()) || !expected.candidate().bindingGeneration().equals(current.candidate().bindingGeneration()) @@ -719,7 +970,10 @@ private static void requireSameAbortIdentity( || expected.candidate().lifecycle() != current.candidate().lifecycle() || expected.candidate().accountIndexState() != current.candidate().accountIndexState() || expected.candidate().issuerIndexState() != current.candidate().issuerIndexState() - || !expected.originalDecision().leaseEvidenceJson().equals(current.originalDecision().leaseEvidenceJson())) { + || !expected + .originalDecision() + .leaseEvidenceJson() + .equals(current.originalDecision().leaseEvidenceJson())) { throw conflict("Actual first-NEW abort identity changed while preparing issuer release"); } } @@ -728,9 +982,12 @@ private static void requireAbortedSource(CanonicalGameplayAdmissionAbortSource s if (!source.isAccountAborted() || source.transition().status() != CanonicalGameplayBindingTransitionSnapshot.Status.ABORTED || source.candidate().lifecycle() - != net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry.Lifecycle.TERMINAL_UNRESOLVED - || (source.reservation().lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING - && source.reservation().lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED)) { + != net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry + .Lifecycle.TERMINAL_UNRESOLVED + || (source.reservation().lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING + && source.reservation().lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED)) { throw conflict("Issuer release requires the actual Account ABORTED and retained GS source"); } } @@ -738,13 +995,16 @@ private static void requireAbortedSource(CanonicalGameplayAdmissionAbortSource s private static void requireSameCurrentIssuerState( CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState expected, CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current) { - if (!CanonicalGameplayIssuerBindingLocalOperationRepository.sameCurrentIssuerState(expected, current)) { + if (!CanonicalGameplayIssuerBindingLocalOperationRepository.sameCurrentIssuerState( + expected, current)) { throw conflict("Issuer source or incarnation moved during local release"); } } - private CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState readCurrentIssuerState() { - return Objects.requireNonNull(currentIssuerStateSource.readFreshCurrentState(), + private CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState + readCurrentIssuerState() { + return Objects.requireNonNull( + currentIssuerStateSource.readFreshCurrentState(), "current issuer state source returned null"); } @@ -758,13 +1018,15 @@ private static UUID freshNonNilUuid() { private static UUID uuid(Record row, String field) { UUID value = row.get(field, UUID.class); - if (value == null || value.equals(new UUID(0L, 0L))) throw conflict("Issuer release SQL " + field + " is unavailable"); + if (value == null || value.equals(new UUID(0L, 0L))) + throw conflict("Issuer release SQL " + field + " is unavailable"); return value; } private static String text(Record row, String field) { String value = row.get(field, String.class); - if (value == null || value.isBlank()) throw conflict("Issuer release SQL " + field + " is unavailable"); + if (value == null || value.isBlank()) + throw conflict("Issuer release SQL " + field + " is unavailable"); return value; } @@ -794,7 +1056,8 @@ private static BigInteger nonnegative(Record row, String field) { private static BigInteger nullablePositive(Record row, String field) { BigDecimal raw = row.get(field, BigDecimal.class); BigInteger value = raw == null ? null : number(row, field); - if (value != null && value.signum() <= 0) throw conflict("Issuer release SQL " + field + " is not positive"); + if (value != null && value.signum() <= 0) + throw conflict("Issuer release SQL " + field + " is not positive"); return value; } @@ -833,4 +1096,3 @@ private static IllegalStateException conflict(String message) { return new IllegalStateException("Issuer binding-local release is unavailable: " + message); } } - diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.java index 3c5389f009..5efc895d77 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.java @@ -21,6 +21,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; @@ -47,8 +48,10 @@ public final class CanonicalGameplayIssuerBindingLocalReleaseRedisOwner { new RedisScriptDescriptor.ArgumentSpec("partitionCount"), new RedisScriptDescriptor.ArgumentSpec("partitionCapacity"), new RedisScriptDescriptor.ArgumentSpec("baselineFieldCountAndExactFieldValuePairs"), - new RedisScriptDescriptor.ArgumentSpec("registeredLocalOperationCountAndExactOperationTupleAndCurrentPhase"), - new RedisScriptDescriptor.ArgumentSpec("originalAndReleasedMemberOperationAndCapacityProof")); + new RedisScriptDescriptor.ArgumentSpec( + "registeredLocalOperationCountAndExactOperationTupleAndCurrentPhase"), + new RedisScriptDescriptor.ArgumentSpec( + "originalAndReleasedMemberOperationAndCapacityProof")); private static final List EXPECTED_OUTCOMES = List.of( new RedisScriptDescriptor.OutcomeSpec( @@ -113,7 +116,8 @@ public Readback releaseAndRead(CanonicalGameplayIssuerBindingLocalReleaseOperati && state.getMessage().contains("Issuer binding-local release is unavailable")) { throw state; } - throw unavailable("Physical issuer release did not obtain exact source and readback proof", failure); + throw unavailable( + "Physical issuer release did not obtain exact source and readback proof", failure); } } @@ -124,8 +128,10 @@ private long writeOneKey(byte[] script, byte[] key, byte[][] arguments) { RedisAsyncCommands commands = requireCommands(connection); requirePrincipal(await(commands.aclWhoami())); String sha = await(commands.scriptLoad(script)); - if (!digest("SHA-1", script).equals(sha)) throw unavailable("Redis loaded a different script"); - Long reply = await(commands.evalsha(sha, ScriptOutputType.INTEGER, new byte[][] {key}, arguments)); + if (!digest("SHA-1", script).equals(sha)) + throw unavailable("Redis loaded a different script"); + Long reply = + await(commands.evalsha(sha, ScriptOutputType.INTEGER, new byte[][] {key}, arguments)); if (reply == null) throw unavailable("Redis returned no release result"); return reply; } catch (RuntimeException failure) { @@ -150,9 +156,11 @@ private byte[] readExactPhysicalState( int maxFields = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_HASH_FIELDS + 2 * CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_MEMBER_OPERATIONS; - if (count == null || count < 1 || count > maxFields) throw unavailable("Issuer partition field count is invalid"); + if (count == null || count < 1 || count > maxFields) + throw unavailable("Issuer partition field count is invalid"); Map raw = await(commands.hgetall(key)); - if (raw == null || raw.size() != count) throw unavailable("Issuer partition readback is incomplete"); + if (raw == null || raw.size() != count) + throw unavailable("Issuer partition readback is incomplete"); Map actual = new HashMap<>(); long bytes = 0; for (Map.Entry field : raw.entrySet()) { @@ -169,7 +177,8 @@ private byte[] readExactPhysicalState( } Map baseline = work.baselineFields(); Map allowed = work.allowedFields(); - if (actual.size() > allowed.size()) throw unavailable("Issuer partition contains an unknown field"); + if (actual.size() > allowed.size()) + throw unavailable("Issuer partition contains an unknown field"); for (Map.Entry field : baseline.entrySet()) { byte[] value = actual.get(b64(field.getKey().getBytes(StandardCharsets.UTF_8))); if (value == null || !Arrays.equals(value, field.getValue())) { @@ -183,7 +192,8 @@ private byte[] readExactPhysicalState( String bindingField = new String(target.owner().bindingRef().bytes(), StandardCharsets.UTF_8); byte[] targetCapacity = actual.get(b64(capacityField.getBytes(StandardCharsets.US_ASCII))); byte[] targetBinding = actual.get(b64(bindingField.getBytes(StandardCharsets.UTF_8))); - if (!Arrays.equals(targetCapacity, operation.exactReleasedMemberValueBytes()) || targetBinding != null) { + if (!Arrays.equals(targetCapacity, operation.exactReleasedMemberValueBytes()) + || targetBinding != null) { throw unavailable("Exact RELEASED capacity field or binding-field removal is absent"); } for (Map.Entry field : actual.entrySet()) { @@ -203,25 +213,42 @@ private byte[] readExactPhysicalState( CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.RESERVATION_FIELD_PREFIX)) { var value = CanonicalGameplayIssuerMemberV2Codec.decode(field.getValue()); physicalReservations++; - if (value.reservation().lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED) { + if (value.reservation().lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED) { physicalCapacity++; } - } else if (!decoded.equals(CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.METADATA_FIELD)) { + } else if (!decoded.equals( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.METADATA_FIELD)) { CanonicalGameplayIssuerMemberV2Codec.decode(field.getValue()); physicalBindings++; } } int baselineReservations = work.baselineProof().physicalReservationCount(); int baselineBindings = work.baselineProof().physicalBindingCount(); - int registeredReservations = Math.toIntExact(work.localEntries().stream() - .filter(entry -> entry.memberValue().reservation().partitionId() - .equals(operation.releasedMemberValue().reservation().partitionId())) - .count()); - int registeredBindings = Math.toIntExact(work.localEntries().stream() - .filter(entry -> entry.memberValue().reservation().partitionId() - .equals(operation.releasedMemberValue().reservation().partitionId()) - && entry.bindingPresent()) - .count()); + int registeredReservations = + Math.toIntExact( + work.localEntries().stream() + .filter( + entry -> + entry + .memberValue() + .reservation() + .partitionId() + .equals(operation.releasedMemberValue().reservation().partitionId())) + .count()); + int registeredBindings = + Math.toIntExact( + work.localEntries().stream() + .filter( + entry -> + entry + .memberValue() + .reservation() + .partitionId() + .equals( + operation.releasedMemberValue().reservation().partitionId()) + && entry.bindingPresent()) + .count()); if (BigInteger.valueOf(physicalCapacity).compareTo(work.anchor().partitionCapacity()) > 0 || BigInteger.valueOf(physicalCapacity).compareTo(work.partitionCapacity()) > 0 || physicalReservations < baselineReservations + 1 @@ -231,7 +258,8 @@ private byte[] readExactPhysicalState( || work.aggregateCapacity().compareTo(work.aggregateBound()) > 0) { throw unavailable("Issuer release readback violates physical or SQL capacity bounds"); } - return CanonicalGameplayIssuerBootstrapCoverageRepository.encodeFieldSet(decodePhysicalMap(actual)); + return CanonicalGameplayIssuerBootstrapCoverageRepository.encodeFieldSet( + decodePhysicalMap(actual)); } catch (RuntimeException failure) { throw unavailable("Independent issuer release readback was not exact", failure); } @@ -247,8 +275,8 @@ private static byte[][] scriptArguments( args.add(ascii(anchor.partitionCount().toString())); args.add(ascii(anchor.partitionCapacity().toString())); Map baseline = work.baselineFields(); - List> sortedBaseline = baseline.entrySet().stream() - .sorted(Map.Entry.comparingByKey()).toList(); + List> sortedBaseline = + baseline.entrySet().stream().sorted(Map.Entry.comparingByKey()).toList(); args.add(ascii(Integer.toString(sortedBaseline.size()))); for (Map.Entry field : sortedBaseline) { args.add(field.getKey().getBytes(StandardCharsets.UTF_8)); @@ -256,8 +284,13 @@ private static byte[][] scriptArguments( } List entries = work.localEntries().stream() - .filter(entry -> entry.memberValue().reservation().partitionId() - .equals(operation.releasedMemberValue().reservation().partitionId())) + .filter( + entry -> + entry + .memberValue() + .reservation() + .partitionId() + .equals(operation.releasedMemberValue().reservation().partitionId())) .sorted(java.util.Comparator.comparing(entry -> entry.operationId().toString())) .toList(); args.add(ascii(Integer.toString(entries.size()))); @@ -285,7 +318,8 @@ private static byte[][] scriptArguments( private static byte[] exactPartitionKey( CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work) { String key = CanonicalGameplayIssuerRedisKeys.forMember(work.targetOperation().memberValue()); - if (!key.startsWith(KEY_PREFIX) || key.length() > 512) throw unavailable("Issuer key is not canonical"); + if (!key.startsWith(KEY_PREFIX) || key.length() > 512) + throw unavailable("Issuer key is not canonical"); return key.getBytes(StandardCharsets.US_ASCII); } @@ -313,12 +347,16 @@ private void requireFreshCurrentState( private RedisScriptDescriptor requireDescriptor() { RedisScriptDescriptor descriptor; try { - descriptor = catalog.require(CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.SCRIPT_ID); + descriptor = + catalog.require( + CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.SCRIPT_ID); } catch (RuntimeException missing) { throw unavailable("Manual issuer release descriptor is not installed", missing); } - if (!CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.SCRIPT_ID.equals(descriptor.scriptId()) - || !CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.RESOURCE_PATH.equals(descriptor.resourcePath()) + if (!CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.SCRIPT_ID.equals( + descriptor.scriptId()) + || !CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.RESOURCE_PATH.equals( + descriptor.resourcePath()) || !"game-session-service".equals(descriptor.owner()) || !PRINCIPAL.equals(descriptor.principal()) || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION @@ -328,8 +366,11 @@ private RedisScriptDescriptor requireDescriptor() { || !EXPECTED_OUTCOMES.equals(descriptor.outcomes()) || descriptor.resetSensitivity() != RedisScriptDescriptor.ResetSensitivity.CLUSTER || descriptor.lossClass() != RedisScriptDescriptor.LossClass.EMPTY_REDIS_COLD_START_OR_RESET - || descriptor.compatibilityLevel() != RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET - || !descriptor.supportedCoexistence().equals(List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "v2"))) + || descriptor.compatibilityLevel() + != RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET + || !descriptor + .supportedCoexistence() + .equals(List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "v2"))) || descriptor.legacyPayloadShape() != null) { throw unavailable("Manual issuer release descriptor differs from its exact owner contract"); } @@ -337,11 +378,14 @@ private RedisScriptDescriptor requireDescriptor() { } private static byte[] scriptSource(RedisScriptDescriptor descriptor) { - try (InputStream input = CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.class - .getClassLoader().getResourceAsStream(descriptor.resourcePath())) { + try (InputStream input = + CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.class + .getClassLoader() + .getResourceAsStream(descriptor.resourcePath())) { if (input == null) throw unavailable("Issuer release Lua resource is missing"); byte[] bytes = input.readNBytes(MAX_SCRIPT_BYTES + 1); - if (bytes.length == 0 || bytes.length > MAX_SCRIPT_BYTES + if (bytes.length == 0 + || bytes.length > MAX_SCRIPT_BYTES || !descriptor.sha256().equals(digest("SHA-256", bytes))) { throw unavailable("Issuer release Lua differs from its exact descriptor digest"); } @@ -353,7 +397,8 @@ private static byte[] scriptSource(RedisScriptDescriptor descriptor) { private static Map decodePhysicalMap(Map encoded) { Map result = new HashMap<>(); - encoded.forEach((field, value) -> result.put(decodeUtf8(Base64.getDecoder().decode(field)), value.clone())); + encoded.forEach( + (field, value) -> result.put(decodeUtf8(Base64.getDecoder().decode(field)), value.clone())); return result; } @@ -363,10 +408,12 @@ private static String b64(byte[] value) { private static String decodeUtf8(byte[] bytes) { try { - return StandardCharsets.UTF_8.newDecoder() + return StandardCharsets.UTF_8 + .newDecoder() .onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT) - .decode(java.nio.ByteBuffer.wrap(bytes)).toString(); + .decode(java.nio.ByteBuffer.wrap(bytes)) + .toString(); } catch (CharacterCodingException malformed) { throw unavailable("Issuer hash field is not valid UTF-8", malformed); } @@ -378,12 +425,14 @@ private static byte[] ascii(String value) { private static RedisAsyncCommands requireCommands( StatefulRedisConnection connection) { - if (connection == null || !connection.isOpen()) throw unavailable("Redis connection is unavailable"); + if (connection == null || !connection.isOpen()) + throw unavailable("Redis connection is unavailable"); return connection.async(); } private static void requirePrincipal(String principal) { - if (!PRINCIPAL.equals(principal)) throw unavailable("Redis principal is not the exact coordination owner"); + if (!PRINCIPAL.equals(principal)) + throw unavailable("Redis principal is not the exact coordination owner"); } private static T await(RedisFuture future) { @@ -418,10 +467,13 @@ private static IllegalStateException unavailable(String message) { } private static IllegalStateException unavailable(String message, Throwable cause) { - return new IllegalStateException("Issuer binding-local release is unavailable: " + message, cause); + return new IllegalStateException( + "Issuer binding-local release is unavailable: " + message, cause); } - /** Exact private physical readback; SQL completion must consume this value in a new transaction. */ + /** + * Exact private physical readback; SQL completion must consume this value in a new transaction. + */ public static final class Readback { private final UUID operationId; private final long scriptOutcome; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.java index fa1834e164..1d22251bdd 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.java @@ -14,7 +14,8 @@ public final class CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution implements RedisScriptContribution { public static final String SCRIPT_ID = "game-session.issuer-binding-local-release.v1"; - public static final String RESOURCE_PATH = "redis/lua/game-session-issuer-binding-local-release.lua"; + public static final String RESOURCE_PATH = + "redis/lua/game-session-issuer-binding-local-release.lua"; private static final String DESCRIPTOR_PATH = "/redis/scripts/game-session-issuer-binding-local-release.json"; private static final JsonMapper JSON = @@ -46,6 +47,7 @@ public Collection descriptors() { } private static IllegalStateException unavailable() { - return new IllegalStateException("Issuer binding-local release Redis descriptor is unavailable"); + return new IllegalStateException( + "Issuer binding-local release Redis descriptor is unavailable"); } } diff --git a/services/game-session-service/src/main/resources/db/migration/V1036__canonical_issuer_first_new_release_proof.sql b/services/game-session-service/src/main/resources/db/migration/V1036__canonical_issuer_first_new_release_proof.sql index 797650982f..438e84b7af 100644 --- a/services/game-session-service/src/main/resources/db/migration/V1036__canonical_issuer_first_new_release_proof.sql +++ b/services/game-session-service/src/main/resources/db/migration/V1036__canonical_issuer_first_new_release_proof.sql @@ -126,6 +126,8 @@ ALTER TABLE game_session_canonical_binding_issuer_index_obligation CREATE INDEX ix_gs_issuer_binding_local_release_status ON game_session_canonical_issuer_binding_local_release_operation (issuer_id, status, partition_id); +-- PostgreSQL trigger bodies remain enforced by Flyway; jOOQ OSS cannot parse this procedural DDL. +-- [jooq ignore start] CREATE FUNCTION require_first_new_issuer_release_source() RETURNS trigger LANGUAGE plpgsql @@ -244,6 +246,160 @@ BEGIN END; $$; +-- Extend the retained V1035 guard with this exact same proof-backed edge. Its original +-- tuple, pending-state and deletion protections continue to apply to every other update. +CREATE OR REPLACE FUNCTION require_first_new_abort_reservation_release() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'UPDATE' AND OLD.lifecycle = 'RELEASE_PENDING' AND NEW.lifecycle = 'RELEASED' THEN + IF (to_jsonb(NEW) - 'lifecycle' - 'inventory_revision') + IS DISTINCT FROM (to_jsonb(OLD) - 'lifecycle' - 'inventory_revision') + OR NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_binding_transition transition + JOIN game_session_canonical_gameplay_binding_inventory candidate + ON candidate.binding_ref = transition.candidate_binding_ref + JOIN game_session_canonical_binding_issuer_index_obligation issuer_obligation + ON issuer_obligation.transition_id = transition.transition_id + AND issuer_obligation.binding_ref = transition.candidate_binding_ref + JOIN game_session_canonical_issuer_binding_local_release_operation release + ON release.operation_id = issuer_obligation.local_release_operation_id + WHERE transition.transition_id = NEW.transition_id + AND transition.status = 'ABORTED' + AND transition.admission_orphan_cleanup_id = release.orphan_cleanup_id + AND transition.inventory_revision = OLD.inventory_revision + AND candidate.lifecycle = 'TERMINAL_UNRESOLVED' + AND candidate.inventory_revision = OLD.inventory_revision + AND candidate.binding_ref = OLD.binding_ref + AND candidate.binding_generation = OLD.binding_generation + AND candidate.issuer_reservation_id = OLD.reservation_id + AND issuer_obligation.status = 'RELEASED' + AND issuer_obligation.inventory_revision = NEW.inventory_revision + AND issuer_obligation.local_release_operation_id = release.operation_id + AND release.status = 'RELEASED' + AND release.transition_id = NEW.transition_id + AND release.reservation_id = NEW.reservation_id + AND release.binding_ref = NEW.binding_ref + AND release.binding_generation = NEW.binding_generation + AND release.source_inventory_revision = OLD.inventory_revision + AND release.completion_inventory_revision = NEW.inventory_revision + AND NEW.inventory_revision > OLD.inventory_revision + AND release.physical_readback_field_set_bytes IS NOT NULL + AND release.physical_readback_field_set_digest ~ '^sha256:[0-9a-f]{64}$' + ) THEN + RAISE EXCEPTION 'First-NEW reservation release requires its exact completed physical issuer proof' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_first_new_issuer_release_reservation_source'; + END IF; + RETURN NEW; + END IF; + IF OLD.lifecycle = 'RELEASE_PENDING' AND EXISTS ( + SELECT 1 FROM game_session_canonical_binding_transition transition + WHERE transition.transition_id = OLD.transition_id + AND transition.issuer_reservation_id = OLD.reservation_id + AND transition.status = 'ABORTED' + AND transition.admission_orphan_cleanup_id IS NOT NULL + ) THEN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Retained first-NEW abort reservation requires qualified release proof' + USING ERRCODE = '23514', CONSTRAINT = 'gs_first_new_abort_reservation_retained'; + END IF; + IF (to_jsonb(NEW) - 'inventory_revision') IS DISTINCT FROM (to_jsonb(OLD) - 'inventory_revision') + OR NEW.inventory_revision < OLD.inventory_revision THEN + RAISE EXCEPTION 'Retained first-NEW abort reservation is immutable without qualified release proof' + USING ERRCODE = '23514', CONSTRAINT = 'gs_first_new_abort_reservation_retained'; + END IF; + RETURN NEW; + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + + IF OLD.lifecycle = 'RESERVED' AND NEW.lifecycle = 'RELEASE_PENDING' THEN + IF NEW.inventory_revision <= OLD.inventory_revision + OR ROW( + NEW.reservation_id, NEW.binding_ref, NEW.account_id, NEW.tenant_id, + NEW.game_instance_id, NEW.runtime_game_instance_id, NEW.session_id, + NEW.binding_generation, NEW.transition_id, NEW.issuer_id, + NEW.issuer_auth_generation, NEW.playable_state_namespace_id, + NEW.character_id, NEW.playable_state_scope, NEW.region_id, NEW.region_epoch, + NEW.partition_id, NEW.issuer_index_layout_version, + NEW.issuer_index_partition_count, NEW.issuer_index_partition_capacity, + NEW.reservation_fence, NEW.issuer_coverage_operation_id, + NEW.issuer_coverage_operation_fence, NEW.coverage_fence, + NEW.inventory_snapshot_revision, NEW.created_at + ) IS DISTINCT FROM ROW( + OLD.reservation_id, OLD.binding_ref, OLD.account_id, OLD.tenant_id, + OLD.game_instance_id, OLD.runtime_game_instance_id, OLD.session_id, + OLD.binding_generation, OLD.transition_id, OLD.issuer_id, + OLD.issuer_auth_generation, OLD.playable_state_namespace_id, + OLD.character_id, OLD.playable_state_scope, OLD.region_id, OLD.region_epoch, + OLD.partition_id, OLD.issuer_index_layout_version, + OLD.issuer_index_partition_count, OLD.issuer_index_partition_capacity, + OLD.reservation_fence, OLD.issuer_coverage_operation_id, + OLD.issuer_coverage_operation_fence, OLD.coverage_fence, + OLD.inventory_snapshot_revision, OLD.created_at + ) THEN + RAISE EXCEPTION 'First-NEW abort reservation transition changed its retained owner tuple' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_first_new_abort_reservation_immutable'; + END IF; + + IF NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_binding_transition transition + JOIN game_session_canonical_gameplay_binding_inventory candidate + ON candidate.binding_ref = transition.candidate_binding_ref + WHERE transition.transition_id = NEW.transition_id + AND transition.status = 'ABORTED' + AND transition.admission_lease_id IS NOT NULL + AND transition.admission_lease_kind = 'NEW_BINDING' + AND transition.expected_prior_binding_ref IS NULL + AND transition.expected_prior_binding_generation IS NULL + AND transition.admission_orphan_cleanup_id IS NOT NULL + AND transition.admission_orphan_cleanup_id <> + '00000000-0000-0000-0000-000000000000'::uuid + AND transition.inventory_revision = NEW.inventory_revision + AND transition.issuer_reservation_id = NEW.reservation_id + AND transition.candidate_binding_ref = NEW.binding_ref + AND transition.candidate_binding_generation = NEW.binding_generation + AND transition.tenant_id = NEW.tenant_id + AND transition.playable_state_namespace_id = NEW.playable_state_namespace_id + AND transition.character_id = NEW.character_id + AND transition.candidate_account_index_fence = candidate.account_index_fence + AND candidate.lifecycle = 'PROVISIONAL' + AND candidate.inventory_revision = OLD.inventory_revision + AND candidate.transition_id = NEW.transition_id + AND candidate.issuer_reservation_id = NEW.reservation_id + AND candidate.account_id = NEW.account_id + AND candidate.tenant_id = NEW.tenant_id + AND candidate.playable_state_namespace_id = NEW.playable_state_namespace_id + AND candidate.character_id = NEW.character_id + AND candidate.game_instance_id = NEW.game_instance_id + AND candidate.runtime_game_instance_id = NEW.runtime_game_instance_id + AND candidate.session_id = NEW.session_id + AND candidate.region_id = NEW.region_id + AND candidate.region_epoch = NEW.region_epoch + AND candidate.issuer_id = NEW.issuer_id + AND candidate.issuer_auth_generation = NEW.issuer_auth_generation + AND candidate.issuer_index_layout_version = NEW.issuer_index_layout_version + AND candidate.issuer_index_partition_count = NEW.issuer_index_partition_count + AND candidate.issuer_index_partition_capacity = NEW.issuer_index_partition_capacity + AND candidate.binding_generation = NEW.binding_generation + AND candidate.binding_ref = NEW.binding_ref + AND candidate.account_index_fence = transition.candidate_account_index_fence + ) THEN + RAISE EXCEPTION 'Only an exact retained first-NEW Account abort may release its reservation' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_first_new_abort_reservation_source_required'; + END IF; + END IF; + RETURN NEW; +END; +$$; + CREATE TRIGGER game_session_first_new_issuer_release_reservation BEFORE UPDATE ON game_session_canonical_issuer_partition_reservation FOR EACH ROW EXECUTE FUNCTION require_first_new_issuer_release_reservation(); @@ -584,3 +740,5 @@ BEGIN RETURN NULL; END; $$; + +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java index 72f4f3758f..7706bdac2e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java @@ -17,9 +17,9 @@ import java.util.EnumSet; import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.UUID; -import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; @@ -41,10 +41,10 @@ import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountMemberRepairRedisScriptContribution; -import net.firedevops.firemud.test.TestContainerImages; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution; +import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -72,18 +72,26 @@ public final class CanonicalGameplayAdmissionAbortCompositionFixture implements private GenericContainer memberRedis; private RedisClient memberRedisApplication; private CanonicalGameplayAccountMemberAcknowledgement memberAcknowledgement; - private final AtomicReference issuerState; - private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource issuerSource; - private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState initialIssuerState; + private final AtomicReference< + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState> + issuerState; + private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + issuerSource; + private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState + initialIssuerState; private final CanonicalGameplayIssuerBindingLocalOperation localOperation; private final CanonicalGameplayIssuerBindingLocalProjectionRepository localProjectionRepository; private final RedisClient issuerRedisClient; private final RedisScriptCatalog issuerCatalog; - private final Map otherOperations = new HashMap<>(); + private final Map otherOperations = + new HashMap<>(); public CanonicalGameplayAdmissionAbortCompositionFixture( - DriverManagerDataSource accountDataSource, Candidate accountCandidate, RedisClient issuerRedisClient) { - this.issuerRedisClient = java.util.Objects.requireNonNull(issuerRedisClient, "issuerRedisClient"); + DriverManagerDataSource accountDataSource, + Candidate accountCandidate, + RedisClient issuerRedisClient) { + this.issuerRedisClient = + java.util.Objects.requireNonNull(issuerRedisClient, "issuerRedisClient"); dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); dataSource.setUrl( @@ -131,37 +139,58 @@ public CanonicalGameplayAdmissionAbortCompositionFixture( BigInteger partitionCount = identity.issuerIndexPartitionCount(); BigInteger partitionCapacity = identity.issuerIndexPartitionCapacity(); String mapping = CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY; - String exactDescriptor = "issuer-layout-descriptor/v1|" + identity.issuerId() + "|" - + layoutVersion + "|" + partitionCount + "|" + partitionCapacity + "|" + mapping; + String exactDescriptor = + "issuer-layout-descriptor/v1|" + + identity.issuerId() + + "|" + + layoutVersion + + "|" + + partitionCount + + "|" + + partitionCapacity + + "|" + + mapping; var trustedLayout = new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor( - identity.issuerId(), layoutVersion, partitionCount, partitionCapacity, mapping, + identity.issuerId(), + layoutVersion, + partitionCount, + partitionCapacity, + mapping, exactDescriptor.getBytes(StandardCharsets.UTF_8)); - var sourceCheckpoint = trustedSourceCheckpoint(identity.issuerId(), identity.issuerAuthGeneration()); + var sourceCheckpoint = + trustedSourceCheckpoint(identity.issuerId(), identity.issuerAuthGeneration()); UUID bootstrapRequestId = UUID.randomUUID(); var bootstrapIntent = new CanonicalGameplayIssuerLayoutBootstrapRepository(dsl) .beginInitialBootstrapIntent(bootstrapRequestId, trustedLayout, sourceCheckpoint); - initialIssuerState = new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( - bootstrapIntent.sourceCheckpoint(), stableIncarnation()); + initialIssuerState = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + bootstrapIntent.sourceCheckpoint(), stableIncarnation()); issuerState = new AtomicReference<>(initialIssuerState); issuerSource = issuerState::get; - issuerCatalog = RedisScriptCatalog.fromContributions(List.of( - new CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution(), - new CanonicalGameplayIssuerBindingLocalRedisScriptContribution(), - new CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution())); - var partitionOwner = new CanonicalGameplayIssuerBootstrapPartitionRedisOwner( - issuerRedisClient, issuerCatalog, issuerSource); + issuerCatalog = + RedisScriptCatalog.fromContributions( + List.of( + new CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution(), + new CanonicalGameplayIssuerBindingLocalRedisScriptContribution(), + new CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution())); + var partitionOwner = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner( + issuerRedisClient, issuerCatalog, issuerSource); new CanonicalGameplayIssuerBootstrapCoverageOwner(dsl, partitionOwner, issuerSource) .completeInitialBootstrap(bootstrapIntent.operationId(), bootstrapRequestId); - var request = new CanonicalGameplayIssuerBindingLocalOperation.Request( - UUID.randomUUID(), transitionId, identity, null, null); - localOperation = new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, issuerSource) - .beginOrResumeOrdinaryNew(request); + var request = + new CanonicalGameplayIssuerBindingLocalOperation.Request( + UUID.randomUUID(), transitionId, identity, null, null); + localOperation = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, issuerSource) + .beginOrResumeOrdinaryNew(request); generation = localOperation.preparedTransition().bindingGeneration(); - localProjectionRepository = new CanonicalGameplayIssuerBindingLocalProjectionRepository(dsl, issuerSource); + localProjectionRepository = + new CanonicalGameplayIssuerBindingLocalProjectionRepository(dsl, issuerSource); new CanonicalGameplayIssuerBindingLocalRedisOwner( - issuerRedisClient, issuerCatalog, localProjectionRepository, issuerSource) + issuerRedisClient, issuerCatalog, localProjectionRepository, issuerSource) .projectAndRead(localOperation); } @@ -373,10 +402,12 @@ public Target target() { } public void publish(AccountGameplayAdmissionLeaseEvidence lease) { - repository.markProvisional(repository.readProvisionalCasEvidence(transitionId), - new CanonicalGameplayAdmissionDecision(transitionId, lease, identity, generation, null, target)); + repository.markProvisional( + repository.readProvisionalCasEvidence(transitionId), + new CanonicalGameplayAdmissionDecision( + transitionId, lease, identity, generation, null, target)); new CanonicalGameplayIssuerBindingLocalRedisOwner( - issuerRedisClient, issuerCatalog, localProjectionRepository, issuerSource) + issuerRedisClient, issuerCatalog, localProjectionRepository, issuerSource) .projectAndRead(localOperation); } @@ -479,7 +510,7 @@ public CanonicalGameplayIssuerBindingLocalReleaseOperation prepareIssuerRelease( public CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.Readback projectIssuerRelease( CanonicalGameplayIssuerBindingLocalReleaseOperation operation) { return new CanonicalGameplayIssuerBindingLocalReleaseRedisOwner( - issuerRedisClient, issuerCatalog, localProjectionRepository, issuerSource) + issuerRedisClient, issuerCatalog, localProjectionRepository, issuerSource) .releaseAndRead(operation); } @@ -488,7 +519,8 @@ public void projectIssuerReleaseAndLoseReply( CanonicalGameplayIssuerBindingLocalReleaseOperation operation) { var readback = projectIssuerRelease(operation); if (!readbackHasExactReleasedMember(operation, readback)) { - throw new IllegalStateException("Actual issuer release did not produce its exact terminal readback"); + throw new IllegalStateException( + "Actual issuer release did not produce its exact terminal readback"); } throw new IllegalStateException("controlled lost issuer release reply after physical readback"); } @@ -503,42 +535,82 @@ public CanonicalGameplayIssuerBindingLocalReleaseOperation completeIssuerRelease public UUID prepareOtherControllerNew(String seed) { CanonicalGameplayBindingIdentity other; do { - other = new CanonicalGameplayBindingIdentity( - identity.accountId(), identity.tenantId(), identity.playableStateNamespaceId(), UUID.randomUUID(), - identity.playableStateScope(), identity.gameInstanceId(), identity.runtimeGameInstanceId(), - UUID.randomUUID().toString(), identity.regionId(), identity.regionEpoch(), identity.issuerId(), - identity.issuerAuthGeneration(), identity.issuerIndexLayoutVersion(), - identity.issuerIndexPartitionCount(), identity.issuerIndexPartitionCapacity()); - } while (!other.bindingRef().partitionId(identity.issuerIndexPartitionCount()) + other = + new CanonicalGameplayBindingIdentity( + identity.accountId(), + identity.tenantId(), + identity.playableStateNamespaceId(), + UUID.randomUUID(), + identity.playableStateScope(), + identity.gameInstanceId(), + identity.runtimeGameInstanceId(), + UUID.randomUUID().toString(), + identity.regionId(), + identity.regionEpoch(), + identity.issuerId(), + identity.issuerAuthGeneration(), + identity.issuerIndexLayoutVersion(), + identity.issuerIndexPartitionCount(), + identity.issuerIndexPartitionCapacity()); + } while (!other + .bindingRef() + .partitionId(identity.issuerIndexPartitionCount()) .equals(localOperation.reservation().partitionId())); - var operation = new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, issuerSource) - .beginOrResumeOrdinaryNew(new CanonicalGameplayIssuerBindingLocalOperation.Request( - UUID.nameUUIDFromBytes((seed + "-request").getBytes(StandardCharsets.UTF_8)), - UUID.nameUUIDFromBytes((seed + "-transition").getBytes(StandardCharsets.UTF_8)), other, null, null)); + var operation = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, issuerSource) + .beginOrResumeOrdinaryNew( + new CanonicalGameplayIssuerBindingLocalOperation.Request( + UUID.nameUUIDFromBytes((seed + "-request").getBytes(StandardCharsets.UTF_8)), + UUID.nameUUIDFromBytes((seed + "-transition").getBytes(StandardCharsets.UTF_8)), + other, + null, + null)); otherOperations.put(seed, operation); return operation.operationId(); } public BigInteger preparedLocalCountedReservations() { var work = localProjectionRepository.readPreparedPartitionWork(localOperation); - return BigInteger.valueOf(work.localEntries().stream() - .filter(entry -> entry.memberValue().reservation().partitionId() - .equals(localOperation.reservation().partitionId())) - .filter(CanonicalGameplayIssuerBindingLocalProjectionRepository.LocalEntry::countsTowardCapacity) - .count()); + return BigInteger.valueOf( + work.localEntries().stream() + .filter( + entry -> + entry + .memberValue() + .reservation() + .partitionId() + .equals(localOperation.reservation().partitionId())) + .filter( + CanonicalGameplayIssuerBindingLocalProjectionRepository.LocalEntry + ::countsTowardCapacity) + .count()); } public void moveIssuerIncarnation() { var current = issuerState.get(); - issuerState.set(new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( - current.accountCheckpoint(), stableIncarnation("moved-release-incarnation"))); + issuerState.set( + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + current.accountCheckpoint(), stableIncarnation("moved-release-incarnation"))); } public void moveIssuerSourceCheckpoint() { var current = issuerState.get(); - issuerState.set(new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( - trustedSourceCheckpoint(identity.issuerId(), identity.issuerAuthGeneration().add(BigInteger.ONE)), - current.incarnation())); + var trusted = + trustedSourceCheckpoint( + identity.issuerId(), identity.issuerAuthGeneration().add(BigInteger.ONE)); + byte[] checkpointBytes = trusted.checkpointBytes(); + byte[] eventBytes = Objects.requireNonNull(trusted.latestEventBytes()); + var checkpoint = + new CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint( + trusted.issuerId(), + trusted.issuerAuthGeneration(), + checkpointBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(checkpointBytes), + eventBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(eventBytes)); + issuerState.set( + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + checkpoint, current.incarnation())); } public void restoreIssuerState() { @@ -548,59 +620,82 @@ public void restoreIssuerState() { public boolean readbackHasExactReleasedMember( CanonicalGameplayIssuerBindingLocalReleaseOperation operation, CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.Readback readback) { - Map fields = CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( - readback.exactPhysicalFieldSetBytes()); - String capacityField = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( - operation.releasedMemberValue().reservation().reservationId()); - String bindingField = new String(operation.releasedMemberValue().owner().bindingRef().bytes(), StandardCharsets.UTF_8); + Map fields = + CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( + readback.exactPhysicalFieldSetBytes()); + String capacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + operation.releasedMemberValue().reservation().reservationId()); + String bindingField = + new String( + operation.releasedMemberValue().owner().bindingRef().bytes(), StandardCharsets.UTF_8); return readback.operationId().equals(operation.operationId()) && Arrays.equals(fields.get(capacityField), operation.exactReleasedMemberValueBytes()) && !fields.containsKey(bindingField); } - public byte[] readReleaseCapacityValue(CanonicalGameplayIssuerBindingLocalReleaseOperation operation) { - byte[] key = CanonicalGameplayIssuerRedisKeys.forMember(localOperation.memberValue()) - .getBytes(StandardCharsets.US_ASCII); - String field = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( - operation.releasedMemberValue().reservation().reservationId()); - try (var connection = issuerRedisClient.connect(io.lettuce.core.codec.ByteArrayCodec.INSTANCE)) { + public byte[] readReleaseCapacityValue( + CanonicalGameplayIssuerBindingLocalReleaseOperation operation) { + byte[] key = + CanonicalGameplayIssuerRedisKeys.forMember(localOperation.memberValue()) + .getBytes(StandardCharsets.US_ASCII); + String field = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + operation.releasedMemberValue().reservation().reservationId()); + try (var connection = + issuerRedisClient.connect(io.lettuce.core.codec.ByteArrayCodec.INSTANCE)) { return connection.sync().hget(key, field.getBytes(StandardCharsets.US_ASCII)); } } - public byte[] readReleaseBindingValue(CanonicalGameplayIssuerBindingLocalReleaseOperation operation) { - byte[] key = CanonicalGameplayIssuerRedisKeys.forMember(localOperation.memberValue()) - .getBytes(StandardCharsets.US_ASCII); + public byte[] readReleaseBindingValue( + CanonicalGameplayIssuerBindingLocalReleaseOperation operation) { + byte[] key = + CanonicalGameplayIssuerRedisKeys.forMember(localOperation.memberValue()) + .getBytes(StandardCharsets.US_ASCII); byte[] field = operation.releasedMemberValue().owner().bindingRef().bytes(); - try (var connection = issuerRedisClient.connect(io.lettuce.core.codec.ByteArrayCodec.INSTANCE)) { + try (var connection = + issuerRedisClient.connect(io.lettuce.core.codec.ByteArrayCodec.INSTANCE)) { return connection.sync().hget(key, field); } } public byte[] otherMemberValueBytes(String seed) { var operation = otherOperations.get(seed); - if (operation == null) throw new IllegalArgumentException("Other NEW operation was not prepared"); + if (operation == null) + throw new IllegalArgumentException("Other NEW operation was not prepared"); return operation.exactMemberValueBytes(); } - /** Places another real SQL operation's exact value under this reservation's field as a conflict. */ + /** + * Places another real SQL operation's exact value under this reservation's field as a conflict. + */ public void installConflictingReleaseCapacity( CanonicalGameplayIssuerBindingLocalReleaseOperation operation, byte[] conflictingBytes) { - byte[] key = CanonicalGameplayIssuerRedisKeys.forMember(localOperation.memberValue()) - .getBytes(StandardCharsets.US_ASCII); - byte[] field = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( - operation.releasedMemberValue().reservation().reservationId()).getBytes(StandardCharsets.US_ASCII); - try (var connection = issuerRedisClient.connect(io.lettuce.core.codec.ByteArrayCodec.INSTANCE)) { + byte[] key = + CanonicalGameplayIssuerRedisKeys.forMember(localOperation.memberValue()) + .getBytes(StandardCharsets.US_ASCII); + byte[] field = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + operation.releasedMemberValue().reservation().reservationId()) + .getBytes(StandardCharsets.US_ASCII); + try (var connection = + issuerRedisClient.connect(io.lettuce.core.codec.ByteArrayCodec.INSTANCE)) { connection.sync().hset(key, field, conflictingBytes); } } - public void restoreOriginalReleaseCapacity(CanonicalGameplayIssuerBindingLocalReleaseOperation operation) { - byte[] key = CanonicalGameplayIssuerRedisKeys.forMember(localOperation.memberValue()) - .getBytes(StandardCharsets.US_ASCII); - byte[] field = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( - operation.releasedMemberValue().reservation().reservationId()).getBytes(StandardCharsets.US_ASCII); - try (var connection = issuerRedisClient.connect(io.lettuce.core.codec.ByteArrayCodec.INSTANCE)) { + public void restoreOriginalReleaseCapacity( + CanonicalGameplayIssuerBindingLocalReleaseOperation operation) { + byte[] key = + CanonicalGameplayIssuerRedisKeys.forMember(localOperation.memberValue()) + .getBytes(StandardCharsets.US_ASCII); + byte[] field = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + operation.releasedMemberValue().reservation().reservationId()) + .getBytes(StandardCharsets.US_ASCII); + try (var connection = + issuerRedisClient.connect(io.lettuce.core.codec.ByteArrayCodec.INSTANCE)) { connection.sync().hset(key, field, operation.exactOriginalMemberValueBytes()); } } @@ -608,10 +703,12 @@ public void restoreOriginalReleaseCapacity(CanonicalGameplayIssuerBindingLocalRe /** Injects a conflicting newer member postimage for the negative physical-owner proof. */ public void installConflictingReleaseBinding( CanonicalGameplayIssuerBindingLocalReleaseOperation operation) { - byte[] key = CanonicalGameplayIssuerRedisKeys.forMember(localOperation.memberValue()) - .getBytes(StandardCharsets.US_ASCII); + byte[] key = + CanonicalGameplayIssuerRedisKeys.forMember(localOperation.memberValue()) + .getBytes(StandardCharsets.US_ASCII); byte[] field = operation.releasedMemberValue().owner().bindingRef().bytes(); - try (var connection = issuerRedisClient.connect(io.lettuce.core.codec.ByteArrayCodec.INSTANCE)) { + try (var connection = + issuerRedisClient.connect(io.lettuce.core.codec.ByteArrayCodec.INSTANCE)) { connection.sync().hset(key, field, operation.exactReleasedMemberValueBytes()); } } @@ -619,19 +716,24 @@ public void installConflictingReleaseBinding( /** Restores the saved exact preimage after the conflict-preservation assertion. */ public void restoreOriginalReleaseBinding( CanonicalGameplayIssuerBindingLocalReleaseOperation operation) { - byte[] key = CanonicalGameplayIssuerRedisKeys.forMember(localOperation.memberValue()) - .getBytes(StandardCharsets.US_ASCII); + byte[] key = + CanonicalGameplayIssuerRedisKeys.forMember(localOperation.memberValue()) + .getBytes(StandardCharsets.US_ASCII); byte[] field = operation.originalOperation().memberValue().owner().bindingRef().bytes(); - try (var connection = issuerRedisClient.connect(io.lettuce.core.codec.ByteArrayCodec.INSTANCE)) { + try (var connection = + issuerRedisClient.connect(io.lettuce.core.codec.ByteArrayCodec.INSTANCE)) { connection.sync().hset(key, field, operation.exactOriginalMemberValueBytes()); } } - public CanonicalGameplayIssuerBindingLocalRedisOwner.Readback projectOtherControllerNew(String seed) { + public CanonicalGameplayIssuerBindingLocalRedisOwner.Readback projectOtherControllerNew( + String seed) { var operation = otherOperations.get(seed); - if (operation == null) throw new IllegalArgumentException("Other NEW operation was not prepared"); + if (operation == null) + throw new IllegalArgumentException("Other NEW operation was not prepared"); return new CanonicalGameplayIssuerBindingLocalRedisOwner( - issuerRedisClient, issuerCatalog, localProjectionRepository, issuerSource).projectAndRead(operation); + issuerRedisClient, issuerCatalog, localProjectionRepository, issuerSource) + .projectAndRead(operation); } /** Attempts a newer candidate; the retained unresolved original must fence preparation. */ @@ -699,18 +801,44 @@ public CanonicalGameplayAdmissionAbortSource source() { return repository.readFirstNewAdmissionAbortSource(transitionId); } - public UUID originalOperationId() { return localOperation.operationId(); } - public byte[] originalMemberValueBytes() { return localOperation.exactMemberValueBytes(); } + /** Comparison accessor for the actual private schema-v2 value; no production API is widened. */ + public net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation + releasedReservation(CanonicalGameplayIssuerBindingLocalReleaseOperation operation) { + return operation.releasedMemberValue().reservation(); + } + + public UUID originalOperationId() { + return localOperation.operationId(); + } + + public byte[] originalMemberValueBytes() { + return localOperation.exactMemberValueBytes(); + } private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint trustedSourceCheckpoint(String issuerId, BigInteger generation) { + if (BigInteger.ONE.equals(generation)) { + // Controlled initial checkpoint: initialized authority has no mutation event at sequence + // zero. + // Keep the actual Account generation; never invent a source event or advance authority. + byte[] checkpoint = + ("controlled-initial-issuer-checkpoint/v1|" + issuerId + "|1") + .getBytes(StandardCharsets.UTF_8); + return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint( + issuerId, generation, checkpoint, null); + } long sequence = generation.longValueExact() - 1; - var event = AccountAuthoritySourceEventV1Codec.sealIssuer( - new AccountAuthoritySourceEventV1Codec.IssuerPreimage( - UUID.randomUUID().toString(), UUID.randomUUID().toString(), - AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + issuerId, - Long.toString(sequence), issuerId, generation.toString(), generation.toString(), - "ISSUER_SECURITY_CHANGE")); + var event = + AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + UUID.randomUUID().toString(), + UUID.randomUUID().toString(), + AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + issuerId, + Long.toString(sequence), + issuerId, + generation.toString(), + generation.toString(), + "ISSUER_SECURITY_CHANGE")); byte[] bytes = event.canonicalJsonUtf8(); return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint( issuerId, generation, bytes, bytes); @@ -721,13 +849,21 @@ private static CanonicalGameplayIssuerMemberV2Value.Incarnation stableIncarnatio } private static CanonicalGameplayIssuerMemberV2Value.Incarnation stableIncarnation(String seed) { - String digest = CanonicalGameplayIssuerMemberV2Codec.sha256( - seed.getBytes(StandardCharsets.UTF_8)); - var deployment = new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( - "controlled-release-deployment-" + seed, "controlled-release-generation-" + seed, - List.of("controlled-release-node-" + seed), "controlled-release-redis-build-" + seed, - "controlled-release-registry-" + seed, digest, "READY", "controlled-release-boot-" + seed, - "controlled-release-startup-" + seed, "controlled-release-storage-" + seed, "controlled-release-aof-" + seed); + String digest = + CanonicalGameplayIssuerMemberV2Codec.sha256(seed.getBytes(StandardCharsets.UTF_8)); + var deployment = + new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "controlled-release-deployment-" + seed, + "controlled-release-generation-" + seed, + List.of("controlled-release-node-" + seed), + "controlled-release-redis-build-" + seed, + "controlled-release-registry-" + seed, + digest, + "READY", + "controlled-release-boot-" + seed, + "controlled-release-startup-" + seed, + "controlled-release-storage-" + seed, + "controlled-release-aof-" + seed); return new CanonicalGameplayIssuerMemberV2Value.Incarnation( "controlled-release-attestor-" + seed, digest, deployment, digest, digest); } 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 04a0fc6a93..788fb1d348 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 @@ -1413,6 +1413,11 @@ private static List rowImages(DSLContext dsl, String tableName) { image = "CASE WHEN to_jsonb(retained_row)->'admission_orphan_cleanup_id' = 'null'::jsonb" + " THEN to_jsonb(retained_row) - 'admission_orphan_cleanup_id' ELSE to_jsonb(retained_row) END"; + } else if (tableName.equals("game_session_canonical_binding_issuer_index_obligation")) { + // V1036's null release link is absent-equivalent; an actual release UUID stays significant. + image = + "CASE WHEN to_jsonb(retained_row)->'local_release_operation_id' = 'null'::jsonb" + + " THEN to_jsonb(retained_row) - 'local_release_operation_id' ELSE to_jsonb(retained_row) END"; } return dsl.fetch( "SELECT (" @@ -1430,6 +1435,11 @@ private static List rowImagesWithXmin(DSLContext dsl, String tableName) image = "CASE WHEN to_jsonb(retained_row)->'admission_orphan_cleanup_id' = 'null'::jsonb" + " THEN to_jsonb(retained_row) - 'admission_orphan_cleanup_id' ELSE to_jsonb(retained_row) END"; + } else if (tableName.equals("game_session_canonical_binding_issuer_index_obligation")) { + // V1036's null release link is absent-equivalent; an actual release UUID stays significant. + image = + "CASE WHEN to_jsonb(retained_row)->'local_release_operation_id' = 'null'::jsonb" + + " THEN to_jsonb(retained_row) - 'local_release_operation_id' ELSE to_jsonb(retained_row) END"; } return dsl.fetch( "SELECT xmin::text || ':' || (" From 524950e5873b253ae22451bde88662000439b42b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:37:34 +1300 Subject: [PATCH 15/34] Align runtime fence refusal assertions with definitive abort evidence --- design/project-management/ai-observations.md | 5 +++++ ...calGameplayBindingInventoryRepositoryIntegrationTest.java | 2 +- ...CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 782cb9a229..ceeeb14869 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -416,3 +416,8 @@ Entry format: - Context: In the combined issuer owner, V1035 added a nullable abort identifier and V1036 added a nullable release linkage. Existing `to_jsonb(row)` cohort captures and retained-row assertions then included a new NULL field, so unchanged historical rows appeared to differ from their frozen source bytes. The focused native checks reproduced both cases. - Observation: Whole-row JSON implicitly includes the database schema. A forward additive column can therefore break byte identity even when every pre-existing value and applied migration is unchanged. This is distinct from a changed non-null owner identity or receipt. - Expected pattern: Preserve original frozen bytes and applied history. Where the owner contract makes the newly added NULL explicitly absence-equivalent, project out only that named field when NULL in current capture and retained-image comparison; keep non-null values and every other field significant. Prove the populated retained upgrade and exact retry, rather than using generic null stripping or rewriting old evidence. + +- `2026-10-26`: Read completed CI conclusions instead of inferring success from active-job absence + - Context: The #3310 observer reported no failures after Game Session disappeared from its query filtered to unfinished jobs. A later full job-list read exposed the actual failed conclusion; the failure at 22:19:23 NZDT was reported about nine minutes late. + - Observation: Absence from an active-job filter proves only that the job is no longer active. Treating it as success delayed repair of two stale raw-abort assertion messages and produced an incorrect status report. This was observer logic, not a FireController defect. + - Expected pattern: The single CI observer reads all current-run job conclusions, including completed failures and cancellations, on every cycle and reports an actionable failure immediately. Use a filtered active-job view only to summarize remaining work; never infer success from that view or wait for the aggregate gate to fail. 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 ba45bfd0b1..bba550617e 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 @@ -852,7 +852,7 @@ void leaseBoundRuntimeFenceTriggerRejectsRawAbortAfterAccountMemberProjection() assertThat(failure.sqlState()).isEqualTo("23514"); assertThat(failure) .hasMessageContaining( - "A lease-bound runtime fence cannot be released without terminal owner reconciliation"); + "A lease-bound runtime fence cannot be released without definitive first-NEW Account abort evidence"); }); assertThat( testSchema 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 de13cb4d06..3abd1c8598 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 @@ -194,7 +194,7 @@ void exactLeaseBoundCandidatePinsRuntimeAndRejectsTerminalTransition() { + " SELECT transition_id FROM game_session_canonical_binding_transition" + " WHERE candidate_binding_ref = ?)", candidateRef)) - .hasMessageContaining("terminal owner reconciliation"); + .hasMessageContaining("definitive first-NEW Account abort evidence"); assertThat( java.util.Objects.requireNonNull( From b7b71c9528f92e9653d19df105142db7f5882187 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 03:08:17 +1300 Subject: [PATCH 16/34] fix(gameplay): fence issuer mutations and retire released capacity --- .../game-session-service/runtime-and-data.md | 2 +- .../architecture/system-architecture-redis.md | 16 +- design/project-management/ai-observations.md | 4 + .../player-access-and-session.md | 2 + ...nitiveAbortCompositionIntegrationTest.java | 25 +- .../game-session-service/build.gradle.kts | 2 + ...IssuerBindingLocalOperationRepository.java | 7 + ...ssuerBindingLocalProjectionRepository.java | 338 ++++- ...lGameplayIssuerBindingLocalRedisOwner.java | 77 +- ...layIssuerBindingLocalReleaseOperation.java | 25 +- ...indingLocalReleaseOperationRepository.java | 72 +- ...ayIssuerBindingLocalReleaseRedisOwner.java | 75 +- ...IssuerBindingLocalRetirementOperation.java | 179 +++ ...ingLocalRetirementOperationRepository.java | 975 +++++++++++++++ ...ssuerBindingLocalRetirementRedisOwner.java | 512 ++++++++ ...playIssuerBootstrapCoverageRepository.java | 84 +- ...uerBootstrapMemberOperationRepository.java | 5 +- ...IssuerBootstrapPartitionPhysicalCodec.java | 14 +- ...layIssuerBootstrapPartitionRedisOwner.java | 18 +- ...lGameplayIssuerBootstrapPartitionWork.java | 12 + .../CanonicalGameplayIssuerCohortSql.java | 92 ++ ...meplayIssuerLayoutBootstrapRepository.java | 77 +- ...ameplayIssuerPartitionBuildRepository.java | 121 +- ...onicalGameplayIssuerPartitionMutation.java | 148 +++ ...playIssuerPartitionMutationRepository.java | 541 ++++++++ ...erBindingLocalRedisScriptContribution.java | 14 +- ...ngLocalReleaseRedisScriptContribution.java | 14 +- ...ocalRetirementRedisScriptContribution.java | 51 + ...strapPartitionRedisScriptContribution.java | 15 +- ...eplayAdmissionDecisionReadGrpcService.java | 59 +- ..._single_first_new_issuer_release_guard.sql | 11 + ...l_issuer_partition_physical_retirement.sql | 565 +++++++++ .../game-session-issuer-binding-local-add.lua | 97 +- ...e-session-issuer-binding-local-release.lua | 67 +- ...ession-issuer-binding-local-retirement.lua | 273 +++++ ...ssion-issuer-bootstrap-partition-build.lua | 36 +- ...game-session-issuer-binding-local-add.json | 4 +- ...-session-issuer-binding-local-release.json | 4 +- ...ssion-issuer-binding-local-retirement.json | 35 + ...sion-issuer-bootstrap-partition-build.json | 5 +- ...eplayAdmissionAbortCompositionFixture.java | 360 +++++- ...calOperationRepositoryIntegrationTest.java | 4 +- ...BindingLocalRedisOwnerIntegrationTest.java | 188 ++- ...BootstrapCoverageOwnerIntegrationTest.java | 4 +- ...rapPartitionRedisOwnerIntegrationTest.java | 16 +- ...rtitionBuildRepositoryIntegrationTest.java | 489 ++++++++ ...suerPhysicalRetirementIntegrationTest.java | 1091 +++++++++++++++++ ...yAdmissionDecisionReadGrpcServiceTest.java | 161 ++- ...meplayIssuerPhysicalFieldSetCodecTest.java | 70 ++ 49 files changed, 6680 insertions(+), 376 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperation.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionMutation.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionMutationRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V1037__single_first_new_issuer_release_guard.sql create mode 100644 services/game-session-service/src/main/resources/db/migration/V1038__canonical_issuer_partition_physical_retirement.sql create mode 100644 services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-retirement.lua create mode 100644 services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-retirement.json create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalFieldSetCodecTest.java 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 cb7d1b84cf..cf377c29a8 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,7 +10,7 @@ The service runtime model assumes replaceable workers, not authoritative in-proc The sections below define the target-state runtime contract. Current implementation and proof status is: -- **Local NEW issuer preparation:** canonical inventory retains Account's exact issuer string and refuses retained UUID issuers rather than relabel them. The unregistered SQL owner persists `INITIAL_BOOTSTRAP_INTENT` with a frozen complete issuer cohort and blocks later preparation. Shape-only schema-v2 member model, codec and key-helper sources are present, but do not implement a partition writer or establish authority. There is no installed pointer, partition/capacity operation, separate issuer acknowledgement, issuer barrier/`OPEN`, final CAS or admission. Descriptor and Account checkpoint inputs remain controlled, and operational incarnation, legacy recovery, PKI and activation holds remain; focused receiving proof and its limits are recorded in the tracker. See the [issuer anchor owner](../../system-architecture-redis.md#installed-issuer-anchor-for-ordinary-new) and [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for the physical contract and donor proof attribution. +- **Local NEW issuer preparation:** the unregistered Game Session sources now manually compose the initial issuer anchor, ordinary post-baseline one-key member/capacity projection, issuer-local release, and original-operation terminal-capacity retirement, each with exact physical readback and controlled Account checkpoint and stable-incarnation collaborators. The focused component proofs do not establish operational source or incarnation custody. A separate admitting issuer acknowledgement, issuer barrier/`OPEN`, final CAS, and admission remain absent. Operational source/incarnation custody, legacy recovery, production PKI, runtime registration, and activation remain open; see the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for proof attribution and limits. The [issuer anchor owner](../../system-architecture-redis.md#installed-issuer-anchor-for-ordinary-new) defines the physical contract. - **Local NEW account-member repair:** the unregistered owner prepares the original binding-local operation, performs one global account-member write and physical readback outside SQL, then accepts its exact acknowledgement in SQL. This supplies `ADD_OR_RETAIN` evidence only; the candidate remains provisional. Account-wide lifecycle writers, remaining index and region acknowledgements, and the guarded final admission CAS remain open. See [Session Behavior](../../system-architecture-session-behavior.md#global-account-active-binding-index) and [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components). diff --git a/design/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index e781f0c9ae..dc52a2cfbf 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -377,7 +377,7 @@ The exact `bindingRef` field identity and canonical partition key remain unchang Capacity evidence shares that same owned partition HASH and atomic boundary. Reserved versioned capacity-field names must be disjoint from every canonical `bindingRef` field, and capacity values retain the exact anchor, layout, original reservation/member-operation tuple, and incarnation needed for comparison. Capacity counts distinct non-terminal reservations through `RESERVED`, `BOUND`, and `RELEASE_PENDING`; it is not inferred from binding rows or total HASH fields. Separate capacity/readback steps compare the same complete tuples and never use a second key, key absence as initialization authority, or SQL intent as physical evidence. -The versioned reserved field `!issuer-partition-bootstrap/v1` retains the exact common bootstrap/layout/source/incarnation context, and `!issuer-reservation-capacity/v1:` retains the complete schema-v2 value for that original reservation and issued local operation. Both names are disjoint from the length-prefixed `bindingRef/v1` field grammar. A partition build compares the complete existing field set before mutation and refuses unknown, legacy, conflicting, expiring or partially decoded state without rewriting it. Full member and reservation values retain their original provenance; a header digest never replaces them. Complete per-partition readback remains a separate input to the later finite issuer-wide coverage proof, and its frozen aggregate expectation is not proof that other partitions have been built. +The versioned reserved field `!issuer-partition-bootstrap/v1` retains the exact common bootstrap/layout/source/incarnation context, and `!issuer-reservation-capacity/v1:` retains the complete schema-v2 value for that original reservation and issued local operation. The reserved `!issuer-partition-mutation-revision/v1` field holds the current owner-allocated canonical non-nil UUID revision used by [physical mutation and retirement](#original-operation-issuer-physical-retirement). These names are disjoint from the length-prefixed `bindingRef/v1` field grammar. A partition build compares the complete existing field set before mutation and refuses unknown, legacy, conflicting, expiring or partially decoded state without rewriting it. Full member and reservation values retain their original provenance; a header digest never replaces them. Complete per-partition readback remains a separate input to the later finite issuer-wide coverage proof, and its frozen aggregate expectation is not proof that other partitions have been built. ### Binding-Local Issuer Release Provenance @@ -387,6 +387,18 @@ The one-key release compares the complete original member and capacity evidence, Consumers require both the exact frozen physical provenance and the matching durable completion receipt and current row. They never require the physical `reservation.inventoryRevision` to equal `R`, rewrite the physical value after SQL merely to equalize revisions, or reuse one snapshot revision for two states. A crash, lost reply or exact retry reuses the original prepared bytes, `P` and operation; a completed retry reads its committed receipt without issuing a second release. Ambiguous readback, changed source/incarnation/reservation/anchor or a newer member refuses completion and preserves the pending obligation. Only that binding-local issuer repair obligation may be settled by this proof; Account cleanup, region cleanup, issuer-wide coverage and final admission retain their separate owners. +### Original-Operation Issuer Physical Retirement + +A committed binding-local release authorizes a separate physical-retirement phase under the same Game Session issuer release/local-mutation owner. The original SQL reservation, release preparation, completion receipt, coverage history and historical physical readbacks remain immutable. Retirement never substitutes absence for the positive `RELEASED` mutation and independent readback required by the preceding release contract. It does not reopen an issuer, reset an epoch, rewrite a baseline, grant global coverage or introduce a generic compaction owner. + +Every ordinary partition `ADD`, release and retirement shares one positively installed partition-local physical mutation revision/fence. Its initial installation requires the existing qualified bootstrap/anchor owner; the durable partition proof retains that exact initial revision alongside the encoded field set. Historical unfenced audit proofs remain immutable and cannot qualify a current fenced installation. A completed ordinary `ADD` retry performs a fresh read-only current-field-set and revision check without replaying its old Lua mutation. A missing or reset field is non-admitting and is never interpreted as zero. Under the existing inventory serialization, the SQL owner durably records the original expected physical revision, a never-reused owner-allocated successor and the exact intended change, and excludes a second pending mutation for that partition. No SQL transaction spans Redis. The single-key Lua mutation compares the original expected revision and atomically advances it with the exact field change, rejecting stale prepared writers before any write. The physical revision is distinct from bootstrap fences, live issuer epochs and inventory revisions `P` and `R`; numeric equality or adjacency across those domains grants no authority. One current partition fence replaces neither complete provenance nor SQL accounting, and permanent Redis fences for every historical operation are not permitted. + +Retirement references the exact committed original release receipt, original reservation and member-operation tuple, frozen schema-v2 `RELEASED` bytes at preparation revision `P`, and actual SQL completion revision `R`. The owner revalidates current source, anchor, layout, incarnation and original release provenance and protects every current binding or reservation reference. It removes only that exact terminal capacity field and refuses a changed or newer value, conflicting original member state or an unresolved operation. Newer and unrelated partition fields and separate Account or region obligations remain unchanged. + +The owner independently reads back both exact field absence and the atomic successor physical fence before committing the durable retirement receipt. A lost reply, crash or ambiguous observation retains the original pending retirement and its exact expected/successor revisions for readback-based recovery; it cannot allocate a replacement intent or issue a blind deletion. Completed original release and retirement retries consume their committed historical evidence and cannot replay stale Lua to recreate a retired field. A pending retirement excludes another same-partition admission mutation until its original outcome is resolved. + +Current unretired physical inventory is bounded separately from retained immutable audit history. Projection, complete per-partition and aggregate capacity accounting, currentness and obligation checks, strict permitted field sets, codecs and actual Lua/readback bounds all use that distinction. A retired field may be absent only when its exact original durable retirement proof accounts for that absence; an arbitrary missing field, foreign field or incomplete SQL inventory still fails closed. Retaining every historical `RELEASED` field, operation or per-operation tombstone in the physical set must not impose a lifetime limit on legitimate capacity turnover. Retirement preserves the complete SQL history and allows normal exact retries and more than 256 successive releases without exhausting a finite physical-history allowance. + ### Canonical Issuer Partition Mapping The target `bindingRef` encoding is one exact versioned UTF-8 byte sequence, consistent with the repository's length-prefixed identity convention. For `segment(bytes) = ascii(canonical_decimal_count(byte_length(bytes))) + ":" + bytes`, where the count has no leading zero, the complete binding identity is encoded in this fixed order: @@ -419,7 +431,7 @@ Changing `issuerIndexPartitionCount` is a layout migration, not a configuration Before enumeration, Game Session establishes one issuer-wide admission `coverageFence` and immutable `inventorySnapshotRevision` under the durable `operationId`/`operationFence`, and pins the active layout pointer as `{issuerIndexLayoutVersion, issuerIndexPartitionCount, issuerIndexPartitionCapacity}` for that operation. The snapshot contains the exact `issuer/` cutoff checkpoint, issuer generation, `issuanceFence`, complete applicable `outboxCheckpoints`, and the pinned layout identity. `coverageFence` is the immutable admission/creation fence for that inventory snapshot and is distinct from the maintenance `operationFence`; `coverageGeneration` is a later generation used to account for every post-fence transition. New binding, reconnect, and resume admission is blocked against that fence while coverage is open; a post-fence binding can become admissible only when it and its exact durable evidence carrier bind both the `operationFence` and `coverageFence` plus a later `coverageGeneration` to the same operation and `inventorySnapshotRevision`. Carrying only one fence or only the coverage generation is invalid. Any race that produces a non-admissible candidate, reservation, or repair obligation must be accounted for before acknowledgement. A standalone issuer-wide operation persists `parentRecoveryOperationId=NOT_APPLICABLE`, `parentLifecycle=NOT_APPLICABLE`, `parentOperationFence=NOT_APPLICABLE`, and `parentCoverageFence=NOT_APPLICABLE`, and self-binds `issuerCoverageOperationId=operationId`, `issuerCoverageLifecycle=lifecycle`, and `issuerCoverageOperationFence=operationFence`; a linked child instead associates the exact parent tuple only through its independent parent edge, while the child itself owns only its operation and coverage fences and never nests under the parent maintenance lock. Every linked child request, digest, transition, readback, acknowledgement, and retry carries only the child-owned tuple; the independent edge and parent's consumption record carry the exact parent tuple and validate the child result. Standalone records carry the four exact `NOT_APPLICABLE` parent markers. Game Session durably acknowledges each partition only with the parent-independent child issuer-partition acknowledgement tuple defined above: issuer operation identity/lifecycle/fence, `issuerId`, applicable child fences, snapshot revision, later coverage generation, pinned layout version/count/capacity, `partitionId`, exact cutoff, reservation lifecycle identities, and local plus aggregate capacity evidence. A missing HASH key is an empty partition only when the read succeeded and the matching acknowledgement proves coverage for that exact issuer-wide snapshot, operation attempt, layout, cutoff, and fences. A missing, stale, or mismatched acknowledgement, cross-snapshot or cross-attempt evidence, an unavailable read, malformed value, conflicting duplicate, unresolved reservation, or unresolved repair obligation is ambiguous coverage; the cutoff fails closed and requires reconciliation/rebuild rather than inferring empty coverage from key absence or an aggregate proof. The coverage generation is index-maintenance evidence, not a second authority generation. -For every partition `p`, `N_issuer_partition(p)` counts distinct non-terminal durable reservation entries, with each binding transition counted once even when its reservation is attached to an active, provisional, or unresolved binding. Each `IssuerPartitionReservation` is Game Session-owned durable evidence with `reservationId`, `owner` (the complete `bindingRef` and owning session identity), exact `transitionId`, `issuerId`, `partitionId`, `issuerIndexLayoutVersion`, lifecycle (`RESERVED`, `BOUND`, `RELEASE_PENDING`, or terminal `RELEASED`), `reservationFence`, and the exact coverage tuple `{issuerCoverageOperationId, operationFence, coverageFence, inventorySnapshotRevision}`. `inventorySnapshotRevision` is the complete immutable issuer-inventory revision; it is not a caller-selected or generic local revision. Before any tenant-local binding CAS publishes a binding, Game Session commits the reservation and any repair obligation in the same durable transaction, then atomically reserves one unit in the target issuer partition through a single-key capacity compare-and-set keyed by the exact reservation and transition. That CAS exact-compares the owner, transition, partition/layout, lifecycle, reservation fence, `issuerCoverageOperationId`, `operationFence`, `coverageFence`, and `inventorySnapshotRevision`, and is idempotent only for the same complete reservation tuple. It rejects or backpressures when the reservation would exceed `issuerIndexPartitionCapacity`. A binding cannot become admissible or a repair obligation be considered covered without the matching reservation. The reservation remains counted through `RESERVED`, `BOUND`, and `RELEASE_PENDING`; failed or ambiguous cleanup leaves it counted. Terminal cleanup first records `RELEASE_PENDING`, exact-compares the same coverage tuple while removing the binding field through the fenced CAS, removes/releases the capacity entry, reads back both absences and the exact terminal state with that tuple, and only then records `RELEASED`; terminal evidence remains available for idempotent reconciliation. Every CAS, readback, acknowledgement, and cleanup must exact-compare all four coverage-tuple fields; a binding-only, reservation-only, operation-only, or current-snapshot match cannot substitute. This reservation-before-binding protocol serializes concurrent admissions at the partition and prevents over-capacity races. At recovery, Game Session must enumerate the complete binding and reservation inventory, establish the same finite per-partition invariant for every `p`, and publish no coverage acknowledgement when any non-terminal reservation exceeds capacity. The aggregate proof is additionally required: `N_issuer = sum_p N_issuer_partition(p) <= issuerIndexPartitionCount * issuerIndexPartitionCapacity`. Aggregate capacity alone is insufficient. +For every partition `p`, `N_issuer_partition(p)` counts distinct non-terminal durable reservation entries, with each binding transition counted once even when its reservation is attached to an active, provisional, or unresolved binding. Each `IssuerPartitionReservation` is Game Session-owned durable evidence with `reservationId`, `owner` (the complete `bindingRef` and owning session identity), exact `transitionId`, `issuerId`, `partitionId`, `issuerIndexLayoutVersion`, lifecycle (`RESERVED`, `BOUND`, `RELEASE_PENDING`, or terminal `RELEASED`), `reservationFence`, and the exact coverage tuple `{issuerCoverageOperationId, operationFence, coverageFence, inventorySnapshotRevision}`. `inventorySnapshotRevision` is the complete immutable issuer-inventory revision; it is not a caller-selected or generic local revision. Before any tenant-local binding CAS publishes a binding, Game Session commits the reservation and any repair obligation in the same durable transaction, then atomically reserves one unit in the target issuer partition through a single-key capacity compare-and-set keyed by the exact reservation and transition. That CAS exact-compares the owner, transition, partition/layout, lifecycle, reservation fence, `issuerCoverageOperationId`, `operationFence`, `coverageFence`, and `inventorySnapshotRevision`, and is idempotent only for the same complete reservation tuple. It rejects or backpressures when the reservation would exceed `issuerIndexPartitionCapacity`. A binding cannot become admissible or a repair obligation be considered covered without the matching reservation. The reservation remains counted through `RESERVED`, `BOUND`, and `RELEASE_PENDING`; failed or ambiguous cleanup leaves it counted. Terminal cleanup first records `RELEASE_PENDING`, exact-compares the same coverage tuple while removing the binding field through the fenced CAS, and retains the exact positive `RELEASED` capacity postimage for independent readback before SQL records `RELEASED`. The separate [original-operation physical retirement](#original-operation-issuer-physical-retirement) may subsequently remove only that terminal capacity field with its positive retirement receipt; immutable release evidence remains available for idempotent reconciliation. Every CAS, readback, acknowledgement, and cleanup must exact-compare all four coverage-tuple fields; a binding-only, reservation-only, operation-only, or current-snapshot match cannot substitute. This reservation-before-binding protocol serializes concurrent admissions at the partition and prevents over-capacity races. At recovery, Game Session must enumerate the complete binding and reservation inventory, establish the same finite per-partition invariant for every `p`, and publish no coverage acknowledgement when any non-terminal reservation exceeds capacity. The aggregate proof is additionally required: `N_issuer = sum_p N_issuer_partition(p) <= issuerIndexPartitionCount * issuerIndexPartitionCapacity`. Aggregate capacity alone is insufficient. Game Session writes and removes issuer fields through a single-key compare-and-set over the complete expected `bindingRef`, `bindingGeneration`, `issuerAuthGeneration`, and `issuerIndexLayoutVersion`, together with the exact reservation identity, owner, transition, partition/layout, lifecycle, reservation fence, and coverage tuple `{issuerCoverageOperationId, operationFence, coverageFence, inventorySnapshotRevision}`. An identical complete value is an idempotent success; a stale or conflicting value leaves a durable repair obligation and reservation unresolved. The tenant-local binding CAS records `issuerIndexState=REPAIR_REQUIRED` and keeps the binding non-admissible until the index CAS, reservation capacity CAS, and obligation acknowledgement complete; a follow-up binding CAS records `issuerIndexState=ACKNOWLEDGED` only when the same candidate generation/fence remains current and the binding or its exact linked durable carrier retains the matching operation and coverage tuple plus later `coverageGeneration`. Recovery rebuilds partitions from the complete durable active-binding and reservation inventory using the same expected-value compare-and-set, reads back every expected binding field and reservation entry, exact-compares the complete reservation coverage tuple, enforces the per-partition capacity before publishing coverage acknowledgements, and clears obligations only after all required acknowledgements carry the matching `issuerCoverageOperationId`, `operationFence`, `coverageFence`, `inventorySnapshotRevision`, and later `coverageGeneration` for the same operation, snapshot, and layout. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index ceeeb14869..6b22ce43f6 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -421,3 +421,7 @@ Entry format: - Context: The #3310 observer reported no failures after Game Session disappeared from its query filtered to unfinished jobs. A later full job-list read exposed the actual failed conclusion; the failure at 22:19:23 NZDT was reported about nine minutes late. - Observation: Absence from an active-job filter proves only that the job is no longer active. Treating it as success delayed repair of two stale raw-abort assertion messages and produced an incorrect status report. This was observer logic, not a FireController defect. - Expected pattern: The single CI observer reads all current-run job conclusions, including completed failures and cancellations, on every cycle and reports an actionable failure immediately. Use a filtered active-job view only to summarize remaining work; never infer success from that view or wait for the aggregate gate to fail. + +- 2026-10-27: Forward owner migrations can break shared disposable fixtures even when focused owner proof passes. In #2973, a new retained completion FK exposed an omitted child in the Game Session baseline TRUNCATE list and broke both Game Session and TCP cross-service suites; a reduced World migration probe also omitted tables required by the new tail migration. Keep explicit baseline descendants and exact original trigger-state restoration together, and make reduced probes execute the complete current migration tail with its real prerequisite tables. A later Hikari closed-connection or teardown refusal can mask the original PostgreSQL error; inspect the first SQL failure in the completed job's JUnit output before attributing it to Docker availability. + +- 2026-10-27: Manual Entity Flyway fixtures must retain Entity’s existing nontransactional PostgreSQL migration-lock setting. The region composition’s new Entity schema otherwise left `CREATE UNIQUE INDEX CONCURRENTLY` waiting on Flyway’s own history transaction. An owned JVM thread dump plus `pg_blocking_pids` identified the self-block; cancelling only that matched test-owned backend preserved the failed run. Use the existing `PostgreSQLConfigurationExtension.setTransactionalLock(false)` pattern for the Entity fixture rather than changing applied migrations or host configuration. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 5ec6719b88..ad9b65fcbf 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -32,6 +32,8 @@ The manually composed first-NEW abort path now joins actual Account current-call R625 freshly passes the combined owner gate: 11 unit cases, 35 issuer PostgreSQL/Redis cases and seven actual Account–Game Session cases, with zero failures, errors or skips. Enabled affected Checkstyle, SpotBugs and formatting pass; R626 documentation checks pass. The new release case drives the actual Account abort and retained Game Session source through SQL release preparation, exact one-key Redis mutation and independent complete readback, then a fresh SQL completion. Another registered transition advances the real inventory clock between preparation and completion. Proof preserves the original operation, reservation and anchor bytes, rejects bare terminal flags and conflicting or newer physical members, replays a lost response without new identities, excludes only completed release capacity for subsequent ordinary NEW, and retains exact Account member history through issuer release and a physical post-abort runtime retirement. The [canonical issuer release owner](../../architecture/system-architecture-redis.md#binding-local-issuer-release-provenance) defines the separate preparation and completion revisions. This settles only the binding-local issuer obligation; it does not remove the Account member, settle region cleanup, acknowledge admitting issuer/region membership or make the candidate playable. Earlier failed R617–R624 attempts remain retained evidence. Descriptor, launch/World, current-source/incarnation and test-PKI collaborators remain controlled; operational authority and production activation are not established. +The expanded #3310 correction implements the [original-operation physical retirement contract](../../architecture/system-architecture-redis.md#original-operation-issuer-physical-retirement) under the existing release/local-mutation owner. R675 freshly passes 77 cases: 21 units, 49 Game Session PostgreSQL/Redis cases and seven actual Account–Game Session cases, with zero failures, errors or skips; enabled affected static analysis, formatting and 547-file documentation checks pass. Physical proof includes 257 actual Game Session releases and retirements with complete immutable SQL history, original lost-reply/restart recovery and completed retry, stale ADD and release rejection, pending same-partition exclusion, missing-revision and foreign/currentness refusal, preservation of newer fields, a 256-readable/257-refused current local-entry bound, and actual 514-field release/readback/persistence/reload. The wide case uses 250 owner-produced provisional bootstrap rows and a small post-baseline cohort; the turnover case retires each terminal field rather than accumulating 256 terminal fields. The physical mutation revision is a separate positively installed UUID domain, and historical unfenced bootstrap audit rows remain retained without qualifying current fenced coverage. The seven Account composition cases separately retain their real current-caller, lease, abort and issuer-release attribution. The new turnover cases use controlled upstream Account lease/abort, issuer checkpoint, launch/World and stable-incarnation inputs; they do not prove those producers or production authority. R672 remains a failed aggregate, including its oversized test-only history image, current-readback omission and retirement Lua shape failure; R677 separately passes the corrected 46-case preflight before R675. Operational custody, registration, admitting acknowledgements, barrier OPEN, final CAS and playable admission remain unproved. + ### Player-created roster consumer preparation The unregistered Game Session composition consumes the independently resolved current published source through Entity's distinct created-roster and selected-character reads, preserving full original creation terminals, frozen menu/actor choice and the typed original-operation receipt/recovery/retirement branch. The [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#player-created-roster-and-selected-character) owns the created evidence contract; [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md#player-created-original-roster-storage) records its local storage consequences. V1020 receipt storage does not include the separate canonical UUID runtime or creation-protection owners and supplies no Account protection or admission authority. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java index f3b2aca83b..7a7a4333cc 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java @@ -286,16 +286,11 @@ void actualAccountAbortedOrdinaryIssuerMemberReleaseHasExactReadbackRetryAndFree assertThat(aborted.reservation().lifecycle()) .isEqualTo(CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING); - var pending = session.gs.prepareIssuerRelease(); - assertThat(pending.originalOperationId()).isEqualTo(originalOperationId); - assertThat(pending.exactOriginalMemberValueBytes()).containsExactly(originalMemberBytes); - assertThat(pending.sourceInventoryRevision()) - .isGreaterThan(aborted.transition().inventoryRevision()); - assertThat(session.gs.source().transition().inventoryRevision()) - .isEqualTo(pending.sourceInventoryRevision()); - UUID secondOperationId = session.gs.prepareOtherControllerNew("second-controller"); assertThat(secondOperationId).isNotEqualTo(originalOperationId); + var secondReadback = session.gs.projectOtherControllerNew("second-controller"); + assertThat(secondReadback.operationId()).isEqualTo(secondOperationId); + assertThat(secondReadback.scriptOutcome()).isEqualTo(1L); var clockAfterOtherWriter = session .gs @@ -304,14 +299,20 @@ void actualAccountAbortedOrdinaryIssuerMemberReleaseHasExactReadbackRetryAndFree "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock WHERE singleton_id = 1") .get("inventory_revision", java.math.BigDecimal.class) .toBigIntegerExact(); - assertThat(clockAfterOtherWriter).isGreaterThan(pending.sourceInventoryRevision()); - assertThat(session.gs.source().transition().inventoryRevision()) - .isEqualTo(pending.sourceInventoryRevision()); assertThat(session.gs.preparedLocalCountedReservations()).isEqualTo(java.math.BigInteger.TWO); assertThatThrownBy(() -> session.gs.prepareOtherControllerNew("full-before-release")) .isInstanceOf(RuntimeException.class) .hasMessageContaining("capacity"); + var pending = session.gs.prepareIssuerRelease(); + assertThat(pending.originalOperationId()).isEqualTo(originalOperationId); + assertThat(pending.exactOriginalMemberValueBytes()).containsExactly(originalMemberBytes); + assertThat(pending.sourceInventoryRevision()) + .isGreaterThan(aborted.transition().inventoryRevision()); + assertThat(pending.sourceInventoryRevision()).isGreaterThan(clockAfterOtherWriter); + assertThat(session.gs.source().transition().inventoryRevision()) + .isEqualTo(pending.sourceInventoryRevision()); + String preparedImage = session.image(); assertThatThrownBy( () -> @@ -417,7 +418,7 @@ void actualAccountAbortedOrdinaryIssuerMemberReleaseHasExactReadbackRetryAndFree "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock WHERE singleton_id = 1") .get("inventory_revision", java.math.BigDecimal.class) .toBigIntegerExact(); - assertThat(clockBeforeCompletion).isEqualTo(clockAfterOtherWriter); + assertThat(clockBeforeCompletion).isEqualTo(pending.sourceInventoryRevision()); var afterPhysicalReadback = session.gs.source(); assertThat(afterPhysicalReadback.reservation().lifecycle()) .isEqualTo(CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING); diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index 195c9e6711..983205a9ab 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -184,6 +184,8 @@ val gameSessionClassesProofJar by tasks.registering(Jar::class) { include("redis/scripts/game-session-issuer-binding-local-add.json") include("redis/lua/game-session-issuer-binding-local-release.lua") include("redis/scripts/game-session-issuer-binding-local-release.json") + include("redis/lua/game-session-issuer-binding-local-retirement.lua") + include("redis/scripts/game-session-issuer-binding-local-retirement.json") } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java index 9c56c8fc67..fabd0ba676 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java @@ -316,6 +316,13 @@ private CanonicalGameplayIssuerBindingLocalOperation recordOrReplayInTransaction CanonicalIssuerPartitionReservation reservation = readAndRequireReservation(transaction, transitionRequest, prepared, null); + CanonicalGameplayIssuerPartitionMutationRepository.PartitionMutationHead mutationHead = + CanonicalGameplayIssuerPartitionMutationRepository.readHeadInTransaction( + transaction, reservation.partitionId()); + if (mutationHead.pendingMutationId() != null) { + throw conflict( + "A same-partition physical mutation is unresolved; new issuer admission remains excluded"); + } var proof = CanonicalGameplayIssuerBootstrapCoverageRepository.readInstalledAnchorPartitionProof( transaction, actualAnchor, reservation.partitionId()); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java index bb3963e250..607f3121a0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java @@ -33,6 +33,10 @@ final class CanonicalGameplayIssuerBindingLocalProjectionRepository { private static final String TRANSITION = "game_session_canonical_binding_transition"; private static final String ISSUER_OBLIGATION = "game_session_canonical_binding_issuer_index_obligation"; + private static final String ACCOUNT_OBLIGATION = + "game_session_canonical_binding_account_index_obligation"; + private static final String REGION_OBLIGATION = + "game_session_canonical_binding_region_bridge_obligation"; private static final String ISSUER_LOCAL_RELEASE = "game_session_canonical_issuer_binding_local_release_operation"; private static final String ACCOUNT_CONTROL = "game_session_canonical_account_coverage_control"; @@ -59,6 +63,16 @@ final class CanonicalGameplayIssuerBindingLocalProjectionRepository { */ PreparedPartitionWork readPreparedPartitionWork( CanonicalGameplayIssuerBindingLocalOperation target) { + return readPreparedPartitionWork(target, false); + } + + PreparedPartitionWork prepareAddMutationWork( + CanonicalGameplayIssuerBindingLocalOperation target) { + return readPreparedPartitionWork(target, true); + } + + private PreparedPartitionWork readPreparedPartitionWork( + CanonicalGameplayIssuerBindingLocalOperation target, boolean prepareAddMutation) { Objects.requireNonNull(target, "target"); requireNoAmbientTransaction(); var before = readCurrentIssuerState(); @@ -72,7 +86,7 @@ PreparedPartitionWork readPreparedPartitionWork( CanonicalGameplayIssuerBootstrapCoverageRepository .readInstalledAnchorForBindingPreparationInTransaction(transaction, before); requireSameAnchor(target.anchor(), anchor); - return prepareInTransaction(transaction, target, anchor); + return prepareInTransaction(transaction, target, anchor, prepareAddMutation); }); var after = readCurrentIssuerState(); requireSameCurrentIssuerState(before, after); @@ -90,25 +104,54 @@ void requireStillCurrent(PreparedPartitionWork expected) { } } + /** Commits a physical revision only after an independent Redis readback has succeeded. */ + void completePhysicalMutation( + CanonicalGameplayIssuerPartitionMutation mutation, byte[] exactReadbackFieldSetBytes) { + Objects.requireNonNull(mutation, "mutation"); + Objects.requireNonNull(exactReadbackFieldSetBytes, "exactReadbackFieldSetBytes"); + requireNoAmbientTransaction(); + dsl.transaction( + configuration -> + CanonicalGameplayIssuerPartitionMutationRepository.completeInTransaction( + org.jooq.impl.DSL.using(configuration), mutation, exactReadbackFieldSetBytes)); + } + private PreparedPartitionWork prepareInTransaction( DSLContext transaction, CanonicalGameplayIssuerBindingLocalOperation target, - CanonicalGameplayIssuerInstalledAnchor anchor) { + CanonicalGameplayIssuerInstalledAnchor anchor, + boolean prepareAddMutation) { BigInteger targetPartition = target.reservation().partitionId(); + CanonicalGameplayIssuerPartitionMutationRepository.PartitionMutationHead mutationHead = + CanonicalGameplayIssuerPartitionMutationRepository.readHeadInTransaction( + transaction, targetPartition); CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof targetBaseline = CanonicalGameplayIssuerBootstrapCoverageRepository.readInstalledAnchorPartitionProof( transaction, anchor, targetPartition); - Map targetBaselineFields = + Map exactTargetBaselineFields = CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( targetBaseline.exactPhysicalFieldSetBytes()); - requireQualifiedBaseline(anchor, targetBaseline, targetBaselineFields); + requireQualifiedBaseline(anchor, targetBaseline, exactTargetBaselineFields); + byte[] initialRevisionField = + exactTargetBaselineFields.remove( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MUTATION_REVISION_FIELD); + if (!Arrays.equals( + initialRevisionField, + mutationHead.initialRevision().toString().getBytes(StandardCharsets.US_ASCII))) { + throw unavailable("The exact installed partition revision differs from its SQL head"); + } + Map targetBaselineFields = exactTargetBaselineFields; List operationRows = transaction.fetch( - "SELECT * FROM " + "SELECT operation.* FROM " + LOCAL_OPERATION - + " WHERE issuer_id = ? ORDER BY operation_fence, operation_id", + + " operation WHERE operation.issuer_id = ? AND NOT EXISTS (SELECT 1 FROM " + + "game_session_canonical_issuer_binding_local_retirement retirement" + + " WHERE retirement.original_local_operation_id = operation.operation_id" + + " AND retirement.status = 'RETIRED')" + + " ORDER BY operation.operation_fence, operation.operation_id", ISSUER); List entries = new ArrayList<>(operationRows.size()); Set localReservationIds = new HashSet<>(); @@ -146,6 +189,17 @@ private PreparedPartitionWork prepareInTransaction( CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( baseline.exactPhysicalFieldSetBytes()); requireQualifiedBaseline(anchor, baseline, baselineFields); + CanonicalGameplayIssuerPartitionMutationRepository.PartitionMutationHead partitionHead = + CanonicalGameplayIssuerPartitionMutationRepository.readHeadInTransaction( + transaction, partitionId); + byte[] initialRevision = + baselineFields.remove( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MUTATION_REVISION_FIELD); + if (!Arrays.equals( + initialRevision, + partitionHead.initialRevision().toString().getBytes(StandardCharsets.US_ASCII))) { + throw unavailable("A retained issuer partition baseline lost its initial revision"); + } } CanonicalGameplayIssuerBootstrapCoverageRepository.requireNewMemberAbsentFromBaseline( baseline, @@ -178,18 +232,15 @@ private PreparedPartitionWork prepareInTransaction( if (baselineReservationIds.size() != anchor.physicalReservationCount()) { throw unavailable("The installed baseline reservation cohort is incomplete"); } - Set expectedReservationIds = new HashSet<>(baselineReservationIds); for (UUID reservationId : localReservationIds) { - if (!expectedReservationIds.add(reservationId)) { + if (baselineReservationIds.contains(reservationId)) { throw unavailable( "A post-baseline issuer operation reuses an installed reservation identity"); } } - Set currentReservationIds = readCurrentReservationIds(transaction); - if (!currentReservationIds.equals(expectedReservationIds)) { - throw unavailable( - "Durable issuer reservations differ from the installed baseline and registered local set"); - } + BigInteger currentReservationCount = + verifyCurrentReservationAccounting(transaction, anchor, baselineReservationIds.size()); + verifyRetirementAccounting(transaction); BigInteger aggregateCapacity = anchor.aggregateCountedCapacity().add(localAggregateCapacity); BigInteger aggregateBound = anchor.partitionCount().multiply(anchor.partitionCapacity()); @@ -207,6 +258,40 @@ private PreparedPartitionWork prepareInTransaction( .filter(entry -> entry.registeredOperationId().equals(target.operationId())) .findFirst() .orElseThrow(() -> unavailable("The requested operation disappeared from its SQL set")); + CanonicalGameplayIssuerPartitionMutation physicalMutation = null; + if (prepareAddMutation) { + CanonicalGameplayIssuerPartitionMutation.Kind kind = + targetEntry.bindingPresent() + ? CanonicalGameplayIssuerPartitionMutation.Kind.ADD_BINDING + : CanonicalGameplayIssuerPartitionMutation.Kind.ADD_CAPACITY; + byte[] intent = + CanonicalGameplayIssuerPartitionMutationRepository.encodeIntendedChange( + kind, + target.operationId(), + targetPartition, + targetEntry.memberValue().owner().bindingRef().bytes(), + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + targetEntry.memberValue().reservation().reservationId()) + .getBytes(StandardCharsets.US_ASCII), + targetEntry.exactMemberValueBytes(), + (targetEntry.bindingPresent() ? "1" : "0").getBytes(StandardCharsets.US_ASCII), + (targetEntry.countsTowardCapacity() ? "1" : "0").getBytes(StandardCharsets.US_ASCII)); + physicalMutation = + CanonicalGameplayIssuerPartitionMutationRepository.prepareInTransaction( + transaction, kind, target.operationId(), targetPartition, intent); + mutationHead = + CanonicalGameplayIssuerPartitionMutationRepository.readHeadInTransaction( + transaction, targetPartition); + if (physicalMutation.status() + == CanonicalGameplayIssuerPartitionMutation.Status.PENDING_PHYSICAL_PROOF + && !physicalMutation.mutationId().equals(mutationHead.pendingMutationId())) { + throw unavailable("The original ADD no longer owns its pending partition revision"); + } + if (physicalMutation.status() == CanonicalGameplayIssuerPartitionMutation.Status.COMMITTED + && mutationHead.pendingMutationId() != null) { + throw unavailable("A later same-partition mutation is unresolved during ADD replay"); + } + } Map allowedFields = new HashMap<>(targetBaselineFields); for (LocalEntry entry : entries) { if (!entry.memberValue().reservation().partitionId().equals(targetPartition)) continue; @@ -222,10 +307,11 @@ private PreparedPartitionWork prepareInTransaction( entry.exactMemberValueBytes()); } } - if (allowedFields.size() - > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_HASH_FIELDS - + 2 * MAX_LOCAL_OPERATIONS_PER_PARTITION + if (allowedFields.size() + 1 + > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_LOCAL_HASH_FIELDS || totalFieldBytes(allowedFields) + + CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD.length() + + 36L > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_TOTAL_HASH_BYTES) { throw unavailable("The prepared local issuer partition exceeds its bounded field set"); } @@ -234,9 +320,11 @@ private PreparedPartitionWork prepareInTransaction( anchor, targetBaseline.exactPhysicalFieldSetBytes(), entries, - currentReservationIds, + currentReservationCount, aggregateCapacity, - partitionCapacity); + partitionCapacity, + mutationHead.currentRevision(), + mutationHead.pendingMutationId()); return new PreparedPartitionWork( anchor, target, @@ -248,6 +336,9 @@ private PreparedPartitionWork prepareInTransaction( aggregateCapacity, aggregateBound, partitionCapacity, + mutationHead.currentRevision(), + mutationHead.pendingMutationId(), + physicalMutation, currentnessDigest); } @@ -391,6 +482,29 @@ private LocalEntry readLocalEntry( transitionRow, issuerObligation); requireAccountControlCurrent(transaction, row, member.owner().accountId()); + CanonicalGameplayIssuerPartitionMutation capacityMutation = + CanonicalGameplayIssuerPartitionMutationRepository.readOptionalInTransaction( + transaction, + CanonicalGameplayIssuerPartitionMutation.Kind.ADD_CAPACITY, + operationId, + reservation.partitionId()); + CanonicalGameplayIssuerPartitionMutation bindingMutation = + CanonicalGameplayIssuerPartitionMutationRepository.readOptionalInTransaction( + transaction, + CanonicalGameplayIssuerPartitionMutation.Kind.ADD_BINDING, + operationId, + reservation.partitionId()); + boolean capacityMustBePresent = + (capacityMutation != null + && capacityMutation.status() + == CanonicalGameplayIssuerPartitionMutation.Status.COMMITTED) + || phase.memberValue().reservation().lifecycle() + == CanonicalIssuerPartitionReservation.Lifecycle.RELEASED; + boolean bindingMustBePresent = + phase.bindingPresent() + && bindingMutation != null + && bindingMutation.status() + == CanonicalGameplayIssuerPartitionMutation.Status.COMMITTED; return new LocalEntry( operationId, phase.operationId(), @@ -402,7 +516,9 @@ private LocalEntry readLocalEntry( phase.countsTowardCapacity(), phase.lifecycle(), phase.transitionStatus(), - phase.inventoryRevision()); + phase.inventoryRevision(), + capacityMustBePresent, + bindingMustBePresent); } private static CurrentPhase verifyCurrentSourceRows( @@ -668,20 +784,129 @@ private static Set readAndVerifyBootstrapReservationIds( return reservationIds; } - private static Set readCurrentReservationIds(DSLContext transaction) { - List rows = - transaction.fetch( - "SELECT reservation_id FROM " + private static BigInteger verifyCurrentReservationAccounting( + DSLContext transaction, + CanonicalGameplayIssuerInstalledAnchor anchor, + int baselineReservationCount) { + Record localCountRow = + transaction.fetchOne( + "SELECT COUNT(*) AS count FROM " + LOCAL_OPERATION + " WHERE issuer_id = ?", ISSUER); + Record reservationCountRow = + transaction.fetchOne( + "SELECT COUNT(*) AS count FROM " + RESERVATION + " WHERE issuer_id = ?", ISSUER); + Record orphanCountRow = + transaction.fetchOne( + "SELECT COUNT(*) AS count FROM " + RESERVATION - + " WHERE issuer_id = ? ORDER BY reservation_id", + + " reservation WHERE reservation.issuer_id = ? AND NOT EXISTS (SELECT 1 FROM " + + BOOTSTRAP_OPERATION + + " bootstrap WHERE bootstrap.bootstrap_operation_id = ?" + + " AND bootstrap.reservation_id = reservation.reservation_id)" + + " AND NOT EXISTS (SELECT 1 FROM " + + LOCAL_OPERATION + + " operation WHERE operation.issuer_id = reservation.issuer_id" + + " AND operation.reservation_id = reservation.reservation_id)", + ISSUER, + anchor.bootstrapOperationId()); + Record missingCountRow = + transaction.fetchOne( + "SELECT COUNT(*) AS count FROM " + + LOCAL_OPERATION + + " operation WHERE operation.issuer_id = ? AND NOT EXISTS (SELECT 1 FROM " + + RESERVATION + + " reservation WHERE reservation.issuer_id = operation.issuer_id" + + " AND reservation.reservation_id = operation.reservation_id)", ISSUER); - Set result = new HashSet<>(); - for (Record row : rows) { - if (!result.add(uuid(row, "reservation_id"))) { - throw unavailable("The current issuer reservation inventory contains duplicate identities"); - } + if (localCountRow == null + || reservationCountRow == null + || orphanCountRow == null + || missingCountRow == null) { + throw unavailable("The complete retained issuer reservation accounting is unavailable"); + } + BigInteger localCount = number(localCountRow, "count"); + BigInteger reservationCount = number(reservationCountRow, "count"); + if (number(orphanCountRow, "count").signum() != 0 + || number(missingCountRow, "count").signum() != 0 + || !reservationCount.equals(localCount.add(BigInteger.valueOf(baselineReservationCount)))) { + throw unavailable( + "Durable issuer reservations differ from full bootstrap and local SQL history"); + } + return reservationCount; + } + + private static void verifyRetirementAccounting(DSLContext transaction) { + Record invalidRows = + transaction.fetchOne( + "SELECT COUNT(*) AS count FROM game_session_canonical_issuer_binding_local_retirement retirement" + + " LEFT JOIN " + + LOCAL_OPERATION + + " original ON original.operation_id = retirement.original_local_operation_id" + + " LEFT JOIN " + + ISSUER_LOCAL_RELEASE + + " release ON release.operation_id = retirement.release_operation_id" + + " LEFT JOIN game_session_canonical_issuer_partition_mutation mutation" + + " ON mutation.mutation_id = retirement.physical_mutation_id" + + " LEFT JOIN " + + RESERVATION + + " reservation ON reservation.reservation_id = retirement.reservation_id" + + " LEFT JOIN " + + INVENTORY + + " inventory ON inventory.binding_ref = retirement.binding_ref" + + " LEFT JOIN " + + TRANSITION + + " transition ON transition.transition_id = retirement.transition_id" + + " LEFT JOIN " + + ISSUER_OBLIGATION + + " obligation ON obligation.transition_id = retirement.transition_id" + + " AND obligation.binding_ref = retirement.binding_ref" + + " LEFT JOIN " + + ACCOUNT_OBLIGATION + + " account_obligation ON account_obligation.transition_id = retirement.transition_id" + + " AND account_obligation.obligation_ordinal = 0" + + " LEFT JOIN " + + REGION_OBLIGATION + + " region_obligation ON region_obligation.transition_id = retirement.transition_id" + + " WHERE retirement.issuer_id = ? AND (original.operation_id IS NULL OR release.operation_id IS NULL" + + " OR mutation.mutation_id IS NULL OR original.reservation_id <> retirement.reservation_id" + + " OR original.binding_ref <> retirement.binding_ref" + + " OR release.status <> 'RELEASED' OR release.original_local_operation_id <> retirement.original_local_operation_id" + + " OR release.transition_id <> retirement.transition_id" + + " OR release.reservation_id <> retirement.reservation_id" + + " OR release.binding_ref <> retirement.binding_ref" + + " OR release.original_member_value_bytes <> retirement.original_member_value_bytes" + + " OR release.released_member_value_bytes <> retirement.released_member_value_bytes" + + " OR release.source_inventory_revision <> retirement.release_source_inventory_revision" + + " OR release.completion_inventory_revision <> retirement.release_completion_inventory_revision" + + " OR mutation.mutation_kind <> 'RETIRE' OR mutation.owner_operation_id <> retirement.retirement_operation_id" + + " OR mutation.expected_revision <> retirement.expected_revision" + + " OR mutation.successor_revision <> retirement.successor_revision" + + " OR mutation.exact_intended_change_bytes <> retirement.exact_intended_change_bytes" + + " OR mutation.exact_intended_change_digest <> retirement.exact_intended_change_digest" + + " OR (retirement.status = 'RETIRED' AND (mutation.status <> 'COMMITTED'" + + " OR mutation.exact_readback_field_set_bytes <> retirement.exact_absence_readback_field_set_bytes))" + + " OR (retirement.status = 'PENDING_PHYSICAL_PROOF' AND (mutation.status <> 'PENDING_PHYSICAL_PROOF'" + + " OR reservation.reservation_id IS NULL OR reservation.lifecycle <> 'RELEASED'" + + " OR reservation.inventory_revision <> retirement.release_completion_inventory_revision" + + " OR reservation.binding_ref <> retirement.binding_ref" + + " OR inventory.binding_ref IS NULL OR inventory.lifecycle <> 'TERMINAL_UNRESOLVED'" + + " OR inventory.inventory_revision <> retirement.release_completion_inventory_revision" + + " OR inventory.transition_id <> retirement.transition_id" + + " OR transition.transition_id IS NULL OR transition.status <> 'ABORTED'" + + " OR transition.inventory_revision <> retirement.release_completion_inventory_revision" + + " OR transition.candidate_binding_ref <> retirement.binding_ref" + + " OR transition.issuer_reservation_id <> retirement.reservation_id" + + " OR obligation.transition_id IS NULL OR obligation.status <> 'RELEASED'" + + " OR obligation.local_release_operation_id <> retirement.release_operation_id" + + " OR obligation.inventory_revision <> retirement.release_completion_inventory_revision" + + " OR account_obligation.transition_id IS NULL" + + " OR account_obligation.inventory_revision <> retirement.release_completion_inventory_revision" + + " OR region_obligation.transition_id IS NULL" + + " OR region_obligation.inventory_revision <> retirement.release_completion_inventory_revision)))", + ISSUER); + if (invalidRows == null || number(invalidRows, "count").signum() != 0) { + throw unavailable( + "A retained physical retirement does not match its exact SQL release and mutation history"); } - return result; } private static void requireQualifiedBaseline( @@ -702,7 +927,13 @@ private static void requireQualifiedBaseline( int reservationCount = 0; int bindingCount = 0; for (Map.Entry field : fields.entrySet()) { - if (field.getKey().equals(headerField)) continue; + if (field.getKey().equals(headerField) + || field + .getKey() + .equals( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MUTATION_REVISION_FIELD)) { + continue; + } CanonicalGameplayIssuerMemberV2Value value; try { value = CanonicalGameplayIssuerMemberV2Codec.decode(field.getValue()); @@ -763,7 +994,7 @@ private static void requireQualifiedBaseline( if (reservationCount != proof.physicalReservationCount() || bindingCount != proof.physicalBindingCount() || countedCapacity != proof.physicalCountedCapacityCount() - || fields.size() != 1 + reservationCount + bindingCount) { + || fields.size() != 2 + reservationCount + bindingCount) { throw unavailable( "The immutable issuer baseline field set does not match its retained counts"); } @@ -956,9 +1187,11 @@ private static byte[] currentnessDigest( CanonicalGameplayIssuerInstalledAnchor anchor, byte[] baselineBytes, List entries, - Set reservationIds, + BigInteger reservationCount, BigInteger aggregateCapacity, - BigInteger partitionCapacity) { + BigInteger partitionCapacity, + UUID currentRevision, + UUID pendingMutationId) { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); update(digest, anchor.exactAnchorBytes()); @@ -975,12 +1208,18 @@ private static byte[] currentnessDigest( update(digest, entry.inventoryRevision().toString().getBytes(StandardCharsets.US_ASCII)); digest.update((byte) (entry.bindingPresent() ? 1 : 0)); digest.update((byte) (entry.countsTowardCapacity() ? 1 : 0)); + digest.update((byte) (entry.capacityMustBePresent() ? 1 : 0)); + digest.update((byte) (entry.bindingMustBePresent() ? 1 : 0)); } - for (UUID id : reservationIds.stream().sorted().toList()) { - update(digest, id.toString().getBytes(StandardCharsets.US_ASCII)); - } + update(digest, reservationCount.toString().getBytes(StandardCharsets.US_ASCII)); update(digest, aggregateCapacity.toString().getBytes(StandardCharsets.US_ASCII)); update(digest, partitionCapacity.toString().getBytes(StandardCharsets.US_ASCII)); + update(digest, currentRevision.toString().getBytes(StandardCharsets.US_ASCII)); + update( + digest, + pendingMutationId == null + ? new byte[0] + : pendingMutationId.toString().getBytes(StandardCharsets.US_ASCII)); return digest.digest(); } catch (Exception impossible) { throw new IllegalStateException("Could not retain local issuer SQL currentness", impossible); @@ -1085,7 +1324,9 @@ record LocalEntry( boolean countsTowardCapacity, String lifecycle, String transitionStatus, - BigInteger inventoryRevision) { + BigInteger inventoryRevision, + boolean capacityMustBePresent, + boolean bindingMustBePresent) { LocalEntry { exactRegisteredMemberValueBytes = exactRegisteredMemberValueBytes.clone(); exactMemberValueBytes = exactMemberValueBytes.clone(); @@ -1115,6 +1356,9 @@ static final class PreparedPartitionWork { private final BigInteger aggregateCapacity; private final BigInteger aggregateBound; private final BigInteger partitionCapacity; + private final UUID currentRevision; + private final UUID pendingMutationId; + private final CanonicalGameplayIssuerPartitionMutation physicalMutation; private final byte[] sqlCurrentnessDigest; private PreparedPartitionWork( @@ -1129,6 +1373,9 @@ private PreparedPartitionWork( BigInteger aggregateCapacity, BigInteger aggregateBound, BigInteger partitionCapacity, + UUID currentRevision, + UUID pendingMutationId, + CanonicalGameplayIssuerPartitionMutation physicalMutation, byte[] sqlCurrentnessDigest) { this.anchor = anchor; this.targetOperation = targetOperation; @@ -1140,6 +1387,9 @@ private PreparedPartitionWork( this.aggregateCapacity = aggregateCapacity; this.aggregateBound = aggregateBound; this.partitionCapacity = partitionCapacity; + this.currentRevision = Objects.requireNonNull(currentRevision, "currentRevision"); + this.pendingMutationId = pendingMutationId; + this.physicalMutation = physicalMutation; this.sqlCurrentnessDigest = sqlCurrentnessDigest.clone(); } @@ -1184,6 +1434,18 @@ BigInteger partitionCapacity() { return partitionCapacity; } + UUID currentRevision() { + return currentRevision; + } + + UUID pendingMutationId() { + return pendingMutationId; + } + + CanonicalGameplayIssuerPartitionMutation physicalMutation() { + return physicalMutation; + } + byte[] sqlCurrentnessDigest() { return sqlCurrentnessDigest.clone(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java index 6aeec1e0d5..eae3c77a7e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java @@ -107,11 +107,25 @@ public Readback projectAndRead(CanonicalGameplayIssuerBindingLocalOperation oper Objects.requireNonNull(operation, "SQL-issued local issuer operation is required"); try { requireNoAmbientTransaction(); - var work = projectionRepository.readPreparedPartitionWork(operation); + var work = projectionRepository.prepareAddMutationWork(operation); requireFreshCurrentState(work); if (!work.targetEntry().operationId().equals(operation.operationId())) { throw unavailable(); } + CanonicalGameplayIssuerPartitionMutation mutation = work.physicalMutation(); + if (mutation == null) throw unavailable(); + if (mutation.status() == CanonicalGameplayIssuerPartitionMutation.Status.COMMITTED) { + if (work.pendingMutationId() != null) throw unavailable(); + byte[] currentReadback = + readExactPhysicalState(exactPartitionKey(work), work, work.currentRevision()); + requireFreshCurrentState(work); + projectionRepository.requireStillCurrent(work); + return new Readback(operation, 3L, currentReadback); + } + if (!mutation.mutationId().equals(work.pendingMutationId()) + || !mutation.expectedRevision().equals(work.currentRevision())) { + throw unavailable(); + } RedisScriptDescriptor descriptor = requireDescriptor(); byte[] script = scriptSource(descriptor); byte[] key = exactPartitionKey(work); @@ -121,14 +135,15 @@ public Readback projectAndRead(CanonicalGameplayIssuerBindingLocalOperation oper throw new IllegalStateException( "Issuer binding-local projection returned script outcome " + result); } - byte[] readbackBytes = readExactPhysicalState(key, work); + byte[] readbackBytes = readExactPhysicalState(key, work, mutation.successorRevision()); requireFreshCurrentState(work); projectionRepository.requireStillCurrent(work); + projectionRepository.completePhysicalMutation(mutation, readbackBytes); return new Readback(operation, result, readbackBytes); } catch (RuntimeException failure) { if (failure instanceof IllegalStateException state && state.getMessage() != null - && state.getMessage().contains("issuer binding-local projection is unavailable")) { + && state.getMessage().startsWith("Issuer binding-local projection is unavailable")) { throw state; } throw unavailable(failure); @@ -154,7 +169,8 @@ private long writeOneKey(byte[] script, byte[] key, byte[][] arguments) { private byte[] readExactPhysicalState( byte[] key, - CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work) { + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work, + UUID expectedPhysicalRevision) { requireNoAmbientTransaction(); try (StatefulRedisConnection connection = redisClient.connect(ByteArrayCodec.INSTANCE)) { @@ -165,9 +181,7 @@ private byte[] readExactPhysicalState( throw unavailable(); } Long length = await(commands.hlen(key)); - int maxFields = - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_HASH_FIELDS - + 2 * CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_MEMBER_OPERATIONS; + int maxFields = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_LOCAL_HASH_FIELDS; if (length == null || length < 1 || length > maxFields) throw unavailable(); Map raw = await(commands.hgetall(key)); if (raw == null || raw.size() != length) throw unavailable(); @@ -187,7 +201,18 @@ private byte[] readExactPhysicalState( Map baseline = work.baselineFields(); Map allowed = work.allowedFields(); - if (actual.size() > allowed.size()) throw unavailable(); + if (actual.size() != allowed.size() + 1) throw unavailable(); + byte[] physicalRevision = + actual.get( + Base64.getEncoder() + .encodeToString( + CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD.getBytes( + StandardCharsets.US_ASCII))); + if (!Arrays.equals( + physicalRevision, + expectedPhysicalRevision.toString().getBytes(StandardCharsets.US_ASCII))) { + throw unavailable(); + } for (Map.Entry field : baseline.entrySet()) { byte[] redisValue = actual.get( @@ -197,10 +222,31 @@ private byte[] readExactPhysicalState( } for (Map.Entry field : actual.entrySet()) { String decodedField = decodeUtf8(Base64.getDecoder().decode(field.getKey())); + if (decodedField.equals(CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD)) + continue; byte[] expected = allowed.get(decodedField); if (expected == null || !Arrays.equals(expected, field.getValue())) throw unavailable(); } + for (var entry : work.localEntries()) { + if (!entry + .memberValue() + .reservation() + .partitionId() + .equals(work.targetOperation().memberValue().reservation().partitionId())) continue; + String capacityName = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + entry.memberValue().reservation().reservationId()); + byte[] capacityValue = actual.get(b64(capacityName.getBytes(StandardCharsets.US_ASCII))); + if (entry.capacityMustBePresent() + && !Arrays.equals(capacityValue, entry.exactMemberValueBytes())) throw unavailable(); + String bindingName = + new String(entry.memberValue().owner().bindingRef().bytes(), StandardCharsets.UTF_8); + byte[] bindingValue = actual.get(b64(bindingName.getBytes(StandardCharsets.UTF_8))); + if (entry.bindingMustBePresent() + && !Arrays.equals(bindingValue, entry.exactMemberValueBytes())) throw unavailable(); + } + var target = work.targetEntry(); String capacityField = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( @@ -238,7 +284,9 @@ private byte[] readExactPhysicalState( for (var entry : actual.entrySet()) { String field = decodeUtf8(Base64.getDecoder().decode(entry.getKey())); byte[] valueBytes = entry.getValue(); - if (field.startsWith( + if (field.equals(CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD)) { + continue; + } else if (field.startsWith( CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.RESERVATION_FIELD_PREFIX)) { var value = CanonicalGameplayIssuerMemberV2Codec.decode(valueBytes); if (value.reservation().lifecycle() @@ -308,6 +356,10 @@ private static Map decodePhysicalMap(Map encoded return result; } + private static String b64(byte[] value) { + return Base64.getEncoder().encodeToString(value); + } + private void requireFreshCurrentState( CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work) { requireNoAmbientTransaction(); @@ -416,6 +468,8 @@ private static byte[][] scriptArguments( arguments.add(entry.exactMemberValueBytes()); arguments.add(ascii(entry.bindingPresent() ? "1" : "0")); arguments.add(ascii(entry.countsTowardCapacity() ? "1" : "0")); + arguments.add(ascii(entry.capacityMustBePresent() ? "1" : "0")); + arguments.add(ascii(entry.bindingMustBePresent() ? "1" : "0")); } var target = work.targetEntry(); arguments.add(ascii(target.operationId().toString())); @@ -426,6 +480,11 @@ private static byte[][] scriptArguments( arguments.add(ascii(work.partitionCapacity().toString())); arguments.add(ascii(work.aggregateCapacity().toString())); arguments.add(ascii(work.aggregateBound().toString())); + var mutation = work.physicalMutation(); + if (mutation == null) throw unavailable(); + arguments.add(ascii(mutation.expectedRevision().toString())); + arguments.add(ascii(mutation.successorRevision().toString())); + arguments.add(ascii(mutation.kind().name())); return arguments.toArray(byte[][]::new); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperation.java index 6a25fd5225..e68a21c26b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperation.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperation.java @@ -28,6 +28,7 @@ public enum Status { private final byte[] exactReleasedMemberValueBytes; private final byte[] exactPhysicalReadbackFieldSetBytes; private final String physicalReadbackDigest; + private final CanonicalGameplayIssuerPartitionMutation physicalMutation; private final Status status; CanonicalGameplayIssuerBindingLocalReleaseOperation( @@ -43,6 +44,7 @@ public enum Status { byte[] exactReleasedMemberValueBytes, byte[] exactPhysicalReadbackFieldSetBytes, String physicalReadbackDigest, + CanonicalGameplayIssuerPartitionMutation physicalMutation, Status status) { this.abortSource = Objects.requireNonNull(abortSource, "Account-aborted source required"); this.originalOperation = @@ -66,6 +68,7 @@ public enum Status { ? null : exactPhysicalReadbackFieldSetBytes.clone(); this.physicalReadbackDigest = physicalReadbackDigest; + this.physicalMutation = Objects.requireNonNull(physicalMutation, "physicalMutation"); this.status = Objects.requireNonNull(status, "status"); CanonicalGameplayIssuerMemberV2Value original = originalOperation.memberValue(); @@ -153,6 +156,19 @@ public enum Status { "Release operation differs from its exact Account-aborted source"); } + if (physicalMutation.kind() != CanonicalGameplayIssuerPartitionMutation.Kind.RELEASE + || !physicalMutation.ownerOperationId().equals(operationId) + || !physicalMutation.partitionId().equals(sourceReservation.partitionId()) + || (status == Status.PENDING_PHYSICAL_PROOF + && physicalMutation.status() + != CanonicalGameplayIssuerPartitionMutation.Status.PENDING_PHYSICAL_PROOF) + || (status == Status.RELEASED + && physicalMutation.status() + != CanonicalGameplayIssuerPartitionMutation.Status.COMMITTED)) { + throw new IllegalArgumentException( + "Release operation differs from its physical revision receipt"); + } + if (status == Status.PENDING_PHYSICAL_PROOF) { if (this.exactPhysicalReadbackFieldSetBytes != null || physicalReadbackDigest != null) { throw new IllegalArgumentException( @@ -178,7 +194,10 @@ public enum Status { String bindingField = new String(releasedMemberValue.owner().bindingRef().bytes(), StandardCharsets.UTF_8); if (!Arrays.equals(readback.get(capacityField), this.exactReleasedMemberValueBytes) - || readback.containsKey(bindingField)) { + || readback.containsKey(bindingField) + || !Arrays.equals( + physicalMutation.exactReadbackFieldSetBytes(), + this.exactPhysicalReadbackFieldSetBytes)) { throw new IllegalArgumentException( "Released proof does not contain its exact terminal capacity postimage"); } @@ -239,6 +258,10 @@ public String physicalReadbackDigest() { return physicalReadbackDigest; } + CanonicalGameplayIssuerPartitionMutation physicalMutation() { + return physicalMutation; + } + public Status status() { return status; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.java index 9dd0814ef5..bf9bf4bff9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.java @@ -71,7 +71,7 @@ CanonicalGameplayIssuerBindingLocalReleaseOperation prepareOrResume(UUID transit transaction.fetchOne( "SELECT * FROM " + RELEASE + " WHERE transition_id = ? FOR UPDATE", transitionId); - if (existing != null) return readOperation(existing, source, original); + if (existing != null) return readOperation(transaction, existing, source, original); if (source.reservation().lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING || !sameOperationSource(original, source)) { @@ -122,7 +122,28 @@ CanonicalGameplayIssuerBindingLocalReleaseOperation prepareOrResume(UUID transit transaction.fetchOne( "SELECT * FROM " + RELEASE + " WHERE operation_id = ? FOR UPDATE", releaseId); if (saved == null) throw conflict("Issuer release operation was not retained"); - return readOperation(saved, source, original); + byte[] mutationIntent = + CanonicalGameplayIssuerPartitionMutationRepository.encodeIntendedChange( + CanonicalGameplayIssuerPartitionMutation.Kind.RELEASE, + releaseId, + original.reservation().partitionId(), + original.operationId().toString().getBytes(StandardCharsets.US_ASCII), + source + .reservation() + .reservationId() + .toString() + .getBytes(StandardCharsets.US_ASCII), + source.transition().bindingRef().bytes(), + originalBytes, + releasedBytes, + sourceRevision.toString().getBytes(StandardCharsets.US_ASCII)); + CanonicalGameplayIssuerPartitionMutationRepository.prepareInTransaction( + transaction, + CanonicalGameplayIssuerPartitionMutation.Kind.RELEASE, + releaseId, + original.reservation().partitionId(), + mutationIntent); + return readOperation(transaction, saved, source, original); }); requireSameCurrentIssuerState(issuerStateBefore, readCurrentIssuerState()); requireSameAbortIdentity( @@ -160,11 +181,14 @@ CanonicalGameplayIssuerBindingLocalReleaseOperation completeWithReadback( "SELECT * FROM " + RELEASE + " WHERE operation_id = ? FOR UPDATE", expected.operationId()); if (releaseRow == null) throw conflict("SQL issuer release operation disappeared"); - var current = readOperation(releaseRow, source, expected.originalOperation()); + var current = + readOperation(transaction, releaseRow, source, expected.originalOperation()); requireSameOperation(expected, current); if (current.status() == CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED) { verifyReadbackMatchesOperation(current, readbackBytes, readbackDigest); + CanonicalGameplayIssuerPartitionMutationRepository.completeInTransaction( + transaction, current.physicalMutation(), readbackBytes); return current; } if (source.reservation().lifecycle() @@ -177,6 +201,8 @@ CanonicalGameplayIssuerBindingLocalReleaseOperation completeWithReadback( "Inventory clock regressed behind the durable issuer release preparation"); } verifyReadbackMatchesOperation(current, readbackBytes, readbackDigest); + CanonicalGameplayIssuerPartitionMutationRepository.completeInTransaction( + transaction, current.physicalMutation(), readbackBytes); BigInteger completionRevision = currentRevision.add(BigInteger.ONE); requireCounterLimit(completionRevision, "completionInventoryRevision"); requireOne( @@ -315,7 +341,8 @@ CanonicalGameplayIssuerBindingLocalReleaseOperation completeWithReadback( expected.operationId()); if (completedRow == null) throw conflict("Released issuer operation disappeared after completion"); - return readOperation(completedRow, completedSource, expected.originalOperation()); + return readOperation( + transaction, completedRow, completedSource, expected.originalOperation()); }); requireSameCurrentIssuerState(issuerStateBefore, readCurrentIssuerState()); CanonicalGameplayAdmissionAbortSource sourceAfter = @@ -328,6 +355,7 @@ CanonicalGameplayIssuerBindingLocalReleaseOperation completeWithReadback( } private CanonicalGameplayIssuerBindingLocalReleaseOperation readOperation( + DSLContext transaction, Record row, CanonicalGameplayAdmissionAbortSource source, CanonicalGameplayIssuerBindingLocalOperation original) { @@ -392,6 +420,27 @@ private CanonicalGameplayIssuerBindingLocalReleaseOperation readOperation( byte[] physicalReadback = optionalBytes(row, "physical_readback_field_set_bytes"); String physicalDigest = row.get("physical_readback_field_set_digest", String.class); BigInteger completionRevision = nullablePositive(row, "completion_inventory_revision"); + CanonicalGameplayIssuerPartitionMutation physicalMutation = + CanonicalGameplayIssuerPartitionMutationRepository.readInTransaction( + transaction, + CanonicalGameplayIssuerPartitionMutation.Kind.RELEASE, + operationId, + original.reservation().partitionId()); + byte[] expectedMutationIntent = + CanonicalGameplayIssuerPartitionMutationRepository.encodeIntendedChange( + CanonicalGameplayIssuerPartitionMutation.Kind.RELEASE, + operationId, + original.reservation().partitionId(), + original.operationId().toString().getBytes(StandardCharsets.US_ASCII), + source.reservation().reservationId().toString().getBytes(StandardCharsets.US_ASCII), + source.transition().bindingRef().bytes(), + bytes(row, "original_member_value_bytes"), + bytes(row, "released_member_value_bytes"), + sourceRevision.toString().getBytes(StandardCharsets.US_ASCII)); + if (!Arrays.equals(expectedMutationIntent, physicalMutation.exactIntendedChangeBytes())) { + throw conflict( + "Stored release revision intent differs from its exact original release tuple"); + } if ((status == CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.PENDING_PHYSICAL_PROOF && (source.reservation().lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING @@ -418,6 +467,7 @@ private CanonicalGameplayIssuerBindingLocalReleaseOperation readOperation( bytes(row, "released_member_value_bytes"), physicalReadback, physicalDigest, + physicalMutation, status); } catch (RuntimeException malformed) { throw conflict("Stored SQL issuer release operation is malformed"); @@ -880,7 +930,19 @@ private static void requireSameOperation( || !Arrays.equals( expected.exactOriginalMemberValueBytes(), current.exactOriginalMemberValueBytes()) || !Arrays.equals( - expected.exactReleasedMemberValueBytes(), current.exactReleasedMemberValueBytes())) { + expected.exactReleasedMemberValueBytes(), current.exactReleasedMemberValueBytes()) + || !expected.physicalMutation().mutationId().equals(current.physicalMutation().mutationId()) + || !expected + .physicalMutation() + .expectedRevision() + .equals(current.physicalMutation().expectedRevision()) + || !expected + .physicalMutation() + .successorRevision() + .equals(current.physicalMutation().successorRevision()) + || !Arrays.equals( + expected.physicalMutation().exactIntendedChangeBytes(), + current.physicalMutation().exactIntendedChangeBytes())) { throw conflict("SQL issuer release operation changed across its physical proof boundary"); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.java index 5efc895d77..418db0284c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.java @@ -96,8 +96,27 @@ public Readback releaseAndRead(CanonicalGameplayIssuerBindingLocalReleaseOperati Objects.requireNonNull(operation, "SQL-issued issuer release is required"); try { requireNoAmbientTransaction(); + if (operation.status() + == CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED) { + CanonicalGameplayIssuerPartitionMutation mutation = operation.physicalMutation(); + if (mutation.status() != CanonicalGameplayIssuerPartitionMutation.Status.COMMITTED + || !Arrays.equals( + mutation.exactReadbackFieldSetBytes(), + operation.exactPhysicalReadbackFieldSetBytes())) { + throw unavailable("Committed issuer release lacks its original physical mutation proof"); + } + return new Readback( + operation.operationId(), 2L, operation.exactPhysicalReadbackFieldSetBytes()); + } var original = operation.originalOperation(); var work = projectionRepository.readPreparedPartitionWork(original); + CanonicalGameplayIssuerPartitionMutation mutation = operation.physicalMutation(); + if (mutation.status() + != CanonicalGameplayIssuerPartitionMutation.Status.PENDING_PHYSICAL_PROOF + || !mutation.mutationId().equals(work.pendingMutationId()) + || !mutation.expectedRevision().equals(work.currentRevision())) { + throw unavailable("Original release no longer owns its prepared partition revision"); + } requireFreshCurrentState(work); RedisScriptDescriptor descriptor = requireDescriptor(); byte[] script = scriptSource(descriptor); @@ -153,9 +172,7 @@ private byte[] readExactPhysicalState( throw unavailable("Issuer partition type or TTL is not canonical"); } Long count = await(commands.hlen(key)); - int maxFields = - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_HASH_FIELDS - + 2 * CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_MEMBER_OPERATIONS; + int maxFields = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_LOCAL_HASH_FIELDS; if (count == null || count < 1 || count > maxFields) throw unavailable("Issuer partition field count is invalid"); Map raw = await(commands.hgetall(key)); @@ -177,8 +194,22 @@ private byte[] readExactPhysicalState( } Map baseline = work.baselineFields(); Map allowed = work.allowedFields(); - if (actual.size() > allowed.size()) + if (actual.size() != allowed.size()) throw unavailable("Issuer partition contains an unknown field"); + byte[] physicalRevision = + actual.get( + b64( + CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD.getBytes( + StandardCharsets.US_ASCII))); + if (!Arrays.equals( + physicalRevision, + operation + .physicalMutation() + .successorRevision() + .toString() + .getBytes(StandardCharsets.US_ASCII))) { + throw unavailable("Issuer release readback lacks its exact successor revision"); + } for (Map.Entry field : baseline.entrySet()) { byte[] value = actual.get(b64(field.getKey().getBytes(StandardCharsets.UTF_8))); if (value == null || !Arrays.equals(value, field.getValue())) { @@ -198,18 +229,47 @@ private byte[] readExactPhysicalState( } for (Map.Entry field : actual.entrySet()) { String decoded = decodeUtf8(Base64.getDecoder().decode(field.getKey())); + if (decoded.equals(CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD)) { + continue; + } if (decoded.equals(capacityField)) continue; byte[] expected = allowed.get(decoded); if (expected == null || !Arrays.equals(expected, field.getValue())) { throw unavailable("Issuer partition contains an unregistered or changed field"); } } + for (var entry : work.localEntries()) { + if (!entry + .memberValue() + .reservation() + .partitionId() + .equals(operation.releasedMemberValue().reservation().partitionId()) + || entry.registeredOperationId().equals(operation.originalOperationId())) continue; + String localCapacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + entry.memberValue().reservation().reservationId()); + byte[] localCapacity = + actual.get(b64(localCapacityField.getBytes(StandardCharsets.US_ASCII))); + if (entry.capacityMustBePresent() + && !Arrays.equals(localCapacity, entry.exactMemberValueBytes())) { + throw unavailable("A committed local capacity field is missing or changed"); + } + String localBindingField = + new String(entry.memberValue().owner().bindingRef().bytes(), StandardCharsets.UTF_8); + byte[] localBinding = actual.get(b64(localBindingField.getBytes(StandardCharsets.UTF_8))); + if (entry.bindingMustBePresent() + && !Arrays.equals(localBinding, entry.exactMemberValueBytes())) { + throw unavailable("A committed local binding field is missing or changed"); + } + } int physicalCapacity = 0; int physicalReservations = 0; int physicalBindings = 0; for (Map.Entry field : actual.entrySet()) { String decoded = decodeUtf8(Base64.getDecoder().decode(field.getKey())); - if (decoded.startsWith( + if (decoded.equals(CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD)) { + continue; + } else if (decoded.startsWith( CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.RESERVATION_FIELD_PREFIX)) { var value = CanonicalGameplayIssuerMemberV2Codec.decode(field.getValue()); physicalReservations++; @@ -301,6 +361,8 @@ private static byte[][] scriptArguments( args.add(entry.exactMemberValueBytes()); args.add(ascii(entry.bindingPresent() ? "1" : "0")); args.add(ascii(entry.countsTowardCapacity() ? "1" : "0")); + args.add(ascii(entry.capacityMustBePresent() ? "1" : "0")); + args.add(ascii(entry.bindingMustBePresent() ? "1" : "0")); } args.add(ascii(operation.originalOperation().operationId().toString())); args.add(ascii(operation.operationId().toString())); @@ -312,6 +374,9 @@ private static byte[][] scriptArguments( args.add(ascii(work.partitionCapacity().toString())); args.add(ascii(work.aggregateCapacity().toString())); args.add(ascii(work.aggregateBound().toString())); + var mutation = operation.physicalMutation(); + args.add(ascii(mutation.expectedRevision().toString())); + args.add(ascii(mutation.successorRevision().toString())); return args.toArray(byte[][]::new); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperation.java new file mode 100644 index 0000000000..52d2252b68 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperation.java @@ -0,0 +1,179 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; + +/** Exact SQL-issued physical removal of one terminal RELEASED capacity field. */ +final class CanonicalGameplayIssuerBindingLocalRetirementOperation { + enum Status { + PENDING_PHYSICAL_PROOF, + RETIRED + } + + private final CanonicalGameplayIssuerBindingLocalReleaseOperation release; + private final UUID operationId; + private final BigInteger partitionId; + private final UUID reservationId; + private final CanonicalGameplayIssuerPartitionMutation physicalMutation; + private final Status status; + private final byte[] exactAbsenceReadbackFieldSetBytes; + private final String exactAbsenceReadbackFieldSetDigest; + + CanonicalGameplayIssuerBindingLocalRetirementOperation( + CanonicalGameplayIssuerBindingLocalReleaseOperation release, + UUID operationId, + CanonicalGameplayIssuerPartitionMutation physicalMutation, + Status status, + byte[] exactAbsenceReadbackFieldSetBytes, + String exactAbsenceReadbackFieldSetDigest) { + this( + Objects.requireNonNull(release, "release"), + operationId, + release.releasedMemberValue().reservation().partitionId(), + release.releasedMemberValue().reservation().reservationId(), + physicalMutation, + status, + exactAbsenceReadbackFieldSetBytes, + exactAbsenceReadbackFieldSetDigest); + } + + private CanonicalGameplayIssuerBindingLocalRetirementOperation( + CanonicalGameplayIssuerBindingLocalReleaseOperation release, + UUID operationId, + BigInteger partitionId, + UUID reservationId, + CanonicalGameplayIssuerPartitionMutation physicalMutation, + Status status, + byte[] exactAbsenceReadbackFieldSetBytes, + String exactAbsenceReadbackFieldSetDigest) { + this.release = release; + this.operationId = requireNonNil(operationId, "operationId"); + this.partitionId = Objects.requireNonNull(partitionId, "partitionId"); + if (partitionId.signum() < 0) + throw new IllegalArgumentException("partitionId must be nonnegative"); + this.reservationId = requireNonNil(reservationId, "reservationId"); + this.physicalMutation = Objects.requireNonNull(physicalMutation, "physicalMutation"); + this.status = Objects.requireNonNull(status, "status"); + this.exactAbsenceReadbackFieldSetBytes = + exactAbsenceReadbackFieldSetBytes == null + ? null + : exactAbsenceReadbackFieldSetBytes.clone(); + this.exactAbsenceReadbackFieldSetDigest = exactAbsenceReadbackFieldSetDigest; + if (physicalMutation.kind() != CanonicalGameplayIssuerPartitionMutation.Kind.RETIRE + || !physicalMutation.ownerOperationId().equals(operationId) + || !physicalMutation.partitionId().equals(partitionId) + || (release == null && status != Status.RETIRED) + || (release != null + && (release.status() + != CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED + || !release.releasedMemberValue().reservation().partitionId().equals(partitionId) + || !release + .releasedMemberValue() + .reservation() + .reservationId() + .equals(reservationId))) + || (status == Status.PENDING_PHYSICAL_PROOF + && (physicalMutation.status() + != CanonicalGameplayIssuerPartitionMutation.Status.PENDING_PHYSICAL_PROOF + || exactAbsenceReadbackFieldSetBytes != null + || exactAbsenceReadbackFieldSetDigest != null)) + || (status == Status.RETIRED + && (physicalMutation.status() + != CanonicalGameplayIssuerPartitionMutation.Status.COMMITTED + || this.exactAbsenceReadbackFieldSetBytes == null + || this.exactAbsenceReadbackFieldSetBytes.length == 0 + || this.exactAbsenceReadbackFieldSetBytes.length > 17_825_792 + || exactAbsenceReadbackFieldSetDigest == null + || !exactAbsenceReadbackFieldSetDigest.equals( + CanonicalGameplayIssuerMemberV2Codec.sha256( + this.exactAbsenceReadbackFieldSetBytes)) + || !Arrays.equals( + physicalMutation.exactReadbackFieldSetBytes(), + this.exactAbsenceReadbackFieldSetBytes)))) { + throw new IllegalArgumentException( + "Retirement differs from its committed release or revision proof"); + } + Map fields = + status == Status.RETIRED + ? CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( + this.exactAbsenceReadbackFieldSetBytes) + : Map.of(); + String capacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField(reservationId); + byte[] revision = fields.get(CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD); + if (status == Status.RETIRED + && (fields.containsKey(capacityField) + || !Arrays.equals( + revision, + physicalMutation + .successorRevision() + .toString() + .getBytes(StandardCharsets.US_ASCII)))) { + throw new IllegalArgumentException( + "Retirement proof does not establish exact capacity absence"); + } + } + + static CanonicalGameplayIssuerBindingLocalRetirementOperation completedHistorical( + UUID operationId, + BigInteger partitionId, + UUID reservationId, + CanonicalGameplayIssuerPartitionMutation physicalMutation, + byte[] exactAbsenceReadbackFieldSetBytes, + String exactAbsenceReadbackFieldSetDigest) { + return new CanonicalGameplayIssuerBindingLocalRetirementOperation( + null, + operationId, + partitionId, + reservationId, + physicalMutation, + Status.RETIRED, + exactAbsenceReadbackFieldSetBytes, + exactAbsenceReadbackFieldSetDigest); + } + + CanonicalGameplayIssuerBindingLocalReleaseOperation release() { + return release; + } + + UUID operationId() { + return operationId; + } + + BigInteger partitionId() { + return partitionId; + } + + UUID reservationId() { + return reservationId; + } + + CanonicalGameplayIssuerPartitionMutation physicalMutation() { + return physicalMutation; + } + + Status status() { + return status; + } + + byte[] exactAbsenceReadbackFieldSetBytes() { + return exactAbsenceReadbackFieldSetBytes == null + ? null + : exactAbsenceReadbackFieldSetBytes.clone(); + } + + String exactAbsenceReadbackFieldSetDigest() { + return exactAbsenceReadbackFieldSetDigest; + } + + private static UUID requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException(name + " must not be nil"); + return value; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java new file mode 100644 index 0000000000..72fd51364a --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java @@ -0,0 +1,975 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** SQL owner for original-operation physical retirement after a committed issuer release. */ +final class CanonicalGameplayIssuerBindingLocalRetirementOperationRepository { + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String RETIREMENT = "game_session_canonical_issuer_binding_local_retirement"; + private static final String RELEASE = + "game_session_canonical_issuer_binding_local_release_operation"; + private static final String LOCAL_OPERATION = + "game_session_canonical_issuer_binding_local_operation"; + private static final String RESERVATION = "game_session_canonical_issuer_partition_reservation"; + private static final String INVENTORY = "game_session_canonical_gameplay_binding_inventory"; + private static final String ISSUER_OBLIGATION = + "game_session_canonical_binding_issuer_index_obligation"; + private static final String INVENTORY_CLOCK = "game_session_canonical_binding_inventory_clock"; + + private final DSLContext dsl; + private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentIssuerStateSource; + private final CanonicalGameplayIssuerBindingLocalReleaseOperationRepository releaseRepository; + + CanonicalGameplayIssuerBindingLocalRetirementOperationRepository( + DSLContext dsl, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentIssuerStateSource) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.currentIssuerStateSource = + Objects.requireNonNull(currentIssuerStateSource, "currentIssuerStateSource"); + this.releaseRepository = + new CanonicalGameplayIssuerBindingLocalReleaseOperationRepository( + dsl, currentIssuerStateSource); + } + + /** Creates or exactly resumes retirement only from the committed original release receipt. */ + CanonicalGameplayIssuerBindingLocalRetirementOperation prepareOrResume(UUID transitionId) { + Objects.requireNonNull(transitionId, "transitionId"); + requireNoAmbientTransaction(); + CanonicalGameplayIssuerBindingLocalRetirementOperation completed = + readCompletedRetirement(transitionId); + if (completed != null) return completed; + CanonicalGameplayIssuerBindingLocalReleaseOperation release = + releaseRepository.prepareOrResume(transitionId); + if (release.status() != CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED) { + throw conflict("Physical retirement requires a committed original RELEASED receipt"); + } + var before = readCurrentIssuerState(); + requireSourceMatchesRelease(release.abortSource(), release); + CanonicalGameplayIssuerBindingLocalRetirementOperation prepared = + dsl.transactionResult( + configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + CanonicalGameplayAdmissionAbortSource currentSource = + CanonicalGameplayBindingInventoryRepository + .readFirstNewAdmissionAbortSourceInTransaction( + transaction, transitionId, true); + requireSameReleaseSource(release.abortSource(), currentSource, release); + requireExactCommittedReleaseRow(transaction, release); + protectCurrentReferences(transaction, release); + BigInteger partitionId = release.releasedMemberValue().reservation().partitionId(); + Record existing = + transaction.fetchOne( + "SELECT * FROM " + RETIREMENT + " WHERE release_operation_id = ? FOR UPDATE", + release.operationId()); + if (existing != null) return readOperation(transaction, existing, release); + + CanonicalGameplayIssuerPartitionMutationRepository.PartitionMutationHead head = + CanonicalGameplayIssuerPartitionMutationRepository.readHeadInTransaction( + transaction, partitionId); + if (head.pendingMutationId() != null) { + throw conflict("Another same-partition mutation is unresolved before retirement"); + } + UUID retirementId = freshNonNilUuid(); + byte[] intendedChange = encodeRetirementIntent(retirementId, release); + CanonicalGameplayIssuerPartitionMutation mutation = + CanonicalGameplayIssuerPartitionMutationRepository.prepareInTransaction( + transaction, + CanonicalGameplayIssuerPartitionMutation.Kind.RETIRE, + retirementId, + partitionId, + intendedChange); + insertRetirement(transaction, retirementId, release, mutation); + Record saved = + transaction.fetchOne( + "SELECT * FROM " + + RETIREMENT + + " WHERE retirement_operation_id = ? FOR UPDATE", + retirementId); + if (saved == null) + throw conflict("Pending issuer retirement intent was not retained"); + return readOperation(transaction, saved, release); + }); + requireSameCurrentIssuerState( + before, readCurrentIssuerState(), prepared.release().originalOperation().anchor()); + CanonicalGameplayIssuerBindingLocalReleaseOperation after = + releaseRepository.prepareOrResume(transitionId); + requireSameReleaseOperation(release, after); + return prepared; + } + + /** Returns only immutable completed history; it does not depend on later mutable V29 rows. */ + private CanonicalGameplayIssuerBindingLocalRetirementOperation readCompletedRetirement( + UUID transitionId) { + requireNoAmbientTransaction(); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + Record retirement = + transaction.fetchOne( + "SELECT * FROM " + + RETIREMENT + + " WHERE issuer_id = ? AND transition_id = ? AND status = 'RETIRED'", + ISSUER, + transitionId); + if (retirement == null) return null; + return readCompletedRetirementInTransaction(transaction, retirement); + }); + } + + private static CanonicalGameplayIssuerBindingLocalRetirementOperation + readCompletedRetirementInTransaction(DSLContext transaction, Record retirement) { + UUID operationId = uuid(retirement, "retirement_operation_id"); + BigInteger partitionId = nonnegative(retirement, "partition_id"); + UUID reservationId = uuid(retirement, "reservation_id"); + UUID releaseId = uuid(retirement, "release_operation_id"); + UUID originalId = uuid(retirement, "original_local_operation_id"); + UUID transitionId = uuid(retirement, "transition_id"); + byte[] bindingRef = bytes(retirement, "binding_ref"); + byte[] originalBytes = bytes(retirement, "original_member_value_bytes"); + byte[] releasedBytes = bytes(retirement, "released_member_value_bytes"); + byte[] absenceBytes = bytes(retirement, "exact_absence_readback_field_set_bytes"); + String absenceDigest = text(retirement, "exact_absence_readback_field_set_digest"); + if (!ISSUER.equals(text(retirement, "issuer_id")) + || !text(retirement, "status").equals("RETIRED") + || !CanonicalGameplayIssuerMemberV2Codec.sha256(originalBytes) + .equals(text(retirement, "original_member_value_digest")) + || !CanonicalGameplayIssuerMemberV2Codec.sha256(releasedBytes) + .equals(text(retirement, "released_member_value_digest")) + || !CanonicalGameplayIssuerMemberV2Codec.sha256(absenceBytes).equals(absenceDigest)) { + throw conflict("Committed retirement history has a changed exact byte receipt"); + } + + CanonicalGameplayIssuerMemberV2Value originalMember; + CanonicalGameplayIssuerMemberV2Value releasedMember; + try { + originalMember = CanonicalGameplayIssuerMemberV2Codec.decode(originalBytes); + releasedMember = CanonicalGameplayIssuerMemberV2Codec.decode(releasedBytes); + } catch (RuntimeException malformed) { + throw conflict("Committed retirement release tuple is not canonical schema v2"); + } + Record release = + transaction.fetchOne("SELECT * FROM " + RELEASE + " WHERE operation_id = ?", releaseId); + Record original = + transaction.fetchOne( + "SELECT * FROM " + LOCAL_OPERATION + " WHERE operation_id = ?", originalId); + if (release == null + || original == null + || !ISSUER.equals(text(release, "issuer_id")) + || !"RELEASED".equals(text(release, "status")) + || !uuid(release, "original_local_operation_id").equals(originalId) + || !uuid(release, "transition_id").equals(transitionId) + || !uuid(release, "reservation_id").equals(reservationId) + || !nonnegative(release, "partition_id").equals(partitionId) + || !Arrays.equals(bytes(release, "binding_ref"), bindingRef) + || !uuid(release, "original_reservation_fence") + .equals(uuid(retirement, "original_reservation_fence")) + || !uuid(release, "original_issuer_coverage_operation_id") + .equals(uuid(retirement, "original_issuer_coverage_operation_id")) + || !positive(release, "original_issuer_coverage_operation_fence") + .equals(positive(retirement, "original_issuer_coverage_operation_fence")) + || !positive(release, "original_coverage_fence") + .equals(positive(retirement, "original_coverage_fence")) + || !positive(release, "original_inventory_snapshot_revision") + .equals(positive(retirement, "original_inventory_snapshot_revision")) + || !positive(release, "original_reservation_inventory_revision") + .equals(positive(retirement, "original_reservation_inventory_revision")) + || !uuid(release, "anchor_issuer_coverage_operation_id") + .equals(uuid(retirement, "anchor_issuer_coverage_operation_id")) + || !positive(release, "anchor_operation_fence") + .equals(positive(retirement, "anchor_operation_fence")) + || !positive(release, "anchor_coverage_fence") + .equals(positive(retirement, "anchor_coverage_fence")) + || !positive(release, "anchor_inventory_snapshot_revision") + .equals(positive(retirement, "anchor_inventory_snapshot_revision")) + || !Arrays.equals(bytes(release, "original_member_value_bytes"), originalBytes) + || !Arrays.equals(bytes(release, "released_member_value_bytes"), releasedBytes) + || !text(release, "original_member_value_digest") + .equals(CanonicalGameplayIssuerMemberV2Codec.sha256(originalBytes)) + || !text(release, "released_member_value_digest") + .equals(CanonicalGameplayIssuerMemberV2Codec.sha256(releasedBytes)) + || !positive(release, "source_inventory_revision") + .equals(positive(retirement, "release_source_inventory_revision")) + || !positive(release, "completion_inventory_revision") + .equals(positive(retirement, "release_completion_inventory_revision")) + || !text(release, "physical_readback_field_set_digest") + .equals( + CanonicalGameplayIssuerMemberV2Codec.sha256(readReleaseReceiptFieldSet(release))) + || !uuid(original, "operation_id").equals(originalId) + || !uuid(original, "reservation_id").equals(reservationId) + || !uuid(original, "transition_id").equals(transitionId) + || !Arrays.equals(bytes(original, "binding_ref"), bindingRef) + || !positive(original, "binding_generation").equals(originalMember.bindingGeneration()) + || !positive(original, "operation_fence") + .equals(originalMember.memberOperation().operationFence()) + || !positive(original, "local_member_generation") + .equals(originalMember.memberOperation().coverageGeneration()) + || !originalMember.memberOperation().operationId().equals(originalId) + || !originalMember.reservation().transitionId().equals(transitionId) + || !Arrays.equals(bytes(original, "member_value_bytes"), originalBytes) + || !text(original, "member_value_digest") + .equals(CanonicalGameplayIssuerMemberV2Codec.sha256(originalBytes))) { + throw conflict("Committed retirement no longer links to its exact immutable release source"); + } + CanonicalIssuerPartitionReservation originalReservation = originalMember.reservation(); + var originalAnchor = originalMember.anchor(); + BigInteger releaseSourceRevision = positive(retirement, "release_source_inventory_revision"); + CanonicalGameplayIssuerMemberV2Value expectedReleasedMember = + new CanonicalGameplayIssuerMemberV2Value( + originalMember.owner(), + originalMember.bindingGeneration(), + new CanonicalIssuerPartitionReservation( + originalReservation.reservationId(), + originalReservation.owner(), + originalReservation.bindingGeneration(), + originalReservation.transitionId(), + originalReservation.partitionId(), + CanonicalIssuerPartitionReservation.Lifecycle.RELEASED, + originalReservation.reservationFence(), + originalReservation.issuerCoverageOperationId(), + originalReservation.issuerCoverageOperationFence(), + originalReservation.coverageFence(), + originalReservation.inventorySnapshotRevision(), + releaseSourceRevision), + originalAnchor, + new CanonicalGameplayIssuerMemberV2Value.LocalMemberOperation( + releaseId, + positive(release, "release_operation_fence"), + positive(release, "release_local_member_generation")), + originalMember.issuerControlEpoch(), + originalMember.layoutDescriptor(), + originalMember.sourceCheckpoint(), + originalMember.incarnation()); + if (originalMember.reservation().lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RESERVED + || releasedMember.reservation().lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED + || !originalReservation + .reservationFence() + .equals(uuid(retirement, "original_reservation_fence")) + || !originalReservation + .issuerCoverageOperationId() + .equals(uuid(retirement, "original_issuer_coverage_operation_id")) + || !originalReservation + .issuerCoverageOperationFence() + .equals(positive(retirement, "original_issuer_coverage_operation_fence")) + || !originalReservation + .coverageFence() + .equals(positive(retirement, "original_coverage_fence")) + || !originalReservation + .inventorySnapshotRevision() + .equals(positive(retirement, "original_inventory_snapshot_revision")) + || !originalReservation + .inventoryRevision() + .equals(positive(retirement, "original_reservation_inventory_revision")) + || !originalAnchor + .issuerCoverageOperationId() + .equals(uuid(retirement, "anchor_issuer_coverage_operation_id")) + || !originalAnchor.operationFence().equals(positive(retirement, "anchor_operation_fence")) + || !originalAnchor.coverageFence().equals(positive(retirement, "anchor_coverage_fence")) + || !originalAnchor + .issuerInventorySnapshotRevision() + .equals(positive(retirement, "anchor_inventory_snapshot_revision")) + || !originalMember.reservation().reservationId().equals(reservationId) + || !releasedMember.reservation().reservationId().equals(reservationId) + || !releasedMember.reservation().partitionId().equals(partitionId) + || !Arrays.equals(releasedMember.owner().bindingRef().bytes(), bindingRef) + || !releasedMember.memberOperation().operationId().equals(releaseId) + || !releasedMember.equals(expectedReleasedMember) + || !Arrays.equals( + releasedBytes, CanonicalGameplayIssuerMemberV2Codec.encode(expectedReleasedMember))) { + throw conflict("Committed retirement does not retain the original RELEASED member value"); + } + + byte[] expectedRetirementIntent = + CanonicalGameplayIssuerPartitionMutationRepository.encodeIntendedChange( + CanonicalGameplayIssuerPartitionMutation.Kind.RETIRE, + operationId, + partitionId, + releaseId.toString().getBytes(StandardCharsets.US_ASCII), + originalId.toString().getBytes(StandardCharsets.US_ASCII), + transitionId.toString().getBytes(StandardCharsets.US_ASCII), + reservationId.toString().getBytes(StandardCharsets.US_ASCII), + bindingRef, + releaseSourceRevision.toString().getBytes(StandardCharsets.US_ASCII), + positive(retirement, "release_completion_inventory_revision") + .toString() + .getBytes(StandardCharsets.US_ASCII), + originalBytes, + releasedBytes); + if (!Arrays.equals(expectedRetirementIntent, bytes(retirement, "exact_intended_change_bytes")) + || !text(retirement, "exact_intended_change_digest") + .equals(CanonicalGameplayIssuerMemberV2Codec.sha256(expectedRetirementIntent))) { + throw conflict("Committed retirement intent differs from its exact immutable release tuple"); + } + + CanonicalGameplayIssuerPartitionMutation releaseMutation = + CanonicalGameplayIssuerPartitionMutationRepository.readInTransaction( + transaction, + CanonicalGameplayIssuerPartitionMutation.Kind.RELEASE, + releaseId, + partitionId); + byte[] releaseReadback = readReleaseReceiptFieldSet(release); + byte[] releaseMutationIntent = + CanonicalGameplayIssuerPartitionMutationRepository.encodeIntendedChange( + CanonicalGameplayIssuerPartitionMutation.Kind.RELEASE, + releaseId, + partitionId, + originalId.toString().getBytes(StandardCharsets.US_ASCII), + reservationId.toString().getBytes(StandardCharsets.US_ASCII), + bindingRef, + originalBytes, + releasedBytes, + positive(retirement, "release_source_inventory_revision") + .toString() + .getBytes(StandardCharsets.US_ASCII)); + if (releaseMutation.status() != CanonicalGameplayIssuerPartitionMutation.Status.COMMITTED + || !Arrays.equals(releaseMutation.exactIntendedChangeBytes(), releaseMutationIntent) + || !Arrays.equals(releaseMutation.exactReadbackFieldSetBytes(), releaseReadback)) { + throw conflict("Committed retirement lost its original physical release proof"); + } + Map releaseFields = + CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet(releaseReadback); + String releasedCapacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField(reservationId); + String releasedBindingField = new String(bindingRef, StandardCharsets.UTF_8); + if (!Arrays.equals( + releaseFields.get(CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD), + releaseMutation.successorRevision().toString().getBytes(StandardCharsets.US_ASCII)) + || !Arrays.equals(releaseFields.get(releasedCapacityField), releasedBytes) + || releaseFields.containsKey(releasedBindingField)) { + throw conflict("Original committed release receipt lacks its exact RELEASED physical proof"); + } + + CanonicalGameplayIssuerPartitionMutation mutation = + CanonicalGameplayIssuerPartitionMutationRepository.readInTransaction( + transaction, + CanonicalGameplayIssuerPartitionMutation.Kind.RETIRE, + operationId, + partitionId); + if (mutation.status() != CanonicalGameplayIssuerPartitionMutation.Status.COMMITTED + || !uuid(retirement, "physical_mutation_id").equals(mutation.mutationId()) + || !mutation.expectedRevision().equals(uuid(retirement, "expected_revision")) + || !mutation.successorRevision().equals(uuid(retirement, "successor_revision")) + || !Arrays.equals( + mutation.exactIntendedChangeBytes(), bytes(retirement, "exact_intended_change_bytes")) + || !mutation + .exactIntendedChangeDigest() + .equals(text(retirement, "exact_intended_change_digest")) + || !Arrays.equals(mutation.exactReadbackFieldSetBytes(), absenceBytes)) { + throw conflict("Committed retirement lacks its exact successor-fence and absence proof"); + } + Map fields = + CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet(absenceBytes); + String targetCapacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField(reservationId); + byte[] revision = fields.get(CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD); + if (fields.containsKey(targetCapacityField) + || !Arrays.equals( + revision, + mutation.successorRevision().toString().getBytes(StandardCharsets.US_ASCII))) { + throw conflict("Committed retirement receipt does not prove exact field absence and fence"); + } + return CanonicalGameplayIssuerBindingLocalRetirementOperation.completedHistorical( + operationId, partitionId, reservationId, mutation, absenceBytes, absenceDigest); + } + + private static byte[] readReleaseReceiptFieldSet(Record release) { + return bytes(release, "physical_readback_field_set_bytes"); + } + + /** Commits exact absence and fence evidence with its physical-mutation receipt. */ + CanonicalGameplayIssuerBindingLocalRetirementOperation completeWithReadback( + CanonicalGameplayIssuerBindingLocalRetirementOperation expected, + CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.Readback readback) { + Objects.requireNonNull(expected, "expected"); + Objects.requireNonNull(readback, "readback"); + requireNoAmbientTransaction(); + if (!expected.operationId().equals(readback.operationId())) { + throw conflict("Issuer retirement readback belongs to a different original operation"); + } + byte[] exactBytes = readback.exactAbsenceReadbackFieldSetBytes(); + String exactDigest = CanonicalGameplayIssuerMemberV2Codec.sha256(exactBytes); + verifyExactAbsence(expected, exactBytes, exactDigest); + if (expected.status() + == CanonicalGameplayIssuerBindingLocalRetirementOperation.Status.RETIRED) { + if (!Arrays.equals(expected.exactAbsenceReadbackFieldSetBytes(), exactBytes)) { + throw conflict("Completed issuer retirement retry changed its original absence readback"); + } + return expected; + } + if (expected.release() == null) { + throw conflict("Pending issuer retirement lacks its current-source release context"); + } + var before = readCurrentIssuerState(); + CanonicalGameplayIssuerBindingLocalRetirementOperation completed = + dsl.transactionResult( + configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + CanonicalGameplayIssuerBindingLocalReleaseOperation release = expected.release(); + CanonicalGameplayAdmissionAbortSource source = + CanonicalGameplayBindingInventoryRepository + .readFirstNewAdmissionAbortSourceInTransaction( + transaction, release.abortSource().transition().transitionId(), true); + requireSameReleaseSource(release.abortSource(), source, release); + requireExactCommittedReleaseRow(transaction, release); + protectCurrentReferences(transaction, release); + Record row = + transaction.fetchOne( + "SELECT * FROM " + + RETIREMENT + + " WHERE retirement_operation_id = ? FOR UPDATE", + expected.operationId()); + if (row == null) throw conflict("Pending issuer retirement disappeared"); + CanonicalGameplayIssuerBindingLocalRetirementOperation current = + readOperation(transaction, row, release); + requireSameRetirement(expected, current); + if (current.status() + == CanonicalGameplayIssuerBindingLocalRetirementOperation.Status.RETIRED) { + verifyExactAbsence(current, exactBytes, exactDigest); + CanonicalGameplayIssuerPartitionMutationRepository.completeInTransaction( + transaction, current.physicalMutation(), exactBytes); + return current; + } + CanonicalGameplayIssuerPartitionMutationRepository.completeInTransaction( + transaction, current.physicalMutation(), exactBytes); + int updated = + transaction.execute( + "UPDATE " + + RETIREMENT + + " SET status = 'RETIRED', exact_absence_readback_field_set_bytes = ?" + + ", exact_absence_readback_field_set_digest = ?, completed_at = CURRENT_TIMESTAMP" + + " WHERE retirement_operation_id = ? AND status = 'PENDING_PHYSICAL_PROOF'" + + " AND physical_mutation_id = ? AND expected_revision = ? AND successor_revision = ?", + exactBytes, + exactDigest, + current.operationId(), + current.physicalMutation().mutationId(), + current.physicalMutation().expectedRevision(), + current.physicalMutation().successorRevision()); + if (updated != 1) throw conflict("Issuer retirement proof compare-and-set refused"); + Record saved = + transaction.fetchOne( + "SELECT * FROM " + RETIREMENT + " WHERE retirement_operation_id = ?", + current.operationId()); + if (saved == null) throw conflict("Committed issuer retirement proof is unreadable"); + return readOperation(transaction, saved, release); + }); + requireSameCurrentIssuerState( + before, readCurrentIssuerState(), completed.release().originalOperation().anchor()); + return completed; + } + + private static void protectCurrentReferences( + DSLContext transaction, CanonicalGameplayIssuerBindingLocalReleaseOperation release) { + var original = release.originalOperation(); + byte[] bindingRef = release.releasedMemberValue().owner().bindingRef().bytes(); + UUID reservationId = release.releasedMemberValue().reservation().reservationId(); + UUID operationId = original.operationId(); + if (count( + transaction, + "SELECT COUNT(*) FROM " + + LOCAL_OPERATION + + " operation WHERE operation.issuer_id = ?" + + " AND operation.binding_ref = ? AND operation.operation_id <> ?" + + " AND NOT EXISTS (SELECT 1 FROM " + + RETIREMENT + + " retired" + + " WHERE retired.original_local_operation_id = operation.operation_id" + + " AND retired.status = 'RETIRED')", + ISSUER, + bindingRef, + operationId) + != 0 + || count( + transaction, + "SELECT COUNT(*) FROM " + + RESERVATION + + " reservation WHERE reservation.issuer_id = ?" + + " AND reservation.binding_ref = ? AND reservation.reservation_id <> ?" + + " AND NOT EXISTS (SELECT 1 FROM " + + RETIREMENT + + " retired" + + " WHERE retired.reservation_id = reservation.reservation_id" + + " AND retired.status = 'RETIRED')", + ISSUER, + bindingRef, + reservationId) + != 0) { + throw conflict("A newer or conflicting SQL issuer reference protects this local member"); + } + Record reservation = + transaction.fetchOne( + "SELECT * FROM " + RESERVATION + " WHERE reservation_id = ? FOR UPDATE", reservationId); + Record candidate = + transaction.fetchOne( + "SELECT * FROM " + INVENTORY + " WHERE binding_ref = ? FOR UPDATE", bindingRef); + Record obligation = + transaction.fetchOne( + "SELECT * FROM " + + ISSUER_OBLIGATION + + " WHERE transition_id = ? AND binding_ref = ? FOR UPDATE", + release.abortSource().transition().transitionId(), + bindingRef); + if (reservation == null + || !"RELEASED".equals(text(reservation, "lifecycle")) + || !number(reservation, "inventory_revision").equals(release.completionInventoryRevision()) + || candidate == null + || !"TERMINAL_UNRESOLVED".equals(text(candidate, "lifecycle")) + || !number(candidate, "inventory_revision").equals(release.completionInventoryRevision()) + || !uuid(candidate, "transition_id") + .equals(release.abortSource().transition().transitionId()) + || obligation == null + || !"RELEASED".equals(text(obligation, "status")) + || !uuid(obligation, "local_release_operation_id").equals(release.operationId()) + || !number(obligation, "inventory_revision") + .equals(release.completionInventoryRevision())) { + throw conflict("Current SQL issuer references no longer match the committed release"); + } + } + + private static void requireExactCommittedReleaseRow( + DSLContext transaction, CanonicalGameplayIssuerBindingLocalReleaseOperation release) { + Record row = + transaction.fetchOne( + "SELECT * FROM " + RELEASE + " WHERE operation_id = ? FOR UPDATE", + release.operationId()); + if (row == null + || !ISSUER.equals(text(row, "issuer_id")) + || !"RELEASED".equals(text(row, "status")) + || !uuid(row, "original_local_operation_id").equals(release.originalOperationId()) + || !positive(row, "source_inventory_revision").equals(release.sourceInventoryRevision()) + || !positive(row, "completion_inventory_revision") + .equals(release.completionInventoryRevision()) + || !Arrays.equals( + bytes(row, "original_member_value_bytes"), release.exactOriginalMemberValueBytes()) + || !Arrays.equals( + bytes(row, "released_member_value_bytes"), release.exactReleasedMemberValueBytes()) + || !text(row, "physical_readback_field_set_digest").equals(release.physicalReadbackDigest()) + || !Arrays.equals( + bytes(row, "physical_readback_field_set_bytes"), + release.exactPhysicalReadbackFieldSetBytes())) { + throw conflict("The original committed release receipt changed before retirement"); + } + } + + private static CanonicalGameplayIssuerBindingLocalRetirementOperation readOperation( + DSLContext transaction, + Record row, + CanonicalGameplayIssuerBindingLocalReleaseOperation release) { + UUID operationId = uuid(row, "retirement_operation_id"); + UUID mutationId = uuid(row, "physical_mutation_id"); + CanonicalGameplayIssuerPartitionMutation mutation = + CanonicalGameplayIssuerPartitionMutationRepository.readInTransaction( + transaction, + CanonicalGameplayIssuerPartitionMutation.Kind.RETIRE, + operationId, + release.releasedMemberValue().reservation().partitionId()); + CanonicalGameplayIssuerPartitionMutationRepository.PartitionMutationHead head = + CanonicalGameplayIssuerPartitionMutationRepository.readHeadInTransaction( + transaction, release.releasedMemberValue().reservation().partitionId()); + if ((mutation.status() == CanonicalGameplayIssuerPartitionMutation.Status.PENDING_PHYSICAL_PROOF + && (!mutation.mutationId().equals(head.pendingMutationId()) + || !mutation.expectedRevision().equals(head.currentRevision()))) + || (mutation.status() == CanonicalGameplayIssuerPartitionMutation.Status.COMMITTED + && mutation.mutationId().equals(head.pendingMutationId()))) { + throw conflict("Original retirement does not match its current partition-head custody"); + } + byte[] intended = encodeRetirementIntent(operationId, release); + var original = release.originalOperation(); + var reservation = original.reservation(); + var anchor = original.anchor(); + if (!mutationId.equals(mutation.mutationId()) + || !Arrays.equals(intended, mutation.exactIntendedChangeBytes()) + || !ISSUER.equals(text(row, "issuer_id")) + || !nonnegative(row, "partition_id") + .equals(release.releasedMemberValue().reservation().partitionId()) + || !uuid(row, "release_operation_id").equals(release.operationId()) + || !uuid(row, "original_local_operation_id").equals(release.originalOperationId()) + || !uuid(row, "transition_id").equals(release.abortSource().transition().transitionId()) + || !uuid(row, "reservation_id") + .equals(release.releasedMemberValue().reservation().reservationId()) + || !Arrays.equals( + bytes(row, "binding_ref"), release.releasedMemberValue().owner().bindingRef().bytes()) + || !uuid(row, "original_reservation_fence").equals(reservation.reservationFence()) + || !uuid(row, "original_issuer_coverage_operation_id") + .equals(reservation.issuerCoverageOperationId()) + || !positive(row, "original_issuer_coverage_operation_fence") + .equals(reservation.issuerCoverageOperationFence()) + || !positive(row, "original_coverage_fence").equals(reservation.coverageFence()) + || !positive(row, "original_inventory_snapshot_revision") + .equals(reservation.inventorySnapshotRevision()) + || !positive(row, "original_reservation_inventory_revision") + .equals(reservation.inventoryRevision()) + || !uuid(row, "anchor_issuer_coverage_operation_id") + .equals(anchor.issuerCoverageOperationId()) + || !positive(row, "anchor_operation_fence").equals(anchor.operationFence()) + || !positive(row, "anchor_coverage_fence").equals(anchor.coverageFence()) + || !positive(row, "anchor_inventory_snapshot_revision") + .equals(anchor.issuerInventorySnapshotRevision()) + || !positive(row, "release_source_inventory_revision") + .equals(release.sourceInventoryRevision()) + || !positive(row, "release_completion_inventory_revision") + .equals(release.completionInventoryRevision()) + || !Arrays.equals( + bytes(row, "original_member_value_bytes"), release.exactOriginalMemberValueBytes()) + || !Arrays.equals( + bytes(row, "released_member_value_bytes"), release.exactReleasedMemberValueBytes()) + || !text(row, "original_member_value_digest") + .equals( + CanonicalGameplayIssuerMemberV2Codec.sha256( + release.exactOriginalMemberValueBytes())) + || !text(row, "released_member_value_digest") + .equals( + CanonicalGameplayIssuerMemberV2Codec.sha256( + release.exactReleasedMemberValueBytes())) + || !uuid(row, "expected_revision").equals(mutation.expectedRevision()) + || !uuid(row, "successor_revision").equals(mutation.successorRevision())) { + throw conflict("Stored issuer retirement differs from the exact release or revision tuple"); + } + CanonicalGameplayIssuerBindingLocalRetirementOperation.Status status; + try { + status = + CanonicalGameplayIssuerBindingLocalRetirementOperation.Status.valueOf( + text(row, "status")); + } catch (RuntimeException malformed) { + throw conflict("Stored issuer retirement status is malformed"); + } + byte[] absence = optionalBytes(row, "exact_absence_readback_field_set_bytes"); + String digest = row.get("exact_absence_readback_field_set_digest", String.class); + if ((status + == CanonicalGameplayIssuerBindingLocalRetirementOperation.Status + .PENDING_PHYSICAL_PROOF + && (absence != null || digest != null || row.get("completed_at") != null)) + || (status == CanonicalGameplayIssuerBindingLocalRetirementOperation.Status.RETIRED + && (absence == null + || digest == null + || !digest.equals(CanonicalGameplayIssuerMemberV2Codec.sha256(absence)) + || row.get("completed_at") == null))) { + throw conflict("Stored issuer retirement lacks its exact bounded absence phase"); + } + try { + return new CanonicalGameplayIssuerBindingLocalRetirementOperation( + release, operationId, mutation, status, absence, digest); + } catch (RuntimeException malformed) { + throw conflict("Stored issuer retirement proof is malformed"); + } + } + + private static void insertRetirement( + DSLContext transaction, + UUID operationId, + CanonicalGameplayIssuerBindingLocalReleaseOperation release, + CanonicalGameplayIssuerPartitionMutation mutation) { + var original = release.originalOperation(); + var released = release.releasedMemberValue(); + var reservation = original.reservation(); + var anchor = original.anchor(); + byte[] originalBytes = release.exactOriginalMemberValueBytes(); + byte[] releasedBytes = release.exactReleasedMemberValueBytes(); + transaction.execute( + "INSERT INTO " + + RETIREMENT + + " (retirement_operation_id, issuer_id, partition_id, release_operation_id, physical_mutation_id," + + " original_local_operation_id, transition_id, reservation_id, binding_ref, original_reservation_fence," + + " original_issuer_coverage_operation_id, original_issuer_coverage_operation_fence, original_coverage_fence," + + " original_inventory_snapshot_revision, original_reservation_inventory_revision," + + " anchor_issuer_coverage_operation_id, anchor_operation_fence, anchor_coverage_fence," + + " anchor_inventory_snapshot_revision, release_source_inventory_revision, release_completion_inventory_revision," + + " original_member_value_bytes, original_member_value_digest, released_member_value_bytes, released_member_value_digest," + + " expected_revision, successor_revision, exact_intended_change_bytes, exact_intended_change_digest, status)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING_PHYSICAL_PROOF')", + operationId, + ISSUER, + decimal(released.reservation().partitionId()), + release.operationId(), + mutation.mutationId(), + original.operationId(), + original.request().transitionId(), + reservation.reservationId(), + released.owner().bindingRef().bytes(), + reservation.reservationFence(), + reservation.issuerCoverageOperationId(), + decimal(reservation.issuerCoverageOperationFence()), + decimal(reservation.coverageFence()), + decimal(reservation.inventorySnapshotRevision()), + decimal(reservation.inventoryRevision()), + anchor.issuerCoverageOperationId(), + decimal(anchor.operationFence()), + decimal(anchor.coverageFence()), + decimal(anchor.issuerInventorySnapshotRevision()), + decimal(release.sourceInventoryRevision()), + decimal(release.completionInventoryRevision()), + originalBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(originalBytes), + releasedBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(releasedBytes), + mutation.expectedRevision(), + mutation.successorRevision(), + mutation.exactIntendedChangeBytes(), + mutation.exactIntendedChangeDigest()); + } + + private static byte[] encodeRetirementIntent( + UUID retirementOperationId, CanonicalGameplayIssuerBindingLocalReleaseOperation release) { + return CanonicalGameplayIssuerPartitionMutationRepository.encodeIntendedChange( + CanonicalGameplayIssuerPartitionMutation.Kind.RETIRE, + retirementOperationId, + release.releasedMemberValue().reservation().partitionId(), + release.operationId().toString().getBytes(StandardCharsets.US_ASCII), + release.originalOperationId().toString().getBytes(StandardCharsets.US_ASCII), + release + .abortSource() + .transition() + .transitionId() + .toString() + .getBytes(StandardCharsets.US_ASCII), + release + .releasedMemberValue() + .reservation() + .reservationId() + .toString() + .getBytes(StandardCharsets.US_ASCII), + release.releasedMemberValue().owner().bindingRef().bytes(), + release.sourceInventoryRevision().toString().getBytes(StandardCharsets.US_ASCII), + release.completionInventoryRevision().toString().getBytes(StandardCharsets.US_ASCII), + release.exactOriginalMemberValueBytes(), + release.exactReleasedMemberValueBytes()); + } + + private static void verifyExactAbsence( + CanonicalGameplayIssuerBindingLocalRetirementOperation operation, + byte[] exactBytes, + String digest) { + if (exactBytes == null + || exactBytes.length == 0 + || exactBytes.length > 17_825_792 + || !digest.equals(CanonicalGameplayIssuerMemberV2Codec.sha256(exactBytes))) { + throw conflict("Issuer retirement readback is missing, oversized, or has a wrong digest"); + } + Map fields = + CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet(exactBytes); + String capacity = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + operation.reservationId()); + byte[] revision = fields.get(CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD); + if (fields.containsKey(capacity) + || !Arrays.equals( + revision, + operation + .physicalMutation() + .successorRevision() + .toString() + .getBytes(StandardCharsets.US_ASCII))) { + throw conflict("Issuer retirement readback does not prove exact capacity-field absence"); + } + } + + private static void requireSameRetirement( + CanonicalGameplayIssuerBindingLocalRetirementOperation expected, + CanonicalGameplayIssuerBindingLocalRetirementOperation actual) { + if (!expected.operationId().equals(actual.operationId()) + || !expected.physicalMutation().mutationId().equals(actual.physicalMutation().mutationId()) + || !expected + .physicalMutation() + .expectedRevision() + .equals(actual.physicalMutation().expectedRevision()) + || !expected + .physicalMutation() + .successorRevision() + .equals(actual.physicalMutation().successorRevision()) + || !Arrays.equals( + expected.physicalMutation().exactIntendedChangeBytes(), + actual.physicalMutation().exactIntendedChangeBytes())) { + throw conflict("Original issuer retirement changed across the physical proof boundary"); + } + } + + private static void requireSameReleaseOperation( + CanonicalGameplayIssuerBindingLocalReleaseOperation expected, + CanonicalGameplayIssuerBindingLocalReleaseOperation actual) { + if (!expected.operationId().equals(actual.operationId()) + || expected.status() != actual.status() + || !Arrays.equals( + expected.exactOriginalMemberValueBytes(), actual.exactOriginalMemberValueBytes()) + || !Arrays.equals( + expected.exactReleasedMemberValueBytes(), actual.exactReleasedMemberValueBytes()) + || !Arrays.equals( + expected.exactPhysicalReadbackFieldSetBytes(), + actual.exactPhysicalReadbackFieldSetBytes())) { + throw conflict("Committed release changed while preparing physical retirement"); + } + } + + private static void requireSameReleaseSource( + CanonicalGameplayAdmissionAbortSource expected, + CanonicalGameplayAdmissionAbortSource actual, + CanonicalGameplayIssuerBindingLocalReleaseOperation release) { + if (!expected.transition().equals(actual.transition()) + || !expected.candidate().equals(actual.candidate()) + || !expected.reservation().equals(actual.reservation()) + || !expected.originalDecision().requestId().equals(actual.originalDecision().requestId()) + || !expected.originalDecision().leaseId().equals(actual.originalDecision().leaseId()) + || !expected + .originalDecision() + .leaseEvidenceJson() + .equals(actual.originalDecision().leaseEvidenceJson()) + || !expected + .originalDecision() + .targetEvidence() + .equals(actual.originalDecision().targetEvidence()) + || !expected.isAccountAborted() + || !actual.isAccountAborted() + || !expected.transition().transitionId().equals(actual.transition().transitionId()) + || actual.transition().status() + != net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot + .Status.ABORTED + || !actual.transition().inventoryRevision().equals(release.completionInventoryRevision()) + || !actual.transition().bindingRef().equals(expected.transition().bindingRef()) + || !actual + .transition() + .bindingGeneration() + .equals(expected.transition().bindingGeneration()) + || !actual.orphanCleanupId().equals(expected.orphanCleanupId()) + || actual.reservation().lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED + || !actual + .reservation() + .reservationId() + .equals(release.releasedMemberValue().reservation().reservationId()) + || !actual.reservation().inventoryRevision().equals(release.completionInventoryRevision()) + || !actual.reservation().owner().equals(release.releasedMemberValue().owner())) { + throw conflict("Current Account-aborted source differs from the committed original release"); + } + } + + private static void requireSourceMatchesRelease( + CanonicalGameplayAdmissionAbortSource source, + CanonicalGameplayIssuerBindingLocalReleaseOperation release) { + requireSameReleaseSource(source, source, release); + } + + private static void requireSameCurrentIssuerState( + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState expected, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState actual, + CanonicalGameplayIssuerInstalledAnchor anchor) { + var a = expected == null ? null : expected.accountCheckpoint(); + var b = actual == null ? null : actual.accountCheckpoint(); + if (a == null + || b == null + || !a.issuerId().equals(b.issuerId()) + || !a.issuerAuthGeneration().equals(b.issuerAuthGeneration()) + || !Arrays.equals(a.exactCheckpointBytes(), b.exactCheckpointBytes()) + || !a.checkpointDigest().equals(b.checkpointDigest()) + || !Objects.equals(a.latestIssuerEventDigest(), b.latestIssuerEventDigest()) + || !Arrays.equals(a.latestIssuerEventBytes(), b.latestIssuerEventBytes()) + || !Arrays.equals( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(expected.incarnation()), + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(actual.incarnation())) + || !Arrays.equals(a.exactCheckpointBytes(), anchor.sourceCheckpointBytes()) + || !a.checkpointDigest().equals(anchor.sourceCheckpointDigest()) + || !Arrays.equals( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(actual.incarnation()), + anchor.incarnationBytes())) { + throw conflict("Issuer source or storage incarnation changed during retirement SQL work"); + } + } + + private CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState + readCurrentIssuerState() { + requireNoAmbientTransaction(); + return Objects.requireNonNull( + currentIssuerStateSource.readFreshCurrentState(), "Current issuer state is required"); + } + + private static long count(DSLContext transaction, String query, Object... bindings) { + Record row = transaction.fetchOne(query, bindings); + if (row == null) throw conflict("Issuer retirement SQL count is unavailable"); + return number(row, "count").longValueExact(); + } + + private static UUID freshNonNilUuid() { + UUID value; + do { + value = UUID.randomUUID(); + } while (value.equals(new UUID(0L, 0L))); + return value; + } + + private static BigDecimal decimal(BigInteger value) { + return new BigDecimal(value); + } + + private static UUID uuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null || value.equals(new UUID(0L, 0L))) + throw conflict(field + " is missing or nil"); + return value; + } + + private static BigInteger number(Record row, String field) { + Object value = row.get(field); + if (!(value instanceof Number number)) throw conflict(field + " is missing or nonnumeric"); + try { + return number instanceof BigDecimal decimal + ? decimal.toBigIntegerExact() + : BigInteger.valueOf(number.longValue()); + } catch (ArithmeticException malformed) { + throw conflict(field + " is not an exact integer"); + } + } + + private static BigInteger positive(Record row, String field) { + BigInteger value = number(row, field); + if (value.signum() <= 0) throw conflict(field + " is not positive"); + return value; + } + + private static BigInteger nonnegative(Record row, String field) { + BigInteger value = number(row, field); + if (value.signum() < 0) throw conflict(field + " is negative"); + return value; + } + + private static String text(Record row, String field) { + String value = row.get(field, String.class); + if (value == null) throw conflict(field + " is missing"); + return value; + } + + private static byte[] bytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + if (value == null || value.length == 0) throw conflict(field + " is missing or empty"); + return value.clone(); + } + + private static byte[] optionalBytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + return value == null ? null : value.clone(); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw conflict("Issuer retirement cannot cross Redis from an ambient SQL transaction"); + } + } + + private static IllegalStateException conflict(String message) { + return new IllegalStateException(message); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.java new file mode 100644 index 0000000000..aec2e24d4f --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.java @@ -0,0 +1,512 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisFuture; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.async.RedisAsyncCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Manual one-key owner for exact original-operation terminal capacity retirement. */ +final class CanonicalGameplayIssuerBindingLocalRetirementRedisOwner { + private static final String PRINCIPAL = "gamesession_coord_app"; + private static final String KEY_PREFIX = "session:game:index:issuer:"; + private static final int MAX_SCRIPT_BYTES = 128 * 1024; + private static final long COMMAND_TIMEOUT_MILLIS = 5_000; + private static final List EXPECTED_KEYS = + List.of( + new RedisScriptDescriptor.KeySpec( + "issuerPartition", KEY_PREFIX, RedisScriptDescriptor.HashTagDeclaration.REQUIRED)); + private static final List EXPECTED_ARGUMENTS = + List.of( + new RedisScriptDescriptor.ArgumentSpec("issuerIdPartitionLayoutAndExactBaselineFields"), + new RedisScriptDescriptor.ArgumentSpec( + "currentUnretiredLocalOperationCountAndExactFields"), + new RedisScriptDescriptor.ArgumentSpec( + "originalReleaseReceiptAndOpaquePhysicalRevisionCompareAndAdvance")); + private static final List EXPECTED_OUTCOMES = + List.of( + new RedisScriptDescriptor.OutcomeSpec( + "TERMINAL_CAPACITY_RETIRED", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "ORIGINAL_RETIREMENT_REPLAY", + RedisScriptDescriptor.OutcomeCategory.REPLAY, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "TYPE_TTL_OR_FIELDSET_REFUSED", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "INVALID_OR_STALE_REVISION_REFUSED", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING)); + + private final RedisClient redisClient; + private final RedisScriptCatalog catalog; + private final CanonicalGameplayIssuerBindingLocalProjectionRepository projectionRepository; + private final CanonicalGameplayIssuerBindingLocalRetirementOperationRepository + retirementRepository; + private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentStateSource; + + CanonicalGameplayIssuerBindingLocalRetirementRedisOwner( + RedisClient redisClient, + RedisScriptCatalog catalog, + CanonicalGameplayIssuerBindingLocalProjectionRepository projectionRepository, + CanonicalGameplayIssuerBindingLocalRetirementOperationRepository retirementRepository, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentStateSource) { + this.redisClient = Objects.requireNonNull(redisClient, "Configured Redis client is required"); + this.catalog = Objects.requireNonNull(catalog, "Manual Redis script catalog is required"); + this.projectionRepository = + Objects.requireNonNull(projectionRepository, "SQL current projection owner is required"); + this.retirementRepository = + Objects.requireNonNull(retirementRepository, "SQL retirement owner is required"); + this.currentStateSource = + Objects.requireNonNull(currentStateSource, "Fresh issuer source is required"); + } + + /** Retires one terminal capacity field and independently proves its exact absence and fence. */ + Readback retireAndRead(CanonicalGameplayIssuerBindingLocalRetirementOperation operation) { + Objects.requireNonNull(operation, "SQL-issued original retirement is required"); + requireNoAmbientTransaction(); + if (operation.status() + == CanonicalGameplayIssuerBindingLocalRetirementOperation.Status.RETIRED) { + return new Readback( + operation.operationId(), 2L, operation.exactAbsenceReadbackFieldSetBytes()); + } + try { + var release = operation.release(); + var work = projectionRepository.readPreparedPartitionWork(release.originalOperation()); + var mutation = operation.physicalMutation(); + if (mutation.status() + != CanonicalGameplayIssuerPartitionMutation.Status.PENDING_PHYSICAL_PROOF + || !mutation.mutationId().equals(work.pendingMutationId()) + || !mutation.expectedRevision().equals(work.currentRevision())) { + throw unavailable("Original retirement no longer owns its prepared partition revision"); + } + requireFreshCurrentState(work); + RedisScriptDescriptor descriptor = requireDescriptor(); + byte[] script = scriptSource(descriptor); + byte[] key = exactPartitionKey(work); + long outcome = writeOneKey(script, key, scriptArguments(work, operation)); + if (outcome != 1 && outcome != 2) { + throw unavailable( + "Issuer retirement Lua refused the exact prepared terminal field: " + outcome); + } + byte[] readback = readExactPhysicalState(key, work, operation); + requireFreshCurrentState(work); + projectionRepository.requireStillCurrent(work); + Readback proof = new Readback(operation.operationId(), outcome, readback); + retirementRepository.completeWithReadback(operation, proof); + return proof; + } catch (RuntimeException failure) { + if (failure instanceof IllegalStateException state + && state.getMessage() != null + && state.getMessage().startsWith("Issuer binding-local retirement is unavailable")) { + throw state; + } + throw unavailable( + "Physical retirement did not obtain exact source and absence proof", failure); + } + } + + private long writeOneKey(byte[] script, byte[] key, byte[][] arguments) { + requireNoAmbientTransaction(); + try (StatefulRedisConnection connection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(connection); + requirePrincipal(await(commands.aclWhoami())); + String sha = await(commands.scriptLoad(script)); + if (!digest("SHA-1", script).equals(sha)) + throw unavailable("Redis loaded a different script"); + Long reply = + await(commands.evalsha(sha, ScriptOutputType.INTEGER, new byte[][] {key}, arguments)); + if (reply == null) throw unavailable("Redis returned no retirement result"); + return reply; + } catch (RuntimeException failure) { + throw unavailable("One-key issuer retirement command failed", failure); + } + } + + private byte[] readExactPhysicalState( + byte[] key, + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work, + CanonicalGameplayIssuerBindingLocalRetirementOperation operation) { + requireNoAmbientTransaction(); + try (StatefulRedisConnection connection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(connection); + requirePrincipal(await(commands.aclWhoami())); + if (!"hash".equals(await(commands.type(key))) + || !Long.valueOf(-1L).equals(await(commands.pttl(key)))) { + throw unavailable("Issuer partition type or TTL is not canonical"); + } + Long length = await(commands.hlen(key)); + int max = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_LOCAL_HASH_FIELDS; + if (length == null || length < 1 || length > max) { + throw unavailable("Issuer retirement readback field count is outside its strict bound"); + } + Map raw = await(commands.hgetall(key)); + if (raw == null || raw.size() != length) + throw unavailable("Issuer retirement readback is incomplete"); + Map actual = new HashMap<>(); + long byteCount = 0; + for (Map.Entry entry : raw.entrySet()) { + byte[] field = Objects.requireNonNull(entry.getKey(), "Redis field"); + byte[] value = Objects.requireNonNull(entry.getValue(), "Redis value"); + byteCount = Math.addExact(byteCount, field.length + (long) value.length); + if (byteCount + > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_TOTAL_HASH_BYTES) { + throw unavailable("Issuer retirement readback exceeds its bounded bytes"); + } + String encoded = Base64.getEncoder().encodeToString(field); + if (actual.putIfAbsent(encoded, value.clone()) != null) { + throw unavailable("Issuer retirement readback repeats a field"); + } + } + Map allowed = new HashMap<>(work.allowedFields()); + String capacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + operation.release().releasedMemberValue().reservation().reservationId()); + if (allowed.containsKey(capacityField)) { + allowed.remove(capacityField); + } else { + throw unavailable( + "The current SQL projection does not contain the terminal target capacity"); + } + byte[] revision = + actual.get( + b64( + CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD.getBytes( + StandardCharsets.US_ASCII))); + if (!Arrays.equals( + revision, + operation + .physicalMutation() + .successorRevision() + .toString() + .getBytes(StandardCharsets.US_ASCII)) + || actual.size() != allowed.size() + 1) { + throw unavailable( + "Issuer retirement lacks the exact successor fence or current field count"); + } + for (Map.Entry field : work.baselineFields().entrySet()) { + byte[] value = actual.get(b64(field.getKey().getBytes(StandardCharsets.UTF_8))); + if (value == null || !Arrays.equals(value, field.getValue())) { + throw unavailable("Exact installed issuer baseline changed during retirement"); + } + } + for (Map.Entry field : actual.entrySet()) { + String decoded = decodeUtf8(Base64.getDecoder().decode(field.getKey())); + if (decoded.equals(CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD)) + continue; + byte[] expected = allowed.get(decoded); + if (expected == null || !Arrays.equals(expected, field.getValue())) { + throw unavailable("Issuer retirement readback contains a foreign or changed field"); + } + } + for (var entry : work.localEntries()) { + if (!entry + .memberValue() + .reservation() + .partitionId() + .equals(operation.release().releasedMemberValue().reservation().partitionId())) + continue; + boolean retirementTarget = + entry + .memberValue() + .reservation() + .reservationId() + .equals(operation.release().releasedMemberValue().reservation().reservationId()); + String localCapacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + entry.memberValue().reservation().reservationId()); + byte[] localCapacity = + actual.get(b64(localCapacityField.getBytes(StandardCharsets.US_ASCII))); + if (!retirementTarget + && entry.capacityMustBePresent() + && !Arrays.equals(localCapacity, entry.exactMemberValueBytes())) { + throw unavailable("A committed local capacity field is missing or changed"); + } + String localBindingField = + new String(entry.memberValue().owner().bindingRef().bytes(), StandardCharsets.UTF_8); + byte[] localBinding = actual.get(b64(localBindingField.getBytes(StandardCharsets.UTF_8))); + if (entry.bindingMustBePresent() + && !Arrays.equals(localBinding, entry.exactMemberValueBytes())) { + throw unavailable("A committed local binding field is missing or changed"); + } + } + if (actual.containsKey(b64(capacityField.getBytes(StandardCharsets.US_ASCII)))) { + throw unavailable("Exact terminal capacity field remains after retirement"); + } + return CanonicalGameplayIssuerBootstrapCoverageRepository.encodeFieldSet( + decodePhysicalMap(actual)); + } catch (RuntimeException failure) { + throw unavailable("Independent issuer retirement readback was not exact", failure); + } + } + + private static byte[][] scriptArguments( + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work, + CanonicalGameplayIssuerBindingLocalRetirementOperation operation) { + var anchor = work.anchor(); + List args = new ArrayList<>(); + args.add(ascii(anchor.issuerId())); + args.add( + ascii(operation.release().releasedMemberValue().reservation().partitionId().toString())); + args.add(ascii(anchor.partitionCount().toString())); + args.add(ascii(anchor.partitionCapacity().toString())); + Map baseline = work.baselineFields(); + List> sorted = + baseline.entrySet().stream().sorted(Map.Entry.comparingByKey()).toList(); + args.add(ascii(Integer.toString(sorted.size()))); + for (Map.Entry field : sorted) { + args.add(field.getKey().getBytes(StandardCharsets.UTF_8)); + args.add(field.getValue()); + } + List entries = + work.localEntries().stream() + .filter( + entry -> + entry + .memberValue() + .reservation() + .partitionId() + .equals( + operation.release().releasedMemberValue().reservation().partitionId())) + .sorted(Comparator.comparing(entry -> entry.operationId().toString())) + .toList(); + args.add(ascii(Integer.toString(entries.size()))); + for (var entry : entries) { + args.add(ascii(entry.operationId().toString())); + args.add(entry.memberValue().owner().bindingRef().bytes()); + args.add(ascii(entry.memberValue().reservation().reservationId().toString())); + args.add(entry.exactMemberValueBytes()); + args.add(ascii(entry.bindingPresent() ? "1" : "0")); + args.add(ascii(entry.countsTowardCapacity() ? "1" : "0")); + args.add(ascii(entry.capacityMustBePresent() ? "1" : "0")); + args.add(ascii(entry.bindingMustBePresent() ? "1" : "0")); + } + var release = operation.release(); + var mutation = operation.physicalMutation(); + args.add(ascii(release.operationId().toString())); + args.add(ascii(operation.operationId().toString())); + args.add(ascii(release.releasedMemberValue().reservation().reservationId().toString())); + args.add(release.releasedMemberValue().owner().bindingRef().bytes()); + args.add(release.exactReleasedMemberValueBytes()); + args.add(ascii(release.sourceInventoryRevision().toString())); + args.add(ascii(release.completionInventoryRevision().toString())); + args.add(ascii(work.partitionCapacity().toString())); + args.add(ascii(work.aggregateCapacity().toString())); + args.add(ascii(work.aggregateBound().toString())); + args.add(ascii(mutation.expectedRevision().toString())); + args.add(ascii(mutation.successorRevision().toString())); + return args.toArray(byte[][]::new); + } + + private byte[] exactPartitionKey( + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work) { + String key = CanonicalGameplayIssuerRedisKeys.forMember(work.targetOperation().memberValue()); + if (!key.startsWith(KEY_PREFIX) || key.length() > 512) + throw unavailable("Issuer key is not canonical"); + return key.getBytes(StandardCharsets.US_ASCII); + } + + private void requireFreshCurrentState( + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work) { + requireNoAmbientTransaction(); + var state = currentStateSource.readFreshCurrentState(); + requireNoAmbientTransaction(); + var checkpoint = state == null ? null : state.accountCheckpoint(); + var anchor = work.anchor(); + if (checkpoint == null + || !checkpoint.issuerId().equals(anchor.issuerId()) + || !checkpoint.issuerAuthGeneration().equals(anchor.issuerAuthGeneration()) + || !Arrays.equals(checkpoint.exactCheckpointBytes(), anchor.sourceCheckpointBytes()) + || !checkpoint.checkpointDigest().equals(anchor.sourceCheckpointDigest()) + || !Arrays.equals(checkpoint.latestIssuerEventBytes(), anchor.sourceEventBytes()) + || !Objects.equals(checkpoint.latestIssuerEventDigest(), anchor.sourceEventDigest()) + || !Arrays.equals( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(state.incarnation()), + anchor.incarnationBytes())) { + throw unavailable("Issuer source checkpoint or incarnation changed"); + } + } + + private RedisScriptDescriptor requireDescriptor() { + RedisScriptDescriptor descriptor; + try { + descriptor = + catalog.require( + CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution.SCRIPT_ID); + } catch (RuntimeException missing) { + throw unavailable("Manual issuer retirement descriptor is not installed", missing); + } + if (!CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution.SCRIPT_ID.equals( + descriptor.scriptId()) + || !CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution.RESOURCE_PATH + .equals(descriptor.resourcePath()) + || !"game-session-service".equals(descriptor.owner()) + || !PRINCIPAL.equals(descriptor.principal()) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || !EXPECTED_KEYS.equals(descriptor.keys()) + || !EXPECTED_ARGUMENTS.equals(descriptor.arguments()) + || descriptor.category() != RedisScriptDescriptor.ScriptCategory.SESSION_ISSUER_INDEX + || !EXPECTED_OUTCOMES.equals(descriptor.outcomes()) + || descriptor.resetSensitivity() != RedisScriptDescriptor.ResetSensitivity.CLUSTER + || descriptor.lossClass() != RedisScriptDescriptor.LossClass.EMPTY_REDIS_COLD_START_OR_RESET + || descriptor.compatibilityLevel() + != RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET + || !descriptor + .supportedCoexistence() + .equals(List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "v2"))) + || descriptor.legacyPayloadShape() != null) { + throw unavailable( + "Manual issuer retirement descriptor differs from its exact owner contract"); + } + return descriptor; + } + + private static byte[] scriptSource(RedisScriptDescriptor descriptor) { + try (InputStream input = + CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.class + .getClassLoader() + .getResourceAsStream(descriptor.resourcePath())) { + if (input == null) throw unavailable("Issuer retirement Lua resource is missing"); + byte[] bytes = input.readNBytes(MAX_SCRIPT_BYTES + 1); + if (bytes.length == 0 + || bytes.length > MAX_SCRIPT_BYTES + || !descriptor.sha256().equals(digest("SHA-256", bytes))) { + throw unavailable("Issuer retirement Lua differs from its exact descriptor digest"); + } + return bytes; + } catch (java.io.IOException failure) { + throw unavailable("Issuer retirement Lua resource could not be read", failure); + } + } + + private static Map decodePhysicalMap(Map encoded) { + Map result = new HashMap<>(); + encoded.forEach( + (field, value) -> result.put(decodeUtf8(Base64.getDecoder().decode(field)), value.clone())); + return result; + } + + private static String b64(byte[] bytes) { + return Base64.getEncoder().encodeToString(bytes); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static String decodeUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw unavailable("Issuer partition contains a non-UTF-8 field", malformed); + } + } + + private static RedisAsyncCommands requireCommands( + StatefulRedisConnection connection) { + if (connection == null || !connection.isOpen()) throw unavailable("Redis connection is closed"); + return connection.async(); + } + + private static void requirePrincipal(String principal) { + if (!PRINCIPAL.equals(principal)) + throw unavailable("Redis ACL principal is not the exact owner"); + } + + private static T await(RedisFuture future) { + try { + return future.get(COMMAND_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + future.cancel(true); + throw unavailable("Redis command was interrupted", interrupted); + } catch (ExecutionException | TimeoutException | RuntimeException failure) { + future.cancel(true); + throw unavailable("Redis command did not return exact proof", failure); + } + } + + private static String digest(String algorithm, byte[] value) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(value)); + } catch (Exception impossible) { + throw new IllegalStateException("Required digest algorithm is unavailable", impossible); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw unavailable("Redis retirement cannot run inside an ambient SQL transaction"); + } + } + + private static IllegalStateException unavailable(String message) { + return new IllegalStateException("Issuer binding-local retirement is unavailable: " + message); + } + + private static IllegalStateException unavailable(String message, Throwable cause) { + return new IllegalStateException( + "Issuer binding-local retirement is unavailable: " + message, cause); + } + + static final class Readback { + private final UUID operationId; + private final long scriptOutcome; + private final byte[] exactAbsenceReadbackFieldSetBytes; + + private Readback(UUID operationId, long scriptOutcome, byte[] exactBytes) { + this.operationId = Objects.requireNonNull(operationId, "operationId"); + this.scriptOutcome = scriptOutcome; + this.exactAbsenceReadbackFieldSetBytes = + Objects.requireNonNull(exactBytes, "exactBytes").clone(); + } + + UUID operationId() { + return operationId; + } + + long scriptOutcome() { + return scriptOutcome; + } + + byte[] exactAbsenceReadbackFieldSetBytes() { + return exactAbsenceReadbackFieldSetBytes.clone(); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java index 69100f7480..b39400ea37 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java @@ -39,6 +39,8 @@ final class CanonicalGameplayIssuerBootstrapCoverageRepository { private static final String ANCHOR = "game_session_canonical_issuer_installed_anchor"; private static final String CONTROL = "game_session_canonical_issuer_layout_bootstrap_control"; private static final String FIELDSET_MAGIC = "issuer-physical-field-set/v1"; + private static final int MAX_LOCAL_PHYSICAL_FIELD_COUNT = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_LOCAL_HASH_FIELDS; private static final String METADATA_FIELD = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.METADATA_FIELD; private static final String CAPACITY_PREFIX = @@ -75,6 +77,13 @@ void recordPartitionProof(CanonicalGameplayIssuerBootstrapPartitionRedisOwner.Re input.partitionId()); if (existing != null) { requireSameProof(existing, input); + CanonicalGameplayIssuerPartitionMutationRepository + .recordInitialPhysicalReadbackInTransaction( + transaction, + work.buildPlan().bootstrapIntent().operationId(), + input.partitionId(), + work.initialPhysicalRevision(), + input.fieldSetBytes()); return; } int inserted = @@ -88,11 +97,12 @@ void recordPartitionProof(CanonicalGameplayIssuerBootstrapPartitionRedisOwner.Re + "partition_capacity, mapping_identity, layout_descriptor_bytes, " + "layout_descriptor_digest, source_checkpoint_bytes, source_checkpoint_digest, " + "source_event_bytes, source_event_digest, incarnation_bytes, incarnation_digest, " - + "partition_id, exact_metadata_bytes, exact_physical_field_set_bytes, " + + "partition_id, initial_physical_mutation_revision, exact_metadata_bytes, " + + "exact_physical_field_set_bytes, " + "exact_physical_field_set_digest, physical_field_count, physical_reservation_count, " + "physical_binding_count, physical_counted_capacity_count, " + "planned_aggregate_capacity_count, proof_state) VALUES (" - + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'EXACT_PHYSICAL_READBACK')", + + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'EXACT_PHYSICAL_READBACK')", input.buildOperationId(), input.bootstrapOperationId(), input.bootstrapRequestId(), @@ -114,6 +124,7 @@ void recordPartitionProof(CanonicalGameplayIssuerBootstrapPartitionRedisOwner.Re input.incarnationBytes(), input.incarnationDigest(), input.partitionId(), + input.initialPhysicalRevision(), input.metadataBytes(), input.fieldSetBytes(), input.fieldSetDigest(), @@ -133,6 +144,13 @@ void recordPartitionProof(CanonicalGameplayIssuerBootstrapPartitionRedisOwner.Re if (saved == null) throw conflict("Exact partition proof is unreadable after persistence"); requireSameProof(saved, input); + CanonicalGameplayIssuerPartitionMutationRepository + .recordInitialPhysicalReadbackInTransaction( + transaction, + work.buildPlan().bootstrapIntent().operationId(), + input.partitionId(), + work.initialPhysicalRevision(), + input.fieldSetBytes()); }); } @@ -273,6 +291,30 @@ static InstalledAnchorPartitionProof readInstalledAnchorPartitionProof( if (!fieldSetDigest.equals(CanonicalGameplayIssuerMemberV2Codec.sha256(fieldSetBytes))) { throw conflict("Installed-anchor partition field set does not match its exact digest"); } + Record mutationHead = + transaction.fetchOne( + "SELECT * FROM " + + CanonicalGameplayIssuerPartitionMutationRepository.HEAD_TABLE + + " WHERE issuer_id = ? AND partition_id = ?", + ISSUER, + partitionId); + if (mutationHead == null + || !anchor + .bootstrapOperationId() + .equals(mutationHead.get("bootstrap_operation_id", UUID.class)) + || !"CURRENT".equals(mutationHead.get("state", String.class))) { + throw conflict("Installed issuer partition lacks its positively installed mutation revision"); + } + Map exactFields = decodeFieldSet(fieldSetBytes); + UUID initialRevision = mutationHead.get("initial_revision", UUID.class); + if (initialRevision == null) { + throw conflict("Installed issuer partition initial mutation revision is missing"); + } + if (!initialRevision.equals(row.get("initial_physical_mutation_revision", UUID.class))) { + throw conflict("Installed issuer partition proof lacks its exact initial mutation revision"); + } + CanonicalGameplayIssuerPartitionMutationRepository.requireRevisionField( + exactFields, initialRevision); return new InstalledAnchorPartitionProof( partitionId, fieldSetBytes, @@ -591,6 +633,25 @@ private static ProofSummary verifyCompleteProof( int expectedPartitionCapacity = expectedCapacityByPartition.getOrDefault(partitionId, 0); Map fields = decodeFieldSet(requireBytes(row, "exact_physical_field_set_bytes")); + UUID initialRevision = requireUuid(row, "initial_physical_mutation_revision"); + if (initialRevision.equals(new UUID(0L, 0L))) { + throw conflict("Initial issuer physical proof has a nil mutation revision"); + } + Record mutationHead = + transaction.fetchOne( + "SELECT * FROM " + + CanonicalGameplayIssuerPartitionMutationRepository.HEAD_TABLE + + " WHERE issuer_id = ? AND partition_id = ?", + ISSUER, + partitionId); + if (mutationHead == null + || !intent.operationId().equals(mutationHead.get("bootstrap_operation_id", UUID.class)) + || !initialRevision.equals(mutationHead.get("initial_revision", UUID.class)) + || !"CURRENT".equals(mutationHead.get("state", String.class))) { + throw conflict("Initial issuer proof does not match its current SQL mutation head"); + } + CanonicalGameplayIssuerPartitionMutationRepository.requireRevisionField( + fields, initialRevision); byte[] metadata = fields.get(METADATA_FIELD); if (metadata == null || !Arrays.equals(metadata, requireBytes(row, "exact_metadata_bytes"))) { throw conflict("Partition proof does not retain its exact common physical metadata"); @@ -603,9 +664,14 @@ private static ProofSummary verifyCompleteProof( int physicalReservations = 0; Set expectedFieldNames = new HashSet<>(); expectedFieldNames.add(METADATA_FIELD); + expectedFieldNames.add(CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD); for (Map.Entry field : fields.entrySet()) { String fieldName = field.getKey(); - if (fieldName.equals(METADATA_FIELD)) continue; + if (fieldName.equals(METADATA_FIELD) + || fieldName.equals( + CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD)) { + continue; + } CanonicalGameplayIssuerMemberV2Value value; try { value = CanonicalGameplayIssuerMemberV2Codec.decode(field.getValue()); @@ -1042,6 +1108,7 @@ private static ProofInput proofInput( CanonicalGameplayIssuerMemberV2Codec.sha256( CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(work.incarnation())), work.partitionId(), + work.initialPhysicalRevision(), physical.metadataBytes(), fieldSet, CanonicalGameplayIssuerMemberV2Codec.sha256(fieldSet), @@ -1119,6 +1186,9 @@ private static void requireSameProof(Record row, ProofInput expected) { || !Arrays.equals(expected.incarnationBytes(), requireBytes(row, "incarnation_bytes")) || !expected.incarnationDigest().equals(requireText(row, "incarnation_digest")) || !expected.partitionId().equals(readInteger(row, "partition_id")) + || !expected + .initialPhysicalRevision() + .equals(row.get("initial_physical_mutation_revision", UUID.class)) || !Arrays.equals(expected.metadataBytes(), requireBytes(row, "exact_metadata_bytes")) || !Arrays.equals( expected.fieldSetBytes(), requireBytes(row, "exact_physical_field_set_bytes")) @@ -1137,6 +1207,9 @@ private static void requireSameProof(Record row, ProofInput expected) { static byte[] encodeFieldSet(Map fields) { List> entries = new ArrayList<>(fields.entrySet()); + if (entries.isEmpty() || entries.size() > MAX_LOCAL_PHYSICAL_FIELD_COUNT) { + throw conflict("Physical field proof count is outside its bound"); + } entries.sort( (left, right) -> compareUnsigned( @@ -1171,8 +1244,7 @@ static Map decodeFieldSet(byte[] encoded) { throw conflict("Persisted issuer physical field proof has an unsupported encoding"); } int count = input.readInt(); - if (count < 1 - || count > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_HASH_FIELDS) { + if (count < 1 || count > MAX_LOCAL_PHYSICAL_FIELD_COUNT) { throw conflict("Persisted issuer physical field count is outside its bound"); } Map fields = new HashMap<>(); @@ -1340,6 +1412,7 @@ private record ProofInput( byte[] incarnationBytes, String incarnationDigest, BigInteger partitionId, + UUID initialPhysicalRevision, byte[] metadataBytes, byte[] fieldSetBytes, String fieldSetDigest, @@ -1349,6 +1422,7 @@ private record ProofInput( int countedCapacityCount, BigInteger aggregateCountedCapacity) { private ProofInput { + Objects.requireNonNull(initialPhysicalRevision, "initialPhysicalRevision"); layoutDescriptorBytes = layoutDescriptorBytes.clone(); sourceCheckpointBytes = sourceCheckpointBytes.clone(); sourceEventBytes = sourceEventBytes == null ? null : sourceEventBytes.clone(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepository.java index 1ac5aa5d38..b921e79e08 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepository.java @@ -93,6 +93,9 @@ CanonicalGameplayIssuerBootstrapPartitionWork preparePartitionWork( || partitionId.compareTo(intent.layoutDescriptor().partitionCount()) >= 0) { throw conflict("Requested partition is outside the exact prepared bootstrap layout"); } + UUID initialPhysicalRevision = + CanonicalGameplayIssuerPartitionMutationRepository.ensureInitialRevisionInTransaction( + transaction, bootstrapOperationId, partitionId); requireCurrentAccountCheckpoint(currentAccountCheckpoint, intent.sourceCheckpoint()); CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation = stableIncarnation.value(); List operations = new ArrayList<>(); @@ -105,7 +108,7 @@ CanonicalGameplayIssuerBootstrapPartitionWork preparePartitionWork( transaction, prepared, currentAccountCheckpoint, incarnation)); } return new CanonicalGameplayIssuerBootstrapPartitionWork( - plan, partitionId, operations, incarnation); + plan, partitionId, initialPhysicalRevision, operations, incarnation); }); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.java index 70040fb7ae..846ce9f334 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.java @@ -31,8 +31,11 @@ final class CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec { static final String METADATA_FIELD = "!issuer-partition-bootstrap/v1"; static final String RESERVATION_FIELD_PREFIX = "!issuer-reservation-capacity/v1:"; + static final String MUTATION_REVISION_FIELD = + CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD; static final int MAX_MEMBER_OPERATIONS = 256; - static final int MAX_HASH_FIELDS = 1 + 2 * MAX_MEMBER_OPERATIONS; + static final int MAX_HASH_FIELDS = 2 + 2 * MAX_MEMBER_OPERATIONS; + static final int MAX_LOCAL_HASH_FIELDS = MAX_HASH_FIELDS + 2 * MAX_MEMBER_OPERATIONS; static final int MAX_BINDING_REF_BYTES = 6_144; static final int MAX_VALUE_BYTES = CanonicalGameplayIssuerMemberV2Codec.MAX_VALUE_BYTES; static final int MAX_METADATA_BYTES = 64 * 1024; @@ -76,10 +79,17 @@ static PhysicalFieldSet expectedFields(CanonicalGameplayIssuerBootstrapPartition Map fields = new LinkedHashMap<>(); putUnique(fields, METADATA_FIELD, metadata); + byte[] initialRevision = + work.initialPhysicalRevision().toString().getBytes(StandardCharsets.US_ASCII); + putUnique(fields, MUTATION_REVISION_FIELD, initialRevision); Set reservations = new HashSet<>(); Set bindings = new HashSet<>(); int bindingCount = 0; - long totalBytes = METADATA_FIELD.getBytes(StandardCharsets.US_ASCII).length + metadata.length; + long totalBytes = + METADATA_FIELD.getBytes(StandardCharsets.US_ASCII).length + + metadata.length + + MUTATION_REVISION_FIELD.getBytes(StandardCharsets.US_ASCII).length + + initialRevision.length; for (CanonicalGameplayIssuerBootstrapMemberOperation operation : work.memberOperations()) { CanonicalGameplayIssuerMemberV2Value value = operation.expectedMemberValue(); byte[] valueBytes = operation.exactMemberValueBytes(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwner.java index e52a26415b..ba44492790 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwner.java @@ -46,6 +46,7 @@ public final class CanonicalGameplayIssuerBootstrapPartitionRedisOwner { new RedisScriptDescriptor.ArgumentSpec("partitionCount"), new RedisScriptDescriptor.ArgumentSpec("partitionCapacity"), new RedisScriptDescriptor.ArgumentSpec("exactBootstrapMetadata"), + new RedisScriptDescriptor.ArgumentSpec("initialPhysicalMutationRevision"), new RedisScriptDescriptor.ArgumentSpec("memberOperationCount"), new RedisScriptDescriptor.ArgumentSpec( "repeatedBindingRefMemberCapacityFieldBindingPresence")); @@ -224,6 +225,14 @@ private PhysicalReadback readExactPhysicalState( .Lifecycle.RELEASED) { capacityCount++; } + } else if (field.equals( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MUTATION_REVISION_FIELD)) { + byte[] revision = + actual.get( + Base64.getEncoder().encodeToString(field.getBytes(StandardCharsets.UTF_8))); + if (!Arrays.equals(revision, entry.getValue())) { + throw unavailable(); + } } else if (!field.equals( CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.METADATA_FIELD)) { CanonicalGameplayIssuerMemberV2Codec.decode( @@ -318,14 +327,15 @@ private static byte[][] scriptArguments( CanonicalGameplayIssuerBootstrapPartitionWork work, CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.PhysicalFieldSet physical) { var intent = work.buildPlan().bootstrapIntent(); - byte[][] arguments = new byte[6 + work.memberOperations().size() * 4][]; + byte[][] arguments = new byte[7 + work.memberOperations().size() * 4][]; arguments[0] = ascii(intent.issuerId()); arguments[1] = ascii(work.partitionId().toString()); arguments[2] = ascii(intent.layoutDescriptor().partitionCount().toString()); arguments[3] = ascii(intent.layoutDescriptor().partitionCapacity().toString()); arguments[4] = physical.metadataBytes(); - arguments[5] = ascii(Integer.toString(work.memberOperations().size())); - int position = 6; + arguments[5] = ascii(work.initialPhysicalRevision().toString()); + arguments[6] = ascii(Integer.toString(work.memberOperations().size())); + int position = 7; for (CanonicalGameplayIssuerBootstrapMemberOperation operation : work.memberOperations()) { CanonicalGameplayIssuerMemberV2Value value = operation.expectedMemberValue(); arguments[position++] = value.owner().bindingRef().bytes(); @@ -444,7 +454,7 @@ private Readback( this.physicalBindingCount = observed.bindingCount(); this.physicalCountedCapacityCount = observed.countedReservationCount(); this.plannedAggregateCapacityCount = Objects.requireNonNull(plannedAggregateCapacityCount); - if (observed.fieldCount() != 1 + physicalReservationCount + physicalBindingCount + if (observed.fieldCount() != 2 + physicalReservationCount + physicalBindingCount || BigInteger.valueOf(observed.countedReservationCount()) .compareTo( work.buildPlan().bootstrapIntent().layoutDescriptor().partitionCapacity()) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionWork.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionWork.java index 050b7d6c55..8dc9a3ad2a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionWork.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionWork.java @@ -3,6 +3,7 @@ import java.math.BigInteger; import java.util.List; import java.util.Objects; +import java.util.UUID; /** * Read-only output of the local SQL owner for one exact partition in a prepared initial bootstrap. @@ -13,12 +14,14 @@ final class CanonicalGameplayIssuerBootstrapPartitionWork { private final CanonicalGameplayIssuerPartitionBuildPlan buildPlan; private final BigInteger partitionId; + private final UUID initialPhysicalRevision; private final List memberOperations; private final CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation; CanonicalGameplayIssuerBootstrapPartitionWork( CanonicalGameplayIssuerPartitionBuildPlan buildPlan, BigInteger partitionId, + UUID initialPhysicalRevision, List memberOperations, CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation) { this.buildPlan = Objects.requireNonNull(buildPlan, "buildPlan"); @@ -26,6 +29,11 @@ final class CanonicalGameplayIssuerBootstrapPartitionWork { throw new IllegalArgumentException("Partition work requires the exact PREPARED build plan"); } this.partitionId = Objects.requireNonNull(partitionId, "partitionId"); + this.initialPhysicalRevision = + Objects.requireNonNull(initialPhysicalRevision, "initialPhysicalRevision"); + if (initialPhysicalRevision.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("initialPhysicalRevision must not be nil"); + } if (partitionId.signum() < 0 || partitionId.compareTo(buildPlan.bootstrapIntent().layoutDescriptor().partitionCount()) >= 0) { @@ -88,6 +96,10 @@ BigInteger partitionId() { return partitionId; } + UUID initialPhysicalRevision() { + return initialPhysicalRevision; + } + List memberOperations() { return memberOperations; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java new file mode 100644 index 0000000000..b50e51f411 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java @@ -0,0 +1,92 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigDecimal; + +/** Shared exact SQL and binding order for capturing and qualifying the issuer bootstrap cohort. */ +final class CanonicalGameplayIssuerCohortSql { + private static final String COHORT_SQL = + "SELECT source_kind, source_key, source_revision, source_row_json FROM (" + + "SELECT CASE WHEN i.issuer_id = ? THEN 'BINDING'" + + " ELSE 'UNRESOLVED_LEGACY_BINDING' END AS source_kind," + + " encode(i.binding_ref, 'hex') AS source_key, i.inventory_revision AS source_revision," + + " to_jsonb(i)::text AS source_row_json FROM game_session_canonical_gameplay_binding_inventory i" + + " WHERE i.inventory_revision <= ?" + + " UNION ALL SELECT 'TRANSITION' AS source_kind, t.transition_id::text AS source_key," + + " t.inventory_revision AS source_revision," + // Preserve frozen pre-V1035 transition bytes for the absence-equivalent new NULL field. + // A definitive abort UUID remains part of the full captured source. + + " CASE WHEN to_jsonb(t)->'admission_orphan_cleanup_id' = 'null'::jsonb" + + " THEN (to_jsonb(t) - 'admission_orphan_cleanup_id')::text" + + " ELSE to_jsonb(t)::text END AS source_row_json" + + " FROM game_session_canonical_binding_transition t WHERE t.inventory_revision <= ?" + + " UNION ALL SELECT CASE WHEN r.issuer_id = ? THEN 'RESERVATION'" + + " ELSE 'UNRESOLVED_LEGACY_RESERVATION' END AS source_kind," + + " r.reservation_id::text AS source_key, r.inventory_revision AS source_revision," + + " to_jsonb(r)::text AS source_row_json FROM game_session_canonical_issuer_partition_reservation r" + + " WHERE r.inventory_revision <= ?" + + " UNION ALL SELECT 'ACCOUNT_OBLIGATION' AS source_kind," + + " a.transition_id::text || ':' || a.obligation_ordinal::text AS source_key," + + " a.inventory_revision AS source_revision, to_jsonb(a)::text AS source_row_json" + + " FROM game_session_canonical_binding_account_index_obligation a" + + " WHERE a.inventory_revision <= ?" + + " UNION ALL SELECT 'ISSUER_OBLIGATION' AS source_kind," + + " encode(o.binding_ref, 'hex') || ':' || o.transition_id::text AS source_key," + + " o.inventory_revision AS source_revision," + // Preserve pre-V1036 frozen bytes only for the absence-equivalent new NULL linkage. + // An actual release-operation identity remains significant captured source evidence. + + " CASE WHEN to_jsonb(o)->'local_release_operation_id' = 'null'::jsonb" + + " THEN (to_jsonb(o) - 'local_release_operation_id')::text" + + " ELSE to_jsonb(o)::text END AS source_row_json" + + " FROM game_session_canonical_binding_issuer_index_obligation o" + + " WHERE o.inventory_revision <= ?" + + " UNION ALL SELECT 'REGION_OBLIGATION' AS source_kind," + + " g.transition_id::text AS source_key, g.inventory_revision AS source_revision," + + " to_jsonb(g)::text AS source_row_json" + + " FROM game_session_canonical_binding_region_bridge_obligation g" + + " WHERE g.inventory_revision <= ?" + + ") captured_cohort ORDER BY source_kind COLLATE \"C\", source_key COLLATE \"C\""; + + static final String FUTURE_REVISION_SQL = + "SELECT EXISTS (SELECT 1 FROM game_session_canonical_gameplay_binding_inventory" + + " WHERE inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_transition" + + " WHERE inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_issuer_partition_reservation" + + " WHERE inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_account_index_obligation" + + " WHERE inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_issuer_index_obligation" + + " WHERE inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_region_bridge_obligation" + + " WHERE inventory_revision > ?) AS has_future_revision"; + + private CanonicalGameplayIssuerCohortSql() {} + + static String cohortSql() { + return COHORT_SQL; + } + + static Object[] cohortBindings(String issuerId, BigDecimal inventoryRevision) { + return new Object[] { + issuerId, + inventoryRevision, + inventoryRevision, + issuerId, + inventoryRevision, + inventoryRevision, + inventoryRevision, + inventoryRevision + }; + } + + static Object[] futureRevisionBindings(BigDecimal inventoryRevision) { + return new Object[] { + inventoryRevision, + inventoryRevision, + inventoryRevision, + inventoryRevision, + inventoryRevision, + inventoryRevision + }; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java index 02456bcd96..97b586ef5e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java @@ -43,63 +43,6 @@ final class CanonicalGameplayIssuerLayoutBootstrapRepository { private static final String MAPPING_IDENTITY = CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY; - private static final String COHORT_SQL = - "SELECT source_kind, source_key, source_revision, source_row_json FROM (" - + "SELECT CASE WHEN i.issuer_id = ? THEN 'BINDING'" - + " ELSE 'UNRESOLVED_LEGACY_BINDING' END AS source_kind," - + " encode(i.binding_ref, 'hex') AS source_key, i.inventory_revision AS source_revision," - + " to_jsonb(i)::text AS source_row_json FROM game_session_canonical_gameplay_binding_inventory i" - + " WHERE i.inventory_revision <= ?" - + " UNION ALL SELECT 'TRANSITION' AS source_kind, t.transition_id::text AS source_key," - + " t.inventory_revision AS source_revision," - // Preserve frozen pre-V1035 transition bytes for the absence-equivalent new NULL field. - // A definitive abort UUID remains part of the full captured source. - + " CASE WHEN to_jsonb(t)->'admission_orphan_cleanup_id' = 'null'::jsonb" - + " THEN (to_jsonb(t) - 'admission_orphan_cleanup_id')::text" - + " ELSE to_jsonb(t)::text END AS source_row_json" - + " FROM game_session_canonical_binding_transition t WHERE t.inventory_revision <= ?" - + " UNION ALL SELECT CASE WHEN r.issuer_id = ? THEN 'RESERVATION'" - + " ELSE 'UNRESOLVED_LEGACY_RESERVATION' END AS source_kind," - + " r.reservation_id::text AS source_key, r.inventory_revision AS source_revision," - + " to_jsonb(r)::text AS source_row_json FROM game_session_canonical_issuer_partition_reservation r" - + " WHERE r.inventory_revision <= ?" - + " UNION ALL SELECT 'ACCOUNT_OBLIGATION' AS source_kind," - + " a.transition_id::text || ':' || a.obligation_ordinal::text AS source_key," - + " a.inventory_revision AS source_revision, to_jsonb(a)::text AS source_row_json" - + " FROM game_session_canonical_binding_account_index_obligation a" - + " WHERE a.inventory_revision <= ?" - + " UNION ALL SELECT 'ISSUER_OBLIGATION' AS source_kind," - + " encode(o.binding_ref, 'hex') || ':' || o.transition_id::text AS source_key," - + " o.inventory_revision AS source_revision," - // Preserve pre-V1036 frozen bytes only for the absence-equivalent new NULL linkage. - // An actual release-operation identity remains significant captured source evidence. - + " CASE WHEN to_jsonb(o)->'local_release_operation_id' = 'null'::jsonb" - + " THEN (to_jsonb(o) - 'local_release_operation_id')::text" - + " ELSE to_jsonb(o)::text END AS source_row_json" - + " FROM game_session_canonical_binding_issuer_index_obligation o" - + " WHERE o.inventory_revision <= ?" - + " UNION ALL SELECT 'REGION_OBLIGATION' AS source_kind," - + " g.transition_id::text AS source_key, g.inventory_revision AS source_revision," - + " to_jsonb(g)::text AS source_row_json" - + " FROM game_session_canonical_binding_region_bridge_obligation g" - + " WHERE g.inventory_revision <= ?" - + ") captured_cohort" - + " ORDER BY source_kind COLLATE \"C\", source_key COLLATE \"C\""; - - private static final String FUTURE_REVISION_SQL = - "SELECT EXISTS (SELECT 1 FROM game_session_canonical_gameplay_binding_inventory" - + " WHERE inventory_revision > ?)" - + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_transition" - + " WHERE inventory_revision > ?)" - + " OR EXISTS (SELECT 1 FROM game_session_canonical_issuer_partition_reservation" - + " WHERE inventory_revision > ?)" - + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_account_index_obligation" - + " WHERE inventory_revision > ?)" - + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_issuer_index_obligation" - + " WHERE inventory_revision > ?)" - + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_region_bridge_obligation" - + " WHERE inventory_revision > ?) AS has_future_revision"; - private final DSLContext dsl; CanonicalGameplayIssuerLayoutBootstrapRepository(DSLContext dsl) { @@ -480,15 +423,8 @@ private static List captureCohort( requireNoFutureInventoryRows(transaction, snapshotRevision); return transaction .fetch( - COHORT_SQL, - ISSUER, - decimal(snapshotRevision), - decimal(snapshotRevision), - ISSUER, - decimal(snapshotRevision), - decimal(snapshotRevision), - decimal(snapshotRevision), - decimal(snapshotRevision)) + CanonicalGameplayIssuerCohortSql.cohortSql(), + CanonicalGameplayIssuerCohortSql.cohortBindings(ISSUER, decimal(snapshotRevision))) .map( row -> new CohortSourceRow( @@ -681,13 +617,8 @@ private static void requireNoFutureInventoryRows( Record row = Objects.requireNonNull( transaction.fetchOne( - FUTURE_REVISION_SQL, - decimal(snapshotRevision), - decimal(snapshotRevision), - decimal(snapshotRevision), - decimal(snapshotRevision), - decimal(snapshotRevision), - decimal(snapshotRevision)), + CanonicalGameplayIssuerCohortSql.FUTURE_REVISION_SQL, + CanonicalGameplayIssuerCohortSql.futureRevisionBindings(decimal(snapshotRevision))), "future inventory revision query must return one row"); if (Boolean.TRUE.equals(row.get("has_future_revision", Boolean.class))) { throw conflict("Issuer bootstrap cannot omit durable rows newer than the inventory clock"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java index fb1a62edd9..f36683fd67 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java @@ -65,62 +65,6 @@ final class CanonicalGameplayIssuerPartitionBuildRepository { private static final UUID NIL_UUID = new UUID(0L, 0L); private static final ObjectMapper JSON = new ObjectMapper(); - private static final String COHORT_SQL = - "SELECT source_kind, source_key, source_revision, source_row_json FROM (" - + "SELECT CASE WHEN i.issuer_id = ? THEN 'BINDING'" - + " ELSE 'UNRESOLVED_LEGACY_BINDING' END AS source_kind," - + " encode(i.binding_ref, 'hex') AS source_key, i.inventory_revision AS source_revision," - + " to_jsonb(i)::text AS source_row_json FROM game_session_canonical_gameplay_binding_inventory i" - + " WHERE i.inventory_revision <= ?" - + " UNION ALL SELECT 'TRANSITION' AS source_kind, t.transition_id::text AS source_key," - + " t.inventory_revision AS source_revision," - // Preserve frozen pre-V1035 transition bytes for the absence-equivalent new NULL field. - // A definitive abort UUID remains part of the full captured source. - + " CASE WHEN to_jsonb(t)->'admission_orphan_cleanup_id' = 'null'::jsonb" - + " THEN (to_jsonb(t) - 'admission_orphan_cleanup_id')::text" - + " ELSE to_jsonb(t)::text END AS source_row_json" - + " FROM game_session_canonical_binding_transition t WHERE t.inventory_revision <= ?" - + " UNION ALL SELECT CASE WHEN r.issuer_id = ? THEN 'RESERVATION'" - + " ELSE 'UNRESOLVED_LEGACY_RESERVATION' END AS source_kind," - + " r.reservation_id::text AS source_key, r.inventory_revision AS source_revision," - + " to_jsonb(r)::text AS source_row_json FROM game_session_canonical_issuer_partition_reservation r" - + " WHERE r.inventory_revision <= ?" - + " UNION ALL SELECT 'ACCOUNT_OBLIGATION' AS source_kind," - + " a.transition_id::text || ':' || a.obligation_ordinal::text AS source_key," - + " a.inventory_revision AS source_revision, to_jsonb(a)::text AS source_row_json" - + " FROM game_session_canonical_binding_account_index_obligation a" - + " WHERE a.inventory_revision <= ?" - + " UNION ALL SELECT 'ISSUER_OBLIGATION' AS source_kind," - + " encode(o.binding_ref, 'hex') || ':' || o.transition_id::text AS source_key," - + " o.inventory_revision AS source_revision," - // Preserve pre-V1036 frozen bytes only for the absence-equivalent new NULL linkage. - // An actual release-operation identity remains significant captured source evidence. - + " CASE WHEN to_jsonb(o)->'local_release_operation_id' = 'null'::jsonb" - + " THEN (to_jsonb(o) - 'local_release_operation_id')::text" - + " ELSE to_jsonb(o)::text END AS source_row_json" - + " FROM game_session_canonical_binding_issuer_index_obligation o" - + " WHERE o.inventory_revision <= ?" - + " UNION ALL SELECT 'REGION_OBLIGATION' AS source_kind," - + " g.transition_id::text AS source_key, g.inventory_revision AS source_revision," - + " to_jsonb(g)::text AS source_row_json" - + " FROM game_session_canonical_binding_region_bridge_obligation g" - + " WHERE g.inventory_revision <= ?" - + ") captured_cohort ORDER BY source_kind COLLATE \"C\", source_key COLLATE \"C\""; - - private static final String FUTURE_REVISION_SQL = - "SELECT EXISTS (SELECT 1 FROM game_session_canonical_gameplay_binding_inventory" - + " WHERE inventory_revision > ?)" - + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_transition" - + " WHERE inventory_revision > ?)" - + " OR EXISTS (SELECT 1 FROM game_session_canonical_issuer_partition_reservation" - + " WHERE inventory_revision > ?)" - + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_account_index_obligation" - + " WHERE inventory_revision > ?)" - + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_issuer_index_obligation" - + " WHERE inventory_revision > ?)" - + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_region_bridge_obligation" - + " WHERE inventory_revision > ?) AS has_future_revision"; - private final DSLContext dsl; CanonicalGameplayIssuerPartitionBuildRepository(DSLContext dsl) { @@ -636,15 +580,8 @@ private static List captureCurrentCohort( requireNoFutureRows(transaction, snapshotRevision); return transaction .fetch( - COHORT_SQL, - ISSUER, - decimal(snapshotRevision), - decimal(snapshotRevision), - ISSUER, - decimal(snapshotRevision), - decimal(snapshotRevision), - decimal(snapshotRevision), - decimal(snapshotRevision)) + CanonicalGameplayIssuerCohortSql.cohortSql(), + CanonicalGameplayIssuerCohortSql.cohortBindings(ISSUER, decimal(snapshotRevision))) .map( row -> { String sourceJson = requireText(row, "source_row_json"); @@ -704,22 +641,8 @@ private static DerivedPlan derivePlan( CanonicalGameplayIssuerLayoutBootstrapIntent intent, List currentRows) { List cohortRows = - currentRows.stream() - .sorted( - Comparator.comparing((IssuerCohortSourceRow row) -> row.cohortRow().kind().name()) - .thenComparing(row -> row.cohortRow().sourceKey())) - .map( - row -> { - var source = row.cohortRow(); - return new CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow( - currentRows.indexOf(row), - source.kind(), - source.sourceKey(), - source.sourceInventoryRevision(), - source.sourceRowJson(), - source.sourceRowDigest()); - }) - .toList(); + assignCanonicalCohortOrdinals( + currentRows.stream().map(IssuerCohortSourceRow::cohortRow).toList()); List blockers = new ArrayList<>(); Map reservations = new HashMap<>(); Map> bindings = new HashMap<>(); @@ -902,6 +825,33 @@ private static DerivedPlan derivePlan( return new DerivedPlan(planned, blockers); } + static List assignCanonicalCohortOrdinals( + List currentRows) { + List sortedRows = + currentRows.stream() + .sorted( + Comparator.comparing( + (CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow row) -> + row.kind().name()) + .thenComparing( + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceKey)) + .toList(); + List numberedRows = + new ArrayList<>(sortedRows.size()); + for (int ordinal = 0; ordinal < sortedRows.size(); ordinal++) { + var source = sortedRows.get(ordinal); + numberedRows.add( + new CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow( + ordinal, + source.kind(), + source.sourceKey(), + source.sourceInventoryRevision(), + source.sourceRowJson(), + source.sourceRowDigest())); + } + return List.copyOf(numberedRows); + } + /** Initial bootstrap adopts its frozen layout; it does not migrate reservations to a new one. */ private static boolean matchesInitialLayout( ReservationSource reservation, CanonicalGameplayIssuerLayoutBootstrapIntent intent) { @@ -1734,13 +1684,8 @@ private static void requireNoFutureRows(DSLContext transaction, BigInteger revis Record row = Objects.requireNonNull( transaction.fetchOne( - FUTURE_REVISION_SQL, - decimal(revision), - decimal(revision), - decimal(revision), - decimal(revision), - decimal(revision), - decimal(revision)), + CanonicalGameplayIssuerCohortSql.FUTURE_REVISION_SQL, + CanonicalGameplayIssuerCohortSql.futureRevisionBindings(decimal(revision))), "future inventory query must return one row"); if (Boolean.TRUE.equals(row.get("has_future_revision", Boolean.class))) { throw conflict("Current issuer inventory has durable rows beyond its locked clock"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionMutation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionMutation.java new file mode 100644 index 0000000000..07a06693d9 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionMutation.java @@ -0,0 +1,148 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.util.Objects; +import java.util.UUID; + +/** One immutable, owner-issued expected/successor revision for a single partition mutation. */ +final class CanonicalGameplayIssuerPartitionMutation { + enum Kind { + ADD_CAPACITY, + ADD_BINDING, + RELEASE, + RETIRE + } + + enum Status { + PENDING_PHYSICAL_PROOF, + COMMITTED + } + + private final UUID mutationId; + private final BigInteger partitionId; + private final Kind kind; + private final UUID ownerOperationId; + private final UUID expectedRevision; + private final UUID successorRevision; + private final byte[] exactIntendedChangeBytes; + private final String exactIntendedChangeDigest; + private final Status status; + private final byte[] exactReadbackFieldSetBytes; + private final String exactReadbackFieldSetDigest; + + CanonicalGameplayIssuerPartitionMutation( + UUID mutationId, + BigInteger partitionId, + Kind kind, + UUID ownerOperationId, + UUID expectedRevision, + UUID successorRevision, + byte[] exactIntendedChangeBytes, + String exactIntendedChangeDigest, + Status status, + byte[] exactReadbackFieldSetBytes, + String exactReadbackFieldSetDigest) { + this.mutationId = requireNonNil(mutationId, "mutationId"); + this.partitionId = Objects.requireNonNull(partitionId, "partitionId"); + if (partitionId.signum() < 0) + throw new IllegalArgumentException("partitionId must be nonnegative"); + this.kind = Objects.requireNonNull(kind, "kind"); + this.ownerOperationId = requireNonNil(ownerOperationId, "ownerOperationId"); + this.expectedRevision = requireNonNil(expectedRevision, "expectedRevision"); + this.successorRevision = requireNonNil(successorRevision, "successorRevision"); + if (expectedRevision.equals(successorRevision)) { + throw new IllegalArgumentException("A partition mutation successor must be a new revision"); + } + this.exactIntendedChangeBytes = + Objects.requireNonNull(exactIntendedChangeBytes, "exactIntendedChangeBytes").clone(); + if (this.exactIntendedChangeBytes.length == 0 + || this.exactIntendedChangeBytes.length > 262_144) { + throw new IllegalArgumentException("Exact intended partition change is outside its bound"); + } + this.exactIntendedChangeDigest = + requireDigest(exactIntendedChangeDigest, "exactIntendedChangeDigest"); + if (!this.exactIntendedChangeDigest.equals( + CanonicalGameplayIssuerMemberV2Codec.sha256(this.exactIntendedChangeBytes))) { + throw new IllegalArgumentException("Exact intended partition change digest differs"); + } + this.status = Objects.requireNonNull(status, "status"); + this.exactReadbackFieldSetBytes = + exactReadbackFieldSetBytes == null ? null : exactReadbackFieldSetBytes.clone(); + this.exactReadbackFieldSetDigest = exactReadbackFieldSetDigest; + if (status == Status.PENDING_PHYSICAL_PROOF) { + if (exactReadbackFieldSetBytes != null || exactReadbackFieldSetDigest != null) { + throw new IllegalArgumentException( + "Pending partition mutation cannot contain readback proof"); + } + } else { + if (this.exactReadbackFieldSetBytes == null + || this.exactReadbackFieldSetBytes.length == 0 + || this.exactReadbackFieldSetBytes.length > 17_825_792 + || !Objects.equals( + exactReadbackFieldSetDigest, + CanonicalGameplayIssuerMemberV2Codec.sha256(this.exactReadbackFieldSetBytes))) { + throw new IllegalArgumentException( + "Committed partition mutation needs exact readback proof"); + } + } + } + + UUID mutationId() { + return mutationId; + } + + BigInteger partitionId() { + return partitionId; + } + + Kind kind() { + return kind; + } + + UUID ownerOperationId() { + return ownerOperationId; + } + + UUID expectedRevision() { + return expectedRevision; + } + + UUID successorRevision() { + return successorRevision; + } + + byte[] exactIntendedChangeBytes() { + return exactIntendedChangeBytes.clone(); + } + + String exactIntendedChangeDigest() { + return exactIntendedChangeDigest; + } + + Status status() { + return status; + } + + byte[] exactReadbackFieldSetBytes() { + return exactReadbackFieldSetBytes == null ? null : exactReadbackFieldSetBytes.clone(); + } + + String exactReadbackFieldSetDigest() { + return exactReadbackFieldSetDigest; + } + + private static UUID requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException(name + " must not be nil"); + return value; + } + + private static String requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(name + " must be a canonical SHA-256 digest"); + } + return value; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionMutationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionMutationRepository.java new file mode 100644 index 0000000000..d8ab67a121 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionMutationRepository.java @@ -0,0 +1,541 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.jooq.DSLContext; +import org.jooq.Record; + +/** SQL serialization owner for each one-key issuer-partition physical mutation. */ +final class CanonicalGameplayIssuerPartitionMutationRepository { + static final String REVISION_FIELD = "!issuer-partition-mutation-revision/v1"; + + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + static final String HEAD_TABLE = "game_session_canonical_issuer_partition_mutation_head"; + private static final String HEAD = HEAD_TABLE; + private static final String MUTATION = "game_session_canonical_issuer_partition_mutation"; + private static final String PROOF = "game_session_canonical_issuer_bootstrap_partition_proof"; + private static final String ANCHOR = "game_session_canonical_issuer_installed_anchor"; + + private CanonicalGameplayIssuerPartitionMutationRepository() {} + + /** + * Allocates the initial opaque physical revision only as part of the existing positive bootstrap + * owner, before that owner writes the initial field set. A retained proof or anchor with no head + * is old/missing physical state and cannot be initialized here. + */ + static UUID ensureInitialRevisionInTransaction( + DSLContext transaction, UUID bootstrapOperationId, BigInteger partitionId) { + Objects.requireNonNull(transaction, "transaction"); + requireNonNil(bootstrapOperationId, "bootstrapOperationId"); + requirePartition(partitionId); + Record existing = + transaction.fetchOne( + "SELECT * FROM " + HEAD + " WHERE issuer_id = ? AND partition_id = ? FOR UPDATE", + ISSUER, + partitionId); + if (existing != null) { + if (!bootstrapOperationId.equals(uuid(existing, "bootstrap_operation_id"))) { + throw conflict("Issuer partition revision belongs to a different initial anchor"); + } + UUID revision = uuid(existing, "initial_revision"); + String state = text(existing, "state"); + UUID currentRevision = uuid(existing, "current_revision"); + if ((!"INITIAL_INSTALL_PENDING".equals(state) && !"CURRENT".equals(state)) + || ("INITIAL_INSTALL_PENDING".equals(state) && !revision.equals(currentRevision))) { + throw conflict("Initial issuer partition revision head is malformed"); + } + return revision; + } + Record proof = + transaction.fetchOne( + "SELECT 1 FROM " + PROOF + " WHERE bootstrap_operation_id = ? AND partition_id = ?", + bootstrapOperationId, + partitionId); + Record anchor = + transaction.fetchOne( + "SELECT 1 FROM " + ANCHOR + " WHERE bootstrap_operation_id = ?", bootstrapOperationId); + if (proof != null || anchor != null) { + throw conflict("Installed issuer partition is missing its positively installed revision"); + } + UUID initialRevision = freshRevision(); + int inserted = + transaction.execute( + "INSERT INTO " + + HEAD + + " (issuer_id, partition_id, bootstrap_operation_id, initial_revision," + + " current_revision, state) VALUES (?, ?, ?, ?, ?, 'INITIAL_INSTALL_PENDING')", + ISSUER, + partitionId, + bootstrapOperationId, + initialRevision, + initialRevision); + if (inserted != 1) throw conflict("Initial issuer partition revision was not persisted"); + return initialRevision; + } + + /** Called only after the existing bootstrap owner independently read back the entire key. */ + static void recordInitialPhysicalReadbackInTransaction( + DSLContext transaction, + UUID bootstrapOperationId, + BigInteger partitionId, + UUID initialRevision, + byte[] exactFieldSetBytes) { + Objects.requireNonNull(transaction, "transaction"); + requireNonNil(bootstrapOperationId, "bootstrapOperationId"); + requirePartition(partitionId); + requireNonNil(initialRevision, "initialRevision"); + Objects.requireNonNull(exactFieldSetBytes, "exactFieldSetBytes"); + Map fields = + CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet(exactFieldSetBytes); + byte[] revisionBytes = fields.get(REVISION_FIELD); + if (!Arrays.equals( + revisionBytes, initialRevision.toString().getBytes(StandardCharsets.US_ASCII))) { + throw conflict("Initial partition readback lacks its exact SQL-issued physical revision"); + } + Record row = + transaction.fetchOne( + "SELECT * FROM " + HEAD + " WHERE issuer_id = ? AND partition_id = ? FOR UPDATE", + ISSUER, + partitionId); + if (row == null + || !bootstrapOperationId.equals(uuid(row, "bootstrap_operation_id")) + || !initialRevision.equals(uuid(row, "initial_revision")) + || !initialRevision.equals(uuid(row, "current_revision"))) { + throw conflict("Initial partition readback differs from its prepared SQL revision"); + } + String state = text(row, "state"); + if ("CURRENT".equals(state)) return; + if (!"INITIAL_INSTALL_PENDING".equals(state) || row.get("pending_mutation_id") != null) { + throw conflict("Initial partition revision is not awaiting bootstrap proof"); + } + int updated = + transaction.execute( + "UPDATE " + + HEAD + + " SET state = 'CURRENT' WHERE issuer_id = ? AND partition_id = ?" + + " AND bootstrap_operation_id = ? AND initial_revision = ?" + + " AND current_revision = ? AND state = 'INITIAL_INSTALL_PENDING'" + + " AND pending_mutation_id IS NULL", + ISSUER, + partitionId, + bootstrapOperationId, + initialRevision, + initialRevision); + if (updated != 1) + throw conflict("Initial partition revision installation compare-and-set refused"); + } + + /** Persists the unique original expected/successor pair and serializes later same-key writers. */ + static CanonicalGameplayIssuerPartitionMutation prepareInTransaction( + DSLContext transaction, + CanonicalGameplayIssuerPartitionMutation.Kind kind, + UUID ownerOperationId, + BigInteger partitionId, + byte[] exactIntendedChangeBytes) { + Objects.requireNonNull(transaction, "transaction"); + Objects.requireNonNull(kind, "kind"); + requireNonNil(ownerOperationId, "ownerOperationId"); + requirePartition(partitionId); + if (exactIntendedChangeBytes == null + || exactIntendedChangeBytes.length == 0 + || exactIntendedChangeBytes.length > 262_144) { + throw conflict("Exact intended issuer partition mutation is missing or oversized"); + } + String digest = CanonicalGameplayIssuerMemberV2Codec.sha256(exactIntendedChangeBytes); + Record current = lockCurrentHead(transaction, partitionId); + Record existing = + transaction.fetchOne( + "SELECT * FROM " + + MUTATION + + " WHERE issuer_id = ? AND partition_id = ? AND mutation_kind = ?" + + " AND owner_operation_id = ? FOR UPDATE", + ISSUER, + partitionId, + kind.name(), + ownerOperationId); + if (existing != null) { + CanonicalGameplayIssuerPartitionMutation mutation = readMutation(existing); + if (!Arrays.equals(mutation.exactIntendedChangeBytes(), exactIntendedChangeBytes) + || !mutation.exactIntendedChangeDigest().equals(digest)) { + throw conflict( + "Original issuer partition mutation retry changed its exact intended change"); + } + if (mutation.status() + == CanonicalGameplayIssuerPartitionMutation.Status.PENDING_PHYSICAL_PROOF) { + if (!mutation.mutationId().equals(nullableUuid(current, "pending_mutation_id")) + || !mutation.expectedRevision().equals(uuid(current, "current_revision"))) { + throw conflict("Pending issuer partition mutation lost its current revision fence"); + } + } + return mutation; + } + if (nullableUuid(current, "pending_mutation_id") != null) { + throw conflict("Another same-partition physical mutation remains unresolved"); + } + UUID expected = uuid(current, "current_revision"); + UUID successor = freshRevision(); + while (successor.equals(expected)) successor = freshRevision(); + UUID mutationId = freshRevision(); + int inserted = + transaction.execute( + "INSERT INTO " + + MUTATION + + " (mutation_id, issuer_id, partition_id, mutation_kind, owner_operation_id," + + " expected_revision, successor_revision, exact_intended_change_bytes," + + " exact_intended_change_digest, status)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING_PHYSICAL_PROOF')", + mutationId, + ISSUER, + partitionId, + kind.name(), + ownerOperationId, + expected, + successor, + exactIntendedChangeBytes, + digest); + if (inserted != 1) throw conflict("Issuer partition mutation intent was not persisted"); + int advanced = + transaction.execute( + "UPDATE " + + HEAD + + " SET pending_mutation_id = ? WHERE issuer_id = ? AND partition_id = ?" + + " AND state = 'CURRENT' AND current_revision = ? AND pending_mutation_id IS NULL", + mutationId, + ISSUER, + partitionId, + expected); + if (advanced != 1) + throw conflict("Issuer partition mutation reservation compare-and-set refused"); + Record saved = + transaction.fetchOne("SELECT * FROM " + MUTATION + " WHERE mutation_id = ?", mutationId); + if (saved == null) throw conflict("Issuer partition mutation is unreadable after preparation"); + return readMutation(saved); + } + + /** Canonical binary carrier for the exact original change, not a caller-supplied digest. */ + static byte[] encodeIntendedChange( + CanonicalGameplayIssuerPartitionMutation.Kind kind, + UUID ownerOperationId, + BigInteger partitionId, + byte[]... exactSourceFields) { + Objects.requireNonNull(kind, "kind"); + requireNonNil(ownerOperationId, "ownerOperationId"); + requirePartition(partitionId); + Objects.requireNonNull(exactSourceFields, "exactSourceFields"); + try { + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + try (DataOutputStream output = new DataOutputStream(buffer)) { + writeField( + output, "canonical-issuer-partition-mutation/v1".getBytes(StandardCharsets.US_ASCII)); + writeField(output, kind.name().getBytes(StandardCharsets.US_ASCII)); + writeField(output, ownerOperationId.toString().getBytes(StandardCharsets.US_ASCII)); + writeField(output, partitionId.toString().getBytes(StandardCharsets.US_ASCII)); + output.writeInt(exactSourceFields.length); + for (byte[] value : exactSourceFields) { + if (value == null) + throw conflict("Exact issuer partition mutation source field is missing"); + writeField(output, value); + } + } + byte[] encoded = buffer.toByteArray(); + if (encoded.length == 0 || encoded.length > 262_144) { + throw conflict("Exact issuer partition mutation tuple exceeds its bound"); + } + return encoded; + } catch (IOException impossible) { + throw new IllegalStateException( + "Could not encode exact issuer partition mutation", impossible); + } + } + + /** Commits only a complete readback already obtained on an independent Redis connection. */ + static CanonicalGameplayIssuerPartitionMutation completeInTransaction( + DSLContext transaction, + CanonicalGameplayIssuerPartitionMutation expected, + byte[] exactReadbackFieldSetBytes) { + Objects.requireNonNull(transaction, "transaction"); + Objects.requireNonNull(expected, "expected"); + if (exactReadbackFieldSetBytes == null + || exactReadbackFieldSetBytes.length == 0 + || exactReadbackFieldSetBytes.length > 17_825_792) { + throw conflict("Issuer partition mutation readback is missing or oversized"); + } + String readbackDigest = CanonicalGameplayIssuerMemberV2Codec.sha256(exactReadbackFieldSetBytes); + Record head = lockCurrentHead(transaction, expected.partitionId()); + Record row = + transaction.fetchOne( + "SELECT * FROM " + MUTATION + " WHERE mutation_id = ? FOR UPDATE", + expected.mutationId()); + if (row == null) throw conflict("Issuer partition mutation disappeared before completion"); + CanonicalGameplayIssuerPartitionMutation current = readMutation(row); + requireSameMutation(expected, current); + if (current.status() == CanonicalGameplayIssuerPartitionMutation.Status.COMMITTED) { + if (!Arrays.equals(current.exactReadbackFieldSetBytes(), exactReadbackFieldSetBytes) + || !current.exactReadbackFieldSetDigest().equals(readbackDigest)) { + throw conflict("Committed issuer partition mutation retry changed its exact readback"); + } + return current; + } + if (!current.mutationId().equals(nullableUuid(head, "pending_mutation_id")) + || !current.expectedRevision().equals(uuid(head, "current_revision"))) { + throw conflict("Issuer partition mutation no longer owns its expected revision"); + } + int committed = + transaction.execute( + "UPDATE " + + MUTATION + + " SET status = 'COMMITTED', exact_readback_field_set_bytes = ?," + + " exact_readback_field_set_digest = ?, completed_at = CURRENT_TIMESTAMP" + + " WHERE mutation_id = ? AND status = 'PENDING_PHYSICAL_PROOF'" + + " AND expected_revision = ? AND successor_revision = ?", + exactReadbackFieldSetBytes, + readbackDigest, + current.mutationId(), + current.expectedRevision(), + current.successorRevision()); + if (committed != 1) + throw conflict("Issuer partition mutation completion compare-and-set refused"); + int advanced = + transaction.execute( + "UPDATE " + + HEAD + + " SET current_revision = ?, pending_mutation_id = NULL" + + " WHERE issuer_id = ? AND partition_id = ? AND state = 'CURRENT'" + + " AND current_revision = ? AND pending_mutation_id = ?", + current.successorRevision(), + ISSUER, + current.partitionId(), + current.expectedRevision(), + current.mutationId()); + if (advanced != 1) + throw conflict("Issuer partition mutation head completion compare-and-set refused"); + Record completed = + transaction.fetchOne( + "SELECT * FROM " + MUTATION + " WHERE mutation_id = ?", current.mutationId()); + if (completed == null) throw conflict("Committed issuer partition mutation is unreadable"); + return readMutation(completed); + } + + static CanonicalGameplayIssuerPartitionMutation readInTransaction( + DSLContext transaction, + CanonicalGameplayIssuerPartitionMutation.Kind kind, + UUID ownerOperationId, + BigInteger partitionId) { + Record row = + transaction.fetchOne( + "SELECT * FROM " + + MUTATION + + " WHERE issuer_id = ? AND partition_id = ? AND mutation_kind = ?" + + " AND owner_operation_id = ?", + ISSUER, + partitionId, + kind.name(), + ownerOperationId); + if (row == null) throw conflict("The original issuer partition mutation evidence is missing"); + return readMutation(row); + } + + static CanonicalGameplayIssuerPartitionMutation readOptionalInTransaction( + DSLContext transaction, + CanonicalGameplayIssuerPartitionMutation.Kind kind, + UUID ownerOperationId, + BigInteger partitionId) { + Record row = + transaction.fetchOne( + "SELECT * FROM " + + MUTATION + + " WHERE issuer_id = ? AND partition_id = ? AND mutation_kind = ?" + + " AND owner_operation_id = ?", + ISSUER, + partitionId, + kind.name(), + ownerOperationId); + return row == null ? null : readMutation(row); + } + + static UUID readCurrentRevisionInTransaction(DSLContext transaction, BigInteger partitionId) { + Record head = lockCurrentHead(transaction, partitionId); + if (nullableUuid(head, "pending_mutation_id") != null) { + throw conflict("A same-partition physical mutation is still unresolved"); + } + return uuid(head, "current_revision"); + } + + static PartitionMutationHead readHeadInTransaction( + DSLContext transaction, BigInteger partitionId) { + Record head = lockCurrentHead(transaction, partitionId); + UUID pendingMutationId = nullableUuid(head, "pending_mutation_id"); + UUID currentRevision = uuid(head, "current_revision"); + if (pendingMutationId != null) { + Record pending = + transaction.fetchOne( + "SELECT * FROM " + MUTATION + " WHERE mutation_id = ? FOR UPDATE", pendingMutationId); + if (pending == null + || !ISSUER.equals(text(pending, "issuer_id")) + || !partitionId.equals(nonnegative(pending, "partition_id")) + || !currentRevision.equals(uuid(pending, "expected_revision")) + || !"PENDING_PHYSICAL_PROOF".equals(text(pending, "status"))) { + throw conflict("Current issuer partition revision has malformed pending mutation custody"); + } + } + return new PartitionMutationHead( + uuid(head, "initial_revision"), currentRevision, pendingMutationId); + } + + static void requireRevisionField(Map fields, UUID expectedRevision) { + byte[] actual = fields.get(REVISION_FIELD); + if (!Arrays.equals(actual, expectedRevision.toString().getBytes(StandardCharsets.US_ASCII))) { + throw conflict("Issuer partition is missing its exact current physical mutation revision"); + } + } + + private static Record lockCurrentHead(DSLContext transaction, BigInteger partitionId) { + Record head = + transaction.fetchOne( + "SELECT * FROM " + HEAD + " WHERE issuer_id = ? AND partition_id = ? FOR UPDATE", + ISSUER, + partitionId); + if (head == null || !"CURRENT".equals(text(head, "state"))) { + throw conflict("Issuer partition has no positively installed current mutation revision"); + } + return head; + } + + private static CanonicalGameplayIssuerPartitionMutation readMutation(Record row) { + CanonicalGameplayIssuerPartitionMutation.Kind kind; + CanonicalGameplayIssuerPartitionMutation.Status status; + try { + kind = CanonicalGameplayIssuerPartitionMutation.Kind.valueOf(text(row, "mutation_kind")); + status = CanonicalGameplayIssuerPartitionMutation.Status.valueOf(text(row, "status")); + } catch (RuntimeException malformed) { + throw conflict("Issuer partition mutation kind or status is malformed"); + } + byte[] intended = bytes(row, "exact_intended_change_bytes"); + String digest = text(row, "exact_intended_change_digest"); + if (!digest.equals(CanonicalGameplayIssuerMemberV2Codec.sha256(intended))) { + throw conflict("Issuer partition mutation intent digest differs from its exact bytes"); + } + byte[] readback = optionalBytes(row, "exact_readback_field_set_bytes"); + String readbackDigest = row.get("exact_readback_field_set_digest", String.class); + if ((status == CanonicalGameplayIssuerPartitionMutation.Status.PENDING_PHYSICAL_PROOF + && (readback != null || readbackDigest != null || row.get("completed_at") != null)) + || (status == CanonicalGameplayIssuerPartitionMutation.Status.COMMITTED + && (readback == null + || readbackDigest == null + || !readbackDigest.equals(CanonicalGameplayIssuerMemberV2Codec.sha256(readback)) + || row.get("completed_at") == null))) { + throw conflict("Issuer partition mutation proof differs from its durable phase"); + } + try { + return new CanonicalGameplayIssuerPartitionMutation( + uuid(row, "mutation_id"), + nonnegative(row, "partition_id"), + kind, + uuid(row, "owner_operation_id"), + uuid(row, "expected_revision"), + uuid(row, "successor_revision"), + intended, + digest, + status, + readback, + readbackDigest); + } catch (RuntimeException malformed) { + throw conflict("Issuer partition mutation row is malformed"); + } + } + + private static void requireSameMutation( + CanonicalGameplayIssuerPartitionMutation expected, + CanonicalGameplayIssuerPartitionMutation actual) { + if (!expected.mutationId().equals(actual.mutationId()) + || !expected.kind().equals(actual.kind()) + || !expected.ownerOperationId().equals(actual.ownerOperationId()) + || !expected.partitionId().equals(actual.partitionId()) + || !expected.expectedRevision().equals(actual.expectedRevision()) + || !expected.successorRevision().equals(actual.successorRevision()) + || !Arrays.equals(expected.exactIntendedChangeBytes(), actual.exactIntendedChangeBytes()) + || !expected.exactIntendedChangeDigest().equals(actual.exactIntendedChangeDigest())) { + throw conflict("Issuer partition mutation changed its original SQL intent"); + } + } + + private static UUID freshRevision() { + UUID revision; + do { + revision = UUID.randomUUID(); + } while (revision.equals(new UUID(0L, 0L))); + return revision; + } + + private static void writeField(DataOutputStream output, byte[] value) throws IOException { + output.writeInt(value.length); + output.write(value); + } + + private static UUID requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) throw conflict(name + " must not be nil"); + return value; + } + + private static void requirePartition(BigInteger partitionId) { + Objects.requireNonNull(partitionId, "partitionId"); + if (partitionId.signum() < 0) throw conflict("Issuer partition id must be nonnegative"); + } + + private static UUID uuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null || value.equals(new UUID(0L, 0L))) + throw conflict(field + " is missing or nil"); + return value; + } + + private static UUID nullableUuid(Record row, String field) { + return row.get(field, UUID.class); + } + + private static BigInteger nonnegative(Record row, String field) { + BigDecimal value = row.get(field, BigDecimal.class); + if (value == null) throw conflict(field + " is missing"); + try { + BigInteger integer = value.toBigIntegerExact(); + if (integer.signum() < 0) throw conflict(field + " must be nonnegative"); + return integer; + } catch (ArithmeticException malformed) { + throw conflict(field + " is not an exact integer"); + } + } + + private static String text(Record row, String field) { + String value = row.get(field, String.class); + if (value == null) throw conflict(field + " is missing"); + return value; + } + + private static byte[] bytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + if (value == null || value.length == 0) throw conflict(field + " is missing"); + return value.clone(); + } + + private static byte[] optionalBytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + return value == null ? null : value.clone(); + } + + private static IllegalStateException conflict(String message) { + return new IllegalStateException(message); + } + + record PartitionMutationHead( + UUID initialRevision, UUID currentRevision, UUID pendingMutationId) {} +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRedisScriptContribution.java index 9c9c71bd5e..3e25b7d29d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRedisScriptContribution.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRedisScriptContribution.java @@ -32,20 +32,22 @@ public String ownerId() { @Override public Collection descriptors() { try (InputStream input = getClass().getResourceAsStream(DESCRIPTOR_PATH)) { - if (input == null) throw unavailable(); + if (input == null) throw new IOException("Descriptor resource is missing"); byte[] bytes = input.readNBytes(16 * 1024 + 1); - if (bytes.length == 0 || bytes.length > 16 * 1024) throw unavailable(); + if (bytes.length == 0 || bytes.length > 16 * 1024) { + throw new IOException("Descriptor resource is empty or oversized"); + } RedisScriptDescriptor descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); if (!ownerId().equals(descriptor.owner()) || !SCRIPT_ID.equals(descriptor.scriptId())) { - throw unavailable(); + throw new IllegalArgumentException("Descriptor owner or script identity is invalid"); } return List.of(descriptor); } catch (IOException | RuntimeException failure) { - throw unavailable(); + throw unavailable(failure); } } - private static IllegalStateException unavailable() { - return new IllegalStateException("Issuer binding-local Redis descriptor is unavailable"); + private static IllegalStateException unavailable(Throwable cause) { + return new IllegalStateException("Issuer binding-local Redis descriptor is unavailable", cause); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.java index 1d22251bdd..c0b5f01a70 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.java @@ -33,21 +33,23 @@ public String ownerId() { @Override public Collection descriptors() { try (InputStream input = getClass().getResourceAsStream(DESCRIPTOR_PATH)) { - if (input == null) throw unavailable(); + if (input == null) throw new IOException("Descriptor resource is missing"); byte[] bytes = input.readNBytes(16 * 1024 + 1); - if (bytes.length == 0 || bytes.length > 16 * 1024) throw unavailable(); + if (bytes.length == 0 || bytes.length > 16 * 1024) { + throw new IOException("Descriptor resource is empty or oversized"); + } RedisScriptDescriptor descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); if (!ownerId().equals(descriptor.owner()) || !SCRIPT_ID.equals(descriptor.scriptId())) { - throw unavailable(); + throw new IllegalArgumentException("Descriptor owner or script identity is invalid"); } return List.of(descriptor); } catch (IOException | RuntimeException failure) { - throw unavailable(); + throw unavailable(failure); } } - private static IllegalStateException unavailable() { + private static IllegalStateException unavailable(Throwable cause) { return new IllegalStateException( - "Issuer binding-local release Redis descriptor is unavailable"); + "Issuer binding-local release Redis descriptor is unavailable", cause); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution.java new file mode 100644 index 0000000000..36aeb0cbd5 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution.java @@ -0,0 +1,51 @@ +package net.firedevops.firemud.gamesession.service; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Collection; +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Passive manual-catalog contribution for one original-operation physical retirement. */ +public final class CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution + implements RedisScriptContribution { + public static final String SCRIPT_ID = "game-session.issuer-binding-local-retirement.v1"; + public static final String RESOURCE_PATH = + "redis/lua/game-session-issuer-binding-local-retirement.lua"; + private static final String DESCRIPTOR_PATH = + "/redis/scripts/game-session-issuer-binding-local-retirement.json"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @Override + public String ownerId() { + return "game-session-service"; + } + + @Override + public Collection descriptors() { + try (InputStream input = getClass().getResourceAsStream(DESCRIPTOR_PATH)) { + if (input == null) throw new IOException("Descriptor resource is missing"); + byte[] bytes = input.readNBytes(16 * 1024 + 1); + if (bytes.length == 0 || bytes.length > 16 * 1024) { + throw new IOException("Descriptor resource is empty or oversized"); + } + RedisScriptDescriptor descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); + if (!ownerId().equals(descriptor.owner()) || !SCRIPT_ID.equals(descriptor.scriptId())) { + throw new IllegalArgumentException("Descriptor owner or script identity is invalid"); + } + return List.of(descriptor); + } catch (IOException | RuntimeException failure) { + throw new IllegalStateException( + "Issuer binding-local retirement descriptor is unavailable", failure); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.java index 7b3eecd8c2..6fcd308104 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.java @@ -33,20 +33,23 @@ public String ownerId() { @Override public Collection descriptors() { try (InputStream input = getClass().getResourceAsStream(DESCRIPTOR_PATH)) { - if (input == null) throw unavailable(); + if (input == null) throw new IOException("Descriptor resource is missing"); byte[] bytes = input.readNBytes(16 * 1024 + 1); - if (bytes.length == 0 || bytes.length > 16 * 1024) throw unavailable(); + if (bytes.length == 0 || bytes.length > 16 * 1024) { + throw new IOException("Descriptor resource is empty or oversized"); + } RedisScriptDescriptor descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); if (!ownerId().equals(descriptor.owner()) || !SCRIPT_ID.equals(descriptor.scriptId())) { - throw unavailable(); + throw new IllegalArgumentException("Descriptor owner or script identity is invalid"); } return List.of(descriptor); } catch (IOException | RuntimeException failure) { - throw unavailable(); + throw unavailable(failure); } } - private static IllegalStateException unavailable() { - return new IllegalStateException("Issuer bootstrap partition Redis descriptor is unavailable"); + private static IllegalStateException unavailable(Throwable cause) { + return new IllegalStateException( + "Issuer bootstrap partition Redis descriptor is unavailable", cause); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java index 0cbdca4e19..9bbf22e587 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java @@ -11,6 +11,7 @@ import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayBindingInventoryConflictException; import net.firedevops.firemud.gamesession.repository.CanonicalGameplayBindingInventoryRepository; import net.firedevops.firemud.gamesession.security.CanonicalGameplayAdmissionDecisionReadWorkloadGuard; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionDecisionReadServiceGrpc; @@ -91,17 +92,47 @@ public void getCanonicalGameplayAdmissionDecision( return; } - final GetCanonicalGameplayAdmissionDecisionResponse response; + final CanonicalGameplayAdmissionDecision decision; try { - CanonicalGameplayAdmissionDecision decision = + decision = repository.readAdmissionDecision( selector.bindingDecisionId(), selector.expectedLeaseEvidence()); - if (decision.leaseKind() - != net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence - .LeaseKind.NEW_BINDING) { - fail(observer, Status.FAILED_PRECONDITION); - return; - } + } catch (CannotCreateTransactionException + | DataAccessResourceFailureException + | TransientDataAccessException unavailable) { + fail(observer, Status.UNAVAILABLE); + return; + } catch (DataAccessException | org.springframework.dao.DataAccessException failure) { + fail(observer, hasConnectionFailureSqlState(failure) ? Status.UNAVAILABLE : Status.INTERNAL); + return; + } catch (CanonicalGameplayBindingInventoryConflictException conflict) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } catch (IllegalStateException conflict) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } catch (RuntimeException unexpectedRepositoryFailure) { + fail(observer, Status.INTERNAL); + return; + } + + final boolean newBindingDecision; + try { + newBindingDecision = + decision.leaseKind() + == net.firedevops.firemud.common.account.admission + .AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING; + } catch (RuntimeException unexpectedDecisionFailure) { + fail(observer, Status.INTERNAL); + return; + } + if (!newBindingDecision) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } + + final GetCanonicalGameplayAdmissionDecisionResponse response; + try { response = CanonicalGameplayAdmissionDecisionReadGrpcCodec.toResponse( selector, @@ -112,16 +143,8 @@ public void getCanonicalGameplayAdmissionDecision( decision.resumeEpisodeId(), toCandidate(decision), toTarget(decision)); - } catch (CannotCreateTransactionException - | DataAccessResourceFailureException - | TransientDataAccessException unavailable) { - fail(observer, Status.UNAVAILABLE); - return; - } catch (DataAccessException | org.springframework.dao.DataAccessException failure) { - fail(observer, hasConnectionFailureSqlState(failure) ? Status.UNAVAILABLE : Status.INTERNAL); - return; - } catch (RuntimeException incompleteOrConflicting) { - fail(observer, Status.FAILED_PRECONDITION); + } catch (RuntimeException responseEncodingFailure) { + fail(observer, Status.INTERNAL); return; } diff --git a/services/game-session-service/src/main/resources/db/migration/V1037__single_first_new_issuer_release_guard.sql b/services/game-session-service/src/main/resources/db/migration/V1037__single_first_new_issuer_release_guard.sql new file mode 100644 index 0000000000..a7abc5db12 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1037__single_first_new_issuer_release_guard.sql @@ -0,0 +1,11 @@ +-- Keep the V1035 reservation and Account-obligation guards as the single authorities for +-- proof-backed first-NEW release. V1036's reservation trigger duplicated the same release +-- predicate, and its Account-obligation trigger duplicated the V1035 deferred source check. +-- [jooq ignore start] +DROP TRIGGER game_session_first_new_issuer_release_reservation + ON game_session_canonical_issuer_partition_reservation; +DROP FUNCTION require_first_new_issuer_release_reservation(); + +DROP TRIGGER game_session_first_new_issuer_release_account_atomic + ON game_session_canonical_binding_account_index_obligation; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V1038__canonical_issuer_partition_physical_retirement.sql b/services/game-session-service/src/main/resources/db/migration/V1038__canonical_issuer_partition_physical_retirement.sql new file mode 100644 index 0000000000..79f635af10 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1038__canonical_issuer_partition_physical_retirement.sql @@ -0,0 +1,565 @@ +-- One opaque current Redis mutation revision per installed issuer partition. The initial value is +-- created only by the existing positive bootstrap owner; every later value is owner-allocated and +-- advanced atomically with one original physical mutation. Historical mutation and retirement +-- receipts stay in PostgreSQL while retired capacity fields leave the bounded Redis projection. + +CREATE TABLE game_session_canonical_issuer_partition_mutation_head ( + issuer_id character varying(64) NOT NULL, + partition_id numeric NOT NULL, + bootstrap_operation_id uuid NOT NULL, + initial_revision uuid NOT NULL, + current_revision uuid NOT NULL, + state character varying(32) NOT NULL, + pending_mutation_id uuid, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT pk_gs_issuer_partition_mutation_head PRIMARY KEY (issuer_id, partition_id), + CONSTRAINT uq_gs_issuer_partition_mutation_head_initial UNIQUE (initial_revision), + CONSTRAINT fk_gs_issuer_partition_mutation_head_bootstrap + FOREIGN KEY (bootstrap_operation_id) + REFERENCES game_session_canonical_issuer_layout_bootstrap_intent (operation_id), + CONSTRAINT chk_gs_issuer_partition_mutation_head CHECK ( + issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND partition_id >= 0 + AND bootstrap_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND initial_revision <> '00000000-0000-0000-0000-000000000000'::uuid + AND current_revision <> '00000000-0000-0000-0000-000000000000'::uuid + AND state IN ('INITIAL_INSTALL_PENDING', 'CURRENT') + AND ((state = 'INITIAL_INSTALL_PENDING' + AND current_revision = initial_revision + AND pending_mutation_id IS NULL) + OR state = 'CURRENT') + AND (pending_mutation_id IS NULL + OR pending_mutation_id <> '00000000-0000-0000-0000-000000000000'::uuid) + ) +); + +-- Preserve the already-retained V1033 audit rows as legacy proof. New proof rows bind the exact +-- initial physical revision installed in Redis for this bootstrap partition. +ALTER TABLE game_session_canonical_issuer_bootstrap_partition_proof + ADD COLUMN initial_physical_mutation_revision uuid; + +ALTER TABLE game_session_canonical_issuer_bootstrap_partition_proof + DROP CONSTRAINT chk_gs_issuer_bootstrap_partition_proof; + +ALTER TABLE game_session_canonical_issuer_bootstrap_partition_proof + ADD CONSTRAINT chk_gs_issuer_bootstrap_partition_proof CHECK ( + issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND bootstrap_operation_fence > 0 + AND bootstrap_coverage_fence > 0 + AND bootstrap_operation_fence <> bootstrap_coverage_fence + AND issuer_inventory_snapshot_revision > 0 + AND layout_version > 0 + AND partition_count > 0 + AND partition_capacity > 0 + AND mapping_identity = 'bindingRef/v1;sha256-u256-mod/v1' + AND octet_length(layout_descriptor_bytes) > 0 + AND layout_descriptor_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(source_checkpoint_bytes) > 0 + AND source_checkpoint_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((source_event_bytes IS NULL AND source_event_digest IS NULL) + OR (source_event_bytes IS NOT NULL + AND octet_length(source_event_bytes) > 0 + AND source_event_digest IS NOT NULL + AND source_event_digest ~ '^sha256:[0-9a-f]{64}$')) + AND octet_length(incarnation_bytes) > 0 + AND incarnation_digest ~ '^sha256:[0-9a-f]{64}$' + AND partition_id >= 0 + AND partition_id < partition_count + AND partition_id = floor(partition_id) + AND octet_length(exact_metadata_bytes) BETWEEN 1 AND 65536 + AND octet_length(exact_physical_field_set_bytes) BETWEEN 1 AND 17825792 + AND exact_physical_field_set_digest ~ '^sha256:[0-9a-f]{64}$' + AND physical_field_count > 0 + AND physical_reservation_count >= 0 + AND physical_binding_count >= 0 + AND physical_counted_capacity_count >= 0 + AND physical_counted_capacity_count <= partition_capacity + AND ((initial_physical_mutation_revision IS NULL + AND physical_field_count = 1 + physical_reservation_count + physical_binding_count) + OR (initial_physical_mutation_revision IS NOT NULL + AND initial_physical_mutation_revision <> '00000000-0000-0000-0000-000000000000'::uuid + AND physical_field_count = 2 + physical_reservation_count + physical_binding_count)) + AND planned_aggregate_capacity_count >= 0 + AND planned_aggregate_capacity_count <= partition_count * partition_capacity + AND proof_state = 'EXACT_PHYSICAL_READBACK' + ); + +CREATE TABLE game_session_canonical_issuer_partition_mutation ( + mutation_id uuid NOT NULL, + issuer_id character varying(64) NOT NULL, + partition_id numeric NOT NULL, + mutation_kind character varying(16) NOT NULL, + owner_operation_id uuid NOT NULL, + expected_revision uuid NOT NULL, + successor_revision uuid NOT NULL, + exact_intended_change_bytes bytea NOT NULL, + exact_intended_change_digest character varying(71) NOT NULL, + status character varying(32) NOT NULL, + exact_readback_field_set_bytes bytea, + exact_readback_field_set_digest character varying(71), + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + completed_at timestamp with time zone, + + CONSTRAINT pk_gs_issuer_partition_mutation PRIMARY KEY (mutation_id), + CONSTRAINT uq_gs_issuer_partition_mutation_operation + UNIQUE (issuer_id, partition_id, mutation_kind, owner_operation_id), + CONSTRAINT uq_gs_issuer_partition_mutation_successor UNIQUE (successor_revision), + CONSTRAINT uq_gs_issuer_partition_mutation_identity + UNIQUE (issuer_id, partition_id, mutation_id), + CONSTRAINT uq_gs_issuer_partition_mutation_expected + UNIQUE (issuer_id, partition_id, expected_revision), + CONSTRAINT fk_gs_issuer_partition_mutation_head + FOREIGN KEY (issuer_id, partition_id) + REFERENCES game_session_canonical_issuer_partition_mutation_head (issuer_id, partition_id), + CONSTRAINT chk_gs_issuer_partition_mutation CHECK ( + mutation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND partition_id >= 0 + AND mutation_kind IN ('ADD_CAPACITY', 'ADD_BINDING', 'RELEASE', 'RETIRE') + AND owner_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND expected_revision <> '00000000-0000-0000-0000-000000000000'::uuid + AND successor_revision <> '00000000-0000-0000-0000-000000000000'::uuid + AND successor_revision <> expected_revision + AND octet_length(exact_intended_change_bytes) BETWEEN 1 AND 262144 + AND exact_intended_change_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((status = 'PENDING_PHYSICAL_PROOF' + AND exact_readback_field_set_bytes IS NULL + AND exact_readback_field_set_digest IS NULL + AND completed_at IS NULL) + OR (status = 'COMMITTED' + AND exact_readback_field_set_bytes IS NOT NULL + AND octet_length(exact_readback_field_set_bytes) BETWEEN 1 AND 17825792 + AND exact_readback_field_set_digest ~ '^sha256:[0-9a-f]{64}$' + AND completed_at IS NOT NULL)) + ) +); + +CREATE INDEX ix_gs_issuer_partition_mutation_revision_expected + ON game_session_canonical_issuer_partition_mutation (expected_revision); + +ALTER TABLE game_session_canonical_issuer_partition_mutation_head + ADD CONSTRAINT fk_gs_issuer_partition_mutation_head_pending + FOREIGN KEY (issuer_id, partition_id, pending_mutation_id) + REFERENCES game_session_canonical_issuer_partition_mutation + (issuer_id, partition_id, mutation_id) + DEFERRABLE INITIALLY DEFERRED; + +CREATE TABLE game_session_canonical_issuer_binding_local_retirement ( + retirement_operation_id uuid NOT NULL, + issuer_id character varying(64) NOT NULL, + partition_id numeric NOT NULL, + release_operation_id uuid NOT NULL, + physical_mutation_id uuid NOT NULL, + original_local_operation_id uuid NOT NULL, + transition_id uuid NOT NULL, + reservation_id uuid NOT NULL, + binding_ref bytea NOT NULL, + original_reservation_fence uuid NOT NULL, + original_issuer_coverage_operation_id uuid NOT NULL, + original_issuer_coverage_operation_fence numeric NOT NULL, + original_coverage_fence numeric NOT NULL, + original_inventory_snapshot_revision numeric NOT NULL, + original_reservation_inventory_revision numeric NOT NULL, + anchor_issuer_coverage_operation_id uuid NOT NULL, + anchor_operation_fence numeric NOT NULL, + anchor_coverage_fence numeric NOT NULL, + anchor_inventory_snapshot_revision numeric NOT NULL, + release_source_inventory_revision numeric NOT NULL, + release_completion_inventory_revision numeric NOT NULL, + original_member_value_bytes bytea NOT NULL, + original_member_value_digest character varying(71) NOT NULL, + released_member_value_bytes bytea NOT NULL, + released_member_value_digest character varying(71) NOT NULL, + expected_revision uuid NOT NULL, + successor_revision uuid NOT NULL, + exact_intended_change_bytes bytea NOT NULL, + exact_intended_change_digest character varying(71) NOT NULL, + status character varying(32) NOT NULL, + exact_absence_readback_field_set_bytes bytea, + exact_absence_readback_field_set_digest character varying(71), + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + completed_at timestamp with time zone, + + CONSTRAINT pk_gs_issuer_binding_local_retirement PRIMARY KEY (retirement_operation_id), + CONSTRAINT uq_gs_issuer_binding_local_retirement_release UNIQUE (release_operation_id), + CONSTRAINT uq_gs_issuer_binding_local_retirement_successor UNIQUE (successor_revision), + CONSTRAINT fk_gs_issuer_binding_local_retirement_release + FOREIGN KEY (release_operation_id) + REFERENCES game_session_canonical_issuer_binding_local_release_operation (operation_id), + CONSTRAINT fk_gs_issuer_binding_local_retirement_original + FOREIGN KEY (original_local_operation_id) + REFERENCES game_session_canonical_issuer_binding_local_operation (operation_id), + CONSTRAINT fk_gs_issuer_binding_local_retirement_mutation + FOREIGN KEY (issuer_id, partition_id, physical_mutation_id) + REFERENCES game_session_canonical_issuer_partition_mutation + (issuer_id, partition_id, mutation_id), + CONSTRAINT chk_gs_issuer_binding_local_retirement CHECK ( + retirement_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND partition_id >= 0 + AND release_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND original_local_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND transition_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND reservation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND octet_length(binding_ref) BETWEEN 1 AND 6144 + AND original_reservation_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND original_issuer_coverage_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND original_issuer_coverage_operation_fence > 0 + AND original_coverage_fence > 0 + AND original_inventory_snapshot_revision > 0 + AND original_reservation_inventory_revision > 0 + AND anchor_issuer_coverage_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND anchor_operation_fence > 0 + AND anchor_coverage_fence > 0 + AND anchor_inventory_snapshot_revision > 0 + AND release_source_inventory_revision > 0 + AND release_completion_inventory_revision > release_source_inventory_revision + AND octet_length(original_member_value_bytes) BETWEEN 1 AND 65536 + AND original_member_value_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(released_member_value_bytes) BETWEEN 1 AND 65536 + AND released_member_value_digest ~ '^sha256:[0-9a-f]{64}$' + AND expected_revision <> '00000000-0000-0000-0000-000000000000'::uuid + AND successor_revision <> '00000000-0000-0000-0000-000000000000'::uuid + AND successor_revision <> expected_revision + AND octet_length(exact_intended_change_bytes) BETWEEN 1 AND 262144 + AND exact_intended_change_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((status = 'PENDING_PHYSICAL_PROOF' + AND exact_absence_readback_field_set_bytes IS NULL + AND exact_absence_readback_field_set_digest IS NULL + AND completed_at IS NULL) + OR (status = 'RETIRED' + AND exact_absence_readback_field_set_bytes IS NOT NULL + AND octet_length(exact_absence_readback_field_set_bytes) BETWEEN 1 AND 17825792 + AND exact_absence_readback_field_set_digest ~ '^sha256:[0-9a-f]{64}$' + AND completed_at IS NOT NULL)) + ) +); + +CREATE INDEX ix_gs_issuer_partition_mutation_pending + ON game_session_canonical_issuer_partition_mutation (issuer_id, partition_id, status); + +CREATE INDEX ix_gs_issuer_local_retirement_status + ON game_session_canonical_issuer_binding_local_retirement (issuer_id, status, partition_id); + +-- The intended mutation and its identity are immutable. Only a pending proof may acquire one exact +-- independently read complete field-set receipt; a committed physical mutation never changes. +-- [jooq ignore start] +CREATE FUNCTION guard_canonical_issuer_partition_mutation_history() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.status <> 'PENDING_PHYSICAL_PROOF' + OR NOT EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_partition_mutation_head head + WHERE head.issuer_id = NEW.issuer_id + AND head.partition_id = NEW.partition_id + AND head.state = 'CURRENT' + AND head.current_revision = NEW.expected_revision + AND head.pending_mutation_id IS NULL) THEN + RAISE EXCEPTION 'Issuer partition mutation requires its exact current unreserved revision' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Issuer partition mutation history is immutable'; + END IF; + IF (to_jsonb(NEW) - 'status' - 'exact_readback_field_set_bytes' + - 'exact_readback_field_set_digest' - 'completed_at') + IS DISTINCT FROM + (to_jsonb(OLD) - 'status' - 'exact_readback_field_set_bytes' + - 'exact_readback_field_set_digest' - 'completed_at') THEN + RAISE EXCEPTION 'Issuer partition mutation intent is immutable'; + END IF; + IF OLD.status <> 'PENDING_PHYSICAL_PROOF' + OR NEW.status <> 'COMMITTED' + OR NEW.exact_readback_field_set_bytes IS NULL + OR NEW.exact_readback_field_set_digest IS NULL + OR NEW.completed_at IS NULL THEN + RAISE EXCEPTION 'Issuer partition mutation may only commit one exact readback'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_gs_issuer_partition_mutation_history + BEFORE INSERT OR UPDATE OR DELETE ON game_session_canonical_issuer_partition_mutation + FOR EACH ROW EXECUTE FUNCTION guard_canonical_issuer_partition_mutation_history(); + +CREATE FUNCTION guard_canonical_issuer_partition_revision_uniqueness() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_partition_mutation_head head + WHERE head.initial_revision = NEW.successor_revision + OR (head.initial_revision = NEW.expected_revision + AND (head.issuer_id, head.partition_id) <> (NEW.issuer_id, NEW.partition_id))) + OR EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_partition_mutation mutation + WHERE mutation.expected_revision = NEW.successor_revision + OR mutation.successor_revision = NEW.successor_revision + OR ((mutation.expected_revision = NEW.expected_revision + OR mutation.successor_revision = NEW.expected_revision) + AND (mutation.issuer_id, mutation.partition_id) <> (NEW.issuer_id, NEW.partition_id))) THEN + RAISE EXCEPTION 'Issuer partition physical revisions are never reused'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_gs_issuer_partition_revision_uniqueness + BEFORE INSERT ON game_session_canonical_issuer_partition_mutation + FOR EACH ROW EXECUTE FUNCTION guard_canonical_issuer_partition_revision_uniqueness(); + +CREATE FUNCTION guard_canonical_issuer_partition_initial_revision_uniqueness() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_partition_mutation mutation + WHERE mutation.expected_revision = NEW.initial_revision + OR mutation.successor_revision = NEW.initial_revision) + OR EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_partition_mutation_head head + WHERE head.initial_revision = NEW.initial_revision + AND (head.issuer_id, head.partition_id) <> (NEW.issuer_id, NEW.partition_id)) THEN + RAISE EXCEPTION 'Issuer partition initial physical revision is reused'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_gs_issuer_partition_initial_revision_uniqueness + BEFORE INSERT ON game_session_canonical_issuer_partition_mutation_head + FOR EACH ROW EXECUTE FUNCTION guard_canonical_issuer_partition_initial_revision_uniqueness(); + +CREATE FUNCTION guard_canonical_issuer_partition_mutation_head() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.state <> 'INITIAL_INSTALL_PENDING' + OR NEW.current_revision <> NEW.initial_revision + OR NEW.pending_mutation_id IS NOT NULL + OR EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_bootstrap_partition_proof proof + WHERE proof.bootstrap_operation_id = NEW.bootstrap_operation_id + AND proof.partition_id = NEW.partition_id) + OR EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_installed_anchor anchor + WHERE anchor.issuer_id = NEW.issuer_id + AND anchor.bootstrap_operation_id = NEW.bootstrap_operation_id) THEN + RAISE EXCEPTION 'Initial issuer partition revision requires an uninstalled bootstrap owner'; + END IF; + RETURN NEW; + END IF; + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Issuer partition mutation head is retained'; + END IF; + IF (to_jsonb(NEW) - 'state' - 'current_revision' - 'pending_mutation_id') + IS DISTINCT FROM + (to_jsonb(OLD) - 'state' - 'current_revision' - 'pending_mutation_id') THEN + RAISE EXCEPTION 'Issuer partition mutation-head identity is immutable'; + END IF; + IF OLD.state = 'INITIAL_INSTALL_PENDING' THEN + IF NEW.state <> 'CURRENT' + OR NEW.current_revision <> OLD.initial_revision + OR NEW.pending_mutation_id IS NOT NULL + OR NOT EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_bootstrap_partition_proof proof + WHERE proof.bootstrap_operation_id = OLD.bootstrap_operation_id + AND proof.issuer_id = OLD.issuer_id + AND proof.partition_id = OLD.partition_id + AND proof.initial_physical_mutation_revision = OLD.initial_revision + AND proof.proof_state = 'EXACT_PHYSICAL_READBACK') THEN + RAISE EXCEPTION 'Initial issuer partition revision requires positive bootstrap proof'; + END IF; + ELSIF OLD.pending_mutation_id IS NULL THEN + IF NEW.state <> OLD.state + OR NEW.pending_mutation_id IS NULL + OR NEW.current_revision <> OLD.current_revision THEN + RAISE EXCEPTION 'Issuer partition mutation requires one durable pending operation'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_partition_mutation mutation + WHERE mutation.mutation_id = NEW.pending_mutation_id + AND mutation.issuer_id = OLD.issuer_id + AND mutation.partition_id = OLD.partition_id + AND mutation.status = 'PENDING_PHYSICAL_PROOF' + AND mutation.expected_revision = OLD.current_revision) THEN + RAISE EXCEPTION 'Issuer partition pending head lacks its exact prepared mutation'; + END IF; + ELSE + IF NEW.state <> OLD.state + OR NEW.pending_mutation_id IS NOT NULL + OR NEW.current_revision = OLD.current_revision THEN + RAISE EXCEPTION 'Issuer partition revision requires its exact pending operation'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_partition_mutation mutation + WHERE mutation.mutation_id = OLD.pending_mutation_id + AND mutation.issuer_id = OLD.issuer_id + AND mutation.partition_id = OLD.partition_id + AND mutation.status = 'COMMITTED' + AND mutation.expected_revision = OLD.current_revision + AND mutation.successor_revision = NEW.current_revision) THEN + RAISE EXCEPTION 'Issuer partition revision does not match its committed mutation'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_gs_issuer_partition_mutation_head + BEFORE INSERT OR UPDATE OR DELETE ON game_session_canonical_issuer_partition_mutation_head + FOR EACH ROW EXECUTE FUNCTION guard_canonical_issuer_partition_mutation_head(); + +CREATE FUNCTION guard_canonical_issuer_bootstrap_partition_proof_initial_revision() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.initial_physical_mutation_revision IS NULL + OR NEW.initial_physical_mutation_revision = '00000000-0000-0000-0000-000000000000'::uuid + OR NOT EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_partition_mutation_head head + WHERE head.issuer_id = NEW.issuer_id + AND head.partition_id = NEW.partition_id + AND head.bootstrap_operation_id = NEW.bootstrap_operation_id + AND head.initial_revision = NEW.initial_physical_mutation_revision) THEN + RAISE EXCEPTION 'New issuer partition proof requires its exact SQL-installed initial revision' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_gs_issuer_bootstrap_partition_proof_initial_revision + BEFORE INSERT ON game_session_canonical_issuer_bootstrap_partition_proof + FOR EACH ROW EXECUTE FUNCTION guard_canonical_issuer_bootstrap_partition_proof_initial_revision(); + +CREATE FUNCTION guard_canonical_issuer_binding_local_retirement() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_issuer_binding_local_release_operation release + WHERE release.operation_id = NEW.release_operation_id + AND release.issuer_id = NEW.issuer_id + AND release.partition_id = NEW.partition_id + AND release.original_local_operation_id = NEW.original_local_operation_id + AND release.transition_id = NEW.transition_id + AND release.reservation_id = NEW.reservation_id + AND release.binding_ref = NEW.binding_ref + AND release.original_reservation_fence = NEW.original_reservation_fence + AND release.original_issuer_coverage_operation_id = NEW.original_issuer_coverage_operation_id + AND release.original_issuer_coverage_operation_fence = NEW.original_issuer_coverage_operation_fence + AND release.original_coverage_fence = NEW.original_coverage_fence + AND release.original_inventory_snapshot_revision = NEW.original_inventory_snapshot_revision + AND release.original_reservation_inventory_revision = NEW.original_reservation_inventory_revision + AND release.anchor_issuer_coverage_operation_id = NEW.anchor_issuer_coverage_operation_id + AND release.anchor_operation_fence = NEW.anchor_operation_fence + AND release.anchor_coverage_fence = NEW.anchor_coverage_fence + AND release.anchor_inventory_snapshot_revision = NEW.anchor_inventory_snapshot_revision + AND release.source_inventory_revision = NEW.release_source_inventory_revision + AND release.completion_inventory_revision = NEW.release_completion_inventory_revision + AND release.original_member_value_bytes = NEW.original_member_value_bytes + AND release.original_member_value_digest = NEW.original_member_value_digest + AND release.released_member_value_bytes = NEW.released_member_value_bytes + AND release.released_member_value_digest = NEW.released_member_value_digest + AND release.status = 'RELEASED') THEN + RAISE EXCEPTION 'Issuer retirement must reference the exact committed release receipt' + USING ERRCODE = '23514'; + END IF; + IF NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_issuer_partition_mutation mutation + WHERE mutation.mutation_id = NEW.physical_mutation_id + AND mutation.issuer_id = NEW.issuer_id + AND mutation.partition_id = NEW.partition_id + AND mutation.mutation_kind = 'RETIRE' + AND mutation.owner_operation_id = NEW.retirement_operation_id + AND mutation.expected_revision = NEW.expected_revision + AND mutation.successor_revision = NEW.successor_revision + AND mutation.exact_intended_change_bytes = NEW.exact_intended_change_bytes + AND mutation.exact_intended_change_digest = NEW.exact_intended_change_digest + AND mutation.status = 'PENDING_PHYSICAL_PROOF') THEN + RAISE EXCEPTION 'Issuer retirement lacks its exact pending physical mutation' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Issuer local retirement history is immutable'; + END IF; + IF (to_jsonb(NEW) - 'status' - 'exact_absence_readback_field_set_bytes' + - 'exact_absence_readback_field_set_digest' - 'completed_at') + IS DISTINCT FROM + (to_jsonb(OLD) - 'status' - 'exact_absence_readback_field_set_bytes' + - 'exact_absence_readback_field_set_digest' - 'completed_at') THEN + RAISE EXCEPTION 'Issuer local retirement intent is immutable'; + END IF; + IF OLD.status <> 'PENDING_PHYSICAL_PROOF' + OR NEW.status <> 'RETIRED' + OR NEW.exact_absence_readback_field_set_bytes IS NULL + OR NEW.exact_absence_readback_field_set_digest IS NULL + OR NEW.completed_at IS NULL THEN + RAISE EXCEPTION 'Issuer local retirement may only commit one exact absence readback'; + END IF; + IF NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_issuer_partition_mutation mutation + WHERE mutation.mutation_id = NEW.physical_mutation_id + AND mutation.issuer_id = NEW.issuer_id + AND mutation.partition_id = NEW.partition_id + AND mutation.mutation_kind = 'RETIRE' + AND mutation.owner_operation_id = NEW.retirement_operation_id + AND mutation.expected_revision = NEW.expected_revision + AND mutation.successor_revision = NEW.successor_revision + AND mutation.exact_intended_change_bytes = NEW.exact_intended_change_bytes + AND mutation.exact_intended_change_digest = NEW.exact_intended_change_digest + AND mutation.status = 'COMMITTED' + AND mutation.exact_readback_field_set_bytes = NEW.exact_absence_readback_field_set_bytes + AND mutation.exact_readback_field_set_digest = NEW.exact_absence_readback_field_set_digest) THEN + RAISE EXCEPTION 'Issuer retirement needs its exact committed physical absence proof'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_gs_issuer_binding_local_retirement + BEFORE INSERT OR UPDATE OR DELETE ON game_session_canonical_issuer_binding_local_retirement + FOR EACH ROW EXECUTE FUNCTION guard_canonical_issuer_binding_local_retirement(); +-- Retained initial revision, mutation and retirement receipts cannot be bypassed by TRUNCATE. +CREATE FUNCTION reject_canonical_issuer_physical_history_truncate() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Issuer physical mutation and retirement history is immutable' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER trg_gs_issuer_partition_mutation_head_no_truncate + BEFORE TRUNCATE ON game_session_canonical_issuer_partition_mutation_head + FOR EACH STATEMENT EXECUTE FUNCTION reject_canonical_issuer_physical_history_truncate(); + +CREATE TRIGGER trg_gs_issuer_partition_mutation_no_truncate + BEFORE TRUNCATE ON game_session_canonical_issuer_partition_mutation + FOR EACH STATEMENT EXECUTE FUNCTION reject_canonical_issuer_physical_history_truncate(); + +CREATE TRIGGER trg_gs_issuer_local_retirement_no_truncate + BEFORE TRUNCATE ON game_session_canonical_issuer_binding_local_retirement + FOR EACH STATEMENT EXECUTE FUNCTION reject_canonical_issuer_physical_history_truncate(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-add.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-add.lua index 4a313dc707..fb3cd63d43 100644 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-add.lua +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-add.lua @@ -2,6 +2,7 @@ -- qualifies, its binding member. KEYS[1] is the only issuer partition hash. local keyPrefix = 'session:game:index:issuer:' local metadataField = '!issuer-partition-bootstrap/v1' +local mutationRevisionField = '!issuer-partition-mutation-revision/v1' local capacityPrefix = '!issuer-reservation-capacity/v1:' local maxDecimalBytes = 256 local maxBindingRefBytes = 6144 @@ -9,6 +10,8 @@ local maxMemberValueBytes = 65536 local maxMetadataBytes = 65536 local maxMemberOperations = 256 local maxHashFields = 1025 +local maxPhysicalFields = 1026 +local maxBaselineFields = 513 local maxHashBytes = 16777216 local function uuid(value) @@ -60,7 +63,9 @@ local function canonicalBindingRef(bytes, member) local domain, offset = readSegment(bytes, 1) if domain ~= 'bindingRef/v1' or not offset then return false end local tenant, afterTenant = readSegment(bytes, offset) + if not tenant or not afterTenant then return false end local instance, afterInstance = readSegment(bytes, afterTenant) + if not instance or not afterInstance then return false end local session, afterSession = readSegment(bytes, afterInstance) if not tenant or not instance or not session or not afterSession or afterSession ~= #bytes + 1 then return false @@ -167,7 +172,7 @@ if issuerId ~= 'firemud-account-service' or not nonnegative(partitionId) or not positive(partitionCount) or not positive(partitionCapacity) or not positive(baselineCountText) then return -2 end local baselineCount = tonumber(baselineCountText) -if not baselineCount or baselineCount > maxHashFields then return -2 end +if not baselineCount or baselineCount > maxBaselineFields then return -2 end local cursor = 6 local baseline = {} @@ -281,21 +286,29 @@ local seenBindings = {} local registeredOperations = {} local localCapacity = 0 local localBindingCount = 0 -local targetOperationId = ARGV[cursor + operationCount * 6] -local targetReservationId = ARGV[cursor + operationCount * 6 + 1] -local targetBindingRef = ARGV[cursor + operationCount * 6 + 2] -local targetMemberBytes = ARGV[cursor + operationCount * 6 + 3] -local targetBindingPresent = ARGV[cursor + operationCount * 6 + 4] -local plannedPartitionCapacity = ARGV[cursor + operationCount * 6 + 5] -local plannedAggregateCapacity = ARGV[cursor + operationCount * 6 + 6] -local aggregateBound = ARGV[cursor + operationCount * 6 + 7] +local targetOperationId = ARGV[cursor + operationCount * 8] +local targetReservationId = ARGV[cursor + operationCount * 8 + 1] +local targetBindingRef = ARGV[cursor + operationCount * 8 + 2] +local targetMemberBytes = ARGV[cursor + operationCount * 8 + 3] +local targetBindingPresent = ARGV[cursor + operationCount * 8 + 4] +local plannedPartitionCapacity = ARGV[cursor + operationCount * 8 + 5] +local plannedAggregateCapacity = ARGV[cursor + operationCount * 8 + 6] +local aggregateBound = ARGV[cursor + operationCount * 8 + 7] +local expectedRevision = ARGV[cursor + operationCount * 8 + 8] +local successorRevision = ARGV[cursor + operationCount * 8 + 9] +local mutationKind = ARGV[cursor + operationCount * 8 + 10] if not uuid(targetOperationId) or not uuid(targetReservationId) or type(targetBindingRef) ~= 'string' or type(targetMemberBytes) ~= 'string' or (targetBindingPresent ~= '0' and targetBindingPresent ~= '1') or not nonnegative(plannedPartitionCapacity) or not nonnegative(plannedAggregateCapacity) or not positive(aggregateBound) - or #ARGV ~= cursor + operationCount * 6 + 7 then return -2 end + or not uuid(expectedRevision) or not uuid(successorRevision) + or expectedRevision == successorRevision + or (mutationKind ~= 'ADD_CAPACITY' and mutationKind ~= 'ADD_BINDING') + or (mutationKind == 'ADD_CAPACITY' and targetBindingPresent ~= '0') + or (mutationKind == 'ADD_BINDING' and targetBindingPresent ~= '1') + or #ARGV ~= cursor + operationCount * 8 + 10 then return -2 end local targetFound = false local position = cursor @@ -306,10 +319,15 @@ for index = 1, operationCount do local memberBytes = ARGV[position + 3] local bindingPresent = ARGV[position + 4] local countsCapacity = ARGV[position + 5] - position = position + 6 + local capacityMustBePresent = ARGV[position + 6] + local bindingMustBePresent = ARGV[position + 7] + position = position + 8 if not uuid(operationId) or not uuid(reservationId) or (bindingPresent ~= '0' and bindingPresent ~= '1') or (countsCapacity ~= '0' and countsCapacity ~= '1') + or (capacityMustBePresent ~= '0' and capacityMustBePresent ~= '1') + or (bindingMustBePresent ~= '0' and bindingMustBePresent ~= '1') + or (bindingMustBePresent == '1' and bindingPresent ~= '1') or type(memberBytes) ~= 'string' or #memberBytes == 0 or #memberBytes > maxMemberValueBytes or seenOperationIds[operationId] or seenReservationIds[reservationId] or seenBindings[bindingRef] then return -2 end @@ -322,10 +340,13 @@ for index = 1, operationCount do seenReservationIds[reservationId] = true seenBindings[bindingRef] = true registeredOperations[#registeredOperations + 1] = { + operationId = operationId, bindingRef = bindingRef, reservationId = reservationId, memberBytes = memberBytes, - bindingPresent = bindingPresent + bindingPresent = bindingPresent, + capacityMustBePresent = capacityMustBePresent, + bindingMustBePresent = bindingMustBePresent } if countsCapacity == '1' then localCapacity = localCapacity + 1 end local capacityField = capacityPrefix .. reservationId @@ -353,7 +374,7 @@ if targetBindingPresent == '1' and allowed[targetBindingRef] ~= targetMemberByte local kind = redis.call('TYPE', KEYS[1]).ok if kind ~= 'hash' or redis.call('PTTL', KEYS[1]) ~= -1 then return -1 end local actual = redis.call('HGETALL', KEYS[1]) -if #actual % 2 ~= 0 or #actual / 2 > maxHashFields then return -1 end +if #actual % 2 ~= 0 or #actual / 2 > maxPhysicalFields then return -1 end local actualCapacityCount = 0 local actualReservationCount = 0 local actualBindingCount = 0 @@ -366,13 +387,19 @@ for index = 1, #actual, 2 do totalActualBytes = totalActualBytes + #field + #valueBytes if totalActualBytes > maxHashBytes then return -1 end local expected = allowed[field] - if expected == nil or expected ~= valueBytes then return -1 end - if string.sub(field, 1, #capacityPrefix) == capacityPrefix then + if field == mutationRevisionField then + if valueBytes ~= expectedRevision and valueBytes ~= successorRevision then return -1 end + elseif expected == nil or expected ~= valueBytes then + return -1 + end + if field == mutationRevisionField then + -- The separately validated fence is not a reservation or binding field. + elseif string.sub(field, 1, #capacityPrefix) == capacityPrefix then local decodedOk, member = pcall(cjson.decode, valueBytes) if not decodedOk or type(member) ~= 'table' or type(member.reservation) ~= 'table' then return -1 end actualReservationCount = actualReservationCount + 1 if member.reservation.lifecycle ~= 'RELEASED' then actualCapacityCount = actualCapacityCount + 1 end - elseif field ~= metadataField then + elseif field ~= metadataField and field ~= mutationRevisionField then actualBindingCount = actualBindingCount + 1 end end @@ -393,14 +420,30 @@ if actualCapacityCount > tonumber(plannedPartitionCapacity) local capacityBefore = redis.call('HGET', KEYS[1], targetCapacityField) local bindingBefore = redis.call('HGET', KEYS[1], targetBindingRef) -if capacityBefore ~= nil and capacityBefore ~= false and capacityBefore ~= targetMemberBytes then return -1 end -if bindingBefore ~= nil and bindingBefore ~= false and targetBindingPresent == '1' - and bindingBefore ~= targetMemberBytes then return -1 end -if targetBindingPresent == '0' and bindingBefore ~= nil and bindingBefore ~= false then return -1 end -local changedCapacity = capacityBefore == false or capacityBefore == nil -local changedBinding = targetBindingPresent == '1' and (bindingBefore == false or bindingBefore == nil) -if changedCapacity then redis.call('HSET', KEYS[1], targetCapacityField, targetMemberBytes) end -if changedBinding then redis.call('HSET', KEYS[1], targetBindingRef, targetMemberBytes) end -if changedBinding then return 2 end -if changedCapacity then return 1 end -return 3 +local revisionBefore = actualFields[mutationRevisionField] +for _, operation in ipairs(registeredOperations) do + if operation.operationId ~= targetOperationId or revisionBefore ~= successorRevision then + local capacity = actualFields[capacityPrefix .. operation.reservationId] + local binding = actualFields[operation.bindingRef] + if operation.capacityMustBePresent == '1' and capacity ~= operation.memberBytes then return -1 end + if operation.bindingMustBePresent == '1' and binding ~= operation.memberBytes then return -1 end + end +end +if revisionBefore == successorRevision then + if capacityBefore ~= targetMemberBytes + or (targetBindingPresent == '1' and bindingBefore ~= targetMemberBytes) + or (targetBindingPresent == '0' and bindingBefore ~= nil and bindingBefore ~= false) then return -1 end + return 3 +end +if revisionBefore ~= expectedRevision then return -1 end +if mutationKind == 'ADD_CAPACITY' then + if capacityBefore ~= nil and capacityBefore ~= false then return -1 end + if bindingBefore ~= nil and bindingBefore ~= false then return -1 end + redis.call('HSET', KEYS[1], mutationRevisionField, successorRevision, + targetCapacityField, targetMemberBytes) + return 1 +end +if capacityBefore ~= targetMemberBytes or (bindingBefore ~= nil and bindingBefore ~= false) then return -1 end +redis.call('HSET', KEYS[1], mutationRevisionField, successorRevision, + targetBindingRef, targetMemberBytes) +return 2 diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-release.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-release.lua index 17a0aa2aa4..7847488920 100644 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-release.lua +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-release.lua @@ -2,11 +2,14 @@ -- KEYS[1] is the sole canonical issuer partition hash. local keyPrefix = 'session:game:index:issuer:' local metadataField = '!issuer-partition-bootstrap/v1' +local mutationRevisionField = '!issuer-partition-mutation-revision/v1' local capacityPrefix = '!issuer-reservation-capacity/v1:' local maxMemberValueBytes = 65536 local maxMetadataBytes = 65536 local maxMemberOperations = 256 local maxHashFields = 1025 +local maxPhysicalFields = 1026 +local maxBaselineFields = 513 local maxHashBytes = 16777216 local function uuid(value) @@ -167,10 +170,14 @@ local issuerId = ARGV[1] local partitionId = ARGV[2] local partitionCount = ARGV[3] local partitionCapacity = ARGV[4] -local baselineCount = tonumber(ARGV[5]) +local baselineCountText = ARGV[5] if issuerId ~= 'firemud-account-service' or not nonnegative(partitionId) or not positive(partitionCount) or not positive(partitionCapacity) - or not baselineCount or baselineCount < 1 or baselineCount > maxHashFields then return -2 end + or not positive(baselineCountText) then return -2 end +local baselineCount = tonumber(baselineCountText) +if not baselineCount or baselineCount ~= baselineCount + or baselineCount == math.huge or baselineCount == -math.huge + or baselineCount < 1 or baselineCount > maxBaselineFields then return -2 end local cursor = 6 local baseline = {} local baselineCapacity = 0 @@ -240,7 +247,10 @@ local partition = {partitionId=partitionId, partitionCount=partitionCount, parti for field, valueBytes in pairs(baseline) do if field ~= metadataField then local ok, member = pcall(cjson.decode, valueBytes) - if not ok or not memberShape(member, issuerId, partition, metadata, nil, + if not ok or type(member) ~= 'table' + or type(member.memberOperation) ~= 'table' + or type(member.reservation) ~= 'table' then return -2 end + if not memberShape(member, issuerId, partition, metadata, nil, member.memberOperation.operationId, member.reservation.reservationId) then return -2 end end end @@ -267,12 +277,17 @@ for index = 1, operationCount do local memberBytes = ARGV[cursor + 3] local bindingPresent = ARGV[cursor + 4] local countsCapacity = ARGV[cursor + 5] - cursor = cursor + 6 + local capacityMustBePresent = ARGV[cursor + 6] + local bindingMustBePresent = ARGV[cursor + 7] + cursor = cursor + 8 if not uuid(operationId) or not uuid(reservationId) or type(bindingRef) ~= 'string' or #bindingRef == 0 or type(memberBytes) ~= 'string' or #memberBytes == 0 or #memberBytes > maxMemberValueBytes or (bindingPresent ~= '0' and bindingPresent ~= '1') or (countsCapacity ~= '0' and countsCapacity ~= '1') + or (capacityMustBePresent ~= '0' and capacityMustBePresent ~= '1') + or (bindingMustBePresent ~= '0' and bindingMustBePresent ~= '1') + or (bindingMustBePresent == '1' and bindingPresent ~= '1') or seenOperations[operationId] or seenReservations[reservationId] or seenBindings[bindingRef] then return -2 end local ok, member = pcall(cjson.decode, memberBytes) if not ok or not memberShape(member, issuerId, partition, metadata, bindingRef, operationId, reservationId) then return -2 end @@ -281,7 +296,8 @@ for index = 1, operationCount do seenOperations[operationId] = true; seenReservations[reservationId] = true; seenBindings[bindingRef] = true operations[#operations + 1] = {operationId=operationId, bindingRef=bindingRef, reservationId=reservationId, memberBytes=memberBytes, - bindingPresent=bindingPresent, countsCapacity=countsCapacity} + bindingPresent=bindingPresent, countsCapacity=countsCapacity, + capacityMustBePresent=capacityMustBePresent, bindingMustBePresent=bindingMustBePresent} if countsCapacity == '1' then registeredCapacity = registeredCapacity + 1 end if bindingPresent == '1' then registeredBindings = registeredBindings + 1 end if not put(capacityPrefix .. reservationId, memberBytes) then return -2 end @@ -298,13 +314,17 @@ local sourceRevision = ARGV[cursor + 6] local plannedPartition = ARGV[cursor + 7] local plannedAggregate = ARGV[cursor + 8] local aggregateBound = ARGV[cursor + 9] -if #ARGV ~= cursor + 9 or not uuid(originalOperationId) or not uuid(releaseOperationId) +local expectedRevision = ARGV[cursor + 10] +local successorRevision = ARGV[cursor + 11] +if #ARGV ~= cursor + 11 or not uuid(originalOperationId) or not uuid(releaseOperationId) or originalOperationId == releaseOperationId or not uuid(targetReservationId) or type(targetBindingRef) ~= 'string' or type(originalBytes) ~= 'string' or type(releasedBytes) ~= 'string' or #originalBytes == 0 or #releasedBytes == 0 or #originalBytes > maxMemberValueBytes or #releasedBytes > maxMemberValueBytes or not positive(sourceRevision) or not nonnegative(plannedPartition) or not nonnegative(plannedAggregate) or not positive(aggregateBound) + or not uuid(expectedRevision) or not uuid(successorRevision) + or expectedRevision == successorRevision or greaterDecimal(plannedPartition, partitionCapacity) or greaterDecimal(plannedAggregate, aggregateBound) then return -2 end local oldOk, oldMember = pcall(cjson.decode, originalBytes) @@ -342,7 +362,7 @@ if allowed[targetBindingRef] == nil and not put(targetBindingRef, originalBytes) local kind = redis.call('TYPE', KEYS[1]).ok if kind ~= 'hash' or redis.call('PTTL', KEYS[1]) ~= -1 then return -1 end local actual = redis.call('HGETALL', KEYS[1]) -if #actual % 2 ~= 0 or #actual / 2 > maxHashFields then return -1 end +if #actual % 2 ~= 0 or #actual / 2 > maxPhysicalFields then return -1 end local actualFields = {}; local actualCapacity = 0; local actualReservations = 0; local actualBindings = 0 local actualBytes = 0 for index = 1, #actual, 2 do @@ -350,12 +370,16 @@ for index = 1, #actual, 2 do actualFields[field] = valueBytes; actualBytes = actualBytes + #field + #valueBytes if actualBytes > maxHashBytes then return -1 end local expected = allowed[field] - if field == targetCapacityField then + if field == mutationRevisionField then + if valueBytes ~= expectedRevision and valueBytes ~= successorRevision then return -1 end + elseif field == targetCapacityField then if valueBytes ~= originalBytes and valueBytes ~= releasedBytes then return -1 end elseif field == targetBindingRef then if valueBytes ~= originalBytes then return -1 end elseif expected == nil or expected ~= valueBytes then return -1 end - if string.sub(field, 1, #capacityPrefix) == capacityPrefix then + if field == mutationRevisionField then + -- The separately validated fence is not a reservation or binding field. + elseif string.sub(field, 1, #capacityPrefix) == capacityPrefix then local ok, member = pcall(cjson.decode, valueBytes) if not ok or type(member) ~= 'table' or type(member.reservation) ~= 'table' then return -1 end actualReservations = actualReservations + 1 @@ -378,10 +402,23 @@ if actualCapacity > tonumber(plannedPartition) or actualBindings < baselineBindings or actualBindings > baselineBindings + registeredBindings then return -1 end -local alreadyReleased = targetCapacityBefore == releasedBytes and targetBindingBefore == nil -if not alreadyReleased then - redis.call('HSET', KEYS[1], targetCapacityField, releasedBytes) - redis.call('HDEL', KEYS[1], targetBindingRef) - return 1 +local revisionBefore = actualFields[mutationRevisionField] +for _, operation in ipairs(operations) do + if operation.operationId ~= originalOperationId or revisionBefore ~= successorRevision then + local capacity = actualFields[capacityPrefix .. operation.reservationId] + local binding = actualFields[operation.bindingRef] + if operation.capacityMustBePresent == '1' and capacity ~= operation.memberBytes then return -1 end + if operation.bindingMustBePresent == '1' and binding ~= operation.memberBytes then return -1 end + end +end +if revisionBefore == successorRevision then + if targetCapacityBefore ~= releasedBytes or targetBindingBefore ~= nil then return -1 end + return 2 end -return 2 +if revisionBefore ~= expectedRevision + or targetCapacityBefore ~= originalBytes + or targetBindingBefore ~= originalBytes then return -1 end +redis.call('HSET', KEYS[1], mutationRevisionField, successorRevision, + targetCapacityField, releasedBytes) +redis.call('HDEL', KEYS[1], targetBindingRef) +return 1 diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-retirement.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-retirement.lua new file mode 100644 index 0000000000..22400f58ef --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-retirement.lua @@ -0,0 +1,273 @@ +-- Retire only one SQL-released terminal capacity field under the partition revision fence. +-- KEYS[1] is the sole canonical issuer partition hash. +local keyPrefix = 'session:game:index:issuer:' +local metadataField = '!issuer-partition-bootstrap/v1' +local revisionField = '!issuer-partition-mutation-revision/v1' +local capacityPrefix = '!issuer-reservation-capacity/v1:' +local maxMemberValueBytes = 65536 +local maxMetadataBytes = 65536 +local maxBaselineFields = 513 +local maxLocalOperations = 256 +local maxCurrentFields = 1026 +local maxExpectedFields = 1025 +local maxHashBytes = 16777216 + +local function uuid(value) + return type(value) == 'string' and #value == 36 + and string.match(value, '^%x%x%x%x%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x$') + and value == string.lower(value) + and value ~= '00000000-0000-0000-0000-000000000000' +end +local function positive(value) + return type(value) == 'string' and #value > 0 and #value <= 256 + and string.match(value, '^[1-9][0-9]*$') ~= nil +end +local function nonnegative(value) + return value == '0' or positive(value) +end +local function digest(value) + return type(value) == 'string' and #value == 71 + and string.match(value, '^sha256:[0-9a-f]+$') ~= nil +end +local function greaterDecimal(left, right) + if #left ~= #right then return #left > #right end + return left > right +end + +if #KEYS ~= 1 or #ARGV < 14 then return -2 end +if type(KEYS[1]) ~= 'string' or #KEYS[1] > 512 + or string.sub(KEYS[1], 1, #keyPrefix) ~= keyPrefix then return -2 end +local issuerId = ARGV[1] +local partitionId = ARGV[2] +local partitionCount = ARGV[3] +local partitionCapacity = ARGV[4] +local baselineCount = tonumber(ARGV[5]) +if issuerId ~= 'firemud-account-service' or not nonnegative(partitionId) + or not positive(partitionCount) or not positive(partitionCapacity) + or not baselineCount or baselineCount ~= baselineCount or baselineCount < 1 + or baselineCount > maxBaselineFields then return -2 end + +local cursor = 6 +local baseline = {} +local baselineReservations = 0 +local baselineBindings = 0 +local baselineCapacity = 0 +local metadataBytes = nil +for index = 1, baselineCount do + local field = ARGV[cursor] + local value = ARGV[cursor + 1] + cursor = cursor + 2 + if type(field) ~= 'string' or #field == 0 or baseline[field] ~= nil + or type(value) ~= 'string' or #value == 0 or #value > maxMemberValueBytes then return -2 end + baseline[field] = value + if field == metadataField then + metadataBytes = value + elseif string.sub(field, 1, #capacityPrefix) == capacityPrefix then + local id = string.sub(field, #capacityPrefix + 1) + local ok, member = pcall(cjson.decode, value) + if not uuid(id) or not ok or type(member) ~= 'table' + or type(member.reservation) ~= 'table' or member.reservation.reservationId ~= id + or member.reservation.partitionId ~= partitionId then return -2 end + baselineReservations = baselineReservations + 1 + if member.reservation.lifecycle ~= 'RELEASED' then baselineCapacity = baselineCapacity + 1 end + else + local ok, member = pcall(cjson.decode, value) + if not ok or type(member) ~= 'table' or type(member.reservation) ~= 'table' + or member.reservation.bindingRef ~= field then return -2 end + baselineBindings = baselineBindings + 1 + end +end +if metadataBytes == nil or #metadataBytes > maxMetadataBytes then return -2 end +local metadataOk, metadata = pcall(cjson.decode, metadataBytes) +if not metadataOk or type(metadata) ~= 'table' or metadata.schemaVersion ~= 1 + or metadata.issuerId ~= issuerId or metadata.partitionId ~= partitionId + or type(metadata.layoutTag) ~= 'string' or #metadata.layoutTag ~= 70 + or not string.match(metadata.layoutTag, '^il%-v1%-%x+$') + or type(metadata.layout) ~= 'table' or type(metadata.anchor) ~= 'table' + or type(metadata.incarnation) ~= 'table' + or metadata.layout.partitionCount ~= partitionCount + or metadata.layout.partitionCapacity ~= partitionCapacity + or metadata.layout.mappingIdentity ~= 'bindingRef/v1;sha256-u256-mod/v1' + or not uuid(metadata.anchor.issuerCoverageOperationId) + or not positive(metadata.anchor.operationFence) + or not positive(metadata.anchor.coverageFence) + or not positive(metadata.anchor.issuerInventorySnapshotRevision) then return -2 end +local expectedKey = keyPrefix .. '{' .. metadata.layoutTag .. '}:' .. issuerId .. ':' .. partitionId +if KEYS[1] ~= expectedKey or not greaterDecimal(partitionCount, partitionId) then return -2 end + +local allowed = {} +local allowedCount = 0 +local expectedBytes = 0 +local function put(field, value) + if type(field) ~= 'string' or #field == 0 or allowed[field] ~= nil then return false end + allowed[field] = value + allowedCount = allowedCount + 1 + expectedBytes = expectedBytes + #field + #value + return allowedCount <= maxExpectedFields and expectedBytes <= maxHashBytes +end +for field, value in pairs(baseline) do if not put(field, value) then return -2 end end + +local operationCount = tonumber(ARGV[cursor]) +cursor = cursor + 1 +if not operationCount or operationCount < 1 or operationCount > maxLocalOperations then return -2 end +local operations = {} +local operationIds = {} +local reservationIds = {} +local bindingRefs = {} +local registeredCapacity = 0 +local registeredBindings = 0 +for index = 1, operationCount do + local operationId = ARGV[cursor] + local bindingRef = ARGV[cursor + 1] + local reservationId = ARGV[cursor + 2] + local memberBytes = ARGV[cursor + 3] + local bindingPresent = ARGV[cursor + 4] + local countsCapacity = ARGV[cursor + 5] + local capacityMustBePresent = ARGV[cursor + 6] + local bindingMustBePresent = ARGV[cursor + 7] + cursor = cursor + 8 + if not uuid(operationId) or not uuid(reservationId) + or type(bindingRef) ~= 'string' or #bindingRef == 0 or #bindingRef > 6144 + or type(memberBytes) ~= 'string' or #memberBytes == 0 or #memberBytes > maxMemberValueBytes + or (bindingPresent ~= '0' and bindingPresent ~= '1') + or (countsCapacity ~= '0' and countsCapacity ~= '1') + or (capacityMustBePresent ~= '0' and capacityMustBePresent ~= '1') + or (bindingMustBePresent ~= '0' and bindingMustBePresent ~= '1') + or (bindingMustBePresent == '1' and bindingPresent ~= '1') + or operationIds[operationId] or reservationIds[reservationId] or bindingRefs[bindingRef] then return -2 end + local ok, member = pcall(cjson.decode, memberBytes) + if not ok or type(member) ~= 'table' or member.schemaVersion ~= 2 + or member.issuerId ~= issuerId or type(member.reservation) ~= 'table' + or type(member.memberOperation) ~= 'table' + or member.reservation.bindingRef ~= bindingRef + or member.reservation.reservationId ~= reservationId + or member.reservation.partitionId ~= partitionId + or member.memberOperation.operationId ~= operationId + or not uuid(member.memberOperation.operationId) + or (countsCapacity == '1' and member.reservation.lifecycle == 'RELEASED') + or (countsCapacity == '0' + and (member.reservation.lifecycle ~= 'RELEASED' or bindingPresent ~= '0')) then return -2 end + operationIds[operationId] = true + reservationIds[reservationId] = true + bindingRefs[bindingRef] = true + operations[#operations + 1] = { + operationId=operationId, bindingRef=bindingRef, reservationId=reservationId, + memberBytes=memberBytes, bindingPresent=bindingPresent, countsCapacity=countsCapacity, + capacityMustBePresent=capacityMustBePresent, bindingMustBePresent=bindingMustBePresent, + member=member + } + if countsCapacity == '1' then registeredCapacity = registeredCapacity + 1 end + if bindingPresent == '1' then registeredBindings = registeredBindings + 1 end + if not put(capacityPrefix .. reservationId, memberBytes) then return -2 end + if bindingPresent == '1' and not put(bindingRef, memberBytes) then return -2 end +end + +local releaseOperationId = ARGV[cursor] +local retirementOperationId = ARGV[cursor + 1] +local targetReservationId = ARGV[cursor + 2] +local targetBindingRef = ARGV[cursor + 3] +local releasedBytes = ARGV[cursor + 4] +local sourceRevision = ARGV[cursor + 5] +local completionRevision = ARGV[cursor + 6] +local plannedPartitionCapacity = ARGV[cursor + 7] +local plannedAggregateCapacity = ARGV[cursor + 8] +local aggregateBound = ARGV[cursor + 9] +local expectedRevision = ARGV[cursor + 10] +local successorRevision = ARGV[cursor + 11] +if #ARGV ~= cursor + 11 or not uuid(releaseOperationId) or not uuid(retirementOperationId) + or not uuid(targetReservationId) or type(targetBindingRef) ~= 'string' + or type(releasedBytes) ~= 'string' or #releasedBytes == 0 or #releasedBytes > maxMemberValueBytes + or not positive(sourceRevision) or not positive(completionRevision) + or not greaterDecimal(completionRevision, sourceRevision) + or not nonnegative(plannedPartitionCapacity) or not nonnegative(plannedAggregateCapacity) + or not positive(aggregateBound) or not uuid(expectedRevision) or not uuid(successorRevision) + or expectedRevision == successorRevision + or greaterDecimal(plannedPartitionCapacity, partitionCapacity) + or greaterDecimal(plannedAggregateCapacity, aggregateBound) then return -2 end +local releasedOk, released = pcall(cjson.decode, releasedBytes) +if not releasedOk or type(released) ~= 'table' or released.schemaVersion ~= 2 + or type(released.reservation) ~= 'table' or type(released.memberOperation) ~= 'table' + or released.issuerId ~= issuerId + or released.reservation.lifecycle ~= 'RELEASED' + or released.reservation.reservationId ~= targetReservationId + or released.reservation.partitionId ~= partitionId + or released.reservation.inventoryRevision ~= sourceRevision + or released.memberOperation.operationId ~= releaseOperationId + or released.reservation.bindingRef ~= targetBindingRef then return -2 end +local targetFound = false +for _, operation in ipairs(operations) do + if operation.reservationId == targetReservationId then + if operation.operationId ~= releaseOperationId + or operation.bindingRef ~= targetBindingRef + or operation.memberBytes ~= releasedBytes + or operation.countsCapacity ~= '0' or operation.bindingPresent ~= '0' then return -2 end + targetFound = true + elseif operation.operationId == releaseOperationId then + return -2 + end +end +if not targetFound then return -2 end +local targetCapacityField = capacityPrefix .. targetReservationId +if allowed[targetCapacityField] ~= releasedBytes then return -2 end +if tostring(baselineCapacity + registeredCapacity) ~= plannedPartitionCapacity then return -2 end + +local kind = redis.call('TYPE', KEYS[1]).ok +if kind ~= 'hash' or redis.call('PTTL', KEYS[1]) ~= -1 then return -1 end +local actual = redis.call('HGETALL', KEYS[1]) +if #actual % 2 ~= 0 or #actual / 2 > maxCurrentFields then return -1 end +local actualFields = {} +local currentBytes = 0 +local actualCapacity = 0 +local actualReservations = 0 +local actualBindings = 0 +for index = 1, #actual, 2 do + local field = actual[index] + local value = actual[index + 1] + actualFields[field] = value + currentBytes = currentBytes + #field + #value + if currentBytes > maxHashBytes then return -1 end + if field == revisionField then + if value ~= expectedRevision and value ~= successorRevision then return -1 end + elseif allowed[field] == nil or allowed[field] ~= value then + return -1 + end + if field == revisionField or field == metadataField then + -- Metadata and revision do not count as reservation or binding members. + elseif string.sub(field, 1, #capacityPrefix) == capacityPrefix then + local ok, member = pcall(cjson.decode, value) + if not ok or type(member) ~= 'table' or type(member.reservation) ~= 'table' then return -1 end + actualReservations = actualReservations + 1 + if member.reservation.lifecycle ~= 'RELEASED' then actualCapacity = actualCapacity + 1 end + else + actualBindings = actualBindings + 1 + end +end +local revisionBefore = actualFields[revisionField] +local targetCapacityBefore = actualFields[targetCapacityField] +for _, operation in ipairs(operations) do + if operation.operationId ~= releaseOperationId or revisionBefore ~= successorRevision then + local capacity = actualFields[capacityPrefix .. operation.reservationId] + local binding = actualFields[operation.bindingRef] + if operation.capacityMustBePresent == '1' and capacity ~= operation.memberBytes then return -1 end + if operation.bindingMustBePresent == '1' and binding ~= operation.memberBytes then return -1 end + end +end +if revisionBefore == successorRevision then + if targetCapacityBefore ~= nil or actualFields[targetBindingRef] == releasedBytes then return -1 end + if #actual / 2 ~= allowedCount then return -1 end + return 2 +end +if revisionBefore ~= expectedRevision + or #actual / 2 ~= allowedCount + 1 + or targetCapacityBefore ~= releasedBytes + or actualFields[targetBindingRef] == releasedBytes + or actualCapacity ~= tonumber(plannedPartitionCapacity) + or actualReservations ~= baselineReservations + operationCount + or actualBindings < baselineBindings + or actualBindings > baselineBindings + registeredBindings then return -1 end +for field, value in pairs(baseline) do + if redis.call('HGET', KEYS[1], field) ~= value then return -1 end +end +redis.call('HDEL', KEYS[1], targetCapacityField) +redis.call('HSET', KEYS[1], revisionField, successorRevision) +return 1 diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-bootstrap-partition-build.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-bootstrap-partition-build.lua index c24d1a83af..870d38e660 100644 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-bootstrap-partition-build.lua +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-bootstrap-partition-build.lua @@ -4,12 +4,13 @@ local keyPrefix = 'session:game:index:issuer:' local metadataField = '!issuer-partition-bootstrap/v1' local capacityPrefix = '!issuer-reservation-capacity/v1:' +local mutationRevisionField = '!issuer-partition-mutation-revision/v1' local maxDecimalBytes = 256 local maxMemberOperations = 256 local maxBindingRefBytes = 6144 local maxMemberValueBytes = 65536 local maxMetadataBytes = 65536 -local maxHashFields = 513 +local maxHashFields = 514 local maxHashBytes = 16777216 local function uuid(value) @@ -131,7 +132,7 @@ local function metadataMatchesMember(metadata, member, partitionId) and sameIncarnation(member.incarnation, metadata.incarnation) end -if #KEYS ~= 1 or #ARGV < 6 then return -2 end +if #KEYS ~= 1 or #ARGV < 7 then return -2 end if type(KEYS[1]) ~= 'string' or #KEYS[1] > 512 or string.sub(KEYS[1], 1, #keyPrefix) ~= keyPrefix then return -2 end @@ -141,13 +142,14 @@ local partitionId = ARGV[2] local partitionCount = ARGV[3] local partitionCapacity = ARGV[4] local metadataBytes = ARGV[5] -local memberCountText = ARGV[6] +local initialPhysicalRevision = ARGV[6] +local memberCountText = ARGV[7] if issuerId ~= 'firemud-account-service' or not nonnegative(partitionId) or not positive(partitionCount) or not positive(partitionCapacity) - or not nonnegative(memberCountText) then return -2 end + or not uuid(initialPhysicalRevision) or not nonnegative(memberCountText) then return -2 end local memberCount = tonumber(memberCountText) if not memberCount or memberCount > maxMemberOperations - or #ARGV ~= 6 + memberCount * 4 then return -2 end + or #ARGV ~= 7 + memberCount * 4 then return -2 end if #metadataBytes == 0 or #metadataBytes > maxMetadataBytes then return -2 end local metadataOk, metadata = pcall(cjson.decode, metadataBytes) @@ -197,6 +199,7 @@ local function putExpected(field, value) return totalExpectedBytes <= maxHashBytes and expectedCount <= maxHashFields end if not putExpected(metadataField, metadataBytes) then return -2 end +if not putExpected(mutationRevisionField, initialPhysicalRevision) then return -2 end local seenReservations = {} local seenBindings = {} @@ -205,7 +208,7 @@ local actualCapacityCount = 0 local actualBindingCount = 0 local totalArgumentBytes = #metadataBytes for index = 0, memberCount - 1 do - local offset = 7 + index * 4 + local offset = 8 + index * 4 local bindingRef = ARGV[offset] local memberBytes = ARGV[offset + 1] local capacityField = ARGV[offset + 2] @@ -273,7 +276,6 @@ end if greaterDecimal(tostring(actualCapacityCount), partitionCapacity) or tostring(actualCapacityCount) ~= metadata.plannedPartitionCapacityCount or actualBindingCount > memberCount then return -2 end -if memberCount > 0 and metadata.plannedPartitionCapacityCount ~= tostring(actualCapacityCount) then return -2 end -- Validate TYPE, persistence and every current field before the first mutation. local kind = redis.call('TYPE', KEYS[1]).ok @@ -302,14 +304,16 @@ for index = 1, #current, 2 do present[field] = true end -if currentLength == expectedCount then return 2 end -local missing = {} -for field, value in pairs(expected) do - if not present[field] then - missing[#missing + 1] = field - missing[#missing + 1] = value +if kind == 'none' then + if currentLength ~= 0 or next(present) ~= nil then return -1 end + local initial = {} + for field, value in pairs(expected) do + initial[#initial + 1] = field + initial[#initial + 1] = value end + if #initial == 0 or #initial % 2 ~= 0 then return -1 end + redis.call('HSET', KEYS[1], unpack(initial)) + return 1 end -if #missing == 0 or #missing % 2 ~= 0 then return -1 end -redis.call('HSET', KEYS[1], unpack(missing)) -return 1 +if currentLength ~= expectedCount then return -1 end +return 2 diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-add.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-add.json index c6da22a71d..0d819db5c5 100644 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-add.json +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-add.json @@ -1,7 +1,7 @@ { "scriptId": "game-session.issuer-binding-local-add.v1", "resourcePath": "redis/lua/game-session-issuer-binding-local-add.lua", - "sha256": "a02489c42e6001a8f80340a5d037dfeb10cb30e045dc997eb289700500c1da18", + "sha256": "f45adaf2c62acd186f5497da6035e190797f7a9a3a1f269ac9ff35936c5120e4", "owner": "game-session-service", "principal": "gamesession_coord_app", "role": "COORDINATION", @@ -30,7 +30,7 @@ {"code": "INVALID_ARGUMENTS_OR_CAPACITY", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} ], "resetSensitivity": "CLUSTER", - "tailLossBehavior": "This local one-key projection requires the exact positively installed issuer anchor, complete immutable partition baseline, and complete SQL-registered post-baseline reservation set. Existing baseline fields must all remain present and exact. A locally registered pending field may be absent or exact; a completed SQL issuer-local release may appear only as its retained exact RELEASED capacity postimage with its binding absent. The physical owner mutates only the target original capacity field and its SQL-qualified target binding field. Missing baseline/header, legacy or malformed values, unknown fields, current source or incarnation movement, or incomplete SQL accounting leaves the operation unqualified. The result is physical readback evidence only; it does not acknowledge issuer-wide coverage, open a barrier, or authorize admission.", + "tailLossBehavior": "This local one-key projection requires the exact positively installed issuer anchor, immutable partition baseline including its owner-installed initial mutation revision, and complete SQL-registered current unretired reservation set. Existing baseline fields must all remain present and exact. A locally registered pending field may be absent or exact; an unretired completed SQL issuer-local release may appear only as its retained exact RELEASED capacity postimage with its binding absent; an authorized retired terminal capacity field is absent only with its exact retained original retirement proof. Every ADD compares and advances the partition-local opaque physical revision atomically with its one-key change, so an older prepared ADD or release cannot replay after a later release or retirement. Missing baseline/header/revision, legacy or malformed values, unknown fields, current source or incarnation movement, or incomplete SQL accounting leaves the operation unqualified. The result is physical readback evidence only; it does not acknowledge issuer-wide coverage, open a barrier, or authorize admission.", "lossClass": "EMPTY_REDIS_COLD_START_OR_RESET", "compatibilityLevel": "REQUIRES_CLUSTER_RESET", "supportedCoexistence": [ diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-release.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-release.json index 0d39ded90f..c00a628fdd 100644 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-release.json +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-release.json @@ -1,7 +1,7 @@ { "scriptId": "game-session.issuer-binding-local-release.v1", "resourcePath": "redis/lua/game-session-issuer-binding-local-release.lua", - "sha256": "82a94b421725ff3fa4a7e77a16755c929700ea68c13e7b6437e7f1ae472b9b22", + "sha256": "2ffdd169b68b368f9b4ea3ae24039d4c6ae0375767f8d5dc5357621fdf506dac", "owner": "game-session-service", "principal": "gamesession_coord_app", "role": "COORDINATION", @@ -29,7 +29,7 @@ {"code": "INVALID_ARGUMENTS_OR_CAPACITY", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} ], "resetSensitivity": "CLUSTER", - "tailLossBehavior": "The one-key release requires the exact installed v2 anchor, complete immutable baseline, current SQL registered local operations, and a genuine Account-aborted first-NEW source. It writes only the SQL-issued RELEASED reservation bytes and removes only that operation's exact original binding field. The terminal V2 value retains its original reservation coverage tuple and installed anchor; its inventoryRevision is the frozen SQL release-preparation source revision P. A later durable SQL receipt advances the current inventory clock to fresh revision R and links P, exact postimage, independent readback, and the original operation. Missing baseline/header, legacy or malformed values, unknown fields, conflicting or newer members, wrong reservation/anchor/incarnation, or changed source fail closed. RELEASE_PENDING remains capacity-counted until exact readback and the guarded SQL completion; only a retained completed RELEASED postimage is excluded from ordinary capacity. No coverage acknowledgement, barrier, or admission authority is produced.", + "tailLossBehavior": "The one-key release requires the exact installed v2 anchor, complete immutable baseline, current SQL registered local operations, and a genuine Account-aborted first-NEW source. It writes only the SQL-issued RELEASED reservation bytes, removes only that operation's exact original binding field, and atomically advances the partition-local opaque physical revision. The terminal V2 value retains its original reservation coverage tuple and installed anchor; its inventoryRevision is the frozen SQL release-preparation source revision P. A later durable SQL receipt advances the current inventory clock to fresh revision R and links P, exact postimage, independent readback, and the original operation. Missing baseline/header/revision, legacy or malformed values, unknown fields, conflicting or newer members, wrong reservation/anchor/incarnation, or changed source fail closed. RELEASE_PENDING remains capacity-counted until exact readback and guarded SQL completion; a completed RELEASED capacity remains in the bounded physical projection until exact original-operation retirement. The physical revision rejects a stale prepared release after retirement. No coverage acknowledgement, barrier, or admission authority is produced.", "lossClass": "EMPTY_REDIS_COLD_START_OR_RESET", "compatibilityLevel": "REQUIRES_CLUSTER_RESET", "supportedCoexistence": [ diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-retirement.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-retirement.json new file mode 100644 index 0000000000..5ac81b3000 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-retirement.json @@ -0,0 +1,35 @@ +{ + "scriptId": "game-session.issuer-binding-local-retirement.v1", + "resourcePath": "redis/lua/game-session-issuer-binding-local-retirement.lua", + "sha256": "b8d9362de8af6b274ca3bc38d4d700d537d056389c73b2bc86378844ab898a76", + "owner": "game-session-service", + "principal": "gamesession_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "issuerPartition", + "ownedPrefix": "session:game:index:issuer:", + "hashTagDeclaration": "REQUIRED" + } + ], + "arguments": [ + {"name": "issuerIdPartitionLayoutAndExactBaselineFields"}, + {"name": "currentUnretiredLocalOperationCountAndExactFields"}, + {"name": "originalReleaseReceiptAndOpaquePhysicalRevisionCompareAndAdvance"} + ], + "category": "SESSION_ISSUER_INDEX", + "outcomes": [ + {"code": "TERMINAL_CAPACITY_RETIRED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "ORIGINAL_RETIREMENT_REPLAY", "category": "REPLAY", "effect": "NON_MUTATING"}, + {"code": "TYPE_TTL_OR_FIELDSET_REFUSED", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, + {"code": "INVALID_OR_STALE_REVISION_REFUSED", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} + ], + "resetSensitivity": "CLUSTER", + "tailLossBehavior": "This passive manual one-key owner removes only the exact terminal capacity field named by the original committed RELEASED receipt at its actual SQL completion revision R. A SQL-persisted partition-local expected/successor revision fences every physical writer. A stale prepared ADD or release is rejected before mutation even after retirement. The owner requires the complete current unretired SQL projection, exact installed baseline, current source and incarnation, exact RELEASED bytes from P, and a current opaque revision. It independently reads back exact target absence and the successor revision before SQL records retirement. Immutable release and bootstrap history remain retained; retirement does not change Account or region obligations, grant coverage, open a barrier, or authorize admission. Unknown outcomes retain the same original pending retirement for exact readback recovery.", + "lossClass": "EMPTY_REDIS_COLD_START_OR_RESET", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [ + {"callerVersion": "v1", "payloadVersion": "v2"} + ], + "legacyPayloadShape": null +} diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-bootstrap-partition-build.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-bootstrap-partition-build.json index 07c21f9b6b..0dc8aaa310 100644 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-bootstrap-partition-build.json +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-bootstrap-partition-build.json @@ -1,7 +1,7 @@ { "scriptId": "game-session.issuer-bootstrap-partition-build.v1", "resourcePath": "redis/lua/game-session-issuer-bootstrap-partition-build.lua", - "sha256": "526383d905b93ef2a8026f6b4ac659b601c40257b874652b8c3b89b637b84531", + "sha256": "15c5f0524b31413da9153e4f35ad6a2c3a578e90ee5a1af7a3e4c358f8a788a7", "owner": "game-session-service", "principal": "gamesession_coord_app", "role": "COORDINATION", @@ -18,6 +18,7 @@ {"name": "partitionCount"}, {"name": "partitionCapacity"}, {"name": "exactBootstrapMetadata"}, + {"name": "initialPhysicalMutationRevision"}, {"name": "memberOperationCount"}, {"name": "repeatedBindingRefMemberCapacityFieldBindingPresence"} ], @@ -30,7 +31,7 @@ ], "resetSensitivity": "CLUSTER", "lossClass": "EMPTY_REDIS_COLD_START_OR_RESET", - "tailLossBehavior": "This local one-partition bootstrap projection is reset-sensitive physical evidence only. The SQL owner must supply a complete positive prepared cohort and the exact member-operation set for this partition. Missing, partial, malformed, legacy, foreign, or mismatched state remains unqualified unless the exact complete field set is written and read back under fresh controlled current-source and incarnation checks. This single partition readback is not complete issuer coverage, an installed anchor, an acknowledgement, barrier OPEN, or admission authority.", + "tailLossBehavior": "This local one-partition bootstrap projection is reset-sensitive physical evidence only. The SQL owner must supply a complete positive prepared cohort, an owner-allocated initial partition-local mutation revision, and the exact member-operation set for this partition. Missing, partial, malformed, legacy, foreign, or mismatched state remains unqualified unless the exact complete field set is written and read back under fresh controlled current-source and incarnation checks. This single partition readback is not complete issuer coverage, an installed anchor, an acknowledgement, barrier OPEN, or admission authority.", "compatibilityLevel": "REQUIRES_CLUSTER_RESET", "supportedCoexistence": [ {"callerVersion": "v1", "payloadVersion": "v2"} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java index 7706bdac2e..de39e0ee4e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java @@ -16,6 +16,7 @@ import java.util.Arrays; import java.util.EnumSet; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -43,6 +44,7 @@ import net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountMemberRepairRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; @@ -85,11 +87,24 @@ public final class CanonicalGameplayAdmissionAbortCompositionFixture implements private final RedisScriptCatalog issuerCatalog; private final Map otherOperations = new HashMap<>(); + private final Map otherLeases = new HashMap<>(); public CanonicalGameplayAdmissionAbortCompositionFixture( DriverManagerDataSource accountDataSource, Candidate accountCandidate, RedisClient issuerRedisClient) { + this(accountDataSource, accountCandidate, issuerRedisClient, 0); + } + + /** Installs actual retained reservations as part of the qualified initial bootstrap cohort. */ + public CanonicalGameplayAdmissionAbortCompositionFixture( + DriverManagerDataSource accountDataSource, + Candidate accountCandidate, + RedisClient issuerRedisClient, + int seedBootstrapMemberCount) { + if (seedBootstrapMemberCount < 0 || seedBootstrapMemberCount > 256) { + throw new IllegalArgumentException("Bootstrap fixture member count must be within [0, 256]"); + } this.issuerRedisClient = java.util.Objects.requireNonNull(issuerRedisClient, "issuerRedisClient"); dataSource = new DriverManagerDataSource(); @@ -134,6 +149,9 @@ public CanonicalGameplayAdmissionAbortCompositionFixture( accountCandidate.issuerIndexPartitionCount(), accountCandidate.issuerIndexPartitionCapacity()); establishActualLegacyDisposition(dsl); + if (seedBootstrapMemberCount > 0) { + seedQualifiedBootstrapMembers(seedBootstrapMemberCount); + } repository = new CanonicalGameplayBindingInventoryRepository(dsl); BigInteger layoutVersion = identity.issuerIndexLayoutVersion(); BigInteger partitionCount = identity.issuerIndexPartitionCount(); @@ -411,6 +429,11 @@ public void publish(AccountGameplayAdmissionLeaseEvidence lease) { .projectAndRead(localOperation); } + /** Uses a controlled Account lease input and the actual provisional SQL/Redis owners. */ + public void publishOriginalWithControlledAccountLease() { + publish(controlledLeaseEvidence(identity, generation, target)); + } + /** * Start the disposable GS role before lease allocation so container startup consumes no lease * lifetime. @@ -507,6 +530,11 @@ public CanonicalGameplayIssuerBindingLocalReleaseOperation prepareIssuerRelease( .prepareOrResume(transitionId); } + public CanonicalGameplayIssuerBindingLocalReleaseOperation prepareIssuerRelease(String seed) { + return new CanonicalGameplayIssuerBindingLocalReleaseOperationRepository(dsl, issuerSource) + .prepareOrResume(otherOperation(seed).request().transitionId()); + } + public CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.Readback projectIssuerRelease( CanonicalGameplayIssuerBindingLocalReleaseOperation operation) { return new CanonicalGameplayIssuerBindingLocalReleaseRedisOwner( @@ -532,6 +560,14 @@ public CanonicalGameplayIssuerBindingLocalReleaseOperation completeIssuerRelease .completeWithReadback(operation, readback); } + /** Records a controlled Account terminal input through the actual Game Session abort owner. */ + public CanonicalGameplayAdmissionAbortSource recordOriginalAccountAbort() { + var source = repository.readFirstNewAdmissionAbortSource(transitionId); + return repository.recordFirstNewAccountAbort( + source, + UUID.nameUUIDFromBytes("original-controller-cleanup".getBytes(StandardCharsets.UTF_8))); + } + public UUID prepareOtherControllerNew(String seed) { CanonicalGameplayBindingIdentity other; do { @@ -569,6 +605,180 @@ public UUID prepareOtherControllerNew(String seed) { return operation.operationId(); } + /** Uses the actual NEW SQL owner to prepare a member in a caller-selected pinned partition. */ + public UUID prepareOtherControllerNewInPartition(String seed, BigInteger partitionId) { + Objects.requireNonNull(seed, "seed"); + Objects.requireNonNull(partitionId, "partitionId"); + if (partitionId.signum() < 0 + || partitionId.compareTo(identity.issuerIndexPartitionCount()) >= 0) { + throw new IllegalArgumentException("partitionId must be within the installed issuer layout"); + } + CanonicalGameplayBindingIdentity other; + do { + other = + new CanonicalGameplayBindingIdentity( + identity.accountId(), + identity.tenantId(), + identity.playableStateNamespaceId(), + UUID.randomUUID(), + identity.playableStateScope(), + identity.gameInstanceId(), + identity.runtimeGameInstanceId(), + UUID.randomUUID().toString(), + identity.regionId(), + identity.regionEpoch(), + identity.issuerId(), + identity.issuerAuthGeneration(), + identity.issuerIndexLayoutVersion(), + identity.issuerIndexPartitionCount(), + identity.issuerIndexPartitionCapacity()); + } while (!other + .bindingRef() + .partitionId(identity.issuerIndexPartitionCount()) + .equals(partitionId)); + var operation = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, issuerSource) + .beginOrResumeOrdinaryNew( + new CanonicalGameplayIssuerBindingLocalOperation.Request( + UUID.nameUUIDFromBytes((seed + "-request").getBytes(StandardCharsets.UTF_8)), + UUID.nameUUIDFromBytes((seed + "-transition").getBytes(StandardCharsets.UTF_8)), + other, + null, + null)); + otherOperations.put(seed, operation); + return operation.operationId(); + } + + /** Replays the exact retained request for a previously prepared controller operation. */ + public UUID retryOtherControllerNew(String seed) { + var operation = otherOperation(seed); + var retried = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, issuerSource) + .beginOrResumeOrdinaryNew(operation.request()); + otherOperations.put(seed, retried); + return retried.operationId(); + } + + /** Uses the actual SQL preparation and physical Redis owner for another same-partition NEW. */ + public CanonicalGameplayIssuerBindingLocalRedisOwner.Readback projectOtherControllerNew( + String seed) { + var operation = otherOperation(seed); + return new CanonicalGameplayIssuerBindingLocalRedisOwner( + issuerRedisClient, issuerCatalog, localProjectionRepository, issuerSource) + .projectAndRead(operation); + } + + /** Publishes a controlled Account lease through the actual SQL and Redis provisional owners. */ + public void publishOtherControllerNew(String seed) { + var operation = otherOperation(seed); + var transitionId = operation.request().transitionId(); + var evidence = repository.readProvisionalCasEvidence(transitionId); + var lease = + otherLeases.computeIfAbsent( + seed, + ignored -> + controlledLeaseEvidence( + operation.request().candidate(), + evidence.transition().bindingGeneration(), + target)); + repository.markProvisional( + evidence, + new CanonicalGameplayAdmissionDecision( + transitionId, + lease, + operation.request().candidate(), + evidence.transition().bindingGeneration(), + null, + target)); + new CanonicalGameplayIssuerBindingLocalRedisOwner( + issuerRedisClient, issuerCatalog, localProjectionRepository, issuerSource) + .projectAndRead(operation); + } + + /** Records a controlled Account abort through the actual Game Session SQL abort owner. */ + public CanonicalGameplayAdmissionAbortSource recordOtherAccountAbort(String seed) { + var operation = otherOperation(seed); + var source = repository.readFirstNewAdmissionAbortSource(operation.request().transitionId()); + return repository.recordFirstNewAccountAbort( + source, UUID.nameUUIDFromBytes((seed + "-cleanup").getBytes(StandardCharsets.UTF_8))); + } + + CanonicalGameplayIssuerBindingLocalOperation otherOperation(String seed) { + var operation = otherOperations.get(seed); + if (operation == null) { + throw new IllegalArgumentException("Other NEW operation was not prepared"); + } + return operation; + } + + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork + prepareOtherAddMutation(String seed) { + return localProjectionRepository.prepareAddMutationWork(otherOperation(seed)); + } + + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork + readPreparedPartitionWork(CanonicalGameplayIssuerBindingLocalOperation operation) { + return localProjectionRepository.readPreparedPartitionWork(operation); + } + + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork + readCurrentOriginalPartitionWork() { + return localProjectionRepository.readPreparedPartitionWork(localOperation); + } + + public CanonicalGameplayIssuerBindingLocalRetirementOperation prepareIssuerRetirement( + UUID transitionId) { + return new CanonicalGameplayIssuerBindingLocalRetirementOperationRepository(dsl, issuerSource) + .prepareOrResume(transitionId); + } + + public CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.Readback retireIssuerCapacity( + CanonicalGameplayIssuerBindingLocalRetirementOperation operation) { + return new CanonicalGameplayIssuerBindingLocalRetirementRedisOwner( + issuerRedisClient, + retirementCatalog(), + localProjectionRepository, + new CanonicalGameplayIssuerBindingLocalRetirementOperationRepository(dsl, issuerSource), + issuerSource) + .retireAndRead(operation); + } + + /** Adds the retirement script only for callers that exercise the new owner. */ + RedisScriptCatalog retirementCatalog() { + return RedisScriptCatalog.fromContributions( + List.of( + new CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution(), + new CanonicalGameplayIssuerBindingLocalRedisScriptContribution(), + new CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution(), + new CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution())); + } + + public byte[] issuerPartitionKey() { + return CanonicalGameplayIssuerRedisKeys.forMember(localOperation.memberValue()) + .getBytes(StandardCharsets.US_ASCII); + } + + public byte[] issuerPartitionKey(String seed) { + return CanonicalGameplayIssuerRedisKeys.forMember(otherOperation(seed).memberValue()) + .getBytes(StandardCharsets.US_ASCII); + } + + public BigInteger originalPartitionId() { + return localOperation.reservation().partitionId(); + } + + public int originalBaselineReservationCount() { + return localOperation.baselinePartitionProof().physicalReservationCount(); + } + + public int originalBaselineCountedCapacity() { + return localOperation.baselinePartitionProof().physicalCountedCapacityCount(); + } + + public int originalBaselineBindingCount() { + return localOperation.baselinePartitionProof().physicalBindingCount(); + } + public BigInteger preparedLocalCountedReservations() { var work = localProjectionRepository.readPreparedPartitionWork(localOperation); return BigInteger.valueOf( @@ -726,16 +936,6 @@ public void restoreOriginalReleaseBinding( } } - public CanonicalGameplayIssuerBindingLocalRedisOwner.Readback projectOtherControllerNew( - String seed) { - var operation = otherOperations.get(seed); - if (operation == null) - throw new IllegalArgumentException("Other NEW operation was not prepared"); - return new CanonicalGameplayIssuerBindingLocalRedisOwner( - issuerRedisClient, issuerCatalog, localProjectionRepository, issuerSource) - .projectAndRead(operation); - } - /** Attempts a newer candidate; the retained unresolved original must fence preparation. */ public BigInteger prepareNewerCandidate() { var newer = @@ -815,6 +1015,146 @@ public byte[] originalMemberValueBytes() { return localOperation.exactMemberValueBytes(); } + private static AccountGameplayAdmissionLeaseEvidence controlledLeaseEvidence( + CanonicalGameplayBindingIdentity candidate, + BigInteger bindingGeneration, + CanonicalPlayableTarget target) { + long now = System.currentTimeMillis(); + String nowSeconds = Long.toString(now / 1000L); + Map carrier = new LinkedHashMap<>(); + carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + carrier.put("schemaVersion", "1"); + carrier.put("mode", "PUBLIC_PRODUCTION"); + carrier.put("leaseKind", AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING.name()); + carrier.put("targetNamespace", target.targetNamespace()); + carrier.put( + "callerWorkload", + "spiffe://firemud/ns/" + target.targetNamespace() + "/sa/game-session-service"); + carrier.put("requestId", UUID.randomUUID().toString()); + carrier.put("leaseId", UUID.randomUUID().toString()); + carrier.put("leaseFence", "1"); + Map scope = new LinkedHashMap<>(); + scope.put("accountId", candidate.accountId().toString()); + scope.put("tenantId", candidate.tenantId().toString()); + scope.put("realmId", target.realmId().toString()); + scope.put("worldSlug", target.worldSlug()); + scope.put("realmSlug", target.realmSlug()); + scope.put("playableStateNamespaceId", target.playableStateNamespaceId().toString()); + scope.put("playableStateScope", target.playableStateScope()); + scope.put("gameInstanceId", target.canonicalGameInstanceId().toString()); + scope.put("characterId", candidate.characterId().toString()); + scope.put("sessionId", candidate.sessionId()); + scope.put("bindingGeneration", bindingGeneration.toString()); + scope.put("catalogRevision", Long.toString(target.catalogRevision())); + scope.put("pointerVersion", Long.toString(target.pointerVersion())); + scope.put("regionId", candidate.regionId().toString()); + scope.put("regionEpoch", candidate.regionEpoch().toString()); + carrier.put("bindingScope", scope); + carrier.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", candidate.issuerAuthGeneration().toString(), + "accountAuthorityGeneration", "1", + "tenantAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1"), + "membershipAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1"), + "privateRealmGrantVersions", List.of())); + carrier.put("issuanceFence", "1"); + carrier.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", "ACTIVE", + "membershipVersion", Map.of(candidate.tenantId().toString(), "1"), + "membershipAuthorityGeneration", "1")); + String prefix = "account:auth-authority:v1:"; + List> checkpoints = new java.util.ArrayList<>(); + for (String stream : + List.of( + "account/" + candidate.accountId(), + "issuer/" + candidate.issuerId(), + "membership/" + candidate.accountId() + "/" + candidate.tenantId(), + "tenant/" + candidate.tenantId())) { + checkpoints.add( + Map.of( + "outboxStreamKey", + prefix + stream, + "outboxSequence", + stream.startsWith("membership/") || stream.startsWith("tenant/") ? "1" : "0")); + } + carrier.put("outboxCheckpoints", checkpoints); + carrier.put( + "tokenIdentityEvidence", + Map.ofEntries( + Map.entry("accountId", candidate.accountId().toString()), + Map.entry("operationId", UUID.randomUUID().toString()), + Map.entry("issuanceRequestId", UUID.randomUUID().toString()), + Map.entry("tokenJti", UUID.randomUUID().toString()), + Map.entry("tokenSHA256", "a".repeat(64)), + Map.entry("tokenProfile", "game-session-account-delegation"), + Map.entry("tokenGeneration", "1"), + Map.entry("issuanceFence", "1"), + Map.entry("tokenIdentityFence", "1"), + Map.entry("issuedAt", nowSeconds), + Map.entry("notBefore", nowSeconds), + Map.entry("expiresAt", Long.toString(now / 1000L + 60L)))); + carrier.put("evaluatedAt", Long.toString(now)); + carrier.put( + "expiresAt", + Long.toString(now + AccountGameplayAdmissionLeaseEvidence.MAX_DURATION_MILLIS)); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + } + + private void seedQualifiedBootstrapMembers(int count) { + var inventoryRepository = new CanonicalGameplayBindingInventoryRepository(dsl); + for (int index = 0; index < count; index++) { + seedQualifiedBootstrapMember(inventoryRepository); + } + } + + private void seedQualifiedBootstrapMember( + CanonicalGameplayBindingInventoryRepository inventoryRepository) { + var candidate = + new CanonicalGameplayBindingIdentity( + UUID.randomUUID(), + identity.tenantId(), + identity.playableStateNamespaceId(), + UUID.randomUUID(), + identity.playableStateScope(), + identity.gameInstanceId(), + identity.runtimeGameInstanceId(), + UUID.randomUUID().toString(), + identity.regionId(), + identity.regionEpoch(), + identity.issuerId(), + identity.issuerAuthGeneration(), + identity.issuerIndexLayoutVersion(), + identity.issuerIndexPartitionCount(), + identity.issuerIndexPartitionCapacity()); + var reservation = + new CanonicalIssuerReservationFenceEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + BigInteger.ONE, + BigInteger.TWO, + BigInteger.ONE); + UUID transitionId = UUID.randomUUID(); + inventoryRepository.prepare( + new CanonicalGameplayBindingTransitionRequest( + transitionId, UUID.randomUUID(), candidate, reservation, null, null)); + var prepared = inventoryRepository.readProvisionalCasEvidence(transitionId); + var lease = + controlledLeaseEvidence(candidate, prepared.transition().bindingGeneration(), target); + inventoryRepository.markProvisional( + prepared, + new CanonicalGameplayAdmissionDecision( + transitionId, + lease, + candidate, + prepared.transition().bindingGeneration(), + null, + target)); + } + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint trustedSourceCheckpoint(String issuerId, BigInteger generation) { if (BigInteger.ONE.equals(generation)) { 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 2a4c14a406..bdc5c5792c 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 @@ -281,7 +281,7 @@ void registersOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() CanonicalGameplayIssuerRedisKeys.forPartition( intent.layoutDescriptor(), BigInteger.ZERO) .getBytes(StandardCharsets.US_ASCII))) - .isEqualTo(1L); + .isEqualTo(2L); String afterFirstRegistration = localRegistrationImage(dsl); CanonicalGameplayIssuerBindingLocalOperation replay = @@ -421,7 +421,7 @@ void registersOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() CanonicalGameplayIssuerRedisKeys.forPartition( intent.layoutDescriptor(), BigInteger.ZERO) .getBytes(StandardCharsets.US_ASCII))) - .isEqualTo(1L); + .isEqualTo(2L); } private CanonicalGameplayIssuerBootstrapCoverageOwner initialCoverageOwner( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java index 14b24ee0b5..2cb1d88a1f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java @@ -2,16 +2,20 @@ 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 io.lettuce.core.AclSetuserArgs; import io.lettuce.core.ClientOptions; import io.lettuce.core.RedisClient; import io.lettuce.core.RedisURI; +import io.lettuce.core.ScriptOutputType; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.sync.RedisCommands; import io.lettuce.core.codec.ByteArrayCodec; import io.lettuce.core.protocol.CommandKeyword; import io.lettuce.core.protocol.CommandType; +import java.io.IOException; +import java.io.InputStream; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.StandardCharsets; @@ -19,11 +23,14 @@ import java.sql.Connection; import java.sql.SQLException; import java.time.Duration; +import java.util.ArrayList; +import java.util.Base64; import java.util.EnumSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; @@ -43,6 +50,7 @@ import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; @@ -58,8 +66,10 @@ import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.ObjectNode; -/** Actual PostgreSQL/Redis proof for local ordinary NEW registration after the installed anchor. */ +/** Actual PostgreSQL/Redis proof for local ordinary NEW physical projection and refusals. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") class CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest { @@ -68,9 +78,11 @@ class CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest { private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; private static final String OWNER_PRINCIPAL = "gamesession_coord_app"; private static final String ISSUER_KEY_PREFIX = "session:game:index:issuer:"; + private static final String METADATA_FIELD = "!issuer-partition-bootstrap/v1"; private static final BigInteger LAYOUT_VERSION = BigInteger.valueOf(3); private static final BigInteger PARTITION_COUNT = BigInteger.ONE; private static final BigInteger PARTITION_CAPACITY = BigInteger.valueOf(2); + private static final JsonMapper JSON = JsonMapper.builder().build(); @Container private static final PostgreSQLContainer POSTGRES = @@ -125,7 +137,7 @@ void tearDown() { } @Test - void registersOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() throws Exception { + void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() throws Exception { DSLContext dsl = schema.dsl(); establishActualLegacyDisposition(dsl); var layout = descriptor(); @@ -291,7 +303,7 @@ void registersOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() CanonicalGameplayIssuerRedisKeys.forPartition( intent.layoutDescriptor(), BigInteger.ZERO) .getBytes(StandardCharsets.US_ASCII))) - .isEqualTo(1L); + .isEqualTo(2L); var projectionOwner = projectionOwner(dsl, currentState::get); var firstCapacityOnly = projectionOwner.projectAndRead(first); @@ -307,6 +319,44 @@ void registersOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() .containsEntry(firstCapacityField, first.exactMemberValueBytes()); assertThat(firstCapacityFields) .doesNotContainKey(new String(firstCandidate.bindingRef().bytes(), StandardCharsets.UTF_8)); + + AtomicInteger sourceReadCount = new AtomicInteger(); + var currentStateDisappearsAfterSqlRead = + (CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource) + () -> sourceReadCount.incrementAndGet() <= 2 ? initialState : null; + var unavailableBeforeRedisWrite = projectionOwner(dsl, currentStateDisappearsAfterSqlRead); + Map beforeUnavailable = + hashImage( + CanonicalGameplayIssuerRedisKeys.forPartition( + intent.layoutDescriptor(), BigInteger.ZERO) + .getBytes(StandardCharsets.US_ASCII)); + Throwable unavailable = catchThrowable(() -> unavailableBeforeRedisWrite.projectAndRead(first)); + assertThat(unavailable) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Issuer binding-local projection is unavailable") + .hasNoCause(); + assertThat(sourceReadCount).hasValue(3); + assertThat( + hashImage( + CanonicalGameplayIssuerRedisKeys.forPartition( + intent.layoutDescriptor(), BigInteger.ZERO) + .getBytes(StandardCharsets.US_ASCII))) + .isEqualTo(beforeUnavailable); + + byte[] partitionKey = + CanonicalGameplayIssuerRedisKeys.forPartition(intent.layoutDescriptor(), BigInteger.ZERO) + .getBytes(StandardCharsets.US_ASCII); + Map beforeMalformedRelease = hashImage(partitionKey); + byte[][] malformedReleaseBaseline = + malformedReleaseBaselineArguments(partitionKey, firstCapacityField); + assertThat( + evalOwnerScript( + CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.RESOURCE_PATH, + partitionKey, + malformedReleaseBaseline)) + .isEqualTo(-2L); + assertThat(hashImage(partitionKey)).isEqualTo(beforeMalformedRelease); + assertThat(projectionOwner.projectAndRead(first).scriptOutcome()).isEqualTo(3L); assertThat(anchorImage(dsl)).isEqualTo(installedAnchorImage); assertThat(proofImage(dsl)).isEqualTo(installedProofImage); @@ -473,7 +523,7 @@ void registersOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( second.reservation().reservationId()); byte[] secondCapacityFieldBytes = secondCapacityField.getBytes(StandardCharsets.US_ASCII); - assertThat(administratorCommands.hlen(key)).isEqualTo(4L); + assertThat(administratorCommands.hlen(key)).isEqualTo(5L); assertThat(firstProjectedFields) .containsEntry(secondCapacityField, second.exactMemberValueBytes()); @@ -547,7 +597,7 @@ void registersOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() assertThatThrownBy(() -> projectionOwner.projectAndRead(second)) .isInstanceOf(IllegalStateException.class); assertThat(administratorCommands.persist(key)).isTrue(); - assertThat(administratorCommands.hlen(key)).isEqualTo(4L); + assertThat(administratorCommands.hlen(key)).isEqualTo(5L); var fencedCandidate = identityForAccount("account-fenced", firstCandidate.accountId()); new CanonicalGameplayAccountAdmissionBarrierRepository(dsl) @@ -563,6 +613,55 @@ void registersOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() assertThat(localRegistrationImage(dsl)).isEqualTo(accountFencedImage); } + @Test + void malformedLuaBindingReferenceAndReleaseCountsRefuseWithoutChangingPartition() + throws Exception { + byte[] key = + (ISSUER_KEY_PREFIX + "malformed-input-vectors").getBytes(StandardCharsets.US_ASCII); + byte[] markerField = "original-field".getBytes(StandardCharsets.US_ASCII); + byte[] markerValue = "original-value".getBytes(StandardCharsets.US_ASCII); + administratorCommands.hset(key, markerField, markerValue); + Map before = hashImage(key); + + byte[] malformedBindingRef = "13:bindingRef/v1".getBytes(StandardCharsets.US_ASCII); + byte[] minimalMember = + ("{\"reservation\":{\"reservationId\":\"00000000-0000-0000-0000-000000000001\"," + + "\"lifecycle\":\"RESERVED\"}}") + .getBytes(StandardCharsets.UTF_8); + List addArguments = + new ArrayList<>( + List.of( + ascii(ISSUER), + ascii("0"), + ascii("1"), + ascii("2"), + ascii("1"), + malformedBindingRef, + minimalMember)); + while (addArguments.size() < 13) addArguments.add(ascii("unused")); + assertThat( + evalOwnerScript( + CanonicalGameplayIssuerBindingLocalRedisScriptContribution.RESOURCE_PATH, + key, + addArguments.toArray(byte[][]::new))) + .isEqualTo(-2L); + assertThat(hashImage(key)).isEqualTo(before); + + for (String malformedCount : List.of("1.5", "0x1", "1e0", "9".repeat(256))) { + List releaseArguments = + new ArrayList<>( + List.of(ascii(ISSUER), ascii("0"), ascii("1"), ascii("2"), ascii(malformedCount))); + while (releaseArguments.size() < 16) releaseArguments.add(ascii("unused")); + assertThat( + evalOwnerScript( + CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.RESOURCE_PATH, + key, + releaseArguments.toArray(byte[][]::new))) + .isEqualTo(-2L); + assertThat(hashImage(key)).isEqualTo(before); + } + } + private static ConcurrentProjections concurrentProjection( CanonicalGameplayIssuerBindingLocalRedisOwner owner, CanonicalGameplayIssuerBindingLocalOperation first, @@ -572,8 +671,19 @@ private static ConcurrentProjections concurrentProjection( try { var firstCall = callers.submit(() -> owner.projectAndRead(first)); var secondCall = callers.submit(() -> owner.projectAndRead(second)); - return new ConcurrentProjections( - firstCall.get(30, TimeUnit.SECONDS), secondCall.get(30, TimeUnit.SECONDS)); + var secondResult = secondCall.get(30, TimeUnit.SECONDS); + CanonicalGameplayIssuerBindingLocalRedisOwner.Readback firstResult; + try { + firstResult = firstCall.get(30, TimeUnit.SECONDS); + } catch (java.util.concurrent.ExecutionException failure) { + assertThat(failure.getCause()) + .isInstanceOf(IllegalStateException.class) + .hasMessageStartingWith("Issuer binding-local projection is unavailable"); + // The same-partition writer may fence a concurrent read-only replay. Retry the original + // operation only after that writer has positively completed; never replay an old write. + firstResult = owner.projectAndRead(first); + } + return new ConcurrentProjections(firstResult, secondResult); } finally { callers.shutdownNow(); } @@ -602,6 +712,70 @@ private CanonicalGameplayIssuerBindingLocalRedisOwner projectionOwner( source); } + private byte[][] malformedReleaseBaselineArguments(byte[] key, String malformedCapacityField) + throws IOException { + Map baseline = new TreeMap<>(); + administratorCommands + .hgetall(key) + .forEach( + (field, value) -> + baseline.put(new String(field, StandardCharsets.UTF_8), value.clone())); + assertThat(baseline).containsKey(METADATA_FIELD).containsKey(malformedCapacityField); + + ObjectNode malformedMember = + (ObjectNode) JSON.readTree(Objects.requireNonNull(baseline.get(malformedCapacityField))); + malformedMember.remove("memberOperation"); + baseline.put(malformedCapacityField, JSON.writeValueAsBytes(malformedMember)); + + List arguments = new ArrayList<>(); + arguments.add(ascii(ISSUER)); + arguments.add(ascii("0")); + arguments.add(ascii(PARTITION_COUNT.toString())); + arguments.add(ascii(PARTITION_CAPACITY.toString())); + arguments.add(ascii(Integer.toString(baseline.size()))); + baseline.forEach( + (field, value) -> { + arguments.add(field.getBytes(StandardCharsets.UTF_8)); + arguments.add(value); + }); + while (arguments.size() < 16) arguments.add(ascii("unused")); + return arguments.toArray(byte[][]::new); + } + + private long evalOwnerScript(String resourcePath, byte[] key, byte[][] arguments) + throws IOException { + byte[] script; + try (InputStream input = getClass().getClassLoader().getResourceAsStream(resourcePath)) { + if (input == null) throw new IOException("Redis Lua test resource is missing"); + script = input.readAllBytes(); + } + try (StatefulRedisConnection connection = + ownerClient.connect(ByteArrayCodec.INSTANCE)) { + RedisCommands commands = connection.sync(); + assertThat(commands.aclWhoami()).isEqualTo(OWNER_PRINCIPAL); + String sha = commands.scriptLoad(script); + return Objects.requireNonNull( + commands.evalsha(sha, ScriptOutputType.INTEGER, new byte[][] {key}, arguments), + "Expected integer Redis Lua outcome"); + } + } + + private Map hashImage(byte[] key) { + Map image = new TreeMap<>(); + administratorCommands + .hgetall(key) + .forEach( + (field, value) -> + image.put( + Base64.getEncoder().encodeToString(field), + Base64.getEncoder().encodeToString(value))); + return image; + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor descriptor() { String exact = diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java index b4a323197f..86e5a06a63 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java @@ -207,9 +207,9 @@ void installsOnlyAfterEveryPopulatedAndEmptyPartitionHasExactPhysicalProofAndRep assertThat(administratorCommands.type(key)).isEqualTo("hash"); assertThat(administratorCommands.pttl(key)).isEqualTo(-1L); if (partitionId.equals(fixture.activePartition())) { - assertThat(administratorCommands.hlen(key)).isEqualTo(3L); + assertThat(administratorCommands.hlen(key)).isEqualTo(4L); } else { - assertThat(administratorCommands.hlen(key)).isEqualTo(1L); + assertThat(administratorCommands.hlen(key)).isEqualTo(2L); } } assertThat(originalReservationImage(fixture.dsl())).isEqualTo(originalReservationImage); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java index 4bfd924115..84fdd821ee 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java @@ -169,7 +169,7 @@ void buildsCompletePopulatedPartitionAndCountsReleasedOnlyAsRetainedEvidence() { var firstOwner = owner(work, currentState(fixture, work)); var first = firstOwner.buildAndRead(work); - assertThat(first.physicalFieldCount()).isEqualTo(4); + assertThat(first.physicalFieldCount()).isEqualTo(5); assertThat(first.physicalPartitionReservationCount()).isEqualTo(2); assertThat(first.physicalBindingCount()).isEqualTo(1); assertThat(first.physicalCountedCapacityCount()).isEqualTo(1); @@ -191,7 +191,7 @@ void buildsCompletePopulatedPartitionAndCountsReleasedOnlyAsRetainedEvidence() { byte[] key = key(fixture, work.partitionId()); assertThat(administratorCommands.type(key)).isEqualTo("hash"); assertThat(administratorCommands.pttl(key)).isEqualTo(-1L); - assertThat(administratorCommands.hlen(key)).isEqualTo(4L); + assertThat(administratorCommands.hlen(key)).isEqualTo(5L); assertThat(statusesRemainPending(fixture.dsl())).isTrue(); } @@ -209,11 +209,11 @@ void positivelyPreparedEmptyPartitionBuildsOnlyItsCommonMetadata() { assertThat(administratorCommands.type(key)).isEqualTo("none"); var readback = owner(work, currentState(fixture, work)).buildAndRead(work); - assertThat(readback.physicalFieldCount()).isEqualTo(1); + assertThat(readback.physicalFieldCount()).isEqualTo(2); assertThat(readback.physicalPartitionReservationCount()).isZero(); assertThat(readback.physicalCountedCapacityCount()).isZero(); assertThat(readback.plannedAggregateCapacityCount()).isEqualTo(BigInteger.ONE); - assertThat(administratorCommands.hlen(key)).isEqualTo(1L); + assertThat(administratorCommands.hlen(key)).isEqualTo(2L); assertThat(statusesRemainPending(fixture.dsl())).isTrue(); } @@ -272,7 +272,7 @@ void sameBindingWithDifferentAnchorReservationLifecycleOrLocalOperationIsAConfli .isInstanceOf(IllegalStateException.class) .hasMessageContaining("projection is unavailable"); assertThat(administratorCommands.hget(key, bindingField)).containsExactly(conflict); - assertThat(administratorCommands.hlen(key)).isEqualTo(3L); + assertThat(administratorCommands.hlen(key)).isEqualTo(4L); administratorCommands.hset(key, bindingField, exact); } assertThat(statusesRemainPending(fixture.dsl())).isTrue(); @@ -391,7 +391,7 @@ void changedFreshCheckpointOrIncarnationBeforeAndAfterRedisLeavesNoReadbackCapab .isInstanceOf(IllegalStateException.class); assertThat(afterCheckpointCalls).hasValue(2); assertThat(administratorCommands.type(key)).isEqualTo("hash"); - assertThat(administratorCommands.hlen(key)).isEqualTo(3L); + assertThat(administratorCommands.hlen(key)).isEqualTo(4L); AtomicInteger afterCalls = new AtomicInteger(); var changedAfterOwner = @@ -407,7 +407,7 @@ void changedFreshCheckpointOrIncarnationBeforeAndAfterRedisLeavesNoReadbackCapab .isInstanceOf(IllegalStateException.class); assertThat(afterCalls).hasValue(2); assertThat(administratorCommands.type(key)).isEqualTo("hash"); - assertThat(administratorCommands.hlen(key)).isEqualTo(3L); + assertThat(administratorCommands.hlen(key)).isEqualTo(4L); assertThat(statusesRemainPending(fixture.dsl())).isTrue(); } @@ -431,7 +431,7 @@ void retainedCommitAfterLostReplyReplaysFromFreshSqlWorkAndSeparatePhysicalReadb partitionWork(fixture, work.partitionId()); var readback = owner(restartedWork, currentState(fixture, restartedWork)).buildAndRead(restartedWork); - assertThat(readback.physicalFieldCount()).isEqualTo(3); + assertThat(readback.physicalFieldCount()).isEqualTo(4); assertThat(readback.physicalCountedCapacityCount()).isEqualTo(1); assertThat(statusesRemainPending(fixture.dsl())).isTrue(); } 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 788fb1d348..5bad360faf 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 @@ -61,6 +61,370 @@ class CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest { static PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Test + void v1037RemovesOnlyDuplicateFirstNewReleaseGuards() { + TestSchema testSchema = newTestSchemaAtVersion("gs_issuer_release_guard_", "1036"); + try { + assertThat( + triggerExists( + testSchema.dsl(), + "game_session_canonical_issuer_partition_reservation", + "game_session_first_new_issuer_release_reservation")) + .isTrue(); + assertThat(functionExists(testSchema.dsl(), "require_first_new_issuer_release_reservation()")) + .isTrue(); + assertThat( + triggerExists( + testSchema.dsl(), + "game_session_canonical_binding_account_index_obligation", + "game_session_first_new_issuer_release_account_atomic")) + .isTrue(); + + migrateThrough1037(testSchema); + + assertThat( + triggerExists( + testSchema.dsl(), + "game_session_canonical_issuer_partition_reservation", + "game_session_first_new_issuer_release_reservation")) + .isFalse(); + assertThat(functionExists(testSchema.dsl(), "require_first_new_issuer_release_reservation()")) + .isFalse(); + assertThat( + triggerExists( + testSchema.dsl(), + "game_session_canonical_binding_account_index_obligation", + "game_session_first_new_issuer_release_account_atomic")) + .isFalse(); + + assertThat( + triggerExists( + testSchema.dsl(), + "game_session_canonical_issuer_partition_reservation", + "game_session_first_new_abort_reservation_release")) + .isTrue(); + assertThat( + triggerExists( + testSchema.dsl(), + "game_session_canonical_binding_account_index_obligation", + "game_session_first_new_abort_account_phase_atomic")) + .isTrue(); + assertThat( + triggerExists( + testSchema.dsl(), + "game_session_canonical_issuer_partition_reservation", + "game_session_first_new_issuer_release_reservation_atomic")) + .isTrue(); + + String retainedReservationGuard = + testSchema + .dsl() + .fetchSingle( + "SELECT pg_get_functiondef(to_regprocedure(?))", + "require_first_new_abort_reservation_release()") + .get(0, String.class); + assertThat(retainedReservationGuard) + .contains("OLD.lifecycle = 'RELEASE_PENDING' AND NEW.lifecycle = 'RELEASED'") + .contains("release.physical_readback_field_set_bytes IS NOT NULL") + .contains( + "First-NEW reservation release requires its exact completed physical issuer proof"); + } finally { + dropSchema(testSchema.schema()); + } + } + + @Test + void v1038PhysicalIssuerHistoryRejectsTruncateCascade() { + TestSchema testSchema = newTestSchemaAtVersion("gs_issuer_physical_history_", "1037"); + try { + migrateThrough1038(testSchema); + assertThat( + triggerExists( + testSchema.dsl(), + "game_session_canonical_issuer_partition_mutation_head", + "trg_gs_issuer_partition_mutation_head_no_truncate")) + .isTrue(); + assertThat( + triggerExists( + testSchema.dsl(), + "game_session_canonical_issuer_partition_mutation", + "trg_gs_issuer_partition_mutation_no_truncate")) + .isTrue(); + assertThat( + triggerExists( + testSchema.dsl(), + "game_session_canonical_issuer_binding_local_retirement", + "trg_gs_issuer_local_retirement_no_truncate")) + .isTrue(); + assertThat( + functionExists( + testSchema.dsl(), "reject_canonical_issuer_physical_history_truncate()")) + .isTrue(); + assertThat( + triggerDefinition( + testSchema.dsl(), + "game_session_canonical_issuer_partition_mutation", + "trg_gs_issuer_partition_mutation_history")) + .contains("INSERT") + .contains("UPDATE") + .contains("DELETE") + .contains("guard_canonical_issuer_partition_mutation_history"); + assertThat( + triggerDefinition( + testSchema.dsl(), + "game_session_canonical_issuer_binding_local_retirement", + "trg_gs_issuer_binding_local_retirement")) + .contains("INSERT") + .contains("UPDATE") + .contains("DELETE") + .contains("guard_canonical_issuer_binding_local_retirement"); + + var fixture = pendingFixture(testSchema); + UUID initialRevision = UUID.randomUUID(); + testSchema + .dsl() + .execute( + "INSERT INTO game_session_canonical_issuer_partition_mutation_head" + + " (issuer_id, partition_id, bootstrap_operation_id, initial_revision," + + " current_revision, state) VALUES (?, 0, ?, ?, ?, 'INITIAL_INSTALL_PENDING')", + ISSUER, + fixture.intent().operationId(), + initialRevision, + initialRevision); + assertThatThrownBy( + () -> + testSchema + .dsl() + .execute( + "INSERT INTO game_session_canonical_issuer_partition_mutation" + + " (mutation_id, issuer_id, partition_id, mutation_kind, owner_operation_id," + + " expected_revision, successor_revision, exact_intended_change_bytes," + + " exact_intended_change_digest, status)" + + " VALUES (?, ?, 0, 'ADD_CAPACITY', ?, ?, ?, ?, ?, 'PENDING_PHYSICAL_PROOF')", + UUID.randomUUID(), + ISSUER, + UUID.randomUUID(), + initialRevision, + UUID.randomUUID(), + new byte[] {1}, + "sha256:" + "a".repeat(64))) + .isInstanceOfSatisfying( + DataAccessException.class, + exception -> assertThat(exception.sqlState()).isEqualTo("23514")); + + List headBefore = + rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_mutation_head"); + List mutationsBefore = + rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_mutation"); + List retirementsBefore = + rowImages(testSchema.dsl(), "game_session_canonical_issuer_binding_local_retirement"); + List migrationHistoryBefore = migrationHistorySnapshot(testSchema.dsl()); + assertThat(headBefore).hasSize(1); + assertThat(mutationsBefore).isEmpty(); + assertThat(retirementsBefore).isEmpty(); + + assertThatThrownBy( + () -> + testSchema + .dsl() + .execute( + "TRUNCATE TABLE" + + " game_session_canonical_issuer_partition_mutation_head," + + " game_session_canonical_issuer_partition_mutation," + + " game_session_canonical_issuer_binding_local_retirement CASCADE")) + .isInstanceOfSatisfying( + DataAccessException.class, + exception -> assertThat(exception.sqlState()).isEqualTo("23514")); + + assertThat( + rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_mutation_head")) + .containsExactlyElementsOf(headBefore); + assertThat(rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_mutation")) + .containsExactlyElementsOf(mutationsBefore); + assertThat( + rowImages(testSchema.dsl(), "game_session_canonical_issuer_binding_local_retirement")) + .containsExactlyElementsOf(retirementsBefore); + assertThat(migrationHistorySnapshot(testSchema.dsl())) + .containsExactlyElementsOf(migrationHistoryBefore); + } finally { + dropSchema(testSchema.schema()); + } + } + + @Test + void v1038RetainsLegacyBootstrapProofWithoutQualifyingCurrentRevision() { + TestSchema historicalSchema = newTestSchemaAtVersion("gs_issuer_legacy_proof_", "1037"); + TestSchema newProofSchema = newTestSchemaAtVersion("gs_issuer_new_proof_", "1037"); + try { + var historicalFixture = pendingFixture(historicalSchema); + var historicalPlan = + new CanonicalGameplayIssuerPartitionBuildRepository(historicalSchema.dsl()) + .prepareInitialBuildPlan( + historicalFixture.intent().operationId(), historicalFixture.requestId()); + assertThat(historicalPlan.state()) + .isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED); + insertControlledBootstrapProof(historicalSchema.dsl(), historicalFixture, historicalPlan); + List legacyProofBefore = + rowImages( + historicalSchema.dsl(), "game_session_canonical_issuer_bootstrap_partition_proof"); + assertThat(legacyProofBefore).hasSize(1); + + migrateThrough1038(historicalSchema); + String mutationHeadGuard = + historicalSchema + .dsl() + .fetchSingle( + "SELECT pg_get_functiondef(to_regprocedure(?))", + "guard_canonical_issuer_partition_mutation_head()") + .get(0, String.class); + assertThat(mutationHeadGuard) + .contains("proof.initial_physical_mutation_revision = OLD.initial_revision"); + assertThat( + historicalSchema + .dsl() + .fetchSingle( + "SELECT initial_physical_mutation_revision" + + " FROM game_session_canonical_issuer_bootstrap_partition_proof" + + " WHERE bootstrap_operation_id = ? AND partition_id = 0", + historicalFixture.intent().operationId()) + .get(0, UUID.class)) + .isNull(); + assertThat( + historicalSchema + .dsl() + .fetch( + "SELECT (to_jsonb(proof) - 'initial_physical_mutation_revision')::text" + + " AS row_image FROM game_session_canonical_issuer_bootstrap_partition_proof proof" + + " ORDER BY partition_id") + .getValues("row_image", String.class)) + .containsExactlyElementsOf(legacyProofBefore); + + UUID historicalInitialRevision = UUID.randomUUID(); + assertThatThrownBy( + () -> + historicalSchema + .dsl() + .execute( + "INSERT INTO game_session_canonical_issuer_partition_mutation_head" + + " (issuer_id, partition_id, bootstrap_operation_id, initial_revision," + + " current_revision, state)" + + " VALUES (?, 0, ?, ?, ?, 'INITIAL_INSTALL_PENDING')", + ISSUER, + historicalFixture.intent().operationId(), + historicalInitialRevision, + historicalInitialRevision)) + .isInstanceOfSatisfying( + DataAccessException.class, + exception -> assertThat(exception.sqlState()).isEqualTo("P0001")); + assertThat( + rowImages( + historicalSchema.dsl(), "game_session_canonical_issuer_partition_mutation_head")) + .isEmpty(); + + migrateThrough1038(newProofSchema); + var newProofFixture = pendingFixture(newProofSchema); + var newProofPlan = + new CanonicalGameplayIssuerPartitionBuildRepository(newProofSchema.dsl()) + .prepareInitialBuildPlan( + newProofFixture.intent().operationId(), newProofFixture.requestId()); + assertThat(newProofPlan.state()) + .isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED); + UUID newInitialRevision = UUID.randomUUID(); + newProofSchema + .dsl() + .execute( + "INSERT INTO game_session_canonical_issuer_partition_mutation_head" + + " (issuer_id, partition_id, bootstrap_operation_id, initial_revision," + + " current_revision, state) VALUES (?, 0, ?, ?, ?, 'INITIAL_INSTALL_PENDING')", + ISSUER, + newProofFixture.intent().operationId(), + newInitialRevision, + newInitialRevision); + assertThatThrownBy( + () -> + insertControlledBootstrapProof( + newProofSchema.dsl(), newProofFixture, newProofPlan, null)) + .isInstanceOfSatisfying( + DataAccessException.class, + exception -> assertThat(exception.sqlState()).isEqualTo("23514")); + assertThatThrownBy( + () -> + insertControlledBootstrapProof( + newProofSchema.dsl(), newProofFixture, newProofPlan, UUID.randomUUID())) + .isInstanceOfSatisfying( + DataAccessException.class, + exception -> { + assertThat(exception.sqlState()).isEqualTo("23514"); + assertThat(exception.getMessage()).contains("exact SQL-installed initial revision"); + }); + assertThat( + rowImages( + newProofSchema.dsl(), "game_session_canonical_issuer_bootstrap_partition_proof")) + .isEmpty(); + } finally { + dropSchema(historicalSchema.schema()); + dropSchema(newProofSchema.schema()); + } + } + + @Test + void cohortOrdinalsFollowCanonicalSortedPositionForUnsortedRows() { + String digestA = "sha256:" + "a".repeat(64); + String digestB = "sha256:" + "b".repeat(64); + String digestC = "sha256:" + "c".repeat(64); + List unsortedRows = + List.of( + new CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow( + 29L, + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.TRANSITION, + "z-transition", + BigInteger.valueOf(7), + "{\"source\":\"transition\"}", + digestC), + new CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow( + 13L, + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.RESERVATION, + "b-reservation", + BigInteger.valueOf(6), + "{\"source\":\"reservation-b\"}", + digestB), + new CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow( + 4L, + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.RESERVATION, + "a-reservation", + BigInteger.valueOf(5), + "{\"source\":\"reservation-a\"}", + digestA)); + + List numberedRows = + CanonicalGameplayIssuerPartitionBuildRepository.assignCanonicalCohortOrdinals(unsortedRows); + + assertThat(numberedRows) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::rowOrdinal) + .containsExactly(0L, 1L, 2L); + assertThat(numberedRows) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::kind) + .containsExactly( + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.RESERVATION, + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.RESERVATION, + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.TRANSITION); + assertThat(numberedRows) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceKey) + .containsExactly("a-reservation", "b-reservation", "z-transition"); + assertThat(numberedRows) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceInventoryRevision) + .containsExactly(BigInteger.valueOf(5), BigInteger.valueOf(6), BigInteger.valueOf(7)); + assertThat(numberedRows) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceRowJson) + .containsExactly( + "{\"source\":\"reservation-a\"}", + "{\"source\":\"reservation-b\"}", + "{\"source\":\"transition\"}"); + assertThat(numberedRows) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceRowDigest) + .containsExactly(digestA, digestB, digestC); + } + @Test void populatedPendingIntentRetainsCompleteCohortAndBothCoverageTuplesAcrossConcurrentRetry() throws Exception { @@ -1305,6 +1669,30 @@ private static void migrateThrough1032(TestSchema testSchema) { .migrate(); } + 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(); + } + + 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(); + } + private static void migrateRemaining(TestSchema testSchema) { Flyway.configure() .dataSource(testSchema.dataSource()) @@ -1342,6 +1730,107 @@ private static TestSchema newLegacyIssuerTestSchema(String prefix) { return new TestSchema(schema, dataSource, dsl); } + private static boolean triggerExists(DSLContext dsl, String table, String trigger) { + return Boolean.TRUE.equals( + dsl.fetchSingle( + "SELECT EXISTS (SELECT 1 FROM pg_trigger" + + " WHERE tgrelid = to_regclass(?) AND tgname = ? AND NOT tgisinternal)", + table, + trigger) + .get(0, Boolean.class)); + } + + private static String triggerDefinition(DSLContext dsl, String table, String trigger) { + return dsl.fetchSingle( + "SELECT pg_get_triggerdef(trigger_row.oid) FROM pg_trigger trigger_row" + + " WHERE trigger_row.tgrelid = to_regclass(?) AND trigger_row.tgname = ?" + + " AND NOT trigger_row.tgisinternal", + table, + trigger) + .get(0, String.class); + } + + private static boolean functionExists(DSLContext dsl, String functionSignature) { + return Boolean.TRUE.equals( + dsl.fetchSingle("SELECT to_regprocedure(?) IS NOT NULL", functionSignature) + .get(0, Boolean.class)); + } + + /** Inserts controlled, non-admitting bytes to exercise proof storage and migration only. */ + private static void insertControlledBootstrapProof( + DSLContext dsl, Fixture fixture, CanonicalGameplayIssuerPartitionBuildPlan plan) { + dsl.execute( + "INSERT INTO game_session_canonical_issuer_bootstrap_partition_proof" + + " (build_operation_id, bootstrap_operation_id, bootstrap_request_id, issuer_id," + + " build_plan_digest, bootstrap_operation_fence, bootstrap_coverage_fence," + + " issuer_inventory_snapshot_revision, layout_version, partition_count," + + " partition_capacity, mapping_identity, layout_descriptor_bytes," + + " layout_descriptor_digest, source_checkpoint_bytes, source_checkpoint_digest," + + " source_event_bytes, source_event_digest, incarnation_bytes, incarnation_digest," + + " partition_id, exact_metadata_bytes, exact_physical_field_set_bytes," + + " exact_physical_field_set_digest, physical_field_count, physical_reservation_count," + + " physical_binding_count, physical_counted_capacity_count," + + " planned_aggregate_capacity_count, proof_state)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, ?, ?, 0," + + " ?, ?, ?, 1, 0, 0, 0, 0, 'EXACT_PHYSICAL_READBACK')", + controlledBootstrapProofBindings(fixture, plan)); + } + + /** Attempts a new proof with no original physical revision; V1038 must reject this insert. */ + private static void insertControlledBootstrapProof( + DSLContext dsl, + Fixture fixture, + CanonicalGameplayIssuerPartitionBuildPlan plan, + UUID initialPhysicalMutationRevision) { + Object[] baseBindings = controlledBootstrapProofBindings(fixture, plan); + Object[] bindings = java.util.Arrays.copyOf(baseBindings, baseBindings.length + 1); + bindings[baseBindings.length] = initialPhysicalMutationRevision; + dsl.execute( + "INSERT INTO game_session_canonical_issuer_bootstrap_partition_proof" + + " (build_operation_id, bootstrap_operation_id, bootstrap_request_id, issuer_id," + + " build_plan_digest, bootstrap_operation_fence, bootstrap_coverage_fence," + + " issuer_inventory_snapshot_revision, layout_version, partition_count," + + " partition_capacity, mapping_identity, layout_descriptor_bytes," + + " layout_descriptor_digest, source_checkpoint_bytes, source_checkpoint_digest," + + " source_event_bytes, source_event_digest, incarnation_bytes, incarnation_digest," + + " partition_id, exact_metadata_bytes, exact_physical_field_set_bytes," + + " exact_physical_field_set_digest, physical_field_count, physical_reservation_count," + + " physical_binding_count, physical_counted_capacity_count," + + " planned_aggregate_capacity_count, proof_state, initial_physical_mutation_revision)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, ?, ?, 0," + + " ?, ?, ?, 1, 0, 0, 0, 0, 'EXACT_PHYSICAL_READBACK', ?)", + bindings); + } + + private static Object[] controlledBootstrapProofBindings( + Fixture fixture, CanonicalGameplayIssuerPartitionBuildPlan plan) { + var intent = fixture.intent(); + String digest = "sha256:" + "a".repeat(64); + return new Object[] { + plan.buildOperationId(), + intent.operationId(), + intent.requestId(), + intent.issuerId(), + plan.planDigest(), + intent.operationFence(), + intent.coverageFence(), + intent.inventorySnapshotRevision(), + intent.layoutDescriptor().layoutVersion(), + intent.layoutDescriptor().partitionCount(), + intent.layoutDescriptor().partitionCapacity(), + intent.layoutDescriptor().mappingIdentity(), + "test-only-layout-descriptor".getBytes(StandardCharsets.UTF_8), + digest, + "test-only-source-checkpoint".getBytes(StandardCharsets.UTF_8), + digest, + "test-only-incarnation".getBytes(StandardCharsets.UTF_8), + digest, + "test-only-metadata".getBytes(StandardCharsets.UTF_8), + "test-only-physical-field-set".getBytes(StandardCharsets.UTF_8), + digest + }; + } + private static void insertLegacyReservationBeforeIssuerStringConversion(DSLContext dsl) { UUID reservationId = UUID.randomUUID(); UUID transitionId = UUID.randomUUID(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java new file mode 100644 index 0000000000..e78c383521 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java @@ -0,0 +1,1091 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import io.lettuce.core.protocol.ProtocolVersion; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution; +import net.firedevops.firemud.test.TestContainerImages; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Actual PostgreSQL/Redis proof of bounded original-operation issuer capacity retirement. Account + * lease and abort inputs, launch target, issuer checkpoint, and incarnation remain controlled; Game + * Session prepares, projects, releases, retires, and reads back every state. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@Execution(ExecutionMode.SAME_THREAD) +class CanonicalGameplayIssuerPhysicalRetirementIntegrationTest { + private static final String OWNER_PRINCIPAL = "gamesession_coord_app"; + private static final String ISSUER_KEY_PREFIX = "session:game:index:issuer:"; + private static final BigInteger PARTITION_CAPACITY = BigInteger.valueOf(256); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + private static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + private RedisClient administrator; + private RedisClient issuerOwner; + private StatefulRedisConnection administratorConnection; + private RedisCommands administratorCommands; + + @BeforeEach + void setUp() { + String password = UUID.randomUUID().toString(); + administrator = createRedisClient(null, null); + administratorConnection = administrator.connect(ByteArrayCodec.INSTANCE); + administratorCommands = administratorConnection.sync(); + administratorCommands.aclSetuser( + OWNER_PRINCIPAL, + new AclSetuserArgs() + .reset() + .on() + .addPassword(password) + .keyPattern(ISSUER_KEY_PREFIX + "*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.HGET) + .addCommand(CommandType.HLEN) + .addCommand(CommandType.HGETALL) + .addCommand(CommandType.HSET) + .addCommand(CommandType.HDEL)); + issuerOwner = createRedisClient(OWNER_PRINCIPAL, password); + } + + @AfterEach + void tearDown() { + if (administratorConnection != null) administratorConnection.close(); + if (issuerOwner != null) issuerOwner.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + if (administrator != null) administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + + @Test + void retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound() throws Exception { + try (var fixture = newFixture()) { + byte[] partitionKey = fixture.issuerPartitionKey(); + byte[] initialFields = physicalFieldSet(partitionKey); + int baselineFieldCount = + fixture.originalBaselineReservationCount() + fixture.originalBaselineBindingCount(); + assertThat(decodeFields(initialFields).size()).isEqualTo(baselineFieldCount + 3); + + fixture.publishOriginalWithControlledAccountLease(); + var originalAbort = fixture.recordOriginalAccountAbort(); + assertThat(originalAbort.isAccountAborted()).isTrue(); + var originalRelease = completeReleaseAfterLostReply(fixture, null); + + String newerSeed = lifetimeSeed(2); + UUID newerOperationId = fixture.prepareOtherControllerNew(newerSeed); + var pendingAdd = fixture.prepareOtherAddMutation(newerSeed); + LuaInvocation staleAddInvocation = addInvocation(fixture, pendingAdd); + var addReadback = fixture.projectOtherControllerNew(newerSeed); + assertThat(addReadback.scriptOutcome()).isEqualTo(1L); + assertThat(fixture.retryOtherControllerNew(newerSeed)).isEqualTo(newerOperationId); + byte[] afterAdd = physicalFieldSet(partitionKey); + assertThat(fixture.projectOtherControllerNew(newerSeed).scriptOutcome()).isEqualTo(3L); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(afterAdd); + + fixture.publishOtherControllerNew(newerSeed); + assertThat(fixture.recordOtherAccountAbort(newerSeed).isAccountAborted()).isTrue(); + var pendingRelease = fixture.prepareIssuerRelease(newerSeed); + LuaInvocation staleReleaseInvocation = releaseInvocation(fixture, pendingRelease); + var releaseReadback = fixture.projectIssuerRelease(pendingRelease); + var newerRelease = fixture.completeIssuerRelease(pendingRelease, releaseReadback); + assertThat(newerRelease.status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); + byte[] beforeReleaseRetry = physicalFieldSet(partitionKey); + var completedReleaseRetry = fixture.prepareIssuerRelease(newerSeed); + var releaseRetryReadback = fixture.projectIssuerRelease(completedReleaseRetry); + assertThat(releaseRetryReadback.scriptOutcome()).isEqualTo(2L); + assertThat(releaseRetryReadback.exactPhysicalFieldSetBytes()) + .isEqualTo(newerRelease.exactPhysicalReadbackFieldSetBytes()); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeReleaseRetry); + + assertThat(releaseCount(fixture.dsl(), "RELEASED")).isEqualTo(2L); + assertThat(retirementCount(fixture.dsl())).isZero(); + byte[] beforeOldestRetirement = physicalFieldSet(partitionKey); + assertThat(capacityFieldCount(beforeOldestRetirement)).isEqualTo(2L); + assertThat(decodeFields(beforeOldestRetirement).size()).isEqualTo(baselineFieldCount + 4); + String historyBeforeOriginalRetirement = durableHistoryImage(fixture.dsl(), NIL_UUID); + + var pendingOldestRetirement = fixture.prepareIssuerRetirement(fixture.transitionId()); + assertThat(pendingOldestRetirement.release().operationId()) + .isEqualTo(originalRelease.operationId()); + assertThat(pendingOldestRetirement.status()) + .isEqualTo( + CanonicalGameplayIssuerBindingLocalRetirementOperation.Status.PENDING_PHYSICAL_PROOF); + LuaInvocation oldestRetirementInvocation = + retirementInvocation(fixture, pendingOldestRetirement); + + long operationCountBeforeBlockedAdmission = localOperationCount(fixture.dsl()); + assertThatThrownBy(() -> fixture.prepareOtherControllerNew("pending-retirement-blocked")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("same-partition physical mutation is unresolved"); + assertThat(localOperationCount(fixture.dsl())) + .isEqualTo(operationCountBeforeBlockedAdmission); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeOldestRetirement); + + fixture.moveIssuerSourceCheckpoint(); + assertThatThrownBy(() -> fixture.retireIssuerCapacity(pendingOldestRetirement)) + .isInstanceOf(IllegalStateException.class); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeOldestRetirement); + fixture.restoreIssuerState(); + + byte[] foreignField = "!issuer-test-foreign/v1".getBytes(StandardCharsets.US_ASCII); + byte[] foreignValue = "controlled-foreign-field".getBytes(StandardCharsets.US_ASCII); + byte[][] foreignFields = {foreignField}; + administratorCommands.hset(partitionKey, foreignField, foreignValue); + byte[] fieldsWithForeign = physicalFieldSet(partitionKey); + assertThatThrownBy(() -> fixture.retireIssuerCapacity(pendingOldestRetirement)) + .isInstanceOf(IllegalStateException.class); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(fieldsWithForeign); + administratorCommands.hdel(partitionKey, foreignFields); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeOldestRetirement); + + long lostRetirementReply = evaluate(oldestRetirementInvocation); + assertThat(lostRetirementReply).isEqualTo(1L); + byte[] afterUncommittedRetirement = physicalFieldSet(partitionKey); + assertRetirementFieldDelta( + beforeOldestRetirement, afterUncommittedRetirement, pendingOldestRetirement); + assertThat(retirementStatus(fixture.dsl(), pendingOldestRetirement.operationId())) + .isEqualTo("PENDING_PHYSICAL_PROOF"); + + var resumedOldestRetirement = fixture.prepareIssuerRetirement(fixture.transitionId()); + assertThat(resumedOldestRetirement.operationId()) + .isEqualTo(pendingOldestRetirement.operationId()); + assertThat(resumedOldestRetirement.physicalMutation().expectedRevision()) + .isEqualTo(pendingOldestRetirement.physicalMutation().expectedRevision()); + assertThat(resumedOldestRetirement.physicalMutation().successorRevision()) + .isEqualTo(pendingOldestRetirement.physicalMutation().successorRevision()); + var recoveredOldestProof = fixture.retireIssuerCapacity(resumedOldestRetirement); + assertThat(recoveredOldestProof.scriptOutcome()).isEqualTo(2L); + assertThat(recoveredOldestProof.exactAbsenceReadbackFieldSetBytes()) + .isEqualTo(afterUncommittedRetirement); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(afterUncommittedRetirement); + assertThat(durableHistoryImage(fixture.dsl(), NIL_UUID)) + .isEqualTo(historyBeforeOriginalRetirement); + assertThat(capacityFieldCount(afterUncommittedRetirement)).isEqualTo(1L); + String newerCapacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + newerRelease.releasedMemberValue().reservation().reservationId()); + assertThat(decodeFields(afterUncommittedRetirement)) + .containsEntry(newerCapacityField, newerRelease.exactReleasedMemberValueBytes()); + + byte[] beforeCompletedRetirementRetry = physicalFieldSet(partitionKey); + var completedOldestRetirement = fixture.prepareIssuerRetirement(fixture.transitionId()); + assertThat(completedOldestRetirement.status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalRetirementOperation.Status.RETIRED); + var completedOldestRetryProof = fixture.retireIssuerCapacity(completedOldestRetirement); + assertThat(completedOldestRetryProof.scriptOutcome()).isEqualTo(2L); + assertThat(completedOldestRetryProof.exactAbsenceReadbackFieldSetBytes()) + .isEqualTo(beforeCompletedRetirementRetry); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeCompletedRetirementRetry); + + assertStaleLuaRejectedWithoutWrites(staleAddInvocation, partitionKey); + assertStaleLuaRejectedWithoutWrites(staleReleaseInvocation, partitionKey); + + UUID newerTransitionId = fixture.otherOperation(newerSeed).request().transitionId(); + var pendingNewerRetirement = fixture.prepareIssuerRetirement(newerTransitionId); + byte[] beforeNewerRetirement = physicalFieldSet(partitionKey); + var completedNewerRetirement = fixture.retireIssuerCapacity(pendingNewerRetirement); + byte[] afterNewerRetirement = physicalFieldSet(partitionKey); + assertThat(completedNewerRetirement.scriptOutcome()).isEqualTo(1L); + assertThat(completedNewerRetirement.exactAbsenceReadbackFieldSetBytes()) + .isEqualTo(afterNewerRetirement); + assertRetirementFieldDelta( + beforeNewerRetirement, afterNewerRetirement, pendingNewerRetirement); + byte[] beforeNewerRetirementRetry = physicalFieldSet(partitionKey); + var completedNewerRetirementRetry = fixture.prepareIssuerRetirement(newerTransitionId); + assertThat(completedNewerRetirementRetry.status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalRetirementOperation.Status.RETIRED); + var newerRetirementRetryProof = fixture.retireIssuerCapacity(completedNewerRetirementRetry); + assertThat(newerRetirementRetryProof.scriptOutcome()).isEqualTo(2L); + assertThat(newerRetirementRetryProof.exactAbsenceReadbackFieldSetBytes()) + .isEqualTo(beforeNewerRetirementRetry); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeNewerRetirementRetry); + + for (int index = 3; index <= 256; index++) { + String seed = lifetimeSeed(index); + fixture.prepareOtherControllerNew(seed); + assertThat(fixture.projectOtherControllerNew(seed).scriptOutcome()).isEqualTo(1L); + fixture.publishOtherControllerNew(seed); + assertThat(fixture.recordOtherAccountAbort(seed).isAccountAborted()).isTrue(); + + var pendingCycleRelease = fixture.prepareIssuerRelease(seed); + var cycleReleaseReadback = fixture.projectIssuerRelease(pendingCycleRelease); + var completedCycleRelease = + fixture.completeIssuerRelease(pendingCycleRelease, cycleReleaseReadback); + assertThat(completedCycleRelease.status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); + + UUID transitionId = fixture.otherOperation(seed).request().transitionId(); + var pendingCycleRetirement = fixture.prepareIssuerRetirement(transitionId); + byte[] beforeCycleRetirement = physicalFieldSet(partitionKey); + var cycleRetirement = fixture.retireIssuerCapacity(pendingCycleRetirement); + byte[] afterCycleRetirement = physicalFieldSet(partitionKey); + assertThat(cycleRetirement.scriptOutcome()).isEqualTo(1L); + assertThat(cycleRetirement.exactAbsenceReadbackFieldSetBytes()) + .isEqualTo(afterCycleRetirement); + assertRetirementFieldDelta( + beforeCycleRetirement, afterCycleRetirement, pendingCycleRetirement); + assertThat(capacityFieldCount(afterCycleRetirement)).isZero(); + assertThat(decodeFields(afterCycleRetirement).size()).isEqualTo(baselineFieldCount + 2); + } + + assertThat(localOperationCount(fixture.dsl())).isEqualTo(256L); + assertThat(releaseCount(fixture.dsl(), "RELEASED")).isEqualTo(256L); + assertThat(releaseProofCount(fixture.dsl())).isEqualTo(256L); + assertThat(retirementCount(fixture.dsl())).isEqualTo(256L); + assertThat(retirementCountByStatus(fixture.dsl(), "RETIRED")).isEqualTo(256L); + String historyBefore257thRelease = durableHistoryImage(fixture.dsl(), NIL_UUID); + + String newSeed = lifetimeSeed(257); + UUID newOperationId = fixture.prepareOtherControllerNew(newSeed); + var finalPendingAdd = fixture.prepareOtherAddMutation(newSeed); + LuaInvocation staleFinalAddInvocation = addInvocation(fixture, finalPendingAdd); + var finalAddReadback = fixture.projectOtherControllerNew(newSeed); + assertThat(finalAddReadback.scriptOutcome()).isEqualTo(1L); + assertThat(fixture.retryOtherControllerNew(newSeed)).isEqualTo(newOperationId); + byte[] afterFinalAdd = physicalFieldSet(partitionKey); + assertThat(fixture.projectOtherControllerNew(newSeed).scriptOutcome()).isEqualTo(3L); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(afterFinalAdd); + + fixture.publishOtherControllerNew(newSeed); + assertThat(fixture.recordOtherAccountAbort(newSeed).isAccountAborted()).isTrue(); + var finalPendingRelease = fixture.prepareIssuerRelease(newSeed); + LuaInvocation staleFinalReleaseInvocation = releaseInvocation(fixture, finalPendingRelease); + var finalReleaseReadback = fixture.projectIssuerRelease(finalPendingRelease); + var finalRelease = fixture.completeIssuerRelease(finalPendingRelease, finalReleaseReadback); + assertThat(finalRelease.status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); + + byte[] beforeFinalReleaseRetry = physicalFieldSet(partitionKey); + var completedFinalReleaseRetry = fixture.prepareIssuerRelease(newSeed); + var finalReleaseRetryReadback = fixture.projectIssuerRelease(completedFinalReleaseRetry); + assertThat(finalReleaseRetryReadback.scriptOutcome()).isEqualTo(2L); + assertThat(finalReleaseRetryReadback.exactPhysicalFieldSetBytes()) + .isEqualTo(finalRelease.exactPhysicalReadbackFieldSetBytes()); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeFinalReleaseRetry); + + UUID finalTransitionId = fixture.otherOperation(newSeed).request().transitionId(); + var pendingFinalRetirement = fixture.prepareIssuerRetirement(finalTransitionId); + byte[] beforeFinalRetirement = physicalFieldSet(partitionKey); + var completedFinalRetirement = fixture.retireIssuerCapacity(pendingFinalRetirement); + byte[] afterFinalRetirement = physicalFieldSet(partitionKey); + assertThat(completedFinalRetirement.scriptOutcome()).isEqualTo(1L); + assertThat(completedFinalRetirement.exactAbsenceReadbackFieldSetBytes()) + .isEqualTo(afterFinalRetirement); + assertRetirementFieldDelta( + beforeFinalRetirement, afterFinalRetirement, pendingFinalRetirement); + + assertStaleLuaRejectedWithoutWrites(staleFinalAddInvocation, partitionKey); + assertStaleLuaRejectedWithoutWrites(staleFinalReleaseInvocation, partitionKey); + byte[] beforeFinalRetirementRetry = physicalFieldSet(partitionKey); + var completedFinalRetirementRetry = fixture.prepareIssuerRetirement(finalTransitionId); + assertThat(completedFinalRetirementRetry.status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalRetirementOperation.Status.RETIRED); + var finalRetirementRetryProof = fixture.retireIssuerCapacity(completedFinalRetirementRetry); + assertThat(finalRetirementRetryProof.scriptOutcome()).isEqualTo(2L); + assertThat(finalRetirementRetryProof.exactAbsenceReadbackFieldSetBytes()) + .isEqualTo(beforeFinalRetirementRetry); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeFinalRetirementRetry); + + assertThat(localOperationCount(fixture.dsl())).isEqualTo(257L); + assertThat(releaseCount(fixture.dsl(), "RELEASED")).isEqualTo(257L); + assertThat(releaseProofCount(fixture.dsl())).isEqualTo(257L); + assertThat(retirementCount(fixture.dsl())).isEqualTo(257L); + assertThat(retirementCountByStatus(fixture.dsl(), "RETIRED")).isEqualTo(257L); + assertThat(capacityFieldCount(afterFinalRetirement)).isZero(); + assertThat(decodeFields(afterFinalRetirement).size()).isEqualTo(baselineFieldCount + 2); + assertThat(durableHistoryImage(fixture.dsl(), finalTransitionId)) + .isEqualTo(historyBefore257thRelease); + } + } + + @Test + void refusesProjectionBeyondTheCurrentLocalEntryBoundWithoutWrites() { + try (var fixture = + newFixture(BigInteger.valueOf(9), BigInteger.ONE, BigInteger.valueOf(512), 0)) { + for (int index = 1; index < PARTITION_CAPACITY.intValueExact(); index++) { + fixture.prepareOtherControllerNew("local-entry-bound-" + index); + } + + assertThat(localOperationCount(fixture.dsl())).isEqualTo(256L); + var currentWork = fixture.readCurrentOriginalPartitionWork(); + assertThat(currentWork.localEntries()).hasSize(256); + + byte[] fieldsBefore257th = physicalFieldSet(fixture.issuerPartitionKey()); + long mutationCountBefore257th = partitionMutationCount(fixture.dsl()); + String seed257 = "local-entry-bound-257"; + fixture.prepareOtherControllerNew(seed257); + assertThat(localOperationCount(fixture.dsl())).isEqualTo(257L); + assertThat(partitionMutationCount(fixture.dsl())).isEqualTo(mutationCountBefore257th); + assertThat(physicalFieldSet(fixture.issuerPartitionKey())).isEqualTo(fieldsBefore257th); + + byte[] fieldsBeforeRefusal = physicalFieldSet(fixture.issuerPartitionKey()); + long mutationCountBeforeRefusal = partitionMutationCount(fixture.dsl()); + String sourceImageBeforeRefusal = durableHistoryImage(fixture.dsl(), NIL_UUID); + assertThatThrownBy(() -> fixture.projectOtherControllerNew(seed257)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Issuer binding-local projection is unavailable: The local partition operation set exceeds the physical owner bound"); + assertThat(durableHistoryImage(fixture.dsl(), NIL_UUID)).isEqualTo(sourceImageBeforeRefusal); + assertThat(localOperationCount(fixture.dsl())).isEqualTo(257L); + assertThat(partitionMutationCount(fixture.dsl())).isEqualTo(mutationCountBeforeRefusal); + assertThat(physicalFieldSet(fixture.issuerPartitionKey())).isEqualTo(fieldsBeforeRefusal); + } + } + + @Test + void ordinaryAddRefusesMissingPartitionRevisionWithoutRedisOrSqlWrites() throws Exception { + try (var fixture = newFixture(BigInteger.valueOf(4), BigInteger.ONE, 0)) { + String seed = "missing-revision-add"; + fixture.prepareOtherControllerNew(seed); + var work = fixture.prepareOtherAddMutation(seed); + var mutation = work.physicalMutation(); + assertMissingRevisionRefusal( + fixture, + fixture.issuerPartitionKey(), + mutation, + "game_session_canonical_issuer_binding_local_operation", + "operation_id", + fixture.otherOperation(seed).operationId(), + addInvocation(fixture, work), + () -> fixture.projectOtherControllerNew(seed)); + } + } + + @Test + void ordinaryReleaseRefusesMissingPartitionRevisionWithoutRedisOrSqlWrites() throws Exception { + try (var fixture = newFixture(BigInteger.valueOf(5), BigInteger.ONE, 0)) { + fixture.publishOriginalWithControlledAccountLease(); + assertThat(fixture.recordOriginalAccountAbort().isAccountAborted()).isTrue(); + var pendingRelease = fixture.prepareIssuerRelease(); + assertMissingRevisionRefusal( + fixture, + fixture.issuerPartitionKey(), + pendingRelease.physicalMutation(), + "game_session_canonical_issuer_binding_local_release_operation", + "operation_id", + pendingRelease.operationId(), + releaseInvocation(fixture, pendingRelease), + () -> fixture.projectIssuerRelease(pendingRelease)); + } + } + + @Test + void retirementRefusesMissingPartitionRevisionWithoutRedisOrSqlWrites() throws Exception { + try (var fixture = newFixture(BigInteger.valueOf(6), BigInteger.ONE, 0)) { + fixture.publishOriginalWithControlledAccountLease(); + assertThat(fixture.recordOriginalAccountAbort().isAccountAborted()).isTrue(); + var pendingRelease = fixture.prepareIssuerRelease(); + var releaseReadback = fixture.projectIssuerRelease(pendingRelease); + assertThat(fixture.completeIssuerRelease(pendingRelease, releaseReadback).status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); + + var pendingRetirement = fixture.prepareIssuerRetirement(fixture.transitionId()); + assertMissingRevisionRefusal( + fixture, + fixture.issuerPartitionKey(), + pendingRetirement.physicalMutation(), + "game_session_canonical_issuer_binding_local_retirement", + "retirement_operation_id", + pendingRetirement.operationId(), + retirementInvocation(fixture, pendingRetirement), + () -> fixture.retireIssuerCapacity(pendingRetirement)); + } + } + + @Test + void postRetirementProjectionRejectsUnaccountedCurrentReservationInAnotherPartition() + throws Exception { + try (var fixture = newFixture(BigInteger.valueOf(7), BigInteger.TWO, 0)) { + fixture.publishOriginalWithControlledAccountLease(); + assertThat(fixture.recordOriginalAccountAbort().isAccountAborted()).isTrue(); + var release = fixture.prepareIssuerRelease(); + var releaseReadback = fixture.projectIssuerRelease(release); + assertThat(fixture.completeIssuerRelease(release, releaseReadback).status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); + var pendingRetirement = fixture.prepareIssuerRetirement(fixture.transitionId()); + var retired = fixture.retireIssuerCapacity(pendingRetirement); + assertThat(retired.scriptOutcome()).isEqualTo(1L); + + BigInteger retiredPartition = fixture.originalPartitionId(); + BigInteger otherPartition = + retiredPartition.equals(BigInteger.ZERO) ? BigInteger.ONE : BigInteger.ZERO; + String otherPartitionSeed = "cross-partition-current"; + fixture.prepareOtherControllerNewInPartition(otherPartitionSeed, otherPartition); + assertThat(fixture.projectOtherControllerNew(otherPartitionSeed).scriptOutcome()) + .isEqualTo(1L); + + String pendingTargetSeed = "cross-partition-drift-target"; + UUID pendingTargetOperationId = fixture.prepareOtherControllerNew(pendingTargetSeed); + var pendingTarget = fixture.otherOperation(pendingTargetSeed); + byte[] retiredPartitionKey = fixture.issuerPartitionKey(); + byte[] otherPartitionKey = fixture.issuerPartitionKey(otherPartitionSeed); + byte[] retiredPartitionBefore = physicalFieldSet(retiredPartitionKey); + byte[] otherPartitionBefore = physicalFieldSet(otherPartitionKey); + String pendingTargetBefore = localOperationImage(fixture.dsl(), pendingTargetOperationId); + String otherPartitionHeadBefore = partitionHeadImage(fixture.dsl(), otherPartition); + UUID unaccountedReservationId = + insertUnaccountedCurrentReservation(fixture, otherPartitionSeed, otherPartition); + String unaccountedReservationBefore = + reservationImage(fixture.dsl(), unaccountedReservationId); + String retiredAuditBefore = retirementImage(fixture.dsl(), fixture.transitionId()); + + assertThatThrownBy(() -> fixture.projectOtherControllerNew(pendingTargetSeed)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Durable issuer reservations differ"); + + assertThat(physicalFieldSet(retiredPartitionKey)).isEqualTo(retiredPartitionBefore); + assertThat(physicalFieldSet(otherPartitionKey)).isEqualTo(otherPartitionBefore); + assertThat(localOperationImage(fixture.dsl(), pendingTargetOperationId)) + .isEqualTo(pendingTargetBefore); + assertThat(partitionHeadImage(fixture.dsl(), otherPartition)) + .isEqualTo(otherPartitionHeadBefore); + assertThat(reservationImage(fixture.dsl(), unaccountedReservationId)) + .isEqualTo(unaccountedReservationBefore); + assertThat(retirementImage(fixture.dsl(), fixture.transitionId())) + .isEqualTo(retiredAuditBefore); + assertThat(retirementStatus(fixture.dsl(), pendingRetirement.operationId())) + .isEqualTo("RETIRED"); + assertThat(retirementCount(fixture.dsl())).isEqualTo(1L); + assertThat(releaseProofCount(fixture.dsl())).isEqualTo(1L); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT count(*) FROM game_session_canonical_issuer_partition_mutation" + + " WHERE owner_operation_id = ? AND mutation_kind = 'ADD_CAPACITY'", + pendingTargetOperationId) + .get(0, Long.class)) + .isZero(); + assertThat(pendingTarget.reservation().partitionId()).isEqualTo(retiredPartition); + } + } + + @Test + void actualReleaseReadbackPersistsAndReloadsWithMoreThan513PhysicalFields() throws Exception { + try (var fixture = newFixture(BigInteger.valueOf(8), BigInteger.ONE, 250)) { + assertThat(fixture.originalBaselineReservationCount()).isEqualTo(250); + assertThat(fixture.originalBaselineCountedCapacity()).isEqualTo(250); + assertThat(fixture.originalBaselineBindingCount()).isEqualTo(250); + fixture.publishOriginalWithControlledAccountLease(); + for (int index = 0; index < 4; index++) { + String seed = "wide-active-" + index; + fixture.prepareOtherControllerNew(seed); + fixture.projectOtherControllerNew(seed); + fixture.publishOtherControllerNew(seed); + } + + String terminalSeed = "wide-retained-terminal"; + fixture.prepareOtherControllerNew(terminalSeed); + fixture.projectOtherControllerNew(terminalSeed); + fixture.publishOtherControllerNew(terminalSeed); + assertThat(fixture.recordOtherAccountAbort(terminalSeed).isAccountAborted()).isTrue(); + var terminalRelease = fixture.prepareIssuerRelease(terminalSeed); + var terminalReadback = fixture.projectIssuerRelease(terminalRelease); + assertThat(fixture.completeIssuerRelease(terminalRelease, terminalReadback).status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); + + String wideReleaseSeed = "wide-release-readback"; + UUID wideOperationId = fixture.prepareOtherControllerNew(wideReleaseSeed); + var pendingAdd = fixture.prepareOtherAddMutation(wideReleaseSeed); + assertThat(pendingAdd.aggregateCapacity()).isEqualTo(PARTITION_CAPACITY); + assertThat(fixture.projectOtherControllerNew(wideReleaseSeed).scriptOutcome()).isEqualTo(1L); + fixture.publishOtherControllerNew(wideReleaseSeed); + assertThat(fixture.recordOtherAccountAbort(wideReleaseSeed).isAccountAborted()).isTrue(); + + var pendingRelease = fixture.prepareIssuerRelease(wideReleaseSeed); + var actualReadback = fixture.projectIssuerRelease(pendingRelease); + assertThat(actualReadback.scriptOutcome()).isEqualTo(1L); + assertThat(decodeFields(actualReadback.exactPhysicalFieldSetBytes()).size()).isEqualTo(514); + var completedRelease = fixture.completeIssuerRelease(pendingRelease, actualReadback); + assertThat(completedRelease.status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); + assertThat(completedRelease.exactPhysicalReadbackFieldSetBytes()) + .isEqualTo(actualReadback.exactPhysicalFieldSetBytes()); + + var reloadedRelease = fixture.prepareIssuerRelease(wideReleaseSeed); + assertThat(reloadedRelease.operationId()).isEqualTo(pendingRelease.operationId()); + assertThat(reloadedRelease.exactPhysicalReadbackFieldSetBytes()) + .isEqualTo(actualReadback.exactPhysicalFieldSetBytes()); + var completedRetry = fixture.projectIssuerRelease(reloadedRelease); + assertThat(completedRetry.scriptOutcome()).isEqualTo(2L); + assertThat(completedRetry.exactPhysicalFieldSetBytes()) + .isEqualTo(actualReadback.exactPhysicalFieldSetBytes()); + assertThat(physicalFieldSet(fixture.issuerPartitionKey())) + .isEqualTo(actualReadback.exactPhysicalFieldSetBytes()); + assertThat(localOperationCount(fixture.dsl())).isEqualTo(7L); + assertThat(releaseCount(fixture.dsl(), "RELEASED")).isEqualTo(2L); + assertThat(wideOperationId).isEqualTo(pendingRelease.originalOperationId()); + } + } + + private RedisClient createRedisClient(String username, String password) { + RedisURI.Builder builder = RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(6379)); + if (username != null) builder.withAuthentication(username, password); + RedisURI uri = builder.build(); + uri.setTimeout(Duration.ofSeconds(5)); + RedisClient client = RedisClient.create(uri); + client.setOptions( + ClientOptions.builder() + .autoReconnect(false) + .protocolVersion(ProtocolVersion.RESP2) + .build()); + return client; + } + + private CanonicalGameplayAdmissionAbortCompositionFixture newFixture() { + return newFixture(controlledCandidate(), 0); + } + + private CanonicalGameplayAdmissionAbortCompositionFixture newFixture( + BigInteger layoutVersion, BigInteger partitionCount, int seedBootstrapMemberCount) { + return newFixture(controlledCandidate(layoutVersion, partitionCount), seedBootstrapMemberCount); + } + + private CanonicalGameplayAdmissionAbortCompositionFixture newFixture( + BigInteger layoutVersion, + BigInteger partitionCount, + BigInteger partitionCapacity, + int seedBootstrapMemberCount) { + return newFixture( + controlledCandidate(layoutVersion, partitionCount, partitionCapacity), + seedBootstrapMemberCount); + } + + private CanonicalGameplayAdmissionAbortCompositionFixture newFixture( + Candidate candidate, int seedBootstrapMemberCount) { + DriverManagerDataSource accountDataSource = new DriverManagerDataSource(); + accountDataSource.setDriverClassName("org.postgresql.Driver"); + String postgresJdbcUrl = POSTGRES.getJdbcUrl(); + accountDataSource.setUrl( + postgresJdbcUrl + (postgresJdbcUrl.contains("?") ? "&" : "?") + "currentSchema=public"); + accountDataSource.setUsername(POSTGRES.getUsername()); + accountDataSource.setPassword(POSTGRES.getPassword()); + return new CanonicalGameplayAdmissionAbortCompositionFixture( + accountDataSource, candidate, issuerOwner, seedBootstrapMemberCount); + } + + private static Candidate controlledCandidate() { + return controlledCandidate(BigInteger.valueOf(3), BigInteger.ONE); + } + + private static Candidate controlledCandidate( + BigInteger layoutVersion, BigInteger partitionCount) { + return controlledCandidate(layoutVersion, partitionCount, PARTITION_CAPACITY); + } + + private static Candidate controlledCandidate( + BigInteger layoutVersion, BigInteger partitionCount, BigInteger partitionCapacity) { + return new Candidate( + uuid("retirement-account"), + uuid("retirement-tenant"), + uuid("retirement-playable-state"), + uuid("retirement-character"), + "SHARED", + uuid("retirement-game"), + 1L, + uuid("retirement-session"), + uuid("retirement-region"), + BigInteger.ONE, + GameSessionAccountDelegationProfile.ISSUER, + BigInteger.ONE, + layoutVersion, + partitionCount, + partitionCapacity); + } + + private void assertMissingRevisionRefusal( + CanonicalGameplayAdmissionAbortCompositionFixture fixture, + byte[] partitionKey, + CanonicalGameplayIssuerPartitionMutation mutation, + String ownerTable, + String ownerIdColumn, + UUID ownerOperationId, + LuaInvocation exactInvocation, + Runnable ordinaryOwnerCall) { + byte[] beforeFault = physicalFieldSet(partitionKey); + assertThat(decodeFields(beforeFault)) + .containsKey(CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD); + String pendingCustodyBefore = + pendingMutationCustodyImage( + fixture.dsl(), mutation, ownerTable, ownerIdColumn, ownerOperationId); + + byte[] revisionField = + CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD.getBytes( + StandardCharsets.US_ASCII); + byte[][] revisionFields = {revisionField}; + assertThat(administratorCommands.hdel(partitionKey, revisionFields)).isEqualTo(1L); + byte[] afterInjectedAbsence = physicalFieldSet(partitionKey); + assertThat(decodeFields(afterInjectedAbsence)) + .doesNotContainKey(CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD); + assertThat( + pendingMutationCustodyImage( + fixture.dsl(), mutation, ownerTable, ownerIdColumn, ownerOperationId)) + .isEqualTo(pendingCustodyBefore); + + assertThat(evaluate(exactInvocation)).isNegative(); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(afterInjectedAbsence); + assertThatThrownBy(ordinaryOwnerCall::run).isInstanceOf(IllegalStateException.class); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(afterInjectedAbsence); + assertThat(administratorCommands.hget(partitionKey, revisionField)).isNull(); + assertThat( + pendingMutationCustodyImage( + fixture.dsl(), mutation, ownerTable, ownerIdColumn, ownerOperationId)) + .isEqualTo(pendingCustodyBefore); + } + + private static String pendingMutationCustodyImage( + DSLContext dsl, + CanonicalGameplayIssuerPartitionMutation mutation, + String ownerTable, + String ownerIdColumn, + UUID ownerOperationId) { + String sql = + "SELECT jsonb_build_object(" + + "'head', (SELECT to_jsonb(head) FROM " + + CanonicalGameplayIssuerPartitionMutationRepository.HEAD_TABLE + + " head WHERE head.issuer_id = ? AND head.partition_id = ?)," + + "'mutation', (SELECT to_jsonb(mutation) FROM " + + "game_session_canonical_issuer_partition_mutation" + + " mutation WHERE mutation.mutation_id = ?)," + + "'owner', (SELECT to_jsonb(owner_row) FROM " + + ownerTable + + " owner_row WHERE owner_row." + + ownerIdColumn + + " = ?))::text"; + return dsl.fetchSingle( + sql, + GameSessionAccountDelegationProfile.ISSUER, + mutation.partitionId(), + mutation.mutationId(), + ownerOperationId) + .get(0, String.class); + } + + private static String localOperationImage(DSLContext dsl, UUID operationId) { + return dsl.fetchSingle( + "SELECT to_jsonb(operation)::text FROM" + + " game_session_canonical_issuer_binding_local_operation operation" + + " WHERE operation.operation_id = ?", + operationId) + .get(0, String.class); + } + + private static String partitionHeadImage(DSLContext dsl, BigInteger partitionId) { + return dsl.fetchSingle( + "SELECT to_jsonb(head)::text FROM " + + CanonicalGameplayIssuerPartitionMutationRepository.HEAD_TABLE + + " head WHERE head.issuer_id = ? AND head.partition_id = ?", + GameSessionAccountDelegationProfile.ISSUER, + partitionId) + .get(0, String.class); + } + + private static UUID insertUnaccountedCurrentReservation( + CanonicalGameplayAdmissionAbortCompositionFixture fixture, + String sourceSeed, + BigInteger partitionId) { + // This row is deliberate run-owned SQL drift: it has no transition or local owner operation. + // The ordinary projection must detect that missing accounting and make no Redis change. + var source = fixture.otherOperation(sourceSeed).memberValue(); + var owner = source.owner(); + var reservation = source.reservation(); + String sessionId; + CanonicalGameplayBindingRef bindingRef; + do { + sessionId = UUID.randomUUID().toString(); + bindingRef = + CanonicalGameplayBindingRef.of(owner.tenantId(), owner.gameInstanceId(), sessionId); + } while (!bindingRef.partitionId(owner.issuerIndexPartitionCount()).equals(partitionId)); + UUID reservationId = UUID.randomUUID(); + fixture + .dsl() + .execute( + "INSERT INTO game_session_canonical_issuer_partition_reservation" + + " (reservation_id, binding_ref, account_id, tenant_id, game_instance_id," + + " runtime_game_instance_id, session_id, binding_generation, transition_id, issuer_id," + + " issuer_auth_generation, playable_state_namespace_id, character_id," + + " playable_state_scope, region_id, region_epoch, partition_id," + + " issuer_index_layout_version, issuer_index_partition_count," + + " issuer_index_partition_capacity, lifecycle, reservation_fence," + + " issuer_coverage_operation_id, issuer_coverage_operation_fence, coverage_fence," + + " inventory_snapshot_revision, inventory_revision)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + + " ?, ?, ?, ?, ?, ?, ?)", + reservationId, + bindingRef.bytes(), + owner.accountId(), + owner.tenantId(), + owner.gameInstanceId(), + owner.runtimeGameInstanceId(), + sessionId, + source.bindingGeneration(), + UUID.randomUUID(), + owner.issuerId(), + owner.issuerAuthGeneration(), + owner.playableStateNamespaceId(), + UUID.randomUUID(), + owner.playableStateScope(), + owner.regionId(), + owner.regionEpoch(), + partitionId, + owner.issuerIndexLayoutVersion(), + owner.issuerIndexPartitionCount(), + owner.issuerIndexPartitionCapacity(), + "RESERVED", + UUID.randomUUID(), + UUID.randomUUID(), + reservation.issuerCoverageOperationFence(), + reservation.coverageFence(), + reservation.inventorySnapshotRevision(), + reservation.inventoryRevision()); + return reservationId; + } + + private static String reservationImage(DSLContext dsl, UUID reservationId) { + return dsl.fetchSingle( + "SELECT to_jsonb(reservation)::text FROM" + + " game_session_canonical_issuer_partition_reservation reservation" + + " WHERE reservation.reservation_id = ?", + reservationId) + .get(0, String.class); + } + + private static String retirementImage(DSLContext dsl, UUID transitionId) { + return dsl.fetchSingle( + "SELECT to_jsonb(retirement)::text FROM" + + " game_session_canonical_issuer_binding_local_retirement retirement" + + " WHERE retirement.transition_id = ?", + transitionId) + .get(0, String.class); + } + + private static CanonicalGameplayIssuerBindingLocalReleaseOperation completeReleaseAfterLostReply( + CanonicalGameplayAdmissionAbortCompositionFixture fixture, String seed) { + var pending = + seed == null ? fixture.prepareIssuerRelease() : fixture.prepareIssuerRelease(seed); + assertThatThrownBy(() -> fixture.projectIssuerReleaseAndLoseReply(pending)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("controlled lost issuer release reply"); + var resumed = + seed == null ? fixture.prepareIssuerRelease() : fixture.prepareIssuerRelease(seed); + var recoveredReadback = fixture.projectIssuerRelease(resumed); + assertThat(recoveredReadback.scriptOutcome()).isEqualTo(2L); + return fixture.completeIssuerRelease(resumed, recoveredReadback); + } + + private static CanonicalGameplayIssuerBindingLocalReleaseOperation completeRelease( + CanonicalGameplayAdmissionAbortCompositionFixture fixture, String seed) { + var pending = fixture.prepareIssuerRelease(seed); + var readback = fixture.projectIssuerRelease(pending); + return fixture.completeIssuerRelease(pending, readback); + } + + private static String lifetimeSeed(int index) { + return "lifetime-" + index; + } + + private static LuaInvocation addInvocation( + CanonicalGameplayAdmissionAbortCompositionFixture fixture, + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work) + throws IOException, ReflectiveOperationException { + return new LuaInvocation( + readScript(CanonicalGameplayIssuerBindingLocalRedisScriptContribution.RESOURCE_PATH), + fixture.issuerPartitionKey(), + scriptArguments( + CanonicalGameplayIssuerBindingLocalRedisOwner.class, + new Class[] { + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork.class + }, + work)); + } + + private static LuaInvocation releaseInvocation( + CanonicalGameplayAdmissionAbortCompositionFixture fixture, + CanonicalGameplayIssuerBindingLocalReleaseOperation operation) + throws IOException, ReflectiveOperationException { + var work = fixture.readPreparedPartitionWork(operation.originalOperation()); + return new LuaInvocation( + readScript(CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.RESOURCE_PATH), + fixture.issuerPartitionKey(), + scriptArguments( + CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.class, + new Class[] { + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork.class, + CanonicalGameplayIssuerBindingLocalReleaseOperation.class + }, + work, + operation)); + } + + private static LuaInvocation retirementInvocation( + CanonicalGameplayAdmissionAbortCompositionFixture fixture, + CanonicalGameplayIssuerBindingLocalRetirementOperation operation) + throws IOException, ReflectiveOperationException { + var work = fixture.readPreparedPartitionWork(operation.release().originalOperation()); + return new LuaInvocation( + readScript( + CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution.RESOURCE_PATH), + fixture.issuerPartitionKey(), + scriptArguments( + CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.class, + new Class[] { + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork.class, + CanonicalGameplayIssuerBindingLocalRetirementOperation.class + }, + work, + operation)); + } + + private static byte[][] scriptArguments( + Class owner, Class[] parameterTypes, Object... arguments) + throws ReflectiveOperationException { + Method method = owner.getDeclaredMethod("scriptArguments", parameterTypes); + if (!method.trySetAccessible()) { + throw new IllegalStateException("Test could not capture the exact owner Lua arguments"); + } + try { + return (byte[][]) method.invoke(null, arguments); + } catch (InvocationTargetException failure) { + Throwable cause = failure.getCause(); + if (cause instanceof RuntimeException runtime) throw runtime; + throw failure; + } + } + + private static byte[] readScript(String resourcePath) throws IOException { + try (InputStream input = + CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.class + .getClassLoader() + .getResourceAsStream(resourcePath)) { + if (input == null) throw new IOException("Missing Redis Lua resource: " + resourcePath); + byte[] bytes = input.readAllBytes(); + if (bytes.length == 0) throw new IOException("Empty Redis Lua resource: " + resourcePath); + return bytes; + } + } + + private Long evaluate(LuaInvocation invocation) { + return administratorCommands.eval( + invocation.script(), + ScriptOutputType.INTEGER, + new byte[][] {invocation.key()}, + invocation.arguments()); + } + + private void assertStaleLuaRejectedWithoutWrites( + LuaInvocation staleInvocation, byte[] partitionKey) { + byte[] before = physicalFieldSet(partitionKey); + Long outcome = evaluate(staleInvocation); + assertThat(outcome).isNegative(); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(before); + } + + private byte[] physicalFieldSet(byte[] key) { + Map raw = administratorCommands.hgetall(key); + Map fields = new HashMap<>(); + raw.forEach( + (field, value) -> fields.put(new String(field, StandardCharsets.UTF_8), value.clone())); + return CanonicalGameplayIssuerBootstrapCoverageRepository.encodeFieldSet(fields); + } + + private static Map decodeFields(byte[] fieldSet) { + return CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet(fieldSet); + } + + private static long capacityFieldCount(byte[] fieldSet) { + return decodeFields(fieldSet).keySet().stream() + .filter( + field -> + field.startsWith( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec + .RESERVATION_FIELD_PREFIX)) + .count(); + } + + private static void assertRetirementFieldDelta( + byte[] before, + byte[] after, + CanonicalGameplayIssuerBindingLocalRetirementOperation operation) { + Map expected = decodeFields(before); + String capacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + operation.release().releasedMemberValue().reservation().reservationId()); + assertThat(expected.get(capacityField)) + .isEqualTo(operation.release().exactReleasedMemberValueBytes()); + expected.remove(capacityField); + expected.put( + CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD, + operation + .physicalMutation() + .successorRevision() + .toString() + .getBytes(StandardCharsets.US_ASCII)); + assertThat(after) + .isEqualTo(CanonicalGameplayIssuerBootstrapCoverageRepository.encodeFieldSet(expected)); + } + + private static long localOperationCount(DSLContext dsl) { + return dsl.fetchSingle( + "SELECT count(*) FROM game_session_canonical_issuer_binding_local_operation") + .get(0, Long.class); + } + + private static long partitionMutationCount(DSLContext dsl) { + return dsl.fetchSingle("SELECT count(*) FROM game_session_canonical_issuer_partition_mutation") + .get(0, Long.class); + } + + private static long releaseCount(DSLContext dsl, String status) { + return dsl.fetchSingle( + "SELECT count(*) FROM game_session_canonical_issuer_binding_local_release_operation" + + " WHERE status = ?", + status) + .get(0, Long.class); + } + + private static long releaseProofCount(DSLContext dsl) { + return dsl.fetchSingle( + "SELECT count(*) FROM game_session_canonical_issuer_binding_local_release_operation" + + " WHERE status = 'RELEASED' AND physical_readback_field_set_bytes IS NOT NULL" + + " AND completion_inventory_revision > source_inventory_revision") + .get(0, Long.class); + } + + private static long retirementCount(DSLContext dsl) { + return dsl.fetchSingle( + "SELECT count(*) FROM game_session_canonical_issuer_binding_local_retirement") + .get(0, Long.class); + } + + private static long retirementCountByStatus(DSLContext dsl, String status) { + return dsl.fetchSingle( + "SELECT count(*) FROM game_session_canonical_issuer_binding_local_retirement WHERE status = ?", + status) + .get(0, Long.class); + } + + private static String retirementStatus(DSLContext dsl, UUID retirementOperationId) { + return dsl.fetchSingle( + "SELECT status FROM game_session_canonical_issuer_binding_local_retirement" + + " WHERE retirement_operation_id = ?", + retirementOperationId) + .get(0, String.class); + } + + private static String durableHistoryImage(DSLContext dsl, UUID excludedTransitionId) { + String sql = + "SELECT jsonb_build_object(" + + "'transitions', COALESCE((SELECT jsonb_agg(to_jsonb(entry) ORDER BY entry.transition_id)" + + " FROM game_session_canonical_binding_transition entry WHERE entry.transition_id <> ?), '[]'::jsonb)," + + "'inventory', COALESCE((SELECT jsonb_agg(to_jsonb(entry) ORDER BY entry.binding_ref)" + + " FROM game_session_canonical_gameplay_binding_inventory entry WHERE entry.transition_id <> ?), '[]'::jsonb)," + + "'reservations', COALESCE((SELECT jsonb_agg(to_jsonb(entry) ORDER BY entry.reservation_id)" + + " FROM game_session_canonical_issuer_partition_reservation entry WHERE entry.transition_id <> ?), '[]'::jsonb)," + + "'accountObligations', COALESCE((SELECT jsonb_agg(to_jsonb(entry) ORDER BY entry.transition_id, entry.obligation_ordinal)" + + " FROM game_session_canonical_binding_account_index_obligation entry WHERE entry.transition_id <> ?), '[]'::jsonb)," + + "'issuerObligations', COALESCE((SELECT jsonb_agg(to_jsonb(entry) ORDER BY entry.transition_id, entry.binding_ref)" + + " FROM game_session_canonical_binding_issuer_index_obligation entry WHERE entry.transition_id <> ?), '[]'::jsonb)," + + "'regionObligations', COALESCE((SELECT jsonb_agg(to_jsonb(entry) ORDER BY entry.transition_id)" + + " FROM game_session_canonical_binding_region_bridge_obligation entry WHERE entry.transition_id <> ?), '[]'::jsonb)," + + "'localOperations', COALESCE((SELECT jsonb_agg(to_jsonb(entry) ORDER BY entry.operation_id)" + + " FROM game_session_canonical_issuer_binding_local_operation entry WHERE entry.transition_id <> ?), '[]'::jsonb)," + + "'releases', COALESCE((SELECT jsonb_agg(to_jsonb(entry) ORDER BY entry.operation_id)" + + " FROM game_session_canonical_issuer_binding_local_release_operation entry WHERE entry.transition_id <> ?), '[]'::jsonb)," + + "'mutations', COALESCE((SELECT jsonb_agg(to_jsonb(mutation) ORDER BY mutation.mutation_id)" + + " FROM game_session_canonical_issuer_partition_mutation mutation WHERE mutation.owner_operation_id IN (" + + " SELECT local_operation.operation_id FROM game_session_canonical_issuer_binding_local_operation local_operation WHERE local_operation.transition_id <> ?" + + " UNION SELECT release_entry.operation_id FROM game_session_canonical_issuer_binding_local_release_operation release_entry WHERE release_entry.transition_id <> ?)), '[]'::jsonb)" + + ")::text"; + return dsl.fetchSingle( + sql, + excludedTransitionId, + excludedTransitionId, + excludedTransitionId, + excludedTransitionId, + excludedTransitionId, + excludedTransitionId, + excludedTransitionId, + excludedTransitionId, + excludedTransitionId, + excludedTransitionId) + .get(0, String.class); + } + + private static UUID uuid(String seed) { + return UUID.nameUUIDFromBytes(seed.getBytes(StandardCharsets.UTF_8)); + } + + private record LuaInvocation(byte[] script, byte[] key, byte[][] arguments) { + private LuaInvocation { + script = script.clone(); + key = key.clone(); + arguments = Arrays.stream(arguments).map(byte[]::clone).toArray(byte[][]::new); + } + + @Override + public byte[] script() { + return script.clone(); + } + + @Override + public byte[] key() { + return key.clone(); + } + + @Override + public byte[][] arguments() { + return Arrays.stream(arguments).map(byte[]::clone).toArray(byte[][]::new); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java index 43c2d7d18a..52c3c8c416 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java @@ -15,17 +15,133 @@ import io.grpc.stub.StreamObserver; import java.util.Map; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; import net.firedevops.firemud.gamesession.security.CanonicalGameplayAdmissionDecisionReadWorkloadGuard; import net.firedevops.firemud.gamesession.service.impl.CanonicalGameplayAdmissionDecisionReadGrpcService; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayAdmissionDecisionRequest; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayAdmissionDecisionResponse; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; +import org.springframework.dao.DataAccessResourceFailureException; /** - * Controlled callback/parser failure tests; native owner composition is a separate PostgreSQL test. + * Controlled parser, repository, codec and callback failure tests; native owner composition is a + * separate PostgreSQL test. */ class CanonicalGameplayAdmissionDecisionReadGrpcServiceTest { + @Test + void unexpectedRepositoryFailureTerminatesOnceWithSanitizedInternal() { + var fixture = validReadFixture(); + when(fixture + .repository() + .readAdmissionDecision( + fixture.decision().bindingDecisionId(), fixture.decision().leaseEvidence())) + .thenThrow(new IllegalArgumentException("private repository programming details")); + try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { + codec + .when( + () -> CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest(fixture.request())) + .thenReturn(fixture.selector()); + new CanonicalGameplayAdmissionDecisionReadGrpcService( + fixture.repository(), fixture.guard(), "test") + .getCanonicalGameplayAdmissionDecision(fixture.request(), fixture.observer()); + } + assertFailure( + fixture.observer(), Status.Code.INTERNAL, "private repository programming details"); + verify(fixture.repository()) + .readAdmissionDecision( + fixture.decision().bindingDecisionId(), fixture.decision().leaseEvidence()); + } + + @Test + void repositoryConflictRemainsFailedPrecondition() { + var fixture = validReadFixture(); + when(fixture + .repository() + .readAdmissionDecision( + fixture.decision().bindingDecisionId(), fixture.decision().leaseEvidence())) + .thenThrow(new CanonicalGameplayBindingInventoryConflictException("decision changed")); + try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { + codec + .when( + () -> CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest(fixture.request())) + .thenReturn(fixture.selector()); + new CanonicalGameplayAdmissionDecisionReadGrpcService( + fixture.repository(), fixture.guard(), "test") + .getCanonicalGameplayAdmissionDecision(fixture.request(), fixture.observer()); + } + assertFailure(fixture.observer(), Status.Code.FAILED_PRECONDITION, null); + } + + @Test + void repositoryIllegalStateConflictRemainsFailedPrecondition() { + var fixture = validReadFixture(); + when(fixture + .repository() + .readAdmissionDecision( + fixture.decision().bindingDecisionId(), fixture.decision().leaseEvidence())) + .thenThrow(new IllegalStateException("stale decision")); + try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { + codec + .when( + () -> CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest(fixture.request())) + .thenReturn(fixture.selector()); + new CanonicalGameplayAdmissionDecisionReadGrpcService( + fixture.repository(), fixture.guard(), "test") + .getCanonicalGameplayAdmissionDecision(fixture.request(), fixture.observer()); + } + assertFailure(fixture.observer(), Status.Code.FAILED_PRECONDITION, null); + } + + @Test + void databaseOutageRemainsUnavailable() { + var fixture = validReadFixture(); + when(fixture + .repository() + .readAdmissionDecision( + fixture.decision().bindingDecisionId(), fixture.decision().leaseEvidence())) + .thenThrow(new DataAccessResourceFailureException("database unavailable")); + try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { + codec + .when( + () -> CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest(fixture.request())) + .thenReturn(fixture.selector()); + new CanonicalGameplayAdmissionDecisionReadGrpcService( + fixture.repository(), fixture.guard(), "test") + .getCanonicalGameplayAdmissionDecision(fixture.request(), fixture.observer()); + } + assertFailure(fixture.observer(), Status.Code.UNAVAILABLE, null); + } + + @Test + void unexpectedResponseEncodingFailureTerminatesOnceWithInternalWithoutAnswer() { + var fixture = validReadFixture(); + when(fixture + .repository() + .readAdmissionDecision( + fixture.decision().bindingDecisionId(), fixture.decision().leaseEvidence())) + .thenReturn(fixture.decision()); + try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { + codec + .when( + () -> CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest(fixture.request())) + .thenReturn(fixture.selector()); + codec + .when( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toResponse( + any(), any(), any(), any(), any(), any(), any(), any())) + .thenThrow(new IllegalStateException("private response codec details")); + new CanonicalGameplayAdmissionDecisionReadGrpcService( + fixture.repository(), fixture.guard(), "test") + .getCanonicalGameplayAdmissionDecision(fixture.request(), fixture.observer()); + } + assertFailure(fixture.observer(), Status.Code.INTERNAL, "private response codec details"); + verify(fixture.repository()) + .readAdmissionDecision( + fixture.decision().bindingDecisionId(), fixture.decision().leaseEvidence()); + } + @Test void unexpectedParserFailureTerminatesOnceWithSanitizedInternalBeforeRepositoryRead() { var repository = mock(CanonicalGameplayBindingInventoryRepository.class); @@ -107,4 +223,47 @@ void onNextFailureSignalsOneErrorButCompletionFailureEscapesWithoutSecondTermina private static StreamObserver observer() { return mock(StreamObserver.class); } + + private static ReadFixture validReadFixture() { + var repository = mock(CanonicalGameplayBindingInventoryRepository.class); + var guard = mock(CanonicalGameplayAdmissionDecisionReadWorkloadGuard.class); + var observer = observer(); + var request = GetCanonicalGameplayAdmissionDecisionRequest.getDefaultInstance(); + var decision = CanonicalGameplayAdmissionAbortOwnerTest.source(false).originalDecision(); + var lease = decision.leaseEvidence(); + when(lease.carrier()) + .thenReturn( + Map.of( + "targetNamespace", + "test", + "callerWorkload", + "spiffe://firemud/ns/test/sa/game-session-service")); + var selector = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.RequestEvidence.class); + when(selector.expectedLeaseEvidence()).thenReturn(lease); + var decisionId = decision.bindingDecisionId(); + when(selector.bindingDecisionId()).thenReturn(decisionId); + return new ReadFixture(repository, guard, observer, request, selector, decision); + } + + private static void assertFailure( + StreamObserver observer, + Status.Code expectedCode, + String privateDetail) { + var failure = ArgumentCaptor.forClass(Throwable.class); + verify(observer).onError(failure.capture()); + assertThat(Status.fromThrowable(failure.getValue()).getCode()).isEqualTo(expectedCode); + if (privateDetail != null) { + assertThat(failure.getValue()).hasMessageNotContaining(privateDetail); + } + verify(observer, never()).onNext(any()); + verify(observer, never()).onCompleted(); + } + + private record ReadFixture( + CanonicalGameplayBindingInventoryRepository repository, + CanonicalGameplayAdmissionDecisionReadWorkloadGuard guard, + StreamObserver observer, + GetCanonicalGameplayAdmissionDecisionRequest request, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.RequestEvidence selector, + CanonicalGameplayAdmissionDecision decision) {} } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalFieldSetCodecTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalFieldSetCodecTest.java new file mode 100644 index 0000000000..0f236fbc96 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalFieldSetCodecTest.java @@ -0,0 +1,70 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.Locale; +import java.util.Map; +import org.junit.jupiter.api.Test; + +class CanonicalGameplayIssuerPhysicalFieldSetCodecTest { + private static final int MAX_LOCAL_PHYSICAL_FIELD_COUNT = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_HASH_FIELDS + + 2 * CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_MEMBER_OPERATIONS; + + @Test + void canonicalFieldSetRoundTripsTheMaximumLocalPhysicalFieldCount() { + Map fields = fields(MAX_LOCAL_PHYSICAL_FIELD_COUNT); + + byte[] encoded = CanonicalGameplayIssuerBootstrapCoverageRepository.encodeFieldSet(fields); + Map decoded = + CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet(encoded); + + assertThat(decoded).hasSameSizeAs(fields); + fields.forEach((field, value) -> assertThat(decoded.get(field)).containsExactly(value)); + assertThat(CanonicalGameplayIssuerBootstrapCoverageRepository.encodeFieldSet(decoded)) + .containsExactly(encoded); + } + + @Test + void fieldSetCodecRejectsOneMoreThanTheLocalPhysicalFieldBound() { + Map overLimit = fields(MAX_LOCAL_PHYSICAL_FIELD_COUNT + 1); + + assertThatThrownBy( + () -> CanonicalGameplayIssuerBootstrapCoverageRepository.encodeFieldSet(overLimit)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( + fieldCountHeader(MAX_LOCAL_PHYSICAL_FIELD_COUNT + 1))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Persisted issuer physical field count is outside its bound"); + } + + private static Map fields(int count) { + Map fields = new LinkedHashMap<>(); + for (int index = count - 1; index >= 0; index--) { + String field = String.format(Locale.ROOT, "field-%04d", index); + fields.put(field, ("value-" + index).getBytes(StandardCharsets.UTF_8)); + } + return fields; + } + + private static byte[] fieldCountHeader(int count) { + byte[] magic = "issuer-physical-field-set/v1".getBytes(StandardCharsets.US_ASCII); + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream output = new DataOutputStream(bytes)) { + output.writeInt(magic.length); + output.write(magic); + output.writeInt(count); + } catch (IOException impossible) { + throw new AssertionError(impossible); + } + return bytes.toByteArray(); + } +} From dd164c1ca4795fc9b1fd11f150ab0edaa7cddbc2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 04:42:58 +1300 Subject: [PATCH 17/34] fix(gameplay): qualify issuer cleanup and original bootstrap retries --- .github/workflows/ci.yml | 2 +- .../game-session-service/runtime-and-data.md | 2 +- .../architecture/system-architecture-redis.md | 8 +- design/project-management/ai-observations.md | 17 +- .../player-access-and-session.md | 2 + ...calGameplayBindingInventoryRepository.java | 42 ++- ...IssuerBindingLocalOperationRepository.java | 38 +- ...ssuerBindingLocalProjectionRepository.java | 91 +++-- ...lGameplayIssuerBindingLocalRedisOwner.java | 1 - ...indingLocalReleaseOperationRepository.java | 59 ++- ...ayIssuerBindingLocalReleaseRedisOwner.java | 2 - ...ingLocalRetirementOperationRepository.java | 11 +- ...ssuerBindingLocalRetirementRedisOwner.java | 16 +- ...lGameplayIssuerBootstrapCoverageOwner.java | 41 +- ...playIssuerBootstrapCoverageRepository.java | 23 +- ...IssuerBootstrapPartitionPhysicalCodec.java | 12 +- ...playIssuerPartitionMutationRepository.java | 4 + ...ession-issuer-binding-local-retirement.lua | 19 +- ...ssion-issuer-binding-local-retirement.json | 2 +- ...eplayAdmissionAbortCompositionFixture.java | 10 + ...BindingLocalRedisOwnerIntegrationTest.java | 99 +++++ ...BootstrapCoverageOwnerIntegrationTest.java | 125 +++++- ...rapPartitionRedisOwnerIntegrationTest.java | 110 ++++++ ...suerPhysicalRetirementIntegrationTest.java | 355 +++++++++++++++++- ...yAdmissionDecisionReadGrpcServiceTest.java | 151 ++++++++ 25 files changed, 1130 insertions(+), 112 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f03b9df51c..a8bd82ca49 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1053,7 +1053,7 @@ jobs: contents: read id-token: write # Account and Game Session need 40 minutes for full checks, packaging and post-job cleanup; World and Game Design retain 30 minutes. - timeout-minutes: ${{ (matrix.module == 'account-service' || matrix.module == 'game-session-service') && 40 || (matrix.module == 'world-management-service' || matrix.module == 'game-design-service') && 30 || 20 }} + timeout-minutes: ${{ (matrix.module == 'account-service' || matrix.module == 'game-session-service') && 60 || (matrix.module == 'world-management-service' || matrix.module == 'game-design-service') && 30 || 20 }} strategy: fail-fast: false matrix: 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 cf377c29a8..0b4932a1e3 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,7 +10,7 @@ The service runtime model assumes replaceable workers, not authoritative in-proc The sections below define the target-state runtime contract. Current implementation and proof status is: -- **Local NEW issuer preparation:** the unregistered Game Session sources now manually compose the initial issuer anchor, ordinary post-baseline one-key member/capacity projection, issuer-local release, and original-operation terminal-capacity retirement, each with exact physical readback and controlled Account checkpoint and stable-incarnation collaborators. The focused component proofs do not establish operational source or incarnation custody. A separate admitting issuer acknowledgement, issuer barrier/`OPEN`, final CAS, and admission remain absent. Operational source/incarnation custody, legacy recovery, production PKI, runtime registration, and activation remain open; see the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for proof attribution and limits. The [issuer anchor owner](../../system-architecture-redis.md#installed-issuer-anchor-for-ordinary-new) defines the physical contract. +- **Local NEW issuer preparation:** the unregistered Game Session sources now manually compose the initial issuer anchor, ordinary post-baseline one-key member/capacity projection, issuer-local release, and original-operation terminal-capacity retirement, each with exact physical readback and controlled Account checkpoint and stable-incarnation collaborators. Ordinary ADD revalidates the target’s current Account authority, while terminal cleanup and non-target accounting preserve captured Account provenance. Completed-original bootstrap retries return retained installation evidence; current physical verification remains separate. The focused component proofs do not establish operational source or incarnation custody. A separate admitting issuer acknowledgement, issuer barrier/`OPEN`, final CAS, and admission remain absent. Operational source/incarnation custody, legacy recovery, production PKI, runtime registration, and activation remain open; see the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for proof attribution and limits. The [issuer anchor owner](../../system-architecture-redis.md#installed-issuer-anchor-for-ordinary-new) defines the physical contract. - **Local NEW account-member repair:** the unregistered owner prepares the original binding-local operation, performs one global account-member write and physical readback outside SQL, then accepts its exact acknowledgement in SQL. This supplies `ADD_OR_RETAIN` evidence only; the candidate remains provisional. Account-wide lifecycle writers, remaining index and region acknowledgements, and the guarded final admission CAS remain open. See [Session Behavior](../../system-architecture-session-behavior.md#global-account-active-binding-index) and [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components). diff --git a/design/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index dc52a2cfbf..c4d5feb46f 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -385,6 +385,8 @@ A binding-local issuer release requires the actual terminal Account abort and th The one-key release compares the complete original member and capacity evidence, removes only that exact old binding member, and retains a positive `RELEASED` capacity value for independent complete readback. Absence alone cannot release capacity or establish cleanup. After successful mutation and independent exact readback, SQL completion reloads the current owner, source, incarnation, reservation and anchor guards and allocates a fresh actual inventory-clock revision `R`. The completion receipt links `P`, the frozen physical postimage and readback, the original release operation and the actual `R` of the current `RELEASED` reservation. `R` must exceed `P` within that same clock domain; intervening writers may advance the clock, so adjacency is not required. No transaction is held over Redis, and no future revision is reserved or guessed. +The original captured Account-control tuple remains immutable provenance for terminal cleanup. Release and retirement requalify the exact definitive Account abort, original operation and transition, current reservation and references, source, anchor and physical proof; retirement additionally requires the original committed `RELEASED` receipt and atomic mutation fence. A legitimate later account-local control advance cannot block disposal of that old terminal member or authorize disposal of a newer member. Global issuer control and intent guards and separate Account and region obligations remain required. Checking retirement prerequisites reads an existing committed release; it never prepares a new release or reserves its partition. + Consumers require both the exact frozen physical provenance and the matching durable completion receipt and current row. They never require the physical `reservation.inventoryRevision` to equal `R`, rewrite the physical value after SQL merely to equalize revisions, or reuse one snapshot revision for two states. A crash, lost reply or exact retry reuses the original prepared bytes, `P` and operation; a completed retry reads its committed receipt without issuing a second release. Ambiguous readback, changed source/incarnation/reservation/anchor or a newer member refuses completion and preserves the pending obligation. Only that binding-local issuer repair obligation may be settled by this proof; Account cleanup, region cleanup, issuer-wide coverage and final admission retain their separate owners. ### Original-Operation Issuer Physical Retirement @@ -397,7 +399,7 @@ Retirement references the exact committed original release receipt, original res The owner independently reads back both exact field absence and the atomic successor physical fence before committing the durable retirement receipt. A lost reply, crash or ambiguous observation retains the original pending retirement and its exact expected/successor revisions for readback-based recovery; it cannot allocate a replacement intent or issue a blind deletion. Completed original release and retirement retries consume their committed historical evidence and cannot replay stale Lua to recreate a retired field. A pending retirement excludes another same-partition admission mutation until its original outcome is resolved. -Current unretired physical inventory is bounded separately from retained immutable audit history. Projection, complete per-partition and aggregate capacity accounting, currentness and obligation checks, strict permitted field sets, codecs and actual Lua/readback bounds all use that distinction. A retired field may be absent only when its exact original durable retirement proof accounts for that absence; an arbitrary missing field, foreign field or incomplete SQL inventory still fails closed. Retaining every historical `RELEASED` field, operation or per-operation tombstone in the physical set must not impose a lifetime limit on legitimate capacity turnover. Retirement preserves the complete SQL history and allows normal exact retries and more than 256 successive releases without exhausting a finite physical-history allowance. +Current unretired physical inventory is bounded separately from retained immutable audit history. Projection, complete per-partition and aggregate capacity accounting, currentness and obligation checks, strict permitted field sets, codecs and actual Lua/readback bounds all use that distinction. The permitted physical field set includes registered operations whose ADD has not committed; those not-yet-projected fields may be absent. Baseline fields, committed capacity and binding fields, and the exact mutation target remain mandatory, with complete byte comparison and bounded accounting; foreign or changed fields refuse. A retired field may be absent only when its exact original durable retirement proof accounts for that absence; a missing mandatory field or incomplete SQL inventory still fails closed. Retaining every historical `RELEASED` field, operation or per-operation tombstone in the physical set must not impose a lifetime limit on legitimate capacity turnover. Retirement preserves the complete SQL history and allows normal exact retries and more than 256 successive releases without exhausting a finite physical-history allowance. ### Canonical Issuer Partition Mapping @@ -457,6 +459,10 @@ Ordinary binding-local `NEW` may use the global issuer index only under a positi The issuer owner establishes that anchor only from an authorized immutable layout descriptor, exact current Account source checkpoint, verified legacy disposition, and complete durable issuer inventory including reservations and unresolved obligations. It must build or verify every required partition and reservation, prove local and aggregate capacity, and retain same-attempt readback before guarded publication. An empty physical index, absent or empty inventory result, or conformance-vector count is not initialization authority; unresolved legacy identities remain retained and fenced. Controlled descriptor, source, and incarnation inputs establish only local algorithm behavior, not operational bootstrap authority. +An exact completed-original bootstrap retry returns its retained committed installation result. It verifies the original request and operation, immutable anchor and all retained partition proofs, and the current issuer source, control and incarnation qualifications promised by that owner. It uses the frozen installed plan without rebuilding from later inventory, replaying old partition mutations or requiring initial baseline bytes to equal later legitimate NEW, release or retirement state. This historical result is not a fresh physical-health or coverage read; ordinary NEW, acknowledgements and admission retain their independent current physical and source verification, including missing or reset-state refusal. + +Ordinary ADD requires its target’s exact current Account-control and source authority before and after the physical boundary. Other retained entries remain fully verified and counted, but their captured Account-control tuples are historical provenance; issuer-wide accounting does not lock unrelated Account rows or require those later mutable rows to remain byte-identical. Account-local control advancement does not waive any target ADD guard or issuer-wide intent fence. + The physical v2 HASH value above is a projection, not the installed anchor or an issuer binding-local acknowledgement. Its anchor tuple and preserved original reservation tuple remain separate even when a bootstrap operation links both to the same frozen cohort. The separate issuer acknowledgement must be explicitly versioned and bind the complete anchor, exact local transition/reservation, member and capacity readbacks, current control/incarnation evidence, and owner-issued per-transition generation. Neither physical-row parsing nor the account `accountIndexAcknowledgement` schema v2 can manufacture that result; the account acknowledgement and its CLOSED barrier receipt establish no issuer anchor or issuer `INSTALLED`/`OPEN` state. The final tenant-local CAS must positively compare the exact issuer barrier `OPEN` state and owner epoch/incarnation with the original candidate and required Account, issuer, and region evidence; global issuer-index and capacity keys never enter tenant-local Lua. ### Recovery and Cutoff Scope Authority diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 6b22ce43f6..82784e7fc0 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -422,6 +422,17 @@ Entry format: - Observation: Absence from an active-job filter proves only that the job is no longer active. Treating it as success delayed repair of two stale raw-abort assertion messages and produced an incorrect status report. This was observer logic, not a FireController defect. - Expected pattern: The single CI observer reads all current-run job conclusions, including completed failures and cancellations, on every cycle and reports an actionable failure immediately. Use a filtered active-job view only to summarize remaining work; never infer success from that view or wait for the aggregate gate to fail. -- 2026-10-27: Forward owner migrations can break shared disposable fixtures even when focused owner proof passes. In #2973, a new retained completion FK exposed an omitted child in the Game Session baseline TRUNCATE list and broke both Game Session and TCP cross-service suites; a reduced World migration probe also omitted tables required by the new tail migration. Keep explicit baseline descendants and exact original trigger-state restoration together, and make reduced probes execute the complete current migration tail with its real prerequisite tables. A later Hikari closed-connection or teardown refusal can mask the original PostgreSQL error; inspect the first SQL failure in the completed job's JUnit output before attributing it to Docker availability. - -- 2026-10-27: Manual Entity Flyway fixtures must retain Entity’s existing nontransactional PostgreSQL migration-lock setting. The region composition’s new Entity schema otherwise left `CREATE UNIQUE INDEX CONCURRENTLY` waiting on Flyway’s own history transaction. An owned JVM thread dump plus `pg_blocking_pids` identified the self-block; cancelling only that matched test-owned backend preserved the failed run. Use the existing `PostgreSQLConfigurationExtension.setTransactionalLock(false)` pattern for the Entity fixture rather than changing applied migrations or host configuration. +- `2026-10-27`: Forward owner migrations can break shared disposable fixtures + - Context: In #2973, a new retained completion FK exposed an omitted child in the Game Session baseline TRUNCATE list and broke both Game Session and TCP cross-service suites; a reduced World migration probe also omitted tables required by the new tail migration. + - Observation: Focused owner proof can pass while shared fixtures fail, and a later Hikari closed-connection or teardown refusal can mask the original PostgreSQL error. + - Expected pattern: Keep explicit baseline descendants and exact original trigger-state restoration together, make reduced probes execute the complete current migration tail with its real prerequisite tables, and inspect the first SQL failure in the completed job's JUnit output before attributing failure to Docker availability. + +- `2026-10-27`: Manual Entity Flyway fixtures require the existing migration-lock setting + - Context: The region composition’s new Entity schema left `CREATE UNIQUE INDEX CONCURRENTLY` waiting on Flyway’s own history transaction. + - Observation: An owned JVM thread dump plus `pg_blocking_pids` identified the self-block; cancelling only that matched test-owned backend preserved the failed run. + - Expected pattern: Retain Entity’s existing `PostgreSQLConfigurationExtension.setTransactionalLock(false)` pattern for the fixture rather than changing applied migrations or host configuration. + +- `2026-10-27`: Failure diagnostics must retain the attempted transaction input + - Context: The manual Human-to-region composition rejected a guarded update and rolled its transaction back before the diagnostic reread. + - Observation: Reconstructing expected values from the retained `PREPARED` row yielded NULL admission fields and misleading predicate failures instead of the attempted decision. + - Expected pattern: Pass the immutable attempted selector to bounded failure-only diagnostics, read actual durable source rows separately, and keep attempted values distinct from committed evidence. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index ad9b65fcbf..7d989f2360 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -34,6 +34,8 @@ R625 freshly passes the combined owner gate: 11 unit cases, 35 issuer PostgreSQL The expanded #3310 correction implements the [original-operation physical retirement contract](../../architecture/system-architecture-redis.md#original-operation-issuer-physical-retirement) under the existing release/local-mutation owner. R675 freshly passes 77 cases: 21 units, 49 Game Session PostgreSQL/Redis cases and seven actual Account–Game Session cases, with zero failures, errors or skips; enabled affected static analysis, formatting and 547-file documentation checks pass. Physical proof includes 257 actual Game Session releases and retirements with complete immutable SQL history, original lost-reply/restart recovery and completed retry, stale ADD and release rejection, pending same-partition exclusion, missing-revision and foreign/currentness refusal, preservation of newer fields, a 256-readable/257-refused current local-entry bound, and actual 514-field release/readback/persistence/reload. The wide case uses 250 owner-produced provisional bootstrap rows and a small post-baseline cohort; the turnover case retires each terminal field rather than accumulating 256 terminal fields. The physical mutation revision is a separate positively installed UUID domain, and historical unfenced bootstrap audit rows remain retained without qualifying current fenced coverage. The seven Account composition cases separately retain their real current-caller, lease, abort and issuer-release attribution. The new turnover cases use controlled upstream Account lease/abort, issuer checkpoint, launch/World and stable-incarnation inputs; they do not prove those producers or production authority. R672 remains a failed aggregate, including its oversized test-only history image, current-readback omission and retirement Lua shape failure; R677 separately passes the corrected 46-case preflight before R675. Operational custody, registration, admitting acknowledgements, barrier OPEN, final CAS and playable admission remain unproved. +The subsequent correction separates immutable Account provenance from current ADD authority through the original abort, release and retirement readers, and makes the full completed-original bootstrap retry return its retained installation result without replaying baseline writes. Current target ADD guards, complete inventory accounting and mandatory physical-field checks remain required. Across R687, R688 and R689, all 88 selected case methods have current qualified execution: 26 units, 55 Game Session PostgreSQL/Redis cases and seven actual Account–Game Session cases. R687 remains a failed 88-case aggregate with 11 failures; R688 recovers those affected suites with 24 cases and one different Redis-startup failure, and R689 separately passes that unchanged negative case. The only source difference between R687 and R688 is test-layout isolation for two new cases; production postimages are identical. The physical suite again proves 257 actual releases and retirements, the 256/257 current-entry boundary and 514-field readback. New proof covers Account A advancing through the real acquisition-intent owner while unrelated Account B progresses, stale target ADD refusal, original cleanup and retirement, newer-field preservation, and unchanged SQL/proofs/Redis state through full bootstrap retries after NEW, release and retirement. That control case starts from captured `NO_ACTIVE_ACCOUNT_WIDE_FLOW`; it does not produce a new `HISTORICAL` control tuple. Enabled affected static analysis and formatting pass. Controlled upstream/source/incarnation inputs and all operational-custody, registration, admitting-acknowledgement, OPEN, final-CAS and activation limits remain unchanged. + ### Player-created roster consumer preparation The unregistered Game Session composition consumes the independently resolved current published source through Entity's distinct created-roster and selected-character reads, preserving full original creation terminals, frozen menu/actor choice and the typed original-operation receipt/recovery/retirement branch. The [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#player-created-roster-and-selected-character) owns the created evidence contract; [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md#player-created-original-roster-storage) records its local storage consequences. V1020 receipt storage does not include the separate canonical UUID runtime or creation-protection owners and supplies no Account protection or admission authority. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index 004a6027e6..4b1fd6cce3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -320,6 +320,22 @@ CanonicalGameplayAdmissionAbortSource readFirstNewAdmissionAbortSource(UUID tran }); } + /** + * Reads only an already recorded definitive first-NEW Account abort for issuer cleanup. Its + * original transition, candidate, reservation, and cleanup identity remain authoritative; a later + * mutable Account-control value does not rewrite that retained terminal provenance. + */ + CanonicalGameplayAdmissionAbortSource readRetainedDefinitiveFirstNewAccountAbortSource( + UUID transitionId) { + Objects.requireNonNull(transitionId, "transitionId"); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + return loadFirstNewAdmissionAbortSource(transaction, transitionId, false, true); + }); + } + /** * Read-only package seam for the local issuer release owner inside its guarded SQL transaction. */ @@ -330,6 +346,15 @@ static CanonicalGameplayAdmissionAbortSource readFirstNewAdmissionAbortSourceInT return loadFirstNewAdmissionAbortSource(transaction, transitionId, forUpdate); } + /** Read-only/update-locked seam for exact retained terminal cleanup inside the caller's SQL. */ + static CanonicalGameplayAdmissionAbortSource + readRetainedDefinitiveFirstNewAccountAbortSourceInTransaction( + DSLContext transaction, UUID transitionId, boolean forUpdate) { + Objects.requireNonNull(transaction, "transaction"); + Objects.requireNonNull(transitionId, "transitionId"); + return loadFirstNewAdmissionAbortSource(transaction, transitionId, forUpdate, true); + } + /** * Commits Account's exact definitive first-NEW abort into the existing transition and retained * candidate/reservation source. The Account RPC is performed by the caller outside this method. @@ -1569,6 +1594,14 @@ private static CanonicalGameplayBindingProvisionalCasEvidence loadProvisionalCas private static CanonicalGameplayAdmissionAbortSource loadFirstNewAdmissionAbortSource( DSLContext transaction, UUID transitionId, boolean forUpdate) { + return loadFirstNewAdmissionAbortSource(transaction, transitionId, forUpdate, false); + } + + private static CanonicalGameplayAdmissionAbortSource loadFirstNewAdmissionAbortSource( + DSLContext transaction, + UUID transitionId, + boolean forUpdate, + boolean retainedDefinitiveAbortCleanup) { String lock = forUpdate ? " FOR UPDATE" : ""; Record transition = transaction.fetchOne( @@ -1640,7 +1673,12 @@ private static CanonicalGameplayAdmissionAbortSource loadFirstNewAdmissionAbortS throw conflict("First-NEW transition changed its complete Account lease evidence"); } - if (forUpdate) { + if (retainedDefinitiveAbortCleanup) { + if (!source.isAccountAborted() || source.orphanCleanupId() == null) { + throw conflict( + "Issuer cleanup requires the exact retained definitive first-NEW Account abort"); + } + } else if (forUpdate) { requireAccountCoverageEvidenceCurrent( transaction, candidate.identity().accountId(), @@ -3747,7 +3785,7 @@ private static CanonicalGameplayBindingTransitionSnapshot toTransitionSnapshot(R toAccountCoverageEvidence(row, identity.accountId())); } - private static CanonicalGameplayAccountCoverageEvidence toAccountCoverageEvidence( + static CanonicalGameplayAccountCoverageEvidence toAccountCoverageEvidence( Record row, UUID accountId) { String state = row.get("account_coverage_state", String.class); if ("NO_ACTIVE_ACCOUNT_WIDE_FLOW".equals(state)) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java index fabd0ba676..f4211b470c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java @@ -148,8 +148,8 @@ CanonicalGameplayIssuerBindingLocalOperation readOriginalForIssuerRelease( .readInstalledAnchorPartitionProof( transaction, anchor, reservation.partitionId()); AccountControlSnapshot accountControl = - readAndRequireAccountControl( - transaction, + readCapturedAccountControl( + operationRow, abortSource.candidate().identity().accountId(), abortSource.transition().accountCoverageEvidence()); Request request = @@ -619,6 +619,40 @@ private static AccountControlSnapshot readAndRequireAccountControl( return current; } + private static AccountControlSnapshot readCapturedAccountControl( + Record operationRow, + UUID accountId, + CanonicalGameplayAccountCoverageEvidence originalEvidence) { + AccountControlSnapshot captured = AccountControlSnapshot.fromOperation(operationRow, accountId); + if (!captured.evidence().equals(originalEvidence)) { + throw conflict( + "Original Account-control provenance differs from the retained first-NEW transition"); + } + return captured; + } + + static void requireCapturedAccountControlMatchesTransition( + Record operationRow, Record transitionRow, UUID accountId) { + readCapturedAccountControl( + operationRow, + accountId, + CanonicalGameplayBindingInventoryRepository.toAccountCoverageEvidence( + transitionRow, accountId)); + } + + static void requireCurrentAccountControlMatchesCaptured( + DSLContext transaction, Record operationRow, UUID accountId) { + Record account = + transaction.fetchOne( + "SELECT * FROM " + ACCOUNT_CONTROL + " WHERE account_id = ? FOR UPDATE", accountId); + if (account == null + || !AccountControlSnapshot.from(account, accountId) + .equals(AccountControlSnapshot.fromOperation(operationRow, accountId))) { + throw conflict( + "Current Account coverage control differs from the original ordinary NEW checkpoint"); + } + } + private static void insertOperation( DSLContext transaction, CanonicalGameplayIssuerBindingLocalOperation.Request request, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java index 607f3121a0..6ac20c1267 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java @@ -39,7 +39,6 @@ final class CanonicalGameplayIssuerBindingLocalProjectionRepository { "game_session_canonical_binding_region_bridge_obligation"; private static final String ISSUER_LOCAL_RELEASE = "game_session_canonical_issuer_binding_local_release_operation"; - private static final String ACCOUNT_CONTROL = "game_session_canonical_account_coverage_control"; private static final String INVENTORY_CLOCK = "game_session_canonical_binding_inventory_clock"; private static final int MAX_LOCAL_OPERATIONS_PER_PARTITION = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_MEMBER_OPERATIONS; @@ -63,16 +62,18 @@ final class CanonicalGameplayIssuerBindingLocalProjectionRepository { */ PreparedPartitionWork readPreparedPartitionWork( CanonicalGameplayIssuerBindingLocalOperation target) { - return readPreparedPartitionWork(target, false); + return readPreparedPartitionWork(target, false, false); } PreparedPartitionWork prepareAddMutationWork( CanonicalGameplayIssuerBindingLocalOperation target) { - return readPreparedPartitionWork(target, true); + return readPreparedPartitionWork(target, true, true); } private PreparedPartitionWork readPreparedPartitionWork( - CanonicalGameplayIssuerBindingLocalOperation target, boolean prepareAddMutation) { + CanonicalGameplayIssuerBindingLocalOperation target, + boolean prepareAddMutation, + boolean requireCurrentTargetAccountControl) { Objects.requireNonNull(target, "target"); requireNoAmbientTransaction(); var before = readCurrentIssuerState(); @@ -86,7 +87,12 @@ private PreparedPartitionWork readPreparedPartitionWork( CanonicalGameplayIssuerBootstrapCoverageRepository .readInstalledAnchorForBindingPreparationInTransaction(transaction, before); requireSameAnchor(target.anchor(), anchor); - return prepareInTransaction(transaction, target, anchor, prepareAddMutation); + return prepareInTransaction( + transaction, + target, + anchor, + prepareAddMutation, + requireCurrentTargetAccountControl); }); var after = readCurrentIssuerState(); requireSameCurrentIssuerState(before, after); @@ -97,7 +103,9 @@ private PreparedPartitionWork readPreparedPartitionWork( /** Re-reads the durable set and all currentness inputs after the Redis round trip. */ void requireStillCurrent(PreparedPartitionWork expected) { Objects.requireNonNull(expected, "expected"); - PreparedPartitionWork current = readPreparedPartitionWork(expected.targetOperation()); + PreparedPartitionWork current = + readPreparedPartitionWork( + expected.targetOperation(), false, expected.requiresCurrentTargetAccountControl()); if (!Arrays.equals(expected.sqlCurrentnessDigest(), current.sqlCurrentnessDigest())) { throw unavailable( "The registered issuer member set or current SQL phase changed during projection"); @@ -120,7 +128,8 @@ private PreparedPartitionWork prepareInTransaction( DSLContext transaction, CanonicalGameplayIssuerBindingLocalOperation target, CanonicalGameplayIssuerInstalledAnchor anchor, - boolean prepareAddMutation) { + boolean prepareAddMutation, + boolean requireCurrentTargetAccountControl) { BigInteger targetPartition = target.reservation().partitionId(); CanonicalGameplayIssuerPartitionMutationRepository.PartitionMutationHead mutationHead = CanonicalGameplayIssuerPartitionMutationRepository.readHeadInTransaction( @@ -168,7 +177,14 @@ private PreparedPartitionWork prepareInTransaction( BigInteger localPartitionCapacity = BigInteger.ZERO; boolean foundTarget = false; for (Record row : operationRows) { - LocalEntry entry = readLocalEntry(transaction, row, anchor, target); + LocalEntry entry = + readLocalEntry( + transaction, + row, + anchor, + target, + requireCurrentTargetAccountControl + && uuid(row, "operation_id").equals(target.operationId())); if (!localOperationIds.add(entry.operationId()) || (!entry.registeredOperationId().equals(entry.operationId()) && !localOperationIds.add(entry.registeredOperationId())) @@ -339,14 +355,16 @@ private PreparedPartitionWork prepareInTransaction( mutationHead.currentRevision(), mutationHead.pendingMutationId(), physicalMutation, - currentnessDigest); + currentnessDigest, + requireCurrentTargetAccountControl); } private LocalEntry readLocalEntry( DSLContext transaction, Record row, CanonicalGameplayIssuerInstalledAnchor anchor, - CanonicalGameplayIssuerBindingLocalOperation target) { + CanonicalGameplayIssuerBindingLocalOperation target, + boolean requireCurrentAccountControl) { if (!ISSUER.equals(text(row, "issuer_id")) || !"PENDING_PHYSICAL_PROOF".equals(text(row, "member_status")) || !Objects.equals(row.get("member_schema_version", Short.class), (short) 2) @@ -481,7 +499,14 @@ private LocalEntry readLocalEntry( inventoryRow, transitionRow, issuerObligation); - requireAccountControlCurrent(transaction, row, member.owner().accountId()); + CanonicalGameplayIssuerBindingLocalOperationRepository + .requireCapturedAccountControlMatchesTransition( + row, transitionRow, member.owner().accountId()); + if (requireCurrentAccountControl) { + CanonicalGameplayIssuerBindingLocalOperationRepository + .requireCurrentAccountControlMatchesCaptured( + transaction, row, member.owner().accountId()); + } CanonicalGameplayIssuerPartitionMutation capacityMutation = CanonicalGameplayIssuerPartitionMutationRepository.readOptionalInTransaction( transaction, @@ -703,41 +728,6 @@ private static void requireOwnerColumns( } } - private static void requireAccountControlCurrent( - DSLContext transaction, Record operation, UUID accountId) { - Record account = - transaction.fetchOne( - "SELECT * FROM " + ACCOUNT_CONTROL + " WHERE account_id = ? FOR UPDATE", accountId); - if (account == null - || !Objects.equals(text(account, "state"), text(operation, "account_control_state")) - || !number(account, "last_operation_fence") - .equals(number(operation, "account_control_epoch")) - || !Objects.equals( - account.get("current_operation_id", UUID.class), - operation.get("account_current_operation_id", UUID.class)) - || !Objects.equals( - account.get("current_operation_fence", BigDecimal.class), - operation.get("account_current_operation_fence", BigDecimal.class)) - || !Objects.equals( - account.get("account_admission_fence", UUID.class), - operation.get("account_admission_fence", UUID.class)) - || !Objects.equals( - account.get("historical_account_admission_fence", UUID.class), - operation.get("account_historical_admission_fence", UUID.class)) - || !Objects.equals( - account.get("coverage_fence", UUID.class), - operation.get("account_coverage_fence", UUID.class)) - || !Objects.equals( - account.get("inventory_snapshot_revision", BigDecimal.class), - operation.get("account_inventory_snapshot_revision", BigDecimal.class)) - || !Objects.equals( - account.get("coverage_generation", BigDecimal.class), - operation.get("account_coverage_generation", BigDecimal.class))) { - throw unavailable( - "The original Account coverage control changed after local issuer registration"); - } - } - private static Set readAndVerifyBootstrapReservationIds( DSLContext transaction, CanonicalGameplayIssuerInstalledAnchor anchor) { List rows = @@ -1360,6 +1350,7 @@ static final class PreparedPartitionWork { private final UUID pendingMutationId; private final CanonicalGameplayIssuerPartitionMutation physicalMutation; private final byte[] sqlCurrentnessDigest; + private final boolean requiresCurrentTargetAccountControl; private PreparedPartitionWork( CanonicalGameplayIssuerInstalledAnchor anchor, @@ -1376,7 +1367,8 @@ private PreparedPartitionWork( UUID currentRevision, UUID pendingMutationId, CanonicalGameplayIssuerPartitionMutation physicalMutation, - byte[] sqlCurrentnessDigest) { + byte[] sqlCurrentnessDigest, + boolean requiresCurrentTargetAccountControl) { this.anchor = anchor; this.targetOperation = targetOperation; this.baselineProof = baselineProof; @@ -1391,6 +1383,7 @@ private PreparedPartitionWork( this.pendingMutationId = pendingMutationId; this.physicalMutation = physicalMutation; this.sqlCurrentnessDigest = sqlCurrentnessDigest.clone(); + this.requiresCurrentTargetAccountControl = requiresCurrentTargetAccountControl; } CanonicalGameplayIssuerInstalledAnchor anchor() { @@ -1401,6 +1394,10 @@ CanonicalGameplayIssuerBindingLocalOperation targetOperation() { return targetOperation; } + boolean requiresCurrentTargetAccountControl() { + return requiresCurrentTargetAccountControl; + } + CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof baselineProof() { return baselineProof; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java index eae3c77a7e..c2151b6fab 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java @@ -201,7 +201,6 @@ private byte[] readExactPhysicalState( Map baseline = work.baselineFields(); Map allowed = work.allowedFields(); - if (actual.size() != allowed.size() + 1) throw unavailable(); byte[] physicalRevision = actual.get( Base64.getEncoder() diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.java index bf9bf4bff9..938b42e430 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.java @@ -52,7 +52,8 @@ final class CanonicalGameplayIssuerBindingLocalReleaseOperationRepository { CanonicalGameplayIssuerBindingLocalReleaseOperation prepareOrResume(UUID transitionId) { Objects.requireNonNull(transitionId, "transitionId"); requireNoAmbientTransaction(); - var sourceBefore = inventoryRepository.readFirstNewAdmissionAbortSource(transitionId); + var sourceBefore = + inventoryRepository.readRetainedDefinitiveFirstNewAccountAbortSource(transitionId); requireAbortedSource(sourceBefore); var issuerStateBefore = readCurrentIssuerState(); var original = localOperationRepository.readOriginalForIssuerRelease(sourceBefore); @@ -64,7 +65,7 @@ CanonicalGameplayIssuerBindingLocalReleaseOperation prepareOrResume(UUID transit CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); var source = CanonicalGameplayBindingInventoryRepository - .readFirstNewAdmissionAbortSourceInTransaction( + .readRetainedDefinitiveFirstNewAccountAbortSourceInTransaction( transaction, transitionId, true); requireSameAbortSource(sourceBefore, source); Record existing = @@ -88,7 +89,7 @@ CanonicalGameplayIssuerBindingLocalReleaseOperation prepareOrResume(UUID transit transaction, source, priorRevision, sourceRevision, currentRevision); source = CanonicalGameplayBindingInventoryRepository - .readFirstNewAdmissionAbortSourceInTransaction( + .readRetainedDefinitiveFirstNewAccountAbortSourceInTransaction( transaction, transitionId, false); var counters = CanonicalGameplayIssuerBindingLocalOperationRepository.allocateLocalCounters( @@ -147,10 +148,54 @@ CanonicalGameplayIssuerBindingLocalReleaseOperation prepareOrResume(UUID transit }); requireSameCurrentIssuerState(issuerStateBefore, readCurrentIssuerState()); requireSameAbortIdentity( - sourceBefore, inventoryRepository.readFirstNewAdmissionAbortSource(transitionId)); + sourceBefore, + inventoryRepository.readRetainedDefinitiveFirstNewAccountAbortSource(transitionId)); return operation; } + /** Reads only an existing, committed release receipt for a physical-retirement caller. */ + CanonicalGameplayIssuerBindingLocalReleaseOperation readCommittedRelease(UUID transitionId) { + Objects.requireNonNull(transitionId, "transitionId"); + requireNoAmbientTransaction(); + CanonicalGameplayAdmissionAbortSource sourceBefore = + inventoryRepository.readRetainedDefinitiveFirstNewAccountAbortSource(transitionId); + requireAbortedSource(sourceBefore); + var issuerStateBefore = readCurrentIssuerState(); + CanonicalGameplayIssuerBindingLocalOperation original = + localOperationRepository.readOriginalForIssuerRelease(sourceBefore); + CanonicalGameplayIssuerBindingLocalReleaseOperation committed = + dsl.transactionResult( + configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + CanonicalGameplayAdmissionAbortSource source = + CanonicalGameplayBindingInventoryRepository + .readRetainedDefinitiveFirstNewAccountAbortSourceInTransaction( + transaction, transitionId, false); + requireSameAbortSource(sourceBefore, source); + Record existing = + transaction.fetchOne( + "SELECT * FROM " + RELEASE + " WHERE transition_id = ?", transitionId); + if (existing == null) { + throw conflict( + "Physical retirement requires an existing committed release receipt"); + } + CanonicalGameplayIssuerBindingLocalReleaseOperation operation = + readOperation(transaction, existing, source, original); + if (operation.status() + != CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED) { + throw conflict( + "Physical retirement requires a committed original RELEASED receipt"); + } + return operation; + }); + requireSameCurrentIssuerState(issuerStateBefore, readCurrentIssuerState()); + requireSameAbortSource( + committed.abortSource(), + inventoryRepository.readRetainedDefinitiveFirstNewAccountAbortSource(transitionId)); + return committed; + } + /** Completes only the exact private physical-owner readback and returns its durable receipt. */ CanonicalGameplayIssuerBindingLocalReleaseOperation completeWithReadback( CanonicalGameplayIssuerBindingLocalReleaseOperation expected, @@ -173,7 +218,7 @@ CanonicalGameplayIssuerBindingLocalReleaseOperation completeWithReadback( UUID transitionId = expected.abortSource().transition().transitionId(); var source = CanonicalGameplayBindingInventoryRepository - .readFirstNewAdmissionAbortSourceInTransaction( + .readRetainedDefinitiveFirstNewAccountAbortSourceInTransaction( transaction, transitionId, true); requireExactReleaseSource(expected, source); Record releaseRow = @@ -333,7 +378,7 @@ CanonicalGameplayIssuerBindingLocalReleaseOperation completeWithReadback( "Issuer release lost the current inventory-clock compare-and-set"); var completedSource = CanonicalGameplayBindingInventoryRepository - .readFirstNewAdmissionAbortSourceInTransaction( + .readRetainedDefinitiveFirstNewAccountAbortSourceInTransaction( transaction, transitionId, false); Record completedRow = transaction.fetchOne( @@ -346,7 +391,7 @@ CanonicalGameplayIssuerBindingLocalReleaseOperation completeWithReadback( }); requireSameCurrentIssuerState(issuerStateBefore, readCurrentIssuerState()); CanonicalGameplayAdmissionAbortSource sourceAfter = - inventoryRepository.readFirstNewAdmissionAbortSource( + inventoryRepository.readRetainedDefinitiveFirstNewAccountAbortSource( completed.abortSource().transition().transitionId()); // The decision is reparsed on each read and deliberately has no object-identity equality. // Compare the complete durable value source and its exact original lease/target instead. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.java index 418db0284c..b9f1d360d4 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.java @@ -194,8 +194,6 @@ private byte[] readExactPhysicalState( } Map baseline = work.baselineFields(); Map allowed = work.allowedFields(); - if (actual.size() != allowed.size()) - throw unavailable("Issuer partition contains an unknown field"); byte[] physicalRevision = actual.get( b64( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java index 72fd51364a..fde559faef 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java @@ -53,10 +53,7 @@ CanonicalGameplayIssuerBindingLocalRetirementOperation prepareOrResume(UUID tran readCompletedRetirement(transitionId); if (completed != null) return completed; CanonicalGameplayIssuerBindingLocalReleaseOperation release = - releaseRepository.prepareOrResume(transitionId); - if (release.status() != CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED) { - throw conflict("Physical retirement requires a committed original RELEASED receipt"); - } + releaseRepository.readCommittedRelease(transitionId); var before = readCurrentIssuerState(); requireSourceMatchesRelease(release.abortSource(), release); CanonicalGameplayIssuerBindingLocalRetirementOperation prepared = @@ -66,7 +63,7 @@ CanonicalGameplayIssuerBindingLocalRetirementOperation prepareOrResume(UUID tran CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); CanonicalGameplayAdmissionAbortSource currentSource = CanonicalGameplayBindingInventoryRepository - .readFirstNewAdmissionAbortSourceInTransaction( + .readRetainedDefinitiveFirstNewAccountAbortSourceInTransaction( transaction, transitionId, true); requireSameReleaseSource(release.abortSource(), currentSource, release); requireExactCommittedReleaseRow(transaction, release); @@ -107,7 +104,7 @@ CanonicalGameplayIssuerBindingLocalRetirementOperation prepareOrResume(UUID tran requireSameCurrentIssuerState( before, readCurrentIssuerState(), prepared.release().originalOperation().anchor()); CanonicalGameplayIssuerBindingLocalReleaseOperation after = - releaseRepository.prepareOrResume(transitionId); + releaseRepository.readCommittedRelease(transitionId); requireSameReleaseOperation(release, after); return prepared; } @@ -424,7 +421,7 @@ CanonicalGameplayIssuerBindingLocalRetirementOperation completeWithReadback( CanonicalGameplayIssuerBindingLocalReleaseOperation release = expected.release(); CanonicalGameplayAdmissionAbortSource source = CanonicalGameplayBindingInventoryRepository - .readFirstNewAdmissionAbortSourceInTransaction( + .readRetainedDefinitiveFirstNewAccountAbortSourceInTransaction( transaction, release.abortSource().transition().transitionId(), true); requireSameReleaseSource(release.abortSource(), source, release); requireExactCommittedReleaseRow(transaction, release); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.java index aec2e24d4f..ea8a7ffa64 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.java @@ -205,15 +205,13 @@ private byte[] readExactPhysicalState( CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD.getBytes( StandardCharsets.US_ASCII))); if (!Arrays.equals( - revision, - operation - .physicalMutation() - .successorRevision() - .toString() - .getBytes(StandardCharsets.US_ASCII)) - || actual.size() != allowed.size() + 1) { - throw unavailable( - "Issuer retirement lacks the exact successor fence or current field count"); + revision, + operation + .physicalMutation() + .successorRevision() + .toString() + .getBytes(StandardCharsets.US_ASCII))) { + throw unavailable("Issuer retirement lacks its exact successor fence"); } for (Map.Entry field : work.baselineFields().entrySet()) { byte[] value = actual.get(b64(field.getKey().getBytes(StandardCharsets.UTF_8))); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwner.java index 84169b204d..514fa6df88 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwner.java @@ -29,8 +29,8 @@ public CanonicalGameplayIssuerBootstrapCoverageOwner( } /** - * Completes or replays one exact pending initial bootstrap operation. Its finite partition range, - * complete source cohort, and partition work are all read from the persisted SQL owners. + * Completes one initial installation or returns the retained result for its exact original retry. + * An installed result is historical installation evidence, not fresh physical coverage. */ public CanonicalGameplayIssuerInstalledAnchor completeInitialBootstrap( UUID bootstrapOperationId, UUID bootstrapRequestId) { @@ -38,6 +38,13 @@ public CanonicalGameplayIssuerInstalledAnchor completeInitialBootstrap( requireNonNil(bootstrapRequestId, "bootstrapRequestId"); requireNoAmbientTransaction(); + CanonicalGameplayIssuerBootstrapCoverageRepository coverageRepository = + new CanonicalGameplayIssuerBootstrapCoverageRepository(dsl); + Optional retainedInstallation = + coverageRepository.readInstalledAnchor( + bootstrapOperationId, bootstrapRequestId, readFreshCurrentState()); + if (retainedInstallation.isPresent()) return retainedInstallation.get(); + CanonicalGameplayIssuerPartitionBuildPlan plan = new CanonicalGameplayIssuerPartitionBuildRepository(dsl) .prepareInitialBuildPlan(bootstrapOperationId, bootstrapRequestId); @@ -46,13 +53,11 @@ public CanonicalGameplayIssuerInstalledAnchor completeInitialBootstrap( } CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState initialState = readAndRequireCurrentState(plan); - CanonicalGameplayIssuerBootstrapCoverageRepository coverageRepository = - new CanonicalGameplayIssuerBootstrapCoverageRepository(dsl); Optional installed = coverageRepository.readInstalledAnchor( bootstrapOperationId, bootstrapRequestId, initialState); if (installed.isPresent()) { - return readInstalledAnchorPartitions(plan, installed.get(), coverageRepository, initialState); + return installed.get(); } CanonicalGameplayIssuerBootstrapMemberOperationRepository memberOperationRepository = @@ -85,6 +90,32 @@ public CanonicalGameplayIssuerInstalledAnchor completeInitialBootstrap( return anchor; } + /** + * Performs a separate read-only physical verification of the original installed baseline. This + * gate intentionally requires the current inventory to still match that frozen baseline. + */ + CanonicalGameplayIssuerInstalledAnchor verifyInstalledPhysicalCoverage( + UUID bootstrapOperationId, UUID bootstrapRequestId) { + requireNonNil(bootstrapOperationId, "bootstrapOperationId"); + requireNonNil(bootstrapRequestId, "bootstrapRequestId"); + requireNoAmbientTransaction(); + CanonicalGameplayIssuerPartitionBuildPlan plan = + new CanonicalGameplayIssuerPartitionBuildRepository(dsl) + .prepareInitialBuildPlan(bootstrapOperationId, bootstrapRequestId); + if (plan.state() != CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED) { + throw unavailable("Complete issuer bootstrap plan contains unresolved blockers"); + } + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState = + readAndRequireCurrentState(plan); + CanonicalGameplayIssuerBootstrapCoverageRepository coverageRepository = + new CanonicalGameplayIssuerBootstrapCoverageRepository(dsl); + CanonicalGameplayIssuerInstalledAnchor installed = + coverageRepository + .readInstalledAnchor(bootstrapOperationId, bootstrapRequestId, currentState) + .orElseThrow(() -> unavailable("Original issuer bootstrap has no installed anchor")); + return readInstalledAnchorPartitions(plan, installed, coverageRepository, currentState); + } + private CanonicalGameplayIssuerInstalledAnchor readInstalledAnchorPartitions( CanonicalGameplayIssuerPartitionBuildPlan plan, CanonicalGameplayIssuerInstalledAnchor installed, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java index b39400ea37..4f4031b675 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java @@ -165,10 +165,16 @@ Optional readInstalledAnchor( return dsl.transactionResult( configuration -> { DSLContext transaction = org.jooq.impl.DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + Record anchorProbe = + transaction.fetchOne( + "SELECT issuer_id FROM " + ANCHOR + " WHERE issuer_id = ?", ISSUER); + if (anchorProbe == null) return Optional.empty(); + CanonicalGameplayIssuerPartitionBuildRepository buildRepository = + new CanonicalGameplayIssuerPartitionBuildRepository(transaction); CanonicalGameplayIssuerPartitionBuildPlan plan = - new CanonicalGameplayIssuerPartitionBuildRepository(transaction) - .readPreparedPlanInTransaction( - transaction, bootstrapOperationId, bootstrapRequestId); + buildRepository.readInstalledPlanForAnchorInTransaction( + transaction, bootstrapOperationId, bootstrapRequestId); requireCurrentState(currentState, plan.bootstrapIntent()); Record row = transaction.fetchOne( @@ -404,11 +410,18 @@ CanonicalGameplayIssuerInstalledAnchor installInitialAnchor( return dsl.transactionResult( configuration -> { DSLContext transaction = org.jooq.impl.DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); CanonicalGameplayIssuerPartitionBuildRepository buildRepository = new CanonicalGameplayIssuerPartitionBuildRepository(transaction); + Record anchorProbe = + transaction.fetchOne( + "SELECT issuer_id FROM " + ANCHOR + " WHERE issuer_id = ?", ISSUER); CanonicalGameplayIssuerPartitionBuildPlan plan = - buildRepository.readPreparedPlanInTransaction( - transaction, bootstrapOperationId, bootstrapRequestId); + anchorProbe == null + ? buildRepository.readPreparedPlanInTransaction( + transaction, bootstrapOperationId, bootstrapRequestId) + : buildRepository.readInstalledPlanForAnchorInTransaction( + transaction, bootstrapOperationId, bootstrapRequestId); CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); requireCurrentState(currentState, intent); Record existing = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.java index 846ce9f334..92ce8c967a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.java @@ -250,6 +250,15 @@ private static void validatePreparedWork(CanonicalGameplayIssuerBootstrapPartiti plan.memberWorks().get(Math.toIntExact(operation.workOrdinal())); var reservation = value.reservation(); var memberRef = value.owner().bindingRef(); + var bindingLifecycle = operation.bindingLifecycle(); + boolean lifecycleHasBinding = + bindingLifecycle + == net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventoryEntry.Lifecycle.ACTIVE + || bindingLifecycle + == net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL; + boolean hasBindingSourceRow = planned.bindingSourceRowOrdinal() != null; if (operation.status() != CanonicalGameplayIssuerBootstrapMemberOperation.Status.PENDING_PHYSICAL_PROOF || !operation.bootstrapOperationId().equals(intent.operationId()) @@ -305,7 +314,8 @@ private static void validatePreparedWork(CanonicalGameplayIssuerBootstrapPartiti != (value.reservation().lifecycle() != net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation .Lifecycle.RELEASED) - || operation.expectedBindingPresent() != (planned.bindingSourceRowOrdinal() != null)) { + || operation.expectedBindingPresent() != lifecycleHasBinding + || (bindingLifecycle == null) != !hasBindingSourceRow) { throw invalid("SQL-issued member differs from the complete frozen preparation tuple"); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionMutationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionMutationRepository.java index d8ab67a121..750905089e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionMutationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionMutationRepository.java @@ -269,6 +269,10 @@ static CanonicalGameplayIssuerPartitionMutation completeInTransaction( || exactReadbackFieldSetBytes.length > 17_825_792) { throw conflict("Issuer partition mutation readback is missing or oversized"); } + Map readbackFields = + CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( + exactReadbackFieldSetBytes); + requireRevisionField(readbackFields, expected.successorRevision()); String readbackDigest = CanonicalGameplayIssuerMemberV2Codec.sha256(exactReadbackFieldSetBytes); Record head = lockCurrentHead(transaction, expected.partitionId()); Record row = diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-retirement.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-retirement.lua index 22400f58ef..dce9a79f69 100644 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-retirement.lua +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-retirement.lua @@ -252,22 +252,21 @@ for _, operation in ipairs(operations) do if operation.bindingMustBePresent == '1' and binding ~= operation.memberBytes then return -1 end end end +for field, value in pairs(baseline) do + if redis.call('HGET', KEYS[1], field) ~= value then return -1 end +end +if actualCapacity > tonumber(plannedPartitionCapacity) + or actualReservations < baselineReservations + or actualReservations > baselineReservations + operationCount + or actualBindings < baselineBindings + or actualBindings > baselineBindings + registeredBindings then return -1 end if revisionBefore == successorRevision then if targetCapacityBefore ~= nil or actualFields[targetBindingRef] == releasedBytes then return -1 end - if #actual / 2 ~= allowedCount then return -1 end return 2 end if revisionBefore ~= expectedRevision - or #actual / 2 ~= allowedCount + 1 or targetCapacityBefore ~= releasedBytes - or actualFields[targetBindingRef] == releasedBytes - or actualCapacity ~= tonumber(plannedPartitionCapacity) - or actualReservations ~= baselineReservations + operationCount - or actualBindings < baselineBindings - or actualBindings > baselineBindings + registeredBindings then return -1 end -for field, value in pairs(baseline) do - if redis.call('HGET', KEYS[1], field) ~= value then return -1 end -end + or actualFields[targetBindingRef] == releasedBytes then return -1 end redis.call('HDEL', KEYS[1], targetCapacityField) redis.call('HSET', KEYS[1], revisionField, successorRevision) return 1 diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-retirement.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-retirement.json index 5ac81b3000..efb9348e9b 100644 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-retirement.json +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-retirement.json @@ -1,7 +1,7 @@ { "scriptId": "game-session.issuer-binding-local-retirement.v1", "resourcePath": "redis/lua/game-session-issuer-binding-local-retirement.lua", - "sha256": "b8d9362de8af6b274ca3bc38d4d700d537d056389c73b2bc86378844ab898a76", + "sha256": "6454e04296ca915004d53175dc70d1b113ed1e0a4bf612ea4b0b6516da51e756", "owner": "game-session-service", "principal": "gamesession_coord_app", "role": "COORDINATION", diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java index de39e0ee4e..23e9a51d13 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java @@ -212,6 +212,16 @@ public CanonicalGameplayAdmissionAbortCompositionFixture( .projectAndRead(localOperation); } + public CanonicalGameplayIssuerInstalledAnchor retryOriginalIssuerBootstrap() { + CanonicalGameplayIssuerInstalledAnchor originalAnchor = localOperation.anchor(); + var partitionOwner = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner( + issuerRedisClient, issuerCatalog, issuerSource); + return new CanonicalGameplayIssuerBootstrapCoverageOwner(dsl, partitionOwner, issuerSource) + .completeInitialBootstrap( + originalAnchor.bootstrapOperationId(), originalAnchor.bootstrapRequestId()); + } + /** * Tuple-consistent controlled upstream target; it does not claim a live initial-admission * producer. diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java index 2cb1d88a1f..2fb5b8438c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java @@ -613,6 +613,105 @@ void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() t assertThat(localRegistrationImage(dsl)).isEqualTo(accountFencedImage); } + @Test + void readsProjectedSubsetWhenTwoSamePartitionRegistrationsPrecedePhysicalProjection() + throws Exception { + DSLContext dsl = schema.dsl(); + establishActualLegacyDisposition(dsl); + var layout = descriptor(); + UUID bootstrapRequestId = UUID.randomUUID(); + var source = sourceCheckpoint(BigInteger.valueOf(7)); + var intent = + new CanonicalGameplayIssuerLayoutBootstrapRepository(dsl) + .beginInitialBootstrapIntent(bootstrapRequestId, layout, source); + migrateRemaining(schema); + + var incarnation = stableIncarnation("subset-readback-anchor"); + var initialState = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + intent.sourceCheckpoint(), incarnation); + AtomicReference + currentState = new AtomicReference<>(initialState); + initialCoverageOwner(dsl, currentState::get) + .completeInitialBootstrap(intent.operationId(), bootstrapRequestId); + + var runtimeTarget = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( + schema.dataSource(), uuid("subset-readback-tenant")); + var targetCandidate = identity("subset-readback-target", runtimeTarget); + var targetRequest = + request( + "subset-readback-target-request", "subset-readback-target-transition", targetCandidate); + var unprojectedCandidate = identity("subset-readback-unprojected"); + var unprojectedRequest = + request( + "subset-readback-unprojected-request", + "subset-readback-unprojected-transition", + unprojectedCandidate); + var operationRepository = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, currentState::get); + var target = operationRepository.beginOrResumeOrdinaryNew(targetRequest); + var unprojected = operationRepository.beginOrResumeOrdinaryNew(unprojectedRequest); + assertThat(target.reservation().partitionId()) + .isEqualTo(unprojected.reservation().partitionId()); + + String targetCapacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + target.reservation().reservationId()); + String unprojectedCapacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + unprojected.reservation().reservationId()); + byte[] partitionKey = + CanonicalGameplayIssuerRedisKeys.forPartition(intent.layoutDescriptor(), BigInteger.ZERO) + .getBytes(StandardCharsets.US_ASCII); + assertThat(hashImage(partitionKey)) + .doesNotContainKey(targetCapacityField) + .doesNotContainKey(unprojectedCapacityField); + + var projectionOwner = projectionOwner(dsl, currentState::get); + var capacityOnly = projectionOwner.projectAndRead(target); + assertThat(capacityOnly.scriptOutcome()).isEqualTo(1L); + var capacityFields = + CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( + capacityOnly.exactReadbackBytes()); + assertThat(capacityFields).containsEntry(targetCapacityField, target.exactMemberValueBytes()); + assertThat(capacityFields).doesNotContainKey(unprojectedCapacityField); + assertThat(capacityFields) + .doesNotContainKey( + new String(unprojectedCandidate.bindingRef().bytes(), StandardCharsets.UTF_8)); + + var provisionalEvidence = + new CanonicalGameplayBindingInventoryRepository(dsl) + .readProvisionalCasEvidence(targetRequest.transitionId()); + var targetLease = + controlledLeaseEvidence( + targetCandidate, + provisionalEvidence.transition().bindingGeneration(), + runtimeTarget.playableTarget()); + var targetDecision = + new CanonicalGameplayAdmissionDecision( + targetRequest.transitionId(), + targetLease, + targetCandidate, + provisionalEvidence.transition().bindingGeneration(), + null, + runtimeTarget.playableTarget()); + new CanonicalGameplayBindingInventoryRepository(dsl) + .markProvisional(provisionalEvidence, targetDecision); + + var addReadback = projectionOwner.projectAndRead(target); + assertThat(addReadback.scriptOutcome()).isEqualTo(2L); + var addedFields = + CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( + addReadback.exactReadbackBytes()); + assertThat(addedFields) + .containsEntry( + new String(targetCandidate.bindingRef().bytes(), StandardCharsets.UTF_8), + target.exactMemberValueBytes()); + assertThat(addedFields).containsEntry(targetCapacityField, target.exactMemberValueBytes()); + assertThat(addedFields).doesNotContainKey(unprojectedCapacityField); + } + @Test void malformedLuaBindingReferenceAndReleaseCountsRefuseWithoutChangingPartition() throws Exception { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java index 86e5a06a63..f0482c2e62 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java @@ -21,8 +21,11 @@ import java.sql.SQLException; import java.time.Duration; import java.util.ArrayList; +import java.util.Base64; import java.util.EnumSet; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; @@ -257,7 +260,7 @@ void installsOnlyAfterEveryPopulatedAndEmptyPartitionHasExactPhysicalProofAndRep } @Test - void installedReplayRefusesMissingPartitionWithoutRebuildingOrAllocatingAnotherGeneration() { + void freshPhysicalVerificationRefusesMissingPartitionWithoutRebuildingOrAllocatingGeneration() { Fixture fixture = fixture(BigInteger.valueOf(4), PARTITION_CAPACITY, 1); var current = currentState(fixture, stableIncarnation("missing-installed")); CanonicalGameplayIssuerInstalledAnchor installed = @@ -271,7 +274,8 @@ void installedReplayRefusesMissingPartitionWithoutRebuildingOrAllocatingAnotherG assertThatThrownBy( () -> owner(fixture, () -> current) - .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId())) + .verifyInstalledPhysicalCoverage( + fixture.intent().operationId(), fixture.requestId())) .isInstanceOf(IllegalStateException.class); assertThat(administratorCommands.type(missingKey)).isEqualTo("none"); assertThat( @@ -290,6 +294,94 @@ void installedReplayRefusesMissingPartitionWithoutRebuildingOrAllocatingAnotherG .isEqualTo(1L); } + @Test + void installedAnchorReadAndRetryUseFrozenPlanAfterOrdinaryNewAdvancesInventoryClock() { + Fixture fixture = fixture(PARTITION_COUNT, PARTITION_CAPACITY, 1); + var current = currentState(fixture, stableIncarnation("ordinary-new-after-anchor")); + CanonicalGameplayIssuerInstalledAnchor installed = + owner(fixture, () -> current) + .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId()); + + var candidate = identity(PARTITION_COUNT, PARTITION_CAPACITY, "post-anchor-ordinary-new"); + new CanonicalGameplayIssuerBindingLocalOperationRepository(fixture.dsl(), () -> current) + .beginOrResumeOrdinaryNew( + new CanonicalGameplayIssuerBindingLocalOperation.Request( + UUID.nameUUIDFromBytes("post-anchor-new-request".getBytes(StandardCharsets.UTF_8)), + UUID.nameUUIDFromBytes( + "post-anchor-new-transition".getBytes(StandardCharsets.UTF_8)), + candidate, + null, + null)); + BigInteger currentInventoryRevision = + fetchRequired( + fixture.dsl(), + "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock" + + " WHERE singleton_id = 1") + .get("inventory_revision", BigDecimal.class) + .toBigIntegerExact(); + assertThat(currentInventoryRevision).isGreaterThan(installed.issuerInventorySnapshotRevision()); + String anchorImageBeforeRead = anchorStorageImage(fixture.dsl()); + String proofImageBeforeRead = proofStorageImage(fixture.dsl()); + String counterImageBeforeRead = coverageCounterImage(fixture.dsl()); + List> physicalImageBeforeRead = physicalPartitionImages(fixture); + + CanonicalGameplayIssuerInstalledAnchor retried = + owner(fixture, () -> current) + .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId()); + + assertThat(retried.exactAnchorBytes()).containsExactly(installed.exactAnchorBytes()); + assertThat(anchorStorageImage(fixture.dsl())).isEqualTo(anchorImageBeforeRead); + assertThat(proofStorageImage(fixture.dsl())).isEqualTo(proofImageBeforeRead); + assertThat(coverageCounterImage(fixture.dsl())).isEqualTo(counterImageBeforeRead); + assertThat(physicalPartitionImages(fixture)).isEqualTo(physicalImageBeforeRead); + assertThat(fixtureProofCount(fixture)).isEqualTo(PARTITION_COUNT.longValueExact()); + } + + @Test + void installedOriginalRetryRejectsWrongTupleAndChangedSourceOrIncarnation() { + Fixture fixture = fixture(PARTITION_COUNT, PARTITION_CAPACITY, 1); + var current = currentState(fixture, stableIncarnation("installed-retry-guards")); + owner(fixture, () -> current) + .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId()); + String anchorImage = anchorStorageImage(fixture.dsl()); + String proofImage = proofStorageImage(fixture.dsl()); + String counterImage = coverageCounterImage(fixture.dsl()); + List> physicalImage = physicalPartitionImages(fixture); + + assertThatThrownBy( + () -> + owner(fixture, () -> current) + .completeInitialBootstrap(UUID.randomUUID(), fixture.requestId())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + owner(fixture, () -> current) + .completeInitialBootstrap(fixture.intent().operationId(), UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class); + + var changedSource = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + checkpointShape(BigInteger.valueOf(8)), current.incarnation()); + assertThatThrownBy( + () -> + owner(fixture, () -> changedSource) + .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId())) + .isInstanceOf(IllegalStateException.class); + var changedIncarnation = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + current.accountCheckpoint(), changedIncarnation(current.incarnation())); + assertThatThrownBy( + () -> + owner(fixture, () -> changedIncarnation) + .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId())) + .isInstanceOf(IllegalStateException.class); + + assertThat(anchorStorageImage(fixture.dsl())).isEqualTo(anchorImage); + assertThat(proofStorageImage(fixture.dsl())).isEqualTo(proofImage); + assertThat(coverageCounterImage(fixture.dsl())).isEqualTo(counterImage); + assertThat(physicalPartitionImages(fixture)).isEqualTo(physicalImage); + } + @Test void movedAccountCheckpointOrStorageIncarnationLeavesNoCoverageGenerationOrPointer() { Fixture sourceFixture = fixture(PARTITION_COUNT, PARTITION_CAPACITY, 1); @@ -770,6 +862,35 @@ private static String proofStorageImage(DSLContext dsl) { .get("image", String.class); } + private static String coverageCounterImage(DSLContext dsl) { + Record counter = + fetchRequired( + dsl, + "SELECT last_issued_coverage_generation, counter_version FROM " + + "game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", + ISSUER); + return counter.get("last_issued_coverage_generation", BigDecimal.class).toPlainString() + + ":" + + counter.get("counter_version", Long.class); + } + + private List> physicalPartitionImages(Fixture fixture) { + List> images = new ArrayList<>(); + for (BigInteger partitionId = BigInteger.ZERO; + partitionId.compareTo(fixture.intent().layoutDescriptor().partitionCount()) < 0; + partitionId = partitionId.add(BigInteger.ONE)) { + Map raw = administratorCommands.hgetall(key(fixture, partitionId)); + Map image = new LinkedHashMap<>(); + raw.forEach( + (field, value) -> + image.put( + Base64.getEncoder().encodeToString(field), + Base64.getEncoder().encodeToString(value))); + images.add(Map.copyOf(image)); + } + return List.copyOf(images); + } + private static long fixtureProofCount(Fixture fixture) { return fetchRequired( fixture.dsl(), diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java index 84fdd821ee..b30a1b479e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java @@ -35,11 +35,13 @@ import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; @@ -217,6 +219,44 @@ void positivelyPreparedEmptyPartitionBuildsOnlyItsCommonMetadata() { assertThat(statusesRemainPending(fixture.dsl())).isTrue(); } + @Test + void candidatePreparedSourceRowRetainsCapacityWithoutCreatingPhysicalBinding() { + Fixture fixture = fixtureWithPreparedCandidate(); + CanonicalGameplayIssuerBootstrapPartitionWork work = + partitionWork(fixture, fixture.partitionId()); + var candidateOperation = + work.memberOperations().stream() + .filter( + operation -> + operation.bindingLifecycle() + == net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventoryEntry.Lifecycle.CANDIDATE_PREPARED) + .findFirst() + .orElseThrow(); + + assertThat(candidateOperation.expectedBindingPresent()).isFalse(); + assertThat(candidateOperation.countsTowardCapacity()).isTrue(); + assertThat(candidateOperation.expectedMemberValue().reservation().lifecycle()) + .isEqualTo(CanonicalIssuerPartitionReservation.Lifecycle.RESERVED); + var readback = owner(work, currentState(fixture, work)).buildAndRead(work); + + assertThat(readback.physicalPartitionReservationCount()).isEqualTo(2); + assertThat(readback.physicalBindingCount()).isEqualTo(1); + assertThat(readback.physicalCountedCapacityCount()).isEqualTo(2); + assertThat(readback.plannedAggregateCapacityCount()).isEqualTo(BigInteger.valueOf(2)); + byte[] key = key(fixture, fixture.partitionId()); + byte[] bindingRef = candidateOperation.expectedMemberValue().owner().bindingRef().bytes(); + byte[] reservationField = + ascii( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + candidateOperation.expectedMemberValue().reservation().reservationId())); + assertThat(administratorCommands.hget(key, bindingRef)).isNull(); + assertThat(administratorCommands.hget(key, reservationField)) + .containsExactly(candidateOperation.exactMemberValueBytes()); + assertThat(administratorCommands.hlen(key)).isEqualTo(5L); + assertThat(statusesRemainPending(fixture.dsl())).isTrue(); + } + @Test void sameBindingWithDifferentAnchorReservationLifecycleOrLocalOperationIsAConflict() { Fixture fixture = fixture(false); @@ -522,6 +562,76 @@ private Fixture fixture(boolean includeReleasedReservation, int activeBindingCou return new Fixture(testSchema, active, intent, requestId, source, partitionId); } + private Fixture fixtureWithPreparedCandidate() { + TestSchema testSchema = newTestSchemaAtVersion("gs_issuer_prepared_physical_", "1030"); + schemas.add(testSchema); + establishActualLegacyDisposition(testSchema.dsl()); + CanonicalGameplayBindingIdentity active = + CanonicalGameplayBindingInventoryRepositoryIntegrationTest.identity( + UUID.randomUUID().toString()); + CanonicalGameplayBindingInventoryRepositoryIntegrationTest.seedActiveSource( + testSchema.dsl(), active); + BigInteger partitionId = active.bindingRef().partitionId(PARTITION_COUNT); + CanonicalGameplayBindingIdentity candidate = preparedCandidateIdentity(partitionId); + var reservationEvidence = + new CanonicalIssuerReservationFenceEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + BigInteger.valueOf(13), + BigInteger.valueOf(17), + BigInteger.valueOf(7)); + new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()) + .prepare( + new CanonicalGameplayBindingTransitionRequest( + UUID.randomUUID(), UUID.randomUUID(), candidate, reservationEvidence, null, null)); + + UUID requestId = UUID.randomUUID(); + var source = sourceCheckpoint(BigInteger.valueOf(7)); + var intent = + new CanonicalGameplayIssuerLayoutBootstrapRepository(testSchema.dsl()) + .beginInitialBootstrapIntent(requestId, descriptor(), source); + migrateRemaining(testSchema); + var plan = + new CanonicalGameplayIssuerPartitionBuildRepository(testSchema.dsl()) + .prepareInitialBuildPlan(intent.operationId(), requestId); + assertThat(plan.state()).isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED); + return new Fixture(testSchema, active, intent, requestId, source, partitionId); + } + + private static CanonicalGameplayBindingIdentity preparedCandidateIdentity( + BigInteger targetPartition) { + for (int candidate = 0; candidate < 10_000; candidate++) { + String seed = "prepared-physical-candidate-" + candidate; + CanonicalGameplayBindingIdentity identity = + new CanonicalGameplayBindingIdentity( + namedUuid(seed + "-account"), + namedUuid(seed + "-tenant"), + namedUuid(seed + "-namespace"), + namedUuid(seed + "-character"), + "SHARED", + namedUuid(seed + "-game"), + 90_000L + candidate, + namedUuid(seed + "-session").toString(), + namedUuid(seed + "-region"), + BigInteger.valueOf(12), + ISSUER, + BigInteger.valueOf(7), + LAYOUT_VERSION, + PARTITION_COUNT, + PARTITION_CAPACITY); + if (identity.bindingRef().partitionId(PARTITION_COUNT).equals(targetPartition)) { + return identity; + } + } + throw new IllegalStateException( + "Could not create a prepared candidate in the target partition"); + } + + private static UUID namedUuid(String value) { + return UUID.nameUUIDFromBytes(value.getBytes(StandardCharsets.UTF_8)); + } + private CanonicalGameplayIssuerBootstrapPartitionWork partitionWork( Fixture fixture, BigInteger partitionId) { return new CanonicalGameplayIssuerBootstrapMemberOperationRepository(fixture.dsl()) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java index e78c383521..faebb5c25c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java @@ -23,10 +23,13 @@ import java.time.Duration; import java.util.Arrays; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.UUID; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution; @@ -119,18 +122,143 @@ void retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound() throws Exc fixture.publishOriginalWithControlledAccountLease(); var originalAbort = fixture.recordOriginalAccountAbort(); assertThat(originalAbort.isAccountAborted()).isTrue(); + + byte[] beforePrematureRetirement = physicalFieldSet(partitionKey); + String historyBeforePrematureRetirement = durableHistoryImage(fixture.dsl(), NIL_UUID); + String headBeforePrematureRetirement = + partitionHeadImage(fixture.dsl(), fixture.originalPartitionId()); + String inventoryClockBeforePrematureRetirement = + fixture + .dsl() + .fetchSingle( + "SELECT to_jsonb(clock)::text FROM" + + " game_session_canonical_binding_inventory_clock clock" + + " WHERE singleton_id = 1") + .get(0, String.class); + long releasesBeforePrematureRetirement = + fixture + .dsl() + .fetchSingle( + "SELECT count(*) FROM" + + " game_session_canonical_issuer_binding_local_release_operation") + .get(0, Long.class); + long mutationsBeforePrematureRetirement = partitionMutationCount(fixture.dsl()); + assertThatThrownBy(() -> fixture.prepareIssuerRetirement(fixture.transitionId())) + .isInstanceOf(IllegalStateException.class); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforePrematureRetirement); + assertThat(durableHistoryImage(fixture.dsl(), NIL_UUID)) + .isEqualTo(historyBeforePrematureRetirement); + assertThat(partitionHeadImage(fixture.dsl(), fixture.originalPartitionId())) + .isEqualTo(headBeforePrematureRetirement); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT to_jsonb(clock)::text FROM" + + " game_session_canonical_binding_inventory_clock clock" + + " WHERE singleton_id = 1") + .get(0, String.class)) + .isEqualTo(inventoryClockBeforePrematureRetirement); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT count(*) FROM" + + " game_session_canonical_issuer_binding_local_release_operation") + .get(0, Long.class)) + .isEqualTo(releasesBeforePrematureRetirement); + assertThat(partitionMutationCount(fixture.dsl())) + .isEqualTo(mutationsBeforePrematureRetirement); + assertThat(retirementCount(fixture.dsl())).isZero(); + var originalRelease = completeReleaseAfterLostReply(fixture, null); String newerSeed = lifetimeSeed(2); UUID newerOperationId = fixture.prepareOtherControllerNew(newerSeed); + String neverProjectedSeed = "same-partition-never-projected"; + UUID neverProjectedOperationId = fixture.prepareOtherControllerNew(neverProjectedSeed); + var neverProjectedOperation = fixture.otherOperation(neverProjectedSeed); + var newerOperation = fixture.otherOperation(newerSeed); + assertThat(neverProjectedOperationId).isEqualTo(neverProjectedOperation.operationId()); + assertThat(neverProjectedOperation.reservation().partitionId()) + .isEqualTo(newerOperation.reservation().partitionId()); + String newerCapacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + newerOperation.reservation().reservationId()); + String neverProjectedCapacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + neverProjectedOperation.reservation().reservationId()); + assertThat(decodeFields(physicalFieldSet(partitionKey))) + .doesNotContainKey(newerCapacityField) + .doesNotContainKey(neverProjectedCapacityField); var pendingAdd = fixture.prepareOtherAddMutation(newerSeed); + byte[] currentRevisionFieldValue = + pendingAdd + .physicalMutation() + .expectedRevision() + .toString() + .getBytes(StandardCharsets.US_ASCII); + Map staleReadbackFields = + new HashMap<>(decodeFields(physicalFieldSet(partitionKey))); + assertThat( + staleReadbackFields.get( + CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD)) + .containsExactly(currentRevisionFieldValue); + byte[] staleReadback = + CanonicalGameplayIssuerBootstrapCoverageRepository.encodeFieldSet(staleReadbackFields); + String mutationCustodyBeforeStaleReadback = + pendingMutationCustodyImage( + fixture.dsl(), + pendingAdd.physicalMutation(), + "game_session_canonical_issuer_binding_local_operation", + "operation_id", + pendingAdd.physicalMutation().ownerOperationId()); + byte[] partitionBeforeStaleReadback = physicalFieldSet(partitionKey); + assertThatThrownBy( + () -> + fixture + .dsl() + .transactionResult( + configuration -> + CanonicalGameplayIssuerPartitionMutationRepository + .completeInTransaction( + org.jooq.impl.DSL.using(configuration), + pendingAdd.physicalMutation(), + staleReadback))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact current physical mutation revision"); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(partitionBeforeStaleReadback); + assertThat( + pendingMutationCustodyImage( + fixture.dsl(), + pendingAdd.physicalMutation(), + "game_session_canonical_issuer_binding_local_operation", + "operation_id", + pendingAdd.physicalMutation().ownerOperationId())) + .isEqualTo(mutationCustodyBeforeStaleReadback); + LuaInvocation staleAddInvocation = addInvocation(fixture, pendingAdd); var addReadback = fixture.projectOtherControllerNew(newerSeed); assertThat(addReadback.scriptOutcome()).isEqualTo(1L); + var addFields = decodeFields(addReadback.exactReadbackBytes()); + assertThat(addFields) + .containsEntry(newerCapacityField, newerOperation.exactMemberValueBytes()); + assertThat(addFields) + .doesNotContainKey( + new String( + newerOperation.memberValue().owner().bindingRef().bytes(), + StandardCharsets.UTF_8)); + assertThat(addFields).doesNotContainKey(neverProjectedCapacityField); + assertThat(addFields) + .doesNotContainKey( + new String( + neverProjectedOperation.memberValue().owner().bindingRef().bytes(), + StandardCharsets.UTF_8)); assertThat(fixture.retryOtherControllerNew(newerSeed)).isEqualTo(newerOperationId); byte[] afterAdd = physicalFieldSet(partitionKey); assertThat(fixture.projectOtherControllerNew(newerSeed).scriptOutcome()).isEqualTo(3L); assertThat(physicalFieldSet(partitionKey)).isEqualTo(afterAdd); + assertOuterBootstrapRetryIsReadOnly(fixture, partitionKey); fixture.publishOtherControllerNew(newerSeed); assertThat(fixture.recordOtherAccountAbort(newerSeed).isAccountAborted()).isTrue(); @@ -140,6 +268,9 @@ void retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound() throws Exc var newerRelease = fixture.completeIssuerRelease(pendingRelease, releaseReadback); assertThat(newerRelease.status()) .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); + assertOuterBootstrapRetryIsReadOnly(fixture, partitionKey); + assertThat(decodeFields(physicalFieldSet(partitionKey))) + .doesNotContainKey(neverProjectedCapacityField); byte[] beforeReleaseRetry = physicalFieldSet(partitionKey); var completedReleaseRetry = fixture.prepareIssuerRelease(newerSeed); var releaseRetryReadback = fixture.projectIssuerRelease(completedReleaseRetry); @@ -212,9 +343,6 @@ void retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound() throws Exc assertThat(durableHistoryImage(fixture.dsl(), NIL_UUID)) .isEqualTo(historyBeforeOriginalRetirement); assertThat(capacityFieldCount(afterUncommittedRetirement)).isEqualTo(1L); - String newerCapacityField = - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( - newerRelease.releasedMemberValue().reservation().reservationId()); assertThat(decodeFields(afterUncommittedRetirement)) .containsEntry(newerCapacityField, newerRelease.exactReleasedMemberValueBytes()); @@ -227,6 +355,7 @@ void retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound() throws Exc assertThat(completedOldestRetryProof.exactAbsenceReadbackFieldSetBytes()) .isEqualTo(beforeCompletedRetirementRetry); assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeCompletedRetirementRetry); + assertOuterBootstrapRetryIsReadOnly(fixture, partitionKey); assertStaleLuaRejectedWithoutWrites(staleAddInvocation, partitionKey); assertStaleLuaRejectedWithoutWrites(staleReleaseInvocation, partitionKey); @@ -239,6 +368,7 @@ void retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound() throws Exc assertThat(completedNewerRetirement.scriptOutcome()).isEqualTo(1L); assertThat(completedNewerRetirement.exactAbsenceReadbackFieldSetBytes()) .isEqualTo(afterNewerRetirement); + assertThat(decodeFields(afterNewerRetirement)).doesNotContainKey(neverProjectedCapacityField); assertRetirementFieldDelta( beforeNewerRetirement, afterNewerRetirement, pendingNewerRetirement); byte[] beforeNewerRetirementRetry = physicalFieldSet(partitionKey); @@ -279,7 +409,7 @@ void retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound() throws Exc assertThat(decodeFields(afterCycleRetirement).size()).isEqualTo(baselineFieldCount + 2); } - assertThat(localOperationCount(fixture.dsl())).isEqualTo(256L); + assertThat(localOperationCount(fixture.dsl())).isEqualTo(257L); assertThat(releaseCount(fixture.dsl(), "RELEASED")).isEqualTo(256L); assertThat(releaseProofCount(fixture.dsl())).isEqualTo(256L); assertThat(retirementCount(fixture.dsl())).isEqualTo(256L); @@ -337,7 +467,7 @@ void retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound() throws Exc .isEqualTo(beforeFinalRetirementRetry); assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeFinalRetirementRetry); - assertThat(localOperationCount(fixture.dsl())).isEqualTo(257L); + assertThat(localOperationCount(fixture.dsl())).isEqualTo(258L); assertThat(releaseCount(fixture.dsl(), "RELEASED")).isEqualTo(257L); assertThat(releaseProofCount(fixture.dsl())).isEqualTo(257L); assertThat(retirementCount(fixture.dsl())).isEqualTo(257L); @@ -349,6 +479,156 @@ void retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound() throws Exc } } + @Test + void unrelatedAccountNewAndOriginalIssuerCleanupSurviveAccountControlAdvance() { + try (var fixture = newFixture(BigInteger.valueOf(11), BigInteger.ONE, 0)) { + byte[] partitionKey = fixture.issuerPartitionKey(); + fixture.publishOriginalWithControlledAccountLease(); + var abort = fixture.recordOriginalAccountAbort(); + assertThat(abort.isAccountAborted()).isTrue(); + + String staleAccountASeed = "account-a-stale-add-after-control-advance"; + fixture.prepareOtherControllerNew(staleAccountASeed); + CanonicalGameplayIssuerMemberV2Value originalMember = + CanonicalGameplayIssuerMemberV2Codec.decode(fixture.originalMemberValueBytes()); + CanonicalGameplayBindingIdentity accountA = originalMember.owner(); + + var intent = + new CanonicalGameplayAccountAdmissionBarrierRepository(fixture.dsl()) + .beginFenceIntent(accountA.accountId(), uuid("account-a-control-advance")); + assertThat(intent).isNotNull(); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT state FROM game_session_canonical_account_coverage_control" + + " WHERE account_id = ?", + accountA.accountId()) + .get(0, String.class)) + .isEqualTo("ACQUISITION_INTENT"); + + byte[] beforeStaleAdd = physicalFieldSet(partitionKey); + long mutationsBeforeStaleAdd = partitionMutationCount(fixture.dsl()); + assertThatThrownBy(() -> fixture.projectOtherControllerNew(staleAccountASeed)) + .isInstanceOf(IllegalStateException.class); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeStaleAdd); + assertThat(partitionMutationCount(fixture.dsl())).isEqualTo(mutationsBeforeStaleAdd); + + CanonicalGameplayBindingIdentity accountB = + otherAccountInPartition(accountA, fixture.originalPartitionId()); + var currentIssuerState = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + originalMember.sourceCheckpoint(), originalMember.incarnation()); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + issuerStateSource = () -> currentIssuerState; + var accountBOperation = + new CanonicalGameplayIssuerBindingLocalOperationRepository( + fixture.dsl(), issuerStateSource) + .beginOrResumeOrdinaryNew( + new CanonicalGameplayIssuerBindingLocalOperation.Request( + UUID.randomUUID(), UUID.randomUUID(), accountB, null, null)); + var localProjection = + new CanonicalGameplayIssuerBindingLocalProjectionRepository( + fixture.dsl(), issuerStateSource); + var accountBOwner = + new CanonicalGameplayIssuerBindingLocalRedisOwner( + issuerOwner, + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayIssuerBindingLocalRedisScriptContribution())), + localProjection, + issuerStateSource); + var accountBAdd = accountBOwner.projectAndRead(accountBOperation); + assertThat(accountBAdd.scriptOutcome()).isEqualTo(1L); + + String accountBCapacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + accountBOperation.reservation().reservationId()); + String accountBBindingField = + new String( + accountBOperation.memberValue().owner().bindingRef().bytes(), StandardCharsets.UTF_8); + var accountBFields = decodeFields(physicalFieldSet(partitionKey)); + assertThat(accountBFields) + .containsEntry(accountBCapacityField, accountBOperation.exactMemberValueBytes()) + .doesNotContainKey(accountBBindingField); + assertThat(localOperationCount(fixture.dsl())).isEqualTo(3L); + + var pendingRelease = fixture.prepareIssuerRelease(); + var releaseReadback = fixture.projectIssuerRelease(pendingRelease); + var release = fixture.completeIssuerRelease(pendingRelease, releaseReadback); + assertThat(release.status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); + var releaseRetry = fixture.prepareIssuerRelease(); + assertThat(releaseRetry.operationId()).isEqualTo(release.operationId()); + assertThat(fixture.projectIssuerRelease(releaseRetry).exactPhysicalFieldSetBytes()) + .isEqualTo(release.exactPhysicalReadbackFieldSetBytes()); + + var pendingRetirement = fixture.prepareIssuerRetirement(fixture.transitionId()); + byte[] releasedCapacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + release.releasedMemberValue().reservation().reservationId()) + .getBytes(StandardCharsets.US_ASCII); + byte[] beforeConflictingCapacity = physicalFieldSet(partitionKey); + administratorCommands.hset( + partitionKey, releasedCapacityField, accountBOperation.exactMemberValueBytes()); + byte[] changedCapacity = physicalFieldSet(partitionKey); + assertThatThrownBy(() -> fixture.retireIssuerCapacity(pendingRetirement)) + .isInstanceOf(IllegalStateException.class); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(changedCapacity); + administratorCommands.hset( + partitionKey, releasedCapacityField, release.exactReleasedMemberValueBytes()); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeConflictingCapacity); + + var retired = fixture.retireIssuerCapacity(pendingRetirement); + assertThat(retired.scriptOutcome()).isEqualTo(1L); + var afterRetirement = decodeFields(physicalFieldSet(partitionKey)); + assertThat(afterRetirement) + .containsEntry(accountBCapacityField, accountBOperation.exactMemberValueBytes()) + .doesNotContainKey(accountBBindingField) + .doesNotContainKey(new String(releasedCapacityField, StandardCharsets.US_ASCII)); + assertThat(capacityFieldCount(physicalFieldSet(partitionKey))).isEqualTo(1L); + assertThat(localOperationCount(fixture.dsl())).isEqualTo(3L); + + var retirementRetry = fixture.prepareIssuerRetirement(fixture.transitionId()); + assertThat(retirementRetry.status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalRetirementOperation.Status.RETIRED); + byte[] beforeRetirementRetry = physicalFieldSet(partitionKey); + assertThat(fixture.retireIssuerCapacity(retirementRetry).scriptOutcome()).isEqualTo(2L); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeRetirementRetry); + } + } + + @Test + void addCurrentnessRereadKeepsTheTargetAccountControlFenceWithoutPreparingAnotherMutation() { + try (var fixture = newFixture(BigInteger.valueOf(12), BigInteger.ONE, 0)) { + String seed = "add-currentness-account-control-reread"; + fixture.prepareOtherControllerNew(seed); + var preparedAdd = fixture.prepareOtherAddMutation(seed); + byte[] partitionKey = fixture.issuerPartitionKey(); + byte[] fieldsBeforeReread = physicalFieldSet(partitionKey); + long mutationsBeforeReread = partitionMutationCount(fixture.dsl()); + CanonicalGameplayIssuerMemberV2Value originalMember = + CanonicalGameplayIssuerMemberV2Codec.decode(fixture.originalMemberValueBytes()); + var currentIssuerState = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + originalMember.sourceCheckpoint(), originalMember.incarnation()); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + issuerStateSource = () -> currentIssuerState; + + new CanonicalGameplayAccountAdmissionBarrierRepository(fixture.dsl()) + .beginFenceIntent( + originalMember.owner().accountId(), uuid("add-currentness-account-fence")); + + assertThatThrownBy( + () -> + new CanonicalGameplayIssuerBindingLocalProjectionRepository( + fixture.dsl(), issuerStateSource) + .requireStillCurrent(preparedAdd)) + .isInstanceOf(IllegalStateException.class); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(fieldsBeforeReread); + assertThat(partitionMutationCount(fixture.dsl())).isEqualTo(mutationsBeforeReread); + } + } + @Test void refusesProjectionBeyondTheCurrentLocalEntryBoundWithoutWrites() { try (var fixture = @@ -644,6 +924,34 @@ private static Candidate controlledCandidate( partitionCapacity); } + private static CanonicalGameplayBindingIdentity otherAccountInPartition( + CanonicalGameplayBindingIdentity template, BigInteger partitionId) { + CanonicalGameplayBindingIdentity candidate; + do { + candidate = + new CanonicalGameplayBindingIdentity( + UUID.randomUUID(), + template.tenantId(), + template.playableStateNamespaceId(), + UUID.randomUUID(), + template.playableStateScope(), + template.gameInstanceId(), + template.runtimeGameInstanceId(), + UUID.randomUUID().toString(), + template.regionId(), + template.regionEpoch(), + template.issuerId(), + template.issuerAuthGeneration(), + template.issuerIndexLayoutVersion(), + template.issuerIndexPartitionCount(), + template.issuerIndexPartitionCapacity()); + } while (!candidate + .bindingRef() + .partitionId(template.issuerIndexPartitionCount()) + .equals(partitionId)); + return candidate; + } + private void assertMissingRevisionRefusal( CanonicalGameplayAdmissionAbortCompositionFixture fixture, byte[] partitionKey, @@ -731,6 +1039,43 @@ private static String partitionHeadImage(DSLContext dsl, BigInteger partitionId) .get(0, String.class); } + private void assertOuterBootstrapRetryIsReadOnly( + CanonicalGameplayAdmissionAbortCompositionFixture fixture, byte[] partitionKey) { + byte[] physicalBefore = physicalFieldSet(partitionKey); + String revisionBefore = partitionHeadImage(fixture.dsl(), fixture.originalPartitionId()); + String anchorAndProofsBefore = anchorAndPartitionProofImage(fixture.dsl()); + byte[] originalAnchorBytes = + fixture + .dsl() + .fetchSingle( + "SELECT exact_anchor_bytes FROM" + + " game_session_canonical_issuer_binding_local_operation" + + " WHERE operation_id = ?", + fixture.originalOperationId()) + .get(0, byte[].class); + + var retriedAnchor = fixture.retryOriginalIssuerBootstrap(); + + assertThat(retriedAnchor.exactAnchorBytes()).containsExactly(originalAnchorBytes); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(physicalBefore); + assertThat(partitionHeadImage(fixture.dsl(), fixture.originalPartitionId())) + .isEqualTo(revisionBefore); + assertThat(anchorAndPartitionProofImage(fixture.dsl())).isEqualTo(anchorAndProofsBefore); + } + + private static String anchorAndPartitionProofImage(DSLContext dsl) { + return dsl.fetchSingle( + "SELECT jsonb_build_object(" + + "'anchors', COALESCE((SELECT jsonb_agg(to_jsonb(anchor)" + + " ORDER BY anchor.issuer_id) FROM" + + " game_session_canonical_issuer_installed_anchor anchor), '[]'::jsonb)," + + "'partitionProofs', COALESCE((SELECT jsonb_agg(to_jsonb(proof)" + + " ORDER BY proof.issuer_id, proof.partition_id) FROM" + + " game_session_canonical_issuer_bootstrap_partition_proof proof), '[]'::jsonb)" + + ")::text") + .get(0, String.class); + } + private static UUID insertUnaccountedCurrentReservation( CanonicalGameplayAdmissionAbortCompositionFixture fixture, String sourceSeed, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java index 52c3c8c416..0f6b2a0aac 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java @@ -11,6 +11,8 @@ import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; import io.grpc.Status; import io.grpc.stub.StreamObserver; import java.util.Map; @@ -23,12 +25,142 @@ import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** * Controlled parser, repository, codec and callback failure tests; native owner composition is a * separate PostgreSQL test. */ class CanonicalGameplayAdmissionDecisionReadGrpcServiceTest { + @Test + void deniesNonAccountCallerBeforeParsingOrRepositoryRead() { + var repository = mock(CanonicalGameplayBindingInventoryRepository.class); + var guard = mock(CanonicalGameplayAdmissionDecisionReadWorkloadGuard.class); + var observer = observer(); + var request = GetCanonicalGameplayAdmissionDecisionRequest.getDefaultInstance(); + doThrow(Status.PERMISSION_DENIED.asRuntimeException()).when(guard).requireAccountCaller(); + try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { + new CanonicalGameplayAdmissionDecisionReadGrpcService(repository, guard, "test") + .getCanonicalGameplayAdmissionDecision(request, observer); + codec.verify( + () -> CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest(request), never()); + } + + assertFailure(observer, Status.Code.PERMISSION_DENIED, null); + verify(guard).requireAccountCaller(); + verifyNoInteractions(repository); + } + + @Test + void rejectsAmbientTransactionBeforeParsingOrRepositoryRead() { + var repository = mock(CanonicalGameplayBindingInventoryRepository.class); + var guard = mock(CanonicalGameplayAdmissionDecisionReadWorkloadGuard.class); + var observer = observer(); + var request = GetCanonicalGameplayAdmissionDecisionRequest.getDefaultInstance(); + try { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { + new CanonicalGameplayAdmissionDecisionReadGrpcService(repository, guard, "test") + .getCanonicalGameplayAdmissionDecision(request, observer); + codec.verify( + () -> CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest(request), never()); + } + assertFailure(observer, Status.Code.FAILED_PRECONDITION, null); + verify(guard).requireAccountCaller(); + verifyNoInteractions(repository); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + @Test + void rejectsSynchronizationWithoutTransactionBeforeParsingOrRepositoryRead() { + var repository = mock(CanonicalGameplayBindingInventoryRepository.class); + var guard = mock(CanonicalGameplayAdmissionDecisionReadWorkloadGuard.class); + var observer = observer(); + var request = GetCanonicalGameplayAdmissionDecisionRequest.getDefaultInstance(); + try { + TransactionSynchronizationManager.initSynchronization(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { + new CanonicalGameplayAdmissionDecisionReadGrpcService(repository, guard, "test") + .getCanonicalGameplayAdmissionDecision(request, observer); + codec.verify( + () -> CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest(request), never()); + } + assertFailure(observer, Status.Code.FAILED_PRECONDITION, null); + verify(guard).requireAccountCaller(); + verifyNoInteractions(repository); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + @Test + void invalidAndOversizedRequestsFailBeforeRepositoryRead() { + var invalid = GetCanonicalGameplayAdmissionDecisionRequest.getDefaultInstance(); + var oversized = + GetCanonicalGameplayAdmissionDecisionRequest.newBuilder() + .mergeUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 100, + UnknownFieldSet.Field.newBuilder() + .addLengthDelimited( + ByteString.copyFrom( + new byte + [CanonicalGameplayAdmissionDecisionReadGrpcCodec + .MAX_REQUEST_WIRE_BYTES + + 1])) + .build()) + .build()) + .build(); + + for (var request : new GetCanonicalGameplayAdmissionDecisionRequest[] {invalid, oversized}) { + var repository = mock(CanonicalGameplayBindingInventoryRepository.class); + var guard = mock(CanonicalGameplayAdmissionDecisionReadWorkloadGuard.class); + var observer = observer(); + new CanonicalGameplayAdmissionDecisionReadGrpcService(repository, guard, "test") + .getCanonicalGameplayAdmissionDecision(request, observer); + + assertFailure(observer, Status.Code.INVALID_ARGUMENT, null); + verify(guard).requireAccountCaller(); + verifyNoInteractions(repository); + } + } + + @Test + void rejectsMismatchedLeaseKindNamespaceAndCallerBeforeRepositoryRead() { + var cases = + new Runnable[] { + () -> { + var fixture = validReadFixture(); + when(fixture.selector().expectedLeaseEvidence().leaseKind()) + .thenReturn( + net.firedevops.firemud.common.account.admission + .AccountGameplayAdmissionLeaseEvidence.LeaseKind.RESUME); + assertDeniedLease(fixture); + }, + () -> { + var fixture = validReadFixture(); + when(fixture.selector().expectedLeaseEvidence().carrier()) + .thenReturn(Map.of("targetNamespace", "other", "callerWorkload", accountPeer())); + assertDeniedLease(fixture); + }, + () -> { + var fixture = validReadFixture(); + when(fixture.selector().expectedLeaseEvidence().carrier()) + .thenReturn(Map.of("targetNamespace", "test", "callerWorkload", "other")); + assertDeniedLease(fixture); + } + }; + + for (var testCase : cases) testCase.run(); + } + @Test void unexpectedRepositoryFailureTerminatesOnceWithSanitizedInternal() { var fixture = validReadFixture(); @@ -245,6 +377,25 @@ private static ReadFixture validReadFixture() { return new ReadFixture(repository, guard, observer, request, selector, decision); } + private static void assertDeniedLease(ReadFixture fixture) { + try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { + codec + .when( + () -> CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest(fixture.request())) + .thenReturn(fixture.selector()); + new CanonicalGameplayAdmissionDecisionReadGrpcService( + fixture.repository(), fixture.guard(), "test") + .getCanonicalGameplayAdmissionDecision(fixture.request(), fixture.observer()); + } + assertFailure(fixture.observer(), Status.Code.PERMISSION_DENIED, null); + verify(fixture.guard()).requireAccountCaller(); + verifyNoInteractions(fixture.repository()); + } + + private static String accountPeer() { + return "spiffe://firemud/ns/test/sa/game-session-service"; + } + private static void assertFailure( StreamObserver observer, Status.Code expectedCode, From 4ce0204ff4691c2fff682cd3fcf788e6a6b6c335 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 06:41:53 +1300 Subject: [PATCH 18/34] fix(gameplay): retain acknowledged abort cleanup across Account advances --- .github/workflows/ci.yml | 2 +- .../player-access-and-session.md | 4 +- ...nitiveAbortCompositionIntegrationTest.java | 175 +++++++++++++++- ...calGameplayBindingInventoryRepository.java | 25 ++- ...lGameplayIssuerBootstrapCoverageOwner.java | 3 +- ...playIssuerBootstrapCoverageRepository.java | 3 +- ...uerBootstrapMemberOperationRepository.java | 3 +- ...layIssuerBootstrapPartitionRedisOwner.java | 5 +- ...irst_new_abort_cleanup_account_control.sql | 196 ++++++++++++++++++ ...eplayAdmissionAbortCompositionFixture.java | 173 ++++++++++++++-- ...IssuerBootstrapAmbientTransactionTest.java | 126 +++++++++++ 11 files changed, 684 insertions(+), 31 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1038.1__retained_first_new_abort_cleanup_account_control.sql create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapAmbientTransactionTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a8bd82ca49..59d3918f98 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1052,7 +1052,7 @@ jobs: permissions: contents: read id-token: write - # Account and Game Session need 40 minutes for full checks, packaging and post-job cleanup; World and Game Design retain 30 minutes. + # Account and Game Session need 60 minutes for full checks including PostgreSQL/Redis issuer suites, packaging and post-job cleanup; World and Game Design retain 30 minutes. timeout-minutes: ${{ (matrix.module == 'account-service' || matrix.module == 'game-session-service') && 60 || (matrix.module == 'world-management-service' || matrix.module == 'game-design-service') && 30 || 20 }} strategy: fail-fast: false diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 7d989f2360..14a20cd151 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -34,7 +34,9 @@ R625 freshly passes the combined owner gate: 11 unit cases, 35 issuer PostgreSQL The expanded #3310 correction implements the [original-operation physical retirement contract](../../architecture/system-architecture-redis.md#original-operation-issuer-physical-retirement) under the existing release/local-mutation owner. R675 freshly passes 77 cases: 21 units, 49 Game Session PostgreSQL/Redis cases and seven actual Account–Game Session cases, with zero failures, errors or skips; enabled affected static analysis, formatting and 547-file documentation checks pass. Physical proof includes 257 actual Game Session releases and retirements with complete immutable SQL history, original lost-reply/restart recovery and completed retry, stale ADD and release rejection, pending same-partition exclusion, missing-revision and foreign/currentness refusal, preservation of newer fields, a 256-readable/257-refused current local-entry bound, and actual 514-field release/readback/persistence/reload. The wide case uses 250 owner-produced provisional bootstrap rows and a small post-baseline cohort; the turnover case retires each terminal field rather than accumulating 256 terminal fields. The physical mutation revision is a separate positively installed UUID domain, and historical unfenced bootstrap audit rows remain retained without qualifying current fenced coverage. The seven Account composition cases separately retain their real current-caller, lease, abort and issuer-release attribution. The new turnover cases use controlled upstream Account lease/abort, issuer checkpoint, launch/World and stable-incarnation inputs; they do not prove those producers or production authority. R672 remains a failed aggregate, including its oversized test-only history image, current-readback omission and retirement Lua shape failure; R677 separately passes the corrected 46-case preflight before R675. Operational custody, registration, admitting acknowledgements, barrier OPEN, final CAS and playable admission remain unproved. -The subsequent correction separates immutable Account provenance from current ADD authority through the original abort, release and retirement readers, and makes the full completed-original bootstrap retry return its retained installation result without replaying baseline writes. Current target ADD guards, complete inventory accounting and mandatory physical-field checks remain required. Across R687, R688 and R689, all 88 selected case methods have current qualified execution: 26 units, 55 Game Session PostgreSQL/Redis cases and seven actual Account–Game Session cases. R687 remains a failed 88-case aggregate with 11 failures; R688 recovers those affected suites with 24 cases and one different Redis-startup failure, and R689 separately passes that unchanged negative case. The only source difference between R687 and R688 is test-layout isolation for two new cases; production postimages are identical. The physical suite again proves 257 actual releases and retirements, the 256/257 current-entry boundary and 514-field readback. New proof covers Account A advancing through the real acquisition-intent owner while unrelated Account B progresses, stale target ADD refusal, original cleanup and retirement, newer-field preservation, and unchanged SQL/proofs/Redis state through full bootstrap retries after NEW, release and retirement. That control case starts from captured `NO_ACTIVE_ACCOUNT_WIDE_FLOW`; it does not produce a new `HISTORICAL` control tuple. Enabled affected static analysis and formatting pass. Controlled upstream/source/incarnation inputs and all operational-custody, registration, admitting-acknowledgement, OPEN, final-CAS and activation limits remain unchanged. +The preceding qualified correction separates immutable Account provenance from current ADD authority through the original abort, release and retirement readers, and makes the full completed-original bootstrap retry return its retained installation result without replaying baseline writes. Current target ADD guards, complete inventory accounting and mandatory physical-field checks remain required. Across R687, R688 and R689, that checkpoint qualifies 88 selected case methods: 26 units, 55 Game Session PostgreSQL/Redis cases and seven actual Account–Game Session cases. R687 remains a failed 88-case aggregate with 11 failures; R688 recovers those affected suites with 24 cases and one different Redis-startup failure, and R689 separately passes that unchanged negative case. The only source difference between R687 and R688 is test-layout isolation for two new cases; production postimages are identical. The physical suite again proves 257 actual releases and retirements, the 256/257 current-entry boundary and 514-field readback. New proof covers Account A advancing through the real acquisition-intent owner while unrelated Account B progresses, stale target ADD refusal, original cleanup and retirement, newer-field preservation, and unchanged SQL/proofs/Redis state through full bootstrap retries after NEW, release and retirement. That control case starts from captured `NO_ACTIVE_ACCOUNT_WIDE_FLOW`; it does not produce a new `HISTORICAL` control tuple. Enabled affected static analysis and formatting pass. Controlled upstream/source/incarnation inputs and all operational-custody, registration, admitting-acknowledgement, OPEN, final-CAS and activation limits remain unchanged. + +The retained acknowledged-member correction adds forward V1038.1 without changing V1035, V1036 or their recorded checksums. It preserves current Account control on the original `PROVISIONAL`-to-`ABORTED` SQL edge, while later cleanup validates the immutable completed Account repair and exact original terminal, reservation, member and obligation evidence. A later acquisition intent does not authorize a new ADD and cannot block disposal of the old acknowledged terminal member. The native actual Account–Game Session composition covers an owner-produced ACK and definitive Account abort, later acquisition intent, rejected stale ADD, default-ordered V1038-to-V1038.1 history/retained-row preservation, issuer release and retirement with exact retries, and preservation of newer issuer and Account members. R707 passes eight of nine Account cases; its remaining failure came from trying to set transaction isolation inside the negative fixture savepoint. R708 corrects that setup and freshly passes the initial-edge stale-control refusal, with unchanged durable rows and physical fields after rollback. That negative uses controlled repository input and does not perform Account’s terminal operation. Eighteen issuer unit cases pass in R706; its aggregate compile failure and the earlier failed aggregates remain retained. Current affected static analysis and formatting pass. These bounded results supplement the preceding physical-owner proof; they do not claim a new whole-service or public-CI pass. ### Player-created roster consumer preparation diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java index 7a7a4333cc..822dd2257c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java @@ -35,6 +35,7 @@ import net.firedevops.firemud.gamesession.repository.CanonicalGameplayAdmissionAbortManualFactory; import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerBindingLocalReleaseOperation; import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import org.flywaydb.core.api.MigrationVersion; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; @@ -636,6 +637,162 @@ void actualCompletedMemberAckSurvivesAccountAbortAndRetainsUnresolvedPhysicalCle } } + @Test + void actualAcknowledgedAbortCleanupSurvivesLaterAccountIntentAndRetiresExactIssuerMember() + throws Exception { + try (var session = open(MigrationVersion.fromVersion("1038"))) { + var acknowledgement = session.gs.repairAccountMember(); + assertThat(acknowledgement.transitionId()).isEqualTo(session.gs.transitionId()); + assertThat(session.gs.hasExactAccountMember()).isTrue(); + var originalAck = session.gs.memberAcknowledgementImage(); + var originalPhase = session.gs.accountObligationPhaseImage(); + + var abort = session.abort(); + assertThat(abort.state()).isEqualTo(CanonicalGameplayAdmissionAbortOutcome.State.ABORTED); + assertThat(session.gs.source().isAccountAborted()).isTrue(); + assertThat(session.gs.source().candidate().accountIndexState()) + .isEqualTo(CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED); + + String newerMemberSeed = "later-account-newer-issuer-member"; + session.gs.prepareOtherControllerNew(newerMemberSeed); + assertThat(session.gs.projectOtherControllerNew(newerMemberSeed).scriptOutcome()) + .isEqualTo(1L); + session.gs.publishOtherControllerNew(newerMemberSeed); + assertThat(session.gs.hasExactOtherControllerMember(newerMemberSeed)).isTrue(); + + String staleTargetAddSeed = "later-account-stale-target-add"; + session.gs.prepareOtherControllerNew(staleTargetAddSeed); + byte[] fieldsBeforeStaleAdd = session.gs.issuerPartitionFieldSetBytes(); + session.gs.beginAccountAcquisitionIntent("later-account-acquisition"); + assertThat( + session + .gs + .dsl() + .fetchSingle( + "SELECT state FROM game_session_canonical_account_coverage_control" + + " WHERE account_id = ?", + session.gs.candidate().accountId()) + .get(0, String.class)) + .isEqualTo("ACQUISITION_INTENT"); + + assertThatThrownBy(() -> session.gs.projectOtherControllerNew(staleTargetAddSeed)) + .isInstanceOf(IllegalStateException.class); + assertThat(session.gs.issuerPartitionFieldSetBytes()).containsExactly(fieldsBeforeStaleAdd); + assertThat(session.gs.hasExactOtherControllerMember(newerMemberSeed)).isTrue(); + assertThat(session.gs.hasExactAccountMember()).isTrue(); + + var retainedRowsBeforeUpgrade = session.gs.retainedFirstNewAbortRowsImage(); + var migrationHistoryBeforeUpgrade = session.gs.migrationHistoryImage(); + assertThat(migrationHistoryBeforeUpgrade) + .anyMatch(row -> row.contains("V1000__create_saga_schema.sql")) + .anyMatch(row -> row.contains("V1001__saga_instance_table.sql")) + .anyMatch(row -> row.contains("V1002__saga_step_table.sql")); + var issuerFieldsBeforeUpgrade = session.gs.issuerPartitionFieldSetBytes(); + assertThat( + session + .gs + .dsl() + .fetchSingle( + "SELECT state FROM game_session_canonical_account_coverage_control" + + " WHERE account_id = ?", + session.gs.candidate().accountId()) + .get(0, String.class)) + .isEqualTo("ACQUISITION_INTENT"); + assertThat( + session.gs.upgradeWithDefaultGameSessionMigrations( + MigrationVersion.fromVersion("1038.1"))) + .isEqualTo(1); + var migrationHistoryAfterUpgrade = session.gs.migrationHistoryImage(); + assertThat(migrationHistoryAfterUpgrade).hasSize(migrationHistoryBeforeUpgrade.size() + 1); + for (int index = 0; index < migrationHistoryBeforeUpgrade.size(); index++) { + assertThat(migrationHistoryAfterUpgrade.get(index)) + .isEqualTo(migrationHistoryBeforeUpgrade.get(index)); + } + assertThat(migrationHistoryAfterUpgrade.get(migrationHistoryAfterUpgrade.size() - 1)) + .contains("1038.1", "V1038.1__retained_first_new_abort_cleanup_account_control.sql"); + assertThat(session.gs.retainedFirstNewAbortRowsImage()).isEqualTo(retainedRowsBeforeUpgrade); + assertThat(session.gs.memberAcknowledgementImage()).isEqualTo(originalAck); + assertThat(session.gs.accountObligationPhaseImage()).isEqualTo(originalPhase); + assertThat(session.gs.issuerPartitionFieldSetBytes()) + .containsExactly(issuerFieldsBeforeUpgrade); + assertThat(session.gs.hasExactAccountMember()).isTrue(); + assertThat(session.gs.hasExactOtherControllerMember(newerMemberSeed)).isTrue(); + + var pendingRelease = session.gs.prepareIssuerRelease(); + var releaseReadback = session.gs.projectIssuerRelease(pendingRelease); + var released = session.gs.completeIssuerRelease(pendingRelease, releaseReadback); + assertThat(released.status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); + assertThat(session.gs.hasExactOtherControllerMember(newerMemberSeed)).isTrue(); + + var releaseRetry = session.gs.prepareIssuerRelease(); + var releaseRetryReadback = session.gs.projectIssuerRelease(releaseRetry); + assertThat(releaseRetryReadback.scriptOutcome()).isEqualTo(2L); + assertThat( + session + .gs + .completeIssuerRelease(releaseRetry, releaseRetryReadback) + .completionInventoryRevision()) + .isEqualTo(released.completionInventoryRevision()); + + var pendingRetirement = session.gs.prepareIssuerRetirement(session.gs.transitionId()); + assertThat(session.gs.retireIssuerCapacityOutcome(pendingRetirement)).isEqualTo(1L); + assertThat(session.gs.hasExactOtherControllerMember(newerMemberSeed)).isTrue(); + byte[] fieldsBeforeRetirementRetry = session.gs.issuerPartitionFieldSetBytes(); + var retirementRetry = session.gs.prepareIssuerRetirement(session.gs.transitionId()); + assertThat(session.gs.isIssuerRetirementComplete(retirementRetry)).isTrue(); + assertThat(session.gs.retireIssuerCapacityOutcome(retirementRetry)).isEqualTo(2L); + assertThat(session.gs.issuerPartitionFieldSetBytes()) + .containsExactly(fieldsBeforeRetirementRetry); + assertThat(session.gs.hasExactOtherControllerMember(newerMemberSeed)).isTrue(); + assertThat(session.gs.hasExactAccountMember()).isTrue(); + assertThat(session.gs.memberAcknowledgementImage()).isEqualTo(originalAck); + assertThat(session.gs.accountObligationPhaseImage()).isEqualTo(originalPhase); + } + } + + /** + * Controlled GS repository input exercises the initial deferred SQL guard, not Account's + * terminal-state operation. + */ + @Test + void initialAbortDeferredGuardStillRejectsControlAdvanceBeforeCommit() throws Exception { + try (var session = open(true)) { + session.gs.repairAccountMember(); + var originalRows = session.gs.retainedFirstNewAbortRowsImage(); + var originalFields = session.gs.issuerPartitionFieldSetBytes(); + assertThatThrownBy(session.gs::recordOriginalAccountAbortThenAdvanceControlBeforeCommit) + .isInstanceOf(RuntimeException.class) + .rootCause() + .isInstanceOf(org.postgresql.util.PSQLException.class) + .hasMessageContaining("First-NEW Account abort requires its exact retained candidate"); + assertThat(session.gs.source().isAccountAborted()).isFalse(); + assertThat(session.gs.retainedFirstNewAbortRowsImage()).isEqualTo(originalRows); + assertThat(session.gs.issuerPartitionFieldSetBytes()).containsExactly(originalFields); + assertThat(session.gs.hasExactAccountMember()).isTrue(); + assertThat( + session + .gs + .dsl() + .fetchSingle( + "SELECT status FROM game_session_canonical_binding_transition" + + " WHERE transition_id = ?", + session.gs.transitionId()) + .get(0, String.class)) + .isEqualTo("PROVISIONAL"); + assertThat( + session + .gs + .dsl() + .fetchSingle( + "SELECT state FROM game_session_canonical_account_coverage_control" + + " WHERE account_id = ?", + session.gs.candidate().accountId()) + .get(0, String.class)) + .isEqualTo("NO_ACTIVE_ACCOUNT_WIDE_FLOW"); + } + } + private Session open() throws Exception { accountFixtures.temporaryDirectory = temporaryDirectory; return new Session(false); @@ -646,6 +803,11 @@ private Session open(boolean prepareMemberRepair) throws Exception { return new Session(prepareMemberRepair); } + private Session open(MigrationVersion migrationTarget) throws Exception { + accountFixtures.temporaryDirectory = temporaryDirectory; + return new Session(true, migrationTarget); + } + private final class Session implements AutoCloseable { private final PhysicalRedisFixture redis = PhysicalRedisFixture.start(); private final AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.Fixture @@ -662,6 +824,11 @@ private final class Session implements AutoCloseable { private AccountGameplayAdmissionLeaseEvidence lease; private Session(boolean prepareMemberRepair) throws Exception { + this(prepareMemberRepair, null); + } + + private Session(boolean prepareMemberRepair, MigrationVersion migrationTarget) + throws Exception { try { accountFixture = accountFixtures.newFixture(redis.client()); var issuance = accountFixture.committedCandidate.identity(); @@ -690,10 +857,14 @@ private Session(boolean prepareMemberRepair) throws Exception { candidate.issuerAuthGeneration(), candidate.issuerIndexLayoutVersion(), candidate.issuerIndexPartitionCount(), - java.math.BigInteger.valueOf(2)); + java.math.BigInteger.valueOf(prepareMemberRepair ? 3 : 2)); gs = new CanonicalGameplayAdmissionAbortCompositionFixture( - accountFixture.dataSource, capacityCandidate, redis.issuerOwnerClient()); + accountFixture.dataSource, + capacityCandidate, + redis.issuerOwnerClient(), + 0, + migrationTarget); if (prepareMemberRepair) gs.prepareMemberRepairRedis(); pkiDirectory = Files.createTempDirectory(temporaryDirectory, "actual-abort-mtls-"); pki = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index 4b1fd6cce3..47d5c745ec 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -1644,7 +1644,7 @@ private static CanonicalGameplayAdmissionAbortSource loadFirstNewAdmissionAbortS reservation = provisional.candidateReservation(); } else { requireRetainedFirstNewAbortObligations( - transaction, transitionId, transitionSnapshot, candidate); + transaction, transitionId, transitionSnapshot, candidate, retainedDefinitiveAbortCleanup); } AccountGameplayAdmissionLeaseEvidence lease; @@ -1696,7 +1696,8 @@ private static void requireRetainedFirstNewAbortObligations( DSLContext transaction, UUID transitionId, CanonicalGameplayBindingTransitionSnapshot transition, - CanonicalGameplayBindingInventoryEntry retainedCandidate) { + CanonicalGameplayBindingInventoryEntry retainedCandidate, + boolean retainedDefinitiveAbortCleanup) { BigInteger revision = transition.inventoryRevision(); byte[] bindingRef = transition.bindingRef().bytes(); CanonicalGameplayBindingIdentity candidate = transition.candidate(); @@ -1777,15 +1778,17 @@ private static void requireRetainedFirstNewAbortObligations( && !completedRevision.equals(obligation.projectionInventoryRevision()))) { throw conflict("Retained abort changed the original completed account-member readback"); } - Record control = - transaction.fetchOne( - "SELECT * FROM game_session_canonical_account_coverage_control WHERE account_id = ?", - operation.accountId()); - if (control == null - || !"NO_ACTIVE_ACCOUNT_WIDE_FLOW".equals(control.get("state", String.class)) - || !readBigInteger(control, "last_operation_fence") - .equals(operation.accountControlEpoch())) { - throw conflict("Retained account-member acknowledgement has a different control epoch"); + if (!retainedDefinitiveAbortCleanup) { + Record control = + transaction.fetchOne( + "SELECT * FROM game_session_canonical_account_coverage_control WHERE account_id = ?", + operation.accountId()); + if (control == null + || !"NO_ACTIVE_ACCOUNT_WIDE_FLOW".equals(control.get("state", String.class)) + || !readBigInteger(control, "last_operation_fence") + .equals(operation.accountControlEpoch())) { + throw conflict("Retained account-member acknowledgement has a different control epoch"); + } } } else if (retainedCandidate.accountIndexState() != CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwner.java index 514fa6df88..0dd47973cd 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwner.java @@ -256,7 +256,8 @@ private static void requireNonNil(UUID value, String name) { } private static void requireNoAmbientTransaction() { - if (TransactionSynchronizationManager.isActualTransactionActive()) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { throw unavailable( "Initial issuer bootstrap completion cannot join an ambient SQL transaction"); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java index 4f4031b675..ee1d89b89f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java @@ -1395,7 +1395,8 @@ private static byte[] optionalBytes(Record row, String field) { } private static void requireNoAmbientTransaction() { - if (TransactionSynchronizationManager.isActualTransactionActive()) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { throw conflict("Issuer bootstrap coverage owner cannot join an ambient SQL transaction"); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepository.java index b921e79e08..0949075610 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepository.java @@ -692,7 +692,8 @@ private static UUID requireUuid(Record row, String field) { } private static void requireNoAmbientTransaction() { - if (TransactionSynchronizationManager.isActualTransactionActive()) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { throw conflict("Issuer bootstrap member operation owner cannot join an ambient transaction"); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwner.java index ba44492790..2abc820fb4 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwner.java @@ -391,7 +391,10 @@ private static T await(RedisFuture future) { } private static void requireNoAmbientTransaction() { - if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw unavailable(); + } } private static String digest(String algorithm, byte[] bytes) { diff --git a/services/game-session-service/src/main/resources/db/migration/V1038.1__retained_first_new_abort_cleanup_account_control.sql b/services/game-session-service/src/main/resources/db/migration/V1038.1__retained_first_new_abort_cleanup_account_control.sql new file mode 100644 index 0000000000..985231be1b --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1038.1__retained_first_new_abort_cleanup_account_control.sql @@ -0,0 +1,196 @@ +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION require_first_new_abort_source_complete() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + affected_transition_id uuid; + initial_abort_transition boolean := false; +BEGIN + IF TG_OP = 'DELETE' THEN affected_transition_id := OLD.transition_id; + ELSE affected_transition_id := NEW.transition_id; + END IF; + IF TG_TABLE_NAME = 'game_session_canonical_binding_transition' + AND TG_OP = 'UPDATE' THEN + IF OLD.status = 'PROVISIONAL' AND NEW.status = 'ABORTED' THEN + initial_abort_transition := true; + END IF; + END IF; + IF NOT EXISTS (SELECT 1 FROM game_session_canonical_binding_transition + WHERE transition_id = affected_transition_id AND status = 'ABORTED' + AND admission_orphan_cleanup_id IS NOT NULL) THEN + RETURN NULL; + END IF; + IF NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_binding_transition transition + JOIN game_session_canonical_gameplay_binding_inventory candidate + ON candidate.binding_ref = transition.candidate_binding_ref + JOIN game_session_canonical_issuer_partition_reservation reservation + ON reservation.reservation_id = transition.issuer_reservation_id + JOIN game_session_canonical_binding_account_index_obligation account_obligation + ON account_obligation.transition_id = transition.transition_id + AND account_obligation.obligation_ordinal = 0 + JOIN game_session_canonical_binding_issuer_index_obligation issuer_obligation + ON issuer_obligation.transition_id = transition.transition_id + AND issuer_obligation.binding_ref = transition.candidate_binding_ref + JOIN game_session_canonical_binding_region_bridge_obligation region_obligation + ON region_obligation.transition_id = transition.transition_id + WHERE transition.transition_id = affected_transition_id + AND transition.status = 'ABORTED' + AND transition.admission_lease_id IS NOT NULL + AND transition.admission_lease_kind = 'NEW_BINDING' + AND transition.admission_lease_evidence IS NOT NULL + AND transition.admission_lease_digest IS NOT NULL + AND transition.expected_prior_binding_ref IS NULL + AND transition.expected_prior_binding_generation IS NULL + AND transition.admission_orphan_cleanup_id IS NOT NULL + AND transition.admission_orphan_cleanup_id <> + '00000000-0000-0000-0000-000000000000'::uuid + AND transition.inventory_revision = candidate.inventory_revision + AND transition.inventory_revision = reservation.inventory_revision + AND transition.inventory_revision = account_obligation.inventory_revision + AND transition.inventory_revision = issuer_obligation.inventory_revision + AND transition.inventory_revision = region_obligation.inventory_revision + AND transition.candidate_binding_ref = candidate.binding_ref + AND transition.candidate_binding_generation = candidate.binding_generation + AND transition.candidate_account_index_fence = candidate.account_index_fence + AND transition.issuer_reservation_id = candidate.issuer_reservation_id + AND transition.tenant_id = candidate.tenant_id + AND transition.playable_state_namespace_id = candidate.playable_state_namespace_id + AND transition.character_id = candidate.character_id + AND candidate.lifecycle = 'TERMINAL_UNRESOLVED' + AND reservation.lifecycle IN ('RELEASE_PENDING', 'RELEASED') + AND reservation.transition_id = transition.transition_id + AND reservation.binding_ref = candidate.binding_ref + AND reservation.binding_generation = candidate.binding_generation + AND reservation.reservation_fence IS NOT NULL + AND reservation.account_id = candidate.account_id + AND reservation.tenant_id = candidate.tenant_id + AND reservation.playable_state_namespace_id = candidate.playable_state_namespace_id + AND reservation.character_id = candidate.character_id + AND reservation.game_instance_id = candidate.game_instance_id + AND reservation.runtime_game_instance_id = candidate.runtime_game_instance_id + AND reservation.session_id = candidate.session_id + AND reservation.region_id = candidate.region_id + AND reservation.region_epoch = candidate.region_epoch + AND reservation.issuer_id = candidate.issuer_id + AND reservation.issuer_auth_generation = candidate.issuer_auth_generation + AND reservation.issuer_index_layout_version = candidate.issuer_index_layout_version + AND reservation.issuer_index_partition_count = candidate.issuer_index_partition_count + AND reservation.issuer_index_partition_capacity = candidate.issuer_index_partition_capacity + AND account_obligation.binding_ref = candidate.binding_ref + AND account_obligation.account_id = candidate.account_id + AND account_obligation.tenant_id = candidate.tenant_id + AND account_obligation.action = 'ADD_OR_RETAIN' + AND account_obligation.binding_generation = candidate.binding_generation + AND account_obligation.expected_prior_generation IS NULL + AND account_obligation.account_index_fence = candidate.account_index_fence + AND account_obligation.execution_phase = 'BEFORE_FINAL_CAS' + AND ( + (account_obligation.status = 'REQUIRED' AND candidate.account_index_state = 'REPAIR_REQUIRED') + OR (account_obligation.status = 'ACKNOWLEDGED' + AND candidate.account_index_state = 'ACKNOWLEDGED' + AND account_obligation.projection_state = 'PRESENT_AWAITING_COVERAGE' + AND EXISTS ( + SELECT 1 FROM game_session_canonical_account_member_repair_operation repair + WHERE repair.transition_id = transition.transition_id + AND repair.obligation_ordinal = 0 + AND repair.status = 'ACKNOWLEDGED' + AND repair.binding_ref = candidate.binding_ref + AND repair.account_id = candidate.account_id + AND repair.tenant_id = candidate.tenant_id + AND repair.binding_generation = candidate.binding_generation + AND repair.account_index_fence = candidate.account_index_fence + AND repair.original_action = 'ADD_OR_RETAIN' + AND repair.original_expected_prior_generation IS NULL + AND repair.original_execution_phase = 'BEFORE_FINAL_CAS' + AND repair.original_status = 'REQUIRED' + AND repair.desired_action = 'ADD_OR_RETAIN' + AND repair.account_control_state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW' + AND ( + NOT initial_abort_transition + OR EXISTS ( + SELECT 1 + FROM game_session_canonical_account_coverage_control control + WHERE control.account_id = repair.account_id + AND control.state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW' + AND control.last_operation_fence = repair.account_control_epoch)) + AND repair.coverage_generation > repair.inventory_snapshot_revision + AND repair.completed_inventory_revision > repair.inventory_snapshot_revision + AND repair.completed_inventory_revision < transition.inventory_revision + AND repair.readback_state = 'PRESENT' + AND repair.readback_member = repair.member + AND repair.member = account_obligation.projection_member + AND repair.member = 'accountIndexMember/v1:' + || rtrim(translate(replace(encode(candidate.binding_ref, 'base64'), E'\n', ''), '+/', '-_'), '=') + || ':' || candidate.binding_generation::text || ':' || candidate.account_index_fence::text + AND ((repair.original_projection_state = 'REQUIRED' + AND account_obligation.projection_inventory_revision = repair.completed_inventory_revision) + OR (repair.original_projection_state = 'PRESENT_AWAITING_COVERAGE' + AND repair.original_projection_member = repair.member + AND account_obligation.projection_inventory_revision = repair.original_projection_inventory_revision)) + )) + ) + AND (SELECT count(*) + FROM game_session_canonical_binding_account_index_obligation extra_account + WHERE extra_account.transition_id = transition.transition_id) = 1 + AND issuer_obligation.reservation_id = reservation.reservation_id + AND issuer_obligation.binding_ref = candidate.binding_ref + AND issuer_obligation.binding_generation = candidate.binding_generation + AND ( + (issuer_obligation.status = 'REQUIRED' + AND issuer_obligation.local_release_operation_id IS NULL + AND reservation.lifecycle = 'RELEASE_PENDING' + AND NOT EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_binding_local_release_operation pending_release + WHERE pending_release.transition_id = transition.transition_id + AND pending_release.status <> 'PENDING_PHYSICAL_PROOF')) + OR (issuer_obligation.status = 'RELEASED' + AND issuer_obligation.local_release_operation_id IS NOT NULL + AND reservation.lifecycle = 'RELEASED' + AND EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_binding_local_release_operation released + WHERE released.operation_id = issuer_obligation.local_release_operation_id + AND released.transition_id = transition.transition_id + AND released.orphan_cleanup_id = transition.admission_orphan_cleanup_id + AND released.reservation_id = reservation.reservation_id + AND released.binding_ref = candidate.binding_ref + AND released.binding_generation = candidate.binding_generation + AND released.status = 'RELEASED' + AND released.source_inventory_revision < transition.inventory_revision + AND released.completion_inventory_revision = transition.inventory_revision + AND released.physical_readback_field_set_bytes IS NOT NULL + AND released.physical_readback_field_set_digest ~ '^sha256:[0-9a-f]{64}$' + AND released.released_member_value_bytes IS NOT NULL + AND released.released_member_value_digest ~ '^sha256:[0-9a-f]{64}$')) + ) + AND (SELECT count(*) + FROM game_session_canonical_binding_issuer_index_obligation extra_issuer + WHERE extra_issuer.transition_id = transition.transition_id) = 1 + AND region_obligation.binding_ref = candidate.binding_ref + AND region_obligation.binding_generation = candidate.binding_generation + AND region_obligation.account_id = candidate.account_id + AND region_obligation.tenant_id = candidate.tenant_id + AND region_obligation.game_instance_id = candidate.game_instance_id + AND region_obligation.runtime_game_instance_id = candidate.runtime_game_instance_id + AND region_obligation.session_id = candidate.session_id + AND region_obligation.region_id = candidate.region_id + AND region_obligation.region_epoch = candidate.region_epoch + AND region_obligation.status = 'REQUIRED' + AND NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_gameplay_binding_inventory active + WHERE active.tenant_id = candidate.tenant_id + AND active.playable_state_namespace_id = candidate.playable_state_namespace_id + AND active.character_id = candidate.character_id + AND active.lifecycle = 'ACTIVE') + ) THEN + RAISE EXCEPTION 'First-NEW Account abort requires its exact retained candidate, reservation, and unresolved obligations' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_first_new_abort_source_incomplete'; + END IF; + RETURN NULL; +END; +$$; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java index 23e9a51d13..5d08abd380 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java @@ -48,6 +48,7 @@ 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.SQLDialect; import org.jooq.impl.DSL; @@ -62,6 +63,16 @@ * replaces the GS reverse decision read. */ public final class CanonicalGameplayAdmissionAbortCompositionFixture implements AutoCloseable { + private static final String SERVICE_MIGRATIONS = + "filesystem:" + + Path.of("../game-session-service/src/main/resources/db/migration") + .toAbsolutePath() + .normalize(); + private static final String SHARED_SAGA_MIGRATIONS = + "filesystem:" + + Path.of("../common-saga/src/main/resources/db/migration/saga") + .toAbsolutePath() + .normalize(); private final DriverManagerDataSource dataSource; private final String schema = "gs_abort_composition_" + UUID.randomUUID().toString().replace("-", ""); @@ -102,6 +113,16 @@ public CanonicalGameplayAdmissionAbortCompositionFixture( Candidate accountCandidate, RedisClient issuerRedisClient, int seedBootstrapMemberCount) { + this(accountDataSource, accountCandidate, issuerRedisClient, seedBootstrapMemberCount, null); + } + + /** Starts from a retained migration frontier when a composition test must upgrade live rows. */ + public CanonicalGameplayAdmissionAbortCompositionFixture( + DriverManagerDataSource accountDataSource, + Candidate accountCandidate, + RedisClient issuerRedisClient, + int seedBootstrapMemberCount, + MigrationVersion migrationTarget) { if (seedBootstrapMemberCount < 0 || seedBootstrapMemberCount > 256) { throw new IllegalArgumentException("Bootstrap fixture member count must be within [0, 256]"); } @@ -114,18 +135,15 @@ public CanonicalGameplayAdmissionAbortCompositionFixture( .replaceAll("currentSchema=[^&]+", "currentSchema=" + schema)); dataSource.setUsername(accountDataSource.getUsername()); dataSource.setPassword(accountDataSource.getPassword()); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .placeholders(java.util.Map.of("serviceSchema", schema)) - .locations( - "filesystem:" - + Path.of("../game-session-service/src/main/resources/db/migration") - .toAbsolutePath() - .normalize()) - .load() - .migrate(); + var migration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(java.util.Map.of("serviceSchema", schema)) + .locations(SERVICE_MIGRATIONS, SHARED_SAGA_MIGRATIONS); + if (migrationTarget != null) migration.target(migrationTarget); + migration.load().migrate(); dsl = DSL.using(dataSource, SQLDialect.POSTGRES); var runtime = CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( @@ -522,6 +540,86 @@ public String accountObligationPhaseImage() { .get(0, String.class); } + /** Preserves the retained terminal source and every proof row across a Flyway upgrade. */ + public String retainedFirstNewAbortRowsImage() { + return dsl.fetchSingle( + "WITH target AS (SELECT * FROM game_session_canonical_binding_transition" + + " WHERE transition_id = ?)" + + " SELECT jsonb_build_object(" + + "'transition', (SELECT to_jsonb(target) FROM target)," + + " 'candidate', (SELECT to_jsonb(candidate)" + + " FROM game_session_canonical_gameplay_binding_inventory candidate" + + " JOIN target ON candidate.binding_ref = target.candidate_binding_ref)," + + " 'reservation', (SELECT to_jsonb(reservation)" + + " FROM game_session_canonical_issuer_partition_reservation reservation" + + " JOIN target ON reservation.reservation_id = target.issuer_reservation_id)," + + " 'account_obligations', (SELECT coalesce(jsonb_agg(to_jsonb(obligation)" + + " ORDER BY obligation.obligation_ordinal), '[]'::jsonb)" + + " FROM game_session_canonical_binding_account_index_obligation obligation" + + " JOIN target ON obligation.transition_id = target.transition_id)," + + " 'issuer_obligations', (SELECT coalesce(jsonb_agg(to_jsonb(obligation)" + + " ORDER BY obligation.binding_ref), '[]'::jsonb)" + + " FROM game_session_canonical_binding_issuer_index_obligation obligation" + + " JOIN target ON obligation.transition_id = target.transition_id)," + + " 'region_obligations', (SELECT coalesce(jsonb_agg(to_jsonb(obligation)" + + " ORDER BY obligation.region_id), '[]'::jsonb)" + + " FROM game_session_canonical_binding_region_bridge_obligation obligation" + + " JOIN target ON obligation.transition_id = target.transition_id)," + + " 'account_member_repairs', (SELECT coalesce(jsonb_agg(to_jsonb(repair)" + + " ORDER BY repair.operation_id), '[]'::jsonb)" + + " FROM game_session_canonical_account_member_repair_operation repair" + + " JOIN target ON repair.transition_id = target.transition_id))::text" + + " FROM target", + transitionId) + .get(0, String.class); + } + + /** Captures exact existing Flyway rows so a forward upgrade can prove append-only history. */ + public List migrationHistoryImage() { + return dsl.fetch( + "SELECT to_jsonb(history_row)::text AS row_json FROM flyway_schema_history" + + " history_row ORDER BY installed_rank") + .getValues("row_json", String.class); + } + + /** Applies pending Game Session migrations with Flyway's default version ordering. */ + public int upgradeWithDefaultGameSessionMigrations(MigrationVersion migrationTarget) { + Flyway flyway = + Flyway.configure() + .target(Objects.requireNonNull(migrationTarget, "migrationTarget")) + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(java.util.Map.of("serviceSchema", schema)) + .locations(SERVICE_MIGRATIONS, SHARED_SAGA_MIGRATIONS) + .load(); + var result = flyway.migrate(); + flyway.validate(); + return result.migrationsExecuted; + } + + /** + * Exercises the deferred initial-abort SQL guard after the actual GS abort owner has written its + * source, then advances Account control before the enclosing transaction commits. + */ + public void recordOriginalAccountAbortThenAdvanceControlBeforeCommit() { + var source = repository.readFirstNewAdmissionAbortSource(transitionId); + dsl.transaction( + configuration -> { + DSLContext transaction = DSL.using(configuration); + var transactionRepository = new CanonicalGameplayBindingInventoryRepository(transaction); + transactionRepository.recordFirstNewAccountAbort( + source, + UUID.nameUUIDFromBytes( + "original-controller-stale-control-cleanup".getBytes(StandardCharsets.UTF_8))); + new CanonicalGameplayAccountAdmissionBarrierRepository(transaction) + .beginFenceIntent( + identity.accountId(), + UUID.nameUUIDFromBytes( + "original-controller-stale-control-intent".getBytes(StandardCharsets.UTF_8))); + }); + } + /** Independent read under the same real GS role; retained ACK never implies physical removal. */ public boolean hasExactAccountMember() { var acknowledgement = @@ -678,6 +776,44 @@ public CanonicalGameplayIssuerBindingLocalRedisOwner.Readback projectOtherContro .projectAndRead(operation); } + /** Advances the real account-wide control through a later acquisition intent. */ + public void beginAccountAcquisitionIntent(String seed) { + new CanonicalGameplayAccountAdmissionBarrierRepository(dsl) + .beginFenceIntent( + identity.accountId(), + UUID.nameUUIDFromBytes((seed + "-request").getBytes(StandardCharsets.UTF_8))); + } + + /** Independently snapshots the actual issuer partition for no-write assertions. */ + public byte[] issuerPartitionFieldSetBytes() { + Map fields = new LinkedHashMap<>(); + try (var connection = + issuerRedisClient.connect(io.lettuce.core.codec.ByteArrayCodec.INSTANCE)) { + connection + .sync() + .hgetall(issuerPartitionKey()) + .forEach((field, value) -> fields.put(new String(field, StandardCharsets.UTF_8), value)); + } + return CanonicalGameplayIssuerBootstrapCoverageRepository.encodeFieldSet(fields); + } + + /** Reads both exact physical indexes for another real issuer member. */ + public boolean hasExactOtherControllerMember(String seed) { + var operation = otherOperation(seed); + byte[] key = issuerPartitionKey(); + byte[] expected = operation.exactMemberValueBytes(); + byte[] capacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + operation.reservation().reservationId()) + .getBytes(StandardCharsets.US_ASCII); + byte[] bindingField = operation.memberValue().owner().bindingRef().bytes(); + try (var connection = + issuerRedisClient.connect(io.lettuce.core.codec.ByteArrayCodec.INSTANCE)) { + return Arrays.equals(connection.sync().hget(key, capacityField), expected) + && Arrays.equals(connection.sync().hget(key, bindingField), expected); + } + } + /** Publishes a controlled Account lease through the actual SQL and Redis provisional owners. */ public void publishOtherControllerNew(String seed) { var operation = otherOperation(seed); @@ -753,6 +889,19 @@ public CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.Readback retireIs .retireAndRead(operation); } + /** Public test bridge for the otherwise package-private retirement readback outcome. */ + public long retireIssuerCapacityOutcome( + CanonicalGameplayIssuerBindingLocalRetirementOperation operation) { + return retireIssuerCapacity(operation).scriptOutcome(); + } + + /** Public test bridge for the otherwise package-private retirement operation status. */ + public boolean isIssuerRetirementComplete( + CanonicalGameplayIssuerBindingLocalRetirementOperation operation) { + return operation.status() + == CanonicalGameplayIssuerBindingLocalRetirementOperation.Status.RETIRED; + } + /** Adds the retirement script only for callers that exercise the new owner. */ RedisScriptCatalog retirementCatalog() { return RedisScriptCatalog.fromContributions( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapAmbientTransactionTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapAmbientTransactionTest.java new file mode 100644 index 0000000000..e0909591df --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapAmbientTransactionTest.java @@ -0,0 +1,126 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.lettuce.core.RedisClient; +import java.math.BigInteger; +import java.util.UUID; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class CanonicalGameplayIssuerBootstrapAmbientTransactionTest { + @Test + void coverageOwnerRejectsBothAmbientStatesBeforeReadingCurrentSourceOrUsingSql() { + DSLContext dsl = mock(DSLContext.class); + var partitionRedisOwner = mock(CanonicalGameplayIssuerBootstrapPartitionRedisOwner.class); + var currentStateSource = + mock(CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource.class); + var owner = + new CanonicalGameplayIssuerBootstrapCoverageOwner( + dsl, partitionRedisOwner, currentStateSource); + UUID operationId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + + assertRefusesInBothAmbientStates( + () -> owner.completeInitialBootstrap(operationId, requestId), "ambient SQL transaction"); + assertRefusesInBothAmbientStates( + () -> owner.verifyInstalledPhysicalCoverage(operationId, requestId), + "ambient SQL transaction"); + + verifyNoInteractions(dsl, partitionRedisOwner, currentStateSource); + } + + @Test + void coverageRepositoryRejectsBothAmbientStatesBeforeSql() { + DSLContext dsl = mock(DSLContext.class); + var repository = new CanonicalGameplayIssuerBootstrapCoverageRepository(dsl); + var currentState = + mock(CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState.class); + UUID operationId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + + assertRefusesInBothAmbientStates( + () -> repository.readInstalledAnchor(operationId, requestId, currentState), + "ambient SQL transaction"); + assertRefusesInBothAmbientStates( + () -> repository.installInitialAnchor(operationId, requestId, currentState), + "ambient SQL transaction"); + + verifyNoInteractions(dsl, currentState); + } + + @Test + void memberOperationRepositoryRejectsBothAmbientStatesBeforeSql() { + DSLContext dsl = mock(DSLContext.class); + var repository = new CanonicalGameplayIssuerBootstrapMemberOperationRepository(dsl); + var currentCheckpoint = + mock(CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint.class); + var incarnation = + mock( + CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation + .class); + UUID operationId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + + assertRefusesInBothAmbientStates( + () -> + repository.beginOrResumePendingPhysicalProof( + operationId, requestId, 0, currentCheckpoint, incarnation), + "ambient transaction"); + assertRefusesInBothAmbientStates( + () -> + repository.preparePartitionWork( + operationId, requestId, BigInteger.ZERO, currentCheckpoint, incarnation), + "ambient transaction"); + + verifyNoInteractions(dsl, currentCheckpoint, incarnation); + } + + @Test + void partitionRedisOwnerRejectsBothAmbientStatesBeforeRedisOrCurrentSource() { + var redisClient = mock(RedisClient.class); + var catalog = mock(RedisScriptCatalog.class); + var currentStateSource = + mock(CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource.class); + var owner = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner( + redisClient, catalog, currentStateSource); + var work = mock(CanonicalGameplayIssuerBootstrapPartitionWork.class); + + assertRefusesInBothAmbientStates( + () -> owner.buildAndRead(work), "partition projection is unavailable"); + assertRefusesInBothAmbientStates( + () -> owner.readExistingAndRead(work), "partition projection is unavailable"); + + verifyNoInteractions(redisClient, catalog, currentStateSource, work); + } + + private static void assertRefusesInBothAmbientStates(Runnable invocation, String message) { + assertRefuses(invocation, message, false); + assertRefuses(invocation, message, true); + } + + private static void assertRefuses( + Runnable invocation, String message, boolean synchronizationOnly) { + try { + if (synchronizationOnly) { + TransactionSynchronizationManager.initSynchronization(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + } else { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + } + assertThatThrownBy(invocation::run) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining(message); + } finally { + TransactionSynchronizationManager.clear(); + } + } +} From 8cf137b8fb31be2728978e1397ffce7012bf313e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 07:40:20 +1300 Subject: [PATCH 19/34] fix(gameplay): block issuer bootstrap plans with unissuable lifecycles --- .../player-access-and-session.md | 2 + ...ameplayIssuerPartitionBuildRepository.java | 34 ++ ...rtitionBuildRepositoryIntegrationTest.java | 392 +++++++++++++++++- 3 files changed, 405 insertions(+), 23 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 14a20cd151..32a33bc15e 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -38,6 +38,8 @@ The preceding qualified correction separates immutable Account provenance from c The retained acknowledged-member correction adds forward V1038.1 without changing V1035, V1036 or their recorded checksums. It preserves current Account control on the original `PROVISIONAL`-to-`ABORTED` SQL edge, while later cleanup validates the immutable completed Account repair and exact original terminal, reservation, member and obligation evidence. A later acquisition intent does not authorize a new ADD and cannot block disposal of the old acknowledged terminal member. The native actual Account–Game Session composition covers an owner-produced ACK and definitive Account abort, later acquisition intent, rejected stale ADD, default-ordered V1038-to-V1038.1 history/retained-row preservation, issuer release and retirement with exact retries, and preservation of newer issuer and Account members. R707 passes eight of nine Account cases; its remaining failure came from trying to set transaction isolation inside the negative fixture savepoint. R708 corrects that setup and freshly passes the initial-edge stale-control refusal, with unchanged durable rows and physical fields after rollback. That negative uses controlled repository input and does not perform Account’s terminal operation. Eighteen issuer unit cases pass in R706; its aggregate compile failure and the earlier failed aggregates remain retained. Current affected static analysis and formatting pass. These bounded results supplement the preceding physical-owner proof; they do not claim a new whole-service or public-CI pass. +The initial issuer planner now records existing blockers for lifecycle pairs that cannot issue bootstrap member work, including retained `TERMINAL_UNRESOLVED` bindings and unlinked `BOUND` or `RELEASE_PENDING` reservations. It retains the complete original cohort and does not issue coverage, member operations or counters for a blocked plan. R718 runs 32 plan/member/coverage/physical-partition cases: 31 pass and the new negative fixture fails before owner setup because its disposable schema name exceeds PostgreSQL's identifier limit. R719 shortens only that fixture prefix and freshly passes all 12 plan cases, including an actual Game Session abort-produced unresolved binding, the shared member-issuance refusal gate and unchanged retained row images. Across R718/R719, all 32 distinct selected methods have passing execution; the failed aggregate remains retained. Enabled affected static analysis and formatting pass. Account lease and launch inputs remain controlled, and the unlinked reservation vectors use explicitly controlled SQL fixtures. No installed authority, production custody, admission or activation is inferred. + ### Player-created roster consumer preparation The unregistered Game Session composition consumes the independently resolved current published source through Entity's distinct created-roster and selected-character reads, preserving full original creation terminals, frozen menu/actor choice and the typed original-operation receipt/recovery/retirement branch. The [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#player-created-roster-and-selected-character) owns the created evidence contract; [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md#player-created-original-roster-storage) records its local storage consequences. V1020 receipt storage does not include the separate canonical UUID runtime or creation-protection owners and supplies no Account protection or admission authority. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java index f36683fd67..4c2487fbe9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java @@ -733,6 +733,40 @@ private static DerivedPlan derivePlan( .CONFLICTING_RESERVATION_LINK)); } else { bindingOrdinalByReservation.put(entry.getKey(), binding.rowOrdinal()); + CanonicalGameplayBindingInventoryEntry.Lifecycle bindingLifecycle = + CanonicalGameplayBindingInventoryEntry.Lifecycle.valueOf(binding.lifecycle()); + CanonicalIssuerPartitionReservation.Lifecycle reservationLifecycle = + CanonicalIssuerPartitionReservation.Lifecycle.valueOf(reservation.lifecycle()); + boolean issuableLifecyclePair = + switch (bindingLifecycle) { + case CANDIDATE_PREPARED, PROVISIONAL -> + reservationLifecycle == CanonicalIssuerPartitionReservation.Lifecycle.RESERVED; + case ACTIVE -> + reservationLifecycle == CanonicalIssuerPartitionReservation.Lifecycle.BOUND + || reservationLifecycle + == CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING; + case TERMINAL -> + reservationLifecycle == CanonicalIssuerPartitionReservation.Lifecycle.RELEASED; + case TERMINAL_UNRESOLVED -> false; + }; + if (!issuableLifecyclePair) { + blockers.add( + new PlanBlocker( + binding.rowOrdinal(), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode.UNREPRESENTABLE_BINDING)); + } + } + } + + for (ReservationSource reservation : reservations.values()) { + if (!bindings.containsKey(reservation.reservationId()) + && !reservation.lifecycle().equals("RESERVED") + && !reservation.lifecycle().equals("RELEASED")) { + blockers.add( + new PlanBlocker( + reservation.rowOrdinal(), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode + .CONFLICTING_RESERVATION_LINK)); } } 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 5bad360faf..693de911f6 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 @@ -11,13 +11,17 @@ import java.sql.SQLException; import java.util.EnumSet; import java.util.List; +import java.util.Map; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; @@ -27,6 +31,7 @@ import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; 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; @@ -585,6 +590,19 @@ void populatedPendingIntentRetainsCompleteCohortAndBothCoverageTuplesAcrossConcu .orElseThrow(); assertThat(reservationOnlyWork.bindingSourceRowOrdinal()).isNull(); assertThat(reservationOnlyWork.bindingSourceRowDigest()).isNull(); + var preparedBindingWork = + firstPlan.memberWorks().stream() + .filter(work -> work.reservationId().equals(prepared.issuerReservationId())) + .findFirst() + .orElseThrow(); + assertThat(preparedBindingWork.reservationLifecycle()).isEqualTo("RESERVED"); + assertThat(preparedBindingWork.bindingSourceRowOrdinal()).isNotNull(); + assertThat( + firstPlan + .cohortRows() + .get(Math.toIntExact(preparedBindingWork.bindingSourceRowOrdinal())) + .sourceRowJson()) + .contains("CANDIDATE_PREPARED"); assertThat(reservationOnlyWork.originalIssuerCoverageOperationId()) .isNotEqualTo(reservationOnlyWork.plannedAnchorOperationId()); assertThat(reservationOnlyWork.originalIssuerCoverageOperationFence()) @@ -902,6 +920,199 @@ void retainedLegacyReservationProducesACompleteBlockedPlan() { } } + @Test + void retainedTerminalUnresolvedAndUnlinkedBoundReservationsBlockMemberIssuance() { + TestSchema testSchema = newTestSchema("gs_issuer_build_unresolved_"); + try { + establishActualLegacyDisposition(testSchema.dsl()); + CanonicalGameplayAdmissionAbortSource abortSource = + createActualRetainedTerminalUnresolved(testSchema); + assertThat(abortSource.isAccountAborted()).isTrue(); + assertThat(abortSource.candidate().lifecycle()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry + .Lifecycle.TERMINAL_UNRESOLVED); + assertThat(abortSource.reservation().lifecycle()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation + .Lifecycle.RELEASE_PENDING); + + // These standalone rows are controlled fixtures for the no-binding BOUND and + // RELEASE_PENDING cases. The linked TERMINAL_UNRESOLVED source above is produced by the + // existing binding inventory abort owner. + UUID unlinkedBoundReservationId = UUID.randomUUID(); + UUID unlinkedReleasePendingReservationId = UUID.randomUUID(); + insertReservationOnly( + testSchema.dsl(), + abortSource.candidate().identity(), + abortSource.transition().inventoryRevision(), + unlinkedBoundReservationId, + BigInteger.valueOf(17), + BigInteger.valueOf(19), + LAYOUT_VERSION, + PARTITION_COUNT, + PARTITION_CAPACITY, + false, + "BOUND", + UUID.randomUUID()); + insertReservationOnly( + testSchema.dsl(), + abortSource.candidate().identity(), + abortSource.transition().inventoryRevision(), + unlinkedReleasePendingReservationId, + BigInteger.valueOf(17), + BigInteger.valueOf(19), + LAYOUT_VERSION, + PARTITION_COUNT, + PARTITION_CAPACITY, + false, + "RELEASE_PENDING", + UUID.randomUUID()); + + UUID requestId = UUID.randomUUID(); + var intent = + new CanonicalGameplayIssuerLayoutBootstrapRepository(testSchema.dsl()) + .beginInitialBootstrapIntent( + requestId, + descriptor(LAYOUT_VERSION, PARTITION_COUNT, PARTITION_CAPACITY), + sourceCheckpoint(BigInteger.valueOf(7))); + List bindingsBeforePlan = + rowImages(testSchema.dsl(), "game_session_canonical_gameplay_binding_inventory"); + List reservationsBeforePlan = + rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_reservation"); + List transitionsBeforePlan = + rowImages(testSchema.dsl(), "game_session_canonical_binding_transition"); + + var owner = new CanonicalGameplayIssuerPartitionBuildRepository(testSchema.dsl()); + var plan = owner.prepareInitialBuildPlan(intent.operationId(), requestId); + + assertThat(plan.state()).isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.BLOCKED); + assertThat(plan.coverageGenerationState()) + .isEqualTo( + CanonicalGameplayIssuerPartitionBuildPlan.CoverageGenerationState.NOT_YET_ISSUED); + assertThat(plan.coverageGeneration()).isNull(); + assertThat(plan.cohortRows()) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::rowOrdinal) + .containsExactlyElementsOf( + intent.cohortRows().stream() + .map(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::rowOrdinal) + .toList()); + assertThat(plan.cohortRows()) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::kind) + .containsExactlyElementsOf( + intent.cohortRows().stream() + .map(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::kind) + .toList()); + assertThat(plan.cohortRows()) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceKey) + .containsExactlyElementsOf( + intent.cohortRows().stream() + .map(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceKey) + .toList()); + assertThat(plan.cohortRows()) + .extracting( + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceInventoryRevision) + .containsExactlyElementsOf( + intent.cohortRows().stream() + .map( + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow + ::sourceInventoryRevision) + .toList()); + assertThat(plan.cohortRows()) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceRowJson) + .containsExactlyElementsOf( + intent.cohortRows().stream() + .map(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceRowJson) + .toList()); + assertThat(plan.cohortRows()) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceRowDigest) + .containsExactlyElementsOf( + intent.cohortRows().stream() + .map(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceRowDigest) + .toList()); + var retainedBindingRow = + plan.cohortRows().stream() + .filter( + row -> + row.kind() == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.BINDING) + .findFirst() + .orElseThrow(); + assertThat(retainedBindingRow.sourceRowJson()).contains("TERMINAL_UNRESOLVED"); + assertThat(plan.blockers()) + .anySatisfy( + blocker -> { + assertThat(blocker.sourceRowOrdinal()).isEqualTo(retainedBindingRow.rowOrdinal()); + assertThat(blocker.sourceRowDigest()) + .isEqualTo(retainedBindingRow.sourceRowDigest()); + assertThat(blocker.code()) + .isEqualTo( + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode + .UNREPRESENTABLE_BINDING); + }); + for (UUID reservationId : + List.of(unlinkedBoundReservationId, unlinkedReleasePendingReservationId)) { + var reservationRow = + plan.cohortRows().stream() + .filter( + row -> + row.kind() + == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind + .RESERVATION + && row.sourceKey().equals(reservationId.toString())) + .findFirst() + .orElseThrow(); + assertThat(plan.blockers()) + .anySatisfy( + blocker -> { + assertThat(blocker.sourceRowOrdinal()).isEqualTo(reservationRow.rowOrdinal()); + assertThat(blocker.sourceRowDigest()).isEqualTo(reservationRow.sourceRowDigest()); + assertThat(blocker.code()) + .isEqualTo( + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode + .CONFLICTING_RESERVATION_LINK); + }); + } + assertThatThrownBy( + () -> + testSchema + .dsl() + .transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + return new CanonicalGameplayIssuerPartitionBuildRepository(transaction) + .readPreparedPlanInTransaction( + transaction, intent.operationId(), requestId); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "Blocked issuer partition build plan cannot issue member operations"); + assertThat( + testSchema + .dsl() + .fetchSingle( + "SELECT count(*) FROM" + + " game_session_canonical_issuer_bootstrap_member_operation") + .get(0, Long.class)) + .isZero(); + assertThat( + testSchema + .dsl() + .fetchSingle( + "SELECT count(*) FROM" + + " game_session_canonical_issuer_bootstrap_member_op_counter") + .get(0, Long.class)) + .isZero(); + assertThat(rowImages(testSchema.dsl(), "game_session_canonical_gameplay_binding_inventory")) + .containsExactlyElementsOf(bindingsBeforePlan); + assertThat(rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_reservation")) + .containsExactlyElementsOf(reservationsBeforePlan); + assertThat(rowImages(testSchema.dsl(), "game_session_canonical_binding_transition")) + .containsExactlyElementsOf(transitionsBeforePlan); + } finally { + dropSchema(testSchema.schema()); + } + } + @Test void initialBootstrapBlocksReservationsFromAnotherLayoutOrNoncanonicalOriginalPartition() { TestSchema layoutSchema = newTestSchema("gs_issuer_build_layout_init_"); @@ -960,12 +1171,6 @@ void initialBootstrapCountsNonterminalReservationCapacityAndExcludesReleasedRows overCapacityPartition.equals(BigInteger.ZERO) ? BigInteger.ONE : BigInteger.ZERO; List capacitySessionIds = new java.util.ArrayList<>(List.of(UUID.fromString(prepared.candidate().sessionId()))); - testSchema - .dsl() - .execute( - "UPDATE game_session_canonical_issuer_partition_reservation" - + " SET lifecycle = 'BOUND' WHERE reservation_id = ?", - prepared.issuerReservationId()); UUID reservedReservationId = UUID.randomUUID(); UUID reservedSessionId = @@ -985,24 +1190,24 @@ void initialBootstrapCountsNonterminalReservationCapacityAndExcludesReleasedRows false, "RESERVED", reservedSessionId); - UUID releasePendingReservationId = UUID.randomUUID(); - UUID releasePendingSessionId = + UUID otherReservedReservationId = UUID.randomUUID(); + UUID otherReservedSessionId = sessionUuidForPartition( prepared.candidate(), partitionCount, otherPartition, capacitySessionIds); - capacitySessionIds.add(releasePendingSessionId); + capacitySessionIds.add(otherReservedSessionId); insertReservationOnly( testSchema.dsl(), prepared.candidate(), prepared.inventoryRevision(), - releasePendingReservationId, + otherReservedReservationId, originalOperationFence, originalCoverageFence, LAYOUT_VERSION, partitionCount, partitionCapacity, false, - "RELEASE_PENDING", - releasePendingSessionId); + "RESERVED", + otherReservedSessionId); UUID releasedReservationId = UUID.randomUUID(); UUID releasedSessionId = sessionUuidForPartition( @@ -1081,7 +1286,7 @@ void initialBootstrapCountsNonterminalReservationCapacityAndExcludesReleasedRows assertThat(plan.memberWorks()).hasSize(4); assertThat(plan.memberWorks()) .extracting(CanonicalGameplayIssuerPartitionBuildPlan.MemberWork::reservationLifecycle) - .containsExactlyInAnyOrder("BOUND", "RESERVED", "RELEASE_PENDING", "RELEASED"); + .containsExactlyInAnyOrder("RESERVED", "RESERVED", "RESERVED", "RELEASED"); assertThat(plan.memberWorks()) .allSatisfy( work -> { @@ -1126,12 +1331,12 @@ void initialBootstrapCountsNonterminalReservationCapacityAndExcludesReleasedRows .filter(work -> work.reservationId().equals(reservedReservationId)) .findFirst() .orElseThrow(); - var releasePendingWork = + var otherReservedWork = plan.memberWorks().stream() - .filter(work -> work.reservationId().equals(releasePendingReservationId)) + .filter(work -> work.reservationId().equals(otherReservedReservationId)) .findFirst() .orElseThrow(); - var boundWork = + var preparedWork = plan.memberWorks().stream() .filter(work -> work.reservationId().equals(prepared.issuerReservationId())) .findFirst() @@ -1142,12 +1347,12 @@ void initialBootstrapCountsNonterminalReservationCapacityAndExcludesReleasedRows assertThat(reservedWork.reservationLifecycle()).isEqualTo("RESERVED"); assertThat(reservedWork.countsTowardCapacity()).isTrue(); assertThat(reservedWork.originalPartitionId()).isEqualTo(overCapacityPartition); - assertThat(releasePendingWork.reservationLifecycle()).isEqualTo("RELEASE_PENDING"); - assertThat(releasePendingWork.countsTowardCapacity()).isTrue(); - assertThat(releasePendingWork.originalPartitionId()).isEqualTo(otherPartition); - assertThat(boundWork.reservationLifecycle()).isEqualTo("BOUND"); - assertThat(boundWork.countsTowardCapacity()).isTrue(); - assertThat(boundWork.originalPartitionId()).isEqualTo(overCapacityPartition); + assertThat(otherReservedWork.reservationLifecycle()).isEqualTo("RESERVED"); + assertThat(otherReservedWork.countsTowardCapacity()).isTrue(); + assertThat(otherReservedWork.originalPartitionId()).isEqualTo(otherPartition); + assertThat(preparedWork.reservationLifecycle()).isEqualTo("RESERVED"); + assertThat(preparedWork.countsTowardCapacity()).isTrue(); + assertThat(preparedWork.originalPartitionId()).isEqualTo(overCapacityPartition); assertThat(plan.blockers()).hasSize(5); assertThat(plan.blockers()) @@ -1164,7 +1369,7 @@ void initialBootstrapCountsNonterminalReservationCapacityAndExcludesReleasedRows .filter(blocker -> blocker.sourceRowOrdinal() == work.reservationSourceRowOrdinal()) .map(CanonicalGameplayIssuerPartitionBuildPlan.Blocker::code) .toList(); - if (work.reservationId().equals(releasePendingWork.reservationId())) { + if (work.reservationId().equals(otherReservedWork.reservationId())) { assertThat(workBlockerCodes) .containsExactly( CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode @@ -1353,6 +1558,147 @@ private static LayoutFixture pendingLayoutFixture( ISSUER, issuerGeneration, eventBytes, eventBytes); } + private static CanonicalGameplayAdmissionAbortSource createActualRetainedTerminalUnresolved( + TestSchema testSchema) { + var runtimeTarget = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( + testSchema.dataSource(), TENANT_ID); + CanonicalGameplayBindingIdentity candidate = + new CanonicalGameplayBindingIdentity( + ACCOUNT_ID, + runtimeTarget.canonicalTenantId(), + runtimeTarget.playableStateNamespaceId(), + CHARACTER_ID, + runtimeTarget.playableStateScope(), + runtimeTarget.gameInstanceUuid(), + runtimeTarget.gameInstanceId(), + UUID.randomUUID().toString(), + REGION_ID, + BigInteger.valueOf(12), + ISSUER, + BigInteger.valueOf(7), + LAYOUT_VERSION, + PARTITION_COUNT, + PARTITION_CAPACITY); + UUID transitionId = UUID.randomUUID(); + var reservation = + new CanonicalIssuerReservationFenceEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + BigInteger.ONE, + BigInteger.TWO, + BigInteger.ONE); + var inventory = new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); + inventory.prepare( + new CanonicalGameplayBindingTransitionRequest( + transitionId, UUID.randomUUID(), candidate, reservation, null, null)); + var prepared = inventory.readProvisionalCasEvidence(transitionId); + CanonicalPlayableTarget target = runtimeTarget.playableTarget(); + var lease = + controlledLeaseEvidence(candidate, prepared.transition().bindingGeneration(), target); + inventory.markProvisional( + prepared, + new CanonicalGameplayAdmissionDecision( + transitionId, + lease, + candidate, + prepared.transition().bindingGeneration(), + null, + target)); + var source = inventory.readFirstNewAdmissionAbortSource(transitionId); + return inventory.recordFirstNewAccountAbort(source, UUID.randomUUID()); + } + + private static AccountGameplayAdmissionLeaseEvidence controlledLeaseEvidence( + CanonicalGameplayBindingIdentity candidate, + BigInteger bindingGeneration, + CanonicalPlayableTarget target) { + long now = System.currentTimeMillis(); + String nowSeconds = Long.toString(now / 1000L); + Map carrier = new java.util.LinkedHashMap<>(); + carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + carrier.put("schemaVersion", "1"); + carrier.put("mode", "PUBLIC_PRODUCTION"); + carrier.put("leaseKind", AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING.name()); + carrier.put("targetNamespace", target.targetNamespace()); + carrier.put( + "callerWorkload", + "spiffe://firemud/ns/" + target.targetNamespace() + "/sa/game-session-service"); + carrier.put("requestId", UUID.randomUUID().toString()); + carrier.put("leaseId", UUID.randomUUID().toString()); + carrier.put("leaseFence", "1"); + carrier.put( + "bindingScope", + Map.ofEntries( + Map.entry("accountId", candidate.accountId().toString()), + Map.entry("tenantId", candidate.tenantId().toString()), + Map.entry("realmId", target.realmId().toString()), + Map.entry("worldSlug", target.worldSlug()), + Map.entry("realmSlug", target.realmSlug()), + Map.entry("playableStateNamespaceId", target.playableStateNamespaceId().toString()), + Map.entry("playableStateScope", target.playableStateScope()), + Map.entry("gameInstanceId", target.canonicalGameInstanceId().toString()), + Map.entry("characterId", candidate.characterId().toString()), + Map.entry("sessionId", candidate.sessionId()), + Map.entry("bindingGeneration", bindingGeneration.toString()), + Map.entry("catalogRevision", Long.toString(target.catalogRevision())), + Map.entry("pointerVersion", Long.toString(target.pointerVersion())), + Map.entry("regionId", candidate.regionId().toString()), + Map.entry("regionEpoch", candidate.regionEpoch().toString()))); + carrier.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", candidate.issuerAuthGeneration().toString(), + "accountAuthorityGeneration", "1", + "tenantAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1"), + "membershipAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1"), + "privateRealmGrantVersions", List.of())); + carrier.put("issuanceFence", "1"); + carrier.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", "ACTIVE", + "membershipVersion", Map.of(candidate.tenantId().toString(), "1"), + "membershipAuthorityGeneration", "1")); + String prefix = "account:auth-authority:v1:"; + List> checkpoints = new java.util.ArrayList<>(); + for (String stream : + List.of( + "account/" + candidate.accountId(), + "issuer/" + candidate.issuerId(), + "membership/" + candidate.accountId() + "/" + candidate.tenantId(), + "tenant/" + candidate.tenantId())) { + checkpoints.add( + Map.of( + "outboxStreamKey", + prefix + stream, + "outboxSequence", + stream.startsWith("membership/") || stream.startsWith("tenant/") ? "1" : "0")); + } + carrier.put("outboxCheckpoints", checkpoints); + carrier.put( + "tokenIdentityEvidence", + Map.ofEntries( + Map.entry("accountId", candidate.accountId().toString()), + Map.entry("operationId", UUID.randomUUID().toString()), + Map.entry("issuanceRequestId", UUID.randomUUID().toString()), + Map.entry("tokenJti", UUID.randomUUID().toString()), + Map.entry("tokenSHA256", "a".repeat(64)), + Map.entry("tokenProfile", "game-session-account-delegation"), + Map.entry("tokenGeneration", "1"), + Map.entry("issuanceFence", "1"), + Map.entry("tokenIdentityFence", "1"), + Map.entry("issuedAt", nowSeconds), + Map.entry("notBefore", nowSeconds), + Map.entry("expiresAt", Long.toString(now / 1000L + 60L)))); + carrier.put("evaluatedAt", Long.toString(now)); + carrier.put( + "expiresAt", + Long.toString(now + AccountGameplayAdmissionLeaseEvidence.MAX_DURATION_MILLIS)); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + } + private static CanonicalGameplayBindingTransitionSnapshot prepareActualBinding( CanonicalGameplayBindingInventoryRepository inventory) { return prepareActualBinding( From 22aeb60eaa12df3332f0168c1501465b0e8f5736 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:49:52 +1300 Subject: [PATCH 20/34] fix: refuse unprojectable issuer partition operations --- .../player-access-and-session.md | 2 + ...IssuerBindingLocalOperationRepository.java | 32 ++++ ...meplayIssuerLayoutBootstrapRepository.java | 37 +---- ...ameplayIssuerPartitionBuildRepository.java | 70 ++++---- ...icalGameplayIssuerSourceEventVerifier.java | 52 ++++++ ...calOperationRepositoryIntegrationTest.java | 72 +++++++- ...rtitionBuildRepositoryIntegrationTest.java | 154 ++++++++++++++++++ 7 files changed, 355 insertions(+), 64 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerSourceEventVerifier.java diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 32a33bc15e..46385b4d90 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for player access and session. Ca ### Canonical NEW admission components +The local issuer owners now reject plans that exceed the executable 256-member-operation bound per partition, including retained `RELEASED` lineage independently of logical active capacity. A blocked plan retains its complete cohort and planned work; physical preparation refuses before allocating operation rows. Fresh ordinary NEW registration also checks the same nonretired local-operation set under the inventory lock before allocating new identities or rows, while exact retries retain their original operation at the bound. Both bootstrap owners use one strict Account issuer source-event verifier. R791 freshly passes the four PostgreSQL boundary cases: 256 allowed, both 257-reservation overflow forms blocked, and ordinary registration refusal/retry with unchanged durable state. R793 then freshly passes all 26 selected PostgreSQL cases across the plan, ordinary-operation and intent owners, plus affected production/integration static analysis, formatting and documentation checks. This is focused owner proof, not a complete service-suite or public admission result. Default registration, external source custody and admission limits remain unchanged. + The Account gameplay-admission lease and the unregistered Game Session receiver remain separate authority boundaries. The unregistered Account verifier uses the pinned trusted JWKS and fixed gameplay-delegation profile, selects the current `COMMITTED`/`ACTIVE` issuance by verified JTI, and compares the full immutable token identity, hash and authority; it retains no presented JWT and makes no membership, entitlement or lease decision. Focused acquisition proof joins the exact recovered JWT to actual current issuance, physical Coordination Redis and the same-connection Account source graph, preserving the original pending lease on retry. R494 freshly passes 104 Account unit cases and eight selected PostgreSQL/Redis cases, with affected static analysis and formatting. Its manual TLS receiver exercises all four generated RPCs with the exact recovered Account JWT and current issuance/registry and SQL sources, then performs PostgreSQL 18 physical COMMIT and independent durable original-ACK insertion/readback. The original lease attempt and ACK are immutable. The original physical-commit executor retains focused PostgreSQL component proof, and the Game Session lease client has controlled mTLS proof; the retained PostgreSQL 18 receipt-reader denial remains unchanged. The reverse Game Session target/decision response and protected signer/materializer evidence remain controlled. Exact metadata and cleanup-obligation recovery revalidate the current caller/global Account/token under Account-first SQL locks without requiring a superseded tenant admission baseline; new acquisition and first finalization retain full tenant-source checks. These results do not prove genuine Game Session authority, cleanup delivery, final controller admission, production custody or activation. Token-retirement, orphan-cleanup delivery and admitted binding remain open. The Game Session canonical inventory now retains Account's exact issuer string through the forward V1024→V1025 conversion. R488 passes 19 selected PostgreSQL cases, including populated-row migration preservation, restart, canonical writes, and refusal by the typed reader to reinterpret retained UUID issuers. This proves storage identity conversion only; issuer ownership and admission remain unqualified. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java index f4211b470c..601b0c185d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java @@ -243,6 +243,7 @@ private CanonicalGameplayBindingTransitionRequest resolveTransitionRequestInTran UUID accountIndexFence; CanonicalIssuerReservationFenceEvidence reservationEvidence; if (priorByTransition == null) { + requirePhysicalOperationSlotAvailable(transaction, request.candidate(), anchor); accountIndexFence = freshNonNilUuid(); reservationEvidence = new CanonicalIssuerReservationFenceEvidence( @@ -267,6 +268,37 @@ private CanonicalGameplayBindingTransitionRequest resolveTransitionRequestInTran null); } + private static void requirePhysicalOperationSlotAvailable( + DSLContext transaction, + CanonicalGameplayBindingIdentity candidate, + CanonicalGameplayIssuerInstalledAnchor anchor) { + // The request factory runs under the inventory/source locks, before preparing any candidate + // rows or allocating identities. Match the projection owner's nonretired local-operation set; + // RELEASED alone does not free a physical slot, and exact registration retries bypass this + // gate. + BigInteger partitionId = candidate.bindingRef().partitionId(anchor.partitionCount()); + Record countRow = + Objects.requireNonNull( + transaction.fetchOne( + "SELECT count(*) FROM " + + OPERATION + + " operation WHERE operation.issuer_id = ? AND operation.partition_id = ?" + + " AND NOT EXISTS (SELECT 1 FROM" + + " game_session_canonical_issuer_binding_local_retirement retirement" + + " WHERE retirement.original_local_operation_id = operation.operation_id" + + " AND retirement.status = 'RETIRED')", + ISSUER, + decimal(partitionId)), + "Expected local issuer operation count row"); + long operationCount = + Objects.requireNonNull( + countRow.get(0, Long.class), "Expected local issuer operation count"); + if (operationCount + >= CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_MEMBER_OPERATIONS) { + throw conflict("The local partition operation set has reached the physical owner bound"); + } + } + private CanonicalGameplayIssuerBindingLocalOperation recordOrReplayInTransaction( CanonicalGameplayIssuerBindingLocalOperation.Request request, DSLContext transaction, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java index 97b586ef5e..5aa2612c4d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java @@ -3,8 +3,6 @@ import java.math.BigDecimal; import java.math.BigInteger; import java.nio.ByteBuffer; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -15,9 +13,6 @@ import java.util.List; import java.util.Objects; import java.util.UUID; -import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; -import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.IssuerEvent; -import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.SourceEvent; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationDisposition; import org.jooq.DSLContext; @@ -197,30 +192,14 @@ private static void requireValidSourceEvent( String issuerId, TrustedAccountIssuerCheckpoint checkpoint) { byte[] eventBytes = checkpoint.latestEventBytes(); if (eventBytes == null) return; - final String eventJson; - try { - eventJson = - StandardCharsets.UTF_8 - .newDecoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .decode(ByteBuffer.wrap(eventBytes)) - .toString(); - } catch (CharacterCodingException malformed) { - throw conflict("Controlled Account issuer source event is not exact UTF-8"); - } - final SourceEvent parsed; - try { - parsed = AccountAuthoritySourceEventV1Codec.verify(eventJson); - } catch (RuntimeException malformed) { - throw conflict("Controlled Account issuer source event is not codec-verified"); - } - if (!(parsed instanceof IssuerEvent event) - || !event.issuerId().equals(issuerId) - || !new BigInteger(event.issuerAuthGeneration()).equals(checkpoint.issuerAuthGeneration()) - || !Arrays.equals(event.canonicalJsonUtf8(), eventBytes)) { - throw conflict("Controlled Account issuer event differs from its exact checkpoint scope"); - } + CanonicalGameplayIssuerSourceEventVerifier.requireValid( + issuerId, + checkpoint.issuerAuthGeneration(), + eventBytes, + "Controlled Account issuer source event is not exact UTF-8", + "Controlled Account issuer source event is not codec-verified", + "Controlled Account issuer event differs from its exact checkpoint scope", + CanonicalGameplayIssuerLayoutBootstrapRepository::conflict); } private static void requireSameTrustedInputs( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java index 4c2487fbe9..827612ed42 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java @@ -6,8 +6,6 @@ import java.math.BigDecimal; import java.math.BigInteger; import java.nio.ByteBuffer; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -22,8 +20,6 @@ import java.util.Objects; import java.util.Set; import java.util.UUID; -import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; -import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.IssuerEvent; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; @@ -816,6 +812,30 @@ private static DerivedPlan derivePlan( .toList(); requireIssuerSourceLinks( cohortRows, reservations, bindingOrdinalByReservation, bindings, blockers); + // Every reservation, including RELEASED lineage, needs a physical bootstrap operation. + // Keep this finite wire bound separate from logical nonterminal reservation capacity. + Map> physicalByPartition = new HashMap<>(); + for (PlannedReservation item : planned) { + physicalByPartition + .computeIfAbsent(item.plannedPartitionId(), ignored -> new ArrayList<>()) + .add(item); + } + Set physicallyOversizedPartitions = new HashSet<>(); + for (var entry : physicalByPartition.entrySet()) { + if (entry.getValue().size() + > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_MEMBER_OPERATIONS) { + physicallyOversizedPartitions.add(entry.getKey()); + entry + .getValue() + .forEach( + item -> + blockers.add( + new PlanBlocker( + item.reservation().rowOrdinal(), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode + .PARTITION_CAPACITY_EXCEEDED))); + } + } Map> countedByPartition = new HashMap<>(); List countedReservations = planned.stream() @@ -826,10 +846,12 @@ private static DerivedPlan derivePlan( .computeIfAbsent(item.plannedPartitionId(), ignored -> new ArrayList<>()) .add(item); } - for (List partitionReservations : countedByPartition.values()) { - if (BigInteger.valueOf(partitionReservations.size()) - .compareTo(intent.layoutDescriptor().partitionCapacity()) - > 0) { + for (var entry : countedByPartition.entrySet()) { + List partitionReservations = entry.getValue(); + if (!physicallyOversizedPartitions.contains(entry.getKey()) + && BigInteger.valueOf(partitionReservations.size()) + .compareTo(intent.layoutDescriptor().partitionCapacity()) + > 0) { partitionReservations.forEach( item -> blockers.add( @@ -1752,30 +1774,14 @@ private static Record lockIntent(DSLContext transaction, UUID operationId) { private static void requireValidSourceEvent( String issuerId, BigInteger generation, byte[] eventBytes) { - final String eventJson; - try { - eventJson = - StandardCharsets.UTF_8 - .newDecoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .decode(ByteBuffer.wrap(eventBytes)) - .toString(); - } catch (CharacterCodingException malformed) { - throw conflict("Persisted Account issuer source event is not exact UTF-8"); - } - final AccountAuthoritySourceEventV1Codec.SourceEvent parsed; - try { - parsed = AccountAuthoritySourceEventV1Codec.verify(eventJson); - } catch (RuntimeException malformed) { - throw conflict("Persisted Account issuer source event is not codec-verified"); - } - if (!(parsed instanceof IssuerEvent event) - || !event.issuerId().equals(issuerId) - || !new BigInteger(event.issuerAuthGeneration()).equals(generation) - || !Arrays.equals(event.canonicalJsonUtf8(), eventBytes)) { - throw conflict("Persisted Account issuer source event differs from its exact checkpoint"); - } + CanonicalGameplayIssuerSourceEventVerifier.requireValid( + issuerId, + generation, + eventBytes, + "Persisted Account issuer source event is not exact UTF-8", + "Persisted Account issuer source event is not codec-verified", + "Persisted Account issuer source event differs from its exact checkpoint", + CanonicalGameplayIssuerPartitionBuildRepository::conflict); } private static JsonNode parseObject(String raw) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerSourceEventVerifier.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerSourceEventVerifier.java new file mode 100644 index 0000000000..45c40f299e --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerSourceEventVerifier.java @@ -0,0 +1,52 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.function.Function; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.IssuerEvent; + +/** Shared strict verification for Account issuer source-event checkpoint bytes. */ +final class CanonicalGameplayIssuerSourceEventVerifier { + private CanonicalGameplayIssuerSourceEventVerifier() {} + + static void requireValid( + String issuerId, + BigInteger generation, + byte[] eventBytes, + String invalidUtf8Message, + String invalidCodecMessage, + String checkpointMismatchMessage, + Function failure) { + final String eventJson; + try { + eventJson = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(eventBytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw failure.apply(invalidUtf8Message); + } + + final AccountAuthoritySourceEventV1Codec.SourceEvent parsed; + try { + parsed = AccountAuthoritySourceEventV1Codec.verify(eventJson); + } catch (RuntimeException malformed) { + throw failure.apply(invalidCodecMessage); + } + + if (!(parsed instanceof IssuerEvent event) + || !event.issuerId().equals(issuerId) + || !new BigInteger(event.issuerAuthGeneration()).equals(generation) + || !Arrays.equals(event.canonicalJsonUtf8(), eventBytes)) { + throw failure.apply(checkpointMismatchMessage); + } + } +} 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 bdc5c5792c..f9eeb64a95 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 @@ -424,6 +424,62 @@ void registersOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() .isEqualTo(2L); } + @Test + void ordinaryNewPhysicalOperationBoundRefuses257thBeforePreparationAndRetainsExact256thRetry() { + DSLContext dsl = schema.dsl(); + establishActualLegacyDisposition(dsl); + BigInteger capacity = BigInteger.valueOf(512); + UUID bootstrapRequestId = UUID.randomUUID(); + var source = sourceCheckpoint(BigInteger.valueOf(7)); + var intent = + new CanonicalGameplayIssuerLayoutBootstrapRepository(dsl) + .beginInitialBootstrapIntent(bootstrapRequestId, descriptor(capacity), source); + migrateRemaining(schema); + var currentState = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + intent.sourceCheckpoint(), stableIncarnation("physical-operation-bound")); + initialCoverageOwner(dsl, () -> currentState) + .completeInitialBootstrap(intent.operationId(), bootstrapRequestId); + var repository = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, () -> currentState); + // Every retained registration is created by the actual SQL owner. No local projection or + // release/retirement is fabricated; these are pending operations under controlled sources. + for (int index = 0; index < 255; index++) { + repository.beginOrResumeOrdinaryNew( + request( + "physical-bound-request-" + index, + "physical-bound-transition-" + index, + identityWithLayout("physical-bound-" + index, LAYOUT_VERSION, capacity))); + } + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isEqualTo(255L); + var lastRequest = + request( + "physical-bound-request-255", + "physical-bound-transition-255", + identityWithLayout("physical-bound-255", LAYOUT_VERSION, capacity)); + var last = repository.beginOrResumeOrdinaryNew(lastRequest); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isEqualTo(256L); + String beforeRefusal = localRegistrationImage(dsl); + String anchorBefore = anchorImage(dsl); + String proofBefore = proofImage(dsl); + assertThatThrownBy( + () -> + repository.beginOrResumeOrdinaryNew( + request( + "physical-bound-request-256", + "physical-bound-transition-256", + identityWithLayout("physical-bound-256", LAYOUT_VERSION, capacity)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("physical owner bound"); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusal); + var retry = repository.beginOrResumeOrdinaryNew(lastRequest); + assertThat(retry.operationId()).isEqualTo(last.operationId()); + assertThat(retry.exactMemberValueBytes()).containsExactly(last.exactMemberValueBytes()); + assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusal); + assertThat(anchorImage(dsl)).isEqualTo(anchorBefore); + assertThat(proofImage(dsl)).isEqualTo(proofBefore); + } + private CanonicalGameplayIssuerBootstrapCoverageOwner initialCoverageOwner( DSLContext dsl, CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource source) { @@ -438,6 +494,11 @@ private CanonicalGameplayIssuerBootstrapCoverageOwner initialCoverageOwner( private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor descriptor() { + return descriptor(PARTITION_CAPACITY); + } + + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor + descriptor(BigInteger capacity) { String exact = "issuer-layout-descriptor/v1|" + ISSUER @@ -446,14 +507,14 @@ private CanonicalGameplayIssuerBootstrapCoverageOwner initialCoverageOwner( + "|" + PARTITION_COUNT + "|" - + PARTITION_CAPACITY + + capacity + "|" + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY; return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor( ISSUER, LAYOUT_VERSION, PARTITION_COUNT, - PARTITION_CAPACITY, + capacity, CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY, exact.getBytes(StandardCharsets.UTF_8)); } @@ -546,6 +607,11 @@ private static CanonicalGameplayBindingIdentity identityForAccount(String seed, private static CanonicalGameplayBindingIdentity identityWithLayout( String seed, BigInteger layoutVersion) { + return identityWithLayout(seed, layoutVersion, PARTITION_CAPACITY); + } + + private static CanonicalGameplayBindingIdentity identityWithLayout( + String seed, BigInteger layoutVersion, BigInteger capacity) { return new CanonicalGameplayBindingIdentity( uuid(seed + "-account"), uuid(seed + "-tenant"), @@ -561,7 +627,7 @@ private static CanonicalGameplayBindingIdentity identityWithLayout( BigInteger.valueOf(7), layoutVersion, PARTITION_COUNT, - PARTITION_CAPACITY); + capacity); } private static CanonicalGameplayBindingIdentity sameControllerDifferentBinding( 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 693de911f6..88a041c16e 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 @@ -1417,6 +1417,160 @@ void initialBootstrapCountsNonterminalReservationCapacityAndExcludesReleasedRows } } + @Test + void initialBootstrapAllows256PhysicalReservationsIncludingReleasedLineage() { + assertPhysicalPartitionPlanBoundary(256, BigInteger.ONE, "RELEASED", false); + } + + @Test + void initialBootstrapBlocks257PhysicalReservationsDespiteReleasedLogicalExclusion() { + assertPhysicalPartitionPlanBoundary(257, BigInteger.ONE, "RELEASED", true); + } + + @Test + void initialBootstrapBlocks257PhysicalReservationsDespiteLargerLogicalCapacity() { + assertPhysicalPartitionPlanBoundary(257, BigInteger.valueOf(512), "RESERVED", true); + } + + private static void assertPhysicalPartitionPlanBoundary( + int reservationCount, BigInteger partitionCapacity, String extraLifecycle, boolean blocked) { + TestSchema testSchema = newTestSchema("gs_build_physical_bound_"); + try { + establishActualLegacyDisposition(testSchema.dsl()); + var prepared = + prepareActualBinding( + new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()), + LAYOUT_VERSION, + BigInteger.ONE, + partitionCapacity, + BigInteger.valueOf(17), + BigInteger.valueOf(19)); + for (int index = 1; index < reservationCount; index++) { + insertReservationOnly( + testSchema.dsl(), + prepared.candidate(), + prepared.inventoryRevision(), + UUID.randomUUID(), + BigInteger.valueOf(17), + BigInteger.valueOf(19), + LAYOUT_VERSION, + BigInteger.ONE, + partitionCapacity, + false, + extraLifecycle, + UUID.randomUUID()); + } + var checkpoint = sourceCheckpoint(BigInteger.valueOf(7)); + UUID requestId = UUID.randomUUID(); + var intent = + new CanonicalGameplayIssuerLayoutBootstrapRepository(testSchema.dsl()) + .beginInitialBootstrapIntent( + requestId, + descriptor(LAYOUT_VERSION, BigInteger.ONE, partitionCapacity), + checkpoint); + List reservationsBefore = + rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_reservation"); + var owner = new CanonicalGameplayIssuerPartitionBuildRepository(testSchema.dsl()); + var plan = owner.prepareInitialBuildPlan(intent.operationId(), requestId); + assertThat(plan.state()) + .isEqualTo( + blocked + ? CanonicalGameplayIssuerPartitionBuildPlan.State.BLOCKED + : CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED); + assertThat(plan.memberWorks()).hasSize(reservationCount); + assertThat(plan.memberWorks()) + .filteredOn(CanonicalGameplayIssuerPartitionBuildPlan.MemberWork::countsTowardCapacity) + .hasSize(extraLifecycle.equals("RELEASED") ? 1 : reservationCount); + assertThat(plan.cohortRows()) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceRowJson) + .containsExactlyElementsOf( + intent.cohortRows().stream() + .map(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceRowJson) + .toList()); + var physicalOwner = + new CanonicalGameplayIssuerBootstrapMemberOperationRepository(testSchema.dsl()); + if (blocked) { + assertThat(plan.blockers()).hasSize(reservationCount); + assertThat(plan.blockers()) + .extracting(CanonicalGameplayIssuerPartitionBuildPlan.Blocker::code) + .containsOnly( + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode.PARTITION_CAPACITY_EXCEEDED); + assertThatThrownBy( + () -> + physicalOwner.preparePartitionWork( + intent.operationId(), + requestId, + BigInteger.ZERO, + checkpoint, + physicalBoundaryIncarnation())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "Blocked issuer partition build plan cannot issue member operations"); + assertThatThrownBy( + () -> + physicalOwner.beginOrResumePendingPhysicalProof( + intent.operationId(), + requestId, + 0, + checkpoint, + physicalBoundaryIncarnation())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "Blocked issuer partition build plan cannot issue member operations"); + assertThat( + rowImages( + testSchema.dsl(), "game_session_canonical_issuer_bootstrap_member_operation")) + .isEmpty(); + assertThat( + rowImages( + testSchema.dsl(), "game_session_canonical_issuer_partition_mutation_head")) + .isEmpty(); + } else { + assertThat(plan.blockers()).isEmpty(); + assertThat( + physicalOwner + .preparePartitionWork( + intent.operationId(), + requestId, + BigInteger.ZERO, + checkpoint, + physicalBoundaryIncarnation()) + .memberOperations()) + .hasSize(reservationCount); + } + var retry = owner.prepareInitialBuildPlan(intent.operationId(), requestId); + assertThat(retry.buildOperationId()).isEqualTo(plan.buildOperationId()); + assertThat(retry.planDigest()).isEqualTo(plan.planDigest()); + assertThat(retry.blockers()).containsExactlyElementsOf(plan.blockers()); + assertThat(rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_reservation")) + .containsExactlyElementsOf(reservationsBefore); + } finally { + dropSchema(testSchema.schema()); + } + } + + private static CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation + physicalBoundaryIncarnation() { + String digest = "sha256:" + "a".repeat(64); + return new CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation( + "controlled-physical-bound-attestor", + digest, + new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "controlled-deployment", + "generation", + List.of("node"), + "redis-build", + "lua-registry", + digest, + "READY", + "boot", + "startup", + "storage", + "aof"), + digest, + digest); + } + private static void assertBlockedInitialReservation( CanonicalGameplayIssuerPartitionBuildRepository owner, CanonicalGameplayIssuerPartitionBuildPlan plan, From 1c68113a96acf10f9a3bb7446ce39bcf59d3b0ef Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 15:12:23 +1300 Subject: [PATCH 21/34] Reuse qualified issuer partition proofs and tighten abort composition assertions --- ...nitiveAbortCompositionIntegrationTest.java | 4 +- ...ssuerBindingLocalProjectionRepository.java | 58 ++++++++++++------- 2 files changed, 39 insertions(+), 23 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java index 822dd2257c..b08c7c313c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java @@ -463,7 +463,7 @@ void actualAccountAbortedOrdinaryIssuerMemberReleaseHasExactReadbackRetryAndFree + " WHERE transition_id = ? AND obligation_ordinal = 0", session.gs.transitionId()) .get("status", String.class)) - .isIn("REQUIRED", "ACKNOWLEDGED"); + .isEqualTo("REQUIRED"); assertThat( session .gs @@ -479,7 +479,7 @@ void actualAccountAbortedOrdinaryIssuerMemberReleaseHasExactReadbackRetryAndFree assertThat(session.gs.preparedLocalCountedReservations()).isEqualTo(java.math.BigInteger.TWO); var thirdReadback = session.gs.projectOtherControllerNew("freed-capacity-other-controller"); assertThat(thirdReadback.operationId()).isEqualTo(thirdOperationId); - assertThat(thirdReadback.scriptOutcome()).isIn(1L, 2L, 3L); + assertThat(thirdReadback.scriptOutcome()).isEqualTo(1L); byte[] retainedReadback = released.exactPhysicalReadbackFieldSetBytes(); var releaseReplay = session.gs.prepareIssuerRelease(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java index 6ac20c1267..eb2056240a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java @@ -183,6 +183,7 @@ private PreparedPartitionWork prepareInTransaction( row, anchor, target, + proofsByPartition, requireCurrentTargetAccountControl && uuid(row, "operation_id").equals(target.operationId())); if (!localOperationIds.add(entry.operationId()) @@ -197,25 +198,8 @@ private PreparedPartitionWork prepareInTransaction( BigInteger partitionId = entry.memberValue().reservation().partitionId(); var baseline = proofsByPartition.get(partitionId); if (baseline == null) { - baseline = - CanonicalGameplayIssuerBootstrapCoverageRepository.readInstalledAnchorPartitionProof( - transaction, anchor, partitionId); + baseline = readQualifiedBaseline(transaction, anchor, partitionId); proofsByPartition.put(partitionId, baseline); - Map baselineFields = - CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( - baseline.exactPhysicalFieldSetBytes()); - requireQualifiedBaseline(anchor, baseline, baselineFields); - CanonicalGameplayIssuerPartitionMutationRepository.PartitionMutationHead partitionHead = - CanonicalGameplayIssuerPartitionMutationRepository.readHeadInTransaction( - transaction, partitionId); - byte[] initialRevision = - baselineFields.remove( - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MUTATION_REVISION_FIELD); - if (!Arrays.equals( - initialRevision, - partitionHead.initialRevision().toString().getBytes(StandardCharsets.US_ASCII))) { - throw unavailable("A retained issuer partition baseline lost its initial revision"); - } } CanonicalGameplayIssuerBootstrapCoverageRepository.requireNewMemberAbsentFromBaseline( baseline, @@ -359,11 +343,41 @@ private PreparedPartitionWork prepareInTransaction( requireCurrentTargetAccountControl); } + private CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof + readQualifiedBaseline( + DSLContext transaction, + CanonicalGameplayIssuerInstalledAnchor anchor, + BigInteger partitionId) { + var baseline = + CanonicalGameplayIssuerBootstrapCoverageRepository.readInstalledAnchorPartitionProof( + transaction, anchor, partitionId); + Map baselineFields = + CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( + baseline.exactPhysicalFieldSetBytes()); + requireQualifiedBaseline(anchor, baseline, baselineFields); + CanonicalGameplayIssuerPartitionMutationRepository.PartitionMutationHead partitionHead = + CanonicalGameplayIssuerPartitionMutationRepository.readHeadInTransaction( + transaction, partitionId); + byte[] initialRevision = + baselineFields.remove( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MUTATION_REVISION_FIELD); + if (!Arrays.equals( + initialRevision, + partitionHead.initialRevision().toString().getBytes(StandardCharsets.US_ASCII))) { + throw unavailable("A retained issuer partition baseline lost its initial revision"); + } + return baseline; + } + private LocalEntry readLocalEntry( DSLContext transaction, Record row, CanonicalGameplayIssuerInstalledAnchor anchor, CanonicalGameplayIssuerBindingLocalOperation target, + Map< + BigInteger, + CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof> + proofsByPartition, boolean requireCurrentAccountControl) { if (!ISSUER.equals(text(row, "issuer_id")) || !"PENDING_PHYSICAL_PROOF".equals(text(row, "member_status")) @@ -455,9 +469,11 @@ private LocalEntry readLocalEntry( } requireAnchorColumns(row, anchor); - var baseline = - CanonicalGameplayIssuerBootstrapCoverageRepository.readInstalledAnchorPartitionProof( - transaction, anchor, reservation.partitionId()); + var baseline = proofsByPartition.get(reservation.partitionId()); + if (baseline == null) { + baseline = readQualifiedBaseline(transaction, anchor, reservation.partitionId()); + proofsByPartition.put(reservation.partitionId(), baseline); + } if (!Arrays.equals( bytes(row, "baseline_field_set_bytes"), baseline.exactPhysicalFieldSetBytes()) || !nonnegative(row, "baseline_partition_id").equals(baseline.partitionId()) From a8ed522f9bc2ef784505b1f22639fe6f97b112b6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 15:42:06 +1300 Subject: [PATCH 22/34] Preserve definitive abort retries and tighten issuer proof integrity --- ...nitiveAbortCompositionIntegrationTest.java | 37 +++++++++++ .../CanonicalGameplayAdmissionAbortOwner.java | 2 +- ...calGameplayBindingInventoryRepository.java | 42 ++++++++++-- ...playIssuerBootstrapCoverageRepository.java | 26 ++------ ..._issuer_local_anchor_source_event_pair.sql | 10 +++ ...calOperationRepositoryIntegrationTest.java | 65 +++++++++++++++++++ ...onicalGameplayAdmissionAbortOwnerTest.java | 40 +++++++++++- 7 files changed, 192 insertions(+), 30 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1038.2__canonical_issuer_local_anchor_source_event_pair.sql diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java index b08c7c313c..620f5d6eab 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java @@ -718,6 +718,23 @@ void actualAcknowledgedAbortCleanupSurvivesLaterAccountIntentAndRetiresExactIssu assertThat(session.gs.hasExactAccountMember()).isTrue(); assertThat(session.gs.hasExactOtherControllerMember(newerMemberSeed)).isTrue(); + // Retained abort replay still authenticates through the actual Account owner after the + // later GS Account intent; it must preserve the original source and cleanup identity. + var imageBeforeAbortRetry = session.image(); + session.restartAccount(); + var abortRetry = session.abort(); + assertThat(abortRetry.state()) + .isEqualTo(CanonicalGameplayAdmissionAbortOutcome.State.ABORTED); + assertThat(abortRetry.orphanCleanupId()).isEqualTo(abort.orphanCleanupId()); + assertThat(abortRetry.accountOperation().originalLeaseEvidence().canonicalJson()) + .isEqualTo(session.lease.canonicalJson()); + assertThat(session.image()).isEqualTo(imageBeforeAbortRetry); + assertThat(session.gs.retainedFirstNewAbortRowsImage()).isEqualTo(retainedRowsBeforeUpgrade); + assertThat(session.gs.memberAcknowledgementImage()).isEqualTo(originalAck); + assertThat(session.gs.accountObligationPhaseImage()).isEqualTo(originalPhase); + assertThat(session.gs.issuerPartitionFieldSetBytes()) + .containsExactly(issuerFieldsBeforeUpgrade); + var pendingRelease = session.gs.prepareIssuerRelease(); var releaseReadback = session.gs.projectIssuerRelease(pendingRelease); var released = session.gs.completeIssuerRelease(pendingRelease, releaseReadback); @@ -751,6 +768,26 @@ void actualAcknowledgedAbortCleanupSurvivesLaterAccountIntentAndRetiresExactIssu } } + @Test + void provisionalAbortStillRefusesLaterAccountIntentWithoutChangingOriginalRows() + throws Exception { + try (var session = open(true)) { + session.gs.repairAccountMember(); + session.gs.beginAccountAcquisitionIntent("provisional-abort-later-account-acquisition"); + var originalRows = session.gs.retainedFirstNewAbortRowsImage(); + var originalImage = session.image(); + var originalFields = session.gs.issuerPartitionFieldSetBytes(); + + assertThatThrownBy(session::abort).isInstanceOf(RuntimeException.class); + + assertThat(session.gs.retainedFirstNewAbortRowsImage()).isEqualTo(originalRows); + assertThat(session.image()).isEqualTo(originalImage); + assertThat(session.gs.issuerPartitionFieldSetBytes()).containsExactly(originalFields); + assertThat(session.client.read(session.jwt, session.leaseBytes()).state()) + .isEqualTo(State.PENDING); + } + } + /** * Controlled GS repository input exercises the initial deferred SQL guard, not Account's * terminal-state operation. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwner.java index f57387d056..ad55fe6f67 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwner.java @@ -47,7 +47,7 @@ public CanonicalGameplayAdmissionAbortOutcome abortFirstNew( } CanonicalGameplayAdmissionAbortSource source = - repository.readFirstNewAdmissionAbortSource(transitionId); + repository.readFirstNewAdmissionAbortRetrySource(transitionId); AccountGameplayAdmissionLeaseEvidence originalLease = source.originalDecision().leaseEvidence(); byte[] originalLeaseBytes = source.originalDecision().leaseEvidenceJson().getBytes(StandardCharsets.UTF_8); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index 47d5c745ec..47006f10fd 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -320,6 +320,19 @@ CanonicalGameplayAdmissionAbortSource readFirstNewAdmissionAbortSource(UUID tran }); } + /** + * Reads a current provisional source or the immutable original of an already definitive abort. + */ + CanonicalGameplayAdmissionAbortSource readFirstNewAdmissionAbortRetrySource(UUID transitionId) { + Objects.requireNonNull(transitionId, "transitionId"); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + return loadFirstNewAdmissionAbortRetrySource(transaction, transitionId, false); + }); + } + /** * Reads only an already recorded definitive first-NEW Account abort for issuer cleanup. Its * original transition, candidate, reservation, and cleanup identity remain authoritative; a later @@ -367,7 +380,8 @@ CanonicalGameplayAdmissionAbortSource recordFirstNewAccountAbort( if (!orphanCleanupId.equals(expectedSource.orphanCleanupId())) { throw conflict("Account abort retry changed the durable cleanup identity"); } - return readFirstNewAdmissionAbortSource(expectedSource.transition().transitionId()); + return readRetainedDefinitiveFirstNewAccountAbortSource( + expectedSource.transition().transitionId()); } return dsl.transactionResult( @@ -376,7 +390,7 @@ CanonicalGameplayAdmissionAbortSource recordFirstNewAccountAbort( BigInteger currentRevision = lockInventoryRevision(transaction); UUID transitionId = expectedSource.transition().transitionId(); CanonicalGameplayAdmissionAbortSource beforeRuntimeLock = - loadFirstNewAdmissionAbortSource(transaction, transitionId, false); + loadFirstNewAdmissionAbortRetrySource(transaction, transitionId, false); if (beforeRuntimeLock.isAccountAborted()) { requireSameFirstNewAdmissionAbortSource(expectedSource, beforeRuntimeLock); if (!orphanCleanupId.equals(beforeRuntimeLock.orphanCleanupId())) { @@ -390,12 +404,8 @@ CanonicalGameplayAdmissionAbortSource recordFirstNewAccountAbort( expectedSource.transition().bindingRef().bytes(), expectedSource.originalDecision().targetEvidence()); CanonicalGameplayAdmissionAbortSource current = - loadFirstNewAdmissionAbortSource(transaction, transitionId, true); + loadFirstNewAdmissionAbortRetrySource(transaction, transitionId, true); requireSameFirstNewAdmissionAbortSource(expectedSource, current); - requireAccountCoverageEvidenceCurrent( - transaction, - current.candidate().identity().accountId(), - current.transition().accountCoverageEvidence()); if (current.isAccountAborted()) { if (!orphanCleanupId.equals(current.orphanCleanupId())) { @@ -403,6 +413,10 @@ CanonicalGameplayAdmissionAbortSource recordFirstNewAccountAbort( } return current; } + requireAccountCoverageEvidenceCurrent( + transaction, + current.candidate().identity().accountId(), + current.transition().accountCoverageEvidence()); if (current.transition().status() != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL) { throw conflict("Only the exact PROVISIONAL first-NEW transition may abort"); @@ -1592,6 +1606,20 @@ private static CanonicalGameplayBindingProvisionalCasEvidence loadProvisionalCas return evidence; } + private static CanonicalGameplayAdmissionAbortSource loadFirstNewAdmissionAbortRetrySource( + DSLContext transaction, UUID transitionId, boolean forUpdate) { + Record transition = + transaction.fetchOne( + "SELECT status FROM " + + TRANSITION + + " WHERE transition_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + transitionId); + boolean alreadyAborted = + transition != null && "ABORTED".equals(transition.get("status", String.class)); + return loadFirstNewAdmissionAbortSource(transaction, transitionId, forUpdate, alreadyAborted); + } + private static CanonicalGameplayAdmissionAbortSource loadFirstNewAdmissionAbortSource( DSLContext transaction, UUID transitionId, boolean forUpdate) { return loadFirstNewAdmissionAbortSource(transaction, transitionId, forUpdate, false); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java index ee1d89b89f..c415569def 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java @@ -583,8 +583,8 @@ private static ProofSummary verifyCompleteProof( Map exactOperationValues = new HashMap<>(); Map expectedReservationsByPartition = new HashMap<>(); Map expectedCapacityByPartition = new HashMap<>(); - int expectedBindingCount = 0; int expectedCapacityCount = 0; + Map expectedBindingsByPartition = new HashMap<>(); for (CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work : plan.memberWorks()) { worksByOrdinal.put(work.workOrdinal(), work); expectedReservationsByPartition.merge(work.plannedPartitionId(), 1, Integer::sum); @@ -623,7 +623,7 @@ private static ProofSummary verifyCompleteProof( throw conflict("Finite SQL work contains a duplicate reservation identity"); } if (Boolean.TRUE.equals(operation.get("expected_binding_present", Boolean.class))) - expectedBindingCount++; + expectedBindingsByPartition.merge(work.plannedPartitionId(), 1, Integer::sum); } BigInteger expectedPartition = BigInteger.ZERO; @@ -644,6 +644,7 @@ private static ProofSummary verifyCompleteProof( int expectedPartitionReservations = expectedReservationsByPartition.getOrDefault(partitionId, 0); int expectedPartitionCapacity = expectedCapacityByPartition.getOrDefault(partitionId, 0); + int expectedPartitionBindings = expectedBindingsByPartition.getOrDefault(partitionId, 0); Map fields = decodeFieldSet(requireBytes(row, "exact_physical_field_set_bytes")); UUID initialRevision = requireUuid(row, "initial_physical_mutation_revision"); @@ -740,7 +741,7 @@ private static ProofSummary verifyCompleteProof( if (!expectedFieldNames.equals(fields.keySet()) || physicalReservations != expectedPartitionReservations || physicalCapacity != expectedPartitionCapacity - || physicalBindings != countBindingsForPartition(operations, worksByOrdinal, partitionId) + || physicalBindings != expectedPartitionBindings || physicalReservations != readInt(row, "physical_reservation_count") || physicalBindings != readInt(row, "physical_binding_count") || physicalCapacity != readInt(row, "physical_counted_capacity_count") @@ -767,7 +768,9 @@ private static ProofSummary verifyCompleteProof( } if (!expectedPartition.equals(partitionCount) || !reservationCount.equals(BigInteger.valueOf(plan.memberWorks().size())) - || !bindingCount.equals(BigInteger.valueOf(expectedBindingCount)) + || !bindingCount.equals( + BigInteger.valueOf( + expectedBindingsByPartition.values().stream().mapToInt(Integer::intValue).sum())) || !aggregateCountedCapacity.equals(expectedAggregateCapacity) || aggregateCountedCapacity.compareTo(aggregateBound) > 0) { throw conflict( @@ -781,21 +784,6 @@ private static ProofSummary verifyCompleteProof( "sha256:" + java.util.HexFormat.of().formatHex(root.digest())); } - private static int countBindingsForPartition( - List operations, - Map worksByOrdinal, - BigInteger partitionId) { - int count = 0; - for (Record operation : operations) { - long ordinal = requireNonNegativeLong(operation, "work_ordinal"); - CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work = worksByOrdinal.get(ordinal); - if (work != null - && work.plannedPartitionId().equals(partitionId) - && Boolean.TRUE.equals(operation.get("expected_binding_present", Boolean.class))) count++; - } - return count; - } - private static void requireOperationMatches( Record row, CanonicalGameplayIssuerPartitionBuildPlan plan, diff --git a/services/game-session-service/src/main/resources/db/migration/V1038.2__canonical_issuer_local_anchor_source_event_pair.sql b/services/game-session-service/src/main/resources/db/migration/V1038.2__canonical_issuer_local_anchor_source_event_pair.sql new file mode 100644 index 0000000000..bb2fa90578 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1038.2__canonical_issuer_local_anchor_source_event_pair.sql @@ -0,0 +1,10 @@ +-- V1034's source-event CHECK can evaluate UNKNOWN when event bytes are present but the digest is +-- NULL. A CHECK accepts UNKNOWN, so enforce the nullable pair invariant in a forward migration. +ALTER TABLE game_session_canonical_issuer_binding_local_operation + ADD CONSTRAINT chk_gs_issuer_binding_local_operation_source_event_pair CHECK ( + (anchor_source_event_bytes IS NULL AND anchor_source_event_digest IS NULL) + OR (anchor_source_event_bytes IS NOT NULL + AND octet_length(anchor_source_event_bytes) > 0 + AND anchor_source_event_digest IS NOT NULL + AND anchor_source_event_digest ~ '^sha256:[0-9a-f]{64}$') + ); 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 f9eeb64a95..bca86d34f1 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 @@ -42,6 +42,7 @@ import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; +import org.jooq.Record; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.AfterEach; @@ -234,6 +235,30 @@ void registersOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() .containsExactly(anchor.sourceCheckpointBytes()); assertThat(first.memberValue().sourceCheckpoint().latestIssuerEventBytes()) .containsExactly(anchor.sourceEventBytes()); + Record sourceEventPair = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT anchor_source_event_bytes, anchor_source_event_digest FROM" + + " game_session_canonical_issuer_binding_local_operation WHERE operation_id = ?", + first.operationId()), + "Expected local operation source-event pair"); + assertThat(sourceEventPair.get("anchor_source_event_bytes", byte[].class)) + .containsExactly(anchor.sourceEventBytes()); + assertThat(sourceEventPair.get("anchor_source_event_digest", String.class)) + .isEqualTo(anchor.sourceEventDigest()); + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO game_session_canonical_issuer_binding_local_operation" + + " SELECT (jsonb_populate_record(NULL::" + + "game_session_canonical_issuer_binding_local_operation," + + " to_jsonb(operation) || jsonb_build_object('operation_id', ?::text," + + " 'anchor_source_event_digest', NULL))).*" + + " FROM game_session_canonical_issuer_binding_local_operation operation" + + " WHERE operation_id = ?", + UUID.randomUUID(), + first.operationId())) + .hasMessageContaining("chk_gs_issuer_binding_local_operation_source_event_pair"); assertThat(first.memberValue().incarnation()).isEqualTo(incarnation); assertThat(first.memberValue().memberOperation().coverageGeneration()) .isEqualTo(first.localMemberGeneration()); @@ -424,6 +449,46 @@ void registersOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() .isEqualTo(2L); } + @Test + void localIssuerOwnerRetainsPairedNullSourceEventEvidence() { + DSLContext dsl = schema.dsl(); + establishActualLegacyDisposition(dsl); + byte[] exactCheckpoint = + "issuer-checkpoint-without-latest-event".getBytes(StandardCharsets.UTF_8); + var source = + new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint( + ISSUER, BigInteger.valueOf(7), exactCheckpoint, null); + var intent = + new CanonicalGameplayIssuerLayoutBootstrapRepository(dsl) + .beginInitialBootstrapIntent(UUID.randomUUID(), descriptor(), source); + migrateRemaining(schema); + var currentState = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + intent.sourceCheckpoint(), stableIncarnation("null-source-event")); + var anchor = + initialCoverageOwner(dsl, () -> currentState) + .completeInitialBootstrap(intent.operationId(), intent.requestId()); + var operation = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, () -> currentState) + .beginOrResumeOrdinaryNew( + request( + "null-source-event-request", + "null-source-event-transition", + identity("null-source-event"))); + + Record sourceEventPair = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT anchor_source_event_bytes, anchor_source_event_digest FROM" + + " game_session_canonical_issuer_binding_local_operation WHERE operation_id = ?", + operation.operationId()), + "Expected local operation source-event pair"); + assertThat(anchor.sourceEventBytes()).isNull(); + assertThat(anchor.sourceEventDigest()).isNull(); + assertThat(sourceEventPair.get("anchor_source_event_bytes", byte[].class)).isNull(); + assertThat(sourceEventPair.get("anchor_source_event_digest", String.class)).isNull(); + } + @Test void ordinaryNewPhysicalOperationBoundRefuses257thBeforePreparationAndRetainsExact256thRetry() { DSLContext dsl = schema.dsl(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwnerTest.java index ff6874c91a..74182a295b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwnerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwnerTest.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamesession.repository; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -37,7 +38,7 @@ void accountTimeoutRetainsTheOriginalNonAdmittingObligation() { var repository = mock(CanonicalGameplayBindingInventoryRepository.class); var accountClient = mock(AccountGameplayAdmissionLeaseClient.class); var source = source(false); - when(repository.readFirstNewAdmissionAbortSource(TRANSITION_ID)).thenReturn(source); + when(repository.readFirstNewAdmissionAbortRetrySource(TRANSITION_ID)).thenReturn(source); when(accountClient.abort(eq("presented-initial-gsa"), any(byte[].class), eq(TRANSITION_ID))) .thenThrow(new IllegalStateException("Account abort response unavailable")); @@ -64,7 +65,8 @@ void retainedTerminalReplayStillAuthenticatesTheCurrentCallerAndCannotCasOnFailu var repository = mock(CanonicalGameplayBindingInventoryRepository.class); var client = mock(AccountGameplayAdmissionLeaseClient.class); var terminalSource = source(true); - when(repository.readFirstNewAdmissionAbortSource(TRANSITION_ID)).thenReturn(terminalSource); + when(repository.readFirstNewAdmissionAbortRetrySource(TRANSITION_ID)) + .thenReturn(terminalSource); when(client.abort(eq("expired-or-revoked-caller"), any(byte[].class), eq(TRANSITION_ID))) .thenThrow(new IllegalStateException("current caller refused")); assertThatThrownBy( @@ -76,6 +78,38 @@ void retainedTerminalReplayStillAuthenticatesTheCurrentCallerAndCannotCasOnFailu verify(repository, never()).recordFirstNewAccountAbort(any(), any()); } + @Test + void retainedTerminalRetryReturnsTheOriginalCleanupOnlyAfterExactAccountReplay() { + var repository = mock(CanonicalGameplayBindingInventoryRepository.class); + var client = mock(AccountGameplayAdmissionLeaseClient.class); + var retained = source(true); + var lease = retained.originalDecision().leaseEvidence(); + when(lease.hasSameIdentity(lease)).thenReturn(true); + var operation = + mock( + net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec + .OperationEvidence.class); + when(operation.originalLeaseEvidence()).thenReturn(lease); + when(operation.state()) + .thenReturn( + net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec + .State.ABORTED); + when(operation.bindingDecisionId()).thenReturn(TRANSITION_ID); + when(operation.orphanCleanupId()).thenReturn(CLEANUP_ID); + when(repository.readFirstNewAdmissionAbortRetrySource(TRANSITION_ID)).thenReturn(retained); + when(client.abort(any(), any(), any())).thenReturn(operation); + + var result = + new CanonicalGameplayAdmissionAbortOwner(repository, client) + .abortFirstNew(TRANSITION_ID, "presented-initial-gsa"); + + assertThat(result.orphanCleanupId()).isEqualTo(CLEANUP_ID); + assertThat(result.accountOperation()).isSameAs(operation); + verify(client).abort(eq("presented-initial-gsa"), any(byte[].class), eq(TRANSITION_ID)); + verify(repository, never()).readFirstNewAdmissionAbortSource(any()); + verify(repository, never()).recordFirstNewAccountAbort(any(), any()); + } + @Test void ambientTransactionOrSynchronizationRefusesBeforeAnyOwnerInteraction() { for (boolean actualTransaction : new boolean[] {false, true}) { @@ -130,7 +164,7 @@ void retainedAbortRejectsContradictoryAccountStatesOrChangedCleanupWithoutCas() } case PENDING -> {} } - when(repository.readFirstNewAdmissionAbortSource(TRANSITION_ID)).thenReturn(retained); + when(repository.readFirstNewAdmissionAbortRetrySource(TRANSITION_ID)).thenReturn(retained); when(client.abort(any(), any(), any())).thenReturn(operation); assertThatThrownBy( () -> From 699967127c1b13687c8d4fca55ed75dfce0475a5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:46:40 +1300 Subject: [PATCH 23/34] Align retirement boundary regression with early registration refusal --- ...IssuerPhysicalRetirementIntegrationTest.java | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java index faebb5c25c..84ebe6c892 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java @@ -630,7 +630,7 @@ void addCurrentnessRereadKeepsTheTargetAccountControlFenceWithoutPreparingAnothe } @Test - void refusesProjectionBeyondTheCurrentLocalEntryBoundWithoutWrites() { + void refusesRegistrationBeyondTheCurrentLocalEntryBoundWithoutWrites() { try (var fixture = newFixture(BigInteger.valueOf(9), BigInteger.ONE, BigInteger.valueOf(512), 0)) { for (int index = 1; index < PARTITION_CAPACITY.intValueExact(); index++) { @@ -641,23 +641,14 @@ void refusesProjectionBeyondTheCurrentLocalEntryBoundWithoutWrites() { var currentWork = fixture.readCurrentOriginalPartitionWork(); assertThat(currentWork.localEntries()).hasSize(256); - byte[] fieldsBefore257th = physicalFieldSet(fixture.issuerPartitionKey()); - long mutationCountBefore257th = partitionMutationCount(fixture.dsl()); - String seed257 = "local-entry-bound-257"; - fixture.prepareOtherControllerNew(seed257); - assertThat(localOperationCount(fixture.dsl())).isEqualTo(257L); - assertThat(partitionMutationCount(fixture.dsl())).isEqualTo(mutationCountBefore257th); - assertThat(physicalFieldSet(fixture.issuerPartitionKey())).isEqualTo(fieldsBefore257th); - byte[] fieldsBeforeRefusal = physicalFieldSet(fixture.issuerPartitionKey()); long mutationCountBeforeRefusal = partitionMutationCount(fixture.dsl()); String sourceImageBeforeRefusal = durableHistoryImage(fixture.dsl(), NIL_UUID); - assertThatThrownBy(() -> fixture.projectOtherControllerNew(seed257)) + assertThatThrownBy(() -> fixture.prepareOtherControllerNew("local-entry-bound-257")) .isInstanceOf(IllegalStateException.class) - .hasMessage( - "Issuer binding-local projection is unavailable: The local partition operation set exceeds the physical owner bound"); + .hasMessage("The local partition operation set has reached the physical owner bound"); assertThat(durableHistoryImage(fixture.dsl(), NIL_UUID)).isEqualTo(sourceImageBeforeRefusal); - assertThat(localOperationCount(fixture.dsl())).isEqualTo(257L); + assertThat(localOperationCount(fixture.dsl())).isEqualTo(256L); assertThat(partitionMutationCount(fixture.dsl())).isEqualTo(mutationCountBeforeRefusal); assertThat(physicalFieldSet(fixture.issuerPartitionKey())).isEqualTo(fieldsBeforeRefusal); } From 88d736bdd1985feb2de13b3a5a257faff312dc5a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:28:47 +1300 Subject: [PATCH 24/34] Recover stale issuer bootstrap candidates and qualify owner proofs --- .github/scripts/classify-change-scope.cjs | 5 + .../scripts/classify-change-scope.test.cjs | 13 + .../architecture/system-architecture-redis.md | 2 + design/project-management/ai-observations.md | 8 + .../player-access-and-session.md | 2 + services/account-service/build.gradle.kts | 3 + ...IssuerBindingLocalOperationRepository.java | 11 - ...meplayIssuerLayoutBootstrapRepository.java | 153 +++++++ ...al_issuer_stale_bootstrap_supersession.sql | 153 +++++++ ...calOperationRepositoryIntegrationTest.java | 8 +- ...BootstrapCoverageOwnerIntegrationTest.java | 22 + ...rapPartitionRedisOwnerIntegrationTest.java | 34 +- ...outBootstrapRepositoryIntegrationTest.java | 384 ++++++++++++++++++ 13 files changed, 774 insertions(+), 24 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1038.3__canonical_issuer_stale_bootstrap_supersession.sql diff --git a/.github/scripts/classify-change-scope.cjs b/.github/scripts/classify-change-scope.cjs index 337dbdb2e9..02d5efe5e6 100644 --- a/.github/scripts/classify-change-scope.cjs +++ b/.github/scripts/classify-change-scope.cjs @@ -185,6 +185,11 @@ function classifyChangeScope(inputFiles, options = {}) { } } } + // Account's native owner composition consumes Game Session classes and migrations. + if (affectedModules.has("game-session-service")) { + affectedModules.add("account-service"); + affectedServices.add("account-service"); + } } const pythonFiles = files.filter((file) => file.endsWith(".py") || isPythonDependency(file)); diff --git a/.github/scripts/classify-change-scope.test.cjs b/.github/scripts/classify-change-scope.test.cjs index 227f9516e4..5bd0855abc 100644 --- a/.github/scripts/classify-change-scope.test.cjs +++ b/.github/scripts/classify-change-scope.test.cjs @@ -78,6 +78,19 @@ test("script tests avoid service validation but retain normal tooling proof", () assert.deepEqual(runtimeResult.affectedServices, ALL_SERVICES); }); +test("Game Session changes also select Account owner-composition validation", () => { + for (const path of [ + "services/game-session-service/src/main/java/Owner.java", + "services/game-session-service/src/main/resources/db/migration/V1038__owner.sql", + ]) { + const result = classifyChangeScope([path]); + assert.equal(result.runAll, false); + assert.deepEqual(result.affectedServices, ["game-session-service", "account-service"]); + assert.deepEqual(result.affectedModules, ["game-session-service", "account-service"]); + assert.deepEqual(result.bootableModules, ["game-session-service", "account-service"]); + } +}); + test("operational Python forces the normal validation path", () => { const result = classifyChangeScope([ "dev-tools/hosted/preview/render-preview-values.py", diff --git a/design/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index c4d5feb46f..95af54921c 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -465,6 +465,8 @@ Ordinary ADD requires its target’s exact current Account-control and source au The physical v2 HASH value above is a projection, not the installed anchor or an issuer binding-local acknowledgement. Its anchor tuple and preserved original reservation tuple remain separate even when a bootstrap operation links both to the same frozen cohort. The separate issuer acknowledgement must be explicitly versioned and bind the complete anchor, exact local transition/reservation, member and capacity readbacks, current control/incarnation evidence, and owner-issued per-transition generation. Neither physical-row parsing nor the account `accountIndexAcknowledgement` schema v2 can manufacture that result; the account acknowledgement and its CLOSED barrier receipt establish no issuer anchor or issuer `INSTALLED`/`OPEN` state. The final tenant-local CAS must positively compare the exact issuer barrier `OPEN` state and owner epoch/incarnation with the original candidate and required Account, issuer, and region evidence; global issuer-index and capacity keys never enter tenant-local Lua. +A pending initial candidate whose inventory snapshot became stale may be superseded only before any issuer anchor is installed. The owner serializes on the inventory clock and exact current control, preserves the original intent, cohort and all issued work, and captures a fresh immutable candidate with a distinct request and strictly advancing operation and coverage fences. An immutable supersession relation and the current-control change commit atomically. The replacement uses a strictly newer trusted layout version so previously issued physical work remains in its original Redis key domain; it does not overwrite, delete or acknowledge cleanup of those retained keys. Exact replay retains the same replacement, while a changed original, stale control or installed anchor refuses the operation. This is recovery of an uninstalled initial candidate, not authority to rotate an active layout or waive any new candidate's current source, complete-cohort, capacity, acknowledgement or admission checks. + ### Recovery and Cutoff Scope Authority The permitted scope is part of the evidence contract, not an operator hint. A region- or tenant-scoped preserved-session parent may enumerate only its binding-local snapshot, repair the region-local and tenant-scoped families it owns, and validate a linked child result. It may not map an issuer layout, perform issuer Redis field or reservation-capacity repair, read back issuer partitions for coverage, publish an issuer-partition acknowledgement, or claim global account-index coverage from its narrow snapshot. An issuer-wide child or standalone issuer operation must use a complete authoritative issuer inventory. A standalone operation carries `parentRecoveryOperationId=NOT_APPLICABLE`, `parentLifecycle=NOT_APPLICABLE`, `parentOperationFence=NOT_APPLICABLE`, and `parentCoverageFence=NOT_APPLICABLE`, then uses its own `issuerCoverageOperationId`, `issuerCoverageOperationFence`, distinct `coverageFence`, later `coverageGeneration`, pinned layout, and all finite partitions. A linked child retains the exact parent tuple through its independent edge but does not nest under the parent maintenance lock; the parent owns that lock and the child owns only its operation and coverage fences. An account-wide operation may cover only the untagged account family from a complete account inventory and its own account coverage evidence; it cannot substitute for issuer coverage. A cluster recovery must rebuild or consume complete per-account and per-issuer coverage for the deployment rather than treating a local region, tenant, or aggregate snapshot as global proof. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 82784e7fc0..dcc46f77e4 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -436,3 +436,11 @@ Entry format: - Context: The manual Human-to-region composition rejected a guarded update and rolled its transaction back before the diagnostic reread. - Observation: Reconstructing expected values from the retained `PREPARED` row yielded NULL admission fields and misleading predicate failures instead of the attempted decision. - Expected pattern: Pass the immutable attempted selector to bounded failure-only diagnostics, read actual durable source rows separately, and keep attempted values distinct from committed evidence. + +- `2026-10-27`: Completed Hosted publication remained in native provider wait + - Context: #3310 Hosted5 completed on the exact requested head at 16:32:58 NZDT, but the original FireController operation still reported `active / provider_wait / trigger_recovered` after the completed publication was visible. + - Observation: the status did not expose the completed review or a capture failure. A bounded provider inspection found review 5661910348 and its six actionable comments; FireController's owner confirmed that the retained capture already contained the publication and began checking parser/attribution. The source completion mismatch delayed consuming the findings. + - Expected pattern: preserve the original attempt and quota, distinguish trigger delivery from provider execution, and expose capture incompatibility as an actionable state. Read the completed source for safe local fixes while the tool owner recovers its official evidence; never repost to obtain another review. + - Reconsideration trigger: the original attempt is recovered and the exact parser/attribution cause and diagnostic behavior are verified. Gameplay reported the retained handles directly to FireController's owner; no database or runtime bypass was used. + + - Recovery: FireController identified six separately fingerprinted findings grouped into five comment containers. Parser fix `8f6e6121` recovered the same original attempt and all six exact findings; Gameplay verified the pinned head/base and finalized their native decisions. No trigger, allowance or controls changed. Full required controller CI was still pending at its owner's recovery handoff; native/race and packaged checks had passed. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 46385b4d90..f4079224db 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for player access and session. Ca ### Canonical NEW admission components +The current local correction adds explicit recovery for a stale, uninstalled initial issuer-bootstrap candidate. Forward V1038.3 retains its original intent, cohort and issued work, captures the new actual inventory cut under monotonic fences, and atomically binds immutable supersession lineage to current control. A strictly newer trusted layout separates old physical work; installed anchors remain ineligible. Account CI selection and migration task inputs now cover its Game Session owner-composition dependency, and the native registration-image and lost-reply proofs use their actual SQL/Lua contracts. R827 passes 31 of 32 focused cases; its remaining failure is a test assertion against the transaction wrapper rather than the nested PostgreSQL refusal. R828 then passes that complete recovery case with affected integration static and formatting checks. Together they qualify 32 distinct current-source cases, including two actual Account abort compositions; frontier, jOOQ, affected static, formatting and documentation checks pass. The new recovery sequence uses controlled Account terminal input through the actual Game Session abort owner, separately from those two authenticated Account compositions. This is focused proof, not a full service-suite, live layout rotation, retained-key cleanup or production-authority claim. + The local issuer owners now reject plans that exceed the executable 256-member-operation bound per partition, including retained `RELEASED` lineage independently of logical active capacity. A blocked plan retains its complete cohort and planned work; physical preparation refuses before allocating operation rows. Fresh ordinary NEW registration also checks the same nonretired local-operation set under the inventory lock before allocating new identities or rows, while exact retries retain their original operation at the bound. Both bootstrap owners use one strict Account issuer source-event verifier. R791 freshly passes the four PostgreSQL boundary cases: 256 allowed, both 257-reservation overflow forms blocked, and ordinary registration refusal/retry with unchanged durable state. R793 then freshly passes all 26 selected PostgreSQL cases across the plan, ordinary-operation and intent owners, plus affected production/integration static analysis, formatting and documentation checks. This is focused owner proof, not a complete service-suite or public admission result. Default registration, external source custody and admission limits remain unchanged. The Account gameplay-admission lease and the unregistered Game Session receiver remain separate authority boundaries. The unregistered Account verifier uses the pinned trusted JWKS and fixed gameplay-delegation profile, selects the current `COMMITTED`/`ACTIVE` issuance by verified JTI, and compares the full immutable token identity, hash and authority; it retains no presented JWT and makes no membership, entitlement or lease decision. Focused acquisition proof joins the exact recovered JWT to actual current issuance, physical Coordination Redis and the same-connection Account source graph, preserving the original pending lease on retry. R494 freshly passes 104 Account unit cases and eight selected PostgreSQL/Redis cases, with affected static analysis and formatting. Its manual TLS receiver exercises all four generated RPCs with the exact recovered Account JWT and current issuance/registry and SQL sources, then performs PostgreSQL 18 physical COMMIT and independent durable original-ACK insertion/readback. The original lease attempt and ACK are immutable. The original physical-commit executor retains focused PostgreSQL component proof, and the Game Session lease client has controlled mTLS proof; the retained PostgreSQL 18 receipt-reader denial remains unchanged. The reverse Game Session target/decision response and protected signer/materializer evidence remain controlled. Exact metadata and cleanup-obligation recovery revalidate the current caller/global Account/token under Account-first SQL locks without requiring a superseded tenant admission baseline; new acquisition and first finalization retain full tenant-source checks. These results do not prove genuine Game Session authority, cleanup delivery, final controller admission, production custody or activation. Token-retirement, orphan-cleanup delivery and admitted binding remain open. diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index c482a1e39c..4969e06c57 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -130,6 +130,9 @@ tasks.named("test") { } tasks.named("integrationTest") { + // Composition fixtures load this owner's migrations directly from the filesystem. + inputs.dir(project(":game-session-service").file("src/main/resources/db/migration")) + .withPathSensitivity(PathSensitivity.RELATIVE) val loggingArtifacts = loggingAdminIntegrationTestArtifacts.artifactFiles classpath = classpath.filter { it !in loggingArtifacts } + files(extractLoggingAdminIntegrationTestClasses) } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java index 601b0c185d..5b2a274b82 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java @@ -342,9 +342,6 @@ private CanonicalGameplayIssuerBindingLocalOperation recordOrReplayInTransaction if (operationRow != null) { throw conflict("A local issuer operation already exists for a newly prepared transition"); } - if (operationRequestExists(transaction, transitionRequest.transitionId())) { - throw conflict("A different request already owns this local issuer transition"); - } CanonicalIssuerPartitionReservation reservation = readAndRequireReservation(transaction, transitionRequest, prepared, null); @@ -1039,14 +1036,6 @@ static boolean sameCurrentIssuerState( CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(right.incarnation())); } - private static boolean operationRequestExists(DSLContext transaction, UUID transitionId) { - return transaction.fetchOne( - "SELECT 1 FROM " + OPERATION + " WHERE issuer_id = ? AND transition_id = ?", - ISSUER, - transitionId) - != null; - } - private static UUID freshOperationId( CanonicalGameplayIssuerBindingLocalOperation.Request request, CanonicalIssuerPartitionReservation reservation, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java index 5aa2612c4d..3e619c4ef3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java @@ -157,6 +157,159 @@ CanonicalGameplayIssuerLayoutBootstrapIntent beginInitialBootstrapIntent( }); } + /** + * Replaces only an uninstalled initial candidate whose immutable inventory cut is stale. The old + * intent and every artifact it produced remain retained; a newer layout isolates in-flight Redis + * work rather than granting deletion or active-layout replacement authority. + */ + CanonicalGameplayIssuerLayoutBootstrapIntent supersedeStaleInitialBootstrapIntent( + UUID expectedOldOperationId, + UUID newRequestId, + TrustedLayoutDescriptor descriptor, + TrustedAccountIssuerCheckpoint sourceCheckpoint) { + requireNonNil(expectedOldOperationId, "expectedOldOperationId"); + requireNonNil(newRequestId, "newRequestId"); + Objects.requireNonNull(descriptor, "descriptor"); + Objects.requireNonNull(sourceCheckpoint, "sourceCheckpoint"); + requireTrustedInputScopes(descriptor, sourceCheckpoint); + requireValidSourceEvent(descriptor.issuerId(), sourceCheckpoint); + requireNoAmbientTransaction(); + String descriptorDigest = sha256(descriptor.exactBytes()); + String checkpointDigest = sha256(sourceCheckpoint.checkpointBytes()); + String sourceEventDigest = + sourceCheckpoint.latestEventBytes() == null + ? null + : sha256(sourceCheckpoint.latestEventBytes()); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger snapshotRevision = lockInventoryRevision(transaction); + Record control = lockControl(transaction, descriptor.issuerId()); + if (control == null) + throw conflict("Initial bootstrap supersession requires current control"); + UUID currentId = control.get("current_operation_id", UUID.class); + Record currentRow = lockIntent(transaction, currentId); + if (currentRow == null) throw conflict("Current initial bootstrap intent is missing"); + var current = loadAndRequireCurrent(transaction, control, currentRow); + if (transaction.fetchExists( + DSL.selectOne() + .from("game_session_canonical_issuer_installed_anchor") + .where(DSL.field("issuer_id").eq(descriptor.issuerId())))) { + throw conflict("An installed issuer anchor forbids initial bootstrap supersession"); + } + if (!expectedOldOperationId.equals(currentId)) { + Record replay = + transaction.fetchOne( + "SELECT * FROM game_session_canonical_issuer_bootstrap_supersession" + + " WHERE old_operation_id = ? AND new_operation_id = ?", + expectedOldOperationId, + currentId); + if (replay == null + || !current.requestId().equals(newRequestId) + || !current.inventorySnapshotRevision().equals(snapshotRevision)) { + throw conflict("Expected original initial bootstrap is no longer current"); + } + requireSameTrustedInputs( + current, + descriptor, + sourceCheckpoint, + descriptorDigest, + checkpointDigest, + sourceEventDigest); + return current; + } + if (newRequestId.equals(expectedOldOperationId) + || newRequestId.equals(current.requestId()) + || transaction.fetchExists( + DSL.selectOne() + .from(INTENT) + .where( + DSL.field("request_id") + .eq(newRequestId) + .or(DSL.field("operation_id").eq(newRequestId))))) { + throw conflict("Initial bootstrap supersession requires a fresh distinct request"); + } + if (snapshotRevision.compareTo(current.inventorySnapshotRevision()) <= 0) { + throw conflict("Initial bootstrap supersession requires strictly newer inventory"); + } + if (descriptor.layoutVersion().compareTo(current.layoutDescriptor().layoutVersion()) + <= 0) { + throw conflict( + "Initial bootstrap supersession requires a strictly newer layout version"); + } + var legacy = readVerifiedLegacyDisposition(transaction, snapshotRevision, true); + requireNoFutureInventoryRows(transaction, snapshotRevision); + var rows = freezeCohort(captureCohort(transaction, snapshotRevision)); + BigInteger previousLastFence = readBigInteger(control, "last_issued_fence"); + BigInteger operationFence = previousLastFence.add(BigInteger.ONE); + BigInteger coverageFence = operationFence.add(BigInteger.ONE); + UUID operationId = randomNonNilUuid(); + while (operationId.equals(newRequestId) || operationId.equals(expectedOldOperationId)) { + operationId = randomNonNilUuid(); + } + insertIntent( + transaction, + operationId, + newRequestId, + descriptor, + descriptorDigest, + sourceCheckpoint, + checkpointDigest, + sourceEventDigest, + snapshotRevision, + operationFence, + operationFence, + coverageFence, + legacy, + rows, + digestCohort(rows)); + insertCohort(transaction, operationId, descriptor.issuerId(), rows); + transaction.execute( + "INSERT INTO game_session_canonical_issuer_bootstrap_supersession" + + " (issuer_id, old_operation_id, new_operation_id, old_inventory_revision," + + " new_inventory_revision, old_operation_fence, old_coverage_fence," + + " previous_last_issued_fence, new_operation_fence, new_coverage_fence)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + descriptor.issuerId(), + expectedOldOperationId, + operationId, + decimal(current.inventorySnapshotRevision()), + decimal(snapshotRevision), + decimal(current.operationFence()), + decimal(current.coverageFence()), + decimal(previousLastFence), + decimal(operationFence), + decimal(coverageFence)); + int changed = + transaction.execute( + "UPDATE " + + CONTROL + + " SET control_epoch = ?, last_issued_fence = ?, current_operation_id = ?," + + " current_operation_fence = ?, current_coverage_fence = ?," + + " updated_at = CURRENT_TIMESTAMP WHERE issuer_id = ?" + + " AND current_operation_id = ? AND control_epoch = ?" + + " AND current_operation_fence = ? AND current_coverage_fence = ?" + + " AND last_issued_fence = ? AND state = 'INITIAL_BOOTSTRAP_INTENT'", + decimal(operationFence), + decimal(coverageFence), + operationId, + decimal(operationFence), + decimal(coverageFence), + descriptor.issuerId(), + expectedOldOperationId, + decimal(current.controlEpoch()), + decimal(current.operationFence()), + decimal(current.coverageFence()), + decimal(previousLastFence)); + if (changed != 1) + throw conflict("Initial bootstrap supersession lost exact current control"); + return loadAndRequireCurrent( + transaction, + Objects.requireNonNull(lockControl(transaction, descriptor.issuerId())), + Objects.requireNonNull(lockIntent(transaction, operationId))); + }); + } + /** Reads the exact persisted pending intent and its frozen cohort by owner-allocated ID. */ CanonicalGameplayIssuerLayoutBootstrapIntent readCurrentInitialBootstrapIntent(UUID operationId) { requireNonNil(operationId, "operationId"); diff --git a/services/game-session-service/src/main/resources/db/migration/V1038.3__canonical_issuer_stale_bootstrap_supersession.sql b/services/game-session-service/src/main/resources/db/migration/V1038.3__canonical_issuer_stale_bootstrap_supersession.sql new file mode 100644 index 0000000000..03d594f0eb --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1038.3__canonical_issuer_stale_bootstrap_supersession.sql @@ -0,0 +1,153 @@ +-- Explicit recovery of an uninstalled initial candidate only. Original intents and physical work +-- remain retained; strictly newer layout versions separate the old and new Redis key domains. +ALTER TABLE game_session_canonical_issuer_layout_bootstrap_intent + ADD CONSTRAINT uq_gs_issuer_bootstrap_supersession_link UNIQUE ( + operation_id, issuer_id, inventory_snapshot_revision, operation_fence, coverage_fence); + +CREATE TABLE game_session_canonical_issuer_bootstrap_supersession ( + issuer_id character varying(64) NOT NULL, + old_operation_id uuid NOT NULL, + new_operation_id uuid NOT NULL, + old_inventory_revision numeric NOT NULL, + new_inventory_revision numeric NOT NULL, + old_operation_fence numeric NOT NULL, + old_coverage_fence numeric NOT NULL, + previous_last_issued_fence numeric NOT NULL, + new_operation_fence numeric NOT NULL, + new_coverage_fence numeric NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_issuer_bootstrap_supersession PRIMARY KEY (old_operation_id), + CONSTRAINT uq_gs_issuer_bootstrap_supersession_new UNIQUE (new_operation_id), + CONSTRAINT fk_gs_issuer_bootstrap_supersession_old FOREIGN KEY ( + old_operation_id, issuer_id, old_inventory_revision, old_operation_fence, old_coverage_fence) + REFERENCES game_session_canonical_issuer_layout_bootstrap_intent ( + operation_id, issuer_id, inventory_snapshot_revision, operation_fence, coverage_fence), + CONSTRAINT fk_gs_issuer_bootstrap_supersession_new FOREIGN KEY ( + new_operation_id, issuer_id, new_inventory_revision, new_operation_fence, new_coverage_fence) + REFERENCES game_session_canonical_issuer_layout_bootstrap_intent ( + operation_id, issuer_id, inventory_snapshot_revision, operation_fence, coverage_fence), + CONSTRAINT chk_gs_issuer_bootstrap_supersession CHECK ( + old_operation_id <> new_operation_id + AND new_inventory_revision > old_inventory_revision + AND previous_last_issued_fence >= old_operation_fence + AND previous_last_issued_fence >= old_coverage_fence + AND new_operation_fence = previous_last_issued_fence + 1 + AND new_coverage_fence = new_operation_fence + 1) +); + +-- [jooq ignore start] +CREATE FUNCTION game_session_guard_issuer_bootstrap_supersession() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + current_revision numeric; + current_control game_session_canonical_issuer_layout_bootstrap_control%ROWTYPE; + original game_session_canonical_issuer_layout_bootstrap_intent%ROWTYPE; + replacement game_session_canonical_issuer_layout_bootstrap_intent%ROWTYPE; +BEGIN + -- Match the owner's inventory -> issuer control -> intent lock order. + SELECT inventory_revision INTO current_revision + FROM game_session_canonical_binding_inventory_clock WHERE singleton_id = 1 FOR UPDATE; + SELECT * INTO current_control FROM game_session_canonical_issuer_layout_bootstrap_control + WHERE issuer_id = NEW.issuer_id FOR UPDATE; + SELECT * INTO original FROM game_session_canonical_issuer_layout_bootstrap_intent + WHERE operation_id = NEW.old_operation_id FOR UPDATE; + SELECT * INTO replacement FROM game_session_canonical_issuer_layout_bootstrap_intent + WHERE operation_id = NEW.new_operation_id FOR UPDATE; + IF current_control.current_operation_id IS DISTINCT FROM NEW.old_operation_id + OR current_control.state IS DISTINCT FROM 'INITIAL_BOOTSTRAP_INTENT' + OR current_control.control_epoch IS DISTINCT FROM NEW.old_operation_fence + OR current_control.current_operation_fence IS DISTINCT FROM NEW.old_operation_fence + OR current_control.current_coverage_fence IS DISTINCT FROM NEW.old_coverage_fence + OR current_control.last_issued_fence IS DISTINCT FROM NEW.previous_last_issued_fence + OR current_revision IS DISTINCT FROM NEW.new_inventory_revision + OR original.issuer_id IS DISTINCT FROM NEW.issuer_id + OR replacement.issuer_id IS DISTINCT FROM NEW.issuer_id + OR original.inventory_snapshot_revision IS DISTINCT FROM NEW.old_inventory_revision + OR replacement.inventory_snapshot_revision IS DISTINCT FROM NEW.new_inventory_revision + OR original.operation_fence IS DISTINCT FROM NEW.old_operation_fence + OR original.coverage_fence IS DISTINCT FROM NEW.old_coverage_fence + OR replacement.operation_fence IS DISTINCT FROM NEW.new_operation_fence + OR replacement.coverage_fence IS DISTINCT FROM NEW.new_coverage_fence + OR replacement.layout_version <= original.layout_version + OR replacement.request_id = original.request_id + OR replacement.request_id = original.operation_id + OR EXISTS (SELECT 1 FROM game_session_canonical_issuer_installed_anchor + WHERE issuer_id = NEW.issuer_id) THEN + RAISE EXCEPTION 'initial issuer bootstrap supersession requires exact stale uninstalled lineage' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_gs_issuer_bootstrap_supersession_guard + BEFORE INSERT ON game_session_canonical_issuer_bootstrap_supersession + FOR EACH ROW EXECUTE FUNCTION game_session_guard_issuer_bootstrap_supersession(); +CREATE TRIGGER trg_gs_issuer_bootstrap_supersession_immutable + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_bootstrap_supersession + FOR EACH ROW EXECUTE FUNCTION game_session_reject_issuer_bootstrap_coverage_change(); +CREATE TRIGGER trg_gs_issuer_bootstrap_supersession_no_truncate + BEFORE TRUNCATE ON game_session_canonical_issuer_bootstrap_supersession + FOR EACH STATEMENT EXECUTE FUNCTION game_session_reject_issuer_bootstrap_coverage_change(); + +CREATE FUNCTION game_session_require_issuer_bootstrap_supersession_control() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_layout_bootstrap_control control + WHERE control.issuer_id = NEW.issuer_id + AND control.state = 'INITIAL_BOOTSTRAP_INTENT' + AND control.current_operation_id = NEW.new_operation_id + AND control.control_epoch = NEW.new_operation_fence + AND control.current_operation_fence = NEW.new_operation_fence + AND control.current_coverage_fence = NEW.new_coverage_fence + AND control.last_issued_fence = NEW.new_coverage_fence) THEN + RAISE EXCEPTION 'initial issuer supersession must move exact current control in the same transaction' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER trg_gs_issuer_bootstrap_supersession_control + AFTER INSERT ON game_session_canonical_issuer_bootstrap_supersession + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION game_session_require_issuer_bootstrap_supersession_control(); + +CREATE FUNCTION game_session_guard_issuer_bootstrap_control_supersession() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.current_operation_id IS DISTINCT FROM OLD.current_operation_id THEN + IF NEW.issuer_id IS DISTINCT FROM OLD.issuer_id + OR NEW.state IS DISTINCT FROM 'INITIAL_BOOTSTRAP_INTENT' + OR OLD.state IS DISTINCT FROM 'INITIAL_BOOTSTRAP_INTENT' + OR NEW.control_epoch IS DISTINCT FROM NEW.current_operation_fence + OR EXISTS (SELECT 1 FROM game_session_canonical_issuer_installed_anchor + WHERE issuer_id = OLD.issuer_id) + OR NOT EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_bootstrap_supersession relation + WHERE relation.issuer_id = OLD.issuer_id + AND relation.old_operation_id = OLD.current_operation_id + AND relation.new_operation_id = NEW.current_operation_id + AND relation.old_operation_fence = OLD.control_epoch + AND relation.old_operation_fence = OLD.current_operation_fence + AND relation.old_coverage_fence = OLD.current_coverage_fence + AND relation.previous_last_issued_fence = OLD.last_issued_fence + AND relation.new_operation_fence = NEW.current_operation_fence + AND relation.new_coverage_fence = NEW.current_coverage_fence + AND relation.new_coverage_fence = NEW.last_issued_fence) THEN + RAISE EXCEPTION 'initial issuer control change requires exact retained supersession lineage' + USING ERRCODE = 'check_violation'; + END IF; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_gs_issuer_bootstrap_control_supersession + BEFORE UPDATE ON game_session_canonical_issuer_layout_bootstrap_control + FOR EACH ROW EXECUTE FUNCTION game_session_guard_issuer_bootstrap_control_supersession(); +-- [jooq ignore stop] 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 bca86d34f1..317788fad8 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 @@ -154,6 +154,8 @@ void registersOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() String installedProofImage = proofImage(dsl); String initialReservationImage = reservationImage(dsl); BigInteger initialGlobalCoverageGeneration = anchor.globalCoverageGeneration(); + String beforeFirstAllocation = localRegistrationImage(dsl); + assertThat(beforeFirstAllocation).isNotNull().endsWith(":missing"); AtomicInteger sourceReads = new AtomicInteger(); CyclicBarrier concurrentPreReadBarrier = new CyclicBarrier(2); @@ -188,6 +190,8 @@ void registersOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() concurrentCallers.shutdownNow(); } assertThat(sourceReads.get()).isEqualTo(4); + assertThat(localRegistrationImage(dsl)).isNotEqualTo(beforeFirstAllocation); + assertThat(localRegistrationImage(dsl)).doesNotEndWith(":missing"); assertThat(concurrentReplay.operationId()).isEqualTo(first.operationId()); assertThat(concurrentReplay.reservation().reservationId()) .isEqualTo(first.reservation().reservationId()); @@ -913,9 +917,9 @@ private static String localRegistrationImage(DSLContext dsl) { + " || (SELECT coalesce(jsonb_agg(to_jsonb(g) ORDER BY tenant_id, playable_state_namespace_id, character_id), '[]'::jsonb)::text" + " FROM game_session_canonical_binding_generation g) || ':'" + " || (SELECT inventory_revision::text FROM game_session_canonical_binding_inventory_clock WHERE singleton_id = 1) || ':'" - + " || (SELECT coalesce(to_jsonb(c)::text, 'missing') FROM game_session_canonical_issuer_bootstrap_member_op_counter c WHERE issuer_id = '" + + " || coalesce((SELECT to_jsonb(c)::text FROM game_session_canonical_issuer_bootstrap_member_op_counter c WHERE issuer_id = '" + ISSUER - + "')"), + + "'), 'missing')"), "Expected local registration aggregate row") .get(0, String.class); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java index f0482c2e62..bb0a8f7384 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java @@ -127,6 +127,28 @@ void installsOnlyAfterEveryPopulatedAndEmptyPartitionHasExactPhysicalProofAndRep owner(fixture, () -> current) .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId()); + String installedAnchorImage = anchorStorageImage(fixture.dsl()); + String installedProofImage = proofStorageImage(fixture.dsl()); + var installedPhysicalImage = physicalPartitionImages(fixture); + assertThatThrownBy( + () -> + new CanonicalGameplayIssuerLayoutBootstrapRepository(fixture.dsl()) + .supersedeStaleInitialBootstrapIntent( + fixture.intent().operationId(), + UUID.randomUUID(), + descriptor(PARTITION_COUNT, PARTITION_CAPACITY), + fixture.currentAccountCheckpoint())) + .hasMessageContaining("installed issuer anchor forbids"); + assertThat(anchorStorageImage(fixture.dsl())).isEqualTo(installedAnchorImage); + assertThat(proofStorageImage(fixture.dsl())).isEqualTo(installedProofImage); + assertThat(physicalPartitionImages(fixture)).isEqualTo(installedPhysicalImage); + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT count(*) FROM game_session_canonical_issuer_bootstrap_supersession") + .get(0, Long.class)) + .isZero(); + assertThat(first.issuerCoverageOperationId()).isEqualTo(fixture.intent().operationId()); assertThat(first.operationFence()).isEqualTo(fixture.intent().operationFence()); assertThat(first.coverageFence()).isEqualTo(fixture.intent().coverageFence()); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java index b30a1b479e..6cb8e4ad59 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java @@ -463,9 +463,16 @@ void retainedCommitAfterLostReplyReplaysFromFreshSqlWorkAndSeparatePhysicalReadb String scriptSha = administratorCommands.scriptLoad(script); byte[] key = key(fixture, work.partitionId()); - // The test deliberately discards this post-commit script reply to model a lost reply/crash. - administratorCommands.evalsha( - scriptSha, ScriptOutputType.INTEGER, new byte[][] {key}, scriptArguments(work, physical)); + // The owner loses the reply; the test driver independently establishes that it committed. + Long committed = + administratorCommands.evalsha( + scriptSha, + ScriptOutputType.INTEGER, + new byte[][] {key}, + scriptArguments(work, physical)); + assertThat(committed).isEqualTo(1L); + assertThat(administratorCommands.type(key)).isEqualTo("hash"); + assertThat(administratorCommands.hlen(key)).isEqualTo(4L); CanonicalGameplayIssuerBootstrapPartitionWork restartedWork = partitionWork(fixture, work.partitionId()); @@ -504,7 +511,7 @@ void deliberatelyLowerCapacityLuaArgumentsRefuseWithoutChangingOwnedHashImage() arguments[3] = ascii("1"); arguments[4] = lowerCapacityMetadata(physical.metadataBytes()); for (int index = 0; index < work.memberOperations().size(); index++) { - int memberArgument = 7 + index * 4; + int memberArgument = 8 + 4 * index; arguments[memberArgument] = lowerCapacityMember(arguments[memberArgument]); } @@ -835,22 +842,27 @@ private static byte[][] scriptArguments( CanonicalGameplayIssuerBootstrapPartitionWork work, CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.PhysicalFieldSet physical) { var intent = work.buildPlan().bootstrapIntent(); - byte[][] arguments = new byte[6 + work.memberOperations().size() * 4][]; + byte[][] arguments = new byte[7 + work.memberOperations().size() * 4][]; arguments[0] = ascii(intent.issuerId()); arguments[1] = ascii(work.partitionId().toString()); arguments[2] = ascii(intent.layoutDescriptor().partitionCount().toString()); arguments[3] = ascii(intent.layoutDescriptor().partitionCapacity().toString()); arguments[4] = physical.metadataBytes(); - arguments[5] = ascii(Integer.toString(work.memberOperations().size())); - int offset = 6; + arguments[5] = ascii(work.initialPhysicalRevision().toString()); + arguments[6] = ascii(Integer.toString(work.memberOperations().size())); + int offset = 7; for (CanonicalGameplayIssuerBootstrapMemberOperation operation : work.memberOperations()) { - arguments[offset++] = operation.expectedMemberValue().owner().bindingRef().bytes(); - arguments[offset++] = operation.exactMemberValueBytes(); - arguments[offset++] = + arguments[offset] = operation.expectedMemberValue().owner().bindingRef().bytes(); + offset++; + arguments[offset] = operation.exactMemberValueBytes(); + offset++; + arguments[offset] = ascii( CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( operation.expectedMemberValue().reservation().reservationId())); - arguments[offset++] = ascii(operation.expectedBindingPresent() ? "1" : "0"); + offset++; + arguments[offset] = ascii(operation.expectedBindingPresent() ? "1" : "0"); + offset++; } return arguments; } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java index 57753dd948..d7052cd5e8 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java @@ -12,6 +12,7 @@ import java.util.EnumSet; import java.util.HexFormat; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.concurrent.CountDownLatch; @@ -19,8 +20,11 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; @@ -30,6 +34,7 @@ import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; 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; @@ -755,6 +760,385 @@ void concurrentDifferentBootstrapRequestsSerializeToOneImmutableIntent() throws } } + @Test + void staleUninstalledIntentRequiresExplicitFreshLayoutAndPreservesOriginalHistory() { + TestSchema testSchema = newTestSchema("gs_issuer_boot_supersede_"); + try { + DSLContext dsl = testSchema.dsl(); + establishActualLegacyDisposition(dsl); + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + var provisional = prepareActualProvisionalFirstNew(testSchema); + var owner = new CanonicalGameplayIssuerLayoutBootstrapRepository(dsl); + var layout = descriptor(LAYOUT_VERSION, PARTITION_COUNT, PARTITION_CAPACITY); + var source = sourceCheckpoint(BigInteger.valueOf(7)); + var original = owner.beginInitialBootstrapIntent(UUID.randomUUID(), layout, source); + var plans = new CanonicalGameplayIssuerPartitionBuildRepository(dsl); + plans.prepareInitialBuildPlan(original.operationId(), original.requestId()); + List originalIntent = + rowImages(dsl, "game_session_canonical_issuer_layout_bootstrap_intent"); + List originalCohort = + rowImages(dsl, "game_session_canonical_issuer_layout_bootstrap_cohort_row"); + List originalPlan = + rowImages(dsl, "game_session_canonical_issuer_partition_build_plan"); + List originalBuildCohort = + rowImages(dsl, "game_session_canonical_issuer_partition_build_cohort_row"); + List originalWork = + rowImages(dsl, "game_session_canonical_issuer_partition_build_member_work"); + List originalControl = + rowImages(dsl, "game_session_canonical_issuer_layout_bootstrap_control"); + var newerLayout = + descriptor(LAYOUT_VERSION.add(BigInteger.ONE), PARTITION_COUNT, PARTITION_CAPACITY); + UUID replacementRequest = UUID.randomUUID(); + assertThatThrownBy( + () -> + owner.supersedeStaleInitialBootstrapIntent( + original.operationId(), replacementRequest, newerLayout, source)) + .hasMessageContaining("strictly newer inventory"); + assertThat(rowImages(dsl, "game_session_canonical_issuer_layout_bootstrap_control")) + .isEqualTo(originalControl); + assertThat(countRows(dsl, "game_session_canonical_issuer_bootstrap_supersession")).isZero(); + + // The actual GS owner consumes a controlled Account terminal input. This does not prove + // the separate authenticated Account definitive-abort producer or its cross-service call. + var advanced = inventory.recordFirstNewAccountAbort(provisional, UUID.randomUUID()); + assertThat(advanced.isAccountAborted()).isTrue(); + assertThat(advanced.transition().inventoryRevision()) + .isGreaterThan(original.inventorySnapshotRevision()); + assertThatThrownBy( + () -> plans.prepareInitialBuildPlan(original.operationId(), original.requestId())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + owner.supersedeStaleInitialBootstrapIntent( + original.operationId(), replacementRequest, layout, source)) + .hasMessageContaining("strictly newer layout version"); + assertThatThrownBy( + () -> + owner.supersedeStaleInitialBootstrapIntent( + original.operationId(), original.requestId(), newerLayout, source)) + .hasMessageContaining("fresh distinct request"); + assertThatThrownBy( + () -> + owner.supersedeStaleInitialBootstrapIntent( + UUID.randomUUID(), replacementRequest, newerLayout, source)) + .hasMessageContaining("no longer current"); + assertThat(rowImages(dsl, "game_session_canonical_issuer_layout_bootstrap_control")) + .isEqualTo(originalControl); + assertThat(rowImages(dsl, "game_session_canonical_issuer_layout_bootstrap_intent")) + .isEqualTo(originalIntent); + assertThat(countRows(dsl, "game_session_canonical_issuer_bootstrap_supersession")).isZero(); + assertThatThrownBy( + () -> owner.beginInitialBootstrapIntent(replacementRequest, newerLayout, source)) + .hasMessageContaining("different initial issuer-layout bootstrap"); + + // Controlled SQL candidates below test a rejected direct write, never owner authority. + assertRelationOnlySupersessionCannotCommit( + dsl, original, advanced.transition().inventoryRevision(), newerLayout); + assertThat(rowImages(dsl, "game_session_canonical_issuer_layout_bootstrap_intent")) + .isEqualTo(originalIntent); + assertThat(rowImages(dsl, "game_session_canonical_issuer_layout_bootstrap_control")) + .isEqualTo(originalControl); + assertThat(countRows(dsl, "game_session_canonical_issuer_bootstrap_supersession")).isZero(); + var replacement = + owner.supersedeStaleInitialBootstrapIntent( + original.operationId(), replacementRequest, newerLayout, source); + assertThat(replacement.inventorySnapshotRevision()) + .isEqualTo(advanced.transition().inventoryRevision()); + assertThat(replacement.operationFence()) + .isEqualTo(original.coverageFence().add(BigInteger.ONE)); + assertThat(replacement.coverageFence()) + .isEqualTo(replacement.operationFence().add(BigInteger.ONE)); + assertThat(replacement.cohortDigest()).isNotEqualTo(original.cohortDigest()); + assertThat( + CanonicalGameplayIssuerRedisKeys.forPartition( + replacement.layoutDescriptor(), BigInteger.ZERO)) + .isNotEqualTo( + CanonicalGameplayIssuerRedisKeys.forPartition( + original.layoutDescriptor(), BigInteger.ZERO)); + assertThat(rowImages(dsl, "game_session_canonical_issuer_layout_bootstrap_intent")) + .containsAll(originalIntent) + .hasSize(2); + assertThat(rowImages(dsl, "game_session_canonical_issuer_layout_bootstrap_cohort_row")) + .containsAll(originalCohort); + assertThat(rowImages(dsl, "game_session_canonical_issuer_partition_build_plan")) + .isEqualTo(originalPlan); + assertThat(rowImages(dsl, "game_session_canonical_issuer_partition_build_cohort_row")) + .isEqualTo(originalBuildCohort); + assertThat(rowImages(dsl, "game_session_canonical_issuer_partition_build_member_work")) + .isEqualTo(originalWork); + assertThatThrownBy(() -> owner.readCurrentInitialBootstrapIntent(original.operationId())) + .hasMessageContaining("control and immutable intent differ"); + assertThatThrownBy( + () -> plans.prepareInitialBuildPlan(original.operationId(), original.requestId())) + .isInstanceOf(IllegalStateException.class); + var restarted = new CanonicalGameplayIssuerLayoutBootstrapRepository(dsl); + var retry = + restarted.supersedeStaleInitialBootstrapIntent( + original.operationId(), replacementRequest, newerLayout, source); + assertThat(retry.operationId()).isEqualTo(replacement.operationId()); + assertThat(retry.cohortDigest()).isEqualTo(replacement.cohortDigest()); + assertThat( + restarted + .beginInitialBootstrapIntent(replacementRequest, newerLayout, source) + .operationId()) + .isEqualTo(replacement.operationId()); + assertThat( + restarted + .readCurrentInitialBootstrapIntent(replacement.operationId()) + .operationFence()) + .isEqualTo(replacement.operationFence()); + plans.prepareInitialBuildPlan(replacement.operationId(), replacementRequest); + List replacementControl = + rowImages(dsl, "game_session_canonical_issuer_layout_bootstrap_control"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_session_canonical_issuer_layout_bootstrap_control" + + " SET current_operation_id = ?, control_epoch = ?, current_operation_fence = ?," + + " current_coverage_fence = ? WHERE issuer_id = ?", + original.operationId(), + new BigDecimal(original.controlEpoch()), + new BigDecimal(original.operationFence()), + new BigDecimal(original.coverageFence()), + ISSUER)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("requires exact retained supersession lineage"); + assertThat(rowImages(dsl, "game_session_canonical_issuer_layout_bootstrap_control")) + .isEqualTo(replacementControl); + List retainedRelation = + rowImages(dsl, "game_session_canonical_issuer_bootstrap_supersession"); + assertThat(retainedRelation).hasSize(1); + assertThatThrownBy( + () -> + restarted.supersedeStaleInitialBootstrapIntent( + original.operationId(), UUID.randomUUID(), newerLayout, source)) + .hasMessageContaining("no longer current"); + assertThatThrownBy( + () -> + restarted.supersedeStaleInitialBootstrapIntent( + original.operationId(), + replacementRequest, + descriptor( + LAYOUT_VERSION.add(BigInteger.TWO), PARTITION_COUNT, PARTITION_CAPACITY), + source)) + .hasMessageContaining("changed its original trusted inputs"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_session_canonical_issuer_bootstrap_supersession" + + " SET new_inventory_revision = new_inventory_revision")) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy( + () -> dsl.execute("DELETE FROM game_session_canonical_issuer_bootstrap_supersession")) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy( + () -> dsl.execute("TRUNCATE game_session_canonical_issuer_bootstrap_supersession")) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(rowImages(dsl, "game_session_canonical_issuer_bootstrap_supersession")) + .isEqualTo(retainedRelation); + assertThat(countRows(dsl, "game_session_canonical_issuer_layout_bootstrap_intent")) + .isEqualTo(2); + } finally { + dropSchema(testSchema.schema()); + } + } + + private static void assertRelationOnlySupersessionCannotCommit( + DSLContext dsl, + CanonicalGameplayIssuerLayoutBootstrapIntent original, + BigInteger currentRevision, + CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor layout) { + UUID replacementId = UUID.randomUUID(); + BigInteger operationFence = original.coverageFence().add(BigInteger.ONE); + BigInteger coverageFence = operationFence.add(BigInteger.ONE); + assertThatThrownBy( + () -> + dsl.transaction( + configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute( + "INSERT INTO game_session_canonical_issuer_layout_bootstrap_intent" + + " SELECT (jsonb_populate_record(" + + " NULL::game_session_canonical_issuer_layout_bootstrap_intent," + + " to_jsonb(original) || jsonb_build_object(" + + " 'operation_id', ?::uuid, 'request_id', ?::uuid," + + " 'control_epoch', ?::numeric, 'operation_fence', ?::numeric," + + " 'coverage_fence', ?::numeric, 'inventory_snapshot_revision', ?::numeric," + + " 'layout_version', ?::numeric, 'layout_descriptor_bytes', ?::bytea," + + " 'layout_descriptor_digest', ?::text))).*" + + " FROM game_session_canonical_issuer_layout_bootstrap_intent original" + + " WHERE original.operation_id = ?", + replacementId, + UUID.randomUUID(), + new BigDecimal(operationFence), + new BigDecimal(operationFence), + new BigDecimal(coverageFence), + new BigDecimal(currentRevision), + new BigDecimal(layout.layoutVersion()), + layout.exactBytes(), + CanonicalGameplayIssuerMemberV2Codec.sha256(layout.exactBytes()), + original.operationId()); + transaction.execute( + "INSERT INTO game_session_canonical_issuer_bootstrap_supersession" + + " (issuer_id, old_operation_id, new_operation_id, old_inventory_revision," + + " new_inventory_revision, old_operation_fence, old_coverage_fence," + + " previous_last_issued_fence, new_operation_fence, new_coverage_fence)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + ISSUER, + original.operationId(), + replacementId, + new BigDecimal(original.inventorySnapshotRevision()), + new BigDecimal(currentRevision), + new BigDecimal(original.operationFence()), + new BigDecimal(original.coverageFence()), + new BigDecimal(original.coverageFence()), + new BigDecimal(operationFence), + new BigDecimal(coverageFence)); + })) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasStackTraceContaining("must move exact current control in the same transaction"); + } + + private static CanonicalGameplayAdmissionAbortSource prepareActualProvisionalFirstNew( + TestSchema testSchema) { + var runtimeTarget = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( + testSchema.dataSource(), TENANT_ID); + CanonicalGameplayBindingIdentity candidate = + new CanonicalGameplayBindingIdentity( + ACCOUNT_ID, + runtimeTarget.canonicalTenantId(), + runtimeTarget.playableStateNamespaceId(), + PREPARED_CHARACTER_ID, + runtimeTarget.playableStateScope(), + runtimeTarget.gameInstanceUuid(), + runtimeTarget.gameInstanceId(), + UUID.randomUUID().toString(), + REGION_ID, + BigInteger.valueOf(12), + ISSUER, + BigInteger.valueOf(7), + LAYOUT_VERSION, + PARTITION_COUNT, + PARTITION_CAPACITY); + UUID transitionId = UUID.randomUUID(); + var reservation = + new CanonicalIssuerReservationFenceEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + BigInteger.ONE, + BigInteger.TWO, + BigInteger.ONE); + var inventory = new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); + inventory.prepare( + new CanonicalGameplayBindingTransitionRequest( + transitionId, UUID.randomUUID(), candidate, reservation, null, null)); + var prepared = inventory.readProvisionalCasEvidence(transitionId); + CanonicalPlayableTarget target = runtimeTarget.playableTarget(); + var lease = + controlledLeaseEvidence(candidate, prepared.transition().bindingGeneration(), target); + inventory.markProvisional( + prepared, + new CanonicalGameplayAdmissionDecision( + transitionId, + lease, + candidate, + prepared.transition().bindingGeneration(), + null, + target)); + return inventory.readFirstNewAdmissionAbortSource(transitionId); + } + + private static AccountGameplayAdmissionLeaseEvidence controlledLeaseEvidence( + CanonicalGameplayBindingIdentity candidate, + BigInteger bindingGeneration, + CanonicalPlayableTarget target) { + long now = System.currentTimeMillis(); + String nowSeconds = Long.toString(now / 1000L); + Map carrier = new java.util.LinkedHashMap<>(); + carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + carrier.put("schemaVersion", "1"); + carrier.put("mode", "PUBLIC_PRODUCTION"); + carrier.put("leaseKind", AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING.name()); + carrier.put("targetNamespace", target.targetNamespace()); + carrier.put( + "callerWorkload", + "spiffe://firemud/ns/" + target.targetNamespace() + "/sa/game-session-service"); + carrier.put("requestId", UUID.randomUUID().toString()); + carrier.put("leaseId", UUID.randomUUID().toString()); + carrier.put("leaseFence", "1"); + carrier.put( + "bindingScope", + Map.ofEntries( + Map.entry("accountId", candidate.accountId().toString()), + Map.entry("tenantId", candidate.tenantId().toString()), + Map.entry("realmId", target.realmId().toString()), + Map.entry("worldSlug", target.worldSlug()), + Map.entry("realmSlug", target.realmSlug()), + Map.entry("playableStateNamespaceId", target.playableStateNamespaceId().toString()), + Map.entry("playableStateScope", target.playableStateScope()), + Map.entry("gameInstanceId", target.canonicalGameInstanceId().toString()), + Map.entry("characterId", candidate.characterId().toString()), + Map.entry("sessionId", candidate.sessionId()), + Map.entry("bindingGeneration", bindingGeneration.toString()), + Map.entry("catalogRevision", Long.toString(target.catalogRevision())), + Map.entry("pointerVersion", Long.toString(target.pointerVersion())), + Map.entry("regionId", candidate.regionId().toString()), + Map.entry("regionEpoch", candidate.regionEpoch().toString()))); + carrier.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", candidate.issuerAuthGeneration().toString(), + "accountAuthorityGeneration", "1", + "tenantAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1"), + "membershipAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1"), + "privateRealmGrantVersions", List.of())); + carrier.put("issuanceFence", "1"); + carrier.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", "ACTIVE", + "membershipVersion", Map.of(candidate.tenantId().toString(), "1"), + "membershipAuthorityGeneration", "1")); + String prefix = "account:auth-authority:v1:"; + List> checkpoints = new java.util.ArrayList<>(); + for (String stream : + List.of( + "account/" + candidate.accountId(), + "issuer/" + candidate.issuerId(), + "membership/" + candidate.accountId() + "/" + candidate.tenantId(), + "tenant/" + candidate.tenantId())) { + checkpoints.add( + Map.of( + "outboxStreamKey", + prefix + stream, + "outboxSequence", + stream.startsWith("membership/") || stream.startsWith("tenant/") ? "1" : "0")); + } + carrier.put("outboxCheckpoints", checkpoints); + carrier.put( + "tokenIdentityEvidence", + Map.ofEntries( + Map.entry("accountId", candidate.accountId().toString()), + Map.entry("operationId", UUID.randomUUID().toString()), + Map.entry("issuanceRequestId", UUID.randomUUID().toString()), + Map.entry("tokenJti", UUID.randomUUID().toString()), + Map.entry("tokenSHA256", "a".repeat(64)), + Map.entry("tokenProfile", "game-session-account-delegation"), + Map.entry("tokenGeneration", "1"), + Map.entry("issuanceFence", "1"), + Map.entry("tokenIdentityFence", "1"), + Map.entry("issuedAt", nowSeconds), + Map.entry("notBefore", nowSeconds), + Map.entry("expiresAt", Long.toString(now / 1000L + 60L)))); + carrier.put("evaluatedAt", Long.toString(now)); + carrier.put( + "expiresAt", + Long.toString(now + AccountGameplayAdmissionLeaseEvidence.MAX_DURATION_MILLIS)); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + } + private static Attempt attempt( DSLContext dsl, UUID requestId, From 3ef811dc53fce280db1442904929c1efab5adddf Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 03:03:22 +1300 Subject: [PATCH 25/34] Preserve bootstrap lineage and partition-local issuer progress --- .../player-access-and-session.md | 2 + ...calGameplayBindingInventoryRepository.java | 9 +- ...IssuerBindingLocalOperationRepository.java | 2 +- ...ssuerBindingLocalProjectionRepository.java | 145 +++++--- ...ingLocalRetirementOperationRepository.java | 8 +- ...playIssuerBootstrapCoverageRepository.java | 99 +++++- ...playIssuerPartitionMutationRepository.java | 140 ++++++-- ...issuer_partition_mutation_head_lineage.sql | 319 ++++++++++++++++++ ...calOperationRepositoryIntegrationTest.java | 181 ++++++++++ ...BindingLocalRedisOwnerIntegrationTest.java | 73 +++- ...outBootstrapRepositoryIntegrationTest.java | 252 ++++++++++++++ ...suerPhysicalRetirementIntegrationTest.java | 110 ++++++ 12 files changed, 1253 insertions(+), 87 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1038.4__issuer_partition_mutation_head_lineage.sql diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index f4079224db..7fcb2e8308 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for player access and session. Ca ### Canonical NEW admission components +The current local review corrections permit ordinary NEW only after proving the complete retained supersession chain ends at exact installed control. Forward V1038.4 retains prior partition heads and mutation receipts while separating their bootstrap lineages. Local physical projection batches source reads for its target partition, retains issuer-wide capacity/accounting checks on every snapshot, and fences target-partition changes independently of unrelated partition progress. R862 freshly passes all 20 selected PostgreSQL/Redis cases, including real retained-work supersession through installation and ordinary NEW, populated forward-migration retention, unrelated-partition progress and same-partition currentness refusal. Its aggregate fails two new test-only nullable-read warnings; those are corrected locally. A final recovery gate also covers exact retained-abort retry comparison and bounds batched ADD-mutation reads to unretired local operations. Earlier results below retain their original source attribution. + The current local correction adds explicit recovery for a stale, uninstalled initial issuer-bootstrap candidate. Forward V1038.3 retains its original intent, cohort and issued work, captures the new actual inventory cut under monotonic fences, and atomically binds immutable supersession lineage to current control. A strictly newer trusted layout separates old physical work; installed anchors remain ineligible. Account CI selection and migration task inputs now cover its Game Session owner-composition dependency, and the native registration-image and lost-reply proofs use their actual SQL/Lua contracts. R827 passes 31 of 32 focused cases; its remaining failure is a test assertion against the transaction wrapper rather than the nested PostgreSQL refusal. R828 then passes that complete recovery case with affected integration static and formatting checks. Together they qualify 32 distinct current-source cases, including two actual Account abort compositions; frontier, jOOQ, affected static, formatting and documentation checks pass. The new recovery sequence uses controlled Account terminal input through the actual Game Session abort owner, separately from those two authenticated Account compositions. This is focused proof, not a full service-suite, live layout rotation, retained-key cleanup or production-authority claim. The local issuer owners now reject plans that exceed the executable 256-member-operation bound per partition, including retained `RELEASED` lineage independently of logical active capacity. A blocked plan retains its complete cohort and planned work; physical preparation refuses before allocating operation rows. Fresh ordinary NEW registration also checks the same nonretired local-operation set under the inventory lock before allocating new identities or rows, while exact retries retain their original operation at the bound. Both bootstrap owners use one strict Account issuer source-event verifier. R791 freshly passes the four PostgreSQL boundary cases: 256 allowed, both 257-reservation overflow forms blocked, and ordinary registration refusal/retry with unchanged durable state. R793 then freshly passes all 26 selected PostgreSQL cases across the plan, ordinary-operation and intent owners, plus affected production/integration static analysis, formatting and documentation checks. This is focused owner proof, not a complete service-suite or public admission result. Default registration, external source custody and admission limits remain unchanged. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index 47006f10fd..a619859824 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -377,11 +377,14 @@ CanonicalGameplayAdmissionAbortSource recordFirstNewAccountAbort( Objects.requireNonNull(expectedSource, "expectedSource"); requireNonNil(orphanCleanupId, "orphanCleanupId"); if (expectedSource.isAccountAborted()) { - if (!orphanCleanupId.equals(expectedSource.orphanCleanupId())) { + CanonicalGameplayAdmissionAbortSource retained = + readRetainedDefinitiveFirstNewAccountAbortSource( + expectedSource.transition().transitionId()); + requireSameFirstNewAdmissionAbortSource(expectedSource, retained); + if (!orphanCleanupId.equals(retained.orphanCleanupId())) { throw conflict("Account abort retry changed the durable cleanup identity"); } - return readRetainedDefinitiveFirstNewAccountAbortSource( - expectedSource.transition().transitionId()); + return retained; } return dsl.transactionResult( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java index 5b2a274b82..0f22a03060 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java @@ -347,7 +347,7 @@ private CanonicalGameplayIssuerBindingLocalOperation recordOrReplayInTransaction readAndRequireReservation(transaction, transitionRequest, prepared, null); CanonicalGameplayIssuerPartitionMutationRepository.PartitionMutationHead mutationHead = CanonicalGameplayIssuerPartitionMutationRepository.readHeadInTransaction( - transaction, reservation.partitionId()); + transaction, actualAnchor.bootstrapOperationId(), reservation.partitionId()); if (mutationHead.pendingMutationId() != null) { throw conflict( "A same-partition physical mutation is unresolved; new issuer admission remains excluded"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java index eb2056240a..347f8c72b6 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java @@ -2,6 +2,7 @@ import java.math.BigDecimal; import java.math.BigInteger; +import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.ArrayList; @@ -133,7 +134,7 @@ private PreparedPartitionWork prepareInTransaction( BigInteger targetPartition = target.reservation().partitionId(); CanonicalGameplayIssuerPartitionMutationRepository.PartitionMutationHead mutationHead = CanonicalGameplayIssuerPartitionMutationRepository.readHeadInTransaction( - transaction, targetPartition); + transaction, anchor.bootstrapOperationId(), targetPartition); CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof targetBaseline = CanonicalGameplayIssuerBootstrapCoverageRepository.readInstalledAnchorPartitionProof( @@ -156,12 +157,15 @@ private PreparedPartitionWork prepareInTransaction( transaction.fetch( "SELECT operation.* FROM " + LOCAL_OPERATION - + " operation WHERE operation.issuer_id = ? AND NOT EXISTS (SELECT 1 FROM " + + " operation WHERE operation.issuer_id = ? AND operation.partition_id = ? AND NOT EXISTS (SELECT 1 FROM " + "game_session_canonical_issuer_binding_local_retirement retirement" + " WHERE retirement.original_local_operation_id = operation.operation_id" + " AND retirement.status = 'RETIRED')" + " ORDER BY operation.operation_fence, operation.operation_id", - ISSUER); + ISSUER, + targetPartition); + PartitionSources sources = + readPartitionSources(transaction, operationRows, anchor, targetPartition); List entries = new ArrayList<>(operationRows.size()); Set localReservationIds = new HashSet<>(); Set localBindingRefs = new HashSet<>(); @@ -173,7 +177,7 @@ private PreparedPartitionWork prepareInTransaction( proofsByPartition.put(targetPartition, targetBaseline); int partitionLocalOperationCount = 0; - BigInteger localAggregateCapacity = BigInteger.ZERO; + BigInteger localAggregateCapacity = readIssuerLocalCapacity(transaction); BigInteger localPartitionCapacity = BigInteger.ZERO; boolean foundTarget = false; for (Record row : operationRows) { @@ -184,6 +188,7 @@ private PreparedPartitionWork prepareInTransaction( anchor, target, proofsByPartition, + sources, requireCurrentTargetAccountControl && uuid(row, "operation_id").equals(target.operationId())); if (!localOperationIds.add(entry.operationId()) @@ -210,8 +215,6 @@ private PreparedPartitionWork prepareInTransaction( if (entry.countsTowardCapacity()) localPartitionCapacity = localPartitionCapacity.add(BigInteger.ONE); } - if (entry.countsTowardCapacity()) - localAggregateCapacity = localAggregateCapacity.add(BigInteger.ONE); if (entry.registeredOperationId().equals(target.operationId())) { if (!Arrays.equals(entry.exactRegisteredMemberValueBytes(), target.exactMemberValueBytes()) || !entry.registeredMemberValue().equals(target.memberValue()) @@ -238,8 +241,7 @@ private PreparedPartitionWork prepareInTransaction( "A post-baseline issuer operation reuses an installed reservation identity"); } } - BigInteger currentReservationCount = - verifyCurrentReservationAccounting(transaction, anchor, baselineReservationIds.size()); + verifyCurrentReservationAccounting(transaction, anchor, baselineReservationIds.size()); verifyRetirementAccounting(transaction); BigInteger aggregateCapacity = anchor.aggregateCountedCapacity().add(localAggregateCapacity); @@ -281,7 +283,7 @@ private PreparedPartitionWork prepareInTransaction( transaction, kind, target.operationId(), targetPartition, intent); mutationHead = CanonicalGameplayIssuerPartitionMutationRepository.readHeadInTransaction( - transaction, targetPartition); + transaction, anchor.bootstrapOperationId(), targetPartition); if (physicalMutation.status() == CanonicalGameplayIssuerPartitionMutation.Status.PENDING_PHYSICAL_PROOF && !physicalMutation.mutationId().equals(mutationHead.pendingMutationId())) { @@ -320,8 +322,6 @@ private PreparedPartitionWork prepareInTransaction( anchor, targetBaseline.exactPhysicalFieldSetBytes(), entries, - currentReservationCount, - aggregateCapacity, partitionCapacity, mutationHead.currentRevision(), mutationHead.pendingMutationId()); @@ -357,7 +357,7 @@ private PreparedPartitionWork prepareInTransaction( requireQualifiedBaseline(anchor, baseline, baselineFields); CanonicalGameplayIssuerPartitionMutationRepository.PartitionMutationHead partitionHead = CanonicalGameplayIssuerPartitionMutationRepository.readHeadInTransaction( - transaction, partitionId); + transaction, anchor.bootstrapOperationId(), partitionId); byte[] initialRevision = baselineFields.remove( CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MUTATION_REVISION_FIELD); @@ -369,6 +369,83 @@ private PreparedPartitionWork prepareInTransaction( return baseline; } + private static BigInteger readIssuerLocalCapacity(DSLContext transaction) { + Record row = + transaction.fetchOne( + "SELECT COUNT(*) AS count FROM " + + LOCAL_OPERATION + + " operation JOIN " + + RESERVATION + + " reservation ON reservation.reservation_id = operation.reservation_id" + + " AND reservation.issuer_id = operation.issuer_id" + + " WHERE operation.issuer_id = ? AND reservation.lifecycle <> 'RELEASED'" + + " AND NOT EXISTS (SELECT 1 FROM game_session_canonical_issuer_binding_local_retirement retirement" + + " WHERE retirement.original_local_operation_id = operation.operation_id AND retirement.status = 'RETIRED')", + ISSUER); + if (row == null) throw unavailable("The issuer-wide local capacity count is unavailable"); + return number(row, "count"); + } + + private static PartitionSources readPartitionSources( + DSLContext transaction, + List operations, + CanonicalGameplayIssuerInstalledAnchor anchor, + BigInteger partitionId) { + List reservationIds = + operations.stream().map(row -> uuid(row, "reservation_id")).toList(); + List transitionIds = operations.stream().map(row -> uuid(row, "transition_id")).toList(); + List bindingRefs = operations.stream().map(row -> bytes(row, "binding_ref")).toList(); + Map reservations = + readSourceRows(transaction, RESERVATION, "reservation_id", reservationIds); + Map transitions = + readSourceRows(transaction, TRANSITION, "transition_id", transitionIds); + Map obligations = + readSourceRows(transaction, ISSUER_OBLIGATION, "transition_id", transitionIds); + Map inventory = new HashMap<>(); + for (Record row : + transaction + .select() + .from(org.jooq.impl.DSL.table(INVENTORY)) + .where(org.jooq.impl.DSL.field("binding_ref", byte[].class).in(bindingRefs)) + .fetch()) { + if (inventory.put(ByteBuffer.wrap(bytes(row, "binding_ref")), row) != null) + throw unavailable("Duplicate local issuer inventory source rows"); + } + Map mutations = new HashMap<>(); + for (var mutation : + CanonicalGameplayIssuerPartitionMutationRepository.readPartitionInTransaction( + transaction, anchor.bootstrapOperationId(), partitionId)) { + if (mutations.put(new MutationKey(mutation.kind(), mutation.ownerOperationId()), mutation) + != null) throw unavailable("Duplicate local issuer mutation source rows"); + } + return new PartitionSources(reservations, inventory, transitions, obligations, mutations); + } + + private static Map readSourceRows( + DSLContext transaction, String table, String identityColumn, List identities) { + Map rows = new HashMap<>(); + for (Record row : + transaction + .select() + .from(org.jooq.impl.DSL.table(table)) + .where(org.jooq.impl.DSL.field(identityColumn, UUID.class).in(identities)) + .fetch()) { + if (rows.put(uuid(row, identityColumn), row) != null) + throw unavailable("Duplicate local issuer source rows in " + table); + } + return rows; + } + + private record MutationKey( + CanonicalGameplayIssuerPartitionMutation.Kind kind, UUID ownerOperationId) {} + + private record PartitionSources( + Map reservations, + Map inventory, + Map transitions, + Map obligations, + Map mutations) {} + private LocalEntry readLocalEntry( DSLContext transaction, Record row, @@ -378,6 +455,7 @@ private LocalEntry readLocalEntry( BigInteger, CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof> proofsByPartition, + PartitionSources sources, boolean requireCurrentAccountControl) { if (!ISSUER.equals(text(row, "issuer_id")) || !"PENDING_PHYSICAL_PROOF".equals(text(row, "member_status")) @@ -484,22 +562,11 @@ private LocalEntry readLocalEntry( "A durable local issuer operation no longer links to its exact immutable baseline partition"); } - Record reservationRow = - transaction.fetchOne( - "SELECT * FROM " + RESERVATION + " WHERE reservation_id = ?", - reservation.reservationId()); + Record reservationRow = sources.reservations().get(reservation.reservationId()); Record inventoryRow = - transaction.fetchOne( - "SELECT * FROM " + INVENTORY + " WHERE binding_ref = ?", - member.owner().bindingRef().bytes()); - Record transitionRow = - transaction.fetchOne( - "SELECT * FROM " + TRANSITION + " WHERE transition_id = ?", reservation.transitionId()); - Record issuerObligation = - transaction.fetchOne( - "SELECT * FROM " + ISSUER_OBLIGATION + " WHERE transition_id = ? AND binding_ref = ?", - reservation.transitionId(), - member.owner().bindingRef().bytes()); + sources.inventory().get(ByteBuffer.wrap(member.owner().bindingRef().bytes())); + Record transitionRow = sources.transitions().get(reservation.transitionId()); + Record issuerObligation = sources.obligations().get(reservation.transitionId()); if (reservationRow == null || inventoryRow == null || transitionRow == null @@ -524,17 +591,17 @@ private LocalEntry readLocalEntry( transaction, row, member.owner().accountId()); } CanonicalGameplayIssuerPartitionMutation capacityMutation = - CanonicalGameplayIssuerPartitionMutationRepository.readOptionalInTransaction( - transaction, - CanonicalGameplayIssuerPartitionMutation.Kind.ADD_CAPACITY, - operationId, - reservation.partitionId()); + sources + .mutations() + .get( + new MutationKey( + CanonicalGameplayIssuerPartitionMutation.Kind.ADD_CAPACITY, operationId)); CanonicalGameplayIssuerPartitionMutation bindingMutation = - CanonicalGameplayIssuerPartitionMutationRepository.readOptionalInTransaction( - transaction, - CanonicalGameplayIssuerPartitionMutation.Kind.ADD_BINDING, - operationId, - reservation.partitionId()); + sources + .mutations() + .get( + new MutationKey( + CanonicalGameplayIssuerPartitionMutation.Kind.ADD_BINDING, operationId)); boolean capacityMustBePresent = (capacityMutation != null && capacityMutation.status() @@ -1193,8 +1260,6 @@ private static byte[] currentnessDigest( CanonicalGameplayIssuerInstalledAnchor anchor, byte[] baselineBytes, List entries, - BigInteger reservationCount, - BigInteger aggregateCapacity, BigInteger partitionCapacity, UUID currentRevision, UUID pendingMutationId) { @@ -1217,8 +1282,6 @@ private static byte[] currentnessDigest( digest.update((byte) (entry.capacityMustBePresent() ? 1 : 0)); digest.update((byte) (entry.bindingMustBePresent() ? 1 : 0)); } - update(digest, reservationCount.toString().getBytes(StandardCharsets.US_ASCII)); - update(digest, aggregateCapacity.toString().getBytes(StandardCharsets.US_ASCII)); update(digest, partitionCapacity.toString().getBytes(StandardCharsets.US_ASCII)); update(digest, currentRevision.toString().getBytes(StandardCharsets.US_ASCII)); update( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java index fde559faef..8a414f064b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java @@ -77,7 +77,9 @@ CanonicalGameplayIssuerBindingLocalRetirementOperation prepareOrResume(UUID tran CanonicalGameplayIssuerPartitionMutationRepository.PartitionMutationHead head = CanonicalGameplayIssuerPartitionMutationRepository.readHeadInTransaction( - transaction, partitionId); + transaction, + release.originalOperation().anchor().bootstrapOperationId(), + partitionId); if (head.pendingMutationId() != null) { throw conflict("Another same-partition mutation is unresolved before retirement"); } @@ -579,7 +581,9 @@ private static CanonicalGameplayIssuerBindingLocalRetirementOperation readOperat release.releasedMemberValue().reservation().partitionId()); CanonicalGameplayIssuerPartitionMutationRepository.PartitionMutationHead head = CanonicalGameplayIssuerPartitionMutationRepository.readHeadInTransaction( - transaction, release.releasedMemberValue().reservation().partitionId()); + transaction, + release.originalOperation().anchor().bootstrapOperationId(), + release.releasedMemberValue().reservation().partitionId()); if ((mutation.status() == CanonicalGameplayIssuerPartitionMutation.Status.PENDING_PHYSICAL_PROOF && (!mutation.mutationId().equals(head.pendingMutationId()) || !mutation.expectedRevision().equals(head.currentRevision()))) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java index c415569def..ad0e3fe074 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java @@ -221,16 +221,7 @@ Optional readInstalledAnchor( throw conflict("Current issuer-control tuple is malformed or no longer positive"); } - List issuerIntents = - transaction.fetch( - "SELECT operation_id FROM " - + "game_session_canonical_issuer_layout_bootstrap_intent" - + " WHERE issuer_id = ? ORDER BY operation_id FOR UPDATE", - ISSUER); - if (issuerIntents.size() != 1 - || !currentOperationId.equals(requireUuid(issuerIntents.get(0), "operation_id"))) { - throw conflict("A conflicting or unpointed issuer layout intent prevents ordinary NEW"); - } + requireRetainedSupersessionLineage(transaction, currentOperationId); Record intentRequest = transaction.fetchOne( @@ -267,6 +258,88 @@ Optional readInstalledAnchor( return actual; } + /** Every retained intent must belong to the one issuer-bound chain ending at current control. */ + private static void requireRetainedSupersessionLineage( + DSLContext transaction, UUID currentOperationId) { + Map intents = new HashMap<>(); + for (Record intent : + transaction.fetch( + "SELECT * FROM game_session_canonical_issuer_layout_bootstrap_intent" + + " WHERE issuer_id = ? ORDER BY operation_id FOR UPDATE", + ISSUER)) { + intents.put(requireUuid(intent, "operation_id"), intent); + } + Map incoming = new HashMap<>(); + Set outgoing = new HashSet<>(); + for (Record relation : + transaction.fetch( + "SELECT * FROM game_session_canonical_issuer_bootstrap_supersession" + + " WHERE issuer_id = ? ORDER BY old_operation_id FOR UPDATE", + ISSUER)) { + UUID oldId = requireUuid(relation, "old_operation_id"); + UUID newId = requireUuid(relation, "new_operation_id"); + Record oldIntent = intents.get(oldId); + Record newIntent = intents.get(newId); + if (oldIntent == null + || newIntent == null + || oldId.equals(newId) + || !outgoing.add(oldId) + || incoming.put(newId, relation) != null + || !ISSUER.equals(requireText(relation, "issuer_id")) + || !readInteger(relation, "old_inventory_revision") + .equals(readInteger(oldIntent, "inventory_snapshot_revision")) + || !readInteger(relation, "new_inventory_revision") + .equals(readInteger(newIntent, "inventory_snapshot_revision")) + || !readInteger(relation, "old_operation_fence") + .equals(readInteger(oldIntent, "operation_fence")) + || !readInteger(relation, "old_coverage_fence") + .equals(readInteger(oldIntent, "coverage_fence")) + || !readInteger(relation, "new_operation_fence") + .equals(readInteger(newIntent, "operation_fence")) + || !readInteger(relation, "new_coverage_fence") + .equals(readInteger(newIntent, "coverage_fence")) + || readInteger(newIntent, "inventory_snapshot_revision") + .compareTo(readInteger(oldIntent, "inventory_snapshot_revision")) + <= 0 + || readInteger(newIntent, "layout_version") + .compareTo(readInteger(oldIntent, "layout_version")) + <= 0 + || !readInteger(oldIntent, "control_epoch") + .equals(readInteger(oldIntent, "operation_fence")) + || !readInteger(newIntent, "control_epoch") + .equals(readInteger(newIntent, "operation_fence")) + || readInteger(relation, "previous_last_issued_fence") + .compareTo(readInteger(oldIntent, "operation_fence")) + < 0 + || readInteger(relation, "previous_last_issued_fence") + .compareTo(readInteger(oldIntent, "coverage_fence")) + < 0 + || !readInteger(newIntent, "operation_fence") + .equals(readInteger(relation, "previous_last_issued_fence").add(BigInteger.ONE)) + || !readInteger(newIntent, "coverage_fence") + .equals(readInteger(newIntent, "operation_fence").add(BigInteger.ONE)) + || requireUuid(newIntent, "request_id").equals(requireUuid(oldIntent, "request_id")) + || requireUuid(newIntent, "request_id").equals(oldId)) { + throw conflict("Malformed retained issuer bootstrap supersession lineage"); + } + } + Set visited = new HashSet<>(); + UUID cursor = currentOperationId; + if (outgoing.contains(cursor)) { + throw conflict("Current issuer intent is not the terminal supersession lineage"); + } + while (cursor != null) { + if (!intents.containsKey(cursor) || !visited.add(cursor)) { + throw conflict("Broken or cyclic retained issuer bootstrap supersession lineage"); + } + Record edge = incoming.get(cursor); + cursor = edge == null ? null : requireUuid(edge, "old_operation_id"); + } + if (visited.size() != intents.size() || incoming.size() != intents.size() - 1) { + throw conflict("A conflicting or unpointed issuer layout intent prevents ordinary NEW"); + } + } + /** Exact immutable baseline field set for one partition of the installed initial anchor. */ static InstalledAnchorPartitionProof readInstalledAnchorPartitionProof( DSLContext transaction, @@ -301,8 +374,9 @@ static InstalledAnchorPartitionProof readInstalledAnchorPartitionProof( transaction.fetchOne( "SELECT * FROM " + CanonicalGameplayIssuerPartitionMutationRepository.HEAD_TABLE - + " WHERE issuer_id = ? AND partition_id = ?", + + " WHERE issuer_id = ? AND bootstrap_operation_id = ? AND partition_id = ?", ISSUER, + anchor.bootstrapOperationId(), partitionId); if (mutationHead == null || !anchor @@ -655,8 +729,9 @@ private static ProofSummary verifyCompleteProof( transaction.fetchOne( "SELECT * FROM " + CanonicalGameplayIssuerPartitionMutationRepository.HEAD_TABLE - + " WHERE issuer_id = ? AND partition_id = ?", + + " WHERE issuer_id = ? AND bootstrap_operation_id = ? AND partition_id = ?", ISSUER, + intent.operationId(), partitionId); if (mutationHead == null || !intent.operationId().equals(mutationHead.get("bootstrap_operation_id", UUID.class)) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionMutationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionMutationRepository.java index 750905089e..b10ad47936 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionMutationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionMutationRepository.java @@ -6,7 +6,9 @@ import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.Arrays; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; @@ -39,8 +41,11 @@ static UUID ensureInitialRevisionInTransaction( requirePartition(partitionId); Record existing = transaction.fetchOne( - "SELECT * FROM " + HEAD + " WHERE issuer_id = ? AND partition_id = ? FOR UPDATE", + "SELECT * FROM " + + HEAD + + " WHERE issuer_id = ? AND bootstrap_operation_id = ? AND partition_id = ? FOR UPDATE", ISSUER, + bootstrapOperationId, partitionId); if (existing != null) { if (!bootstrapOperationId.equals(uuid(existing, "bootstrap_operation_id"))) { @@ -103,8 +108,11 @@ static void recordInitialPhysicalReadbackInTransaction( } Record row = transaction.fetchOne( - "SELECT * FROM " + HEAD + " WHERE issuer_id = ? AND partition_id = ? FOR UPDATE", + "SELECT * FROM " + + HEAD + + " WHERE issuer_id = ? AND bootstrap_operation_id = ? AND partition_id = ? FOR UPDATE", ISSUER, + bootstrapOperationId, partitionId); if (row == null || !bootstrapOperationId.equals(uuid(row, "bootstrap_operation_id")) @@ -151,14 +159,16 @@ static CanonicalGameplayIssuerPartitionMutation prepareInTransaction( throw conflict("Exact intended issuer partition mutation is missing or oversized"); } String digest = CanonicalGameplayIssuerMemberV2Codec.sha256(exactIntendedChangeBytes); - Record current = lockCurrentHead(transaction, partitionId); + UUID bootstrapOperationId = installedBootstrapOperationId(transaction); + Record current = lockCurrentHead(transaction, bootstrapOperationId, partitionId); Record existing = transaction.fetchOne( "SELECT * FROM " + MUTATION - + " WHERE issuer_id = ? AND partition_id = ? AND mutation_kind = ?" + + " WHERE issuer_id = ? AND bootstrap_operation_id = ? AND partition_id = ? AND mutation_kind = ?" + " AND owner_operation_id = ? FOR UPDATE", ISSUER, + bootstrapOperationId, partitionId, kind.name(), ownerOperationId); @@ -189,12 +199,13 @@ static CanonicalGameplayIssuerPartitionMutation prepareInTransaction( transaction.execute( "INSERT INTO " + MUTATION - + " (mutation_id, issuer_id, partition_id, mutation_kind, owner_operation_id," + + " (mutation_id, issuer_id, bootstrap_operation_id, partition_id, mutation_kind, owner_operation_id," + " expected_revision, successor_revision, exact_intended_change_bytes," + " exact_intended_change_digest, status)" - + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING_PHYSICAL_PROOF')", + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING_PHYSICAL_PROOF')", mutationId, ISSUER, + bootstrapOperationId, partitionId, kind.name(), ownerOperationId, @@ -207,16 +218,24 @@ static CanonicalGameplayIssuerPartitionMutation prepareInTransaction( transaction.execute( "UPDATE " + HEAD - + " SET pending_mutation_id = ? WHERE issuer_id = ? AND partition_id = ?" + + " SET pending_mutation_id = ? WHERE issuer_id = ? AND bootstrap_operation_id = ? AND partition_id = ?" + " AND state = 'CURRENT' AND current_revision = ? AND pending_mutation_id IS NULL", mutationId, ISSUER, + bootstrapOperationId, partitionId, expected); if (advanced != 1) throw conflict("Issuer partition mutation reservation compare-and-set refused"); Record saved = - transaction.fetchOne("SELECT * FROM " + MUTATION + " WHERE mutation_id = ?", mutationId); + transaction.fetchOne( + "SELECT * FROM " + + MUTATION + + " WHERE issuer_id = ? AND bootstrap_operation_id = ? AND partition_id = ? AND mutation_id = ?", + ISSUER, + bootstrapOperationId, + partitionId, + mutationId); if (saved == null) throw conflict("Issuer partition mutation is unreadable after preparation"); return readMutation(saved); } @@ -274,12 +293,20 @@ static CanonicalGameplayIssuerPartitionMutation completeInTransaction( exactReadbackFieldSetBytes); requireRevisionField(readbackFields, expected.successorRevision()); String readbackDigest = CanonicalGameplayIssuerMemberV2Codec.sha256(exactReadbackFieldSetBytes); - Record head = lockCurrentHead(transaction, expected.partitionId()); + UUID bootstrapOperationId = installedBootstrapOperationId(transaction); + Record head = lockCurrentHead(transaction, bootstrapOperationId, expected.partitionId()); Record row = transaction.fetchOne( - "SELECT * FROM " + MUTATION + " WHERE mutation_id = ? FOR UPDATE", + "SELECT * FROM " + + MUTATION + + " WHERE issuer_id = ? AND bootstrap_operation_id = ? AND partition_id = ? AND mutation_id = ? FOR UPDATE", + ISSUER, + bootstrapOperationId, + expected.partitionId(), expected.mutationId()); - if (row == null) throw conflict("Issuer partition mutation disappeared before completion"); + if (row == null || !bootstrapOperationId.equals(uuid(row, "bootstrap_operation_id"))) + throw conflict( + "Issuer partition mutation disappeared or changed bootstrap lineage before completion"); CanonicalGameplayIssuerPartitionMutation current = readMutation(row); requireSameMutation(expected, current); if (current.status() == CanonicalGameplayIssuerPartitionMutation.Status.COMMITTED) { @@ -299,10 +326,14 @@ static CanonicalGameplayIssuerPartitionMutation completeInTransaction( + MUTATION + " SET status = 'COMMITTED', exact_readback_field_set_bytes = ?," + " exact_readback_field_set_digest = ?, completed_at = CURRENT_TIMESTAMP" - + " WHERE mutation_id = ? AND status = 'PENDING_PHYSICAL_PROOF'" + + " WHERE issuer_id = ? AND bootstrap_operation_id = ? AND partition_id = ?" + + " AND mutation_id = ? AND status = 'PENDING_PHYSICAL_PROOF'" + " AND expected_revision = ? AND successor_revision = ?", exactReadbackFieldSetBytes, readbackDigest, + ISSUER, + bootstrapOperationId, + current.partitionId(), current.mutationId(), current.expectedRevision(), current.successorRevision()); @@ -313,10 +344,11 @@ static CanonicalGameplayIssuerPartitionMutation completeInTransaction( "UPDATE " + HEAD + " SET current_revision = ?, pending_mutation_id = NULL" - + " WHERE issuer_id = ? AND partition_id = ? AND state = 'CURRENT'" + + " WHERE issuer_id = ? AND bootstrap_operation_id = ? AND partition_id = ? AND state = 'CURRENT'" + " AND current_revision = ? AND pending_mutation_id = ?", current.successorRevision(), ISSUER, + bootstrapOperationId, current.partitionId(), current.expectedRevision(), current.mutationId()); @@ -324,7 +356,13 @@ static CanonicalGameplayIssuerPartitionMutation completeInTransaction( throw conflict("Issuer partition mutation head completion compare-and-set refused"); Record completed = transaction.fetchOne( - "SELECT * FROM " + MUTATION + " WHERE mutation_id = ?", current.mutationId()); + "SELECT * FROM " + + MUTATION + + " WHERE issuer_id = ? AND bootstrap_operation_id = ? AND partition_id = ? AND mutation_id = ?", + ISSUER, + bootstrapOperationId, + current.partitionId(), + current.mutationId()); if (completed == null) throw conflict("Committed issuer partition mutation is unreadable"); return readMutation(completed); } @@ -338,9 +376,10 @@ static CanonicalGameplayIssuerPartitionMutation readInTransaction( transaction.fetchOne( "SELECT * FROM " + MUTATION - + " WHERE issuer_id = ? AND partition_id = ? AND mutation_kind = ?" + + " WHERE issuer_id = ? AND bootstrap_operation_id = ? AND partition_id = ? AND mutation_kind = ?" + " AND owner_operation_id = ?", ISSUER, + installedBootstrapOperationId(transaction), partitionId, kind.name(), ownerOperationId); @@ -357,17 +396,49 @@ static CanonicalGameplayIssuerPartitionMutation readOptionalInTransaction( transaction.fetchOne( "SELECT * FROM " + MUTATION - + " WHERE issuer_id = ? AND partition_id = ? AND mutation_kind = ?" + + " WHERE issuer_id = ? AND bootstrap_operation_id = ? AND partition_id = ? AND mutation_kind = ?" + " AND owner_operation_id = ?", ISSUER, + installedBootstrapOperationId(transaction), partitionId, kind.name(), ownerOperationId); return row == null ? null : readMutation(row); } - static UUID readCurrentRevisionInTransaction(DSLContext transaction, BigInteger partitionId) { - Record head = lockCurrentHead(transaction, partitionId); + static List readPartitionInTransaction( + DSLContext transaction, UUID bootstrapOperationId, BigInteger partitionId) { + if (!bootstrapOperationId.equals(installedBootstrapOperationId(transaction))) { + throw conflict( + "Issuer partition mutation history belongs to a different installed bootstrap"); + } + List mutations = new ArrayList<>(); + for (Record row : + transaction.fetch( + "SELECT * FROM " + + MUTATION + + " WHERE issuer_id = ? AND bootstrap_operation_id = ? AND partition_id = ?" + + " AND mutation_kind IN ('ADD_CAPACITY', 'ADD_BINDING')" + + " AND owner_operation_id IN (SELECT operation.operation_id" + + " FROM game_session_canonical_issuer_binding_local_operation operation" + + " WHERE operation.issuer_id = ? AND operation.partition_id = ?" + + " AND NOT EXISTS (SELECT 1 FROM game_session_canonical_issuer_binding_local_retirement retirement" + + " WHERE retirement.original_local_operation_id = operation.operation_id" + + " AND retirement.status = 'RETIRED'))" + + " ORDER BY mutation_id", + ISSUER, + bootstrapOperationId, + partitionId, + ISSUER, + partitionId)) { + mutations.add(readMutation(row)); + } + return List.copyOf(mutations); + } + + static UUID readCurrentRevisionInTransaction( + DSLContext transaction, UUID bootstrapOperationId, BigInteger partitionId) { + Record head = lockCurrentHead(transaction, bootstrapOperationId, partitionId); if (nullableUuid(head, "pending_mutation_id") != null) { throw conflict("A same-partition physical mutation is still unresolved"); } @@ -375,16 +446,23 @@ static UUID readCurrentRevisionInTransaction(DSLContext transaction, BigInteger } static PartitionMutationHead readHeadInTransaction( - DSLContext transaction, BigInteger partitionId) { - Record head = lockCurrentHead(transaction, partitionId); + DSLContext transaction, UUID bootstrapOperationId, BigInteger partitionId) { + Record head = lockCurrentHead(transaction, bootstrapOperationId, partitionId); UUID pendingMutationId = nullableUuid(head, "pending_mutation_id"); UUID currentRevision = uuid(head, "current_revision"); if (pendingMutationId != null) { Record pending = transaction.fetchOne( - "SELECT * FROM " + MUTATION + " WHERE mutation_id = ? FOR UPDATE", pendingMutationId); + "SELECT * FROM " + + MUTATION + + " WHERE issuer_id = ? AND bootstrap_operation_id = ? AND partition_id = ? AND mutation_id = ? FOR UPDATE", + ISSUER, + bootstrapOperationId, + partitionId, + pendingMutationId); if (pending == null || !ISSUER.equals(text(pending, "issuer_id")) + || !bootstrapOperationId.equals(uuid(pending, "bootstrap_operation_id")) || !partitionId.equals(nonnegative(pending, "partition_id")) || !currentRevision.equals(uuid(pending, "expected_revision")) || !"PENDING_PHYSICAL_PROOF".equals(text(pending, "status"))) { @@ -402,11 +480,27 @@ static void requireRevisionField(Map fields, UUID expectedRevisi } } - private static Record lockCurrentHead(DSLContext transaction, BigInteger partitionId) { + private static UUID installedBootstrapOperationId(DSLContext transaction) { + Record anchor = + transaction.fetchOne( + "SELECT bootstrap_operation_id FROM " + ANCHOR + " WHERE issuer_id = ?", ISSUER); + if (anchor == null) + throw conflict("Issuer partition mutation requires its installed bootstrap anchor"); + return uuid(anchor, "bootstrap_operation_id"); + } + + private static Record lockCurrentHead( + DSLContext transaction, UUID bootstrapOperationId, BigInteger partitionId) { + if (!bootstrapOperationId.equals(installedBootstrapOperationId(transaction))) { + throw conflict("Issuer partition mutation head belongs to a different installed bootstrap"); + } Record head = transaction.fetchOne( - "SELECT * FROM " + HEAD + " WHERE issuer_id = ? AND partition_id = ? FOR UPDATE", + "SELECT * FROM " + + HEAD + + " WHERE issuer_id = ? AND bootstrap_operation_id = ? AND partition_id = ? FOR UPDATE", ISSUER, + bootstrapOperationId, partitionId); if (head == null || !"CURRENT".equals(text(head, "state"))) { throw conflict("Issuer partition has no positively installed current mutation revision"); diff --git a/services/game-session-service/src/main/resources/db/migration/V1038.4__issuer_partition_mutation_head_lineage.sql b/services/game-session-service/src/main/resources/db/migration/V1038.4__issuer_partition_mutation_head_lineage.sql new file mode 100644 index 0000000000..f6287dc347 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1038.4__issuer_partition_mutation_head_lineage.sql @@ -0,0 +1,319 @@ +-- Retain every existing bootstrap head and physical mutation while separating versioned +-- uninstalled bootstrap key domains. No intent, work, pending receipt or history is discarded. +ALTER TABLE game_session_canonical_issuer_partition_mutation_head + DROP CONSTRAINT fk_gs_issuer_partition_mutation_head_bootstrap; +ALTER TABLE game_session_canonical_issuer_partition_mutation_head + ADD CONSTRAINT fk_gs_issuer_partition_mutation_head_bootstrap + FOREIGN KEY (bootstrap_operation_id, issuer_id) + REFERENCES game_session_canonical_issuer_layout_bootstrap_intent (operation_id, issuer_id); + +ALTER TABLE game_session_canonical_issuer_partition_mutation + ADD COLUMN bootstrap_operation_id uuid; + +-- The old primary key makes this association unique. Retention guards remain enabled except for +-- this exact owner-controlled backfill of the newly introduced lineage column. +-- [jooq ignore start] +ALTER TABLE game_session_canonical_issuer_partition_mutation + DISABLE TRIGGER trg_gs_issuer_partition_mutation_history; +UPDATE game_session_canonical_issuer_partition_mutation mutation + SET bootstrap_operation_id = head.bootstrap_operation_id + FROM game_session_canonical_issuer_partition_mutation_head head + WHERE head.issuer_id = mutation.issuer_id AND head.partition_id = mutation.partition_id; +ALTER TABLE game_session_canonical_issuer_partition_mutation + ENABLE TRIGGER trg_gs_issuer_partition_mutation_history; +-- [jooq ignore stop] + +ALTER TABLE game_session_canonical_issuer_partition_mutation + ALTER COLUMN bootstrap_operation_id SET NOT NULL; +ALTER TABLE game_session_canonical_issuer_partition_mutation + ADD CONSTRAINT uq_gs_issuer_partition_mutation_lineage + UNIQUE (issuer_id, bootstrap_operation_id, partition_id, mutation_id); +ALTER TABLE game_session_canonical_issuer_partition_mutation + DROP CONSTRAINT fk_gs_issuer_partition_mutation_head; +ALTER TABLE game_session_canonical_issuer_partition_mutation_head + DROP CONSTRAINT fk_gs_issuer_partition_mutation_head_pending; +ALTER TABLE game_session_canonical_issuer_partition_mutation_head + DROP CONSTRAINT pk_gs_issuer_partition_mutation_head; +ALTER TABLE game_session_canonical_issuer_partition_mutation_head + ADD CONSTRAINT pk_gs_issuer_partition_mutation_head + PRIMARY KEY (issuer_id, bootstrap_operation_id, partition_id); +ALTER TABLE game_session_canonical_issuer_partition_mutation + ADD CONSTRAINT fk_gs_issuer_partition_mutation_head + FOREIGN KEY (issuer_id, bootstrap_operation_id, partition_id) + REFERENCES game_session_canonical_issuer_partition_mutation_head + (issuer_id, bootstrap_operation_id, partition_id); +ALTER TABLE game_session_canonical_issuer_partition_mutation_head + ADD CONSTRAINT fk_gs_issuer_partition_mutation_head_pending + FOREIGN KEY (issuer_id, bootstrap_operation_id, partition_id, pending_mutation_id) + REFERENCES game_session_canonical_issuer_partition_mutation + (issuer_id, bootstrap_operation_id, partition_id, mutation_id) + DEFERRABLE INITIALLY DEFERRED; + +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION guard_canonical_issuer_partition_mutation_history() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.status <> 'PENDING_PHYSICAL_PROOF' + OR NOT EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_installed_anchor anchor + WHERE anchor.issuer_id = NEW.issuer_id + AND anchor.bootstrap_operation_id = NEW.bootstrap_operation_id) + OR NOT EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_partition_mutation_head head + WHERE head.issuer_id = NEW.issuer_id + AND head.bootstrap_operation_id = NEW.bootstrap_operation_id + AND head.partition_id = NEW.partition_id + AND head.state = 'CURRENT' + AND head.current_revision = NEW.expected_revision + AND head.pending_mutation_id IS NULL) THEN + RAISE EXCEPTION 'Issuer partition mutation requires its exact current unreserved revision' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Issuer partition mutation history is immutable'; + END IF; + IF (to_jsonb(NEW) - 'status' - 'exact_readback_field_set_bytes' + - 'exact_readback_field_set_digest' - 'completed_at') + IS DISTINCT FROM + (to_jsonb(OLD) - 'status' - 'exact_readback_field_set_bytes' + - 'exact_readback_field_set_digest' - 'completed_at') THEN + RAISE EXCEPTION 'Issuer partition mutation intent is immutable'; + END IF; + IF OLD.status <> 'PENDING_PHYSICAL_PROOF' + OR NEW.status <> 'COMMITTED' + OR NEW.exact_readback_field_set_bytes IS NULL + OR NEW.exact_readback_field_set_digest IS NULL + OR NEW.completed_at IS NULL THEN + RAISE EXCEPTION 'Issuer partition mutation may only commit one exact readback'; + END IF; + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION guard_canonical_issuer_partition_revision_uniqueness() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_partition_mutation_head head + WHERE head.initial_revision = NEW.successor_revision + OR (head.initial_revision = NEW.expected_revision + AND (head.issuer_id, head.bootstrap_operation_id, head.partition_id) + <> (NEW.issuer_id, NEW.bootstrap_operation_id, NEW.partition_id))) + OR EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_partition_mutation mutation + WHERE mutation.expected_revision = NEW.successor_revision + OR mutation.successor_revision = NEW.successor_revision + OR ((mutation.expected_revision = NEW.expected_revision + OR mutation.successor_revision = NEW.expected_revision) + AND (mutation.issuer_id, mutation.bootstrap_operation_id, mutation.partition_id) + <> (NEW.issuer_id, NEW.bootstrap_operation_id, NEW.partition_id))) THEN + RAISE EXCEPTION 'Issuer partition physical revisions are never reused'; + END IF; + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION guard_canonical_issuer_partition_initial_revision_uniqueness() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_partition_mutation mutation + WHERE mutation.expected_revision = NEW.initial_revision + OR mutation.successor_revision = NEW.initial_revision) + OR EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_partition_mutation_head head + WHERE head.initial_revision = NEW.initial_revision + AND (head.issuer_id, head.bootstrap_operation_id, head.partition_id) + <> (NEW.issuer_id, NEW.bootstrap_operation_id, NEW.partition_id)) THEN + RAISE EXCEPTION 'Issuer partition initial physical revision is reused'; + END IF; + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION guard_canonical_issuer_partition_mutation_head() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.state <> 'INITIAL_INSTALL_PENDING' + OR NOT EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_layout_bootstrap_control control + WHERE control.issuer_id = NEW.issuer_id + AND control.state = 'INITIAL_BOOTSTRAP_INTENT' + AND control.current_operation_id = NEW.bootstrap_operation_id) + OR NEW.current_revision <> NEW.initial_revision + OR NEW.pending_mutation_id IS NOT NULL + OR EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_bootstrap_partition_proof proof + WHERE proof.bootstrap_operation_id = NEW.bootstrap_operation_id + AND proof.partition_id = NEW.partition_id) + OR EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_installed_anchor anchor + WHERE anchor.issuer_id = NEW.issuer_id) THEN + RAISE EXCEPTION 'Initial issuer partition revision requires an uninstalled bootstrap owner'; + END IF; + RETURN NEW; + END IF; + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Issuer partition mutation head is retained'; + END IF; + IF (to_jsonb(NEW) - 'state' - 'current_revision' - 'pending_mutation_id') + IS DISTINCT FROM + (to_jsonb(OLD) - 'state' - 'current_revision' - 'pending_mutation_id') THEN + RAISE EXCEPTION 'Issuer partition mutation-head identity is immutable'; + END IF; + IF OLD.state = 'INITIAL_INSTALL_PENDING' THEN + IF NEW.state <> 'CURRENT' + OR NEW.current_revision <> OLD.initial_revision + OR NEW.pending_mutation_id IS NOT NULL + OR NOT EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_bootstrap_partition_proof proof + WHERE proof.bootstrap_operation_id = OLD.bootstrap_operation_id + AND proof.issuer_id = OLD.issuer_id + AND proof.partition_id = OLD.partition_id + AND proof.initial_physical_mutation_revision = OLD.initial_revision + AND proof.proof_state = 'EXACT_PHYSICAL_READBACK') THEN + RAISE EXCEPTION 'Initial issuer partition revision requires positive bootstrap proof'; + END IF; + ELSIF OLD.pending_mutation_id IS NULL THEN + IF NEW.state <> OLD.state + OR NEW.pending_mutation_id IS NULL + OR NEW.current_revision <> OLD.current_revision THEN + RAISE EXCEPTION 'Issuer partition mutation requires one durable pending operation'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_partition_mutation mutation + WHERE mutation.mutation_id = NEW.pending_mutation_id + AND mutation.issuer_id = OLD.issuer_id + AND mutation.bootstrap_operation_id = OLD.bootstrap_operation_id + AND mutation.partition_id = OLD.partition_id + AND mutation.status = 'PENDING_PHYSICAL_PROOF' + AND mutation.expected_revision = OLD.current_revision) THEN + RAISE EXCEPTION 'Issuer partition pending head lacks its exact prepared mutation'; + END IF; + ELSE + IF NEW.state <> OLD.state + OR NEW.pending_mutation_id IS NOT NULL + OR NEW.current_revision = OLD.current_revision THEN + RAISE EXCEPTION 'Issuer partition revision requires its exact pending operation'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_partition_mutation mutation + WHERE mutation.mutation_id = OLD.pending_mutation_id + AND mutation.issuer_id = OLD.issuer_id + AND mutation.bootstrap_operation_id = OLD.bootstrap_operation_id + AND mutation.partition_id = OLD.partition_id + AND mutation.status = 'COMMITTED' + AND mutation.expected_revision = OLD.current_revision + AND mutation.successor_revision = NEW.current_revision) THEN + RAISE EXCEPTION 'Issuer partition revision does not match its committed mutation'; + END IF; + END IF; + RETURN NEW; +END; +$$; +CREATE OR REPLACE FUNCTION guard_canonical_issuer_binding_local_retirement() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_issuer_binding_local_release_operation release + WHERE release.operation_id = NEW.release_operation_id + AND release.issuer_id = NEW.issuer_id + AND release.partition_id = NEW.partition_id + AND release.original_local_operation_id = NEW.original_local_operation_id + AND release.transition_id = NEW.transition_id + AND release.reservation_id = NEW.reservation_id + AND release.binding_ref = NEW.binding_ref + AND release.original_reservation_fence = NEW.original_reservation_fence + AND release.original_issuer_coverage_operation_id = NEW.original_issuer_coverage_operation_id + AND release.original_issuer_coverage_operation_fence = NEW.original_issuer_coverage_operation_fence + AND release.original_coverage_fence = NEW.original_coverage_fence + AND release.original_inventory_snapshot_revision = NEW.original_inventory_snapshot_revision + AND release.original_reservation_inventory_revision = NEW.original_reservation_inventory_revision + AND release.anchor_issuer_coverage_operation_id = NEW.anchor_issuer_coverage_operation_id + AND release.anchor_operation_fence = NEW.anchor_operation_fence + AND release.anchor_coverage_fence = NEW.anchor_coverage_fence + AND release.anchor_inventory_snapshot_revision = NEW.anchor_inventory_snapshot_revision + AND release.source_inventory_revision = NEW.release_source_inventory_revision + AND release.completion_inventory_revision = NEW.release_completion_inventory_revision + AND release.original_member_value_bytes = NEW.original_member_value_bytes + AND release.original_member_value_digest = NEW.original_member_value_digest + AND release.released_member_value_bytes = NEW.released_member_value_bytes + AND release.released_member_value_digest = NEW.released_member_value_digest + AND release.status = 'RELEASED') THEN + RAISE EXCEPTION 'Issuer retirement must reference the exact committed release receipt' + USING ERRCODE = '23514'; + END IF; + IF NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_issuer_partition_mutation mutation + WHERE mutation.mutation_id = NEW.physical_mutation_id + AND mutation.issuer_id = NEW.issuer_id + AND mutation.bootstrap_operation_id = NEW.anchor_issuer_coverage_operation_id + AND mutation.partition_id = NEW.partition_id + AND mutation.mutation_kind = 'RETIRE' + AND mutation.owner_operation_id = NEW.retirement_operation_id + AND mutation.expected_revision = NEW.expected_revision + AND mutation.successor_revision = NEW.successor_revision + AND mutation.exact_intended_change_bytes = NEW.exact_intended_change_bytes + AND mutation.exact_intended_change_digest = NEW.exact_intended_change_digest + AND mutation.status = 'PENDING_PHYSICAL_PROOF') THEN + RAISE EXCEPTION 'Issuer retirement lacks its exact pending physical mutation' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Issuer local retirement history is immutable'; + END IF; + IF (to_jsonb(NEW) - 'status' - 'exact_absence_readback_field_set_bytes' + - 'exact_absence_readback_field_set_digest' - 'completed_at') + IS DISTINCT FROM + (to_jsonb(OLD) - 'status' - 'exact_absence_readback_field_set_bytes' + - 'exact_absence_readback_field_set_digest' - 'completed_at') THEN + RAISE EXCEPTION 'Issuer local retirement intent is immutable'; + END IF; + IF OLD.status <> 'PENDING_PHYSICAL_PROOF' + OR NEW.status <> 'RETIRED' + OR NEW.exact_absence_readback_field_set_bytes IS NULL + OR NEW.exact_absence_readback_field_set_digest IS NULL + OR NEW.completed_at IS NULL THEN + RAISE EXCEPTION 'Issuer local retirement may only commit one exact absence readback'; + END IF; + IF NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_issuer_partition_mutation mutation + WHERE mutation.mutation_id = NEW.physical_mutation_id + AND mutation.issuer_id = NEW.issuer_id + AND mutation.bootstrap_operation_id = NEW.anchor_issuer_coverage_operation_id + AND mutation.partition_id = NEW.partition_id + AND mutation.mutation_kind = 'RETIRE' + AND mutation.owner_operation_id = NEW.retirement_operation_id + AND mutation.expected_revision = NEW.expected_revision + AND mutation.successor_revision = NEW.successor_revision + AND mutation.exact_intended_change_bytes = NEW.exact_intended_change_bytes + AND mutation.exact_intended_change_digest = NEW.exact_intended_change_digest + AND mutation.status = 'COMMITTED' + AND mutation.exact_readback_field_set_bytes = NEW.exact_absence_readback_field_set_bytes + AND mutation.exact_readback_field_set_digest = NEW.exact_absence_readback_field_set_digest) THEN + RAISE EXCEPTION 'Issuer retirement needs its exact committed physical absence proof'; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] 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 317788fad8..672fa3f1aa 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 @@ -549,6 +549,187 @@ void ordinaryNewPhysicalOperationBoundRefuses257thBeforePreparationAndRetainsExa assertThat(proofImage(dsl)).isEqualTo(proofBefore); } + @Test + void forwardMigrationRetainsCommittedAndPendingPhysicalMutationLineage() { + DSLContext dsl = schema.dsl(); + establishActualLegacyDisposition(dsl); + var source = sourceCheckpoint(BigInteger.valueOf(7)); + 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(); + var state = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + intent.sourceCheckpoint(), stableIncarnation("lineage-migration")); + var anchor = + initialCoverageOwner(dsl, () -> state) + .completeInitialBootstrap(intent.operationId(), intent.requestId()); + var local = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, () -> state) + .beginOrResumeOrdinaryNew( + request("migration-request", "migration-transition", identity("migration"))); + UUID committedId = UUID.randomUUID(); + UUID pendingId = UUID.randomUUID(); + UUID successor = UUID.randomUUID(); + UUID laterSuccessor = UUID.randomUUID(); + UUID initialRevision = + dsl.fetchSingle( + "SELECT current_revision FROM game_session_canonical_issuer_partition_mutation_head WHERE issuer_id = ?", + ISSUER) + .get(0, UUID.class); + byte[] intended = "controlled-pre-upgrade-mutation".getBytes(StandardCharsets.US_ASCII); + byte[] readback = + CanonicalGameplayIssuerBootstrapCoverageRepository.encodeFieldSet( + java.util.Map.of( + CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD, + successor.toString().getBytes(StandardCharsets.US_ASCII))); + // Controlled pre-upgrade SQL receipts exercise retention, immutability and the pending FK. + // They do not claim a Redis mutation/readback or authorize admission; the bootstrap above is + // the actual local SQL/Redis owner, under controlled Account/incarnation collaborators. + dsl.transaction( + configuration -> { + DSLContext transaction = DSL.using(configuration); + insertPreLineageMutation( + transaction, + committedId, + local.operationId(), + "ADD_CAPACITY", + initialRevision, + successor, + intended); + transaction.execute( + "UPDATE game_session_canonical_issuer_partition_mutation_head" + + " SET pending_mutation_id = ? WHERE issuer_id = ?", + committedId, + ISSUER); + transaction.execute( + "UPDATE game_session_canonical_issuer_partition_mutation" + + " SET status = 'COMMITTED', exact_readback_field_set_bytes = ?," + + " exact_readback_field_set_digest = ?, completed_at = CURRENT_TIMESTAMP WHERE mutation_id = ?", + readback, + digest(readback), + committedId); + transaction.execute( + "UPDATE game_session_canonical_issuer_partition_mutation_head" + + " SET current_revision = ?, pending_mutation_id = NULL WHERE issuer_id = ?", + successor, + ISSUER); + insertPreLineageMutation( + transaction, + pendingId, + local.operationId(), + "ADD_BINDING", + successor, + laterSuccessor, + intended); + transaction.execute( + "UPDATE game_session_canonical_issuer_partition_mutation_head" + + " SET pending_mutation_id = ? WHERE issuer_id = ?", + pendingId, + ISSUER); + }); + List beforeHistory = + dsl.fetch( + "SELECT to_jsonb(mutation)::text FROM game_session_canonical_issuer_partition_mutation mutation ORDER BY mutation_id") + .getValues(0, String.class); + List beforeHeads = + dsl.fetch( + "SELECT to_jsonb(head)::text FROM game_session_canonical_issuer_partition_mutation_head head ORDER BY partition_id") + .getValues(0, String.class); + String beforeAnchor = anchorImage(dsl); + String beforeProof = proofImage(dsl); + migrateRemaining(schema); + assertThat( + dsl.fetch( + "SELECT (to_jsonb(mutation) - 'bootstrap_operation_id')::text" + + " FROM game_session_canonical_issuer_partition_mutation mutation ORDER BY mutation_id") + .getValues(0, String.class)) + .containsExactlyElementsOf(beforeHistory); + assertThat( + dsl.fetch( + "SELECT to_jsonb(head)::text FROM game_session_canonical_issuer_partition_mutation_head head ORDER BY partition_id") + .getValues(0, String.class)) + .containsExactlyElementsOf(beforeHeads); + assertThat(anchorImage(dsl)).isEqualTo(beforeAnchor); + assertThat(proofImage(dsl)).isEqualTo(beforeProof); + assertThat( + dsl.fetch( + "SELECT DISTINCT bootstrap_operation_id FROM game_session_canonical_issuer_partition_mutation") + .getValues(0, UUID.class)) + .containsExactly(anchor.bootstrapOperationId()); + dsl.transaction( + configuration -> { + DSLContext transaction = DSL.using(configuration); + var head = + CanonicalGameplayIssuerPartitionMutationRepository.readHeadInTransaction( + transaction, anchor.bootstrapOperationId(), BigInteger.ZERO); + assertThat(head.pendingMutationId()).isEqualTo(pendingId); + assertThat(head.currentRevision()).isEqualTo(successor); + var history = + CanonicalGameplayIssuerPartitionMutationRepository.readPartitionInTransaction( + transaction, anchor.bootstrapOperationId(), BigInteger.ZERO); + assertThat(history).hasSize(2); + assertThat(history.stream().map(CanonicalGameplayIssuerPartitionMutation::status)) + .containsExactlyInAnyOrder( + CanonicalGameplayIssuerPartitionMutation.Status.COMMITTED, + CanonicalGameplayIssuerPartitionMutation.Status.PENDING_PHYSICAL_PROOF); + }); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_session_canonical_issuer_partition_mutation SET bootstrap_operation_id = ? WHERE mutation_id = ?", + UUID.randomUUID(), + pendingId)) + .hasMessageContaining("immutable"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_session_canonical_issuer_partition_mutation_head SET bootstrap_operation_id = ? WHERE issuer_id = ?", + UUID.randomUUID(), + ISSUER)) + .hasMessageContaining("immutable"); + assertThat( + dsl.fetch( + "SELECT conname, pg_get_constraintdef(oid) AS definition FROM pg_constraint" + + " WHERE conrelid IN ('game_session_canonical_issuer_partition_mutation'::regclass," + + " 'game_session_canonical_issuer_partition_mutation_head'::regclass)" + + " AND conname IN ('fk_gs_issuer_partition_mutation_head', 'fk_gs_issuer_partition_mutation_head_pending')") + .getValues("definition", String.class)) + .hasSize(2) + .allSatisfy(definition -> assertThat(definition).contains("bootstrap_operation_id")); + } + + private static void insertPreLineageMutation( + DSLContext transaction, + UUID mutationId, + UUID ownerId, + String kind, + UUID expected, + UUID successor, + byte[] intended) { + transaction.execute( + "INSERT INTO game_session_canonical_issuer_partition_mutation" + + " (mutation_id, issuer_id, partition_id, mutation_kind, owner_operation_id, expected_revision," + + " successor_revision, exact_intended_change_bytes, exact_intended_change_digest, status)" + + " VALUES (?, ?, 0, ?, ?, ?, ?, ?, ?, 'PENDING_PHYSICAL_PROOF')", + mutationId, + ISSUER, + kind, + ownerId, + expected, + successor, + intended, + digest(intended)); + } + private CanonicalGameplayIssuerBootstrapCoverageOwner initialCoverageOwner( DSLContext dsl, CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource source) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java index 2fb5b8438c..2da00814a2 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java @@ -168,6 +168,8 @@ void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() t assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isZero(); assertThat(count(dsl, "game_session_canonical_gameplay_binding_inventory")).isZero(); + assertThat(localRegistrationImage(dsl)).endsWith(":missing"); + CanonicalGameplayIssuerInstalledAnchor anchor = initialCoverageOwner(dsl, currentState::get) .completeInitialBootstrap(intent.operationId(), bootstrapRequestId); @@ -761,6 +763,55 @@ void malformedLuaBindingReferenceAndReleaseCountsRefuseWithoutChangingPartition( } } + @Test + void differentPartitionProgressDoesNotFenceTargetButSamePartitionProgressDoes() throws Exception { + DSLContext dsl = schema.dsl(); + establishActualLegacyDisposition(dsl); + BigInteger partitions = BigInteger.TWO; + UUID bootstrapRequest = UUID.randomUUID(); + var intent = + new CanonicalGameplayIssuerLayoutBootstrapRepository(dsl) + .beginInitialBootstrapIntent( + bootstrapRequest, descriptor(partitions), sourceCheckpoint(BigInteger.valueOf(7))); + migrateRemaining(schema); + var state = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + intent.sourceCheckpoint(), stableIncarnation("partition-isolation")); + initialCoverageOwner(dsl, () -> state) + .completeInitialBootstrap(intent.operationId(), bootstrapRequest); + var runtime = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( + schema.dataSource(), uuid("partition-isolation-tenant")); + List zero = new ArrayList<>(); + CanonicalGameplayBindingIdentity other = null; + for (int index = 0; index < 128 && (zero.size() < 2 || other == null); index++) { + var candidate = identity("partition-isolation-" + index, runtime, partitions); + if (candidate.bindingRef().partitionId(partitions).equals(BigInteger.ZERO)) + zero.add(candidate); + else other = candidate; + } + assertThat(zero).hasSizeGreaterThanOrEqualTo(2); + assertThat(other).isNotNull(); + var operations = new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, () -> state); + var first = + operations.beginOrResumeOrdinaryNew( + request("partition-target", "partition-target-transition", zero.get(0))); + var sql = new CanonicalGameplayIssuerBindingLocalProjectionRepository(dsl, () -> state); + var beforeOther = sql.readPreparedPartitionWork(first); + var second = + operations.beginOrResumeOrdinaryNew( + request("partition-other", "partition-other-transition", other)); + projectionOwner(dsl, () -> state).projectAndRead(second); + // This includes another partition's new reservation, capacity and committed physical revision. + sql.requireStillCurrent(beforeOther); + assertThat(sql.readPreparedPartitionWork(first).localEntries()).hasSize(1); + operations.beginOrResumeOrdinaryNew( + request("partition-same", "partition-same-transition", zero.get(1))); + assertThatThrownBy(() -> sql.requireStillCurrent(beforeOther)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("changed during projection"); + } + private static ConcurrentProjections concurrentProjection( CanonicalGameplayIssuerBindingLocalRedisOwner owner, CanonicalGameplayIssuerBindingLocalOperation first, @@ -877,13 +928,18 @@ private static byte[] ascii(String value) { private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor descriptor() { + return descriptor(PARTITION_COUNT); + } + + private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor + descriptor(BigInteger partitions) { String exact = "issuer-layout-descriptor/v1|" + ISSUER + "|" + LAYOUT_VERSION + "|" - + PARTITION_COUNT + + partitions + "|" + PARTITION_CAPACITY + "|" @@ -891,7 +947,7 @@ private static byte[] ascii(String value) { return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor( ISSUER, LAYOUT_VERSION, - PARTITION_COUNT, + partitions, PARTITION_CAPACITY, CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY, exact.getBytes(StandardCharsets.UTF_8)); @@ -985,6 +1041,13 @@ private static CanonicalGameplayBindingIdentity identityForAccount(String seed, private static CanonicalGameplayBindingIdentity identity( String seed, CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget runtimeTarget) { + return identity(seed, runtimeTarget, PARTITION_COUNT); + } + + private static CanonicalGameplayBindingIdentity identity( + String seed, + CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget runtimeTarget, + BigInteger partitions) { return new CanonicalGameplayBindingIdentity( uuid(seed + "-account"), runtimeTarget.canonicalTenantId(), @@ -999,7 +1062,7 @@ private static CanonicalGameplayBindingIdentity identity( ISSUER, BigInteger.valueOf(7), LAYOUT_VERSION, - PARTITION_COUNT, + partitions, PARTITION_CAPACITY); } @@ -1333,9 +1396,9 @@ private static String localRegistrationImage(DSLContext dsl) { + " || (SELECT coalesce(jsonb_agg(to_jsonb(g) ORDER BY tenant_id, playable_state_namespace_id, character_id), '[]'::jsonb)::text" + " FROM game_session_canonical_binding_generation g) || ':'" + " || (SELECT inventory_revision::text FROM game_session_canonical_binding_inventory_clock WHERE singleton_id = 1) || ':'" - + " || (SELECT coalesce(to_jsonb(c)::text, 'missing') FROM game_session_canonical_issuer_bootstrap_member_op_counter c WHERE issuer_id = '" + + " || coalesce((SELECT to_jsonb(c)::text FROM game_session_canonical_issuer_bootstrap_member_op_counter c WHERE issuer_id = '" + ISSUER - + "')"), + + "'), 'missing')"), "Expected local registration aggregate row") .get(0, String.class); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java index d7052cd5e8..469530fc09 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java @@ -3,14 +3,22 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.sql.Connection; import java.sql.SQLException; +import java.time.Duration; import java.util.EnumSet; import java.util.HexFormat; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -22,6 +30,7 @@ import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; @@ -35,6 +44,7 @@ import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; @@ -42,6 +52,7 @@ import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @@ -70,6 +81,10 @@ class CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest { static PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + @Test void absenceAndRequiredLegacyDispositionCannotCreateAnIntent() { TestSchema testSchema = newTestSchema("gs_issuer_boot_legacy_"); @@ -943,6 +958,243 @@ void staleUninstalledIntentRequiresExplicitFreshLayoutAndPreservesOriginalHistor } } + @Test + void retainedPhysicalWorkDoesNotStrandSupersedingLayoutOrOrdinaryNew() { + TestSchema schema = newTestSchema("gs_issuer_physical_supersede_"); + RedisClient administrator = + RedisClient.create( + RedisURI.Builder.redis(redis.getHost(), redis.getMappedPort(6379)).build()); + String password = UUID.randomUUID().toString(); + RedisClient ownerClient = + RedisClient.create( + RedisURI.Builder.redis(redis.getHost(), redis.getMappedPort(6379)) + .withAuthentication("gamesession_coord_app", password) + .build()); + try (var admin = administrator.connect(ByteArrayCodec.INSTANCE)) { + admin + .sync() + .aclSetuser( + "gamesession_coord_app", + new AclSetuserArgs() + .reset() + .on() + .addPassword(password) + .keyPattern("session:game:index:issuer:*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.HLEN) + .addCommand(CommandType.HGETALL) + .addCommand(CommandType.HSET)); + DSLContext dsl = schema.dsl(); + establishActualLegacyDisposition(dsl); + var bootstrap = new CanonicalGameplayIssuerLayoutBootstrapRepository(dsl); + var source = sourceCheckpoint(BigInteger.valueOf(7)); + var original = + bootstrap.beginInitialBootstrapIntent( + UUID.randomUUID(), + descriptor(LAYOUT_VERSION, PARTITION_COUNT, PARTITION_CAPACITY), + source); + var incarnation = stableSupersessionIncarnation(); + var state = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + original.sourceCheckpoint(), incarnation); + var partitionOwner = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner( + ownerClient, + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution())), + () -> state); + var plans = new CanonicalGameplayIssuerPartitionBuildRepository(dsl); + plans.prepareInitialBuildPlan(original.operationId(), original.requestId()); + var work = + new CanonicalGameplayIssuerBootstrapMemberOperationRepository(dsl) + .preparePartitionWork( + original.operationId(), + original.requestId(), + BigInteger.ZERO, + source, + new CanonicalGameplayIssuerBootstrapMemberOperationRepository + .TrustedStableIncarnation( + incarnation.attestorBinding(), + incarnation.acceptedAttestationDigest(), + incarnation.targetDeploymentEvidence(), + incarnation.coordOpsRoAclDigest(), + incarnation.coordRedisConfigObservedDigest())); + partitionOwner.buildAndRead(work); + byte[] oldKey = + CanonicalGameplayIssuerRedisKeys.forPartition( + original.layoutDescriptor(), BigInteger.ZERO) + .getBytes(StandardCharsets.UTF_8); + byte[] oldPhysical = physicalImage(admin.sync().hgetall(oldKey)); + Map> retained = new LinkedHashMap<>(); + for (String table : + List.of( + "game_session_canonical_issuer_layout_bootstrap_intent", + "game_session_canonical_issuer_layout_bootstrap_cohort_row", + "game_session_canonical_issuer_partition_build_plan", + "game_session_canonical_issuer_partition_build_cohort_row", + "game_session_canonical_issuer_partition_build_member_work", + "game_session_canonical_issuer_bootstrap_member_operation", + "game_session_canonical_issuer_partition_mutation_head")) { + retained.put(table, rowImages(dsl, table)); + } + // Controlled inventory-clock input isolates supersession from unrelated terminalization + // and old-layout reservation blockers. No binding, reservation or admission is fabricated. + assertThat( + dsl.execute( + "UPDATE game_session_canonical_binding_inventory_clock" + + " SET inventory_revision = inventory_revision + 1 WHERE singleton_id = 1")) + .isEqualTo(1); + var replacement = + bootstrap.supersedeStaleInitialBootstrapIntent( + original.operationId(), + UUID.randomUUID(), + descriptor(LAYOUT_VERSION.add(BigInteger.ONE), PARTITION_COUNT, PARTITION_CAPACITY), + source); + var coverage = + new CanonicalGameplayIssuerBootstrapCoverageOwner(dsl, partitionOwner, () -> state); + var anchor = + coverage.completeInitialBootstrap(replacement.operationId(), replacement.requestId()); + assertThat(anchor.bootstrapOperationId()).isEqualTo(replacement.operationId()); + var runtime = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( + schema.dataSource(), TENANT_ID); + var candidate = + new CanonicalGameplayBindingIdentity( + ACCOUNT_ID, + runtime.canonicalTenantId(), + runtime.playableStateNamespaceId(), + UUID.randomUUID(), + runtime.playableStateScope(), + runtime.gameInstanceUuid(), + runtime.gameInstanceId(), + UUID.randomUUID().toString(), + REGION_ID, + BigInteger.valueOf(12), + ISSUER, + BigInteger.valueOf(7), + replacement.layoutDescriptor().layoutVersion(), + PARTITION_COUNT, + PARTITION_CAPACITY); + var request = + new CanonicalGameplayIssuerBindingLocalOperation.Request( + UUID.randomUUID(), UUID.randomUUID(), candidate, null, null); + var local = new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, () -> state); + var ordinaryNew = local.beginOrResumeOrdinaryNew(request); + assertThat(ordinaryNew.anchor().bootstrapOperationId()).isEqualTo(replacement.operationId()); + assertThat(local.beginOrResumeOrdinaryNew(request).operationId()) + .isEqualTo(ordinaryNew.operationId()); + retained.forEach((table, rows) -> assertThat(rowImages(dsl, table)).containsAll(rows)); + assertThat(physicalImage(admin.sync().hgetall(oldKey))).containsExactly(oldPhysical); + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM game_session_canonical_issuer_partition_mutation_head" + + " WHERE bootstrap_operation_id = ? AND state = 'INITIAL_INSTALL_PENDING'", + original.operationId()) + .get(0, Long.class)) + .isEqualTo(1L); + assertThatThrownBy( + () -> + bootstrap.supersedeStaleInitialBootstrapIntent( + replacement.operationId(), + UUID.randomUUID(), + descriptor( + LAYOUT_VERSION.add(BigInteger.TWO), PARTITION_COUNT, PARTITION_CAPACITY), + source)) + .hasMessageContaining("installed issuer anchor forbids"); + assertMalformedSupersessionRefusesOrdinaryNew(dsl, local, request, state); + } finally { + ownerClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + dropSchema(schema.schema()); + } + } + + private static void assertMalformedSupersessionRefusesOrdinaryNew( + DSLContext dsl, + CanonicalGameplayIssuerBindingLocalOperationRepository local, + CanonicalGameplayIssuerBindingLocalOperation.Request request, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState state) { + // Rollback-only corruption fixtures test read-side refusal of unavailable or malformed lineage. + // They are never committed and confer no owner authority. + for (String corruption : + List.of( + "INSERT INTO game_session_canonical_issuer_layout_bootstrap_intent" + + " SELECT (jsonb_populate_record(NULL::game_session_canonical_issuer_layout_bootstrap_intent," + + " to_jsonb(original) || jsonb_build_object('operation_id', gen_random_uuid()," + + " 'request_id', gen_random_uuid(), 'operation_fence', operation_fence + 100," + + " 'control_epoch', operation_fence + 100, 'coverage_fence', coverage_fence + 100))).*" + + " FROM game_session_canonical_issuer_layout_bootstrap_intent original" + + " ORDER BY operation_fence DESC LIMIT 1", + "UPDATE game_session_canonical_issuer_bootstrap_supersession SET old_operation_fence = old_operation_fence + 1")) { + assertThatThrownBy( + () -> + dsl.transaction( + configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute( + "ALTER TABLE game_session_canonical_issuer_bootstrap_supersession DISABLE TRIGGER USER"); + if (corruption.startsWith("UPDATE")) { + transaction.execute( + "ALTER TABLE game_session_canonical_issuer_bootstrap_supersession" + + " DROP CONSTRAINT chk_gs_issuer_bootstrap_supersession"); + transaction.execute( + "ALTER TABLE game_session_canonical_issuer_bootstrap_supersession" + + " DROP CONSTRAINT fk_gs_issuer_bootstrap_supersession_old"); + } + transaction.execute(corruption); + // Invoke the exact anchor gate in this same transaction, without opening + // another connection. + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision( + transaction); + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction( + transaction, state); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + corruption.startsWith("UPDATE") + ? "Malformed retained issuer bootstrap supersession lineage" + : "conflicting or unpointed issuer layout intent"); + assertThat(local.beginOrResumeOrdinaryNew(request).operationId()).isNotNull(); + } + } + + private static byte[] physicalImage(Map fields) { + Map named = new LinkedHashMap<>(); + fields.forEach((key, value) -> named.put(new String(key, StandardCharsets.UTF_8), value)); + return CanonicalGameplayIssuerBootstrapCoverageRepository.encodeFieldSet(named); + } + + private static CanonicalGameplayIssuerMemberV2Value.Incarnation stableSupersessionIncarnation() { + String digest = + CanonicalGameplayIssuerMemberV2Codec.sha256( + "supersession".getBytes(StandardCharsets.US_ASCII)); + var deployment = + new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "controlled-deployment", + "controlled-generation", + List.of("controlled-node"), + "controlled-build", + "controlled-registry", + digest, + "READY", + "boot", + "startup", + "storage", + "aof"); + // Controlled Account source and incarnation collaborators; this is local owner proof, not an + // authenticated Account producer, protected attestor or operational reset-recovery proof. + return new CanonicalGameplayIssuerMemberV2Value.Incarnation( + "controlled-attestor", digest, deployment, digest, digest); + } + private static void assertRelationOnlySupersessionCannotCommit( DSLContext dsl, CanonicalGameplayIssuerLayoutBootstrapIntent original, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java index 84ebe6c892..642c4cb079 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java @@ -29,8 +29,11 @@ import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution; @@ -507,6 +510,113 @@ void unrelatedAccountNewAndOriginalIssuerCleanupSurviveAccountControlAdvance() { .get(0, String.class)) .isEqualTo("ACQUISITION_INTENT"); + var inventoryRepository = new CanonicalGameplayBindingInventoryRepository(fixture.dsl()); + String historyBeforeAbortRetry = durableHistoryImage(fixture.dsl(), NIL_UUID); + String retainedRowsBeforeAbortRetry = fixture.retainedFirstNewAbortRowsImage(); + byte[] fieldsBeforeAbortRetry = physicalFieldSet(partitionKey); + String controlRowsSql = + "SELECT jsonb_build_object(" + + "'clock', (SELECT to_jsonb(clock) FROM game_session_canonical_binding_inventory_clock clock WHERE singleton_id = 1)," + + " 'accountControl', (SELECT to_jsonb(control) FROM game_session_canonical_account_coverage_control control WHERE account_id = ?)," + + " 'issuerControl', (SELECT to_jsonb(control) FROM game_session_canonical_issuer_layout_bootstrap_control control WHERE issuer_id = ?))::text"; + String controlRowsBeforeAbortRetry = + fixture + .dsl() + .fetchSingle(controlRowsSql, accountA.accountId(), accountA.issuerId()) + .get(0, String.class); + Runnable assertAbortRetryUnchanged = + () -> { + assertThat(durableHistoryImage(fixture.dsl(), NIL_UUID)) + .isEqualTo(historyBeforeAbortRetry); + assertThat(fixture.retainedFirstNewAbortRowsImage()) + .isEqualTo(retainedRowsBeforeAbortRetry); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(fieldsBeforeAbortRetry); + assertThat( + fixture + .dsl() + .fetchSingle(controlRowsSql, accountA.accountId(), accountA.issuerId()) + .get(0, String.class)) + .isEqualTo(controlRowsBeforeAbortRetry); + }; + + // Exact terminal retries retain their original provenance after the real Account intent. + var abortRetry = + inventoryRepository.recordFirstNewAccountAbort(abort, abort.orphanCleanupId()); + assertThat(abortRetry.transition()).isEqualTo(abort.transition()); + assertThat(abortRetry.candidate()).isEqualTo(abort.candidate()); + assertThat(abortRetry.reservation()).isEqualTo(abort.reservation()); + assertThat(abortRetry.originalDecision().leaseEvidenceJson()) + .isEqualTo(abort.originalDecision().leaseEvidenceJson()); + assertThat(abortRetry.orphanCleanupId()).isEqualTo(abort.orphanCleanupId()); + assertAbortRetryUnchanged.run(); + + var candidate = abort.candidate(); + var changedCandidate = + new CanonicalGameplayBindingInventoryEntry( + candidate.identity(), + candidate.bindingRef(), + candidate.bindingGeneration(), + candidate.accountIndexFence(), + candidate.issuerReservationId(), + candidate.transitionId(), + candidate.lifecycle(), + candidate.accountIndexState(), + candidate.issuerIndexState() + == CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED + ? CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED + : CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED, + candidate.inventoryRevision()); + var reservation = abort.reservation(); + var changedReservation = + new CanonicalIssuerPartitionReservation( + reservation.reservationId(), + reservation.owner(), + reservation.bindingGeneration(), + reservation.transitionId(), + reservation.partitionId(), + reservation.lifecycle(), + reservation.reservationFence(), + reservation.issuerCoverageOperationId(), + reservation.issuerCoverageOperationFence(), + reservation.coverageFence().add(BigInteger.ONE), + reservation.inventorySnapshotRevision(), + reservation.inventoryRevision()); + // Shape-valid caller objects exercise the SQL comparison; no stored evidence is changed. + for (var changedSource : + List.of( + new CanonicalGameplayAdmissionAbortSource( + abort.transition(), + abort.candidate(), + abort.reservation(), + abort.originalDecision(), + UUID.randomUUID()), + new CanonicalGameplayAdmissionAbortSource( + abort.transition(), + changedCandidate, + abort.reservation(), + abort.originalDecision(), + abort.orphanCleanupId()), + new CanonicalGameplayAdmissionAbortSource( + abort.transition(), + abort.candidate(), + changedReservation, + abort.originalDecision(), + abort.orphanCleanupId()))) { + assertThatThrownBy( + () -> + inventoryRepository.recordFirstNewAccountAbort( + changedSource, changedSource.orphanCleanupId())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("Retained first-NEW abort source changed during exact retry"); + assertAbortRetryUnchanged.run(); + } + assertThat( + inventoryRepository + .recordFirstNewAccountAbort(abort, abort.orphanCleanupId()) + .orphanCleanupId()) + .isEqualTo(abort.orphanCleanupId()); + assertAbortRetryUnchanged.run(); + byte[] beforeStaleAdd = physicalFieldSet(partitionKey); long mutationsBeforeStaleAdd = partitionMutationCount(fixture.dsl()); assertThatThrownBy(() -> fixture.projectOtherControllerNew(staleAccountASeed)) From 95acdbf6720c22c7c73a5e689f1a6a86a65a006b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 03:16:32 +1300 Subject: [PATCH 26/34] Record completed issuer recovery proof explicitly --- .../implementation-tracking/player-access-and-session.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 7fcb2e8308..c31289cead 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for player access and session. Ca ### Canonical NEW admission components -The current local review corrections permit ordinary NEW only after proving the complete retained supersession chain ends at exact installed control. Forward V1038.4 retains prior partition heads and mutation receipts while separating their bootstrap lineages. Local physical projection batches source reads for its target partition, retains issuer-wide capacity/accounting checks on every snapshot, and fences target-partition changes independently of unrelated partition progress. R862 freshly passes all 20 selected PostgreSQL/Redis cases, including real retained-work supersession through installation and ordinary NEW, populated forward-migration retention, unrelated-partition progress and same-partition currentness refusal. Its aggregate fails two new test-only nullable-read warnings; those are corrected locally. A final recovery gate also covers exact retained-abort retry comparison and bounds batched ADD-mutation reads to unretired local operations. Earlier results below retain their original source attribution. +The current local review corrections permit ordinary NEW only after proving the complete retained supersession chain ends at exact installed control. Forward V1038.4 retains prior partition heads and mutation receipts while separating their bootstrap lineages. Local physical projection batches source reads for its target partition, retains issuer-wide capacity/accounting checks on every snapshot, and fences target-partition changes independently of unrelated partition progress. R862 freshly passes all 20 selected PostgreSQL/Redis cases, including real retained-work supersession through installation and ordinary NEW, populated forward-migration retention, unrelated-partition progress and same-partition currentness refusal. Its aggregate fails two new test-only nullable-read warnings. R863 subsequently passes all 21 selected cases and the affected enabled main/integration static, migration-frontier, jOOQ generation, formatting and documentation checks after those warnings are corrected. This recovery also proves exact retained-abort retry comparison and ADD-mutation batch reads bounded to unretired local operations. The earlier failed R862 aggregate remains retained. Earlier results below retain their original source attribution. The current local correction adds explicit recovery for a stale, uninstalled initial issuer-bootstrap candidate. Forward V1038.3 retains its original intent, cohort and issued work, captures the new actual inventory cut under monotonic fences, and atomically binds immutable supersession lineage to current control. A strictly newer trusted layout separates old physical work; installed anchors remain ineligible. Account CI selection and migration task inputs now cover its Game Session owner-composition dependency, and the native registration-image and lost-reply proofs use their actual SQL/Lua contracts. R827 passes 31 of 32 focused cases; its remaining failure is a test assertion against the transaction wrapper rather than the nested PostgreSQL refusal. R828 then passes that complete recovery case with affected integration static and formatting checks. Together they qualify 32 distinct current-source cases, including two actual Account abort compositions; frontier, jOOQ, affected static, formatting and documentation checks pass. The new recovery sequence uses controlled Account terminal input through the actual Game Session abort owner, separately from those two authenticated Account compositions. This is focused proof, not a full service-suite, live layout rotation, retained-key cleanup or production-authority claim. From bd2f159581d2cc0f816c2bf4d6bb30dc903cf8a7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 03:44:46 +1300 Subject: [PATCH 27/34] Keep completed issuer ADD retries read-only after release --- ...ssuerBindingLocalProjectionRepository.java | 41 ++++--- ...lGameplayIssuerBindingLocalRedisOwner.java | 5 +- ...layIssuerBootstrapPartitionRedisOwner.java | 7 +- ...suerPhysicalRetirementIntegrationTest.java | 111 ++++++++++++++++++ 4 files changed, 145 insertions(+), 19 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java index 347f8c72b6..c89d416491 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java @@ -266,21 +266,32 @@ private PreparedPartitionWork prepareInTransaction( targetEntry.bindingPresent() ? CanonicalGameplayIssuerPartitionMutation.Kind.ADD_BINDING : CanonicalGameplayIssuerPartitionMutation.Kind.ADD_CAPACITY; - byte[] intent = - CanonicalGameplayIssuerPartitionMutationRepository.encodeIntendedChange( - kind, - target.operationId(), - targetPartition, - targetEntry.memberValue().owner().bindingRef().bytes(), - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( - targetEntry.memberValue().reservation().reservationId()) - .getBytes(StandardCharsets.US_ASCII), - targetEntry.exactMemberValueBytes(), - (targetEntry.bindingPresent() ? "1" : "0").getBytes(StandardCharsets.US_ASCII), - (targetEntry.countsTowardCapacity() ? "1" : "0").getBytes(StandardCharsets.US_ASCII)); - physicalMutation = - CanonicalGameplayIssuerPartitionMutationRepository.prepareInTransaction( - transaction, kind, target.operationId(), targetPartition, intent); + physicalMutation = sources.mutations().get(new MutationKey(kind, target.operationId())); + // A completed ADD is a historical receipt. Later release changes the current projection, + // not the frozen intended change; its replay performs independent current readback only. + if (physicalMutation == null + || physicalMutation.status() + != CanonicalGameplayIssuerPartitionMutation.Status.COMMITTED) { + if (!targetEntry.operationId().equals(target.operationId())) { + throw unavailable("A changed terminal projection cannot issue or resume an ADD mutation"); + } + byte[] intent = + CanonicalGameplayIssuerPartitionMutationRepository.encodeIntendedChange( + kind, + target.operationId(), + targetPartition, + targetEntry.memberValue().owner().bindingRef().bytes(), + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + targetEntry.memberValue().reservation().reservationId()) + .getBytes(StandardCharsets.US_ASCII), + targetEntry.exactMemberValueBytes(), + (targetEntry.bindingPresent() ? "1" : "0").getBytes(StandardCharsets.US_ASCII), + (targetEntry.countsTowardCapacity() ? "1" : "0") + .getBytes(StandardCharsets.US_ASCII)); + physicalMutation = + CanonicalGameplayIssuerPartitionMutationRepository.prepareInTransaction( + transaction, kind, target.operationId(), targetPartition, intent); + } mutationHead = CanonicalGameplayIssuerPartitionMutationRepository.readHeadInTransaction( transaction, anchor.bootstrapOperationId(), targetPartition); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java index c2151b6fab..741ef960b6 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java @@ -109,7 +109,7 @@ public Readback projectAndRead(CanonicalGameplayIssuerBindingLocalOperation oper requireNoAmbientTransaction(); var work = projectionRepository.prepareAddMutationWork(operation); requireFreshCurrentState(work); - if (!work.targetEntry().operationId().equals(operation.operationId())) { + if (!work.targetEntry().registeredOperationId().equals(operation.operationId())) { throw unavailable(); } CanonicalGameplayIssuerPartitionMutation mutation = work.physicalMutation(); @@ -122,6 +122,7 @@ public Readback projectAndRead(CanonicalGameplayIssuerBindingLocalOperation oper projectionRepository.requireStillCurrent(work); return new Readback(operation, 3L, currentReadback); } + if (!work.targetEntry().operationId().equals(operation.operationId())) throw unavailable(); if (!mutation.mutationId().equals(work.pendingMutationId()) || !mutation.expectedRevision().equals(work.currentRevision())) { throw unavailable(); @@ -331,7 +332,7 @@ private byte[] readExactPhysicalState( work.targetOperation().memberValue().reservation().partitionId())) .count()); if (BigInteger.valueOf(physicalCapacityCount).compareTo(work.anchor().partitionCapacity()) > 0 - || physicalCapacityCount < baselineCapacityCount + 1 + || physicalCapacityCount < baselineCapacityCount + (target.countsTowardCapacity() ? 1 : 0) || physicalCapacityCount > baselineCapacityCount + registeredCapacityCount || physicalReservationCount < baselineReservationCount + 1 || physicalReservationCount > baselineReservationCount + registeredReservationCount diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwner.java index 2abc820fb4..6fd2a8f84f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwner.java @@ -117,8 +117,11 @@ public Readback buildAndRead(CanonicalGameplayIssuerBootstrapPartitionWork work) } /** - * Reads and verifies the exact current physical field set for an installed-anchor retry or - * reader. This method never creates, repairs, or rebuilds a missing partition. + * Verifies only the original bootstrap field set and initial revision, before any local + * post-anchor mutation. It deliberately refuses a later ADD, release or retirement projection. + * Completed-original bootstrap retries use retained installation evidence instead; ordinary + * current-state readers use the binding-local projection owner. This method never creates, + * repairs or rebuilds a missing partition. */ public Readback readExistingAndRead(CanonicalGameplayIssuerBootstrapPartitionWork work) { Objects.requireNonNull(work, "Prepared issuer partition work is required"); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java index 642c4cb079..505ac1730c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java @@ -764,6 +764,117 @@ void refusesRegistrationBeyondTheCurrentLocalEntryBoundWithoutWrites() { } } + @Test + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "VA_PRIMITIVE_ARRAY_PASSED_TO_OBJECT_VARARG", + justification = + "RedisCommands takes binary field keys; byte[][] supplies one field. Native deletion and readback verify the exact semantics.") + void completedAddRetryReadsReleasedZeroCapacityStateWithoutWritesAndRejectsPhysicalDrift() { + try (var fixture = newFixture(BigInteger.valueOf(16), BigInteger.ONE, 0)) { + String capacityAddSql = + "SELECT to_jsonb(mutation)::text FROM game_session_canonical_issuer_partition_mutation mutation" + + " WHERE mutation_kind = 'ADD_CAPACITY' AND owner_operation_id = ?"; + String originalCapacityAddReceipt = + fixture + .dsl() + .fetchSingle(capacityAddSql, fixture.originalOperationId()) + .get(0, String.class); + fixture.publishOriginalWithControlledAccountLease(); + assertThat(fixture.recordOriginalAccountAbort().isAccountAborted()).isTrue(); + var pendingRelease = fixture.prepareIssuerRelease(); + var released = + fixture.completeIssuerRelease( + pendingRelease, fixture.projectIssuerRelease(pendingRelease)); + assertThat(released.status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); + var originalMember = + CanonicalGameplayIssuerMemberV2Codec.decode(fixture.originalMemberValueBytes()); + var current = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + originalMember.sourceCheckpoint(), originalMember.incarnation()); + var projectionRepository = + new CanonicalGameplayIssuerBindingLocalProjectionRepository(fixture.dsl(), () -> current); + var originalOperation = released.originalOperation(); + var work = projectionRepository.readPreparedPartitionWork(originalOperation); + assertThat(work.baselineProof().physicalCountedCapacityCount()).isZero(); + assertThat(work.targetEntry().countsTowardCapacity()).isFalse(); + assertThat(work.partitionCapacity()).isZero(); + assertThat(work.aggregateCapacity()).isZero(); + var owner = + new CanonicalGameplayIssuerBindingLocalRedisOwner( + issuerOwner, + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayIssuerBindingLocalRedisScriptContribution())), + projectionRepository, + () -> current); + byte[] partitionKey = fixture.issuerPartitionKey(); + byte[] releasedFields = physicalFieldSet(partitionKey); + assertThat(capacityFieldCount(releasedFields)).isEqualTo(1L); + String releasedCapacityName = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + released.releasedMemberValue().reservation().reservationId()); + assertThat(decodeFields(releasedFields)) + .containsEntry(releasedCapacityName, released.exactReleasedMemberValueBytes()); + String historyBefore = durableHistoryImage(fixture.dsl(), NIL_UUID); + String headBefore = partitionHeadImage(fixture.dsl(), fixture.originalPartitionId()); + String anchorBefore = anchorAndPartitionProofImage(fixture.dsl()); + String retainedBefore = fixture.retainedFirstNewAbortRowsImage(); + Runnable assertSqlUnchanged = + () -> { + assertThat( + fixture + .dsl() + .fetchSingle(capacityAddSql, fixture.originalOperationId()) + .get(0, String.class)) + .isEqualTo(originalCapacityAddReceipt); + assertThat(durableHistoryImage(fixture.dsl(), NIL_UUID)).isEqualTo(historyBefore); + assertThat(partitionHeadImage(fixture.dsl(), fixture.originalPartitionId())) + .isEqualTo(headBefore); + assertThat(anchorAndPartitionProofImage(fixture.dsl())).isEqualTo(anchorBefore); + assertThat(fixture.retainedFirstNewAbortRowsImage()).isEqualTo(retainedBefore); + }; + var retry = owner.projectAndRead(originalOperation); + assertThat(retry.scriptOutcome()).isEqualTo(3L); + assertThat(retry.exactReadbackBytes()).containsExactly(releasedFields); + assertThat(physicalFieldSet(partitionKey)).containsExactly(releasedFields); + assertSqlUnchanged.run(); + + byte[] capacityField = releasedCapacityName.getBytes(StandardCharsets.US_ASCII); + byte[] revisionField = + CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD.getBytes( + StandardCharsets.US_ASCII); + // Administrator-injected absence and conflicting bytes remain non-admitting on read-only + // retry. + for (byte[] field : List.of(capacityField, revisionField)) { + byte[] originalValue = + java.util.Objects.requireNonNull( + administratorCommands.hget(partitionKey, field), + "Expected original released field"); + for (boolean missing : List.of(true, false)) { + if (missing) administratorCommands.hdel(partitionKey, new byte[][] {field}); + else + administratorCommands.hset( + partitionKey, + field, + (Arrays.equals(field, revisionField) + ? UUID.randomUUID().toString() + : "changed-release-field") + .getBytes(StandardCharsets.US_ASCII)); + byte[] injectedFields = physicalFieldSet(partitionKey); + assertThatThrownBy(() -> owner.projectAndRead(originalOperation)) + .isInstanceOf(IllegalStateException.class); + assertThat(physicalFieldSet(partitionKey)).containsExactly(injectedFields); + assertSqlUnchanged.run(); + administratorCommands.hset(partitionKey, field, originalValue); + assertThat(physicalFieldSet(partitionKey)).containsExactly(releasedFields); + } + } + assertThat(owner.projectAndRead(originalOperation).scriptOutcome()).isEqualTo(3L); + assertThat(physicalFieldSet(partitionKey)).containsExactly(releasedFields); + assertSqlUnchanged.run(); + } + } + @Test void ordinaryAddRefusesMissingPartitionRevisionWithoutRedisOrSqlWrites() throws Exception { try (var fixture = newFixture(BigInteger.valueOf(4), BigInteger.ONE, 0)) { From 7cec9f93a35b4635b1fe6691f756bb251ab7fbfd Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 05:37:21 +1300 Subject: [PATCH 28/34] test: separate current abort composition from historical migration proof --- ...nitiveAbortCompositionIntegrationTest.java | 512 ++++++++++++++++-- 1 file changed, 462 insertions(+), 50 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java index 620f5d6eab..72da645ffc 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java @@ -13,6 +13,10 @@ import java.nio.file.Files; import java.nio.file.Path; import java.time.Clock; +import java.time.OffsetDateTime; +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; @@ -35,7 +39,12 @@ import net.firedevops.firemud.gamesession.repository.CanonicalGameplayAdmissionAbortManualFactory; import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerBindingLocalReleaseOperation; import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; @@ -43,6 +52,7 @@ import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; +import org.springframework.jdbc.datasource.DriverManagerDataSource; /** * Actual Account acquisition/current caller/physical token and abort owner, real GS durable @@ -637,10 +647,19 @@ void actualCompletedMemberAckSurvivesAccountAbortAndRetainsUnresolvedPhysicalCle } } + @Test + void controlledHistoricalV1038AbortRowsAndHistorySurviveForwardCleanupMigration() + throws Exception { + accountFixtures.temporaryDirectory = temporaryDirectory; + // Reuse only the run-owned PostgreSQL connection; no current Game Session owner is + // constructed against V1038, and no transport or Redis authority is fabricated. + new HistoricalRetainedAbortMigration().verify(accountFixtures.newFixture(null).dataSource); + } + @Test void actualAcknowledgedAbortCleanupSurvivesLaterAccountIntentAndRetiresExactIssuerMember() throws Exception { - try (var session = open(MigrationVersion.fromVersion("1038"))) { + try (var session = open(true)) { var acknowledgement = session.gs.repairAccountMember(); assertThat(acknowledgement.transitionId()).isEqualTo(session.gs.transitionId()); assertThat(session.gs.hasExactAccountMember()).isTrue(); @@ -681,40 +700,10 @@ void actualAcknowledgedAbortCleanupSurvivesLaterAccountIntentAndRetiresExactIssu assertThat(session.gs.hasExactOtherControllerMember(newerMemberSeed)).isTrue(); assertThat(session.gs.hasExactAccountMember()).isTrue(); - var retainedRowsBeforeUpgrade = session.gs.retainedFirstNewAbortRowsImage(); - var migrationHistoryBeforeUpgrade = session.gs.migrationHistoryImage(); - assertThat(migrationHistoryBeforeUpgrade) - .anyMatch(row -> row.contains("V1000__create_saga_schema.sql")) - .anyMatch(row -> row.contains("V1001__saga_instance_table.sql")) - .anyMatch(row -> row.contains("V1002__saga_step_table.sql")); - var issuerFieldsBeforeUpgrade = session.gs.issuerPartitionFieldSetBytes(); - assertThat( - session - .gs - .dsl() - .fetchSingle( - "SELECT state FROM game_session_canonical_account_coverage_control" - + " WHERE account_id = ?", - session.gs.candidate().accountId()) - .get(0, String.class)) - .isEqualTo("ACQUISITION_INTENT"); - assertThat( - session.gs.upgradeWithDefaultGameSessionMigrations( - MigrationVersion.fromVersion("1038.1"))) - .isEqualTo(1); - var migrationHistoryAfterUpgrade = session.gs.migrationHistoryImage(); - assertThat(migrationHistoryAfterUpgrade).hasSize(migrationHistoryBeforeUpgrade.size() + 1); - for (int index = 0; index < migrationHistoryBeforeUpgrade.size(); index++) { - assertThat(migrationHistoryAfterUpgrade.get(index)) - .isEqualTo(migrationHistoryBeforeUpgrade.get(index)); - } - assertThat(migrationHistoryAfterUpgrade.get(migrationHistoryAfterUpgrade.size() - 1)) - .contains("1038.1", "V1038.1__retained_first_new_abort_cleanup_account_control.sql"); - assertThat(session.gs.retainedFirstNewAbortRowsImage()).isEqualTo(retainedRowsBeforeUpgrade); + var retainedRowsBeforeRetry = session.gs.retainedFirstNewAbortRowsImage(); + var issuerFieldsBeforeRetry = session.gs.issuerPartitionFieldSetBytes(); assertThat(session.gs.memberAcknowledgementImage()).isEqualTo(originalAck); assertThat(session.gs.accountObligationPhaseImage()).isEqualTo(originalPhase); - assertThat(session.gs.issuerPartitionFieldSetBytes()) - .containsExactly(issuerFieldsBeforeUpgrade); assertThat(session.gs.hasExactAccountMember()).isTrue(); assertThat(session.gs.hasExactOtherControllerMember(newerMemberSeed)).isTrue(); @@ -729,11 +718,11 @@ void actualAcknowledgedAbortCleanupSurvivesLaterAccountIntentAndRetiresExactIssu assertThat(abortRetry.accountOperation().originalLeaseEvidence().canonicalJson()) .isEqualTo(session.lease.canonicalJson()); assertThat(session.image()).isEqualTo(imageBeforeAbortRetry); - assertThat(session.gs.retainedFirstNewAbortRowsImage()).isEqualTo(retainedRowsBeforeUpgrade); + assertThat(session.gs.retainedFirstNewAbortRowsImage()).isEqualTo(retainedRowsBeforeRetry); assertThat(session.gs.memberAcknowledgementImage()).isEqualTo(originalAck); assertThat(session.gs.accountObligationPhaseImage()).isEqualTo(originalPhase); assertThat(session.gs.issuerPartitionFieldSetBytes()) - .containsExactly(issuerFieldsBeforeUpgrade); + .containsExactly(issuerFieldsBeforeRetry); var pendingRelease = session.gs.prepareIssuerRelease(); var releaseReadback = session.gs.projectIssuerRelease(pendingRelease); @@ -840,11 +829,6 @@ private Session open(boolean prepareMemberRepair) throws Exception { return new Session(prepareMemberRepair); } - private Session open(MigrationVersion migrationTarget) throws Exception { - accountFixtures.temporaryDirectory = temporaryDirectory; - return new Session(true, migrationTarget); - } - private final class Session implements AutoCloseable { private final PhysicalRedisFixture redis = PhysicalRedisFixture.start(); private final AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.Fixture @@ -861,11 +845,6 @@ private final class Session implements AutoCloseable { private AccountGameplayAdmissionLeaseEvidence lease; private Session(boolean prepareMemberRepair) throws Exception { - this(prepareMemberRepair, null); - } - - private Session(boolean prepareMemberRepair, MigrationVersion migrationTarget) - throws Exception { try { accountFixture = accountFixtures.newFixture(redis.client()); var issuance = accountFixture.committedCandidate.identity(); @@ -897,11 +876,7 @@ private Session(boolean prepareMemberRepair, MigrationVersion migrationTarget) java.math.BigInteger.valueOf(prepareMemberRepair ? 3 : 2)); gs = new CanonicalGameplayAdmissionAbortCompositionFixture( - accountFixture.dataSource, - capacityCandidate, - redis.issuerOwnerClient(), - 0, - migrationTarget); + accountFixture.dataSource, capacityCandidate, redis.issuerOwnerClient(), 0); if (prepareMemberRepair) gs.prepareMemberRepairRedis(); pkiDirectory = Files.createTempDirectory(temporaryDirectory, "actual-abort-mtls-"); pki = @@ -1043,4 +1018,441 @@ public void close() throws Exception { } } } + + /** + * Controlled V1038 predecessor storage with installed guards and actual filesystem migrations. + * Lease, terminal Account outcome and member readback are stipulated historical SQL inputs; this + * never invokes current owners or supplies fresh admission, issuer control or grants. + */ + private static final class HistoricalRetainedAbortMigration { + private static final String PREFIX = "game_session_canonical_"; + private static final List RETAINED_TABLES = + List.of( + "binding_transition", + "gameplay_binding_inventory", + "issuer_partition_reservation", + "binding_account_index_obligation", + "binding_issuer_index_obligation", + "binding_region_bridge_obligation", + "account_member_repair_operation"); + private static final UUID ACCOUNT = UUID.randomUUID(); + private static final UUID TENANT = UUID.randomUUID(); + private static final UUID NAMESPACE = UUID.randomUUID(); + private static final UUID CHARACTER = UUID.randomUUID(); + private static final UUID TRANSITION = UUID.randomUUID(); + private static final UUID RESERVATION = UUID.randomUUID(); + private static final UUID ACCOUNT_FENCE = UUID.randomUUID(); + private static final UUID INSTANCE = UUID.randomUUID(); + private static final UUID REGION = UUID.randomUUID(); + private static final byte[] BINDING_REF = new byte[] {1, 2, 3}; + private static final String MEMBER = "accountIndexMember/v1:AQID:1:" + ACCOUNT_FENCE; + private static final String RAW_DIGEST = "a".repeat(64); + private static final String DIGEST = "sha256:" + RAW_DIGEST; + + void verify(DriverManagerDataSource source) { + String schema = "gs_retained_abort_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = + new DriverManagerDataSource( + java.util.Objects.requireNonNull(source.getUrl(), "Account fixture JDBC URL"), + source.getUsername(), + source.getPassword()); + dataSource.setSchema(schema); + try { + Flyway predecessor = flyway(dataSource, schema, "1038"); + predecessor.migrate(); + predecessor.validate(); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + seedControlledAcknowledgedAbort(dsl); + // Validate the complete terminal predecessor under its original NO_ACTIVE control. All + // installed immediate and deferred guards remain enabled; no current prepare owner is used. + dsl.execute( + "UPDATE " + PREFIX + "binding_transition SET inventory_revision = inventory_revision"); + seedLaterControlledAcquisitionIntent(dsl); + + Map> originalRows = rows(dsl, false); + originalRows.values().forEach(images -> assertThat(images).hasSize(1)); + Map> immutableRows = rows(dsl, true); + assertThat( + dsl.fetchSingle("SELECT state FROM " + PREFIX + "account_coverage_control") + .get(0, String.class)) + .isEqualTo("ACQUISITION_INTENT"); + List historyBefore = history(dsl); + assertThat(historyBefore) + .anyMatch(row -> row.contains("V1000__create_saga_schema.sql")) + .anyMatch(row -> row.contains("V1001__saga_instance_table.sql")) + .anyMatch(row -> row.contains("V1002__saga_step_table.sql")); + assertThat( + dsl.fetchSingle( + "SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1") + .get(0, String.class)) + .isEqualTo("1038"); + + // This is the V1038 defect: a retained abort's exact original ACK must not require the + // account to remain forever at its old NO_ACTIVE epoch. The failed transaction rolls back + // every affected row, including the singleton inventory clock. + assertThatThrownBy(() -> advanceRetainedRevision(dsl)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .rootCause() + .isInstanceOf(org.postgresql.util.PSQLException.class) + .hasMessageContaining("First-NEW Account abort requires its exact retained candidate"); + assertThat(rows(dsl, false)).isEqualTo(originalRows); + assertThat( + dsl.fetchSingle( + "SELECT inventory_revision FROM " + PREFIX + "binding_inventory_clock") + .get(0, Integer.class)) + .isEqualTo(5); + + Flyway upgraded = flyway(dataSource, schema, "1038.1"); + assertThat(upgraded.migrate().migrationsExecuted).isEqualTo(1); + upgraded.validate(); + List historyAfter = history(dsl); + assertThat(historyAfter).hasSize(historyBefore.size() + 1); + assertThat(historyAfter.subList(0, historyBefore.size())) + .containsExactlyElementsOf(historyBefore); + assertThat(historyAfter.get(historyAfter.size() - 1)) + .contains("1038.1", "V1038.1__retained_first_new_abort_cleanup_account_control.sql"); + assertThat(rows(dsl, false)).isEqualTo(originalRows); + assertThat( + dsl.fetchSingle( + "SELECT inventory_revision FROM " + PREFIX + "binding_inventory_clock") + .get(0, Integer.class)) + .isEqualTo(5); + + advanceRetainedRevision(dsl); + assertThat(rows(dsl, true)).isEqualTo(immutableRows); + for (String table : RETAINED_TABLES.subList(0, 6)) { + assertThat( + dsl.fetchSingle("SELECT inventory_revision FROM " + PREFIX + table) + .get(0, Integer.class)) + .isEqualTo(6); + } + assertThat( + dsl.fetchSingle( + "SELECT inventory_revision FROM " + PREFIX + "binding_inventory_clock") + .get(0, Integer.class)) + .isEqualTo(6); + assertThat(history(dsl)).containsExactlyElementsOf(historyAfter); + assertThat(upgraded.migrate().migrationsExecuted).isZero(); + assertThat(history(dsl)).containsExactlyElementsOf(historyAfter); + } finally { + DSL.using(dataSource, SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } + } + + private static void seedControlledAcknowledgedAbort(DSLContext dsl) { + dsl.transaction( + configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute("UPDATE " + PREFIX + "binding_inventory_clock SET inventory_revision = 5"); + insert( + tx, + "account_coverage_control", + Map.of( + "account_id", + ACCOUNT, + "state", + "NO_ACTIVE_ACCOUNT_WIDE_FLOW", + "last_operation_fence", + 0)); + insert( + tx, + "account_member_repair_control", + Map.of( + "account_id", ACCOUNT, + "last_operation_fence", 1, + "last_coverage_generation", 3)); + Map candidate = new LinkedHashMap<>(); + candidate.put("binding_ref", BINDING_REF); + candidate.put("account_id", ACCOUNT); + candidate.put("tenant_id", TENANT); + candidate.put("playable_state_namespace_id", NAMESPACE); + candidate.put("character_id", CHARACTER); + candidate.put("playable_state_scope", "SHARED"); + candidate.put("game_instance_id", INSTANCE); + candidate.put("runtime_game_instance_id", 1L); + candidate.put("session_id", UUID.randomUUID().toString()); + candidate.put("binding_generation", 1); + candidate.put("region_id", REGION); + candidate.put("region_epoch", 1); + candidate.put("issuer_id", "firemud-account-service"); + candidate.put("issuer_auth_generation", 1); + candidate.put("issuer_index_layout_version", 1); + candidate.put("issuer_index_partition_count", 1); + candidate.put("issuer_index_partition_capacity", 3); + candidate.put("issuer_partition_id", 0); + candidate.put("account_index_fence", ACCOUNT_FENCE); + candidate.put("issuer_reservation_id", RESERVATION); + candidate.put("transition_id", TRANSITION); + candidate.put("lifecycle", "TERMINAL_UNRESOLVED"); + candidate.put("account_index_state", "ACKNOWLEDGED"); + candidate.put("issuer_index_state", "REPAIR_REQUIRED"); + candidate.put("inventory_revision", 5); + insert(tx, "gameplay_binding_inventory", candidate); + + Map transition = new LinkedHashMap<>(); + transition.put("transition_id", TRANSITION); + transition.put("tenant_id", TENANT); + transition.put("playable_state_namespace_id", NAMESPACE); + transition.put("character_id", CHARACTER); + transition.put("candidate_binding_ref", BINDING_REF); + transition.put("candidate_binding_generation", 1); + transition.put("candidate_account_index_fence", ACCOUNT_FENCE); + transition.put("issuer_reservation_id", RESERVATION); + transition.put("status", "ABORTED"); + transition.put("inventory_revision", 5); + transition.put("admission_request_id", UUID.randomUUID()); + transition.put("admission_lease_id", UUID.randomUUID()); + transition.put("admission_lease_fence", 1); + transition.put("admission_lease_kind", "NEW_BINDING"); + transition.put("admission_lease_digest", RAW_DIGEST); + transition.put( + "admission_lease_evidence", "{\"controlledHistoricalAccountAbort\":true}"); + transition.put("admission_lease_expires_at", 1); + transition.put("admission_orphan_cleanup_id", UUID.randomUUID()); + transition.put("admission_target_namespace", "test"); + transition.put("admission_target_tenant_slug", "historical-tenant"); + transition.put("admission_target_tenant_id", TENANT); + transition.put("admission_target_world_slug", "historical-world"); + transition.put("admission_target_world_display_name", "Historical world"); + transition.put("admission_target_realm_id", UUID.randomUUID()); + transition.put("admission_target_realm_slug", "historical-realm"); + transition.put("admission_target_realm_display_name", "Historical realm"); + transition.put("admission_target_game_session_tenant_id", 1L); + transition.put("admission_target_game_instance_id", 1L); + transition.put("admission_target_playable_state_namespace_id", NAMESPACE); + transition.put("admission_target_playable_state_scope", "SHARED"); + transition.put("admission_target_canonical_game_instance_id", INSTANCE); + transition.put("admission_target_canonical_version_id", UUID.randomUUID()); + transition.put("admission_target_runtime_version_id", 1L); + transition.put("admission_target_catalog_revision", 1L); + transition.put("admission_target_pointer_version", 1L); + transition.put("admission_target_pointer_snapshot_digest", RAW_DIGEST); + transition.put("admission_target_active_world_epoch", 1L); + transition.put( + "admission_target_initial_admission_request_id", "controlled-historical-request"); + transition.put("admission_target_initial_admission_request_digest", RAW_DIGEST); + transition.put("admission_target_origin_kind", "NO_PRIOR_POINTER"); + transition.put("admission_target_hold_id", UUID.randomUUID()); + transition.put("admission_target_hold_fence", UUID.randomUUID()); + transition.put("admission_target_hold_binding_digest", DIGEST); + transition.put("admission_target_audit_event_id", 1L); + transition.put("admission_target_owner_proof_digest", DIGEST); + transition.put("admission_target_owner_proof_outcome", "COMMITTED"); + transition.put("admission_target_positive_durable_abort", false); + transition.put( + "admission_target_terminal_at", OffsetDateTime.parse("2026-10-26T00:00:00Z")); + transition.put("admission_target_character_creation_policy", "{}"); + insert(tx, "binding_transition", transition); + + Map reservation = new LinkedHashMap<>(candidate); + reservation.remove("issuer_partition_id"); + reservation.remove("account_index_fence"); + reservation.remove("issuer_reservation_id"); + reservation.remove("account_index_state"); + reservation.remove("issuer_index_state"); + reservation.put("reservation_id", RESERVATION); + reservation.put("partition_id", 0); + reservation.put("lifecycle", "RELEASE_PENDING"); + reservation.put("reservation_fence", UUID.randomUUID()); + reservation.put("issuer_coverage_operation_id", UUID.randomUUID()); + reservation.put("issuer_coverage_operation_fence", 1); + reservation.put("coverage_fence", 1); + reservation.put("inventory_snapshot_revision", 1); + insert(tx, "issuer_partition_reservation", reservation); + + Map accountObligation = new LinkedHashMap<>(); + accountObligation.put("transition_id", TRANSITION); + accountObligation.put("obligation_ordinal", 0); + accountObligation.put("binding_ref", BINDING_REF); + accountObligation.put("account_id", ACCOUNT); + accountObligation.put("tenant_id", TENANT); + accountObligation.put("action", "ADD_OR_RETAIN"); + accountObligation.put("binding_generation", 1); + accountObligation.put("account_index_fence", ACCOUNT_FENCE); + accountObligation.put("execution_phase", "BEFORE_FINAL_CAS"); + accountObligation.put("status", "ACKNOWLEDGED"); + accountObligation.put("inventory_revision", 5); + accountObligation.put("projection_state", "PRESENT_AWAITING_COVERAGE"); + accountObligation.put("projection_member", MEMBER); + accountObligation.put("projection_inventory_revision", 4); + insert(tx, "binding_account_index_obligation", accountObligation); + insert( + tx, + "binding_issuer_index_obligation", + Map.of( + "transition_id", + TRANSITION, + "binding_ref", + BINDING_REF, + "binding_generation", + 1, + "reservation_id", + RESERVATION, + "status", + "REQUIRED", + "inventory_revision", + 5)); + Map region = new LinkedHashMap<>(); + for (String key : + List.of( + "transition_id", + "binding_ref", + "binding_generation", + "account_id", + "tenant_id", + "game_instance_id", + "runtime_game_instance_id", + "session_id", + "region_id", + "region_epoch", + "inventory_revision")) { + region.put(key, candidate.get(key)); + } + region.put("status", "REQUIRED"); + insert(tx, "binding_region_bridge_obligation", region); + + Map repair = new LinkedHashMap<>(); + repair.put("operation_id", UUID.randomUUID()); + repair.put("transition_id", TRANSITION); + repair.put("obligation_ordinal", 0); + repair.put("operation_fence", 1); + repair.put("coverage_fence", UUID.randomUUID()); + repair.put("inventory_snapshot_revision", 2); + repair.put("binding_ref", BINDING_REF); + repair.put("account_id", ACCOUNT); + repair.put("tenant_id", TENANT); + repair.put("binding_generation", 1); + repair.put("account_index_fence", ACCOUNT_FENCE); + repair.put("original_action", "ADD_OR_RETAIN"); + repair.put("original_execution_phase", "BEFORE_FINAL_CAS"); + repair.put("original_status", "REQUIRED"); + repair.put("original_inventory_revision", 1); + repair.put("original_projection_state", "REQUIRED"); + repair.put("desired_action", "ADD_OR_RETAIN"); + repair.put("member", MEMBER); + repair.put("account_control_state", "NO_ACTIVE_ACCOUNT_WIDE_FLOW"); + repair.put("account_control_epoch", 0); + repair.put("status", "ACKNOWLEDGED"); + repair.put("coverage_generation", 3); + repair.put("readback_state", "PRESENT"); + repair.put("readback_member", MEMBER); + repair.put("completed_inventory_revision", 4); + insert(tx, "account_member_repair_operation", repair); + }); + } + + private static void seedLaterControlledAcquisitionIntent(DSLContext dsl) { + UUID intent = UUID.randomUUID(); + UUID fence = UUID.randomUUID(); + Map operation = new LinkedHashMap<>(); + operation.put("operation_id", intent); + operation.put("request_id", UUID.randomUUID()); + operation.put("account_id", ACCOUNT); + operation.put("operation_fence", 1); + operation.put("planned_account_admission_fence", fence); + operation.put("inventory_snapshot_revision", 5); + operation.put("legacy_cohort_id", UUID.randomUUID()); + operation.put("legacy_owner_operation_id", UUID.randomUUID()); + operation.put("legacy_writer_fence", UUID.randomUUID()); + operation.put("legacy_source_snapshot_revision", 1); + operation.put("legacy_canonical_inventory_revision", 1); + operation.put("legacy_namespace_index_readback_revision", 1); + operation.put("legacy_evidence_digest", DIGEST); + operation.put("intent_state", "ACQUISITION_INTENT"); + operation.put("cohort_row_count", 0L); + operation.put("cohort_digest", DIGEST); + operation.put("barrier_target_count", 0L); + operation.put("barrier_target_digest", DIGEST); + insert(dsl, "account_admission_fence_intent", operation); + dsl.execute( + "UPDATE " + + PREFIX + + "account_coverage_control SET state = 'ACQUISITION_INTENT'," + + " last_operation_fence = 1, current_operation_fence = 1," + + " current_fence_intent_id = ?, account_admission_fence = ?, inventory_snapshot_revision = 5" + + " WHERE account_id = ?", + intent, + fence, + ACCOUNT); + } + + private static void advanceRetainedRevision(DSLContext dsl) { + dsl.transaction( + configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute("UPDATE " + PREFIX + "binding_inventory_clock SET inventory_revision = 6"); + for (String table : RETAINED_TABLES.subList(0, 6)) { + tx.execute("UPDATE " + PREFIX + table + " SET inventory_revision = 6"); + } + }); + } + + private static Map> rows(DSLContext dsl, boolean immutableOnly) { + Map> rows = new LinkedHashMap<>(); + for (String table : RETAINED_TABLES) { + String expression = "to_jsonb(retained)"; + if (immutableOnly && !table.equals("account_member_repair_operation")) { + expression += " - 'inventory_revision'"; + } + rows.put( + table, + dsl.fetch( + "SELECT (" + + expression + + ")::text AS image FROM " + + PREFIX + + table + + " retained ORDER BY 1") + .getValues("image", String.class)); + } + for (String table : + List.of( + "account_coverage_control", + "account_admission_fence_intent", + "account_member_repair_control")) { + rows.put( + table, + dsl.fetch( + "SELECT to_jsonb(retained)::text AS image FROM " + + PREFIX + + table + + " retained ORDER BY 1") + .getValues("image", String.class)); + } + return rows; + } + + private static void insert(DSLContext dsl, String table, Map values) { + Map, Object> fields = new LinkedHashMap<>(); + values.forEach((column, value) -> fields.put(DSL.field(DSL.name(column)), value)); + dsl.insertInto(DSL.table(DSL.name(PREFIX + table))).set(fields).execute(); + } + + private static List history(DSLContext dsl) { + return dsl.fetch( + "SELECT to_jsonb(history_row)::text AS image FROM flyway_schema_history history_row" + + " ORDER BY installed_rank") + .getValues("image", String.class); + } + + private static Flyway flyway(DriverManagerDataSource dataSource, String schema, String target) { + return Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .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()) + .target(MigrationVersion.fromVersion(target)) + .load(); + } + } } From 77877e04511db5cd6defb8d6e2e7e701e83efa86 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:32:31 +1300 Subject: [PATCH 29/34] Recover original ordinary NEW operations after source progression --- .../player-access-and-session.md | 2 + ...IssuerBindingLocalOperationRepository.java | 31 +++++++-- ...BindingLocalRedisOwnerIntegrationTest.java | 65 ++++++++++++++++++- ...onicalGameplayAdmissionAbortOwnerTest.java | 13 ++-- 4 files changed, 99 insertions(+), 12 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index c31289cead..ec27b3d512 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for player access and session. Ca ### Canonical NEW admission components +Ordinary NEW exact retry now reconstructs the original durable local issuer operation after legitimate provisional and Account-member progression. It retains the frozen reservation, member bytes, operation identity, fences, generation and local snapshot while requiring current eligible source revisions to remain at least the frozen revision and mutually coherent. Initial creation still requires exact current revision; current anchor, lineage, Account control, source/incarnation and lifecycle checks remain mandatory. R918 freshly passes all 17 selected cases (nine units and eight PostgreSQL/Redis cases), including reconstructed operation and projection owners after actual provisional publication, candidate-member presence and physical Account-member repair/acknowledgement. Independent Spring transaction-only and synchronization-only refusals are proved. The current `develop` dependency updates are reconciled locally; migration frontier, jOOQ generation, affected enabled static analysis, formatting and documentation checks pass. These are focused manually composed component results with controlled Account/source collaborators, not operational custody, default registration or public-admission qualification. + The current local review corrections permit ordinary NEW only after proving the complete retained supersession chain ends at exact installed control. Forward V1038.4 retains prior partition heads and mutation receipts while separating their bootstrap lineages. Local physical projection batches source reads for its target partition, retains issuer-wide capacity/accounting checks on every snapshot, and fences target-partition changes independently of unrelated partition progress. R862 freshly passes all 20 selected PostgreSQL/Redis cases, including real retained-work supersession through installation and ordinary NEW, populated forward-migration retention, unrelated-partition progress and same-partition currentness refusal. Its aggregate fails two new test-only nullable-read warnings. R863 subsequently passes all 21 selected cases and the affected enabled main/integration static, migration-frontier, jOOQ generation, formatting and documentation checks after those warnings are corrected. This recovery also proves exact retained-abort retry comparison and ADD-mutation batch reads bounded to unretired local operations. The earlier failed R862 aggregate remains retained. Earlier results below retain their original source attribution. The current local correction adds explicit recovery for a stale, uninstalled initial issuer-bootstrap candidate. Forward V1038.3 retains its original intent, cohort and issued work, captures the new actual inventory cut under monotonic fences, and atomically binds immutable supersession lineage to current control. A strictly newer trusted layout separates old physical work; installed anchors remain ineligible. Account CI selection and migration task inputs now cover its Game Session owner-composition dependency, and the native registration-image and lost-reply proofs use their actual SQL/Lua contracts. R827 passes 31 of 32 focused cases; its remaining failure is a test assertion against the transaction wrapper rather than the nested PostgreSQL refusal. R828 then passes that complete recovery case with affected integration static and formatting checks. Together they qualify 32 distinct current-source cases, including two actual Account abort compositions; frontier, jOOQ, affected static, formatting and documentation checks pass. The new recovery sequence uses controlled Account terminal input through the actual Game Session abort owner, separately from those two authenticated Account compositions. This is focused proof, not a full service-suite, live layout rotation, retained-key cleanup or production-authority claim. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java index 0f22a03060..b112ecaf1e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java @@ -337,7 +337,8 @@ private CanonicalGameplayIssuerBindingLocalOperation recordOrReplayInTransaction proof, currentState, accountControl, - operationRow); + operationRow, + true); } if (operationRow != null) { throw conflict("A local issuer operation already exists for a newly prepared transition"); @@ -397,7 +398,15 @@ private CanonicalGameplayIssuerBindingLocalOperation recordOrReplayInTransaction transitionRequest.transitionId()); if (saved == null) throw conflict("Local issuer operation is unreadable after persistence"); return returnOperation( - request, prepared, reservation, actualAnchor, proof, currentState, accountControl, saved); + request, + prepared, + reservation, + actualAnchor, + proof, + currentState, + accountControl, + saved, + false); } private CanonicalGameplayIssuerBindingLocalOperation returnOperation( @@ -408,9 +417,18 @@ private CanonicalGameplayIssuerBindingLocalOperation returnOperation( CanonicalGameplayIssuerBootstrapCoverageRepository.InstalledAnchorPartitionProof proof, CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState, AccountControlSnapshot accountControl, - Record row) { + Record row, + boolean exactRetry) { requireSameStoredOperation( - row, request, prepared, reservation, anchor, proof, currentState, accountControl, false); + row, + request, + prepared, + reservation, + anchor, + proof, + currentState, + accountControl, + exactRetry); UUID operationId = requireUuid(row, "operation_id"); BigInteger operationFence = readPositive(row, "operation_fence"); BigInteger localMemberGeneration = readPositive(row, "local_member_generation"); @@ -535,6 +553,8 @@ private static CanonicalIssuerPartitionReservation readAndRequireReservation( CanonicalGameplayIssuerMemberV2Value stored = CanonicalGameplayIssuerMemberV2Codec.decode( requireBytes(operationRow, "member_value_bytes")); + // The physical member retains its original revision while owner transitions advance SQL. + // Exact retry must return those frozen bytes without accepting a regressed current source. reservation = stored.reservation(); requireIdentityMatchesReservation(request.candidate(), row); if (!reservation.reservationId().equals(requireUuid(row, "reservation_id")) @@ -553,7 +573,8 @@ private static CanonicalIssuerPartitionReservation readAndRequireReservation( || !reservation .inventorySnapshotRevision() .equals(readPositive(row, "inventory_snapshot_revision")) - || !reservation.inventoryRevision().equals(readPositive(row, "inventory_revision"))) { + || readPositive(row, "inventory_revision").compareTo(reservation.inventoryRevision()) + < 0) { throw conflict( "Current reservation no longer matches its immutable local operation source"); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java index 2da00814a2..74fc535db1 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java @@ -42,8 +42,10 @@ import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountIndexMember; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; @@ -112,6 +114,7 @@ void setUp() { .on() .addPassword(password) .keyPattern(ISSUER_KEY_PREFIX + "*") + .keyPattern("session:game:index:account:*") .addCommand(CommandType.HELLO) .addCommand(CommandType.PING) .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) @@ -123,7 +126,9 @@ void setUp() { .addCommand(CommandType.HGET) .addCommand(CommandType.HLEN) .addCommand(CommandType.HGETALL) - .addCommand(CommandType.HSET)); + .addCommand(CommandType.HSET) + .addCommand(CommandType.SADD) + .addCommand(CommandType.SISMEMBER)); ownerClient = createRedisClient(OWNER_PRINCIPAL, password); schema = newTestSchemaAtVersion("gs_issuer_local_new_"); } @@ -492,7 +497,9 @@ void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() t runtimeTarget.playableTarget()); new CanonicalGameplayBindingInventoryRepository(dsl) .markProvisional(provisionalEvidence, firstDecision); - var firstWithBinding = projectionOwner.projectAndRead(first); + var resumedProvisional = reloadProgressedOperation(dsl, currentState::get, first); + var firstWithBinding = + projectionOwner(dsl, currentState::get).projectAndRead(resumedProvisional); assertThat(firstWithBinding.scriptOutcome()).isEqualTo(2L); var firstProjectedFields = CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( @@ -505,6 +512,33 @@ void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() t .containsEntry(firstCapacityField, first.exactMemberValueBytes()); assertThat(projectionOwner.projectAndRead(first).scriptOutcome()).isEqualTo(3L); + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + var currentProvisional = inventory.readProvisionalCasEvidence(firstRequest.transitionId()); + String accountMember = + CanonicalGameplayAccountIndexMember.of(currentProvisional.candidate()).value(); + inventory.markCandidateAccountIndexPresent(currentProvisional, accountMember); + var resumedPresent = reloadProgressedOperation(dsl, currentState::get, first); + assertThat(resumedPresent.preparedTransition().inventoryRevision()) + .isGreaterThan(resumedProvisional.preparedTransition().inventoryRevision()); + assertThat( + projectionOwner(dsl, currentState::get).projectAndRead(resumedPresent).scriptOutcome()) + .isEqualTo(3L); + + var memberRepair = inventory.beginAccountMemberRepair(firstRequest.transitionId()); + var accountRedisOwner = + new CanonicalGameplayAccountMemberRepairRedisOwner( + ownerClient, RedisScriptCatalog.loadInstalled(getClass().getClassLoader())); + var memberReadback = accountRedisOwner.projectAndRead(memberRepair); + inventory.acknowledgeAccountMemberRepair(memberRepair, memberReadback); + var resumedAcknowledged = reloadProgressedOperation(dsl, currentState::get, first); + assertThat(resumedAcknowledged.preparedTransition().inventoryRevision()) + .isGreaterThan(resumedPresent.preparedTransition().inventoryRevision()); + assertThat( + projectionOwner(dsl, currentState::get) + .projectAndRead(resumedAcknowledged) + .scriptOutcome()) + .isEqualTo(3L); + String beforeCapacityRefusal = localRegistrationImage(dsl); assertThatThrownBy( () -> @@ -851,6 +885,33 @@ private CanonicalGameplayIssuerBootstrapCoverageOwner initialCoverageOwner( return new CanonicalGameplayIssuerBootstrapCoverageOwner(dsl, partitionOwner, source); } + private static CanonicalGameplayIssuerBindingLocalOperation reloadProgressedOperation( + DSLContext dsl, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource source, + CanonicalGameplayIssuerBindingLocalOperation original) { + // A replacement worker has only the caller request; its repository reloads the durable source. + var reloaded = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, source) + .beginOrResumeOrdinaryNew(original.request()); + assertThat(reloaded.preparedTransition().status()) + .isEqualTo(CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL); + assertThat(reloaded.preparedTransition().inventoryRevision()) + .isGreaterThan(original.localInventorySnapshotRevision()); + assertThat(reloaded.request()).isEqualTo(original.request()); + assertThat(reloaded.reservation()).isEqualTo(original.reservation()); + assertThat(reloaded.candidateAccountIndexFence()) + .isEqualTo(original.candidateAccountIndexFence()); + assertThat(reloaded.operationId()).isEqualTo(original.operationId()); + assertThat(reloaded.operationFence()).isEqualTo(original.operationFence()); + assertThat(reloaded.localMemberGeneration()).isEqualTo(original.localMemberGeneration()); + assertThat(reloaded.localInventorySnapshotRevision()) + .isEqualTo(original.localInventorySnapshotRevision()); + assertThat(reloaded.memberValue()).isEqualTo(original.memberValue()); + assertThat(reloaded.exactMemberValueBytes()).containsExactly(original.exactMemberValueBytes()); + assertThat(reloaded.memberValueDigest()).isEqualTo(original.memberValueDigest()); + return reloaded; + } + private CanonicalGameplayIssuerBindingLocalRedisOwner projectionOwner( DSLContext dsl, CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource source) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwnerTest.java index 74182a295b..5304a1efa5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwnerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwnerTest.java @@ -112,13 +112,16 @@ void retainedTerminalRetryReturnsTheOriginalCleanupOnlyAfterExactAccountReplay() @Test void ambientTransactionOrSynchronizationRefusesBeforeAnyOwnerInteraction() { - for (boolean actualTransaction : new boolean[] {false, true}) { + for (boolean synchronizationOnly : new boolean[] {false, true}) { var repository = mock(CanonicalGameplayBindingInventoryRepository.class); var client = mock(AccountGameplayAdmissionLeaseClient.class); - org.springframework.transaction.support.TransactionSynchronizationManager - .initSynchronization(); - org.springframework.transaction.support.TransactionSynchronizationManager - .setActualTransactionActive(actualTransaction); + if (synchronizationOnly) { + org.springframework.transaction.support.TransactionSynchronizationManager + .initSynchronization(); + } else { + org.springframework.transaction.support.TransactionSynchronizationManager + .setActualTransactionActive(true); + } try { assertThatThrownBy( () -> From 0b368b8bc98b53f046fb20b97a3bc6da32828003 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:33:48 +1300 Subject: [PATCH 30/34] fix: preserve exact bootstrap supersession replay --- .../player-access-and-session.md | 2 +- services/account-service/build.gradle.kts | 4 +- ...meplayIssuerLayoutBootstrapRepository.java | 4 +- ...calOperationRepositoryIntegrationTest.java | 84 +---------- ...BindingLocalRedisOwnerIntegrationTest.java | 84 +---------- ...BootstrapCoverageOwnerIntegrationTest.java | 84 +---------- ...berOperationRepositoryIntegrationTest.java | 86 +---------- ...rapPartitionRedisOwnerIntegrationTest.java | 84 +---------- ...outBootstrapRepositoryIntegrationTest.java | 141 +++++++----------- ...rtitionBuildRepositoryIntegrationTest.java | 86 +---------- .../CanonicalGameplayIssuerTestFixtures.java | 97 ++++++++++++ 11 files changed, 162 insertions(+), 594 deletions(-) create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerTestFixtures.java diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index ec27b3d512..b3cfa16258 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -20,7 +20,7 @@ The Account gameplay-admission lease and the unregistered Game Session receiver The Game Session canonical inventory now retains Account's exact issuer string through the forward V1024→V1025 conversion. R488 passes 19 selected PostgreSQL cases, including populated-row migration preservation, restart, canonical writes, and refusal by the typed reader to reinterpret retained UUID issuers. This proves storage identity conversion only; issuer ownership and admission remain unqualified. -The receiving source includes a pending issuer-bootstrap SQL owner that freezes the complete issuer cohort under the inventory clock, requires actual persisted `VERIFIED` legacy-owner evidence, and blocks new preparation. Exact replay of a pre-intent frozen transition retains all original request, reservation and current Account checks and performs no new allocation. Descriptor and Account issuer-checkpoint inputs remain controlled. Donor-source R539 recorded 65 focused cases (9 unit and 56 PostgreSQL/Redis, including existing account-member regressions); donor-source R545 recorded 12 cases for the physical schema-v2 shape work. Those remain donor-only attributions. Receiving-parent R548 passes 106 fresh cases (12 unit and 94 PostgreSQL/Redis) on parent `be0e20b`, including the 38-case roster regression, full pending-intent repository/migration coverage and existing account-member owners. jOOQ generation, enabled affected Checkstyle/SpotBugs/formatting and documentation checks pass; all exact test containers are absent. This focused receiving proof does not establish a complete service-suite pass or public runtime admission. Donor proof includes the missing-control refusal, both PostgreSQL-observed prepare/intent lock orders, and populated V1029→V1030 retention/restart. The V1028 retained-row fixture uses controlled historical SQL rows, not an actual pre-migration prepare. That receiving checkpoint had shape-only v2 member model, codec and key-helper sources, without physical Redis mutation/readback, capacity accounting or a separate issuer acknowledgement. The canonical physical schema v2 preserves the original reservation coverage tuple separately from the anchor tuple; R551 passes 21 fresh focused cases (12 unit and nine PostgreSQL), including an actual populated reservation with distinct original coverage and new bootstrap anchor, preserved source rows and cohort, independent physical identities and closed malformed-field refusal. Enabled affected Checkstyle/SpotBugs/formatting and documentation checks pass; all exact test containers are absent. This is representation proof with controlled member-operation and incarnation inputs, not an installed anchor or qualified physical write. Retained v1 artifacts remain unqualified with no fallback. No installed pointer, complete partition/capacity proof, issuer acknowledgement, barrier `OPEN`, final CAS or admission is established. Operational source/incarnation custody, legacy recovery, PKI and activation holds remain; see the [issuer anchor owner](../../architecture/system-architecture-redis.md#installed-issuer-anchor-for-ordinary-new). +The receiving source includes a pending issuer-bootstrap SQL owner that freezes the complete issuer cohort under the inventory clock, requires actual persisted `VERIFIED` legacy-owner evidence, and blocks new preparation. Exact replay of a pre-intent frozen transition retains all original request, reservation and current Account checks and performs no new allocation. Descriptor and Account issuer-checkpoint inputs remain controlled. Donor-source R539 recorded 65 focused cases (9 unit and 56 PostgreSQL/Redis, including existing account-member regressions); donor-source R545 recorded 12 cases for the physical schema-v2 shape work. Those remain donor-only attributions. Receiving-parent R548 passes 106 fresh cases (12 unit and 94 PostgreSQL/Redis) on parent `be0e20b`, including the 38-case roster regression, full pending-intent repository/migration coverage and existing account-member owners. jOOQ generation, enabled affected Checkstyle/SpotBugs/formatting and documentation checks pass; all exact test containers are absent. This focused receiving proof does not establish a complete service-suite pass or public runtime admission. Donor proof includes the missing-control refusal, both PostgreSQL-observed prepare/intent lock orders, and populated V1029→V1030 retention/restart. The V1028 retained-row fixture uses controlled historical SQL rows, not an actual pre-migration prepare. That receiving checkpoint had shape-only v2 member model, codec and key-helper sources, without physical Redis mutation/readback, capacity accounting or a separate issuer acknowledgement. The canonical physical schema v2 preserves the original reservation coverage tuple separately from the anchor tuple; R551 passes 21 fresh focused cases (12 unit and nine PostgreSQL), including an actual populated reservation with distinct original coverage and new bootstrap anchor, preserved source rows and cohort, independent physical identities and closed malformed-field refusal. Enabled affected Checkstyle/SpotBugs/formatting and documentation checks pass; all exact test containers are absent. This is representation proof with controlled member-operation and incarnation inputs, not an installed anchor or qualified physical write. Retained v1 artifacts remain unqualified with no fallback. At the R548/R551 receiving checkpoint, no installed pointer or complete partition/capacity proof existed; the later qualified anchor and physical owners are recorded below. Issuer acknowledgement, barrier `OPEN`, final CAS and admission remain outside this bootstrap boundary. Operational source/incarnation custody, legacy recovery, PKI and activation holds remain; see the [issuer anchor owner](../../architecture/system-architecture-redis.md#installed-issuer-anchor-for-ordinary-new). The unregistered no-active first-NEW member-repair owner composes the original durable operation, the physical one-key global account-member write/readback outside SQL, and separate SQL acceptance. V1026 preserves the operation and completion. R506 freshly passes all 29 selected PostgreSQL/Redis cases, including composed completion, frozen retry/restart, retained prior PRESENT observations, positive control-row requirements, exact member preservation, and malformed-completion refusal. Seven focused unit cases retain R505 attribution; ten shared Redis contract cases retain R500 attribution. This is binding-local `ADD_OR_RETAIN` evidence only: it does not enumerate the account, establish global completeness, or admit the candidate. diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index 4969e06c57..6c4b196df1 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -130,9 +130,11 @@ tasks.named("test") { } tasks.named("integrationTest") { - // Composition fixtures load this owner's migrations directly from the filesystem. + // Composition fixtures load Game Session and Common Saga migrations directly from the filesystem. inputs.dir(project(":game-session-service").file("src/main/resources/db/migration")) .withPathSensitivity(PathSensitivity.RELATIVE) + inputs.dir(project(":common-saga").file("src/main/resources/db/migration/saga")) + .withPathSensitivity(PathSensitivity.RELATIVE) val loggingArtifacts = loggingAdminIntegrationTestArtifacts.artifactFiles classpath = classpath.filter { it !in loggingArtifacts } + files(extractLoggingAdminIntegrationTestClasses) } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java index 3e619c4ef3..00c056826b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java @@ -206,7 +206,9 @@ CanonicalGameplayIssuerLayoutBootstrapIntent supersedeStaleInitialBootstrapInten currentId); if (replay == null || !current.requestId().equals(newRequestId) - || !current.inventorySnapshotRevision().equals(snapshotRevision)) { + || !current + .inventorySnapshotRevision() + .equals(readBigInteger(replay, "new_inventory_revision"))) { throw conflict("Expected original initial bootstrap is no longer current"); } requireSameTrustedInputs( 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 672fa3f1aa..57c87fb794 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 @@ -19,7 +19,6 @@ import java.sql.Connection; import java.sql.SQLException; import java.time.Duration; -import java.util.EnumSet; import java.util.List; import java.util.Objects; import java.util.UUID; @@ -33,10 +32,6 @@ import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; @@ -905,84 +900,7 @@ private static UUID uuid(String value) { } private void establishActualLegacyDisposition(DSLContext dsl) { - var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); - var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); - UUID cohortId = UUID.randomUUID(); - UUID writerFence = UUID.randomUUID(); - var storageIdentity = - new CanonicalGameplayLegacyMigrationStorageIdentity( - "controlled-cluster-uid", - "controlled-namespace-uid", - "controlled-producer-pod-uid", - "controlled-container-id", - "controlled-node-uid", - "123456789", - 42L, - "controlled-postgres-volume-uid", - "controlled-redis-run-id", - "controlled-redis-volume-uid"); - var fencedCohort = - new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { - @Override - public UUID cohortId() { - return cohortId; - } - - @Override - public UUID legacyWriterFence() { - return writerFence; - } - - @Override - public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { - return storageIdentity; - } - - @Override - public void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity expected) { - if (!storageIdentity.equals(expected)) { - throw new IllegalStateException("Controlled test storage identity changed"); - } - } - }; - new CanonicalGameplayLegacyMigrationOwner( - migration, - inventory, - () -> fencedCohort, - ignored -> - new CanonicalGameplayLegacyMigrationSourceSnapshot( - EnumSet.of( - Family.TENANT_SESSION_CONTEXT, - Family.SESSION_ALIAS_CONTEXT, - Family.GAMEPLAY_IDENTITY_CONTEXT, - Family.GAMEPLAY_NAME_CONTEXT, - Family.MOVEMENT_EFFECT, - Family.DURABLE_EFFECT), - List.of()), - new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { - @Override - public void rebuildExact( - CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, - CanonicalGameplayLegacyMigrationSourceSnapshot source, - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingInventorySnapshot - canonical) { - assertThat(canonical.bindings()).isEmpty(); - assertThat(canonical.reservations()).isEmpty(); - } - - @Override - public CanonicalGameplayLegacyMigrationReadback readBackExact( - CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingInventorySnapshot - canonical) { - assertThat(canonical.bindings()).isEmpty(); - return new CanonicalGameplayLegacyMigrationReadback( - List.of(), List.of(), List.of(), List.of()); - } - }) - .migrate(); + CanonicalGameplayIssuerTestFixtures.establishActualLegacyDisposition(dsl); } private TestSchema newTestSchemaAtVersion(String prefix) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java index 74fc535db1..40a6ac0b26 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java @@ -25,7 +25,6 @@ import java.time.Duration; import java.util.ArrayList; import java.util.Base64; -import java.util.EnumSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -46,10 +45,6 @@ import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution; @@ -1264,84 +1259,7 @@ private static AccountGameplayAdmissionLeaseEvidence controlledLeaseEvidence( } private void establishActualLegacyDisposition(DSLContext dsl) { - var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); - var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); - UUID cohortId = UUID.randomUUID(); - UUID writerFence = UUID.randomUUID(); - var storageIdentity = - new CanonicalGameplayLegacyMigrationStorageIdentity( - "controlled-cluster-uid", - "controlled-namespace-uid", - "controlled-producer-pod-uid", - "controlled-container-id", - "controlled-node-uid", - "123456789", - 42L, - "controlled-postgres-volume-uid", - "controlled-redis-run-id", - "controlled-redis-volume-uid"); - var fencedCohort = - new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { - @Override - public UUID cohortId() { - return cohortId; - } - - @Override - public UUID legacyWriterFence() { - return writerFence; - } - - @Override - public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { - return storageIdentity; - } - - @Override - public void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity expected) { - if (!storageIdentity.equals(expected)) { - throw new IllegalStateException("Controlled test storage identity changed"); - } - } - }; - new CanonicalGameplayLegacyMigrationOwner( - migration, - inventory, - () -> fencedCohort, - ignored -> - new CanonicalGameplayLegacyMigrationSourceSnapshot( - EnumSet.of( - Family.TENANT_SESSION_CONTEXT, - Family.SESSION_ALIAS_CONTEXT, - Family.GAMEPLAY_IDENTITY_CONTEXT, - Family.GAMEPLAY_NAME_CONTEXT, - Family.MOVEMENT_EFFECT, - Family.DURABLE_EFFECT), - List.of()), - new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { - @Override - public void rebuildExact( - CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, - CanonicalGameplayLegacyMigrationSourceSnapshot source, - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingInventorySnapshot - canonical) { - assertThat(canonical.bindings()).isEmpty(); - assertThat(canonical.reservations()).isEmpty(); - } - - @Override - public CanonicalGameplayLegacyMigrationReadback readBackExact( - CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingInventorySnapshot - canonical) { - assertThat(canonical.bindings()).isEmpty(); - return new CanonicalGameplayLegacyMigrationReadback( - List.of(), List.of(), List.of(), List.of()); - } - }) - .migrate(); + CanonicalGameplayIssuerTestFixtures.establishActualLegacyDisposition(dsl); } private TestSchema newTestSchemaAtVersion(String prefix) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java index bb0a8f7384..372a50972a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java @@ -22,7 +22,6 @@ import java.time.Duration; import java.util.ArrayList; import java.util.Base64; -import java.util.EnumSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -32,10 +31,6 @@ import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution; import net.firedevops.firemud.test.TestContainerImages; @@ -948,84 +943,7 @@ private static byte[] key(Fixture fixture, BigInteger partitionId) { } private void establishActualLegacyDisposition(DSLContext dsl) { - var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); - var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); - UUID cohortId = UUID.randomUUID(); - UUID writerFence = UUID.randomUUID(); - var storageIdentity = - new CanonicalGameplayLegacyMigrationStorageIdentity( - "controlled-cluster-uid", - "controlled-namespace-uid", - "controlled-producer-pod-uid", - "controlled-container-id", - "controlled-node-uid", - "123456789", - 42L, - "controlled-postgres-volume-uid", - "controlled-redis-run-id", - "controlled-redis-volume-uid"); - var fencedCohort = - new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { - @Override - public UUID cohortId() { - return cohortId; - } - - @Override - public UUID legacyWriterFence() { - return writerFence; - } - - @Override - public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { - return storageIdentity; - } - - @Override - public void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity expected) { - if (!storageIdentity.equals(expected)) { - throw new IllegalStateException("Controlled test storage identity changed"); - } - } - }; - new CanonicalGameplayLegacyMigrationOwner( - migration, - inventory, - () -> fencedCohort, - ignored -> - new CanonicalGameplayLegacyMigrationSourceSnapshot( - EnumSet.of( - Family.TENANT_SESSION_CONTEXT, - Family.SESSION_ALIAS_CONTEXT, - Family.GAMEPLAY_IDENTITY_CONTEXT, - Family.GAMEPLAY_NAME_CONTEXT, - Family.MOVEMENT_EFFECT, - Family.DURABLE_EFFECT), - List.of()), - new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { - @Override - public void rebuildExact( - CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, - CanonicalGameplayLegacyMigrationSourceSnapshot source, - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingInventorySnapshot - canonical) { - assertThat(canonical.bindings()).isEmpty(); - assertThat(canonical.reservations()).isEmpty(); - } - - @Override - public CanonicalGameplayLegacyMigrationReadback readBackExact( - CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingInventorySnapshot - canonical) { - assertThat(canonical.bindings()).isEmpty(); - return new CanonicalGameplayLegacyMigrationReadback( - List.of(), List.of(), List.of(), List.of()); - } - }) - .migrate(); + CanonicalGameplayIssuerTestFixtures.establishActualLegacyDisposition(dsl); } private TestSchema newTestSchemaAtVersion(String prefix, String version) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java index a1c6c491aa..6675c180aa 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java @@ -8,7 +8,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.security.MessageDigest; -import java.util.EnumSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -24,10 +23,6 @@ import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; -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; @@ -795,86 +790,7 @@ private static String digest(String text) { } private static void establishActualLegacyDisposition(DSLContext dsl) { - var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); - var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); - UUID cohortId = UUID.randomUUID(); - UUID writerFence = UUID.randomUUID(); - var storageIdentity = - new CanonicalGameplayLegacyMigrationStorageIdentity( - "controlled-cluster-uid", - "controlled-namespace-uid", - "controlled-producer-pod-uid", - "controlled-container-id", - "controlled-node-uid", - "123456789", - 42L, - "controlled-postgres-volume-uid", - "controlled-redis-run-id", - "controlled-redis-volume-uid"); - var fencedCohort = - new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { - @Override - public UUID cohortId() { - return cohortId; - } - - @Override - public UUID legacyWriterFence() { - return writerFence; - } - - @Override - public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { - return storageIdentity; - } - - @Override - public void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity expected) { - if (!storageIdentity.equals(expected)) { - throw new IllegalStateException("Controlled fixture storage identity changed"); - } - } - }; - var owner = - new CanonicalGameplayLegacyMigrationOwner( - migration, - inventory, - () -> fencedCohort, - ignored -> - new CanonicalGameplayLegacyMigrationSourceSnapshot( - EnumSet.of( - Family.TENANT_SESSION_CONTEXT, - Family.SESSION_ALIAS_CONTEXT, - Family.GAMEPLAY_IDENTITY_CONTEXT, - Family.GAMEPLAY_NAME_CONTEXT, - Family.MOVEMENT_EFFECT, - Family.DURABLE_EFFECT), - List.of()), - new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { - @Override - public void rebuildExact( - CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, - CanonicalGameplayLegacyMigrationSourceSnapshot source, - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingInventorySnapshot - canonical) { - assertThat(canonical.bindings()).isEmpty(); - assertThat(canonical.reservations()).isEmpty(); - } - - @Override - public CanonicalGameplayLegacyMigrationReadback readBackExact( - CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingInventorySnapshot - canonical) { - assertThat(canonical.bindings()).isEmpty(); - return new CanonicalGameplayLegacyMigrationReadback( - List.of(), List.of(), List.of(), List.of()); - } - }); - assertThat(owner.migrate().state()) - .isEqualTo(CanonicalGameplayLegacyMigrationOperation.State.VERIFIED); + CanonicalGameplayIssuerTestFixtures.establishActualLegacyDisposition(dsl); } private static void migrateThrough1031(TestSchema testSchema) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java index 6cb8e4ad59..915b6f9542 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java @@ -23,7 +23,6 @@ import java.time.Duration; import java.util.ArrayList; import java.util.Base64; -import java.util.EnumSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -36,10 +35,6 @@ import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution; @@ -1126,84 +1121,7 @@ private static boolean statusesRemainPending(DSLContext dsl) { } private static void establishActualLegacyDisposition(DSLContext dsl) { - var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); - var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); - UUID cohortId = UUID.randomUUID(); - UUID writerFence = UUID.randomUUID(); - var storageIdentity = - new CanonicalGameplayLegacyMigrationStorageIdentity( - "controlled-cluster-uid", - "controlled-namespace-uid", - "controlled-producer-pod-uid", - "controlled-container-id", - "controlled-node-uid", - "123456789", - 42L, - "controlled-postgres-volume-uid", - "controlled-redis-run-id", - "controlled-redis-volume-uid"); - var fencedCohort = - new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { - @Override - public UUID cohortId() { - return cohortId; - } - - @Override - public UUID legacyWriterFence() { - return writerFence; - } - - @Override - public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { - return storageIdentity; - } - - @Override - public void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity expected) { - if (!storageIdentity.equals(expected)) { - throw new IllegalStateException("Controlled test storage identity changed"); - } - } - }; - new CanonicalGameplayLegacyMigrationOwner( - migration, - inventory, - () -> fencedCohort, - ignored -> - new CanonicalGameplayLegacyMigrationSourceSnapshot( - EnumSet.of( - Family.TENANT_SESSION_CONTEXT, - Family.SESSION_ALIAS_CONTEXT, - Family.GAMEPLAY_IDENTITY_CONTEXT, - Family.GAMEPLAY_NAME_CONTEXT, - Family.MOVEMENT_EFFECT, - Family.DURABLE_EFFECT), - List.of()), - new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { - @Override - public void rebuildExact( - CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, - CanonicalGameplayLegacyMigrationSourceSnapshot source, - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingInventorySnapshot - canonical) { - assertThat(canonical.bindings()).isEmpty(); - assertThat(canonical.reservations()).isEmpty(); - } - - @Override - public CanonicalGameplayLegacyMigrationReadback readBackExact( - CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingInventorySnapshot - canonical) { - assertThat(canonical.bindings()).isEmpty(); - return new CanonicalGameplayLegacyMigrationReadback( - List.of(), List.of(), List.of(), List.of()); - } - }) - .migrate(); + CanonicalGameplayIssuerTestFixtures.establishActualLegacyDisposition(dsl); } private TestSchema newTestSchemaAtVersion(String prefix, String version) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java index 469530fc09..22ddf91539 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java @@ -16,7 +16,6 @@ import java.sql.Connection; import java.sql.SQLException; import java.time.Duration; -import java.util.EnumSet; import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.List; @@ -37,10 +36,6 @@ import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; @@ -783,6 +778,7 @@ void staleUninstalledIntentRequiresExplicitFreshLayoutAndPreservesOriginalHistor establishActualLegacyDisposition(dsl); var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); var provisional = prepareActualProvisionalFirstNew(testSchema); + var unrelatedProvisional = prepareActualProvisionalFirstNew(testSchema, UUID.randomUUID()); var owner = new CanonicalGameplayIssuerLayoutBootstrapRepository(dsl); var layout = descriptor(LAYOUT_VERSION, PARTITION_COUNT, PARTITION_CAPACITY); var source = sourceCheckpoint(BigInteger.valueOf(7)); @@ -923,20 +919,50 @@ void staleUninstalledIntentRequiresExplicitFreshLayoutAndPreservesOriginalHistor List retainedRelation = rowImages(dsl, "game_session_canonical_issuer_bootstrap_supersession"); assertThat(retainedRelation).hasSize(1); + List replacementIntent = + rowImages(dsl, "game_session_canonical_issuer_layout_bootstrap_intent"); + List replacementCohort = + rowImages(dsl, "game_session_canonical_issuer_layout_bootstrap_cohort_row"); + var unrelatedAbort = + inventory.recordFirstNewAccountAbort(unrelatedProvisional, UUID.randomUUID()); + assertThat(unrelatedAbort.isAccountAborted()).isTrue(); + assertThat(unrelatedAbort.transition().inventoryRevision()) + .isGreaterThan(replacement.inventorySnapshotRevision()); + var restartedAfterProgress = new CanonicalGameplayIssuerLayoutBootstrapRepository(dsl); + var replayAfterProgress = + restartedAfterProgress.supersedeStaleInitialBootstrapIntent( + original.operationId(), replacementRequest, newerLayout, source); + assertThat(replayAfterProgress).usingRecursiveComparison().isEqualTo(replacement); + assertThat(rowImages(dsl, "game_session_canonical_issuer_layout_bootstrap_intent")) + .isEqualTo(replacementIntent); + assertThat(rowImages(dsl, "game_session_canonical_issuer_layout_bootstrap_cohort_row")) + .isEqualTo(replacementCohort); + assertThat(rowImages(dsl, "game_session_canonical_issuer_layout_bootstrap_control")) + .isEqualTo(replacementControl); + assertThat(rowImages(dsl, "game_session_canonical_issuer_bootstrap_supersession")) + .isEqualTo(retainedRelation); assertThatThrownBy( () -> - restarted.supersedeStaleInitialBootstrapIntent( + restartedAfterProgress.supersedeStaleInitialBootstrapIntent( original.operationId(), UUID.randomUUID(), newerLayout, source)) .hasMessageContaining("no longer current"); assertThatThrownBy( () -> - restarted.supersedeStaleInitialBootstrapIntent( + restartedAfterProgress.supersedeStaleInitialBootstrapIntent( original.operationId(), replacementRequest, descriptor( LAYOUT_VERSION.add(BigInteger.TWO), PARTITION_COUNT, PARTITION_CAPACITY), source)) .hasMessageContaining("changed its original trusted inputs"); + assertThatThrownBy( + () -> + restartedAfterProgress.supersedeStaleInitialBootstrapIntent( + original.operationId(), + replacementRequest, + newerLayout, + sourceCheckpoint(BigInteger.valueOf(8)))) + .hasMessageContaining("changed its original trusted inputs"); assertThatThrownBy( () -> dsl.execute( @@ -1108,6 +1134,18 @@ void retainedPhysicalWorkDoesNotStrandSupersedingLayoutOrOrdinaryNew() { LAYOUT_VERSION.add(BigInteger.TWO), PARTITION_COUNT, PARTITION_CAPACITY), source)) .hasMessageContaining("installed issuer anchor forbids"); + assertThatThrownBy( + () -> + new CanonicalGameplayIssuerLayoutBootstrapRepository(dsl) + .supersedeStaleInitialBootstrapIntent( + original.operationId(), + replacement.requestId(), + descriptor( + LAYOUT_VERSION.add(BigInteger.ONE), + PARTITION_COUNT, + PARTITION_CAPACITY), + source)) + .hasMessageContaining("installed issuer anchor forbids"); assertMalformedSupersessionRefusesOrdinaryNew(dsl, local, request, state); } finally { ownerClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); @@ -1253,9 +1291,14 @@ private static void assertRelationOnlySupersessionCannotCommit( private static CanonicalGameplayAdmissionAbortSource prepareActualProvisionalFirstNew( TestSchema testSchema) { + return prepareActualProvisionalFirstNew(testSchema, TENANT_ID); + } + + private static CanonicalGameplayAdmissionAbortSource prepareActualProvisionalFirstNew( + TestSchema testSchema, UUID tenantId) { var runtimeTarget = CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( - testSchema.dataSource(), TENANT_ID); + testSchema.dataSource(), tenantId); CanonicalGameplayBindingIdentity candidate = new CanonicalGameplayBindingIdentity( ACCOUNT_ID, @@ -1556,87 +1599,7 @@ private static void insertReservationOnly( } private static void establishActualLegacyDisposition(DSLContext dsl) { - var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); - var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); - UUID cohortId = UUID.randomUUID(); - UUID writerFence = UUID.randomUUID(); - var storageIdentity = - new CanonicalGameplayLegacyMigrationStorageIdentity( - "controlled-cluster-uid", - "controlled-namespace-uid", - "controlled-producer-pod-uid", - "controlled-container-id", - "controlled-node-uid", - "123456789", - 42L, - "controlled-postgres-volume-uid", - "controlled-redis-run-id", - "controlled-redis-volume-uid"); - var fencedCohort = - new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { - @Override - public UUID cohortId() { - return cohortId; - } - - @Override - public UUID legacyWriterFence() { - return writerFence; - } - - @Override - public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { - return storageIdentity; - } - - @Override - public void requireStillFenced( - CanonicalGameplayLegacyMigrationStorageIdentity expectedIdentity) { - if (!storageIdentity.equals(expectedIdentity)) { - throw new IllegalStateException("Controlled fixture storage identity changed"); - } - } - }; - var owner = - new CanonicalGameplayLegacyMigrationOwner( - migration, - inventory, - () -> fencedCohort, - ignored -> - new CanonicalGameplayLegacyMigrationSourceSnapshot( - EnumSet.of( - Family.TENANT_SESSION_CONTEXT, - Family.SESSION_ALIAS_CONTEXT, - Family.GAMEPLAY_IDENTITY_CONTEXT, - Family.GAMEPLAY_NAME_CONTEXT, - Family.MOVEMENT_EFFECT, - Family.DURABLE_EFFECT), - List.of()), - new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { - @Override - public void rebuildExact( - CanonicalGameplayLegacyMigrationOwner.FencedCohort ignoredCohort, - CanonicalGameplayLegacyMigrationSourceSnapshot source, - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingInventorySnapshot - canonical) { - assertThat(canonical.bindings()).isEmpty(); - assertThat(canonical.reservations()).isEmpty(); - } - - @Override - public CanonicalGameplayLegacyMigrationReadback readBackExact( - CanonicalGameplayLegacyMigrationOwner.FencedCohort ignoredCohort, - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingInventorySnapshot - canonical) { - assertThat(canonical.bindings()).isEmpty(); - return new CanonicalGameplayLegacyMigrationReadback( - List.of(), List.of(), List.of(), List.of()); - } - }); - assertThat(owner.migrate().state()) - .isEqualTo(CanonicalGameplayLegacyMigrationOperation.State.VERIFIED); + CanonicalGameplayIssuerTestFixtures.establishActualLegacyDisposition(dsl); } private static TestSchema newTestSchema(String prefix) { 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 88a041c16e..83c8ed2811 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 @@ -9,7 +9,6 @@ import java.nio.file.Path; import java.sql.Connection; import java.sql.SQLException; -import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.UUID; @@ -26,10 +25,6 @@ import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.test.TestContainerImages; @@ -2044,86 +2039,7 @@ private static void insertReservationOnly( } private static void establishActualLegacyDisposition(DSLContext dsl) { - var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); - var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); - UUID cohortId = UUID.randomUUID(); - UUID writerFence = UUID.randomUUID(); - var storageIdentity = - new CanonicalGameplayLegacyMigrationStorageIdentity( - "controlled-cluster-uid", - "controlled-namespace-uid", - "controlled-producer-pod-uid", - "controlled-container-id", - "controlled-node-uid", - "123456789", - 42L, - "controlled-postgres-volume-uid", - "controlled-redis-run-id", - "controlled-redis-volume-uid"); - var fencedCohort = - new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { - @Override - public UUID cohortId() { - return cohortId; - } - - @Override - public UUID legacyWriterFence() { - return writerFence; - } - - @Override - public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { - return storageIdentity; - } - - @Override - public void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity expected) { - if (!storageIdentity.equals(expected)) { - throw new IllegalStateException("Controlled fixture storage identity changed"); - } - } - }; - var owner = - new CanonicalGameplayLegacyMigrationOwner( - migration, - inventory, - () -> fencedCohort, - ignored -> - new CanonicalGameplayLegacyMigrationSourceSnapshot( - EnumSet.of( - Family.TENANT_SESSION_CONTEXT, - Family.SESSION_ALIAS_CONTEXT, - Family.GAMEPLAY_IDENTITY_CONTEXT, - Family.GAMEPLAY_NAME_CONTEXT, - Family.MOVEMENT_EFFECT, - Family.DURABLE_EFFECT), - List.of()), - new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { - @Override - public void rebuildExact( - CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, - CanonicalGameplayLegacyMigrationSourceSnapshot source, - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingInventorySnapshot - canonical) { - assertThat(canonical.bindings()).isEmpty(); - assertThat(canonical.reservations()).isEmpty(); - } - - @Override - public CanonicalGameplayLegacyMigrationReadback readBackExact( - CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingInventorySnapshot - canonical) { - assertThat(canonical.bindings()).isEmpty(); - return new CanonicalGameplayLegacyMigrationReadback( - List.of(), List.of(), List.of(), List.of()); - } - }); - assertThat(owner.migrate().state()) - .isEqualTo(CanonicalGameplayLegacyMigrationOperation.State.VERIFIED); + CanonicalGameplayIssuerTestFixtures.establishActualLegacyDisposition(dsl); } private static TestSchema newTestSchema(String prefix) { 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 new file mode 100644 index 0000000000..d960ed6c29 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerTestFixtures.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.EnumSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventorySnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; +import org.jooq.DSLContext; + +/** Shared actual-owner fixtures for issuer bootstrap and ordinary NEW integration proof. */ +final class CanonicalGameplayIssuerTestFixtures { + private CanonicalGameplayIssuerTestFixtures() {} + + static void establishActualLegacyDisposition(DSLContext dsl) { + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); + UUID cohortId = UUID.randomUUID(); + UUID writerFence = UUID.randomUUID(); + var storageIdentity = + new CanonicalGameplayLegacyMigrationStorageIdentity( + "controlled-cluster-uid", + "controlled-namespace-uid", + "controlled-producer-pod-uid", + "controlled-container-id", + "controlled-node-uid", + "123456789", + 42L, + "controlled-postgres-volume-uid", + "controlled-redis-run-id", + "controlled-redis-volume-uid"); + var fencedCohort = + new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { + @Override + public UUID cohortId() { + return cohortId; + } + + @Override + public UUID legacyWriterFence() { + return writerFence; + } + + @Override + public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + return storageIdentity; + } + + @Override + public void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity expected) { + if (!storageIdentity.equals(expected)) { + throw new IllegalStateException("Controlled fixture storage identity changed"); + } + } + }; + var owner = + new CanonicalGameplayLegacyMigrationOwner( + migration, + inventory, + () -> fencedCohort, + ignored -> + new CanonicalGameplayLegacyMigrationSourceSnapshot( + EnumSet.of( + Family.TENANT_SESSION_CONTEXT, + Family.SESSION_ALIAS_CONTEXT, + Family.GAMEPLAY_IDENTITY_CONTEXT, + Family.GAMEPLAY_NAME_CONTEXT, + Family.MOVEMENT_EFFECT, + Family.DURABLE_EFFECT), + List.of()), + new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { + @Override + public void rebuildExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + CanonicalGameplayLegacyMigrationSourceSnapshot source, + CanonicalGameplayBindingInventorySnapshot canonical) { + assertThat(canonical.bindings()).isEmpty(); + assertThat(canonical.reservations()).isEmpty(); + } + + @Override + public CanonicalGameplayLegacyMigrationReadback readBackExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + CanonicalGameplayBindingInventorySnapshot canonical) { + assertThat(canonical.bindings()).isEmpty(); + return new CanonicalGameplayLegacyMigrationReadback( + List.of(), List.of(), List.of(), List.of()); + } + }); + assertThat(owner.migrate().state()) + .isEqualTo(CanonicalGameplayLegacyMigrationOperation.State.VERIFIED); + } +} From 27820e7535ca0c3250e556dbf6b5e01740437594 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 14:20:41 +1300 Subject: [PATCH 31/34] Consolidate issuer fixtures and strict Redis lifecycle support --- ...lGameplayIssuerBindingLocalRedisOwner.java | 218 ++------------ ...ayIssuerBindingLocalReleaseRedisOwner.java | 199 ++---------- ...ssuerBindingLocalRetirementRedisOwner.java | 196 ++---------- ...alGameplayIssuerPartitionRedisSupport.java | 229 ++++++++++++++ ...erBindingLocalRedisScriptContribution.java | 36 +-- ...ngLocalReleaseRedisScriptContribution.java | 37 +-- ...ocalRetirementRedisScriptContribution.java | 33 +- ...strapPartitionRedisScriptContribution.java | 37 +-- .../GameSessionRedisScriptDescriptors.java | 38 +++ ...calOperationRepositoryIntegrationTest.java | 126 ++------ ...BindingLocalRedisOwnerIntegrationTest.java | 225 ++------------ ...BootstrapCoverageOwnerIntegrationTest.java | 112 +------ ...berOperationRepositoryIntegrationTest.java | 121 +------- ...rapPartitionRedisOwnerIntegrationTest.java | 105 +------ ...outBootstrapRepositoryIntegrationTest.java | 153 +--------- ...rtitionBuildRepositoryIntegrationTest.java | 194 ++---------- ...suerPhysicalRetirementIntegrationTest.java | 7 - .../CanonicalGameplayIssuerTestFixtures.java | 285 ++++++++++++++++++ 18 files changed, 785 insertions(+), 1566 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionRedisSupport.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRedisScriptDescriptors.java diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java index 741ef960b6..dec5b5e131 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java @@ -1,45 +1,34 @@ package net.firedevops.firemud.gamesession.repository; +import static net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerPartitionRedisSupport.KEY_PREFIX; +import static net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerPartitionRedisSupport.ascii; +import static net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerPartitionRedisSupport.b64; + import io.lettuce.core.RedisClient; -import io.lettuce.core.RedisFuture; -import io.lettuce.core.ScriptOutputType; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.async.RedisAsyncCommands; import io.lettuce.core.codec.ByteArrayCodec; -import java.io.IOException; -import java.io.InputStream; import java.math.BigInteger; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; import java.util.ArrayList; import java.util.Arrays; -import java.util.Base64; -import java.util.HashMap; -import java.util.HexFormat; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; -import org.springframework.transaction.support.TransactionSynchronizationManager; /** * Explicit, unregistered one-key projection owner for SQL-prepared ordinary issuer NEW work. * Physical readback is local evidence only and leaves its SQL operation pending. */ public final class CanonicalGameplayIssuerBindingLocalRedisOwner { - private static final String PRINCIPAL = "gamesession_coord_app"; - private static final String KEY_PREFIX = "session:game:index:issuer:"; - private static final int MAX_SCRIPT_BYTES = 128 * 1024; - private static final long COMMAND_TIMEOUT_MILLIS = 5_000; + private static final CanonicalGameplayIssuerPartitionRedisSupport REDIS = + new CanonicalGameplayIssuerPartitionRedisSupport( + (message, cause) -> cause == null ? unavailable() : unavailable(cause)); private static final List EXPECTED_KEYS = List.of( new RedisScriptDescriptor.KeySpec( @@ -128,7 +117,7 @@ public Readback projectAndRead(CanonicalGameplayIssuerBindingLocalOperation oper throw unavailable(); } RedisScriptDescriptor descriptor = requireDescriptor(); - byte[] script = scriptSource(descriptor); + byte[] script = REDIS.scriptSource(descriptor); byte[] key = exactPartitionKey(work); byte[][] arguments = scriptArguments(work); long result = writeOneKey(script, key, arguments); @@ -153,16 +142,8 @@ public Readback projectAndRead(CanonicalGameplayIssuerBindingLocalOperation oper private long writeOneKey(byte[] script, byte[] key, byte[][] arguments) { requireNoAmbientTransaction(); - try (StatefulRedisConnection connection = - redisClient.connect(ByteArrayCodec.INSTANCE)) { - RedisAsyncCommands commands = requireCommands(connection); - requirePrincipal(await(commands.aclWhoami())); - String sha = await(commands.scriptLoad(script)); - if (!digest("SHA-1", script).equals(sha)) throw unavailable(); - Long reply = - await(commands.evalsha(sha, ScriptOutputType.INTEGER, new byte[][] {key}, arguments)); - if (reply == null) throw unavailable(); - return reply; + try { + return REDIS.writeOneKey(redisClient, script, key, arguments); } catch (RuntimeException failure) { throw unavailable(failure); } @@ -175,53 +156,26 @@ private byte[] readExactPhysicalState( requireNoAmbientTransaction(); try (StatefulRedisConnection connection = redisClient.connect(ByteArrayCodec.INSTANCE)) { - RedisAsyncCommands commands = requireCommands(connection); - requirePrincipal(await(commands.aclWhoami())); - if (!"hash".equals(await(commands.type(key))) - || !Long.valueOf(-1L).equals(await(commands.pttl(key)))) { - throw unavailable(); - } - Long length = await(commands.hlen(key)); - int maxFields = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_LOCAL_HASH_FIELDS; - if (length == null || length < 1 || length > maxFields) throw unavailable(); - Map raw = await(commands.hgetall(key)); - if (raw == null || raw.size() != length) throw unavailable(); - Map actual = new HashMap<>(); - long totalBytes = 0; - for (Map.Entry entry : raw.entrySet()) { - byte[] field = Objects.requireNonNull(entry.getKey(), "Redis field"); - byte[] value = Objects.requireNonNull(entry.getValue(), "Redis value"); - totalBytes = Math.addExact(totalBytes, field.length + (long) value.length); - if (totalBytes - > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_TOTAL_HASH_BYTES) { - throw unavailable(); - } - String encoded = Base64.getEncoder().encodeToString(field); - if (actual.putIfAbsent(encoded, value.clone()) != null) throw unavailable(); - } - + RedisAsyncCommands commands = REDIS.authenticatedCommands(connection); + Map actual = REDIS.readBoundedHash(commands, key); Map baseline = work.baselineFields(); Map allowed = work.allowedFields(); byte[] physicalRevision = actual.get( - Base64.getEncoder() - .encodeToString( - CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD.getBytes( - StandardCharsets.US_ASCII))); + b64( + CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD.getBytes( + StandardCharsets.US_ASCII))); if (!Arrays.equals( physicalRevision, expectedPhysicalRevision.toString().getBytes(StandardCharsets.US_ASCII))) { throw unavailable(); } for (Map.Entry field : baseline.entrySet()) { - byte[] redisValue = - actual.get( - Base64.getEncoder() - .encodeToString(field.getKey().getBytes(StandardCharsets.UTF_8))); + byte[] redisValue = actual.get(b64(field.getKey().getBytes(StandardCharsets.UTF_8))); if (redisValue == null || !Arrays.equals(redisValue, field.getValue())) throw unavailable(); } for (Map.Entry field : actual.entrySet()) { - String decodedField = decodeUtf8(Base64.getDecoder().decode(field.getKey())); + String decodedField = REDIS.decodeField(field.getKey()); if (decodedField.equals(CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD)) continue; byte[] expected = allowed.get(decodedField); @@ -251,16 +205,11 @@ private byte[] readExactPhysicalState( String capacityField = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( target.memberValue().reservation().reservationId()); - byte[] targetCapacity = - actual.get( - Base64.getEncoder() - .encodeToString(capacityField.getBytes(StandardCharsets.US_ASCII))); + byte[] targetCapacity = actual.get(b64(capacityField.getBytes(StandardCharsets.US_ASCII))); if (!Arrays.equals(targetCapacity, target.exactMemberValueBytes())) throw unavailable(); String bindingField = new String(target.memberValue().owner().bindingRef().bytes(), StandardCharsets.UTF_8); - byte[] targetBinding = - actual.get( - Base64.getEncoder().encodeToString(bindingField.getBytes(StandardCharsets.UTF_8))); + byte[] targetBinding = actual.get(b64(bindingField.getBytes(StandardCharsets.UTF_8))); if (target.bindingPresent()) { if (!Arrays.equals(targetBinding, target.exactMemberValueBytes())) throw unavailable(); } else if (targetBinding != null) { @@ -282,7 +231,7 @@ private byte[] readExactPhysicalState( } } for (var entry : actual.entrySet()) { - String field = decodeUtf8(Base64.getDecoder().decode(entry.getKey())); + String field = REDIS.decodeField(entry.getKey()); byte[] valueBytes = entry.getValue(); if (field.equals(CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD)) { continue; @@ -343,34 +292,18 @@ private byte[] readExactPhysicalState( throw unavailable(); } return CanonicalGameplayIssuerBootstrapCoverageRepository.encodeFieldSet( - decodePhysicalMap(actual)); + REDIS.decodePhysicalMap(actual)); } catch (RuntimeException failure) { throw unavailable(failure); } } - private static Map decodePhysicalMap(Map encoded) { - Map result = new HashMap<>(); - encoded.forEach( - (field, value) -> result.put(decodeUtf8(Base64.getDecoder().decode(field)), value.clone())); - return result; - } - - private static String b64(byte[] value) { - return Base64.getEncoder().encodeToString(value); - } - private void requireFreshCurrentState( CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work) { requireNoAmbientTransaction(); var current = currentStateSource.readFreshCurrentState(); requireNoAmbientTransaction(); - var anchor = work.anchor(); - if (current == null - || !sameCheckpoint(current.accountCheckpoint(), anchor) - || !Arrays.equals( - CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(current.incarnation()), - anchor.incarnationBytes())) { + if (!REDIS.matchesCurrentState(current, work.anchor())) { throw unavailable(); } } @@ -379,26 +312,13 @@ private RedisScriptDescriptor requireDescriptor() { try { RedisScriptDescriptor descriptor = catalog.require(CanonicalGameplayIssuerBindingLocalRedisScriptContribution.SCRIPT_ID); - if (!CanonicalGameplayIssuerBindingLocalRedisScriptContribution.SCRIPT_ID.equals( - descriptor.scriptId()) - || !CanonicalGameplayIssuerBindingLocalRedisScriptContribution.RESOURCE_PATH.equals( - descriptor.resourcePath()) - || !"game-session-service".equals(descriptor.owner()) - || !PRINCIPAL.equals(descriptor.principal()) - || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION - || !EXPECTED_KEYS.equals(descriptor.keys()) - || !EXPECTED_ARGUMENTS.equals(descriptor.arguments()) - || descriptor.category() != RedisScriptDescriptor.ScriptCategory.SESSION_ISSUER_INDEX - || !EXPECTED_OUTCOMES.equals(descriptor.outcomes()) - || descriptor.resetSensitivity() != RedisScriptDescriptor.ResetSensitivity.CLUSTER - || descriptor.lossClass() - != RedisScriptDescriptor.LossClass.EMPTY_REDIS_COLD_START_OR_RESET - || descriptor.compatibilityLevel() - != RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET - || !descriptor - .supportedCoexistence() - .equals(List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "v2"))) - || descriptor.legacyPayloadShape() != null) { + if (!REDIS.matchesDescriptor( + descriptor, + CanonicalGameplayIssuerBindingLocalRedisScriptContribution.SCRIPT_ID, + CanonicalGameplayIssuerBindingLocalRedisScriptContribution.RESOURCE_PATH, + EXPECTED_KEYS, + EXPECTED_ARGUMENTS, + EXPECTED_OUTCOMES)) { throw unavailable(); } return descriptor; @@ -407,24 +327,6 @@ private RedisScriptDescriptor requireDescriptor() { } } - private static byte[] scriptSource(RedisScriptDescriptor descriptor) { - try (InputStream input = - CanonicalGameplayIssuerBindingLocalRedisOwner.class - .getClassLoader() - .getResourceAsStream(descriptor.resourcePath())) { - if (input == null) throw unavailable(); - byte[] bytes = input.readNBytes(MAX_SCRIPT_BYTES + 1); - if (bytes.length == 0 - || bytes.length > MAX_SCRIPT_BYTES - || !descriptor.sha256().equals(digest("SHA-256", bytes))) { - throw unavailable(); - } - return bytes; - } catch (IOException | RuntimeException failure) { - throw unavailable(failure); - } - } - private static byte[] exactPartitionKey( CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work) { String key = CanonicalGameplayIssuerRedisKeys.forMember(work.targetOperation().memberValue()); @@ -488,68 +390,8 @@ private static byte[][] scriptArguments( return arguments.toArray(byte[][]::new); } - private static boolean sameCheckpoint( - CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint current, - CanonicalGameplayIssuerInstalledAnchor anchor) { - return current != null - && current.issuerId().equals(anchor.issuerId()) - && current.issuerAuthGeneration().equals(anchor.issuerAuthGeneration()) - && Arrays.equals(current.exactCheckpointBytes(), anchor.sourceCheckpointBytes()) - && current.checkpointDigest().equals(anchor.sourceCheckpointDigest()) - && Arrays.equals(current.latestIssuerEventBytes(), anchor.sourceEventBytes()) - && Objects.equals(current.latestIssuerEventDigest(), anchor.sourceEventDigest()); - } - - private static byte[] ascii(String value) { - return value.getBytes(StandardCharsets.US_ASCII); - } - - private static String decodeUtf8(byte[] bytes) { - try { - return StandardCharsets.UTF_8 - .newDecoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .decode(java.nio.ByteBuffer.wrap(bytes)) - .toString(); - } catch (CharacterCodingException malformed) { - throw unavailable(malformed); - } - } - - private static RedisAsyncCommands requireCommands( - StatefulRedisConnection connection) { - if (connection == null || !connection.isOpen()) throw unavailable(); - return connection.async(); - } - - private static void requirePrincipal(String principal) { - if (!PRINCIPAL.equals(principal)) throw unavailable(); - } - - private static T await(RedisFuture future) { - try { - return future.get(COMMAND_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - future.cancel(true); - throw unavailable(interrupted); - } catch (ExecutionException | TimeoutException | RuntimeException failure) { - future.cancel(true); - throw unavailable(failure); - } - } - private static void requireNoAmbientTransaction() { - if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); - } - - private static String digest(String algorithm, byte[] bytes) { - try { - return HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(bytes)); - } catch (Exception failure) { - throw unavailable(failure); - } + REDIS.requireNoAmbientTransaction(); } private static IllegalStateException unavailable() { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.java index b9f1d360d4..0c191f5887 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.java @@ -1,42 +1,31 @@ package net.firedevops.firemud.gamesession.repository; +import static net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerPartitionRedisSupport.KEY_PREFIX; +import static net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerPartitionRedisSupport.ascii; +import static net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerPartitionRedisSupport.b64; + import io.lettuce.core.RedisClient; -import io.lettuce.core.RedisFuture; -import io.lettuce.core.ScriptOutputType; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.async.RedisAsyncCommands; import io.lettuce.core.codec.ByteArrayCodec; -import java.io.IOException; -import java.io.InputStream; import java.math.BigInteger; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; import java.util.ArrayList; import java.util.Arrays; -import java.util.Base64; -import java.util.HashMap; -import java.util.HexFormat; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution; -import org.springframework.transaction.support.TransactionSynchronizationManager; /** Manual one-key physical owner for an SQL-issued first-NEW issuer release successor. */ public final class CanonicalGameplayIssuerBindingLocalReleaseRedisOwner { - private static final String PRINCIPAL = "gamesession_coord_app"; - private static final String KEY_PREFIX = "session:game:index:issuer:"; - private static final int MAX_SCRIPT_BYTES = 128 * 1024; - private static final long COMMAND_TIMEOUT_MILLIS = 5_000; + private static final CanonicalGameplayIssuerPartitionRedisSupport REDIS = + new CanonicalGameplayIssuerPartitionRedisSupport( + CanonicalGameplayIssuerBindingLocalReleaseRedisOwner::unavailable); private static final List EXPECTED_KEYS = List.of( new RedisScriptDescriptor.KeySpec( @@ -119,7 +108,7 @@ public Readback releaseAndRead(CanonicalGameplayIssuerBindingLocalReleaseOperati } requireFreshCurrentState(work); RedisScriptDescriptor descriptor = requireDescriptor(); - byte[] script = scriptSource(descriptor); + byte[] script = REDIS.scriptSource(descriptor); byte[] key = exactPartitionKey(work); long outcome = writeOneKey(script, key, scriptArguments(work, operation)); if (outcome != 1 && outcome != 2) { @@ -142,17 +131,8 @@ public Readback releaseAndRead(CanonicalGameplayIssuerBindingLocalReleaseOperati private long writeOneKey(byte[] script, byte[] key, byte[][] arguments) { requireNoAmbientTransaction(); - try (StatefulRedisConnection connection = - redisClient.connect(ByteArrayCodec.INSTANCE)) { - RedisAsyncCommands commands = requireCommands(connection); - requirePrincipal(await(commands.aclWhoami())); - String sha = await(commands.scriptLoad(script)); - if (!digest("SHA-1", script).equals(sha)) - throw unavailable("Redis loaded a different script"); - Long reply = - await(commands.evalsha(sha, ScriptOutputType.INTEGER, new byte[][] {key}, arguments)); - if (reply == null) throw unavailable("Redis returned no release result"); - return reply; + try { + return REDIS.writeOneKey(redisClient, script, key, arguments); } catch (RuntimeException failure) { throw unavailable("One-key issuer release command failed", failure); } @@ -165,33 +145,8 @@ private byte[] readExactPhysicalState( requireNoAmbientTransaction(); try (StatefulRedisConnection connection = redisClient.connect(ByteArrayCodec.INSTANCE)) { - RedisAsyncCommands commands = requireCommands(connection); - requirePrincipal(await(commands.aclWhoami())); - if (!"hash".equals(await(commands.type(key))) - || !Long.valueOf(-1L).equals(await(commands.pttl(key)))) { - throw unavailable("Issuer partition type or TTL is not canonical"); - } - Long count = await(commands.hlen(key)); - int maxFields = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_LOCAL_HASH_FIELDS; - if (count == null || count < 1 || count > maxFields) - throw unavailable("Issuer partition field count is invalid"); - Map raw = await(commands.hgetall(key)); - if (raw == null || raw.size() != count) - throw unavailable("Issuer partition readback is incomplete"); - Map actual = new HashMap<>(); - long bytes = 0; - for (Map.Entry field : raw.entrySet()) { - byte[] name = Objects.requireNonNull(field.getKey(), "Redis field"); - byte[] value = Objects.requireNonNull(field.getValue(), "Redis value"); - bytes = Math.addExact(bytes, name.length + (long) value.length); - if (bytes > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_TOTAL_HASH_BYTES) { - throw unavailable("Issuer partition readback exceeds its bounded field set"); - } - String encodedName = Base64.getEncoder().encodeToString(name); - if (actual.putIfAbsent(encodedName, value.clone()) != null) { - throw unavailable("Issuer partition readback repeats a physical field"); - } - } + RedisAsyncCommands commands = REDIS.authenticatedCommands(connection); + Map actual = REDIS.readBoundedHash(commands, key); Map baseline = work.baselineFields(); Map allowed = work.allowedFields(); byte[] physicalRevision = @@ -226,7 +181,7 @@ private byte[] readExactPhysicalState( throw unavailable("Exact RELEASED capacity field or binding-field removal is absent"); } for (Map.Entry field : actual.entrySet()) { - String decoded = decodeUtf8(Base64.getDecoder().decode(field.getKey())); + String decoded = REDIS.decodeField(field.getKey()); if (decoded.equals(CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD)) { continue; } @@ -264,7 +219,7 @@ private byte[] readExactPhysicalState( int physicalReservations = 0; int physicalBindings = 0; for (Map.Entry field : actual.entrySet()) { - String decoded = decodeUtf8(Base64.getDecoder().decode(field.getKey())); + String decoded = REDIS.decodeField(field.getKey()); if (decoded.equals(CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD)) { continue; } else if (decoded.startsWith( @@ -317,7 +272,7 @@ private byte[] readExactPhysicalState( throw unavailable("Issuer release readback violates physical or SQL capacity bounds"); } return CanonicalGameplayIssuerBootstrapCoverageRepository.encodeFieldSet( - decodePhysicalMap(actual)); + REDIS.decodePhysicalMap(actual)); } catch (RuntimeException failure) { throw unavailable("Independent issuer release readback was not exact", failure); } @@ -389,20 +344,9 @@ private static byte[] exactPartitionKey( private void requireFreshCurrentState( CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work) { requireNoAmbientTransaction(); - var state = currentStateSource.readFreshCurrentState(); + var current = currentStateSource.readFreshCurrentState(); requireNoAmbientTransaction(); - var checkpoint = state == null ? null : state.accountCheckpoint(); - var anchor = work.anchor(); - if (checkpoint == null - || !checkpoint.issuerId().equals(anchor.issuerId()) - || !checkpoint.issuerAuthGeneration().equals(anchor.issuerAuthGeneration()) - || !Arrays.equals(checkpoint.exactCheckpointBytes(), anchor.sourceCheckpointBytes()) - || !checkpoint.checkpointDigest().equals(anchor.sourceCheckpointDigest()) - || !Arrays.equals(checkpoint.latestIssuerEventBytes(), anchor.sourceEventBytes()) - || !Objects.equals(checkpoint.latestIssuerEventDigest(), anchor.sourceEventDigest()) - || !Arrays.equals( - CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(state.incarnation()), - anchor.incarnationBytes())) { + if (!REDIS.matchesCurrentState(current, work.anchor())) { throw unavailable("Issuer source checkpoint or incarnation changed"); } } @@ -416,113 +360,20 @@ private RedisScriptDescriptor requireDescriptor() { } catch (RuntimeException missing) { throw unavailable("Manual issuer release descriptor is not installed", missing); } - if (!CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.SCRIPT_ID.equals( - descriptor.scriptId()) - || !CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.RESOURCE_PATH.equals( - descriptor.resourcePath()) - || !"game-session-service".equals(descriptor.owner()) - || !PRINCIPAL.equals(descriptor.principal()) - || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION - || !EXPECTED_KEYS.equals(descriptor.keys()) - || !EXPECTED_ARGUMENTS.equals(descriptor.arguments()) - || descriptor.category() != RedisScriptDescriptor.ScriptCategory.SESSION_ISSUER_INDEX - || !EXPECTED_OUTCOMES.equals(descriptor.outcomes()) - || descriptor.resetSensitivity() != RedisScriptDescriptor.ResetSensitivity.CLUSTER - || descriptor.lossClass() != RedisScriptDescriptor.LossClass.EMPTY_REDIS_COLD_START_OR_RESET - || descriptor.compatibilityLevel() - != RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET - || !descriptor - .supportedCoexistence() - .equals(List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "v2"))) - || descriptor.legacyPayloadShape() != null) { + if (!REDIS.matchesDescriptor( + descriptor, + CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.SCRIPT_ID, + CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.RESOURCE_PATH, + EXPECTED_KEYS, + EXPECTED_ARGUMENTS, + EXPECTED_OUTCOMES)) { throw unavailable("Manual issuer release descriptor differs from its exact owner contract"); } return descriptor; } - private static byte[] scriptSource(RedisScriptDescriptor descriptor) { - try (InputStream input = - CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.class - .getClassLoader() - .getResourceAsStream(descriptor.resourcePath())) { - if (input == null) throw unavailable("Issuer release Lua resource is missing"); - byte[] bytes = input.readNBytes(MAX_SCRIPT_BYTES + 1); - if (bytes.length == 0 - || bytes.length > MAX_SCRIPT_BYTES - || !descriptor.sha256().equals(digest("SHA-256", bytes))) { - throw unavailable("Issuer release Lua differs from its exact descriptor digest"); - } - return bytes; - } catch (IOException | RuntimeException failure) { - throw unavailable("Issuer release Lua is unavailable", failure); - } - } - - private static Map decodePhysicalMap(Map encoded) { - Map result = new HashMap<>(); - encoded.forEach( - (field, value) -> result.put(decodeUtf8(Base64.getDecoder().decode(field)), value.clone())); - return result; - } - - private static String b64(byte[] value) { - return Base64.getEncoder().encodeToString(value); - } - - private static String decodeUtf8(byte[] bytes) { - try { - return StandardCharsets.UTF_8 - .newDecoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .decode(java.nio.ByteBuffer.wrap(bytes)) - .toString(); - } catch (CharacterCodingException malformed) { - throw unavailable("Issuer hash field is not valid UTF-8", malformed); - } - } - - private static byte[] ascii(String value) { - return value.getBytes(StandardCharsets.US_ASCII); - } - - private static RedisAsyncCommands requireCommands( - StatefulRedisConnection connection) { - if (connection == null || !connection.isOpen()) - throw unavailable("Redis connection is unavailable"); - return connection.async(); - } - - private static void requirePrincipal(String principal) { - if (!PRINCIPAL.equals(principal)) - throw unavailable("Redis principal is not the exact coordination owner"); - } - - private static T await(RedisFuture future) { - try { - return future.get(COMMAND_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - future.cancel(true); - throw unavailable("Redis issuer release command was interrupted", interrupted); - } catch (ExecutionException | TimeoutException | RuntimeException failure) { - future.cancel(true); - throw unavailable("Redis issuer release command failed", failure); - } - } - - private static String digest(String algorithm, byte[] bytes) { - try { - return HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(bytes)); - } catch (Exception failure) { - throw unavailable("Could not verify issuer release Lua digest", failure); - } - } - private static void requireNoAmbientTransaction() { - if (TransactionSynchronizationManager.isActualTransactionActive()) { - throw unavailable("Physical issuer release cannot run inside an ambient SQL transaction"); - } + REDIS.requireNoAmbientTransaction(); } private static IllegalStateException unavailable(String message) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.java index ea8a7ffa64..598167ed9f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.java @@ -1,40 +1,31 @@ package net.firedevops.firemud.gamesession.repository; +import static net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerPartitionRedisSupport.KEY_PREFIX; +import static net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerPartitionRedisSupport.ascii; +import static net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerPartitionRedisSupport.b64; + import io.lettuce.core.RedisClient; -import io.lettuce.core.RedisFuture; -import io.lettuce.core.ScriptOutputType; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.async.RedisAsyncCommands; import io.lettuce.core.codec.ByteArrayCodec; -import java.io.InputStream; -import java.nio.ByteBuffer; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; import java.util.ArrayList; import java.util.Arrays; -import java.util.Base64; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution; -import org.springframework.transaction.support.TransactionSynchronizationManager; /** Manual one-key owner for exact original-operation terminal capacity retirement. */ final class CanonicalGameplayIssuerBindingLocalRetirementRedisOwner { - private static final String PRINCIPAL = "gamesession_coord_app"; - private static final String KEY_PREFIX = "session:game:index:issuer:"; - private static final int MAX_SCRIPT_BYTES = 128 * 1024; - private static final long COMMAND_TIMEOUT_MILLIS = 5_000; + private static final CanonicalGameplayIssuerPartitionRedisSupport REDIS = + new CanonicalGameplayIssuerPartitionRedisSupport( + CanonicalGameplayIssuerBindingLocalRetirementRedisOwner::unavailable); private static final List EXPECTED_KEYS = List.of( new RedisScriptDescriptor.KeySpec( @@ -111,7 +102,7 @@ Readback retireAndRead(CanonicalGameplayIssuerBindingLocalRetirementOperation op } requireFreshCurrentState(work); RedisScriptDescriptor descriptor = requireDescriptor(); - byte[] script = scriptSource(descriptor); + byte[] script = REDIS.scriptSource(descriptor); byte[] key = exactPartitionKey(work); long outcome = writeOneKey(script, key, scriptArguments(work, operation)); if (outcome != 1 && outcome != 2) { @@ -137,17 +128,8 @@ Readback retireAndRead(CanonicalGameplayIssuerBindingLocalRetirementOperation op private long writeOneKey(byte[] script, byte[] key, byte[][] arguments) { requireNoAmbientTransaction(); - try (StatefulRedisConnection connection = - redisClient.connect(ByteArrayCodec.INSTANCE)) { - RedisAsyncCommands commands = requireCommands(connection); - requirePrincipal(await(commands.aclWhoami())); - String sha = await(commands.scriptLoad(script)); - if (!digest("SHA-1", script).equals(sha)) - throw unavailable("Redis loaded a different script"); - Long reply = - await(commands.evalsha(sha, ScriptOutputType.INTEGER, new byte[][] {key}, arguments)); - if (reply == null) throw unavailable("Redis returned no retirement result"); - return reply; + try { + return REDIS.writeOneKey(redisClient, script, key, arguments); } catch (RuntimeException failure) { throw unavailable("One-key issuer retirement command failed", failure); } @@ -160,35 +142,8 @@ private byte[] readExactPhysicalState( requireNoAmbientTransaction(); try (StatefulRedisConnection connection = redisClient.connect(ByteArrayCodec.INSTANCE)) { - RedisAsyncCommands commands = requireCommands(connection); - requirePrincipal(await(commands.aclWhoami())); - if (!"hash".equals(await(commands.type(key))) - || !Long.valueOf(-1L).equals(await(commands.pttl(key)))) { - throw unavailable("Issuer partition type or TTL is not canonical"); - } - Long length = await(commands.hlen(key)); - int max = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_LOCAL_HASH_FIELDS; - if (length == null || length < 1 || length > max) { - throw unavailable("Issuer retirement readback field count is outside its strict bound"); - } - Map raw = await(commands.hgetall(key)); - if (raw == null || raw.size() != length) - throw unavailable("Issuer retirement readback is incomplete"); - Map actual = new HashMap<>(); - long byteCount = 0; - for (Map.Entry entry : raw.entrySet()) { - byte[] field = Objects.requireNonNull(entry.getKey(), "Redis field"); - byte[] value = Objects.requireNonNull(entry.getValue(), "Redis value"); - byteCount = Math.addExact(byteCount, field.length + (long) value.length); - if (byteCount - > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_TOTAL_HASH_BYTES) { - throw unavailable("Issuer retirement readback exceeds its bounded bytes"); - } - String encoded = Base64.getEncoder().encodeToString(field); - if (actual.putIfAbsent(encoded, value.clone()) != null) { - throw unavailable("Issuer retirement readback repeats a field"); - } - } + RedisAsyncCommands commands = REDIS.authenticatedCommands(connection); + Map actual = REDIS.readBoundedHash(commands, key); Map allowed = new HashMap<>(work.allowedFields()); String capacityField = CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( @@ -220,7 +175,7 @@ private byte[] readExactPhysicalState( } } for (Map.Entry field : actual.entrySet()) { - String decoded = decodeUtf8(Base64.getDecoder().decode(field.getKey())); + String decoded = REDIS.decodeField(field.getKey()); if (decoded.equals(CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD)) continue; byte[] expected = allowed.get(decoded); @@ -263,7 +218,7 @@ private byte[] readExactPhysicalState( throw unavailable("Exact terminal capacity field remains after retirement"); } return CanonicalGameplayIssuerBootstrapCoverageRepository.encodeFieldSet( - decodePhysicalMap(actual)); + REDIS.decodePhysicalMap(actual)); } catch (RuntimeException failure) { throw unavailable("Independent issuer retirement readback was not exact", failure); } @@ -338,20 +293,9 @@ private byte[] exactPartitionKey( private void requireFreshCurrentState( CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work) { requireNoAmbientTransaction(); - var state = currentStateSource.readFreshCurrentState(); + var current = currentStateSource.readFreshCurrentState(); requireNoAmbientTransaction(); - var checkpoint = state == null ? null : state.accountCheckpoint(); - var anchor = work.anchor(); - if (checkpoint == null - || !checkpoint.issuerId().equals(anchor.issuerId()) - || !checkpoint.issuerAuthGeneration().equals(anchor.issuerAuthGeneration()) - || !Arrays.equals(checkpoint.exactCheckpointBytes(), anchor.sourceCheckpointBytes()) - || !checkpoint.checkpointDigest().equals(anchor.sourceCheckpointDigest()) - || !Arrays.equals(checkpoint.latestIssuerEventBytes(), anchor.sourceEventBytes()) - || !Objects.equals(checkpoint.latestIssuerEventDigest(), anchor.sourceEventDigest()) - || !Arrays.equals( - CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(state.incarnation()), - anchor.incarnationBytes())) { + if (!REDIS.matchesCurrentState(current, work.anchor())) { throw unavailable("Issuer source checkpoint or incarnation changed"); } } @@ -365,113 +309,21 @@ private RedisScriptDescriptor requireDescriptor() { } catch (RuntimeException missing) { throw unavailable("Manual issuer retirement descriptor is not installed", missing); } - if (!CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution.SCRIPT_ID.equals( - descriptor.scriptId()) - || !CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution.RESOURCE_PATH - .equals(descriptor.resourcePath()) - || !"game-session-service".equals(descriptor.owner()) - || !PRINCIPAL.equals(descriptor.principal()) - || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION - || !EXPECTED_KEYS.equals(descriptor.keys()) - || !EXPECTED_ARGUMENTS.equals(descriptor.arguments()) - || descriptor.category() != RedisScriptDescriptor.ScriptCategory.SESSION_ISSUER_INDEX - || !EXPECTED_OUTCOMES.equals(descriptor.outcomes()) - || descriptor.resetSensitivity() != RedisScriptDescriptor.ResetSensitivity.CLUSTER - || descriptor.lossClass() != RedisScriptDescriptor.LossClass.EMPTY_REDIS_COLD_START_OR_RESET - || descriptor.compatibilityLevel() - != RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET - || !descriptor - .supportedCoexistence() - .equals(List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "v2"))) - || descriptor.legacyPayloadShape() != null) { + if (!REDIS.matchesDescriptor( + descriptor, + CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution.SCRIPT_ID, + CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution.RESOURCE_PATH, + EXPECTED_KEYS, + EXPECTED_ARGUMENTS, + EXPECTED_OUTCOMES)) { throw unavailable( "Manual issuer retirement descriptor differs from its exact owner contract"); } return descriptor; } - private static byte[] scriptSource(RedisScriptDescriptor descriptor) { - try (InputStream input = - CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.class - .getClassLoader() - .getResourceAsStream(descriptor.resourcePath())) { - if (input == null) throw unavailable("Issuer retirement Lua resource is missing"); - byte[] bytes = input.readNBytes(MAX_SCRIPT_BYTES + 1); - if (bytes.length == 0 - || bytes.length > MAX_SCRIPT_BYTES - || !descriptor.sha256().equals(digest("SHA-256", bytes))) { - throw unavailable("Issuer retirement Lua differs from its exact descriptor digest"); - } - return bytes; - } catch (java.io.IOException failure) { - throw unavailable("Issuer retirement Lua resource could not be read", failure); - } - } - - private static Map decodePhysicalMap(Map encoded) { - Map result = new HashMap<>(); - encoded.forEach( - (field, value) -> result.put(decodeUtf8(Base64.getDecoder().decode(field)), value.clone())); - return result; - } - - private static String b64(byte[] bytes) { - return Base64.getEncoder().encodeToString(bytes); - } - - private static byte[] ascii(String value) { - return value.getBytes(StandardCharsets.US_ASCII); - } - - private static String decodeUtf8(byte[] bytes) { - try { - return StandardCharsets.UTF_8 - .newDecoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .decode(ByteBuffer.wrap(bytes)) - .toString(); - } catch (CharacterCodingException malformed) { - throw unavailable("Issuer partition contains a non-UTF-8 field", malformed); - } - } - - private static RedisAsyncCommands requireCommands( - StatefulRedisConnection connection) { - if (connection == null || !connection.isOpen()) throw unavailable("Redis connection is closed"); - return connection.async(); - } - - private static void requirePrincipal(String principal) { - if (!PRINCIPAL.equals(principal)) - throw unavailable("Redis ACL principal is not the exact owner"); - } - - private static T await(RedisFuture future) { - try { - return future.get(COMMAND_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - future.cancel(true); - throw unavailable("Redis command was interrupted", interrupted); - } catch (ExecutionException | TimeoutException | RuntimeException failure) { - future.cancel(true); - throw unavailable("Redis command did not return exact proof", failure); - } - } - - private static String digest(String algorithm, byte[] value) { - try { - return java.util.HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(value)); - } catch (Exception impossible) { - throw new IllegalStateException("Required digest algorithm is unavailable", impossible); - } - } - private static void requireNoAmbientTransaction() { - if (TransactionSynchronizationManager.isActualTransactionActive()) { - throw unavailable("Redis retirement cannot run inside an ambient SQL transaction"); - } + REDIS.requireNoAmbientTransaction(); } private static IllegalStateException unavailable(String message) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionRedisSupport.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionRedisSupport.java new file mode 100644 index 0000000000..b34fc21b37 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionRedisSupport.java @@ -0,0 +1,229 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisFuture; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.async.RedisAsyncCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.BiFunction; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Shared strict mechanics for the manual issuer partition lifecycle owners. */ +final class CanonicalGameplayIssuerPartitionRedisSupport { + static final String KEY_PREFIX = "session:game:index:issuer:"; + private static final String PRINCIPAL = "gamesession_coord_app"; + private static final int MAX_SCRIPT_BYTES = 128 * 1024; + private static final long COMMAND_TIMEOUT_MILLIS = 5_000; + + private final BiFunction unavailable; + + CanonicalGameplayIssuerPartitionRedisSupport( + BiFunction unavailable) { + this.unavailable = Objects.requireNonNull(unavailable, "Owner error factory is required"); + } + + boolean matchesCurrentState( + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current, + CanonicalGameplayIssuerInstalledAnchor anchor) { + return current != null + && sameCheckpoint(current.accountCheckpoint(), anchor) + && Arrays.equals( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(current.incarnation()), + anchor.incarnationBytes()); + } + + private static boolean sameCheckpoint( + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint current, + CanonicalGameplayIssuerInstalledAnchor anchor) { + return current != null + && current.issuerId().equals(anchor.issuerId()) + && current.issuerAuthGeneration().equals(anchor.issuerAuthGeneration()) + && Arrays.equals(current.exactCheckpointBytes(), anchor.sourceCheckpointBytes()) + && current.checkpointDigest().equals(anchor.sourceCheckpointDigest()) + && Arrays.equals(current.latestIssuerEventBytes(), anchor.sourceEventBytes()) + && Objects.equals(current.latestIssuerEventDigest(), anchor.sourceEventDigest()); + } + + boolean matchesDescriptor( + RedisScriptDescriptor descriptor, + String scriptId, + String resourcePath, + List keys, + List arguments, + List outcomes) { + return scriptId.equals(descriptor.scriptId()) + && resourcePath.equals(descriptor.resourcePath()) + && "game-session-service".equals(descriptor.owner()) + && PRINCIPAL.equals(descriptor.principal()) + && descriptor.role() == RedisScriptDescriptor.RedisRole.COORDINATION + && keys.equals(descriptor.keys()) + && arguments.equals(descriptor.arguments()) + && descriptor.category() == RedisScriptDescriptor.ScriptCategory.SESSION_ISSUER_INDEX + && outcomes.equals(descriptor.outcomes()) + && descriptor.resetSensitivity() == RedisScriptDescriptor.ResetSensitivity.CLUSTER + && descriptor.lossClass() == RedisScriptDescriptor.LossClass.EMPTY_REDIS_COLD_START_OR_RESET + && descriptor.compatibilityLevel() + == RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET + && descriptor + .supportedCoexistence() + .equals(List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "v2"))) + && descriptor.legacyPayloadShape() == null; + } + + byte[] scriptSource(RedisScriptDescriptor descriptor) { + try (InputStream input = + CanonicalGameplayIssuerPartitionRedisSupport.class + .getClassLoader() + .getResourceAsStream(descriptor.resourcePath())) { + if (input == null) throw failure("Issuer Lua resource is missing", null); + byte[] bytes = input.readNBytes(MAX_SCRIPT_BYTES + 1); + if (bytes.length == 0 + || bytes.length > MAX_SCRIPT_BYTES + || !descriptor.sha256().equals(digest("SHA-256", bytes))) { + throw failure("Issuer Lua differs from its exact descriptor digest", null); + } + return bytes; + } catch (IOException failure) { + throw failure("Issuer Lua resource could not be read", failure); + } + } + + long writeOneKey(RedisClient client, byte[] script, byte[] key, byte[][] arguments) { + try (StatefulRedisConnection connection = + client.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = authenticatedCommands(connection); + String sha = await(commands.scriptLoad(script)); + if (!digest("SHA-1", script).equals(sha)) + throw failure("Redis loaded a different script", null); + Long reply = + await(commands.evalsha(sha, ScriptOutputType.INTEGER, new byte[][] {key}, arguments)); + if (reply == null) throw failure("Redis returned no issuer mutation result", null); + return reply; + } + } + + /** Returns Base64 field keys so distinct byte fields cannot be collapsed by text decoding. */ + Map readBoundedHash(RedisAsyncCommands commands, byte[] key) { + if (!"hash".equals(await(commands.type(key))) + || !Long.valueOf(-1L).equals(await(commands.pttl(key)))) { + throw failure("Issuer partition type or TTL is not canonical", null); + } + Long count = await(commands.hlen(key)); + if (count == null + || count < 1 + || count > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_LOCAL_HASH_FIELDS) { + throw failure("Issuer partition field count is outside its strict bound", null); + } + Map raw = await(commands.hgetall(key)); + if (raw == null || raw.size() != count) + throw failure("Issuer partition readback is incomplete", null); + Map actual = new HashMap<>(); + long bytes = 0; + for (Map.Entry field : raw.entrySet()) { + byte[] name = Objects.requireNonNull(field.getKey(), "Redis field"); + byte[] value = Objects.requireNonNull(field.getValue(), "Redis value"); + bytes = Math.addExact(bytes, name.length + (long) value.length); + if (bytes > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_TOTAL_HASH_BYTES) { + throw failure("Issuer partition readback exceeds its bounded bytes", null); + } + if (actual.putIfAbsent(b64(name), value.clone()) != null) { + throw failure("Issuer partition readback repeats a physical field", null); + } + } + return actual; + } + + Map decodePhysicalMap(Map encoded) { + Map result = new HashMap<>(); + encoded.forEach((field, value) -> result.put(decodeField(field), value.clone())); + return result; + } + + String decodeField(String encoded) { + return decodeUtf8(Base64.getDecoder().decode(encoded)); + } + + private String decodeUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw failure("Issuer partition contains a non-UTF-8 field", malformed); + } + } + + RedisAsyncCommands authenticatedCommands( + StatefulRedisConnection connection) { + if (connection == null || !connection.isOpen()) + throw failure("Redis connection is closed", null); + RedisAsyncCommands commands = connection.async(); + requirePrincipal(await(commands.aclWhoami())); + return commands; + } + + private void requirePrincipal(String principal) { + if (!PRINCIPAL.equals(principal)) + throw failure("Redis ACL principal is not the exact owner", null); + } + + private T await(RedisFuture future) { + try { + return future.get(COMMAND_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + future.cancel(true); + throw failure("Redis command was interrupted", interrupted); + } catch (ExecutionException | TimeoutException | RuntimeException failure) { + future.cancel(true); + throw failure("Redis command did not return exact proof", failure); + } + } + + void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) + throw failure("Issuer Redis operation cannot run inside an ambient SQL transaction", null); + } + + private String digest(String algorithm, byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(value)); + } catch (Exception failure) { + throw failure("Could not verify issuer Lua digest", failure); + } + } + + static String b64(byte[] bytes) { + return Base64.getEncoder().encodeToString(bytes); + } + + static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private IllegalStateException failure(String message, Throwable cause) { + return unavailable.apply(message, cause); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRedisScriptContribution.java index 3e25b7d29d..1dac7891be 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRedisScriptContribution.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRedisScriptContribution.java @@ -1,14 +1,9 @@ package net.firedevops.firemud.gamesession.service; -import java.io.IOException; -import java.io.InputStream; import java.util.Collection; import java.util.List; import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; -import tools.jackson.core.StreamReadFeature; -import tools.jackson.databind.DeserializationFeature; -import tools.jackson.databind.json.JsonMapper; /** Passive manual-catalog contribution for ordinary binding-local issuer projection. */ public final class CanonicalGameplayIssuerBindingLocalRedisScriptContribution @@ -17,12 +12,6 @@ public final class CanonicalGameplayIssuerBindingLocalRedisScriptContribution public static final String RESOURCE_PATH = "redis/lua/game-session-issuer-binding-local-add.lua"; private static final String DESCRIPTOR_PATH = "/redis/scripts/game-session-issuer-binding-local-add.json"; - private static final JsonMapper JSON = - JsonMapper.builder() - .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) - .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) - .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) - .build(); @Override public String ownerId() { @@ -31,23 +20,12 @@ public String ownerId() { @Override public Collection descriptors() { - try (InputStream input = getClass().getResourceAsStream(DESCRIPTOR_PATH)) { - if (input == null) throw new IOException("Descriptor resource is missing"); - byte[] bytes = input.readNBytes(16 * 1024 + 1); - if (bytes.length == 0 || bytes.length > 16 * 1024) { - throw new IOException("Descriptor resource is empty or oversized"); - } - RedisScriptDescriptor descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); - if (!ownerId().equals(descriptor.owner()) || !SCRIPT_ID.equals(descriptor.scriptId())) { - throw new IllegalArgumentException("Descriptor owner or script identity is invalid"); - } - return List.of(descriptor); - } catch (IOException | RuntimeException failure) { - throw unavailable(failure); - } - } - - private static IllegalStateException unavailable(Throwable cause) { - return new IllegalStateException("Issuer binding-local Redis descriptor is unavailable", cause); + return List.of( + GameSessionRedisScriptDescriptors.load( + getClass(), + DESCRIPTOR_PATH, + ownerId(), + SCRIPT_ID, + "Issuer binding-local Redis descriptor is unavailable")); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.java index c0b5f01a70..99092f15f9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.java @@ -1,14 +1,9 @@ package net.firedevops.firemud.gamesession.service; -import java.io.IOException; -import java.io.InputStream; import java.util.Collection; import java.util.List; import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; -import tools.jackson.core.StreamReadFeature; -import tools.jackson.databind.DeserializationFeature; -import tools.jackson.databind.json.JsonMapper; /** Passive manual-catalog contribution for the purpose-specific issuer release operation. */ public final class CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution @@ -18,12 +13,6 @@ public final class CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribu "redis/lua/game-session-issuer-binding-local-release.lua"; private static final String DESCRIPTOR_PATH = "/redis/scripts/game-session-issuer-binding-local-release.json"; - private static final JsonMapper JSON = - JsonMapper.builder() - .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) - .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) - .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) - .build(); @Override public String ownerId() { @@ -32,24 +21,12 @@ public String ownerId() { @Override public Collection descriptors() { - try (InputStream input = getClass().getResourceAsStream(DESCRIPTOR_PATH)) { - if (input == null) throw new IOException("Descriptor resource is missing"); - byte[] bytes = input.readNBytes(16 * 1024 + 1); - if (bytes.length == 0 || bytes.length > 16 * 1024) { - throw new IOException("Descriptor resource is empty or oversized"); - } - RedisScriptDescriptor descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); - if (!ownerId().equals(descriptor.owner()) || !SCRIPT_ID.equals(descriptor.scriptId())) { - throw new IllegalArgumentException("Descriptor owner or script identity is invalid"); - } - return List.of(descriptor); - } catch (IOException | RuntimeException failure) { - throw unavailable(failure); - } - } - - private static IllegalStateException unavailable(Throwable cause) { - return new IllegalStateException( - "Issuer binding-local release Redis descriptor is unavailable", cause); + return List.of( + GameSessionRedisScriptDescriptors.load( + getClass(), + DESCRIPTOR_PATH, + ownerId(), + SCRIPT_ID, + "Issuer binding-local release Redis descriptor is unavailable")); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution.java index 36aeb0cbd5..82c0ae78b1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution.java @@ -1,14 +1,9 @@ package net.firedevops.firemud.gamesession.service; -import java.io.IOException; -import java.io.InputStream; import java.util.Collection; import java.util.List; import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; -import tools.jackson.core.StreamReadFeature; -import tools.jackson.databind.DeserializationFeature; -import tools.jackson.databind.json.JsonMapper; /** Passive manual-catalog contribution for one original-operation physical retirement. */ public final class CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution @@ -18,12 +13,6 @@ public final class CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContr "redis/lua/game-session-issuer-binding-local-retirement.lua"; private static final String DESCRIPTOR_PATH = "/redis/scripts/game-session-issuer-binding-local-retirement.json"; - private static final JsonMapper JSON = - JsonMapper.builder() - .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) - .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) - .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) - .build(); @Override public String ownerId() { @@ -32,20 +21,12 @@ public String ownerId() { @Override public Collection descriptors() { - try (InputStream input = getClass().getResourceAsStream(DESCRIPTOR_PATH)) { - if (input == null) throw new IOException("Descriptor resource is missing"); - byte[] bytes = input.readNBytes(16 * 1024 + 1); - if (bytes.length == 0 || bytes.length > 16 * 1024) { - throw new IOException("Descriptor resource is empty or oversized"); - } - RedisScriptDescriptor descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); - if (!ownerId().equals(descriptor.owner()) || !SCRIPT_ID.equals(descriptor.scriptId())) { - throw new IllegalArgumentException("Descriptor owner or script identity is invalid"); - } - return List.of(descriptor); - } catch (IOException | RuntimeException failure) { - throw new IllegalStateException( - "Issuer binding-local retirement descriptor is unavailable", failure); - } + return List.of( + GameSessionRedisScriptDescriptors.load( + getClass(), + DESCRIPTOR_PATH, + ownerId(), + SCRIPT_ID, + "Issuer binding-local retirement descriptor is unavailable")); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.java index 6fcd308104..bcf59d0ae2 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution.java @@ -1,14 +1,9 @@ package net.firedevops.firemud.gamesession.service; -import java.io.IOException; -import java.io.InputStream; import java.util.Collection; import java.util.List; import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; -import tools.jackson.core.StreamReadFeature; -import tools.jackson.databind.DeserializationFeature; -import tools.jackson.databind.json.JsonMapper; /** Passive manual-catalog contribution for the local issuer-bootstrap partition builder. */ public final class CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution @@ -18,12 +13,6 @@ public final class CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribut "redis/lua/game-session-issuer-bootstrap-partition-build.lua"; private static final String DESCRIPTOR_PATH = "/redis/scripts/game-session-issuer-bootstrap-partition-build.json"; - private static final JsonMapper JSON = - JsonMapper.builder() - .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) - .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) - .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) - .build(); @Override public String ownerId() { @@ -32,24 +21,12 @@ public String ownerId() { @Override public Collection descriptors() { - try (InputStream input = getClass().getResourceAsStream(DESCRIPTOR_PATH)) { - if (input == null) throw new IOException("Descriptor resource is missing"); - byte[] bytes = input.readNBytes(16 * 1024 + 1); - if (bytes.length == 0 || bytes.length > 16 * 1024) { - throw new IOException("Descriptor resource is empty or oversized"); - } - RedisScriptDescriptor descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); - if (!ownerId().equals(descriptor.owner()) || !SCRIPT_ID.equals(descriptor.scriptId())) { - throw new IllegalArgumentException("Descriptor owner or script identity is invalid"); - } - return List.of(descriptor); - } catch (IOException | RuntimeException failure) { - throw unavailable(failure); - } - } - - private static IllegalStateException unavailable(Throwable cause) { - return new IllegalStateException( - "Issuer bootstrap partition Redis descriptor is unavailable", cause); + return List.of( + GameSessionRedisScriptDescriptors.load( + getClass(), + DESCRIPTOR_PATH, + ownerId(), + SCRIPT_ID, + "Issuer bootstrap partition Redis descriptor is unavailable")); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRedisScriptDescriptors.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRedisScriptDescriptors.java new file mode 100644 index 0000000000..771e5d8790 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRedisScriptDescriptors.java @@ -0,0 +1,38 @@ +package net.firedevops.firemud.gamesession.service; + +import java.io.IOException; +import java.io.InputStream; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Strict bounded resource loading for passive Game Session Redis script contributions. */ +final class GameSessionRedisScriptDescriptors { + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private GameSessionRedisScriptDescriptors() {} + + static RedisScriptDescriptor load( + Class resourceOwner, String path, String ownerId, String scriptId, String failureMessage) { + try (InputStream input = resourceOwner.getResourceAsStream(path)) { + if (input == null) throw new IOException("Descriptor resource is missing"); + byte[] bytes = input.readNBytes(16 * 1024 + 1); + if (bytes.length == 0 || bytes.length > 16 * 1024) { + throw new IOException("Descriptor resource is empty or oversized"); + } + RedisScriptDescriptor descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); + if (!ownerId.equals(descriptor.owner()) || !scriptId.equals(descriptor.scriptId())) { + throw new IllegalArgumentException("Descriptor owner or script identity is invalid"); + } + return descriptor; + } catch (IOException | RuntimeException failure) { + throw new IllegalStateException(failureMessage, failure); + } + } +} 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 57c87fb794..092c886ee6 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 @@ -4,9 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import io.lettuce.core.AclSetuserArgs; -import io.lettuce.core.ClientOptions; import io.lettuce.core.RedisClient; -import io.lettuce.core.RedisURI; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.sync.RedisCommands; import io.lettuce.core.codec.ByteArrayCodec; @@ -16,8 +14,6 @@ import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.nio.file.Path; -import java.sql.Connection; -import java.sql.SQLException; import java.time.Duration; import java.util.List; import java.util.Objects; @@ -28,7 +24,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; -import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; @@ -744,76 +739,22 @@ private CanonicalGameplayIssuerBootstrapCoverageOwner initialCoverageOwner( private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor descriptor(BigInteger capacity) { - String exact = - "issuer-layout-descriptor/v1|" - + ISSUER - + "|" - + LAYOUT_VERSION - + "|" - + PARTITION_COUNT - + "|" - + capacity - + "|" - + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY; - return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor( - ISSUER, - LAYOUT_VERSION, - PARTITION_COUNT, - capacity, - CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY, - exact.getBytes(StandardCharsets.UTF_8)); + return CanonicalGameplayIssuerTestFixtures.descriptor( + ISSUER, LAYOUT_VERSION, PARTITION_COUNT, capacity); } private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint sourceCheckpoint(BigInteger generation) { - long sequence = generation.longValueExact() - 1; - var event = - AccountAuthoritySourceEventV1Codec.sealIssuer( - new AccountAuthoritySourceEventV1Codec.IssuerPreimage( - UUID.randomUUID().toString(), - UUID.randomUUID().toString(), - AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + ISSUER, - Long.toString(sequence), - ISSUER, - generation.toString(), - generation.toString(), - "ISSUER_SECURITY_CHANGE")); - byte[] bytes = event.canonicalJsonUtf8(); - return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint( - ISSUER, generation, bytes, bytes); + return CanonicalGameplayIssuerTestFixtures.sourceCheckpoint(ISSUER, generation); } private static CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint checkpointShape(BigInteger generation) { - var trusted = sourceCheckpoint(generation); - byte[] checkpoint = trusted.checkpointBytes(); - byte[] event = trusted.latestEventBytes(); - return new CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint( - trusted.issuerId(), - trusted.issuerAuthGeneration(), - checkpoint, - CanonicalGameplayIssuerMemberV2Codec.sha256(checkpoint), - event, - CanonicalGameplayIssuerMemberV2Codec.sha256(event)); + return CanonicalGameplayIssuerTestFixtures.checkpointShape(ISSUER, generation); } private static CanonicalGameplayIssuerMemberV2Value.Incarnation stableIncarnation(String seed) { - String digest = digest(seed.getBytes(StandardCharsets.UTF_8)); - var deployment = - new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( - "controlled-deployment-" + seed, - "deployment-generation-" + seed, - List.of("controlled-node-" + seed), - "controlled-redis-build-" + seed, - "controlled-lua-registry-" + seed, - digest, - "READY", - "boot-" + seed, - "startup-" + seed, - "storage-" + seed, - "aof-" + seed); - return new CanonicalGameplayIssuerMemberV2Value.Incarnation( - "controlled-attestor-" + seed, digest, deployment, digest, digest); + return CanonicalGameplayIssuerTestFixtures.stableIncarnation(seed); } private static CanonicalGameplayIssuerBindingLocalOperation.Request request( @@ -904,64 +845,33 @@ private void establishActualLegacyDisposition(DSLContext dsl) { } private TestSchema newTestSchemaAtVersion(String prefix) { - String schema = prefix + UUID.randomUUID().toString().replace("-", ""); + 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("1030")) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, schema, MIGRATION_LOCATION, "1030"); return new TestSchema(schema, dataSource, DSL.using(dataSource, SQLDialect.POSTGRES)); } private static void migrateRemaining(TestSchema schema) { - Flyway.configure() - .dataSource(schema.dataSource()) - .schemas(schema.schema()) - .defaultSchema(schema.schema()) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + schema.dataSource(), schema.schema(), MIGRATION_LOCATION, null); } private DriverManagerDataSource dataSource(String schemaName) { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("org.postgresql.Driver"); - String jdbcUrl = POSTGRES.getJdbcUrl(); - dataSource.setUrl( - jdbcUrl + (jdbcUrl.contains("?") ? "&" : "?") + "currentSchema=" + schemaName); - dataSource.setUsername(POSTGRES.getUsername()); - dataSource.setPassword(POSTGRES.getPassword()); - return dataSource; + return CanonicalGameplayIssuerTestFixtures.dataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword(), schemaName); } private void dropSchema(String schemaName) { - try (Connection connection = dataSource("public").getConnection()) { - DSL.using(connection, SQLDialect.POSTGRES) - .execute("DROP SCHEMA IF EXISTS \"" + schemaName + "\" CASCADE"); - } catch (SQLException failure) { - throw new IllegalStateException( - "Could not drop the owned issuer local-operation test schema", failure); - } + CanonicalGameplayIssuerTestFixtures.dropSchema( + dataSource("public"), + schemaName, + "Could not drop the owned issuer local-operation test schema"); } private static RedisClient createRedisClient(String username, String password) { - RedisURI.Builder builder = RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(6379)); - if (username != null) builder.withAuthentication(username, password); - RedisURI uri = builder.build(); - uri.setTimeout(Duration.ofSeconds(5)); - RedisClient client = RedisClient.create(uri); - client.setOptions( - ClientOptions.builder() - .autoReconnect(false) - .protocolVersion(io.lettuce.core.protocol.ProtocolVersion.RESP2) - .build()); - return client; + return CanonicalGameplayIssuerTestFixtures.createRedisClient( + REDIS.getHost(), REDIS.getMappedPort(6379), username, password); } private static long count(DSLContext dsl, String table) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java index 40a6ac0b26..031ddb7e26 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java @@ -5,9 +5,7 @@ import static org.assertj.core.api.Assertions.catchThrowable; import io.lettuce.core.AclSetuserArgs; -import io.lettuce.core.ClientOptions; import io.lettuce.core.RedisClient; -import io.lettuce.core.RedisURI; import io.lettuce.core.ScriptOutputType; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.sync.RedisCommands; @@ -20,12 +18,9 @@ import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.nio.file.Path; -import java.sql.Connection; -import java.sql.SQLException; import java.time.Duration; import java.util.ArrayList; import java.util.Base64; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -38,7 +33,6 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; -import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountIndexMember; @@ -50,8 +44,6 @@ import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution; 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.SQLDialect; import org.jooq.impl.DSL; @@ -989,76 +981,22 @@ private static byte[] ascii(String value) { private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor descriptor(BigInteger partitions) { - String exact = - "issuer-layout-descriptor/v1|" - + ISSUER - + "|" - + LAYOUT_VERSION - + "|" - + partitions - + "|" - + PARTITION_CAPACITY - + "|" - + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY; - return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor( - ISSUER, - LAYOUT_VERSION, - partitions, - PARTITION_CAPACITY, - CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY, - exact.getBytes(StandardCharsets.UTF_8)); + return CanonicalGameplayIssuerTestFixtures.descriptor( + ISSUER, LAYOUT_VERSION, partitions, PARTITION_CAPACITY); } private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint sourceCheckpoint(BigInteger generation) { - long sequence = generation.longValueExact() - 1; - var event = - AccountAuthoritySourceEventV1Codec.sealIssuer( - new AccountAuthoritySourceEventV1Codec.IssuerPreimage( - UUID.randomUUID().toString(), - UUID.randomUUID().toString(), - AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + ISSUER, - Long.toString(sequence), - ISSUER, - generation.toString(), - generation.toString(), - "ISSUER_SECURITY_CHANGE")); - byte[] bytes = event.canonicalJsonUtf8(); - return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint( - ISSUER, generation, bytes, bytes); + return CanonicalGameplayIssuerTestFixtures.sourceCheckpoint(ISSUER, generation); } private static CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint checkpointShape(BigInteger generation) { - var trusted = sourceCheckpoint(generation); - byte[] checkpoint = trusted.checkpointBytes(); - byte[] event = trusted.latestEventBytes(); - return new CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint( - trusted.issuerId(), - trusted.issuerAuthGeneration(), - checkpoint, - CanonicalGameplayIssuerMemberV2Codec.sha256(checkpoint), - event, - CanonicalGameplayIssuerMemberV2Codec.sha256(event)); + return CanonicalGameplayIssuerTestFixtures.checkpointShape(ISSUER, generation); } private static CanonicalGameplayIssuerMemberV2Value.Incarnation stableIncarnation(String seed) { - String digest = digest(seed.getBytes(StandardCharsets.UTF_8)); - var deployment = - new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( - "controlled-deployment-" + seed, - "deployment-generation-" + seed, - List.of("controlled-node-" + seed), - "controlled-redis-build-" + seed, - "controlled-lua-registry-" + seed, - digest, - "READY", - "boot-" + seed, - "startup-" + seed, - "storage-" + seed, - "aof-" + seed); - return new CanonicalGameplayIssuerMemberV2Value.Incarnation( - "controlled-attestor-" + seed, digest, deployment, digest, digest); + return CanonicalGameplayIssuerTestFixtures.stableIncarnation(seed); } private static CanonicalGameplayIssuerBindingLocalOperation.Request request( @@ -1171,91 +1109,17 @@ private static AccountGameplayAdmissionLeaseEvidence controlledLeaseEvidence( CanonicalGameplayBindingIdentity candidate, BigInteger bindingGeneration, CanonicalPlayableTarget target) { - long now = System.currentTimeMillis(); - String nowSeconds = Long.toString(now / 1000L); - Map carrier = new LinkedHashMap<>(); - carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); - carrier.put("schemaVersion", "1"); - carrier.put("mode", "PUBLIC_PRODUCTION"); - carrier.put("leaseKind", AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING.name()); - carrier.put("targetNamespace", target.targetNamespace()); - carrier.put( - "callerWorkload", - "spiffe://firemud/ns/" + target.targetNamespace() + "/sa/game-session-service"); - carrier.put("requestId", "10101010-1010-4010-8010-101010101010"); - carrier.put("leaseId", "20202020-2020-4020-8020-202020202020"); - carrier.put("leaseFence", "1"); - Map scope = new LinkedHashMap<>(); - scope.put("accountId", candidate.accountId().toString()); - scope.put("tenantId", candidate.tenantId().toString()); - scope.put("realmId", target.realmId().toString()); - scope.put("worldSlug", target.worldSlug()); - scope.put("realmSlug", target.realmSlug()); - scope.put("playableStateNamespaceId", target.playableStateNamespaceId().toString()); - scope.put("playableStateScope", target.playableStateScope()); - scope.put("gameInstanceId", target.canonicalGameInstanceId().toString()); - scope.put("characterId", candidate.characterId().toString()); - scope.put("sessionId", candidate.sessionId()); - scope.put("bindingGeneration", bindingGeneration.toString()); - scope.put("catalogRevision", Long.toString(target.catalogRevision())); - scope.put("pointerVersion", Long.toString(target.pointerVersion())); - scope.put("regionId", candidate.regionId().toString()); - scope.put("regionEpoch", candidate.regionEpoch().toString()); - carrier.put("bindingScope", scope); - Map authority = new LinkedHashMap<>(); - authority.put("issuerAuthGeneration", candidate.issuerAuthGeneration().toString()); - authority.put("accountAuthorityGeneration", "1"); - authority.put("tenantAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1")); - authority.put("membershipAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1")); - authority.put("privateRealmGrantVersions", List.of()); - carrier.put("authorityTuple", authority); - carrier.put("issuanceFence", "1"); - carrier.put( - "membershipBaseline", - new LinkedHashMap<>( - Map.of( - "membershipLifecycleState", - "ACTIVE", - "membershipVersion", - Map.of(candidate.tenantId().toString(), "1"), - "membershipAuthorityGeneration", - "1"))); - String prefix = "account:auth-authority:v1:"; - List> checkpoints = new java.util.ArrayList<>(); - for (String stream : - List.of( - "account/" + candidate.accountId(), - "issuer/" + ISSUER, - "membership/" + candidate.accountId() + "/" + candidate.tenantId(), - "tenant/" + candidate.tenantId())) { - checkpoints.add( - new LinkedHashMap<>( - Map.of( - "outboxStreamKey", - prefix + stream, - "outboxSequence", - stream.startsWith("membership/") || stream.startsWith("tenant/") ? "1" : "0"))); - } - carrier.put("outboxCheckpoints", checkpoints); - Map tokenIdentity = new LinkedHashMap<>(); - tokenIdentity.put("accountId", candidate.accountId().toString()); - tokenIdentity.put("operationId", "40404040-4040-4040-8040-404040404040"); - tokenIdentity.put("issuanceRequestId", "50505050-5050-4050-8050-505050505050"); - tokenIdentity.put("tokenJti", "60606060-6060-4060-8060-606060606060"); - tokenIdentity.put("tokenSHA256", "a".repeat(64)); - tokenIdentity.put("tokenProfile", "game-session-account-delegation"); - tokenIdentity.put("tokenGeneration", "1"); - tokenIdentity.put("issuanceFence", "1"); - tokenIdentity.put("tokenIdentityFence", "1"); - tokenIdentity.put("issuedAt", nowSeconds); - tokenIdentity.put("notBefore", nowSeconds); - tokenIdentity.put("expiresAt", Long.toString(now / 1000L + 60L)); - carrier.put("tokenIdentityEvidence", tokenIdentity); - carrier.put("evaluatedAt", Long.toString(now)); - carrier.put( - "expiresAt", - Long.toString(now + AccountGameplayAdmissionLeaseEvidence.MAX_DURATION_MILLIS)); - return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + return CanonicalGameplayIssuerTestFixtures.controlledLeaseEvidence( + candidate, + bindingGeneration, + target, + new CanonicalGameplayIssuerTestFixtures.ControlledLeaseEvidenceIdentity( + ISSUER, + UUID.fromString("10101010-1010-4010-8010-101010101010"), + UUID.fromString("20202020-2020-4020-8020-202020202020"), + UUID.fromString("40404040-4040-4040-8040-404040404040"), + UUID.fromString("50505050-5050-4050-8050-505050505050"), + UUID.fromString("60606060-6060-4060-8060-606060606060"))); } private void establishActualLegacyDisposition(DSLContext dsl) { @@ -1263,64 +1127,33 @@ private void establishActualLegacyDisposition(DSLContext dsl) { } private TestSchema newTestSchemaAtVersion(String prefix) { - String schema = prefix + UUID.randomUUID().toString().replace("-", ""); + 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("1030")) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, schema, MIGRATION_LOCATION, "1030"); return new TestSchema(schema, dataSource, DSL.using(dataSource, SQLDialect.POSTGRES)); } private static void migrateRemaining(TestSchema schema) { - Flyway.configure() - .dataSource(schema.dataSource()) - .schemas(schema.schema()) - .defaultSchema(schema.schema()) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + schema.dataSource(), schema.schema(), MIGRATION_LOCATION, null); } private DriverManagerDataSource dataSource(String schemaName) { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("org.postgresql.Driver"); - String jdbcUrl = POSTGRES.getJdbcUrl(); - dataSource.setUrl( - jdbcUrl + (jdbcUrl.contains("?") ? "&" : "?") + "currentSchema=" + schemaName); - dataSource.setUsername(POSTGRES.getUsername()); - dataSource.setPassword(POSTGRES.getPassword()); - return dataSource; + return CanonicalGameplayIssuerTestFixtures.dataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword(), schemaName); } private void dropSchema(String schemaName) { - try (Connection connection = dataSource("public").getConnection()) { - DSL.using(connection, SQLDialect.POSTGRES) - .execute("DROP SCHEMA IF EXISTS \"" + schemaName + "\" CASCADE"); - } catch (SQLException failure) { - throw new IllegalStateException( - "Could not drop the owned issuer local-operation test schema", failure); - } + CanonicalGameplayIssuerTestFixtures.dropSchema( + dataSource("public"), + schemaName, + "Could not drop the owned issuer local-operation test schema"); } private static RedisClient createRedisClient(String username, String password) { - RedisURI.Builder builder = RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(6379)); - if (username != null) builder.withAuthentication(username, password); - RedisURI uri = builder.build(); - uri.setTimeout(Duration.ofSeconds(5)); - RedisClient client = RedisClient.create(uri); - client.setOptions( - ClientOptions.builder() - .autoReconnect(false) - .protocolVersion(io.lettuce.core.protocol.ProtocolVersion.RESP2) - .build()); - return client; + return CanonicalGameplayIssuerTestFixtures.createRedisClient( + REDIS.getHost(), REDIS.getMappedPort(6379), username, password); } private static long count(DSLContext dsl, String table) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java index 372a50972a..0371943fd6 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java @@ -4,9 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import io.lettuce.core.AclSetuserArgs; -import io.lettuce.core.ClientOptions; import io.lettuce.core.RedisClient; -import io.lettuce.core.RedisURI; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.sync.RedisCommands; import io.lettuce.core.codec.ByteArrayCodec; @@ -17,8 +15,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.security.MessageDigest; -import java.sql.Connection; -import java.sql.SQLException; import java.time.Duration; import java.util.ArrayList; import java.util.Base64; @@ -27,15 +23,12 @@ import java.util.Map; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; -import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; 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; @@ -608,63 +601,22 @@ private CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState c private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor descriptor(BigInteger partitions, BigInteger capacity) { - String exact = - "issuer-layout-descriptor/v1|" - + ISSUER - + "|" - + LAYOUT_VERSION - + "|" - + partitions - + "|" - + capacity - + "|" - + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY; - return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor( - ISSUER, - LAYOUT_VERSION, - partitions, - capacity, - CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY, - exact.getBytes(StandardCharsets.UTF_8)); + return CanonicalGameplayIssuerTestFixtures.descriptor( + ISSUER, LAYOUT_VERSION, partitions, capacity); } private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint sourceCheckpoint(BigInteger generation) { - long sequence = generation.longValueExact() - 1; - var event = - AccountAuthoritySourceEventV1Codec.sealIssuer( - new AccountAuthoritySourceEventV1Codec.IssuerPreimage( - UUID.randomUUID().toString(), - UUID.randomUUID().toString(), - AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + ISSUER, - Long.toString(sequence), - ISSUER, - generation.toString(), - generation.toString(), - "ISSUER_SECURITY_CHANGE")); - byte[] bytes = event.canonicalJsonUtf8(); - return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint( - ISSUER, generation, bytes, bytes); + return CanonicalGameplayIssuerTestFixtures.sourceCheckpoint(ISSUER, generation); } private static CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint checkpointShape(BigInteger generation) { - var trusted = sourceCheckpoint(generation); - byte[] checkpoint = trusted.checkpointBytes(); - byte[] event = trusted.latestEventBytes(); - return new CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint( - trusted.issuerId(), - trusted.issuerAuthGeneration(), - checkpoint, - CanonicalGameplayIssuerMemberV2Codec.sha256(checkpoint), - event, - CanonicalGameplayIssuerMemberV2Codec.sha256(event)); + return CanonicalGameplayIssuerTestFixtures.checkpointShape(ISSUER, generation); } private static CanonicalGameplayIssuerMemberV2Value.Incarnation stableIncarnation(String seed) { - String digest = digest(seed.getBytes(StandardCharsets.UTF_8)); - return new CanonicalGameplayIssuerMemberV2Value.Incarnation( - "controlled-attestor-" + seed, digest, deploymentEvidence(seed, digest), digest, digest); + return CanonicalGameplayIssuerTestFixtures.stableIncarnation(seed); } private static CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation @@ -947,63 +899,31 @@ private void establishActualLegacyDisposition(DSLContext dsl) { } private TestSchema newTestSchemaAtVersion(String prefix, String version) { - String schema = prefix + UUID.randomUUID().toString().replace("-", ""); + 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(version)) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, schema, MIGRATION_LOCATION, version); return new TestSchema(schema, dataSource, DSL.using(dataSource, SQLDialect.POSTGRES)); } private static void migrateRemaining(TestSchema schema) { - Flyway.configure() - .dataSource(schema.dataSource()) - .schemas(schema.schema()) - .defaultSchema(schema.schema()) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + schema.dataSource(), schema.schema(), MIGRATION_LOCATION, null); } private DriverManagerDataSource dataSource(String schema) { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("org.postgresql.Driver"); - String jdbcUrl = POSTGRES.getJdbcUrl(); - dataSource.setUrl(jdbcUrl + (jdbcUrl.contains("?") ? "&" : "?") + "currentSchema=" + schema); - dataSource.setUsername(POSTGRES.getUsername()); - dataSource.setPassword(POSTGRES.getPassword()); - return dataSource; + return CanonicalGameplayIssuerTestFixtures.dataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword(), schema); } private void dropSchema(String schema) { - try (Connection connection = dataSource("public").getConnection()) { - DSL.using(connection, SQLDialect.POSTGRES) - .execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); - } catch (SQLException failure) { - throw new IllegalStateException( - "Could not drop the owned issuer coverage test schema", failure); - } + CanonicalGameplayIssuerTestFixtures.dropSchema( + dataSource("public"), schema, "Could not drop the owned issuer coverage test schema"); } private static RedisClient createRedisClient(String username, String password) { - RedisURI.Builder builder = RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(6379)); - if (username != null) builder.withAuthentication(username, password); - RedisURI uri = builder.build(); - uri.setTimeout(Duration.ofSeconds(5)); - RedisClient client = RedisClient.create(uri); - client.setOptions( - ClientOptions.builder() - .autoReconnect(false) - .protocolVersion(io.lettuce.core.protocol.ProtocolVersion.RESP2) - .build()); - return client; + return CanonicalGameplayIssuerTestFixtures.createRedisClient( + REDIS.getHost(), REDIS.getMappedPort(6379), username, password); } private static byte[] ascii(String value) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java index 6675c180aa..76f3eeb7b8 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java @@ -16,7 +16,6 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; @@ -25,8 +24,6 @@ import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; -import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.exception.DataAccessException; @@ -716,65 +713,17 @@ private static UUID sessionUuidForPartition( private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor descriptor(BigInteger version, BigInteger count, BigInteger capacity) { - String encoded = - "issuer-layout-descriptor/v1|" - + ISSUER - + "|" - + version - + "|" - + count - + "|" - + capacity - + "|" - + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY; - return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor( - ISSUER, - version, - count, - capacity, - CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY, - encoded.getBytes(StandardCharsets.UTF_8)); + return CanonicalGameplayIssuerTestFixtures.descriptor(ISSUER, version, count, capacity); } private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint sourceCheckpoint(BigInteger issuerGeneration) { - long sequence = issuerGeneration.longValueExact() - 1L; - var event = - AccountAuthoritySourceEventV1Codec.sealIssuer( - new AccountAuthoritySourceEventV1Codec.IssuerPreimage( - UUID.randomUUID().toString(), - UUID.randomUUID().toString(), - AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + ISSUER, - Long.toString(sequence), - ISSUER, - issuerGeneration.toString(), - issuerGeneration.toString(), - "ISSUER_SECURITY_CHANGE")); - byte[] eventBytes = event.canonicalJsonUtf8(); - return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint( - ISSUER, issuerGeneration, eventBytes, eventBytes); + return CanonicalGameplayIssuerTestFixtures.sourceCheckpoint(ISSUER, issuerGeneration); } private static CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation stableIncarnation(String seed) { - String digest = digest(seed); - return new CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation( - "controlled-attestor-" + seed, - digest, - new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( - "controlled-deployment-" + seed, - "deployment-generation-" + seed, - List.of("controlled-node-" + seed), - "controlled-redis-build-" + seed, - "controlled-lua-registry-" + seed, - digest, - "READY", - "boot-" + seed, - "startup-" + seed, - "storage-" + seed, - "aof-" + seed), - digest, - digest); + return CanonicalGameplayIssuerTestFixtures.trustedStableIncarnation(seed); } private static String digest(String text) { @@ -794,52 +743,25 @@ private static void establishActualLegacyDisposition(DSLContext dsl) { } private static void migrateThrough1031(TestSchema testSchema) { - Flyway.configure() - .dataSource(testSchema.dataSource()) - .schemas(testSchema.schema()) - .defaultSchema(testSchema.schema()) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .target(MigrationVersion.fromVersion("1031")) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + testSchema.dataSource(), testSchema.schema(), MIGRATION_LOCATION, "1031"); } private static void migrateThrough1032(TestSchema testSchema) { - Flyway.configure() - .dataSource(testSchema.dataSource()) - .schemas(testSchema.schema()) - .defaultSchema(testSchema.schema()) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .target(MigrationVersion.fromVersion("1032")) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + testSchema.dataSource(), testSchema.schema(), MIGRATION_LOCATION, "1032"); } private static void migrateRemaining(TestSchema testSchema) { - Flyway.configure() - .dataSource(testSchema.dataSource()) - .schemas(testSchema.schema()) - .defaultSchema(testSchema.schema()) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + testSchema.dataSource(), testSchema.schema(), MIGRATION_LOCATION, null); } private static TestSchema newTestSchemaAtVersion(String prefix, String version) { - String schema = prefix + UUID.randomUUID().toString().replace("-", ""); + String schema = CanonicalGameplayIssuerTestFixtures.schemaName(prefix); DriverManagerDataSource dataSource = dataSource(schema); - var configuration = - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION); - if (version != null) configuration.target(MigrationVersion.fromVersion(version)); - configuration.load().migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, schema, MIGRATION_LOCATION, version); return new TestSchema(schema, dataSource, DSL.using(dataSource, SQLDialect.POSTGRES)); } @@ -886,24 +808,13 @@ private static void assertNoIssuedRows(DSLContext dsl) { } private static DriverManagerDataSource dataSource(String schema) { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("org.postgresql.Driver"); - String jdbcUrl = postgres.getJdbcUrl(); - String separator = jdbcUrl.contains("?") ? "&" : "?"; - dataSource.setUrl(jdbcUrl + separator + "currentSchema=" + schema); - dataSource.setUsername(postgres.getUsername()); - dataSource.setPassword(postgres.getPassword()); - return dataSource; + return CanonicalGameplayIssuerTestFixtures.dataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword(), schema); } private static void dropSchema(String schema) { - try (var connection = dataSource("public").getConnection()) { - DSL.using(connection, SQLDialect.POSTGRES) - .execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); - } catch (Exception failure) { - throw new IllegalStateException( - "Could not drop the owned member-operation test schema", failure); - } + CanonicalGameplayIssuerTestFixtures.dropSchema( + dataSource("public"), schema, "Could not drop the owned member-operation test schema"); } private record Fixture( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java index 915b6f9542..6d10a68caa 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java @@ -4,9 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import io.lettuce.core.AclSetuserArgs; -import io.lettuce.core.ClientOptions; import io.lettuce.core.RedisClient; -import io.lettuce.core.RedisURI; import io.lettuce.core.ScriptOutputType; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.sync.RedisCommands; @@ -18,8 +16,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.security.MessageDigest; -import java.sql.Connection; -import java.sql.SQLException; import java.time.Duration; import java.util.ArrayList; import java.util.Base64; @@ -28,7 +24,6 @@ import java.util.Map; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; -import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; @@ -39,8 +34,6 @@ import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; 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.SQLDialect; import org.jooq.impl.DSL; @@ -669,43 +662,13 @@ private CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState c private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor descriptor() { - String bytes = - "issuer-layout-descriptor/v1|" - + ISSUER - + "|" - + LAYOUT_VERSION - + "|" - + PARTITION_COUNT - + "|" - + PARTITION_CAPACITY - + "|" - + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY; - return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor( - ISSUER, - LAYOUT_VERSION, - PARTITION_COUNT, - PARTITION_CAPACITY, - CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY, - bytes.getBytes(StandardCharsets.UTF_8)); + return CanonicalGameplayIssuerTestFixtures.descriptor( + ISSUER, LAYOUT_VERSION, PARTITION_COUNT, PARTITION_CAPACITY); } private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint sourceCheckpoint(BigInteger generation) { - long sequence = generation.longValueExact() - 1; - var event = - AccountAuthoritySourceEventV1Codec.sealIssuer( - new AccountAuthoritySourceEventV1Codec.IssuerPreimage( - UUID.randomUUID().toString(), - UUID.randomUUID().toString(), - AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + ISSUER, - Long.toString(sequence), - ISSUER, - generation.toString(), - generation.toString(), - "ISSUER_SECURITY_CHANGE")); - byte[] exactEvent = event.canonicalJsonUtf8(); - return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint( - ISSUER, generation, exactEvent, exactEvent); + return CanonicalGameplayIssuerTestFixtures.sourceCheckpoint(ISSUER, generation); } private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint @@ -729,13 +692,7 @@ private CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState c private static CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation stableIncarnation(String seed) { - String digest = digest(seed.getBytes(StandardCharsets.UTF_8)); - return new CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation( - "controlled-attestor-" + seed, - digest, - targetDeploymentEvidence(seed, digest), - digest, - digest); + return CanonicalGameplayIssuerTestFixtures.trustedStableIncarnation(seed); } private static CanonicalGameplayIssuerMemberV2Value.Incarnation changedIncarnation( @@ -1125,63 +1082,31 @@ private static void establishActualLegacyDisposition(DSLContext dsl) { } private TestSchema newTestSchemaAtVersion(String prefix, String version) { - String schema = prefix + UUID.randomUUID().toString().replace("-", ""); + 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(version)) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, schema, MIGRATION_LOCATION, version); return new TestSchema(schema, dataSource, DSL.using(dataSource, SQLDialect.POSTGRES)); } private static void migrateRemaining(TestSchema schema) { - Flyway.configure() - .dataSource(schema.dataSource()) - .schemas(schema.schema()) - .defaultSchema(schema.schema()) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + schema.dataSource(), schema.schema(), MIGRATION_LOCATION, null); } private DriverManagerDataSource dataSource(String schema) { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("org.postgresql.Driver"); - String jdbcUrl = POSTGRES.getJdbcUrl(); - dataSource.setUrl(jdbcUrl + (jdbcUrl.contains("?") ? "&" : "?") + "currentSchema=" + schema); - dataSource.setUsername(POSTGRES.getUsername()); - dataSource.setPassword(POSTGRES.getPassword()); - return dataSource; + return CanonicalGameplayIssuerTestFixtures.dataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword(), schema); } private void dropSchema(String schema) { - try (Connection connection = dataSource("public").getConnection()) { - DSL.using(connection, SQLDialect.POSTGRES) - .execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); - } catch (SQLException failure) { - throw new IllegalStateException( - "Could not drop the owned issuer physical test schema", failure); - } + CanonicalGameplayIssuerTestFixtures.dropSchema( + dataSource("public"), schema, "Could not drop the owned issuer physical test schema"); } private static RedisClient createRedisClient(String username, String password) { - RedisURI.Builder builder = RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(6379)); - if (username != null) builder.withAuthentication(username, password); - RedisURI uri = builder.build(); - uri.setTimeout(Duration.ofSeconds(5)); - RedisClient client = RedisClient.create(uri); - client.setOptions( - ClientOptions.builder() - .autoReconnect(false) - .protocolVersion(io.lettuce.core.protocol.ProtocolVersion.RESP2) - .build()); - return client; + return CanonicalGameplayIssuerTestFixtures.createRedisClient( + REDIS.getHost(), REDIS.getMappedPort(6379), username, password); } private static String digest(byte[] bytes) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java index 22ddf91539..ffd1e3cbcd 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java @@ -14,7 +14,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.sql.Connection; -import java.sql.SQLException; import java.time.Duration; import java.util.HexFormat; import java.util.LinkedHashMap; @@ -28,7 +27,6 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; -import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; @@ -41,7 +39,6 @@ import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution; import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -1349,89 +1346,8 @@ private static AccountGameplayAdmissionLeaseEvidence controlledLeaseEvidence( CanonicalGameplayBindingIdentity candidate, BigInteger bindingGeneration, CanonicalPlayableTarget target) { - long now = System.currentTimeMillis(); - String nowSeconds = Long.toString(now / 1000L); - Map carrier = new java.util.LinkedHashMap<>(); - carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); - carrier.put("schemaVersion", "1"); - carrier.put("mode", "PUBLIC_PRODUCTION"); - carrier.put("leaseKind", AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING.name()); - carrier.put("targetNamespace", target.targetNamespace()); - carrier.put( - "callerWorkload", - "spiffe://firemud/ns/" + target.targetNamespace() + "/sa/game-session-service"); - carrier.put("requestId", UUID.randomUUID().toString()); - carrier.put("leaseId", UUID.randomUUID().toString()); - carrier.put("leaseFence", "1"); - carrier.put( - "bindingScope", - Map.ofEntries( - Map.entry("accountId", candidate.accountId().toString()), - Map.entry("tenantId", candidate.tenantId().toString()), - Map.entry("realmId", target.realmId().toString()), - Map.entry("worldSlug", target.worldSlug()), - Map.entry("realmSlug", target.realmSlug()), - Map.entry("playableStateNamespaceId", target.playableStateNamespaceId().toString()), - Map.entry("playableStateScope", target.playableStateScope()), - Map.entry("gameInstanceId", target.canonicalGameInstanceId().toString()), - Map.entry("characterId", candidate.characterId().toString()), - Map.entry("sessionId", candidate.sessionId()), - Map.entry("bindingGeneration", bindingGeneration.toString()), - Map.entry("catalogRevision", Long.toString(target.catalogRevision())), - Map.entry("pointerVersion", Long.toString(target.pointerVersion())), - Map.entry("regionId", candidate.regionId().toString()), - Map.entry("regionEpoch", candidate.regionEpoch().toString()))); - carrier.put( - "authorityTuple", - Map.of( - "issuerAuthGeneration", candidate.issuerAuthGeneration().toString(), - "accountAuthorityGeneration", "1", - "tenantAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1"), - "membershipAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1"), - "privateRealmGrantVersions", List.of())); - carrier.put("issuanceFence", "1"); - carrier.put( - "membershipBaseline", - Map.of( - "membershipLifecycleState", "ACTIVE", - "membershipVersion", Map.of(candidate.tenantId().toString(), "1"), - "membershipAuthorityGeneration", "1")); - String prefix = "account:auth-authority:v1:"; - List> checkpoints = new java.util.ArrayList<>(); - for (String stream : - List.of( - "account/" + candidate.accountId(), - "issuer/" + candidate.issuerId(), - "membership/" + candidate.accountId() + "/" + candidate.tenantId(), - "tenant/" + candidate.tenantId())) { - checkpoints.add( - Map.of( - "outboxStreamKey", - prefix + stream, - "outboxSequence", - stream.startsWith("membership/") || stream.startsWith("tenant/") ? "1" : "0")); - } - carrier.put("outboxCheckpoints", checkpoints); - carrier.put( - "tokenIdentityEvidence", - Map.ofEntries( - Map.entry("accountId", candidate.accountId().toString()), - Map.entry("operationId", UUID.randomUUID().toString()), - Map.entry("issuanceRequestId", UUID.randomUUID().toString()), - Map.entry("tokenJti", UUID.randomUUID().toString()), - Map.entry("tokenSHA256", "a".repeat(64)), - Map.entry("tokenProfile", "game-session-account-delegation"), - Map.entry("tokenGeneration", "1"), - Map.entry("issuanceFence", "1"), - Map.entry("tokenIdentityFence", "1"), - Map.entry("issuedAt", nowSeconds), - Map.entry("notBefore", nowSeconds), - Map.entry("expiresAt", Long.toString(now / 1000L + 60L)))); - carrier.put("evaluatedAt", Long.toString(now)); - carrier.put( - "expiresAt", - Long.toString(now + AccountGameplayAdmissionLeaseEvidence.MAX_DURATION_MILLIS)); - return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + return CanonicalGameplayIssuerTestFixtures.controlledLeaseEvidence( + candidate, bindingGeneration, target); } private static Attempt attempt( @@ -1461,43 +1377,12 @@ private static Attempt attempt( private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor descriptor(BigInteger version, BigInteger count, BigInteger capacity) { - String encoded = - "issuer-layout-descriptor/v1|" - + ISSUER - + "|" - + version - + "|" - + count - + "|" - + capacity - + "|" - + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY; - return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor( - ISSUER, - version, - count, - capacity, - CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY, - encoded.getBytes(StandardCharsets.UTF_8)); + return CanonicalGameplayIssuerTestFixtures.descriptor(ISSUER, version, count, capacity); } private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint sourceCheckpoint(BigInteger issuerGeneration) { - long sequence = issuerGeneration.longValueExact() - 1L; - var event = - AccountAuthoritySourceEventV1Codec.sealIssuer( - new AccountAuthoritySourceEventV1Codec.IssuerPreimage( - UUID.randomUUID().toString(), - UUID.randomUUID().toString(), - AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + ISSUER, - Long.toString(sequence), - ISSUER, - issuerGeneration.toString(), - issuerGeneration.toString(), - "ISSUER_SECURITY_CHANGE")); - byte[] eventBytes = event.canonicalJsonUtf8(); - return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint( - ISSUER, issuerGeneration, eventBytes, eventBytes); + return CanonicalGameplayIssuerTestFixtures.sourceCheckpoint(ISSUER, issuerGeneration); } private static CanonicalGameplayBindingTransitionSnapshot prepareActualBinding( @@ -1603,38 +1488,20 @@ private static void establishActualLegacyDisposition(DSLContext dsl) { } private static TestSchema newTestSchema(String prefix) { - String schema = prefix + UUID.randomUUID().toString().replace("-", ""); + String schema = CanonicalGameplayIssuerTestFixtures.schemaName(prefix); 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); return new TestSchema(schema, dataSource, DSL.using(dataSource, SQLDialect.POSTGRES)); } private static DriverManagerDataSource dataSource(String schema) { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("org.postgresql.Driver"); - String jdbcUrl = postgres.getJdbcUrl(); - String separator = jdbcUrl.contains("?") ? "&" : "?"; - dataSource.setUrl(jdbcUrl + separator + "currentSchema=" + schema); - dataSource.setUsername(postgres.getUsername()); - dataSource.setPassword(postgres.getPassword()); - return dataSource; + return CanonicalGameplayIssuerTestFixtures.dataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword(), schema); } private static void dropSchema(String schema) { - try (Connection connection = dataSource("public").getConnection()) { - DSL.using(connection, SQLDialect.POSTGRES) - .execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); - } catch (SQLException failure) { - throw new IllegalStateException( - "Could not drop the owned issuer-bootstrap test schema", failure); - } + CanonicalGameplayIssuerTestFixtures.dropSchema( + dataSource("public"), schema, "Could not drop the owned issuer-bootstrap test schema"); } private static int countRows(DSLContext dsl, String tableName) { 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 83c8ed2811..66b8cd7366 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 @@ -7,17 +7,13 @@ import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.nio.file.Path; -import java.sql.Connection; -import java.sql.SQLException; import java.util.List; -import java.util.Map; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; -import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; @@ -1668,43 +1664,12 @@ private static LayoutFixture pendingLayoutFixture( private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor descriptor(BigInteger version, BigInteger count, BigInteger capacity) { - String encoded = - "issuer-layout-descriptor/v1|" - + ISSUER - + "|" - + version - + "|" - + count - + "|" - + capacity - + "|" - + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY; - return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor( - ISSUER, - version, - count, - capacity, - CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY, - encoded.getBytes(StandardCharsets.UTF_8)); + return CanonicalGameplayIssuerTestFixtures.descriptor(ISSUER, version, count, capacity); } private static CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint sourceCheckpoint(BigInteger issuerGeneration) { - long sequence = issuerGeneration.longValueExact() - 1L; - var event = - AccountAuthoritySourceEventV1Codec.sealIssuer( - new AccountAuthoritySourceEventV1Codec.IssuerPreimage( - UUID.randomUUID().toString(), - UUID.randomUUID().toString(), - AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + ISSUER, - Long.toString(sequence), - ISSUER, - issuerGeneration.toString(), - issuerGeneration.toString(), - "ISSUER_SECURITY_CHANGE")); - byte[] eventBytes = event.canonicalJsonUtf8(); - return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint( - ISSUER, issuerGeneration, eventBytes, eventBytes); + return CanonicalGameplayIssuerTestFixtures.sourceCheckpoint(ISSUER, issuerGeneration); } private static CanonicalGameplayAdmissionAbortSource createActualRetainedTerminalUnresolved( @@ -1763,89 +1728,8 @@ private static AccountGameplayAdmissionLeaseEvidence controlledLeaseEvidence( CanonicalGameplayBindingIdentity candidate, BigInteger bindingGeneration, CanonicalPlayableTarget target) { - long now = System.currentTimeMillis(); - String nowSeconds = Long.toString(now / 1000L); - Map carrier = new java.util.LinkedHashMap<>(); - carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); - carrier.put("schemaVersion", "1"); - carrier.put("mode", "PUBLIC_PRODUCTION"); - carrier.put("leaseKind", AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING.name()); - carrier.put("targetNamespace", target.targetNamespace()); - carrier.put( - "callerWorkload", - "spiffe://firemud/ns/" + target.targetNamespace() + "/sa/game-session-service"); - carrier.put("requestId", UUID.randomUUID().toString()); - carrier.put("leaseId", UUID.randomUUID().toString()); - carrier.put("leaseFence", "1"); - carrier.put( - "bindingScope", - Map.ofEntries( - Map.entry("accountId", candidate.accountId().toString()), - Map.entry("tenantId", candidate.tenantId().toString()), - Map.entry("realmId", target.realmId().toString()), - Map.entry("worldSlug", target.worldSlug()), - Map.entry("realmSlug", target.realmSlug()), - Map.entry("playableStateNamespaceId", target.playableStateNamespaceId().toString()), - Map.entry("playableStateScope", target.playableStateScope()), - Map.entry("gameInstanceId", target.canonicalGameInstanceId().toString()), - Map.entry("characterId", candidate.characterId().toString()), - Map.entry("sessionId", candidate.sessionId()), - Map.entry("bindingGeneration", bindingGeneration.toString()), - Map.entry("catalogRevision", Long.toString(target.catalogRevision())), - Map.entry("pointerVersion", Long.toString(target.pointerVersion())), - Map.entry("regionId", candidate.regionId().toString()), - Map.entry("regionEpoch", candidate.regionEpoch().toString()))); - carrier.put( - "authorityTuple", - Map.of( - "issuerAuthGeneration", candidate.issuerAuthGeneration().toString(), - "accountAuthorityGeneration", "1", - "tenantAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1"), - "membershipAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1"), - "privateRealmGrantVersions", List.of())); - carrier.put("issuanceFence", "1"); - carrier.put( - "membershipBaseline", - Map.of( - "membershipLifecycleState", "ACTIVE", - "membershipVersion", Map.of(candidate.tenantId().toString(), "1"), - "membershipAuthorityGeneration", "1")); - String prefix = "account:auth-authority:v1:"; - List> checkpoints = new java.util.ArrayList<>(); - for (String stream : - List.of( - "account/" + candidate.accountId(), - "issuer/" + candidate.issuerId(), - "membership/" + candidate.accountId() + "/" + candidate.tenantId(), - "tenant/" + candidate.tenantId())) { - checkpoints.add( - Map.of( - "outboxStreamKey", - prefix + stream, - "outboxSequence", - stream.startsWith("membership/") || stream.startsWith("tenant/") ? "1" : "0")); - } - carrier.put("outboxCheckpoints", checkpoints); - carrier.put( - "tokenIdentityEvidence", - Map.ofEntries( - Map.entry("accountId", candidate.accountId().toString()), - Map.entry("operationId", UUID.randomUUID().toString()), - Map.entry("issuanceRequestId", UUID.randomUUID().toString()), - Map.entry("tokenJti", UUID.randomUUID().toString()), - Map.entry("tokenSHA256", "a".repeat(64)), - Map.entry("tokenProfile", "game-session-account-delegation"), - Map.entry("tokenGeneration", "1"), - Map.entry("issuanceFence", "1"), - Map.entry("tokenIdentityFence", "1"), - Map.entry("issuedAt", nowSeconds), - Map.entry("notBefore", nowSeconds), - Map.entry("expiresAt", Long.toString(now / 1000L + 60L)))); - carrier.put("evaluatedAt", Long.toString(now)); - carrier.put( - "expiresAt", - Long.toString(now + AccountGameplayAdmissionLeaseEvidence.MAX_DURATION_MILLIS)); - return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + return CanonicalGameplayIssuerTestFixtures.controlledLeaseEvidence( + candidate, bindingGeneration, target); } private static CanonicalGameplayBindingTransitionSnapshot prepareActualBinding( @@ -2043,46 +1927,28 @@ private static void establishActualLegacyDisposition(DSLContext dsl) { } private static TestSchema newTestSchema(String prefix) { - return newTestSchemaAtVersion(prefix, null); + String schema = CanonicalGameplayIssuerTestFixtures.schemaName(prefix); + DriverManagerDataSource dataSource = dataSource(schema); + CanonicalGameplayIssuerTestFixtures.migrateSchema(dataSource, schema, MIGRATION_LOCATION, null); + return new TestSchema(schema, dataSource, DSL.using(dataSource, SQLDialect.POSTGRES)); } private static TestSchema newTestSchemaAtVersion(String prefix, String version) { - String schema = prefix + UUID.randomUUID().toString().replace("-", ""); + String schema = CanonicalGameplayIssuerTestFixtures.schemaName(prefix); DriverManagerDataSource dataSource = dataSource(schema); - var configuration = - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION); - if (version != null) configuration.target(MigrationVersion.fromVersion(version)); - configuration.load().migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, schema, MIGRATION_LOCATION, version); return new TestSchema(schema, dataSource, DSL.using(dataSource, SQLDialect.POSTGRES)); } private static void migrateThrough1031(TestSchema testSchema) { - Flyway.configure() - .dataSource(testSchema.dataSource()) - .schemas(testSchema.schema()) - .defaultSchema(testSchema.schema()) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .target(MigrationVersion.fromVersion("1031")) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + testSchema.dataSource(), testSchema.schema(), MIGRATION_LOCATION, "1031"); } private static void migrateThrough1032(TestSchema testSchema) { - Flyway.configure() - .dataSource(testSchema.dataSource()) - .schemas(testSchema.schema()) - .defaultSchema(testSchema.schema()) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .target(MigrationVersion.fromVersion("1032")) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + testSchema.dataSource(), testSchema.schema(), MIGRATION_LOCATION, "1032"); } private static void migrateThrough1037(TestSchema testSchema) { @@ -2110,18 +1976,12 @@ private static void migrateThrough1038(TestSchema testSchema) { } private static void migrateRemaining(TestSchema testSchema) { - Flyway.configure() - .dataSource(testSchema.dataSource()) - .schemas(testSchema.schema()) - .defaultSchema(testSchema.schema()) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + testSchema.dataSource(), testSchema.schema(), MIGRATION_LOCATION, null); } private static TestSchema newLegacyIssuerTestSchema(String prefix) { - String schema = prefix + UUID.randomUUID().toString().replace("-", ""); + String schema = CanonicalGameplayIssuerTestFixtures.schemaName(prefix); DriverManagerDataSource dataSource = dataSource(schema); Flyway.configure() .dataSource(dataSource) @@ -2301,14 +2161,8 @@ private static void insertLegacyReservationBeforeIssuerStringConversion(DSLConte } private static DriverManagerDataSource dataSource(String schema) { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("org.postgresql.Driver"); - String jdbcUrl = postgres.getJdbcUrl(); - String separator = jdbcUrl.contains("?") ? "&" : "?"; - dataSource.setUrl(jdbcUrl + separator + "currentSchema=" + schema); - dataSource.setUsername(postgres.getUsername()); - dataSource.setPassword(postgres.getPassword()); - return dataSource; + return CanonicalGameplayIssuerTestFixtures.dataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword(), schema); } private static List rowImages(DSLContext dsl, String tableName) { @@ -2363,12 +2217,8 @@ private static List migrationHistorySnapshot(DSLContext dsl) { } private static void dropSchema(String schema) { - try (Connection connection = dataSource("public").getConnection()) { - DSL.using(connection, SQLDialect.POSTGRES) - .execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); - } catch (SQLException failure) { - throw new IllegalStateException("Could not drop the owned issuer-build test schema", failure); - } + CanonicalGameplayIssuerTestFixtures.dropSchema( + dataSource("public"), schema, "Could not drop the owned issuer-build test schema"); } private record Fixture( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java index 505ac1730c..121cb98d5e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java @@ -1381,13 +1381,6 @@ private static CanonicalGameplayIssuerBindingLocalReleaseOperation completeRelea return fixture.completeIssuerRelease(resumed, recoveredReadback); } - private static CanonicalGameplayIssuerBindingLocalReleaseOperation completeRelease( - CanonicalGameplayAdmissionAbortCompositionFixture fixture, String seed) { - var pending = fixture.prepareIssuerRelease(seed); - var readback = fixture.projectIssuerRelease(pending); - return fixture.completeIssuerRelease(pending, readback); - } - private static String lifetimeSeed(int index) { return "lifetime-" + index; } 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 d960ed6c29..2691789cc0 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 @@ -2,20 +2,305 @@ import static org.assertj.core.api.Assertions.assertThat; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.sql.SQLException; +import java.time.Duration; import java.util.EnumSet; import java.util.List; +import java.util.Map; import java.util.UUID; +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; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventorySnapshot; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.springframework.jdbc.datasource.DriverManagerDataSource; /** Shared actual-owner fixtures for issuer bootstrap and ordinary NEW integration proof. */ final class CanonicalGameplayIssuerTestFixtures { private CanonicalGameplayIssuerTestFixtures() {} + static String schemaName(String prefix) { + return prefix + UUID.randomUUID().toString().replace("-", ""); + } + + static DriverManagerDataSource dataSource( + String jdbcUrl, String username, String password, String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + String separator = jdbcUrl.contains("?") ? "&" : "?"; + dataSource.setUrl(jdbcUrl + separator + "currentSchema=" + schema); + dataSource.setUsername(username); + dataSource.setPassword(password); + return dataSource; + } + + 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); + if (targetVersion != null) configuration.target(MigrationVersion.fromVersion(targetVersion)); + configuration.load().migrate(); + } + + static void dropSchema( + DriverManagerDataSource publicDataSource, String schema, String failureMessage) { + try (Connection connection = publicDataSource.getConnection()) { + DSL.using(connection, SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } catch (SQLException failure) { + throw new IllegalStateException(failureMessage, failure); + } + } + + static RedisClient createRedisClient(String host, int port, String username, String password) { + RedisURI.Builder builder = RedisURI.Builder.redis(host, port); + if (username != null) builder.withAuthentication(username, password); + RedisURI uri = builder.build(); + uri.setTimeout(Duration.ofSeconds(5)); + RedisClient client = RedisClient.create(uri); + client.setOptions( + ClientOptions.builder() + .autoReconnect(false) + .protocolVersion(io.lettuce.core.protocol.ProtocolVersion.RESP2) + .build()); + return client; + } + + static TrustedLayoutDescriptor descriptor( + String issuerId, BigInteger version, BigInteger partitionCount, BigInteger capacity) { + String exact = + "issuer-layout-descriptor/v1|" + + issuerId + + "|" + + version + + "|" + + partitionCount + + "|" + + capacity + + "|" + + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY; + return new TrustedLayoutDescriptor( + issuerId, + version, + partitionCount, + capacity, + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY, + exact.getBytes(StandardCharsets.UTF_8)); + } + + static TrustedAccountIssuerCheckpoint sourceCheckpoint(String issuerId, BigInteger generation) { + long sequence = generation.longValueExact() - 1L; + var event = + AccountAuthoritySourceEventV1Codec.sealIssuer( + new IssuerPreimage( + UUID.randomUUID().toString(), + UUID.randomUUID().toString(), + AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + issuerId, + Long.toString(sequence), + issuerId, + generation.toString(), + generation.toString(), + "ISSUER_SECURITY_CHANGE")); + byte[] exactEvent = event.canonicalJsonUtf8(); + return new TrustedAccountIssuerCheckpoint(issuerId, generation, exactEvent, exactEvent); + } + + static AccountIssuerSourceCheckpoint checkpointShape(String issuerId, BigInteger generation) { + var trusted = sourceCheckpoint(issuerId, generation); + byte[] checkpoint = trusted.checkpointBytes(); + byte[] event = trusted.latestEventBytes(); + return new AccountIssuerSourceCheckpoint( + trusted.issuerId(), + trusted.issuerAuthGeneration(), + checkpoint, + CanonicalGameplayIssuerMemberV2Codec.sha256(checkpoint), + event, + CanonicalGameplayIssuerMemberV2Codec.sha256(event)); + } + + static CanonicalGameplayIssuerMemberV2Value.Incarnation stableIncarnation(String seed) { + String digest = digest(seed.getBytes(StandardCharsets.UTF_8)); + var deployment = + new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "controlled-deployment-" + seed, + "deployment-generation-" + seed, + List.of("controlled-node-" + seed), + "controlled-redis-build-" + seed, + "controlled-lua-registry-" + seed, + digest, + "READY", + "boot-" + seed, + "startup-" + seed, + "storage-" + seed, + "aof-" + seed); + return new CanonicalGameplayIssuerMemberV2Value.Incarnation( + "controlled-attestor-" + seed, digest, deployment, digest, digest); + } + + static TrustedStableIncarnation trustedStableIncarnation(String seed) { + var incarnation = stableIncarnation(seed); + return new TrustedStableIncarnation( + incarnation.attestorBinding(), + incarnation.acceptedAttestationDigest(), + incarnation.targetDeploymentEvidence(), + incarnation.coordOpsRoAclDigest(), + incarnation.coordRedisConfigObservedDigest()); + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + static AccountGameplayAdmissionLeaseEvidence controlledLeaseEvidence( + CanonicalGameplayBindingIdentity candidate, + BigInteger bindingGeneration, + CanonicalPlayableTarget target) { + return controlledLeaseEvidence( + candidate, + bindingGeneration, + target, + new ControlledLeaseEvidenceIdentity( + candidate.issuerId(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID())); + } + + static AccountGameplayAdmissionLeaseEvidence controlledLeaseEvidence( + CanonicalGameplayBindingIdentity candidate, + BigInteger bindingGeneration, + CanonicalPlayableTarget target, + ControlledLeaseEvidenceIdentity identity) { + long now = System.currentTimeMillis(); + String nowSeconds = Long.toString(now / 1000L); + Map carrier = new java.util.LinkedHashMap<>(); + carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + carrier.put("schemaVersion", "1"); + carrier.put("mode", "PUBLIC_PRODUCTION"); + carrier.put("leaseKind", AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING.name()); + carrier.put("targetNamespace", target.targetNamespace()); + carrier.put( + "callerWorkload", + "spiffe://firemud/ns/" + target.targetNamespace() + "/sa/game-session-service"); + carrier.put("requestId", identity.requestId().toString()); + carrier.put("leaseId", identity.leaseId().toString()); + carrier.put("leaseFence", "1"); + carrier.put( + "bindingScope", + Map.ofEntries( + Map.entry("accountId", candidate.accountId().toString()), + Map.entry("tenantId", candidate.tenantId().toString()), + Map.entry("realmId", target.realmId().toString()), + Map.entry("worldSlug", target.worldSlug()), + Map.entry("realmSlug", target.realmSlug()), + Map.entry("playableStateNamespaceId", target.playableStateNamespaceId().toString()), + Map.entry("playableStateScope", target.playableStateScope()), + Map.entry("gameInstanceId", target.canonicalGameInstanceId().toString()), + Map.entry("characterId", candidate.characterId().toString()), + Map.entry("sessionId", candidate.sessionId()), + Map.entry("bindingGeneration", bindingGeneration.toString()), + Map.entry("catalogRevision", Long.toString(target.catalogRevision())), + Map.entry("pointerVersion", Long.toString(target.pointerVersion())), + Map.entry("regionId", candidate.regionId().toString()), + Map.entry("regionEpoch", candidate.regionEpoch().toString()))); + carrier.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", candidate.issuerAuthGeneration().toString(), + "accountAuthorityGeneration", "1", + "tenantAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1"), + "membershipAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1"), + "privateRealmGrantVersions", List.of())); + carrier.put("issuanceFence", "1"); + carrier.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", "ACTIVE", + "membershipVersion", Map.of(candidate.tenantId().toString(), "1"), + "membershipAuthorityGeneration", "1")); + String prefix = "account:auth-authority:v1:"; + List> checkpoints = new java.util.ArrayList<>(); + for (String stream : + List.of( + "account/" + candidate.accountId(), + "issuer/" + identity.issuerId(), + "membership/" + candidate.accountId() + "/" + candidate.tenantId(), + "tenant/" + candidate.tenantId())) { + checkpoints.add( + Map.of( + "outboxStreamKey", + prefix + stream, + "outboxSequence", + stream.startsWith("membership/") || stream.startsWith("tenant/") ? "1" : "0")); + } + carrier.put("outboxCheckpoints", checkpoints); + carrier.put( + "tokenIdentityEvidence", + Map.ofEntries( + Map.entry("accountId", candidate.accountId().toString()), + Map.entry("operationId", identity.operationId().toString()), + Map.entry("issuanceRequestId", identity.issuanceRequestId().toString()), + Map.entry("tokenJti", identity.tokenJti().toString()), + Map.entry("tokenSHA256", "a".repeat(64)), + Map.entry("tokenProfile", "game-session-account-delegation"), + Map.entry("tokenGeneration", "1"), + Map.entry("issuanceFence", "1"), + Map.entry("tokenIdentityFence", "1"), + Map.entry("issuedAt", nowSeconds), + Map.entry("notBefore", nowSeconds), + Map.entry("expiresAt", Long.toString(now / 1000L + 60L)))); + carrier.put("evaluatedAt", Long.toString(now)); + carrier.put( + "expiresAt", + Long.toString(now + AccountGameplayAdmissionLeaseEvidence.MAX_DURATION_MILLIS)); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + } + + record ControlledLeaseEvidenceIdentity( + String issuerId, + UUID requestId, + UUID leaseId, + UUID operationId, + UUID issuanceRequestId, + UUID tokenJti) {} + static void establishActualLegacyDisposition(DSLContext dsl) { var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); From 6b2d4b383fb18563ba1119c0c60be3f9343bb1f1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 14:48:53 +1300 Subject: [PATCH 32/34] Keep bounded issuer foundation separate from terminal retirement --- .../game-session-service/runtime-and-data.md | 2 +- design/project-management/ai-observations.md | 2 + .../player-access-and-session.md | 4 +- ...nitiveAbortCompositionIntegrationTest.java | 11 +- .../game-session-service/build.gradle.kts | 2 - ...IssuerBindingLocalRetirementOperation.java | 179 -- ...ingLocalRetirementOperationRepository.java | 976 ---------- ...ssuerBindingLocalRetirementRedisOwner.java | 362 ---- ...ocalRetirementRedisScriptContribution.java | 32 - ...ession-issuer-binding-local-retirement.lua | 272 --- ...ssion-issuer-binding-local-retirement.json | 35 - ...eplayAdmissionAbortCompositionFixture.java | 41 - ...lGameplayIssuerLifecycleProofFixtures.java | 610 ++++++ ...layIssuerLocalCapacityIntegrationTest.java | 486 +++++ ...suerPhysicalRetirementIntegrationTest.java | 1641 ----------------- 15 files changed, 1103 insertions(+), 3552 deletions(-) delete mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperation.java delete mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java delete mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.java delete mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution.java delete mode 100644 services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-retirement.lua delete mode 100644 services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-retirement.json create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLifecycleProofFixtures.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLocalCapacityIntegrationTest.java delete mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java 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 0b4932a1e3..f371a916ec 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,7 +10,7 @@ The service runtime model assumes replaceable workers, not authoritative in-proc The sections below define the target-state runtime contract. Current implementation and proof status is: -- **Local NEW issuer preparation:** the unregistered Game Session sources now manually compose the initial issuer anchor, ordinary post-baseline one-key member/capacity projection, issuer-local release, and original-operation terminal-capacity retirement, each with exact physical readback and controlled Account checkpoint and stable-incarnation collaborators. Ordinary ADD revalidates the target’s current Account authority, while terminal cleanup and non-target accounting preserve captured Account provenance. Completed-original bootstrap retries return retained installation evidence; current physical verification remains separate. The focused component proofs do not establish operational source or incarnation custody. A separate admitting issuer acknowledgement, issuer barrier/`OPEN`, final CAS, and admission remain absent. Operational source/incarnation custody, legacy recovery, production PKI, runtime registration, and activation remain open; see the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for proof attribution and limits. The [issuer anchor owner](../../system-architecture-redis.md#installed-issuer-anchor-for-ordinary-new) defines the physical contract. +- **Local NEW issuer preparation:** the unregistered Game Session sources now manually compose the initial issuer anchor, ordinary post-baseline one-key member/capacity projection and issuer-local release, each with exact physical readback and controlled Account checkpoint and stable-incarnation collaborators. Ordinary ADD revalidates the target’s current Account authority, while terminal cleanup and non-target accounting preserve captured Account provenance. Completed-original bootstrap retries return retained installation evidence; current physical verification remains separate. The bounded foundation does not execute physical retirement; retained storage and fail-closed accounting remain prerequisites for the separate settlement owner. The focused component proofs do not establish operational source or incarnation custody. A separate admitting issuer acknowledgement, issuer barrier/`OPEN`, final CAS, and admission remain absent. Operational source/incarnation custody, legacy recovery, production PKI, runtime registration, and activation remain open; see the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for proof attribution and limits. The [issuer anchor owner](../../system-architecture-redis.md#installed-issuer-anchor-for-ordinary-new) defines the physical contract. - **Local NEW account-member repair:** the unregistered owner prepares the original binding-local operation, performs one global account-member write and physical readback outside SQL, then accepts its exact acknowledgement in SQL. This supplies `ADD_OR_RETAIN` evidence only; the candidate remains provisional. Account-wide lifecycle writers, remaining index and region acknowledgements, and the guarded final admission CAS remain open. See [Session Behavior](../../system-architecture-session-behavior.md#global-account-active-binding-index) and [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components). diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index dcc46f77e4..1756238232 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -444,3 +444,5 @@ Entry format: - Reconsideration trigger: the original attempt is recovered and the exact parser/attribution cause and diagnostic behavior are verified. Gameplay reported the retained handles directly to FireController's owner; no database or runtime bypass was used. - Recovery: FireController identified six separately fingerprinted findings grouped into five comment containers. Parser fix `8f6e6121` recovered the same original attempt and all six exact findings; Gameplay verified the pinned head/base and finalized their native decisions. No trigger, allowance or controls changed. Full required controller CI was still pending at its owner's recovery handoff; native/race and packaged checks had passed. + +- `2026-10-29`: Malformed source-refresh IDs missing the `review_refresh_` prefix returned unrelated startup-binding advice. The original full receipt IDs recovered the existing observations without another fetch. FireController owner reports client-only fix `18cf3b4d` now identifies `refresh_id`, its required prefix/format and retained-receipt recovery; an existing MCP process keeps its prior binary until normal reconnection. Preserve exact full handles in delegation messages rather than abbreviating tool arguments. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index b3cfa16258..cc04528616 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for player access and session. Ca ### Canonical NEW admission components +The bounded issuer foundation in #3310 owns bootstrap, ordinary local projection and proof-backed release after a known first-NEW Account abort. The executable original-operation physical-retirement owner and its turnover proof belong with #2973 settlement. The foundation retains the V1038/V1038.4 storage and history guards required by ordinary projection; it retains terminal capacity and refuses fresh allocation at the existing 256-unretired-operation bound until the successor supplies physical retirement. This separates executable capability without weakening the canonical retirement contract or claiming unknown-decision orphan-cleanup delivery. Earlier combined proof below retains its original source attribution. + Ordinary NEW exact retry now reconstructs the original durable local issuer operation after legitimate provisional and Account-member progression. It retains the frozen reservation, member bytes, operation identity, fences, generation and local snapshot while requiring current eligible source revisions to remain at least the frozen revision and mutually coherent. Initial creation still requires exact current revision; current anchor, lineage, Account control, source/incarnation and lifecycle checks remain mandatory. R918 freshly passes all 17 selected cases (nine units and eight PostgreSQL/Redis cases), including reconstructed operation and projection owners after actual provisional publication, candidate-member presence and physical Account-member repair/acknowledgement. Independent Spring transaction-only and synchronization-only refusals are proved. The current `develop` dependency updates are reconciled locally; migration frontier, jOOQ generation, affected enabled static analysis, formatting and documentation checks pass. These are focused manually composed component results with controlled Account/source collaborators, not operational custody, default registration or public-admission qualification. The current local review corrections permit ordinary NEW only after proving the complete retained supersession chain ends at exact installed control. Forward V1038.4 retains prior partition heads and mutation receipts while separating their bootstrap lineages. Local physical projection batches source reads for its target partition, retains issuer-wide capacity/accounting checks on every snapshot, and fences target-partition changes independently of unrelated partition progress. R862 freshly passes all 20 selected PostgreSQL/Redis cases, including real retained-work supersession through installation and ordinary NEW, populated forward-migration retention, unrelated-partition progress and same-partition currentness refusal. Its aggregate fails two new test-only nullable-read warnings. R863 subsequently passes all 21 selected cases and the affected enabled main/integration static, migration-frontier, jOOQ generation, formatting and documentation checks after those warnings are corrected. This recovery also proves exact retained-abort retry comparison and ADD-mutation batch reads bounded to unretired local operations. The earlier failed R862 aggregate remains retained. Earlier results below retain their original source attribution. @@ -40,7 +42,7 @@ The manually composed first-NEW abort path now joins actual Account current-call R625 freshly passes the combined owner gate: 11 unit cases, 35 issuer PostgreSQL/Redis cases and seven actual Account–Game Session cases, with zero failures, errors or skips. Enabled affected Checkstyle, SpotBugs and formatting pass; R626 documentation checks pass. The new release case drives the actual Account abort and retained Game Session source through SQL release preparation, exact one-key Redis mutation and independent complete readback, then a fresh SQL completion. Another registered transition advances the real inventory clock between preparation and completion. Proof preserves the original operation, reservation and anchor bytes, rejects bare terminal flags and conflicting or newer physical members, replays a lost response without new identities, excludes only completed release capacity for subsequent ordinary NEW, and retains exact Account member history through issuer release and a physical post-abort runtime retirement. The [canonical issuer release owner](../../architecture/system-architecture-redis.md#binding-local-issuer-release-provenance) defines the separate preparation and completion revisions. This settles only the binding-local issuer obligation; it does not remove the Account member, settle region cleanup, acknowledge admitting issuer/region membership or make the candidate playable. Earlier failed R617–R624 attempts remain retained evidence. Descriptor, launch/World, current-source/incarnation and test-PKI collaborators remain controlled; operational authority and production activation are not established. -The expanded #3310 correction implements the [original-operation physical retirement contract](../../architecture/system-architecture-redis.md#original-operation-issuer-physical-retirement) under the existing release/local-mutation owner. R675 freshly passes 77 cases: 21 units, 49 Game Session PostgreSQL/Redis cases and seven actual Account–Game Session cases, with zero failures, errors or skips; enabled affected static analysis, formatting and 547-file documentation checks pass. Physical proof includes 257 actual Game Session releases and retirements with complete immutable SQL history, original lost-reply/restart recovery and completed retry, stale ADD and release rejection, pending same-partition exclusion, missing-revision and foreign/currentness refusal, preservation of newer fields, a 256-readable/257-refused current local-entry bound, and actual 514-field release/readback/persistence/reload. The wide case uses 250 owner-produced provisional bootstrap rows and a small post-baseline cohort; the turnover case retires each terminal field rather than accumulating 256 terminal fields. The physical mutation revision is a separate positively installed UUID domain, and historical unfenced bootstrap audit rows remain retained without qualifying current fenced coverage. The seven Account composition cases separately retain their real current-caller, lease, abort and issuer-release attribution. The new turnover cases use controlled upstream Account lease/abort, issuer checkpoint, launch/World and stable-incarnation inputs; they do not prove those producers or production authority. R672 remains a failed aggregate, including its oversized test-only history image, current-readback omission and retirement Lua shape failure; R677 separately passes the corrected 46-case preflight before R675. Operational custody, registration, admitting acknowledgements, barrier OPEN, final CAS and playable admission remain unproved. +The preserved combined issuer checkpoint implements the [original-operation physical retirement contract](../../architecture/system-architecture-redis.md#original-operation-issuer-physical-retirement) under the existing release/local-mutation owner; its executable retirement component is now assigned to #2973. On the original combined source, R675 passes 77 cases: 21 units, 49 Game Session PostgreSQL/Redis cases and seven actual Account–Game Session cases, with zero failures, errors or skips; enabled affected static analysis, formatting and 547-file documentation checks pass. Physical proof includes 257 actual Game Session releases and retirements with complete immutable SQL history, original lost-reply/restart recovery and completed retry, stale ADD and release rejection, pending same-partition exclusion, missing-revision and foreign/currentness refusal, preservation of newer fields, a 256-readable/257-refused current local-entry bound, and actual 514-field release/readback/persistence/reload. The wide case uses 250 owner-produced provisional bootstrap rows and a small post-baseline cohort; the turnover case retires each terminal field rather than accumulating 256 terminal fields. The physical mutation revision is a separate positively installed UUID domain, and historical unfenced bootstrap audit rows remain retained without qualifying current fenced coverage. The seven Account composition cases separately retain their real current-caller, lease, abort and issuer-release attribution. The new turnover cases use controlled upstream Account lease/abort, issuer checkpoint, launch/World and stable-incarnation inputs; they do not prove those producers or production authority. R672 remains a failed aggregate, including its oversized test-only history image, current-readback omission and retirement Lua shape failure; R677 separately passes the corrected 46-case preflight before R675. Operational custody, registration, admitting acknowledgements, barrier OPEN, final CAS and playable admission remain unproved. The preceding qualified correction separates immutable Account provenance from current ADD authority through the original abort, release and retirement readers, and makes the full completed-original bootstrap retry return its retained installation result without replaying baseline writes. Current target ADD guards, complete inventory accounting and mandatory physical-field checks remain required. Across R687, R688 and R689, that checkpoint qualifies 88 selected case methods: 26 units, 55 Game Session PostgreSQL/Redis cases and seven actual Account–Game Session cases. R687 remains a failed 88-case aggregate with 11 failures; R688 recovers those affected suites with 24 cases and one different Redis-startup failure, and R689 separately passes that unchanged negative case. The only source difference between R687 and R688 is test-layout isolation for two new cases; production postimages are identical. The physical suite again proves 257 actual releases and retirements, the 256/257 current-entry boundary and 514-field readback. New proof covers Account A advancing through the real acquisition-intent owner while unrelated Account B progresses, stale target ADD refusal, original cleanup and retirement, newer-field preservation, and unchanged SQL/proofs/Redis state through full bootstrap retries after NEW, release and retirement. That control case starts from captured `NO_ACTIVE_ACCOUNT_WIDE_FLOW`; it does not produce a new `HISTORICAL` control tuple. Enabled affected static analysis and formatting pass. Controlled upstream/source/incarnation inputs and all operational-custody, registration, admitting-acknowledgement, OPEN, final-CAS and activation limits remain unchanged. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java index 72da645ffc..282514015b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java @@ -657,7 +657,7 @@ void controlledHistoricalV1038AbortRowsAndHistorySurviveForwardCleanupMigration( } @Test - void actualAcknowledgedAbortCleanupSurvivesLaterAccountIntentAndRetiresExactIssuerMember() + void actualAcknowledgedAbortCleanupSurvivesLaterAccountIntentAndReleasesExactIssuerMember() throws Exception { try (var session = open(true)) { var acknowledgement = session.gs.repairAccountMember(); @@ -741,15 +741,6 @@ void actualAcknowledgedAbortCleanupSurvivesLaterAccountIntentAndRetiresExactIssu .completionInventoryRevision()) .isEqualTo(released.completionInventoryRevision()); - var pendingRetirement = session.gs.prepareIssuerRetirement(session.gs.transitionId()); - assertThat(session.gs.retireIssuerCapacityOutcome(pendingRetirement)).isEqualTo(1L); - assertThat(session.gs.hasExactOtherControllerMember(newerMemberSeed)).isTrue(); - byte[] fieldsBeforeRetirementRetry = session.gs.issuerPartitionFieldSetBytes(); - var retirementRetry = session.gs.prepareIssuerRetirement(session.gs.transitionId()); - assertThat(session.gs.isIssuerRetirementComplete(retirementRetry)).isTrue(); - assertThat(session.gs.retireIssuerCapacityOutcome(retirementRetry)).isEqualTo(2L); - assertThat(session.gs.issuerPartitionFieldSetBytes()) - .containsExactly(fieldsBeforeRetirementRetry); assertThat(session.gs.hasExactOtherControllerMember(newerMemberSeed)).isTrue(); assertThat(session.gs.hasExactAccountMember()).isTrue(); assertThat(session.gs.memberAcknowledgementImage()).isEqualTo(originalAck); diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index 983205a9ab..195c9e6711 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -184,8 +184,6 @@ val gameSessionClassesProofJar by tasks.registering(Jar::class) { include("redis/scripts/game-session-issuer-binding-local-add.json") include("redis/lua/game-session-issuer-binding-local-release.lua") include("redis/scripts/game-session-issuer-binding-local-release.json") - include("redis/lua/game-session-issuer-binding-local-retirement.lua") - include("redis/scripts/game-session-issuer-binding-local-retirement.json") } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperation.java deleted file mode 100644 index 52d2252b68..0000000000 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperation.java +++ /dev/null @@ -1,179 +0,0 @@ -package net.firedevops.firemud.gamesession.repository; - -import java.math.BigInteger; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; - -/** Exact SQL-issued physical removal of one terminal RELEASED capacity field. */ -final class CanonicalGameplayIssuerBindingLocalRetirementOperation { - enum Status { - PENDING_PHYSICAL_PROOF, - RETIRED - } - - private final CanonicalGameplayIssuerBindingLocalReleaseOperation release; - private final UUID operationId; - private final BigInteger partitionId; - private final UUID reservationId; - private final CanonicalGameplayIssuerPartitionMutation physicalMutation; - private final Status status; - private final byte[] exactAbsenceReadbackFieldSetBytes; - private final String exactAbsenceReadbackFieldSetDigest; - - CanonicalGameplayIssuerBindingLocalRetirementOperation( - CanonicalGameplayIssuerBindingLocalReleaseOperation release, - UUID operationId, - CanonicalGameplayIssuerPartitionMutation physicalMutation, - Status status, - byte[] exactAbsenceReadbackFieldSetBytes, - String exactAbsenceReadbackFieldSetDigest) { - this( - Objects.requireNonNull(release, "release"), - operationId, - release.releasedMemberValue().reservation().partitionId(), - release.releasedMemberValue().reservation().reservationId(), - physicalMutation, - status, - exactAbsenceReadbackFieldSetBytes, - exactAbsenceReadbackFieldSetDigest); - } - - private CanonicalGameplayIssuerBindingLocalRetirementOperation( - CanonicalGameplayIssuerBindingLocalReleaseOperation release, - UUID operationId, - BigInteger partitionId, - UUID reservationId, - CanonicalGameplayIssuerPartitionMutation physicalMutation, - Status status, - byte[] exactAbsenceReadbackFieldSetBytes, - String exactAbsenceReadbackFieldSetDigest) { - this.release = release; - this.operationId = requireNonNil(operationId, "operationId"); - this.partitionId = Objects.requireNonNull(partitionId, "partitionId"); - if (partitionId.signum() < 0) - throw new IllegalArgumentException("partitionId must be nonnegative"); - this.reservationId = requireNonNil(reservationId, "reservationId"); - this.physicalMutation = Objects.requireNonNull(physicalMutation, "physicalMutation"); - this.status = Objects.requireNonNull(status, "status"); - this.exactAbsenceReadbackFieldSetBytes = - exactAbsenceReadbackFieldSetBytes == null - ? null - : exactAbsenceReadbackFieldSetBytes.clone(); - this.exactAbsenceReadbackFieldSetDigest = exactAbsenceReadbackFieldSetDigest; - if (physicalMutation.kind() != CanonicalGameplayIssuerPartitionMutation.Kind.RETIRE - || !physicalMutation.ownerOperationId().equals(operationId) - || !physicalMutation.partitionId().equals(partitionId) - || (release == null && status != Status.RETIRED) - || (release != null - && (release.status() - != CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED - || !release.releasedMemberValue().reservation().partitionId().equals(partitionId) - || !release - .releasedMemberValue() - .reservation() - .reservationId() - .equals(reservationId))) - || (status == Status.PENDING_PHYSICAL_PROOF - && (physicalMutation.status() - != CanonicalGameplayIssuerPartitionMutation.Status.PENDING_PHYSICAL_PROOF - || exactAbsenceReadbackFieldSetBytes != null - || exactAbsenceReadbackFieldSetDigest != null)) - || (status == Status.RETIRED - && (physicalMutation.status() - != CanonicalGameplayIssuerPartitionMutation.Status.COMMITTED - || this.exactAbsenceReadbackFieldSetBytes == null - || this.exactAbsenceReadbackFieldSetBytes.length == 0 - || this.exactAbsenceReadbackFieldSetBytes.length > 17_825_792 - || exactAbsenceReadbackFieldSetDigest == null - || !exactAbsenceReadbackFieldSetDigest.equals( - CanonicalGameplayIssuerMemberV2Codec.sha256( - this.exactAbsenceReadbackFieldSetBytes)) - || !Arrays.equals( - physicalMutation.exactReadbackFieldSetBytes(), - this.exactAbsenceReadbackFieldSetBytes)))) { - throw new IllegalArgumentException( - "Retirement differs from its committed release or revision proof"); - } - Map fields = - status == Status.RETIRED - ? CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( - this.exactAbsenceReadbackFieldSetBytes) - : Map.of(); - String capacityField = - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField(reservationId); - byte[] revision = fields.get(CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD); - if (status == Status.RETIRED - && (fields.containsKey(capacityField) - || !Arrays.equals( - revision, - physicalMutation - .successorRevision() - .toString() - .getBytes(StandardCharsets.US_ASCII)))) { - throw new IllegalArgumentException( - "Retirement proof does not establish exact capacity absence"); - } - } - - static CanonicalGameplayIssuerBindingLocalRetirementOperation completedHistorical( - UUID operationId, - BigInteger partitionId, - UUID reservationId, - CanonicalGameplayIssuerPartitionMutation physicalMutation, - byte[] exactAbsenceReadbackFieldSetBytes, - String exactAbsenceReadbackFieldSetDigest) { - return new CanonicalGameplayIssuerBindingLocalRetirementOperation( - null, - operationId, - partitionId, - reservationId, - physicalMutation, - Status.RETIRED, - exactAbsenceReadbackFieldSetBytes, - exactAbsenceReadbackFieldSetDigest); - } - - CanonicalGameplayIssuerBindingLocalReleaseOperation release() { - return release; - } - - UUID operationId() { - return operationId; - } - - BigInteger partitionId() { - return partitionId; - } - - UUID reservationId() { - return reservationId; - } - - CanonicalGameplayIssuerPartitionMutation physicalMutation() { - return physicalMutation; - } - - Status status() { - return status; - } - - byte[] exactAbsenceReadbackFieldSetBytes() { - return exactAbsenceReadbackFieldSetBytes == null - ? null - : exactAbsenceReadbackFieldSetBytes.clone(); - } - - String exactAbsenceReadbackFieldSetDigest() { - return exactAbsenceReadbackFieldSetDigest; - } - - private static UUID requireNonNil(UUID value, String name) { - Objects.requireNonNull(value, name); - if (value.equals(new UUID(0L, 0L))) - throw new IllegalArgumentException(name + " must not be nil"); - return value; - } -} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java deleted file mode 100644 index 8a414f064b..0000000000 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java +++ /dev/null @@ -1,976 +0,0 @@ -package net.firedevops.firemud.gamesession.repository; - -import java.math.BigDecimal; -import java.math.BigInteger; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; -import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; -import org.jooq.DSLContext; -import org.jooq.Record; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -/** SQL owner for original-operation physical retirement after a committed issuer release. */ -final class CanonicalGameplayIssuerBindingLocalRetirementOperationRepository { - private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; - private static final String RETIREMENT = "game_session_canonical_issuer_binding_local_retirement"; - private static final String RELEASE = - "game_session_canonical_issuer_binding_local_release_operation"; - private static final String LOCAL_OPERATION = - "game_session_canonical_issuer_binding_local_operation"; - private static final String RESERVATION = "game_session_canonical_issuer_partition_reservation"; - private static final String INVENTORY = "game_session_canonical_gameplay_binding_inventory"; - private static final String ISSUER_OBLIGATION = - "game_session_canonical_binding_issuer_index_obligation"; - private static final String INVENTORY_CLOCK = "game_session_canonical_binding_inventory_clock"; - - private final DSLContext dsl; - private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource - currentIssuerStateSource; - private final CanonicalGameplayIssuerBindingLocalReleaseOperationRepository releaseRepository; - - CanonicalGameplayIssuerBindingLocalRetirementOperationRepository( - DSLContext dsl, - CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource - currentIssuerStateSource) { - this.dsl = Objects.requireNonNull(dsl, "dsl"); - this.currentIssuerStateSource = - Objects.requireNonNull(currentIssuerStateSource, "currentIssuerStateSource"); - this.releaseRepository = - new CanonicalGameplayIssuerBindingLocalReleaseOperationRepository( - dsl, currentIssuerStateSource); - } - - /** Creates or exactly resumes retirement only from the committed original release receipt. */ - CanonicalGameplayIssuerBindingLocalRetirementOperation prepareOrResume(UUID transitionId) { - Objects.requireNonNull(transitionId, "transitionId"); - requireNoAmbientTransaction(); - CanonicalGameplayIssuerBindingLocalRetirementOperation completed = - readCompletedRetirement(transitionId); - if (completed != null) return completed; - CanonicalGameplayIssuerBindingLocalReleaseOperation release = - releaseRepository.readCommittedRelease(transitionId); - var before = readCurrentIssuerState(); - requireSourceMatchesRelease(release.abortSource(), release); - CanonicalGameplayIssuerBindingLocalRetirementOperation prepared = - dsl.transactionResult( - configuration -> { - DSLContext transaction = org.jooq.impl.DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - CanonicalGameplayAdmissionAbortSource currentSource = - CanonicalGameplayBindingInventoryRepository - .readRetainedDefinitiveFirstNewAccountAbortSourceInTransaction( - transaction, transitionId, true); - requireSameReleaseSource(release.abortSource(), currentSource, release); - requireExactCommittedReleaseRow(transaction, release); - protectCurrentReferences(transaction, release); - BigInteger partitionId = release.releasedMemberValue().reservation().partitionId(); - Record existing = - transaction.fetchOne( - "SELECT * FROM " + RETIREMENT + " WHERE release_operation_id = ? FOR UPDATE", - release.operationId()); - if (existing != null) return readOperation(transaction, existing, release); - - CanonicalGameplayIssuerPartitionMutationRepository.PartitionMutationHead head = - CanonicalGameplayIssuerPartitionMutationRepository.readHeadInTransaction( - transaction, - release.originalOperation().anchor().bootstrapOperationId(), - partitionId); - if (head.pendingMutationId() != null) { - throw conflict("Another same-partition mutation is unresolved before retirement"); - } - UUID retirementId = freshNonNilUuid(); - byte[] intendedChange = encodeRetirementIntent(retirementId, release); - CanonicalGameplayIssuerPartitionMutation mutation = - CanonicalGameplayIssuerPartitionMutationRepository.prepareInTransaction( - transaction, - CanonicalGameplayIssuerPartitionMutation.Kind.RETIRE, - retirementId, - partitionId, - intendedChange); - insertRetirement(transaction, retirementId, release, mutation); - Record saved = - transaction.fetchOne( - "SELECT * FROM " - + RETIREMENT - + " WHERE retirement_operation_id = ? FOR UPDATE", - retirementId); - if (saved == null) - throw conflict("Pending issuer retirement intent was not retained"); - return readOperation(transaction, saved, release); - }); - requireSameCurrentIssuerState( - before, readCurrentIssuerState(), prepared.release().originalOperation().anchor()); - CanonicalGameplayIssuerBindingLocalReleaseOperation after = - releaseRepository.readCommittedRelease(transitionId); - requireSameReleaseOperation(release, after); - return prepared; - } - - /** Returns only immutable completed history; it does not depend on later mutable V29 rows. */ - private CanonicalGameplayIssuerBindingLocalRetirementOperation readCompletedRetirement( - UUID transitionId) { - requireNoAmbientTransaction(); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = org.jooq.impl.DSL.using(configuration); - Record retirement = - transaction.fetchOne( - "SELECT * FROM " - + RETIREMENT - + " WHERE issuer_id = ? AND transition_id = ? AND status = 'RETIRED'", - ISSUER, - transitionId); - if (retirement == null) return null; - return readCompletedRetirementInTransaction(transaction, retirement); - }); - } - - private static CanonicalGameplayIssuerBindingLocalRetirementOperation - readCompletedRetirementInTransaction(DSLContext transaction, Record retirement) { - UUID operationId = uuid(retirement, "retirement_operation_id"); - BigInteger partitionId = nonnegative(retirement, "partition_id"); - UUID reservationId = uuid(retirement, "reservation_id"); - UUID releaseId = uuid(retirement, "release_operation_id"); - UUID originalId = uuid(retirement, "original_local_operation_id"); - UUID transitionId = uuid(retirement, "transition_id"); - byte[] bindingRef = bytes(retirement, "binding_ref"); - byte[] originalBytes = bytes(retirement, "original_member_value_bytes"); - byte[] releasedBytes = bytes(retirement, "released_member_value_bytes"); - byte[] absenceBytes = bytes(retirement, "exact_absence_readback_field_set_bytes"); - String absenceDigest = text(retirement, "exact_absence_readback_field_set_digest"); - if (!ISSUER.equals(text(retirement, "issuer_id")) - || !text(retirement, "status").equals("RETIRED") - || !CanonicalGameplayIssuerMemberV2Codec.sha256(originalBytes) - .equals(text(retirement, "original_member_value_digest")) - || !CanonicalGameplayIssuerMemberV2Codec.sha256(releasedBytes) - .equals(text(retirement, "released_member_value_digest")) - || !CanonicalGameplayIssuerMemberV2Codec.sha256(absenceBytes).equals(absenceDigest)) { - throw conflict("Committed retirement history has a changed exact byte receipt"); - } - - CanonicalGameplayIssuerMemberV2Value originalMember; - CanonicalGameplayIssuerMemberV2Value releasedMember; - try { - originalMember = CanonicalGameplayIssuerMemberV2Codec.decode(originalBytes); - releasedMember = CanonicalGameplayIssuerMemberV2Codec.decode(releasedBytes); - } catch (RuntimeException malformed) { - throw conflict("Committed retirement release tuple is not canonical schema v2"); - } - Record release = - transaction.fetchOne("SELECT * FROM " + RELEASE + " WHERE operation_id = ?", releaseId); - Record original = - transaction.fetchOne( - "SELECT * FROM " + LOCAL_OPERATION + " WHERE operation_id = ?", originalId); - if (release == null - || original == null - || !ISSUER.equals(text(release, "issuer_id")) - || !"RELEASED".equals(text(release, "status")) - || !uuid(release, "original_local_operation_id").equals(originalId) - || !uuid(release, "transition_id").equals(transitionId) - || !uuid(release, "reservation_id").equals(reservationId) - || !nonnegative(release, "partition_id").equals(partitionId) - || !Arrays.equals(bytes(release, "binding_ref"), bindingRef) - || !uuid(release, "original_reservation_fence") - .equals(uuid(retirement, "original_reservation_fence")) - || !uuid(release, "original_issuer_coverage_operation_id") - .equals(uuid(retirement, "original_issuer_coverage_operation_id")) - || !positive(release, "original_issuer_coverage_operation_fence") - .equals(positive(retirement, "original_issuer_coverage_operation_fence")) - || !positive(release, "original_coverage_fence") - .equals(positive(retirement, "original_coverage_fence")) - || !positive(release, "original_inventory_snapshot_revision") - .equals(positive(retirement, "original_inventory_snapshot_revision")) - || !positive(release, "original_reservation_inventory_revision") - .equals(positive(retirement, "original_reservation_inventory_revision")) - || !uuid(release, "anchor_issuer_coverage_operation_id") - .equals(uuid(retirement, "anchor_issuer_coverage_operation_id")) - || !positive(release, "anchor_operation_fence") - .equals(positive(retirement, "anchor_operation_fence")) - || !positive(release, "anchor_coverage_fence") - .equals(positive(retirement, "anchor_coverage_fence")) - || !positive(release, "anchor_inventory_snapshot_revision") - .equals(positive(retirement, "anchor_inventory_snapshot_revision")) - || !Arrays.equals(bytes(release, "original_member_value_bytes"), originalBytes) - || !Arrays.equals(bytes(release, "released_member_value_bytes"), releasedBytes) - || !text(release, "original_member_value_digest") - .equals(CanonicalGameplayIssuerMemberV2Codec.sha256(originalBytes)) - || !text(release, "released_member_value_digest") - .equals(CanonicalGameplayIssuerMemberV2Codec.sha256(releasedBytes)) - || !positive(release, "source_inventory_revision") - .equals(positive(retirement, "release_source_inventory_revision")) - || !positive(release, "completion_inventory_revision") - .equals(positive(retirement, "release_completion_inventory_revision")) - || !text(release, "physical_readback_field_set_digest") - .equals( - CanonicalGameplayIssuerMemberV2Codec.sha256(readReleaseReceiptFieldSet(release))) - || !uuid(original, "operation_id").equals(originalId) - || !uuid(original, "reservation_id").equals(reservationId) - || !uuid(original, "transition_id").equals(transitionId) - || !Arrays.equals(bytes(original, "binding_ref"), bindingRef) - || !positive(original, "binding_generation").equals(originalMember.bindingGeneration()) - || !positive(original, "operation_fence") - .equals(originalMember.memberOperation().operationFence()) - || !positive(original, "local_member_generation") - .equals(originalMember.memberOperation().coverageGeneration()) - || !originalMember.memberOperation().operationId().equals(originalId) - || !originalMember.reservation().transitionId().equals(transitionId) - || !Arrays.equals(bytes(original, "member_value_bytes"), originalBytes) - || !text(original, "member_value_digest") - .equals(CanonicalGameplayIssuerMemberV2Codec.sha256(originalBytes))) { - throw conflict("Committed retirement no longer links to its exact immutable release source"); - } - CanonicalIssuerPartitionReservation originalReservation = originalMember.reservation(); - var originalAnchor = originalMember.anchor(); - BigInteger releaseSourceRevision = positive(retirement, "release_source_inventory_revision"); - CanonicalGameplayIssuerMemberV2Value expectedReleasedMember = - new CanonicalGameplayIssuerMemberV2Value( - originalMember.owner(), - originalMember.bindingGeneration(), - new CanonicalIssuerPartitionReservation( - originalReservation.reservationId(), - originalReservation.owner(), - originalReservation.bindingGeneration(), - originalReservation.transitionId(), - originalReservation.partitionId(), - CanonicalIssuerPartitionReservation.Lifecycle.RELEASED, - originalReservation.reservationFence(), - originalReservation.issuerCoverageOperationId(), - originalReservation.issuerCoverageOperationFence(), - originalReservation.coverageFence(), - originalReservation.inventorySnapshotRevision(), - releaseSourceRevision), - originalAnchor, - new CanonicalGameplayIssuerMemberV2Value.LocalMemberOperation( - releaseId, - positive(release, "release_operation_fence"), - positive(release, "release_local_member_generation")), - originalMember.issuerControlEpoch(), - originalMember.layoutDescriptor(), - originalMember.sourceCheckpoint(), - originalMember.incarnation()); - if (originalMember.reservation().lifecycle() - != CanonicalIssuerPartitionReservation.Lifecycle.RESERVED - || releasedMember.reservation().lifecycle() - != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED - || !originalReservation - .reservationFence() - .equals(uuid(retirement, "original_reservation_fence")) - || !originalReservation - .issuerCoverageOperationId() - .equals(uuid(retirement, "original_issuer_coverage_operation_id")) - || !originalReservation - .issuerCoverageOperationFence() - .equals(positive(retirement, "original_issuer_coverage_operation_fence")) - || !originalReservation - .coverageFence() - .equals(positive(retirement, "original_coverage_fence")) - || !originalReservation - .inventorySnapshotRevision() - .equals(positive(retirement, "original_inventory_snapshot_revision")) - || !originalReservation - .inventoryRevision() - .equals(positive(retirement, "original_reservation_inventory_revision")) - || !originalAnchor - .issuerCoverageOperationId() - .equals(uuid(retirement, "anchor_issuer_coverage_operation_id")) - || !originalAnchor.operationFence().equals(positive(retirement, "anchor_operation_fence")) - || !originalAnchor.coverageFence().equals(positive(retirement, "anchor_coverage_fence")) - || !originalAnchor - .issuerInventorySnapshotRevision() - .equals(positive(retirement, "anchor_inventory_snapshot_revision")) - || !originalMember.reservation().reservationId().equals(reservationId) - || !releasedMember.reservation().reservationId().equals(reservationId) - || !releasedMember.reservation().partitionId().equals(partitionId) - || !Arrays.equals(releasedMember.owner().bindingRef().bytes(), bindingRef) - || !releasedMember.memberOperation().operationId().equals(releaseId) - || !releasedMember.equals(expectedReleasedMember) - || !Arrays.equals( - releasedBytes, CanonicalGameplayIssuerMemberV2Codec.encode(expectedReleasedMember))) { - throw conflict("Committed retirement does not retain the original RELEASED member value"); - } - - byte[] expectedRetirementIntent = - CanonicalGameplayIssuerPartitionMutationRepository.encodeIntendedChange( - CanonicalGameplayIssuerPartitionMutation.Kind.RETIRE, - operationId, - partitionId, - releaseId.toString().getBytes(StandardCharsets.US_ASCII), - originalId.toString().getBytes(StandardCharsets.US_ASCII), - transitionId.toString().getBytes(StandardCharsets.US_ASCII), - reservationId.toString().getBytes(StandardCharsets.US_ASCII), - bindingRef, - releaseSourceRevision.toString().getBytes(StandardCharsets.US_ASCII), - positive(retirement, "release_completion_inventory_revision") - .toString() - .getBytes(StandardCharsets.US_ASCII), - originalBytes, - releasedBytes); - if (!Arrays.equals(expectedRetirementIntent, bytes(retirement, "exact_intended_change_bytes")) - || !text(retirement, "exact_intended_change_digest") - .equals(CanonicalGameplayIssuerMemberV2Codec.sha256(expectedRetirementIntent))) { - throw conflict("Committed retirement intent differs from its exact immutable release tuple"); - } - - CanonicalGameplayIssuerPartitionMutation releaseMutation = - CanonicalGameplayIssuerPartitionMutationRepository.readInTransaction( - transaction, - CanonicalGameplayIssuerPartitionMutation.Kind.RELEASE, - releaseId, - partitionId); - byte[] releaseReadback = readReleaseReceiptFieldSet(release); - byte[] releaseMutationIntent = - CanonicalGameplayIssuerPartitionMutationRepository.encodeIntendedChange( - CanonicalGameplayIssuerPartitionMutation.Kind.RELEASE, - releaseId, - partitionId, - originalId.toString().getBytes(StandardCharsets.US_ASCII), - reservationId.toString().getBytes(StandardCharsets.US_ASCII), - bindingRef, - originalBytes, - releasedBytes, - positive(retirement, "release_source_inventory_revision") - .toString() - .getBytes(StandardCharsets.US_ASCII)); - if (releaseMutation.status() != CanonicalGameplayIssuerPartitionMutation.Status.COMMITTED - || !Arrays.equals(releaseMutation.exactIntendedChangeBytes(), releaseMutationIntent) - || !Arrays.equals(releaseMutation.exactReadbackFieldSetBytes(), releaseReadback)) { - throw conflict("Committed retirement lost its original physical release proof"); - } - Map releaseFields = - CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet(releaseReadback); - String releasedCapacityField = - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField(reservationId); - String releasedBindingField = new String(bindingRef, StandardCharsets.UTF_8); - if (!Arrays.equals( - releaseFields.get(CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD), - releaseMutation.successorRevision().toString().getBytes(StandardCharsets.US_ASCII)) - || !Arrays.equals(releaseFields.get(releasedCapacityField), releasedBytes) - || releaseFields.containsKey(releasedBindingField)) { - throw conflict("Original committed release receipt lacks its exact RELEASED physical proof"); - } - - CanonicalGameplayIssuerPartitionMutation mutation = - CanonicalGameplayIssuerPartitionMutationRepository.readInTransaction( - transaction, - CanonicalGameplayIssuerPartitionMutation.Kind.RETIRE, - operationId, - partitionId); - if (mutation.status() != CanonicalGameplayIssuerPartitionMutation.Status.COMMITTED - || !uuid(retirement, "physical_mutation_id").equals(mutation.mutationId()) - || !mutation.expectedRevision().equals(uuid(retirement, "expected_revision")) - || !mutation.successorRevision().equals(uuid(retirement, "successor_revision")) - || !Arrays.equals( - mutation.exactIntendedChangeBytes(), bytes(retirement, "exact_intended_change_bytes")) - || !mutation - .exactIntendedChangeDigest() - .equals(text(retirement, "exact_intended_change_digest")) - || !Arrays.equals(mutation.exactReadbackFieldSetBytes(), absenceBytes)) { - throw conflict("Committed retirement lacks its exact successor-fence and absence proof"); - } - Map fields = - CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet(absenceBytes); - String targetCapacityField = - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField(reservationId); - byte[] revision = fields.get(CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD); - if (fields.containsKey(targetCapacityField) - || !Arrays.equals( - revision, - mutation.successorRevision().toString().getBytes(StandardCharsets.US_ASCII))) { - throw conflict("Committed retirement receipt does not prove exact field absence and fence"); - } - return CanonicalGameplayIssuerBindingLocalRetirementOperation.completedHistorical( - operationId, partitionId, reservationId, mutation, absenceBytes, absenceDigest); - } - - private static byte[] readReleaseReceiptFieldSet(Record release) { - return bytes(release, "physical_readback_field_set_bytes"); - } - - /** Commits exact absence and fence evidence with its physical-mutation receipt. */ - CanonicalGameplayIssuerBindingLocalRetirementOperation completeWithReadback( - CanonicalGameplayIssuerBindingLocalRetirementOperation expected, - CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.Readback readback) { - Objects.requireNonNull(expected, "expected"); - Objects.requireNonNull(readback, "readback"); - requireNoAmbientTransaction(); - if (!expected.operationId().equals(readback.operationId())) { - throw conflict("Issuer retirement readback belongs to a different original operation"); - } - byte[] exactBytes = readback.exactAbsenceReadbackFieldSetBytes(); - String exactDigest = CanonicalGameplayIssuerMemberV2Codec.sha256(exactBytes); - verifyExactAbsence(expected, exactBytes, exactDigest); - if (expected.status() - == CanonicalGameplayIssuerBindingLocalRetirementOperation.Status.RETIRED) { - if (!Arrays.equals(expected.exactAbsenceReadbackFieldSetBytes(), exactBytes)) { - throw conflict("Completed issuer retirement retry changed its original absence readback"); - } - return expected; - } - if (expected.release() == null) { - throw conflict("Pending issuer retirement lacks its current-source release context"); - } - var before = readCurrentIssuerState(); - CanonicalGameplayIssuerBindingLocalRetirementOperation completed = - dsl.transactionResult( - configuration -> { - DSLContext transaction = org.jooq.impl.DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - CanonicalGameplayIssuerBindingLocalReleaseOperation release = expected.release(); - CanonicalGameplayAdmissionAbortSource source = - CanonicalGameplayBindingInventoryRepository - .readRetainedDefinitiveFirstNewAccountAbortSourceInTransaction( - transaction, release.abortSource().transition().transitionId(), true); - requireSameReleaseSource(release.abortSource(), source, release); - requireExactCommittedReleaseRow(transaction, release); - protectCurrentReferences(transaction, release); - Record row = - transaction.fetchOne( - "SELECT * FROM " - + RETIREMENT - + " WHERE retirement_operation_id = ? FOR UPDATE", - expected.operationId()); - if (row == null) throw conflict("Pending issuer retirement disappeared"); - CanonicalGameplayIssuerBindingLocalRetirementOperation current = - readOperation(transaction, row, release); - requireSameRetirement(expected, current); - if (current.status() - == CanonicalGameplayIssuerBindingLocalRetirementOperation.Status.RETIRED) { - verifyExactAbsence(current, exactBytes, exactDigest); - CanonicalGameplayIssuerPartitionMutationRepository.completeInTransaction( - transaction, current.physicalMutation(), exactBytes); - return current; - } - CanonicalGameplayIssuerPartitionMutationRepository.completeInTransaction( - transaction, current.physicalMutation(), exactBytes); - int updated = - transaction.execute( - "UPDATE " - + RETIREMENT - + " SET status = 'RETIRED', exact_absence_readback_field_set_bytes = ?" - + ", exact_absence_readback_field_set_digest = ?, completed_at = CURRENT_TIMESTAMP" - + " WHERE retirement_operation_id = ? AND status = 'PENDING_PHYSICAL_PROOF'" - + " AND physical_mutation_id = ? AND expected_revision = ? AND successor_revision = ?", - exactBytes, - exactDigest, - current.operationId(), - current.physicalMutation().mutationId(), - current.physicalMutation().expectedRevision(), - current.physicalMutation().successorRevision()); - if (updated != 1) throw conflict("Issuer retirement proof compare-and-set refused"); - Record saved = - transaction.fetchOne( - "SELECT * FROM " + RETIREMENT + " WHERE retirement_operation_id = ?", - current.operationId()); - if (saved == null) throw conflict("Committed issuer retirement proof is unreadable"); - return readOperation(transaction, saved, release); - }); - requireSameCurrentIssuerState( - before, readCurrentIssuerState(), completed.release().originalOperation().anchor()); - return completed; - } - - private static void protectCurrentReferences( - DSLContext transaction, CanonicalGameplayIssuerBindingLocalReleaseOperation release) { - var original = release.originalOperation(); - byte[] bindingRef = release.releasedMemberValue().owner().bindingRef().bytes(); - UUID reservationId = release.releasedMemberValue().reservation().reservationId(); - UUID operationId = original.operationId(); - if (count( - transaction, - "SELECT COUNT(*) FROM " - + LOCAL_OPERATION - + " operation WHERE operation.issuer_id = ?" - + " AND operation.binding_ref = ? AND operation.operation_id <> ?" - + " AND NOT EXISTS (SELECT 1 FROM " - + RETIREMENT - + " retired" - + " WHERE retired.original_local_operation_id = operation.operation_id" - + " AND retired.status = 'RETIRED')", - ISSUER, - bindingRef, - operationId) - != 0 - || count( - transaction, - "SELECT COUNT(*) FROM " - + RESERVATION - + " reservation WHERE reservation.issuer_id = ?" - + " AND reservation.binding_ref = ? AND reservation.reservation_id <> ?" - + " AND NOT EXISTS (SELECT 1 FROM " - + RETIREMENT - + " retired" - + " WHERE retired.reservation_id = reservation.reservation_id" - + " AND retired.status = 'RETIRED')", - ISSUER, - bindingRef, - reservationId) - != 0) { - throw conflict("A newer or conflicting SQL issuer reference protects this local member"); - } - Record reservation = - transaction.fetchOne( - "SELECT * FROM " + RESERVATION + " WHERE reservation_id = ? FOR UPDATE", reservationId); - Record candidate = - transaction.fetchOne( - "SELECT * FROM " + INVENTORY + " WHERE binding_ref = ? FOR UPDATE", bindingRef); - Record obligation = - transaction.fetchOne( - "SELECT * FROM " - + ISSUER_OBLIGATION - + " WHERE transition_id = ? AND binding_ref = ? FOR UPDATE", - release.abortSource().transition().transitionId(), - bindingRef); - if (reservation == null - || !"RELEASED".equals(text(reservation, "lifecycle")) - || !number(reservation, "inventory_revision").equals(release.completionInventoryRevision()) - || candidate == null - || !"TERMINAL_UNRESOLVED".equals(text(candidate, "lifecycle")) - || !number(candidate, "inventory_revision").equals(release.completionInventoryRevision()) - || !uuid(candidate, "transition_id") - .equals(release.abortSource().transition().transitionId()) - || obligation == null - || !"RELEASED".equals(text(obligation, "status")) - || !uuid(obligation, "local_release_operation_id").equals(release.operationId()) - || !number(obligation, "inventory_revision") - .equals(release.completionInventoryRevision())) { - throw conflict("Current SQL issuer references no longer match the committed release"); - } - } - - private static void requireExactCommittedReleaseRow( - DSLContext transaction, CanonicalGameplayIssuerBindingLocalReleaseOperation release) { - Record row = - transaction.fetchOne( - "SELECT * FROM " + RELEASE + " WHERE operation_id = ? FOR UPDATE", - release.operationId()); - if (row == null - || !ISSUER.equals(text(row, "issuer_id")) - || !"RELEASED".equals(text(row, "status")) - || !uuid(row, "original_local_operation_id").equals(release.originalOperationId()) - || !positive(row, "source_inventory_revision").equals(release.sourceInventoryRevision()) - || !positive(row, "completion_inventory_revision") - .equals(release.completionInventoryRevision()) - || !Arrays.equals( - bytes(row, "original_member_value_bytes"), release.exactOriginalMemberValueBytes()) - || !Arrays.equals( - bytes(row, "released_member_value_bytes"), release.exactReleasedMemberValueBytes()) - || !text(row, "physical_readback_field_set_digest").equals(release.physicalReadbackDigest()) - || !Arrays.equals( - bytes(row, "physical_readback_field_set_bytes"), - release.exactPhysicalReadbackFieldSetBytes())) { - throw conflict("The original committed release receipt changed before retirement"); - } - } - - private static CanonicalGameplayIssuerBindingLocalRetirementOperation readOperation( - DSLContext transaction, - Record row, - CanonicalGameplayIssuerBindingLocalReleaseOperation release) { - UUID operationId = uuid(row, "retirement_operation_id"); - UUID mutationId = uuid(row, "physical_mutation_id"); - CanonicalGameplayIssuerPartitionMutation mutation = - CanonicalGameplayIssuerPartitionMutationRepository.readInTransaction( - transaction, - CanonicalGameplayIssuerPartitionMutation.Kind.RETIRE, - operationId, - release.releasedMemberValue().reservation().partitionId()); - CanonicalGameplayIssuerPartitionMutationRepository.PartitionMutationHead head = - CanonicalGameplayIssuerPartitionMutationRepository.readHeadInTransaction( - transaction, - release.originalOperation().anchor().bootstrapOperationId(), - release.releasedMemberValue().reservation().partitionId()); - if ((mutation.status() == CanonicalGameplayIssuerPartitionMutation.Status.PENDING_PHYSICAL_PROOF - && (!mutation.mutationId().equals(head.pendingMutationId()) - || !mutation.expectedRevision().equals(head.currentRevision()))) - || (mutation.status() == CanonicalGameplayIssuerPartitionMutation.Status.COMMITTED - && mutation.mutationId().equals(head.pendingMutationId()))) { - throw conflict("Original retirement does not match its current partition-head custody"); - } - byte[] intended = encodeRetirementIntent(operationId, release); - var original = release.originalOperation(); - var reservation = original.reservation(); - var anchor = original.anchor(); - if (!mutationId.equals(mutation.mutationId()) - || !Arrays.equals(intended, mutation.exactIntendedChangeBytes()) - || !ISSUER.equals(text(row, "issuer_id")) - || !nonnegative(row, "partition_id") - .equals(release.releasedMemberValue().reservation().partitionId()) - || !uuid(row, "release_operation_id").equals(release.operationId()) - || !uuid(row, "original_local_operation_id").equals(release.originalOperationId()) - || !uuid(row, "transition_id").equals(release.abortSource().transition().transitionId()) - || !uuid(row, "reservation_id") - .equals(release.releasedMemberValue().reservation().reservationId()) - || !Arrays.equals( - bytes(row, "binding_ref"), release.releasedMemberValue().owner().bindingRef().bytes()) - || !uuid(row, "original_reservation_fence").equals(reservation.reservationFence()) - || !uuid(row, "original_issuer_coverage_operation_id") - .equals(reservation.issuerCoverageOperationId()) - || !positive(row, "original_issuer_coverage_operation_fence") - .equals(reservation.issuerCoverageOperationFence()) - || !positive(row, "original_coverage_fence").equals(reservation.coverageFence()) - || !positive(row, "original_inventory_snapshot_revision") - .equals(reservation.inventorySnapshotRevision()) - || !positive(row, "original_reservation_inventory_revision") - .equals(reservation.inventoryRevision()) - || !uuid(row, "anchor_issuer_coverage_operation_id") - .equals(anchor.issuerCoverageOperationId()) - || !positive(row, "anchor_operation_fence").equals(anchor.operationFence()) - || !positive(row, "anchor_coverage_fence").equals(anchor.coverageFence()) - || !positive(row, "anchor_inventory_snapshot_revision") - .equals(anchor.issuerInventorySnapshotRevision()) - || !positive(row, "release_source_inventory_revision") - .equals(release.sourceInventoryRevision()) - || !positive(row, "release_completion_inventory_revision") - .equals(release.completionInventoryRevision()) - || !Arrays.equals( - bytes(row, "original_member_value_bytes"), release.exactOriginalMemberValueBytes()) - || !Arrays.equals( - bytes(row, "released_member_value_bytes"), release.exactReleasedMemberValueBytes()) - || !text(row, "original_member_value_digest") - .equals( - CanonicalGameplayIssuerMemberV2Codec.sha256( - release.exactOriginalMemberValueBytes())) - || !text(row, "released_member_value_digest") - .equals( - CanonicalGameplayIssuerMemberV2Codec.sha256( - release.exactReleasedMemberValueBytes())) - || !uuid(row, "expected_revision").equals(mutation.expectedRevision()) - || !uuid(row, "successor_revision").equals(mutation.successorRevision())) { - throw conflict("Stored issuer retirement differs from the exact release or revision tuple"); - } - CanonicalGameplayIssuerBindingLocalRetirementOperation.Status status; - try { - status = - CanonicalGameplayIssuerBindingLocalRetirementOperation.Status.valueOf( - text(row, "status")); - } catch (RuntimeException malformed) { - throw conflict("Stored issuer retirement status is malformed"); - } - byte[] absence = optionalBytes(row, "exact_absence_readback_field_set_bytes"); - String digest = row.get("exact_absence_readback_field_set_digest", String.class); - if ((status - == CanonicalGameplayIssuerBindingLocalRetirementOperation.Status - .PENDING_PHYSICAL_PROOF - && (absence != null || digest != null || row.get("completed_at") != null)) - || (status == CanonicalGameplayIssuerBindingLocalRetirementOperation.Status.RETIRED - && (absence == null - || digest == null - || !digest.equals(CanonicalGameplayIssuerMemberV2Codec.sha256(absence)) - || row.get("completed_at") == null))) { - throw conflict("Stored issuer retirement lacks its exact bounded absence phase"); - } - try { - return new CanonicalGameplayIssuerBindingLocalRetirementOperation( - release, operationId, mutation, status, absence, digest); - } catch (RuntimeException malformed) { - throw conflict("Stored issuer retirement proof is malformed"); - } - } - - private static void insertRetirement( - DSLContext transaction, - UUID operationId, - CanonicalGameplayIssuerBindingLocalReleaseOperation release, - CanonicalGameplayIssuerPartitionMutation mutation) { - var original = release.originalOperation(); - var released = release.releasedMemberValue(); - var reservation = original.reservation(); - var anchor = original.anchor(); - byte[] originalBytes = release.exactOriginalMemberValueBytes(); - byte[] releasedBytes = release.exactReleasedMemberValueBytes(); - transaction.execute( - "INSERT INTO " - + RETIREMENT - + " (retirement_operation_id, issuer_id, partition_id, release_operation_id, physical_mutation_id," - + " original_local_operation_id, transition_id, reservation_id, binding_ref, original_reservation_fence," - + " original_issuer_coverage_operation_id, original_issuer_coverage_operation_fence, original_coverage_fence," - + " original_inventory_snapshot_revision, original_reservation_inventory_revision," - + " anchor_issuer_coverage_operation_id, anchor_operation_fence, anchor_coverage_fence," - + " anchor_inventory_snapshot_revision, release_source_inventory_revision, release_completion_inventory_revision," - + " original_member_value_bytes, original_member_value_digest, released_member_value_bytes, released_member_value_digest," - + " expected_revision, successor_revision, exact_intended_change_bytes, exact_intended_change_digest, status)" - + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING_PHYSICAL_PROOF')", - operationId, - ISSUER, - decimal(released.reservation().partitionId()), - release.operationId(), - mutation.mutationId(), - original.operationId(), - original.request().transitionId(), - reservation.reservationId(), - released.owner().bindingRef().bytes(), - reservation.reservationFence(), - reservation.issuerCoverageOperationId(), - decimal(reservation.issuerCoverageOperationFence()), - decimal(reservation.coverageFence()), - decimal(reservation.inventorySnapshotRevision()), - decimal(reservation.inventoryRevision()), - anchor.issuerCoverageOperationId(), - decimal(anchor.operationFence()), - decimal(anchor.coverageFence()), - decimal(anchor.issuerInventorySnapshotRevision()), - decimal(release.sourceInventoryRevision()), - decimal(release.completionInventoryRevision()), - originalBytes, - CanonicalGameplayIssuerMemberV2Codec.sha256(originalBytes), - releasedBytes, - CanonicalGameplayIssuerMemberV2Codec.sha256(releasedBytes), - mutation.expectedRevision(), - mutation.successorRevision(), - mutation.exactIntendedChangeBytes(), - mutation.exactIntendedChangeDigest()); - } - - private static byte[] encodeRetirementIntent( - UUID retirementOperationId, CanonicalGameplayIssuerBindingLocalReleaseOperation release) { - return CanonicalGameplayIssuerPartitionMutationRepository.encodeIntendedChange( - CanonicalGameplayIssuerPartitionMutation.Kind.RETIRE, - retirementOperationId, - release.releasedMemberValue().reservation().partitionId(), - release.operationId().toString().getBytes(StandardCharsets.US_ASCII), - release.originalOperationId().toString().getBytes(StandardCharsets.US_ASCII), - release - .abortSource() - .transition() - .transitionId() - .toString() - .getBytes(StandardCharsets.US_ASCII), - release - .releasedMemberValue() - .reservation() - .reservationId() - .toString() - .getBytes(StandardCharsets.US_ASCII), - release.releasedMemberValue().owner().bindingRef().bytes(), - release.sourceInventoryRevision().toString().getBytes(StandardCharsets.US_ASCII), - release.completionInventoryRevision().toString().getBytes(StandardCharsets.US_ASCII), - release.exactOriginalMemberValueBytes(), - release.exactReleasedMemberValueBytes()); - } - - private static void verifyExactAbsence( - CanonicalGameplayIssuerBindingLocalRetirementOperation operation, - byte[] exactBytes, - String digest) { - if (exactBytes == null - || exactBytes.length == 0 - || exactBytes.length > 17_825_792 - || !digest.equals(CanonicalGameplayIssuerMemberV2Codec.sha256(exactBytes))) { - throw conflict("Issuer retirement readback is missing, oversized, or has a wrong digest"); - } - Map fields = - CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet(exactBytes); - String capacity = - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( - operation.reservationId()); - byte[] revision = fields.get(CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD); - if (fields.containsKey(capacity) - || !Arrays.equals( - revision, - operation - .physicalMutation() - .successorRevision() - .toString() - .getBytes(StandardCharsets.US_ASCII))) { - throw conflict("Issuer retirement readback does not prove exact capacity-field absence"); - } - } - - private static void requireSameRetirement( - CanonicalGameplayIssuerBindingLocalRetirementOperation expected, - CanonicalGameplayIssuerBindingLocalRetirementOperation actual) { - if (!expected.operationId().equals(actual.operationId()) - || !expected.physicalMutation().mutationId().equals(actual.physicalMutation().mutationId()) - || !expected - .physicalMutation() - .expectedRevision() - .equals(actual.physicalMutation().expectedRevision()) - || !expected - .physicalMutation() - .successorRevision() - .equals(actual.physicalMutation().successorRevision()) - || !Arrays.equals( - expected.physicalMutation().exactIntendedChangeBytes(), - actual.physicalMutation().exactIntendedChangeBytes())) { - throw conflict("Original issuer retirement changed across the physical proof boundary"); - } - } - - private static void requireSameReleaseOperation( - CanonicalGameplayIssuerBindingLocalReleaseOperation expected, - CanonicalGameplayIssuerBindingLocalReleaseOperation actual) { - if (!expected.operationId().equals(actual.operationId()) - || expected.status() != actual.status() - || !Arrays.equals( - expected.exactOriginalMemberValueBytes(), actual.exactOriginalMemberValueBytes()) - || !Arrays.equals( - expected.exactReleasedMemberValueBytes(), actual.exactReleasedMemberValueBytes()) - || !Arrays.equals( - expected.exactPhysicalReadbackFieldSetBytes(), - actual.exactPhysicalReadbackFieldSetBytes())) { - throw conflict("Committed release changed while preparing physical retirement"); - } - } - - private static void requireSameReleaseSource( - CanonicalGameplayAdmissionAbortSource expected, - CanonicalGameplayAdmissionAbortSource actual, - CanonicalGameplayIssuerBindingLocalReleaseOperation release) { - if (!expected.transition().equals(actual.transition()) - || !expected.candidate().equals(actual.candidate()) - || !expected.reservation().equals(actual.reservation()) - || !expected.originalDecision().requestId().equals(actual.originalDecision().requestId()) - || !expected.originalDecision().leaseId().equals(actual.originalDecision().leaseId()) - || !expected - .originalDecision() - .leaseEvidenceJson() - .equals(actual.originalDecision().leaseEvidenceJson()) - || !expected - .originalDecision() - .targetEvidence() - .equals(actual.originalDecision().targetEvidence()) - || !expected.isAccountAborted() - || !actual.isAccountAborted() - || !expected.transition().transitionId().equals(actual.transition().transitionId()) - || actual.transition().status() - != net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot - .Status.ABORTED - || !actual.transition().inventoryRevision().equals(release.completionInventoryRevision()) - || !actual.transition().bindingRef().equals(expected.transition().bindingRef()) - || !actual - .transition() - .bindingGeneration() - .equals(expected.transition().bindingGeneration()) - || !actual.orphanCleanupId().equals(expected.orphanCleanupId()) - || actual.reservation().lifecycle() - != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED - || !actual - .reservation() - .reservationId() - .equals(release.releasedMemberValue().reservation().reservationId()) - || !actual.reservation().inventoryRevision().equals(release.completionInventoryRevision()) - || !actual.reservation().owner().equals(release.releasedMemberValue().owner())) { - throw conflict("Current Account-aborted source differs from the committed original release"); - } - } - - private static void requireSourceMatchesRelease( - CanonicalGameplayAdmissionAbortSource source, - CanonicalGameplayIssuerBindingLocalReleaseOperation release) { - requireSameReleaseSource(source, source, release); - } - - private static void requireSameCurrentIssuerState( - CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState expected, - CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState actual, - CanonicalGameplayIssuerInstalledAnchor anchor) { - var a = expected == null ? null : expected.accountCheckpoint(); - var b = actual == null ? null : actual.accountCheckpoint(); - if (a == null - || b == null - || !a.issuerId().equals(b.issuerId()) - || !a.issuerAuthGeneration().equals(b.issuerAuthGeneration()) - || !Arrays.equals(a.exactCheckpointBytes(), b.exactCheckpointBytes()) - || !a.checkpointDigest().equals(b.checkpointDigest()) - || !Objects.equals(a.latestIssuerEventDigest(), b.latestIssuerEventDigest()) - || !Arrays.equals(a.latestIssuerEventBytes(), b.latestIssuerEventBytes()) - || !Arrays.equals( - CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(expected.incarnation()), - CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(actual.incarnation())) - || !Arrays.equals(a.exactCheckpointBytes(), anchor.sourceCheckpointBytes()) - || !a.checkpointDigest().equals(anchor.sourceCheckpointDigest()) - || !Arrays.equals( - CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(actual.incarnation()), - anchor.incarnationBytes())) { - throw conflict("Issuer source or storage incarnation changed during retirement SQL work"); - } - } - - private CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState - readCurrentIssuerState() { - requireNoAmbientTransaction(); - return Objects.requireNonNull( - currentIssuerStateSource.readFreshCurrentState(), "Current issuer state is required"); - } - - private static long count(DSLContext transaction, String query, Object... bindings) { - Record row = transaction.fetchOne(query, bindings); - if (row == null) throw conflict("Issuer retirement SQL count is unavailable"); - return number(row, "count").longValueExact(); - } - - private static UUID freshNonNilUuid() { - UUID value; - do { - value = UUID.randomUUID(); - } while (value.equals(new UUID(0L, 0L))); - return value; - } - - private static BigDecimal decimal(BigInteger value) { - return new BigDecimal(value); - } - - private static UUID uuid(Record row, String field) { - UUID value = row.get(field, UUID.class); - if (value == null || value.equals(new UUID(0L, 0L))) - throw conflict(field + " is missing or nil"); - return value; - } - - private static BigInteger number(Record row, String field) { - Object value = row.get(field); - if (!(value instanceof Number number)) throw conflict(field + " is missing or nonnumeric"); - try { - return number instanceof BigDecimal decimal - ? decimal.toBigIntegerExact() - : BigInteger.valueOf(number.longValue()); - } catch (ArithmeticException malformed) { - throw conflict(field + " is not an exact integer"); - } - } - - private static BigInteger positive(Record row, String field) { - BigInteger value = number(row, field); - if (value.signum() <= 0) throw conflict(field + " is not positive"); - return value; - } - - private static BigInteger nonnegative(Record row, String field) { - BigInteger value = number(row, field); - if (value.signum() < 0) throw conflict(field + " is negative"); - return value; - } - - private static String text(Record row, String field) { - String value = row.get(field, String.class); - if (value == null) throw conflict(field + " is missing"); - return value; - } - - private static byte[] bytes(Record row, String field) { - byte[] value = row.get(field, byte[].class); - if (value == null || value.length == 0) throw conflict(field + " is missing or empty"); - return value.clone(); - } - - private static byte[] optionalBytes(Record row, String field) { - byte[] value = row.get(field, byte[].class); - return value == null ? null : value.clone(); - } - - private static void requireNoAmbientTransaction() { - if (TransactionSynchronizationManager.isActualTransactionActive()) { - throw conflict("Issuer retirement cannot cross Redis from an ambient SQL transaction"); - } - } - - private static IllegalStateException conflict(String message) { - return new IllegalStateException(message); - } -} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.java deleted file mode 100644 index 598167ed9f..0000000000 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.java +++ /dev/null @@ -1,362 +0,0 @@ -package net.firedevops.firemud.gamesession.repository; - -import static net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerPartitionRedisSupport.KEY_PREFIX; -import static net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerPartitionRedisSupport.ascii; -import static net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerPartitionRedisSupport.b64; - -import io.lettuce.core.RedisClient; -import io.lettuce.core.api.StatefulRedisConnection; -import io.lettuce.core.api.async.RedisAsyncCommands; -import io.lettuce.core.codec.ByteArrayCodec; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; -import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; -import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; -import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution; - -/** Manual one-key owner for exact original-operation terminal capacity retirement. */ -final class CanonicalGameplayIssuerBindingLocalRetirementRedisOwner { - private static final CanonicalGameplayIssuerPartitionRedisSupport REDIS = - new CanonicalGameplayIssuerPartitionRedisSupport( - CanonicalGameplayIssuerBindingLocalRetirementRedisOwner::unavailable); - private static final List EXPECTED_KEYS = - List.of( - new RedisScriptDescriptor.KeySpec( - "issuerPartition", KEY_PREFIX, RedisScriptDescriptor.HashTagDeclaration.REQUIRED)); - private static final List EXPECTED_ARGUMENTS = - List.of( - new RedisScriptDescriptor.ArgumentSpec("issuerIdPartitionLayoutAndExactBaselineFields"), - new RedisScriptDescriptor.ArgumentSpec( - "currentUnretiredLocalOperationCountAndExactFields"), - new RedisScriptDescriptor.ArgumentSpec( - "originalReleaseReceiptAndOpaquePhysicalRevisionCompareAndAdvance")); - private static final List EXPECTED_OUTCOMES = - List.of( - new RedisScriptDescriptor.OutcomeSpec( - "TERMINAL_CAPACITY_RETIRED", - RedisScriptDescriptor.OutcomeCategory.SUCCESS, - RedisScriptDescriptor.MutationEffect.MUTATING), - new RedisScriptDescriptor.OutcomeSpec( - "ORIGINAL_RETIREMENT_REPLAY", - RedisScriptDescriptor.OutcomeCategory.REPLAY, - RedisScriptDescriptor.MutationEffect.NON_MUTATING), - new RedisScriptDescriptor.OutcomeSpec( - "TYPE_TTL_OR_FIELDSET_REFUSED", - RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, - RedisScriptDescriptor.MutationEffect.NON_MUTATING), - new RedisScriptDescriptor.OutcomeSpec( - "INVALID_OR_STALE_REVISION_REFUSED", - RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, - RedisScriptDescriptor.MutationEffect.NON_MUTATING)); - - private final RedisClient redisClient; - private final RedisScriptCatalog catalog; - private final CanonicalGameplayIssuerBindingLocalProjectionRepository projectionRepository; - private final CanonicalGameplayIssuerBindingLocalRetirementOperationRepository - retirementRepository; - private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource - currentStateSource; - - CanonicalGameplayIssuerBindingLocalRetirementRedisOwner( - RedisClient redisClient, - RedisScriptCatalog catalog, - CanonicalGameplayIssuerBindingLocalProjectionRepository projectionRepository, - CanonicalGameplayIssuerBindingLocalRetirementOperationRepository retirementRepository, - CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource - currentStateSource) { - this.redisClient = Objects.requireNonNull(redisClient, "Configured Redis client is required"); - this.catalog = Objects.requireNonNull(catalog, "Manual Redis script catalog is required"); - this.projectionRepository = - Objects.requireNonNull(projectionRepository, "SQL current projection owner is required"); - this.retirementRepository = - Objects.requireNonNull(retirementRepository, "SQL retirement owner is required"); - this.currentStateSource = - Objects.requireNonNull(currentStateSource, "Fresh issuer source is required"); - } - - /** Retires one terminal capacity field and independently proves its exact absence and fence. */ - Readback retireAndRead(CanonicalGameplayIssuerBindingLocalRetirementOperation operation) { - Objects.requireNonNull(operation, "SQL-issued original retirement is required"); - requireNoAmbientTransaction(); - if (operation.status() - == CanonicalGameplayIssuerBindingLocalRetirementOperation.Status.RETIRED) { - return new Readback( - operation.operationId(), 2L, operation.exactAbsenceReadbackFieldSetBytes()); - } - try { - var release = operation.release(); - var work = projectionRepository.readPreparedPartitionWork(release.originalOperation()); - var mutation = operation.physicalMutation(); - if (mutation.status() - != CanonicalGameplayIssuerPartitionMutation.Status.PENDING_PHYSICAL_PROOF - || !mutation.mutationId().equals(work.pendingMutationId()) - || !mutation.expectedRevision().equals(work.currentRevision())) { - throw unavailable("Original retirement no longer owns its prepared partition revision"); - } - requireFreshCurrentState(work); - RedisScriptDescriptor descriptor = requireDescriptor(); - byte[] script = REDIS.scriptSource(descriptor); - byte[] key = exactPartitionKey(work); - long outcome = writeOneKey(script, key, scriptArguments(work, operation)); - if (outcome != 1 && outcome != 2) { - throw unavailable( - "Issuer retirement Lua refused the exact prepared terminal field: " + outcome); - } - byte[] readback = readExactPhysicalState(key, work, operation); - requireFreshCurrentState(work); - projectionRepository.requireStillCurrent(work); - Readback proof = new Readback(operation.operationId(), outcome, readback); - retirementRepository.completeWithReadback(operation, proof); - return proof; - } catch (RuntimeException failure) { - if (failure instanceof IllegalStateException state - && state.getMessage() != null - && state.getMessage().startsWith("Issuer binding-local retirement is unavailable")) { - throw state; - } - throw unavailable( - "Physical retirement did not obtain exact source and absence proof", failure); - } - } - - private long writeOneKey(byte[] script, byte[] key, byte[][] arguments) { - requireNoAmbientTransaction(); - try { - return REDIS.writeOneKey(redisClient, script, key, arguments); - } catch (RuntimeException failure) { - throw unavailable("One-key issuer retirement command failed", failure); - } - } - - private byte[] readExactPhysicalState( - byte[] key, - CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work, - CanonicalGameplayIssuerBindingLocalRetirementOperation operation) { - requireNoAmbientTransaction(); - try (StatefulRedisConnection connection = - redisClient.connect(ByteArrayCodec.INSTANCE)) { - RedisAsyncCommands commands = REDIS.authenticatedCommands(connection); - Map actual = REDIS.readBoundedHash(commands, key); - Map allowed = new HashMap<>(work.allowedFields()); - String capacityField = - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( - operation.release().releasedMemberValue().reservation().reservationId()); - if (allowed.containsKey(capacityField)) { - allowed.remove(capacityField); - } else { - throw unavailable( - "The current SQL projection does not contain the terminal target capacity"); - } - byte[] revision = - actual.get( - b64( - CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD.getBytes( - StandardCharsets.US_ASCII))); - if (!Arrays.equals( - revision, - operation - .physicalMutation() - .successorRevision() - .toString() - .getBytes(StandardCharsets.US_ASCII))) { - throw unavailable("Issuer retirement lacks its exact successor fence"); - } - for (Map.Entry field : work.baselineFields().entrySet()) { - byte[] value = actual.get(b64(field.getKey().getBytes(StandardCharsets.UTF_8))); - if (value == null || !Arrays.equals(value, field.getValue())) { - throw unavailable("Exact installed issuer baseline changed during retirement"); - } - } - for (Map.Entry field : actual.entrySet()) { - String decoded = REDIS.decodeField(field.getKey()); - if (decoded.equals(CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD)) - continue; - byte[] expected = allowed.get(decoded); - if (expected == null || !Arrays.equals(expected, field.getValue())) { - throw unavailable("Issuer retirement readback contains a foreign or changed field"); - } - } - for (var entry : work.localEntries()) { - if (!entry - .memberValue() - .reservation() - .partitionId() - .equals(operation.release().releasedMemberValue().reservation().partitionId())) - continue; - boolean retirementTarget = - entry - .memberValue() - .reservation() - .reservationId() - .equals(operation.release().releasedMemberValue().reservation().reservationId()); - String localCapacityField = - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( - entry.memberValue().reservation().reservationId()); - byte[] localCapacity = - actual.get(b64(localCapacityField.getBytes(StandardCharsets.US_ASCII))); - if (!retirementTarget - && entry.capacityMustBePresent() - && !Arrays.equals(localCapacity, entry.exactMemberValueBytes())) { - throw unavailable("A committed local capacity field is missing or changed"); - } - String localBindingField = - new String(entry.memberValue().owner().bindingRef().bytes(), StandardCharsets.UTF_8); - byte[] localBinding = actual.get(b64(localBindingField.getBytes(StandardCharsets.UTF_8))); - if (entry.bindingMustBePresent() - && !Arrays.equals(localBinding, entry.exactMemberValueBytes())) { - throw unavailable("A committed local binding field is missing or changed"); - } - } - if (actual.containsKey(b64(capacityField.getBytes(StandardCharsets.US_ASCII)))) { - throw unavailable("Exact terminal capacity field remains after retirement"); - } - return CanonicalGameplayIssuerBootstrapCoverageRepository.encodeFieldSet( - REDIS.decodePhysicalMap(actual)); - } catch (RuntimeException failure) { - throw unavailable("Independent issuer retirement readback was not exact", failure); - } - } - - private static byte[][] scriptArguments( - CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work, - CanonicalGameplayIssuerBindingLocalRetirementOperation operation) { - var anchor = work.anchor(); - List args = new ArrayList<>(); - args.add(ascii(anchor.issuerId())); - args.add( - ascii(operation.release().releasedMemberValue().reservation().partitionId().toString())); - args.add(ascii(anchor.partitionCount().toString())); - args.add(ascii(anchor.partitionCapacity().toString())); - Map baseline = work.baselineFields(); - List> sorted = - baseline.entrySet().stream().sorted(Map.Entry.comparingByKey()).toList(); - args.add(ascii(Integer.toString(sorted.size()))); - for (Map.Entry field : sorted) { - args.add(field.getKey().getBytes(StandardCharsets.UTF_8)); - args.add(field.getValue()); - } - List entries = - work.localEntries().stream() - .filter( - entry -> - entry - .memberValue() - .reservation() - .partitionId() - .equals( - operation.release().releasedMemberValue().reservation().partitionId())) - .sorted(Comparator.comparing(entry -> entry.operationId().toString())) - .toList(); - args.add(ascii(Integer.toString(entries.size()))); - for (var entry : entries) { - args.add(ascii(entry.operationId().toString())); - args.add(entry.memberValue().owner().bindingRef().bytes()); - args.add(ascii(entry.memberValue().reservation().reservationId().toString())); - args.add(entry.exactMemberValueBytes()); - args.add(ascii(entry.bindingPresent() ? "1" : "0")); - args.add(ascii(entry.countsTowardCapacity() ? "1" : "0")); - args.add(ascii(entry.capacityMustBePresent() ? "1" : "0")); - args.add(ascii(entry.bindingMustBePresent() ? "1" : "0")); - } - var release = operation.release(); - var mutation = operation.physicalMutation(); - args.add(ascii(release.operationId().toString())); - args.add(ascii(operation.operationId().toString())); - args.add(ascii(release.releasedMemberValue().reservation().reservationId().toString())); - args.add(release.releasedMemberValue().owner().bindingRef().bytes()); - args.add(release.exactReleasedMemberValueBytes()); - args.add(ascii(release.sourceInventoryRevision().toString())); - args.add(ascii(release.completionInventoryRevision().toString())); - args.add(ascii(work.partitionCapacity().toString())); - args.add(ascii(work.aggregateCapacity().toString())); - args.add(ascii(work.aggregateBound().toString())); - args.add(ascii(mutation.expectedRevision().toString())); - args.add(ascii(mutation.successorRevision().toString())); - return args.toArray(byte[][]::new); - } - - private byte[] exactPartitionKey( - CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work) { - String key = CanonicalGameplayIssuerRedisKeys.forMember(work.targetOperation().memberValue()); - if (!key.startsWith(KEY_PREFIX) || key.length() > 512) - throw unavailable("Issuer key is not canonical"); - return key.getBytes(StandardCharsets.US_ASCII); - } - - private void requireFreshCurrentState( - CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work) { - requireNoAmbientTransaction(); - var current = currentStateSource.readFreshCurrentState(); - requireNoAmbientTransaction(); - if (!REDIS.matchesCurrentState(current, work.anchor())) { - throw unavailable("Issuer source checkpoint or incarnation changed"); - } - } - - private RedisScriptDescriptor requireDescriptor() { - RedisScriptDescriptor descriptor; - try { - descriptor = - catalog.require( - CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution.SCRIPT_ID); - } catch (RuntimeException missing) { - throw unavailable("Manual issuer retirement descriptor is not installed", missing); - } - if (!REDIS.matchesDescriptor( - descriptor, - CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution.SCRIPT_ID, - CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution.RESOURCE_PATH, - EXPECTED_KEYS, - EXPECTED_ARGUMENTS, - EXPECTED_OUTCOMES)) { - throw unavailable( - "Manual issuer retirement descriptor differs from its exact owner contract"); - } - return descriptor; - } - - private static void requireNoAmbientTransaction() { - REDIS.requireNoAmbientTransaction(); - } - - private static IllegalStateException unavailable(String message) { - return new IllegalStateException("Issuer binding-local retirement is unavailable: " + message); - } - - private static IllegalStateException unavailable(String message, Throwable cause) { - return new IllegalStateException( - "Issuer binding-local retirement is unavailable: " + message, cause); - } - - static final class Readback { - private final UUID operationId; - private final long scriptOutcome; - private final byte[] exactAbsenceReadbackFieldSetBytes; - - private Readback(UUID operationId, long scriptOutcome, byte[] exactBytes) { - this.operationId = Objects.requireNonNull(operationId, "operationId"); - this.scriptOutcome = scriptOutcome; - this.exactAbsenceReadbackFieldSetBytes = - Objects.requireNonNull(exactBytes, "exactBytes").clone(); - } - - UUID operationId() { - return operationId; - } - - long scriptOutcome() { - return scriptOutcome; - } - - byte[] exactAbsenceReadbackFieldSetBytes() { - return exactAbsenceReadbackFieldSetBytes.clone(); - } - } -} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution.java deleted file mode 100644 index 82c0ae78b1..0000000000 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution.java +++ /dev/null @@ -1,32 +0,0 @@ -package net.firedevops.firemud.gamesession.service; - -import java.util.Collection; -import java.util.List; -import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; -import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; - -/** Passive manual-catalog contribution for one original-operation physical retirement. */ -public final class CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution - implements RedisScriptContribution { - public static final String SCRIPT_ID = "game-session.issuer-binding-local-retirement.v1"; - public static final String RESOURCE_PATH = - "redis/lua/game-session-issuer-binding-local-retirement.lua"; - private static final String DESCRIPTOR_PATH = - "/redis/scripts/game-session-issuer-binding-local-retirement.json"; - - @Override - public String ownerId() { - return "game-session-service"; - } - - @Override - public Collection descriptors() { - return List.of( - GameSessionRedisScriptDescriptors.load( - getClass(), - DESCRIPTOR_PATH, - ownerId(), - SCRIPT_ID, - "Issuer binding-local retirement descriptor is unavailable")); - } -} diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-retirement.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-retirement.lua deleted file mode 100644 index dce9a79f69..0000000000 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-retirement.lua +++ /dev/null @@ -1,272 +0,0 @@ --- Retire only one SQL-released terminal capacity field under the partition revision fence. --- KEYS[1] is the sole canonical issuer partition hash. -local keyPrefix = 'session:game:index:issuer:' -local metadataField = '!issuer-partition-bootstrap/v1' -local revisionField = '!issuer-partition-mutation-revision/v1' -local capacityPrefix = '!issuer-reservation-capacity/v1:' -local maxMemberValueBytes = 65536 -local maxMetadataBytes = 65536 -local maxBaselineFields = 513 -local maxLocalOperations = 256 -local maxCurrentFields = 1026 -local maxExpectedFields = 1025 -local maxHashBytes = 16777216 - -local function uuid(value) - return type(value) == 'string' and #value == 36 - and string.match(value, '^%x%x%x%x%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x$') - and value == string.lower(value) - and value ~= '00000000-0000-0000-0000-000000000000' -end -local function positive(value) - return type(value) == 'string' and #value > 0 and #value <= 256 - and string.match(value, '^[1-9][0-9]*$') ~= nil -end -local function nonnegative(value) - return value == '0' or positive(value) -end -local function digest(value) - return type(value) == 'string' and #value == 71 - and string.match(value, '^sha256:[0-9a-f]+$') ~= nil -end -local function greaterDecimal(left, right) - if #left ~= #right then return #left > #right end - return left > right -end - -if #KEYS ~= 1 or #ARGV < 14 then return -2 end -if type(KEYS[1]) ~= 'string' or #KEYS[1] > 512 - or string.sub(KEYS[1], 1, #keyPrefix) ~= keyPrefix then return -2 end -local issuerId = ARGV[1] -local partitionId = ARGV[2] -local partitionCount = ARGV[3] -local partitionCapacity = ARGV[4] -local baselineCount = tonumber(ARGV[5]) -if issuerId ~= 'firemud-account-service' or not nonnegative(partitionId) - or not positive(partitionCount) or not positive(partitionCapacity) - or not baselineCount or baselineCount ~= baselineCount or baselineCount < 1 - or baselineCount > maxBaselineFields then return -2 end - -local cursor = 6 -local baseline = {} -local baselineReservations = 0 -local baselineBindings = 0 -local baselineCapacity = 0 -local metadataBytes = nil -for index = 1, baselineCount do - local field = ARGV[cursor] - local value = ARGV[cursor + 1] - cursor = cursor + 2 - if type(field) ~= 'string' or #field == 0 or baseline[field] ~= nil - or type(value) ~= 'string' or #value == 0 or #value > maxMemberValueBytes then return -2 end - baseline[field] = value - if field == metadataField then - metadataBytes = value - elseif string.sub(field, 1, #capacityPrefix) == capacityPrefix then - local id = string.sub(field, #capacityPrefix + 1) - local ok, member = pcall(cjson.decode, value) - if not uuid(id) or not ok or type(member) ~= 'table' - or type(member.reservation) ~= 'table' or member.reservation.reservationId ~= id - or member.reservation.partitionId ~= partitionId then return -2 end - baselineReservations = baselineReservations + 1 - if member.reservation.lifecycle ~= 'RELEASED' then baselineCapacity = baselineCapacity + 1 end - else - local ok, member = pcall(cjson.decode, value) - if not ok or type(member) ~= 'table' or type(member.reservation) ~= 'table' - or member.reservation.bindingRef ~= field then return -2 end - baselineBindings = baselineBindings + 1 - end -end -if metadataBytes == nil or #metadataBytes > maxMetadataBytes then return -2 end -local metadataOk, metadata = pcall(cjson.decode, metadataBytes) -if not metadataOk or type(metadata) ~= 'table' or metadata.schemaVersion ~= 1 - or metadata.issuerId ~= issuerId or metadata.partitionId ~= partitionId - or type(metadata.layoutTag) ~= 'string' or #metadata.layoutTag ~= 70 - or not string.match(metadata.layoutTag, '^il%-v1%-%x+$') - or type(metadata.layout) ~= 'table' or type(metadata.anchor) ~= 'table' - or type(metadata.incarnation) ~= 'table' - or metadata.layout.partitionCount ~= partitionCount - or metadata.layout.partitionCapacity ~= partitionCapacity - or metadata.layout.mappingIdentity ~= 'bindingRef/v1;sha256-u256-mod/v1' - or not uuid(metadata.anchor.issuerCoverageOperationId) - or not positive(metadata.anchor.operationFence) - or not positive(metadata.anchor.coverageFence) - or not positive(metadata.anchor.issuerInventorySnapshotRevision) then return -2 end -local expectedKey = keyPrefix .. '{' .. metadata.layoutTag .. '}:' .. issuerId .. ':' .. partitionId -if KEYS[1] ~= expectedKey or not greaterDecimal(partitionCount, partitionId) then return -2 end - -local allowed = {} -local allowedCount = 0 -local expectedBytes = 0 -local function put(field, value) - if type(field) ~= 'string' or #field == 0 or allowed[field] ~= nil then return false end - allowed[field] = value - allowedCount = allowedCount + 1 - expectedBytes = expectedBytes + #field + #value - return allowedCount <= maxExpectedFields and expectedBytes <= maxHashBytes -end -for field, value in pairs(baseline) do if not put(field, value) then return -2 end end - -local operationCount = tonumber(ARGV[cursor]) -cursor = cursor + 1 -if not operationCount or operationCount < 1 or operationCount > maxLocalOperations then return -2 end -local operations = {} -local operationIds = {} -local reservationIds = {} -local bindingRefs = {} -local registeredCapacity = 0 -local registeredBindings = 0 -for index = 1, operationCount do - local operationId = ARGV[cursor] - local bindingRef = ARGV[cursor + 1] - local reservationId = ARGV[cursor + 2] - local memberBytes = ARGV[cursor + 3] - local bindingPresent = ARGV[cursor + 4] - local countsCapacity = ARGV[cursor + 5] - local capacityMustBePresent = ARGV[cursor + 6] - local bindingMustBePresent = ARGV[cursor + 7] - cursor = cursor + 8 - if not uuid(operationId) or not uuid(reservationId) - or type(bindingRef) ~= 'string' or #bindingRef == 0 or #bindingRef > 6144 - or type(memberBytes) ~= 'string' or #memberBytes == 0 or #memberBytes > maxMemberValueBytes - or (bindingPresent ~= '0' and bindingPresent ~= '1') - or (countsCapacity ~= '0' and countsCapacity ~= '1') - or (capacityMustBePresent ~= '0' and capacityMustBePresent ~= '1') - or (bindingMustBePresent ~= '0' and bindingMustBePresent ~= '1') - or (bindingMustBePresent == '1' and bindingPresent ~= '1') - or operationIds[operationId] or reservationIds[reservationId] or bindingRefs[bindingRef] then return -2 end - local ok, member = pcall(cjson.decode, memberBytes) - if not ok or type(member) ~= 'table' or member.schemaVersion ~= 2 - or member.issuerId ~= issuerId or type(member.reservation) ~= 'table' - or type(member.memberOperation) ~= 'table' - or member.reservation.bindingRef ~= bindingRef - or member.reservation.reservationId ~= reservationId - or member.reservation.partitionId ~= partitionId - or member.memberOperation.operationId ~= operationId - or not uuid(member.memberOperation.operationId) - or (countsCapacity == '1' and member.reservation.lifecycle == 'RELEASED') - or (countsCapacity == '0' - and (member.reservation.lifecycle ~= 'RELEASED' or bindingPresent ~= '0')) then return -2 end - operationIds[operationId] = true - reservationIds[reservationId] = true - bindingRefs[bindingRef] = true - operations[#operations + 1] = { - operationId=operationId, bindingRef=bindingRef, reservationId=reservationId, - memberBytes=memberBytes, bindingPresent=bindingPresent, countsCapacity=countsCapacity, - capacityMustBePresent=capacityMustBePresent, bindingMustBePresent=bindingMustBePresent, - member=member - } - if countsCapacity == '1' then registeredCapacity = registeredCapacity + 1 end - if bindingPresent == '1' then registeredBindings = registeredBindings + 1 end - if not put(capacityPrefix .. reservationId, memberBytes) then return -2 end - if bindingPresent == '1' and not put(bindingRef, memberBytes) then return -2 end -end - -local releaseOperationId = ARGV[cursor] -local retirementOperationId = ARGV[cursor + 1] -local targetReservationId = ARGV[cursor + 2] -local targetBindingRef = ARGV[cursor + 3] -local releasedBytes = ARGV[cursor + 4] -local sourceRevision = ARGV[cursor + 5] -local completionRevision = ARGV[cursor + 6] -local plannedPartitionCapacity = ARGV[cursor + 7] -local plannedAggregateCapacity = ARGV[cursor + 8] -local aggregateBound = ARGV[cursor + 9] -local expectedRevision = ARGV[cursor + 10] -local successorRevision = ARGV[cursor + 11] -if #ARGV ~= cursor + 11 or not uuid(releaseOperationId) or not uuid(retirementOperationId) - or not uuid(targetReservationId) or type(targetBindingRef) ~= 'string' - or type(releasedBytes) ~= 'string' or #releasedBytes == 0 or #releasedBytes > maxMemberValueBytes - or not positive(sourceRevision) or not positive(completionRevision) - or not greaterDecimal(completionRevision, sourceRevision) - or not nonnegative(plannedPartitionCapacity) or not nonnegative(plannedAggregateCapacity) - or not positive(aggregateBound) or not uuid(expectedRevision) or not uuid(successorRevision) - or expectedRevision == successorRevision - or greaterDecimal(plannedPartitionCapacity, partitionCapacity) - or greaterDecimal(plannedAggregateCapacity, aggregateBound) then return -2 end -local releasedOk, released = pcall(cjson.decode, releasedBytes) -if not releasedOk or type(released) ~= 'table' or released.schemaVersion ~= 2 - or type(released.reservation) ~= 'table' or type(released.memberOperation) ~= 'table' - or released.issuerId ~= issuerId - or released.reservation.lifecycle ~= 'RELEASED' - or released.reservation.reservationId ~= targetReservationId - or released.reservation.partitionId ~= partitionId - or released.reservation.inventoryRevision ~= sourceRevision - or released.memberOperation.operationId ~= releaseOperationId - or released.reservation.bindingRef ~= targetBindingRef then return -2 end -local targetFound = false -for _, operation in ipairs(operations) do - if operation.reservationId == targetReservationId then - if operation.operationId ~= releaseOperationId - or operation.bindingRef ~= targetBindingRef - or operation.memberBytes ~= releasedBytes - or operation.countsCapacity ~= '0' or operation.bindingPresent ~= '0' then return -2 end - targetFound = true - elseif operation.operationId == releaseOperationId then - return -2 - end -end -if not targetFound then return -2 end -local targetCapacityField = capacityPrefix .. targetReservationId -if allowed[targetCapacityField] ~= releasedBytes then return -2 end -if tostring(baselineCapacity + registeredCapacity) ~= plannedPartitionCapacity then return -2 end - -local kind = redis.call('TYPE', KEYS[1]).ok -if kind ~= 'hash' or redis.call('PTTL', KEYS[1]) ~= -1 then return -1 end -local actual = redis.call('HGETALL', KEYS[1]) -if #actual % 2 ~= 0 or #actual / 2 > maxCurrentFields then return -1 end -local actualFields = {} -local currentBytes = 0 -local actualCapacity = 0 -local actualReservations = 0 -local actualBindings = 0 -for index = 1, #actual, 2 do - local field = actual[index] - local value = actual[index + 1] - actualFields[field] = value - currentBytes = currentBytes + #field + #value - if currentBytes > maxHashBytes then return -1 end - if field == revisionField then - if value ~= expectedRevision and value ~= successorRevision then return -1 end - elseif allowed[field] == nil or allowed[field] ~= value then - return -1 - end - if field == revisionField or field == metadataField then - -- Metadata and revision do not count as reservation or binding members. - elseif string.sub(field, 1, #capacityPrefix) == capacityPrefix then - local ok, member = pcall(cjson.decode, value) - if not ok or type(member) ~= 'table' or type(member.reservation) ~= 'table' then return -1 end - actualReservations = actualReservations + 1 - if member.reservation.lifecycle ~= 'RELEASED' then actualCapacity = actualCapacity + 1 end - else - actualBindings = actualBindings + 1 - end -end -local revisionBefore = actualFields[revisionField] -local targetCapacityBefore = actualFields[targetCapacityField] -for _, operation in ipairs(operations) do - if operation.operationId ~= releaseOperationId or revisionBefore ~= successorRevision then - local capacity = actualFields[capacityPrefix .. operation.reservationId] - local binding = actualFields[operation.bindingRef] - if operation.capacityMustBePresent == '1' and capacity ~= operation.memberBytes then return -1 end - if operation.bindingMustBePresent == '1' and binding ~= operation.memberBytes then return -1 end - end -end -for field, value in pairs(baseline) do - if redis.call('HGET', KEYS[1], field) ~= value then return -1 end -end -if actualCapacity > tonumber(plannedPartitionCapacity) - or actualReservations < baselineReservations - or actualReservations > baselineReservations + operationCount - or actualBindings < baselineBindings - or actualBindings > baselineBindings + registeredBindings then return -1 end -if revisionBefore == successorRevision then - if targetCapacityBefore ~= nil or actualFields[targetBindingRef] == releasedBytes then return -1 end - return 2 -end -if revisionBefore ~= expectedRevision - or targetCapacityBefore ~= releasedBytes - or actualFields[targetBindingRef] == releasedBytes then return -1 end -redis.call('HDEL', KEYS[1], targetCapacityField) -redis.call('HSET', KEYS[1], revisionField, successorRevision) -return 1 diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-retirement.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-retirement.json deleted file mode 100644 index efb9348e9b..0000000000 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-retirement.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "scriptId": "game-session.issuer-binding-local-retirement.v1", - "resourcePath": "redis/lua/game-session-issuer-binding-local-retirement.lua", - "sha256": "6454e04296ca915004d53175dc70d1b113ed1e0a4bf612ea4b0b6516da51e756", - "owner": "game-session-service", - "principal": "gamesession_coord_app", - "role": "COORDINATION", - "keys": [ - { - "name": "issuerPartition", - "ownedPrefix": "session:game:index:issuer:", - "hashTagDeclaration": "REQUIRED" - } - ], - "arguments": [ - {"name": "issuerIdPartitionLayoutAndExactBaselineFields"}, - {"name": "currentUnretiredLocalOperationCountAndExactFields"}, - {"name": "originalReleaseReceiptAndOpaquePhysicalRevisionCompareAndAdvance"} - ], - "category": "SESSION_ISSUER_INDEX", - "outcomes": [ - {"code": "TERMINAL_CAPACITY_RETIRED", "category": "SUCCESS", "effect": "MUTATING"}, - {"code": "ORIGINAL_RETIREMENT_REPLAY", "category": "REPLAY", "effect": "NON_MUTATING"}, - {"code": "TYPE_TTL_OR_FIELDSET_REFUSED", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, - {"code": "INVALID_OR_STALE_REVISION_REFUSED", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} - ], - "resetSensitivity": "CLUSTER", - "tailLossBehavior": "This passive manual one-key owner removes only the exact terminal capacity field named by the original committed RELEASED receipt at its actual SQL completion revision R. A SQL-persisted partition-local expected/successor revision fences every physical writer. A stale prepared ADD or release is rejected before mutation even after retirement. The owner requires the complete current unretired SQL projection, exact installed baseline, current source and incarnation, exact RELEASED bytes from P, and a current opaque revision. It independently reads back exact target absence and the successor revision before SQL records retirement. Immutable release and bootstrap history remain retained; retirement does not change Account or region obligations, grant coverage, open a barrier, or authorize admission. Unknown outcomes retain the same original pending retirement for exact readback recovery.", - "lossClass": "EMPTY_REDIS_COLD_START_OR_RESET", - "compatibilityLevel": "REQUIRES_CLUSTER_RESET", - "supportedCoexistence": [ - {"callerVersion": "v1", "payloadVersion": "v2"} - ], - "legacyPayloadShape": null -} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java index 5d08abd380..a8f87e8553 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java @@ -44,7 +44,6 @@ import net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountMemberRepairRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution; -import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; @@ -872,46 +871,6 @@ CanonicalGameplayIssuerBindingLocalOperation otherOperation(String seed) { return localProjectionRepository.readPreparedPartitionWork(localOperation); } - public CanonicalGameplayIssuerBindingLocalRetirementOperation prepareIssuerRetirement( - UUID transitionId) { - return new CanonicalGameplayIssuerBindingLocalRetirementOperationRepository(dsl, issuerSource) - .prepareOrResume(transitionId); - } - - public CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.Readback retireIssuerCapacity( - CanonicalGameplayIssuerBindingLocalRetirementOperation operation) { - return new CanonicalGameplayIssuerBindingLocalRetirementRedisOwner( - issuerRedisClient, - retirementCatalog(), - localProjectionRepository, - new CanonicalGameplayIssuerBindingLocalRetirementOperationRepository(dsl, issuerSource), - issuerSource) - .retireAndRead(operation); - } - - /** Public test bridge for the otherwise package-private retirement readback outcome. */ - public long retireIssuerCapacityOutcome( - CanonicalGameplayIssuerBindingLocalRetirementOperation operation) { - return retireIssuerCapacity(operation).scriptOutcome(); - } - - /** Public test bridge for the otherwise package-private retirement operation status. */ - public boolean isIssuerRetirementComplete( - CanonicalGameplayIssuerBindingLocalRetirementOperation operation) { - return operation.status() - == CanonicalGameplayIssuerBindingLocalRetirementOperation.Status.RETIRED; - } - - /** Adds the retirement script only for callers that exercise the new owner. */ - RedisScriptCatalog retirementCatalog() { - return RedisScriptCatalog.fromContributions( - List.of( - new CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution(), - new CanonicalGameplayIssuerBindingLocalRedisScriptContribution(), - new CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution(), - new CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution())); - } - public byte[] issuerPartitionKey() { return CanonicalGameplayIssuerRedisKeys.forMember(localOperation.memberValue()) .getBytes(StandardCharsets.US_ASCII); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLifecycleProofFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLifecycleProofFixtures.java new file mode 100644 index 0000000000..1a2f27027d --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLifecycleProofFixtures.java @@ -0,0 +1,610 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import io.lettuce.core.protocol.ProtocolVersion; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution; +import net.firedevops.firemud.test.TestContainerImages; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; + +/** + * Shared PostgreSQL/Redis setup and owner helpers for the separate local-capacity and retirement + * proofs. + */ +@SuppressWarnings("resource") +abstract class CanonicalGameplayIssuerLifecycleProofFixtures { + protected static final String OWNER_PRINCIPAL = "gamesession_coord_app"; + protected static final String ISSUER_KEY_PREFIX = "session:game:index:issuer:"; + protected static final BigInteger PARTITION_CAPACITY = BigInteger.valueOf(256); + protected static final UUID NIL_UUID = new UUID(0L, 0L); + + @Container + protected static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + protected static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + protected RedisClient administrator; + protected RedisClient issuerOwner; + protected StatefulRedisConnection administratorConnection; + protected RedisCommands administratorCommands; + + @BeforeEach + void setUp() { + String password = UUID.randomUUID().toString(); + administrator = createRedisClient(null, null); + administratorConnection = administrator.connect(ByteArrayCodec.INSTANCE); + administratorCommands = administratorConnection.sync(); + administratorCommands.aclSetuser( + OWNER_PRINCIPAL, + new AclSetuserArgs() + .reset() + .on() + .addPassword(password) + .keyPattern(ISSUER_KEY_PREFIX + "*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.HGET) + .addCommand(CommandType.HLEN) + .addCommand(CommandType.HGETALL) + .addCommand(CommandType.HSET) + .addCommand(CommandType.HDEL)); + issuerOwner = createRedisClient(OWNER_PRINCIPAL, password); + } + + @AfterEach + void tearDown() { + if (administratorConnection != null) administratorConnection.close(); + if (issuerOwner != null) issuerOwner.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + if (administrator != null) administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + + protected RedisClient createRedisClient(String username, String password) { + RedisURI.Builder builder = RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(6379)); + if (username != null) builder.withAuthentication(username, password); + RedisURI uri = builder.build(); + uri.setTimeout(Duration.ofSeconds(5)); + RedisClient client = RedisClient.create(uri); + client.setOptions( + ClientOptions.builder() + .autoReconnect(false) + .protocolVersion(ProtocolVersion.RESP2) + .build()); + return client; + } + + protected CanonicalGameplayAdmissionAbortCompositionFixture newFixture() { + return newFixture(controlledCandidate(), 0); + } + + protected CanonicalGameplayAdmissionAbortCompositionFixture newFixture( + BigInteger layoutVersion, BigInteger partitionCount, int seedBootstrapMemberCount) { + return newFixture(controlledCandidate(layoutVersion, partitionCount), seedBootstrapMemberCount); + } + + protected CanonicalGameplayAdmissionAbortCompositionFixture newFixture( + BigInteger layoutVersion, + BigInteger partitionCount, + BigInteger partitionCapacity, + int seedBootstrapMemberCount) { + return newFixture( + controlledCandidate(layoutVersion, partitionCount, partitionCapacity), + seedBootstrapMemberCount); + } + + protected CanonicalGameplayAdmissionAbortCompositionFixture newFixture( + Candidate candidate, int seedBootstrapMemberCount) { + DriverManagerDataSource accountDataSource = new DriverManagerDataSource(); + accountDataSource.setDriverClassName("org.postgresql.Driver"); + String postgresJdbcUrl = POSTGRES.getJdbcUrl(); + accountDataSource.setUrl( + postgresJdbcUrl + (postgresJdbcUrl.contains("?") ? "&" : "?") + "currentSchema=public"); + accountDataSource.setUsername(POSTGRES.getUsername()); + accountDataSource.setPassword(POSTGRES.getPassword()); + return new CanonicalGameplayAdmissionAbortCompositionFixture( + accountDataSource, candidate, issuerOwner, seedBootstrapMemberCount); + } + + protected static Candidate controlledCandidate() { + return controlledCandidate(BigInteger.valueOf(3), BigInteger.ONE); + } + + protected static Candidate controlledCandidate( + BigInteger layoutVersion, BigInteger partitionCount) { + return controlledCandidate(layoutVersion, partitionCount, PARTITION_CAPACITY); + } + + protected static Candidate controlledCandidate( + BigInteger layoutVersion, BigInteger partitionCount, BigInteger partitionCapacity) { + return new Candidate( + uuid("retirement-account"), + uuid("retirement-tenant"), + uuid("retirement-playable-state"), + uuid("retirement-character"), + "SHARED", + uuid("retirement-game"), + 1L, + uuid("retirement-session"), + uuid("retirement-region"), + BigInteger.ONE, + GameSessionAccountDelegationProfile.ISSUER, + BigInteger.ONE, + layoutVersion, + partitionCount, + partitionCapacity); + } + + protected static CanonicalGameplayBindingIdentity otherAccountInPartition( + CanonicalGameplayBindingIdentity template, BigInteger partitionId) { + CanonicalGameplayBindingIdentity candidate; + do { + candidate = + new CanonicalGameplayBindingIdentity( + UUID.randomUUID(), + template.tenantId(), + template.playableStateNamespaceId(), + UUID.randomUUID(), + template.playableStateScope(), + template.gameInstanceId(), + template.runtimeGameInstanceId(), + UUID.randomUUID().toString(), + template.regionId(), + template.regionEpoch(), + template.issuerId(), + template.issuerAuthGeneration(), + template.issuerIndexLayoutVersion(), + template.issuerIndexPartitionCount(), + template.issuerIndexPartitionCapacity()); + } while (!candidate + .bindingRef() + .partitionId(template.issuerIndexPartitionCount()) + .equals(partitionId)); + return candidate; + } + + protected void assertMissingRevisionRefusal( + CanonicalGameplayAdmissionAbortCompositionFixture fixture, + byte[] partitionKey, + CanonicalGameplayIssuerPartitionMutation mutation, + String ownerTable, + String ownerIdColumn, + UUID ownerOperationId, + LuaInvocation exactInvocation, + Runnable ordinaryOwnerCall) { + byte[] beforeFault = physicalFieldSet(partitionKey); + assertThat(decodeFields(beforeFault)) + .containsKey(CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD); + String pendingCustodyBefore = + pendingMutationCustodyImage( + fixture.dsl(), mutation, ownerTable, ownerIdColumn, ownerOperationId); + + byte[] revisionField = + CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD.getBytes( + StandardCharsets.US_ASCII); + byte[][] revisionFields = {revisionField}; + assertThat(administratorCommands.hdel(partitionKey, revisionFields)).isEqualTo(1L); + byte[] afterInjectedAbsence = physicalFieldSet(partitionKey); + assertThat(decodeFields(afterInjectedAbsence)) + .doesNotContainKey(CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD); + assertThat( + pendingMutationCustodyImage( + fixture.dsl(), mutation, ownerTable, ownerIdColumn, ownerOperationId)) + .isEqualTo(pendingCustodyBefore); + + assertThat(evaluate(exactInvocation)).isNegative(); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(afterInjectedAbsence); + assertThatThrownBy(ordinaryOwnerCall::run).isInstanceOf(IllegalStateException.class); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(afterInjectedAbsence); + assertThat(administratorCommands.hget(partitionKey, revisionField)).isNull(); + assertThat( + pendingMutationCustodyImage( + fixture.dsl(), mutation, ownerTable, ownerIdColumn, ownerOperationId)) + .isEqualTo(pendingCustodyBefore); + } + + protected static String pendingMutationCustodyImage( + DSLContext dsl, + CanonicalGameplayIssuerPartitionMutation mutation, + String ownerTable, + String ownerIdColumn, + UUID ownerOperationId) { + String sql = + "SELECT jsonb_build_object(" + + "'head', (SELECT to_jsonb(head) FROM " + + CanonicalGameplayIssuerPartitionMutationRepository.HEAD_TABLE + + " head WHERE head.issuer_id = ? AND head.partition_id = ?)," + + "'mutation', (SELECT to_jsonb(mutation) FROM " + + "game_session_canonical_issuer_partition_mutation" + + " mutation WHERE mutation.mutation_id = ?)," + + "'owner', (SELECT to_jsonb(owner_row) FROM " + + ownerTable + + " owner_row WHERE owner_row." + + ownerIdColumn + + " = ?))::text"; + return dsl.fetchSingle( + sql, + GameSessionAccountDelegationProfile.ISSUER, + mutation.partitionId(), + mutation.mutationId(), + ownerOperationId) + .get(0, String.class); + } + + protected static String localOperationImage(DSLContext dsl, UUID operationId) { + return dsl.fetchSingle( + "SELECT to_jsonb(operation)::text FROM" + + " game_session_canonical_issuer_binding_local_operation operation" + + " WHERE operation.operation_id = ?", + operationId) + .get(0, String.class); + } + + protected static String partitionHeadImage(DSLContext dsl, BigInteger partitionId) { + return dsl.fetchSingle( + "SELECT to_jsonb(head)::text FROM " + + CanonicalGameplayIssuerPartitionMutationRepository.HEAD_TABLE + + " head WHERE head.issuer_id = ? AND head.partition_id = ?", + GameSessionAccountDelegationProfile.ISSUER, + partitionId) + .get(0, String.class); + } + + protected void assertOuterBootstrapRetryIsReadOnly( + CanonicalGameplayAdmissionAbortCompositionFixture fixture, byte[] partitionKey) { + byte[] physicalBefore = physicalFieldSet(partitionKey); + String revisionBefore = partitionHeadImage(fixture.dsl(), fixture.originalPartitionId()); + String anchorAndProofsBefore = anchorAndPartitionProofImage(fixture.dsl()); + byte[] originalAnchorBytes = + fixture + .dsl() + .fetchSingle( + "SELECT exact_anchor_bytes FROM" + + " game_session_canonical_issuer_binding_local_operation" + + " WHERE operation_id = ?", + fixture.originalOperationId()) + .get(0, byte[].class); + + var retriedAnchor = fixture.retryOriginalIssuerBootstrap(); + + assertThat(retriedAnchor.exactAnchorBytes()).containsExactly(originalAnchorBytes); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(physicalBefore); + assertThat(partitionHeadImage(fixture.dsl(), fixture.originalPartitionId())) + .isEqualTo(revisionBefore); + assertThat(anchorAndPartitionProofImage(fixture.dsl())).isEqualTo(anchorAndProofsBefore); + } + + protected static String anchorAndPartitionProofImage(DSLContext dsl) { + return dsl.fetchSingle( + "SELECT jsonb_build_object(" + + "'anchors', COALESCE((SELECT jsonb_agg(to_jsonb(anchor)" + + " ORDER BY anchor.issuer_id) FROM" + + " game_session_canonical_issuer_installed_anchor anchor), '[]'::jsonb)," + + "'partitionProofs', COALESCE((SELECT jsonb_agg(to_jsonb(proof)" + + " ORDER BY proof.issuer_id, proof.partition_id) FROM" + + " game_session_canonical_issuer_bootstrap_partition_proof proof), '[]'::jsonb)" + + ")::text") + .get(0, String.class); + } + + protected static UUID insertUnaccountedCurrentReservation( + CanonicalGameplayAdmissionAbortCompositionFixture fixture, + String sourceSeed, + BigInteger partitionId) { + // This row is deliberate run-owned SQL drift: it has no transition or local owner operation. + // The ordinary projection must detect that missing accounting and make no Redis change. + var source = fixture.otherOperation(sourceSeed).memberValue(); + var owner = source.owner(); + var reservation = source.reservation(); + String sessionId; + CanonicalGameplayBindingRef bindingRef; + do { + sessionId = UUID.randomUUID().toString(); + bindingRef = + CanonicalGameplayBindingRef.of(owner.tenantId(), owner.gameInstanceId(), sessionId); + } while (!bindingRef.partitionId(owner.issuerIndexPartitionCount()).equals(partitionId)); + UUID reservationId = UUID.randomUUID(); + fixture + .dsl() + .execute( + "INSERT INTO game_session_canonical_issuer_partition_reservation" + + " (reservation_id, binding_ref, account_id, tenant_id, game_instance_id," + + " runtime_game_instance_id, session_id, binding_generation, transition_id, issuer_id," + + " issuer_auth_generation, playable_state_namespace_id, character_id," + + " playable_state_scope, region_id, region_epoch, partition_id," + + " issuer_index_layout_version, issuer_index_partition_count," + + " issuer_index_partition_capacity, lifecycle, reservation_fence," + + " issuer_coverage_operation_id, issuer_coverage_operation_fence, coverage_fence," + + " inventory_snapshot_revision, inventory_revision)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + + " ?, ?, ?, ?, ?, ?, ?)", + reservationId, + bindingRef.bytes(), + owner.accountId(), + owner.tenantId(), + owner.gameInstanceId(), + owner.runtimeGameInstanceId(), + sessionId, + source.bindingGeneration(), + UUID.randomUUID(), + owner.issuerId(), + owner.issuerAuthGeneration(), + owner.playableStateNamespaceId(), + UUID.randomUUID(), + owner.playableStateScope(), + owner.regionId(), + owner.regionEpoch(), + partitionId, + owner.issuerIndexLayoutVersion(), + owner.issuerIndexPartitionCount(), + owner.issuerIndexPartitionCapacity(), + "RESERVED", + UUID.randomUUID(), + UUID.randomUUID(), + reservation.issuerCoverageOperationFence(), + reservation.coverageFence(), + reservation.inventorySnapshotRevision(), + reservation.inventoryRevision()); + return reservationId; + } + + protected static String reservationImage(DSLContext dsl, UUID reservationId) { + return dsl.fetchSingle( + "SELECT to_jsonb(reservation)::text FROM" + + " game_session_canonical_issuer_partition_reservation reservation" + + " WHERE reservation.reservation_id = ?", + reservationId) + .get(0, String.class); + } + + protected static CanonicalGameplayIssuerBindingLocalReleaseOperation + completeReleaseAfterLostReply( + CanonicalGameplayAdmissionAbortCompositionFixture fixture, String seed) { + var pending = + seed == null ? fixture.prepareIssuerRelease() : fixture.prepareIssuerRelease(seed); + assertThatThrownBy(() -> fixture.projectIssuerReleaseAndLoseReply(pending)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("controlled lost issuer release reply"); + var resumed = + seed == null ? fixture.prepareIssuerRelease() : fixture.prepareIssuerRelease(seed); + var recoveredReadback = fixture.projectIssuerRelease(resumed); + assertThat(recoveredReadback.scriptOutcome()).isEqualTo(2L); + return fixture.completeIssuerRelease(resumed, recoveredReadback); + } + + protected static String lifetimeSeed(int index) { + return "lifetime-" + index; + } + + protected static LuaInvocation addInvocation( + CanonicalGameplayAdmissionAbortCompositionFixture fixture, + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work) + throws IOException, ReflectiveOperationException { + return new LuaInvocation( + readScript(CanonicalGameplayIssuerBindingLocalRedisScriptContribution.RESOURCE_PATH), + fixture.issuerPartitionKey(), + scriptArguments( + CanonicalGameplayIssuerBindingLocalRedisOwner.class, + new Class[] { + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork.class + }, + work)); + } + + protected static LuaInvocation releaseInvocation( + CanonicalGameplayAdmissionAbortCompositionFixture fixture, + CanonicalGameplayIssuerBindingLocalReleaseOperation operation) + throws IOException, ReflectiveOperationException { + var work = fixture.readPreparedPartitionWork(operation.originalOperation()); + return new LuaInvocation( + readScript(CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.RESOURCE_PATH), + fixture.issuerPartitionKey(), + scriptArguments( + CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.class, + new Class[] { + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork.class, + CanonicalGameplayIssuerBindingLocalReleaseOperation.class + }, + work, + operation)); + } + + protected static byte[][] scriptArguments( + Class owner, Class[] parameterTypes, Object... arguments) + throws ReflectiveOperationException { + Method method = owner.getDeclaredMethod("scriptArguments", parameterTypes); + if (!method.trySetAccessible()) { + throw new IllegalStateException("Test could not capture the exact owner Lua arguments"); + } + try { + return (byte[][]) method.invoke(null, arguments); + } catch (InvocationTargetException failure) { + Throwable cause = failure.getCause(); + if (cause instanceof RuntimeException runtime) throw runtime; + throw failure; + } + } + + protected static byte[] readScript(String resourcePath) throws IOException { + try (InputStream input = + CanonicalGameplayIssuerLifecycleProofFixtures.class + .getClassLoader() + .getResourceAsStream(resourcePath)) { + if (input == null) throw new IOException("Missing Redis Lua resource: " + resourcePath); + byte[] bytes = input.readAllBytes(); + if (bytes.length == 0) throw new IOException("Empty Redis Lua resource: " + resourcePath); + return bytes; + } + } + + protected Long evaluate(LuaInvocation invocation) { + return administratorCommands.eval( + invocation.script(), + ScriptOutputType.INTEGER, + new byte[][] {invocation.key()}, + invocation.arguments()); + } + + protected void assertStaleLuaRejectedWithoutWrites( + LuaInvocation staleInvocation, byte[] partitionKey) { + byte[] before = physicalFieldSet(partitionKey); + Long outcome = evaluate(staleInvocation); + assertThat(outcome).isNegative(); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(before); + } + + protected byte[] physicalFieldSet(byte[] key) { + Map raw = administratorCommands.hgetall(key); + Map fields = new HashMap<>(); + raw.forEach( + (field, value) -> fields.put(new String(field, StandardCharsets.UTF_8), value.clone())); + return CanonicalGameplayIssuerBootstrapCoverageRepository.encodeFieldSet(fields); + } + + protected static Map decodeFields(byte[] fieldSet) { + return CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet(fieldSet); + } + + protected static long capacityFieldCount(byte[] fieldSet) { + return decodeFields(fieldSet).keySet().stream() + .filter( + field -> + field.startsWith( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec + .RESERVATION_FIELD_PREFIX)) + .count(); + } + + protected static long localOperationCount(DSLContext dsl) { + return dsl.fetchSingle( + "SELECT count(*) FROM game_session_canonical_issuer_binding_local_operation") + .get(0, Long.class); + } + + protected static long partitionMutationCount(DSLContext dsl) { + return dsl.fetchSingle("SELECT count(*) FROM game_session_canonical_issuer_partition_mutation") + .get(0, Long.class); + } + + protected static long releaseCount(DSLContext dsl, String status) { + return dsl.fetchSingle( + "SELECT count(*) FROM game_session_canonical_issuer_binding_local_release_operation" + + " WHERE status = ?", + status) + .get(0, Long.class); + } + + protected static long releaseProofCount(DSLContext dsl) { + return dsl.fetchSingle( + "SELECT count(*) FROM game_session_canonical_issuer_binding_local_release_operation" + + " WHERE status = 'RELEASED' AND physical_readback_field_set_bytes IS NOT NULL" + + " AND completion_inventory_revision > source_inventory_revision") + .get(0, Long.class); + } + + protected static String durableHistoryImage(DSLContext dsl, UUID excludedTransitionId) { + String sql = + "SELECT jsonb_build_object(" + + "'transitions', COALESCE((SELECT jsonb_agg(to_jsonb(entry) ORDER BY entry.transition_id)" + + " FROM game_session_canonical_binding_transition entry WHERE entry.transition_id <> ?), '[]'::jsonb)," + + "'inventory', COALESCE((SELECT jsonb_agg(to_jsonb(entry) ORDER BY entry.binding_ref)" + + " FROM game_session_canonical_gameplay_binding_inventory entry WHERE entry.transition_id <> ?), '[]'::jsonb)," + + "'reservations', COALESCE((SELECT jsonb_agg(to_jsonb(entry) ORDER BY entry.reservation_id)" + + " FROM game_session_canonical_issuer_partition_reservation entry WHERE entry.transition_id <> ?), '[]'::jsonb)," + + "'accountObligations', COALESCE((SELECT jsonb_agg(to_jsonb(entry) ORDER BY entry.transition_id, entry.obligation_ordinal)" + + " FROM game_session_canonical_binding_account_index_obligation entry WHERE entry.transition_id <> ?), '[]'::jsonb)," + + "'issuerObligations', COALESCE((SELECT jsonb_agg(to_jsonb(entry) ORDER BY entry.transition_id, entry.binding_ref)" + + " FROM game_session_canonical_binding_issuer_index_obligation entry WHERE entry.transition_id <> ?), '[]'::jsonb)," + + "'regionObligations', COALESCE((SELECT jsonb_agg(to_jsonb(entry) ORDER BY entry.transition_id)" + + " FROM game_session_canonical_binding_region_bridge_obligation entry WHERE entry.transition_id <> ?), '[]'::jsonb)," + + "'localOperations', COALESCE((SELECT jsonb_agg(to_jsonb(entry) ORDER BY entry.operation_id)" + + " FROM game_session_canonical_issuer_binding_local_operation entry WHERE entry.transition_id <> ?), '[]'::jsonb)," + + "'releases', COALESCE((SELECT jsonb_agg(to_jsonb(entry) ORDER BY entry.operation_id)" + + " FROM game_session_canonical_issuer_binding_local_release_operation entry WHERE entry.transition_id <> ?), '[]'::jsonb)," + + "'mutations', COALESCE((SELECT jsonb_agg(to_jsonb(mutation) ORDER BY mutation.mutation_id)" + + " FROM game_session_canonical_issuer_partition_mutation mutation WHERE mutation.owner_operation_id IN (" + + " SELECT local_operation.operation_id FROM game_session_canonical_issuer_binding_local_operation local_operation WHERE local_operation.transition_id <> ?" + + " UNION SELECT release_entry.operation_id FROM game_session_canonical_issuer_binding_local_release_operation release_entry WHERE release_entry.transition_id <> ?)), '[]'::jsonb)" + + ")::text"; + return dsl.fetchSingle( + sql, + excludedTransitionId, + excludedTransitionId, + excludedTransitionId, + excludedTransitionId, + excludedTransitionId, + excludedTransitionId, + excludedTransitionId, + excludedTransitionId, + excludedTransitionId, + excludedTransitionId) + .get(0, String.class); + } + + protected static UUID uuid(String seed) { + return UUID.nameUUIDFromBytes(seed.getBytes(StandardCharsets.UTF_8)); + } + + protected record LuaInvocation(byte[] script, byte[] key, byte[][] arguments) { + protected LuaInvocation { + script = script.clone(); + key = key.clone(); + arguments = Arrays.stream(arguments).map(byte[]::clone).toArray(byte[][]::new); + } + + @Override + public byte[] script() { + return script.clone(); + } + + @Override + public byte[] key() { + return key.clone(); + } + + @Override + public byte[][] arguments() { + return Arrays.stream(arguments).map(byte[]::clone).toArray(byte[][]::new); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLocalCapacityIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLocalCapacityIntegrationTest.java new file mode 100644 index 0000000000..c07b6a9b80 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLocalCapacityIntegrationTest.java @@ -0,0 +1,486 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Actual PostgreSQL/Redis proof for local issuer capacity, ordinary ADD, and release boundaries. + * Account control, abort, lease, and source collaborators remain controlled; Game Session owns + * durable preparation, physical projection, readback, and release completion. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@Execution(ExecutionMode.SAME_THREAD) +class CanonicalGameplayIssuerLocalCapacityIntegrationTest + extends CanonicalGameplayIssuerLifecycleProofFixtures { + @Test + void unrelatedAccountNewAndOriginalIssuerCleanupSurviveAccountControlAdvance() { + try (var fixture = newFixture(BigInteger.valueOf(11), BigInteger.ONE, 0)) { + byte[] partitionKey = fixture.issuerPartitionKey(); + fixture.publishOriginalWithControlledAccountLease(); + var abort = fixture.recordOriginalAccountAbort(); + assertThat(abort.isAccountAborted()).isTrue(); + + String staleAccountASeed = "account-a-stale-add-after-control-advance"; + fixture.prepareOtherControllerNew(staleAccountASeed); + CanonicalGameplayIssuerMemberV2Value originalMember = + CanonicalGameplayIssuerMemberV2Codec.decode(fixture.originalMemberValueBytes()); + CanonicalGameplayBindingIdentity accountA = originalMember.owner(); + + var intent = + new CanonicalGameplayAccountAdmissionBarrierRepository(fixture.dsl()) + .beginFenceIntent(accountA.accountId(), uuid("account-a-control-advance")); + assertThat(intent).isNotNull(); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT state FROM game_session_canonical_account_coverage_control" + + " WHERE account_id = ?", + accountA.accountId()) + .get(0, String.class)) + .isEqualTo("ACQUISITION_INTENT"); + + var inventoryRepository = new CanonicalGameplayBindingInventoryRepository(fixture.dsl()); + String historyBeforeAbortRetry = durableHistoryImage(fixture.dsl(), NIL_UUID); + String retainedRowsBeforeAbortRetry = fixture.retainedFirstNewAbortRowsImage(); + byte[] fieldsBeforeAbortRetry = physicalFieldSet(partitionKey); + String controlRowsSql = + "SELECT jsonb_build_object(" + + "'clock', (SELECT to_jsonb(clock) FROM game_session_canonical_binding_inventory_clock clock WHERE singleton_id = 1)," + + " 'accountControl', (SELECT to_jsonb(control) FROM game_session_canonical_account_coverage_control control WHERE account_id = ?)," + + " 'issuerControl', (SELECT to_jsonb(control) FROM game_session_canonical_issuer_layout_bootstrap_control control WHERE issuer_id = ?))::text"; + String controlRowsBeforeAbortRetry = + fixture + .dsl() + .fetchSingle(controlRowsSql, accountA.accountId(), accountA.issuerId()) + .get(0, String.class); + Runnable assertAbortRetryUnchanged = + () -> { + assertThat(durableHistoryImage(fixture.dsl(), NIL_UUID)) + .isEqualTo(historyBeforeAbortRetry); + assertThat(fixture.retainedFirstNewAbortRowsImage()) + .isEqualTo(retainedRowsBeforeAbortRetry); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(fieldsBeforeAbortRetry); + assertThat( + fixture + .dsl() + .fetchSingle(controlRowsSql, accountA.accountId(), accountA.issuerId()) + .get(0, String.class)) + .isEqualTo(controlRowsBeforeAbortRetry); + }; + + // Exact terminal retries retain their original provenance after the real Account intent. + var abortRetry = + inventoryRepository.recordFirstNewAccountAbort(abort, abort.orphanCleanupId()); + assertThat(abortRetry.transition()).isEqualTo(abort.transition()); + assertThat(abortRetry.candidate()).isEqualTo(abort.candidate()); + assertThat(abortRetry.reservation()).isEqualTo(abort.reservation()); + assertThat(abortRetry.originalDecision().leaseEvidenceJson()) + .isEqualTo(abort.originalDecision().leaseEvidenceJson()); + assertThat(abortRetry.orphanCleanupId()).isEqualTo(abort.orphanCleanupId()); + assertAbortRetryUnchanged.run(); + + var candidate = abort.candidate(); + var changedCandidate = + new CanonicalGameplayBindingInventoryEntry( + candidate.identity(), + candidate.bindingRef(), + candidate.bindingGeneration(), + candidate.accountIndexFence(), + candidate.issuerReservationId(), + candidate.transitionId(), + candidate.lifecycle(), + candidate.accountIndexState(), + candidate.issuerIndexState() + == CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED + ? CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED + : CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED, + candidate.inventoryRevision()); + var reservation = abort.reservation(); + var changedReservation = + new CanonicalIssuerPartitionReservation( + reservation.reservationId(), + reservation.owner(), + reservation.bindingGeneration(), + reservation.transitionId(), + reservation.partitionId(), + reservation.lifecycle(), + reservation.reservationFence(), + reservation.issuerCoverageOperationId(), + reservation.issuerCoverageOperationFence(), + reservation.coverageFence().add(BigInteger.ONE), + reservation.inventorySnapshotRevision(), + reservation.inventoryRevision()); + // Shape-valid caller objects exercise the SQL comparison; no stored evidence is changed. + for (var changedSource : + List.of( + new CanonicalGameplayAdmissionAbortSource( + abort.transition(), + abort.candidate(), + abort.reservation(), + abort.originalDecision(), + UUID.randomUUID()), + new CanonicalGameplayAdmissionAbortSource( + abort.transition(), + changedCandidate, + abort.reservation(), + abort.originalDecision(), + abort.orphanCleanupId()), + new CanonicalGameplayAdmissionAbortSource( + abort.transition(), + abort.candidate(), + changedReservation, + abort.originalDecision(), + abort.orphanCleanupId()))) { + assertThatThrownBy( + () -> + inventoryRepository.recordFirstNewAccountAbort( + changedSource, changedSource.orphanCleanupId())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("Retained first-NEW abort source changed during exact retry"); + assertAbortRetryUnchanged.run(); + } + assertThat( + inventoryRepository + .recordFirstNewAccountAbort(abort, abort.orphanCleanupId()) + .orphanCleanupId()) + .isEqualTo(abort.orphanCleanupId()); + assertAbortRetryUnchanged.run(); + + byte[] beforeStaleAdd = physicalFieldSet(partitionKey); + long mutationsBeforeStaleAdd = partitionMutationCount(fixture.dsl()); + assertThatThrownBy(() -> fixture.projectOtherControllerNew(staleAccountASeed)) + .isInstanceOf(IllegalStateException.class); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeStaleAdd); + assertThat(partitionMutationCount(fixture.dsl())).isEqualTo(mutationsBeforeStaleAdd); + + CanonicalGameplayBindingIdentity accountB = + otherAccountInPartition(accountA, fixture.originalPartitionId()); + var currentIssuerState = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + originalMember.sourceCheckpoint(), originalMember.incarnation()); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + issuerStateSource = () -> currentIssuerState; + var accountBOperation = + new CanonicalGameplayIssuerBindingLocalOperationRepository( + fixture.dsl(), issuerStateSource) + .beginOrResumeOrdinaryNew( + new CanonicalGameplayIssuerBindingLocalOperation.Request( + UUID.randomUUID(), UUID.randomUUID(), accountB, null, null)); + var localProjection = + new CanonicalGameplayIssuerBindingLocalProjectionRepository( + fixture.dsl(), issuerStateSource); + var accountBOwner = + new CanonicalGameplayIssuerBindingLocalRedisOwner( + issuerOwner, + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayIssuerBindingLocalRedisScriptContribution())), + localProjection, + issuerStateSource); + var accountBAdd = accountBOwner.projectAndRead(accountBOperation); + assertThat(accountBAdd.scriptOutcome()).isEqualTo(1L); + + String accountBCapacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + accountBOperation.reservation().reservationId()); + String accountBBindingField = + new String( + accountBOperation.memberValue().owner().bindingRef().bytes(), StandardCharsets.UTF_8); + var accountBFields = decodeFields(physicalFieldSet(partitionKey)); + assertThat(accountBFields) + .containsEntry(accountBCapacityField, accountBOperation.exactMemberValueBytes()) + .doesNotContainKey(accountBBindingField); + assertThat(localOperationCount(fixture.dsl())).isEqualTo(3L); + + var pendingRelease = fixture.prepareIssuerRelease(); + var releaseReadback = fixture.projectIssuerRelease(pendingRelease); + var release = fixture.completeIssuerRelease(pendingRelease, releaseReadback); + assertThat(release.status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); + var releaseRetry = fixture.prepareIssuerRelease(); + assertThat(releaseRetry.operationId()).isEqualTo(release.operationId()); + assertThat(fixture.projectIssuerRelease(releaseRetry).exactPhysicalFieldSetBytes()) + .isEqualTo(release.exactPhysicalReadbackFieldSetBytes()); + } + } + + @Test + void addCurrentnessRereadKeepsTheTargetAccountControlFenceWithoutPreparingAnotherMutation() { + try (var fixture = newFixture(BigInteger.valueOf(12), BigInteger.ONE, 0)) { + String seed = "add-currentness-account-control-reread"; + fixture.prepareOtherControllerNew(seed); + var preparedAdd = fixture.prepareOtherAddMutation(seed); + byte[] partitionKey = fixture.issuerPartitionKey(); + byte[] fieldsBeforeReread = physicalFieldSet(partitionKey); + long mutationsBeforeReread = partitionMutationCount(fixture.dsl()); + CanonicalGameplayIssuerMemberV2Value originalMember = + CanonicalGameplayIssuerMemberV2Codec.decode(fixture.originalMemberValueBytes()); + var currentIssuerState = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + originalMember.sourceCheckpoint(), originalMember.incarnation()); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + issuerStateSource = () -> currentIssuerState; + + new CanonicalGameplayAccountAdmissionBarrierRepository(fixture.dsl()) + .beginFenceIntent( + originalMember.owner().accountId(), uuid("add-currentness-account-fence")); + + assertThatThrownBy( + () -> + new CanonicalGameplayIssuerBindingLocalProjectionRepository( + fixture.dsl(), issuerStateSource) + .requireStillCurrent(preparedAdd)) + .isInstanceOf(IllegalStateException.class); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(fieldsBeforeReread); + assertThat(partitionMutationCount(fixture.dsl())).isEqualTo(mutationsBeforeReread); + } + } + + @Test + void refusesRegistrationBeyondTheCurrentLocalEntryBoundWithoutWrites() { + try (var fixture = + newFixture(BigInteger.valueOf(9), BigInteger.ONE, BigInteger.valueOf(512), 0)) { + for (int index = 1; index < PARTITION_CAPACITY.intValueExact(); index++) { + fixture.prepareOtherControllerNew("local-entry-bound-" + index); + } + + assertThat(localOperationCount(fixture.dsl())).isEqualTo(256L); + var currentWork = fixture.readCurrentOriginalPartitionWork(); + assertThat(currentWork.localEntries()).hasSize(256); + + byte[] fieldsBeforeRefusal = physicalFieldSet(fixture.issuerPartitionKey()); + long mutationCountBeforeRefusal = partitionMutationCount(fixture.dsl()); + String sourceImageBeforeRefusal = durableHistoryImage(fixture.dsl(), NIL_UUID); + assertThatThrownBy(() -> fixture.prepareOtherControllerNew("local-entry-bound-257")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("The local partition operation set has reached the physical owner bound"); + assertThat(durableHistoryImage(fixture.dsl(), NIL_UUID)).isEqualTo(sourceImageBeforeRefusal); + assertThat(localOperationCount(fixture.dsl())).isEqualTo(256L); + assertThat(partitionMutationCount(fixture.dsl())).isEqualTo(mutationCountBeforeRefusal); + assertThat(physicalFieldSet(fixture.issuerPartitionKey())).isEqualTo(fieldsBeforeRefusal); + } + } + + @Test + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "VA_PRIMITIVE_ARRAY_PASSED_TO_OBJECT_VARARG", + justification = + "RedisCommands takes binary field keys; byte[][] supplies one field. Native deletion and readback verify the exact semantics.") + void completedAddRetryReadsReleasedZeroCapacityStateWithoutWritesAndRejectsPhysicalDrift() { + try (var fixture = newFixture(BigInteger.valueOf(16), BigInteger.ONE, 0)) { + String capacityAddSql = + "SELECT to_jsonb(mutation)::text FROM game_session_canonical_issuer_partition_mutation mutation" + + " WHERE mutation_kind = 'ADD_CAPACITY' AND owner_operation_id = ?"; + String originalCapacityAddReceipt = + fixture + .dsl() + .fetchSingle(capacityAddSql, fixture.originalOperationId()) + .get(0, String.class); + fixture.publishOriginalWithControlledAccountLease(); + assertThat(fixture.recordOriginalAccountAbort().isAccountAborted()).isTrue(); + var pendingRelease = fixture.prepareIssuerRelease(); + var released = + fixture.completeIssuerRelease( + pendingRelease, fixture.projectIssuerRelease(pendingRelease)); + assertThat(released.status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); + var originalMember = + CanonicalGameplayIssuerMemberV2Codec.decode(fixture.originalMemberValueBytes()); + var current = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + originalMember.sourceCheckpoint(), originalMember.incarnation()); + var projectionRepository = + new CanonicalGameplayIssuerBindingLocalProjectionRepository(fixture.dsl(), () -> current); + var originalOperation = released.originalOperation(); + var work = projectionRepository.readPreparedPartitionWork(originalOperation); + assertThat(work.baselineProof().physicalCountedCapacityCount()).isZero(); + assertThat(work.targetEntry().countsTowardCapacity()).isFalse(); + assertThat(work.partitionCapacity()).isZero(); + assertThat(work.aggregateCapacity()).isZero(); + var owner = + new CanonicalGameplayIssuerBindingLocalRedisOwner( + issuerOwner, + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayIssuerBindingLocalRedisScriptContribution())), + projectionRepository, + () -> current); + byte[] partitionKey = fixture.issuerPartitionKey(); + byte[] releasedFields = physicalFieldSet(partitionKey); + assertThat(capacityFieldCount(releasedFields)).isEqualTo(1L); + String releasedCapacityName = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + released.releasedMemberValue().reservation().reservationId()); + assertThat(decodeFields(releasedFields)) + .containsEntry(releasedCapacityName, released.exactReleasedMemberValueBytes()); + String historyBefore = durableHistoryImage(fixture.dsl(), NIL_UUID); + String headBefore = partitionHeadImage(fixture.dsl(), fixture.originalPartitionId()); + String anchorBefore = anchorAndPartitionProofImage(fixture.dsl()); + String retainedBefore = fixture.retainedFirstNewAbortRowsImage(); + Runnable assertSqlUnchanged = + () -> { + assertThat( + fixture + .dsl() + .fetchSingle(capacityAddSql, fixture.originalOperationId()) + .get(0, String.class)) + .isEqualTo(originalCapacityAddReceipt); + assertThat(durableHistoryImage(fixture.dsl(), NIL_UUID)).isEqualTo(historyBefore); + assertThat(partitionHeadImage(fixture.dsl(), fixture.originalPartitionId())) + .isEqualTo(headBefore); + assertThat(anchorAndPartitionProofImage(fixture.dsl())).isEqualTo(anchorBefore); + assertThat(fixture.retainedFirstNewAbortRowsImage()).isEqualTo(retainedBefore); + }; + var retry = owner.projectAndRead(originalOperation); + assertThat(retry.scriptOutcome()).isEqualTo(3L); + assertThat(retry.exactReadbackBytes()).containsExactly(releasedFields); + assertThat(physicalFieldSet(partitionKey)).containsExactly(releasedFields); + assertSqlUnchanged.run(); + + byte[] capacityField = releasedCapacityName.getBytes(StandardCharsets.US_ASCII); + byte[] revisionField = + CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD.getBytes( + StandardCharsets.US_ASCII); + // Administrator-injected absence and conflicting bytes remain non-admitting on read-only + // retry. + for (byte[] field : List.of(capacityField, revisionField)) { + byte[] originalValue = + java.util.Objects.requireNonNull( + administratorCommands.hget(partitionKey, field), + "Expected original released field"); + for (boolean missing : List.of(true, false)) { + if (missing) administratorCommands.hdel(partitionKey, new byte[][] {field}); + else + administratorCommands.hset( + partitionKey, + field, + (Arrays.equals(field, revisionField) + ? UUID.randomUUID().toString() + : "changed-release-field") + .getBytes(StandardCharsets.US_ASCII)); + byte[] injectedFields = physicalFieldSet(partitionKey); + assertThatThrownBy(() -> owner.projectAndRead(originalOperation)) + .isInstanceOf(IllegalStateException.class); + assertThat(physicalFieldSet(partitionKey)).containsExactly(injectedFields); + assertSqlUnchanged.run(); + administratorCommands.hset(partitionKey, field, originalValue); + assertThat(physicalFieldSet(partitionKey)).containsExactly(releasedFields); + } + } + assertThat(owner.projectAndRead(originalOperation).scriptOutcome()).isEqualTo(3L); + assertThat(physicalFieldSet(partitionKey)).containsExactly(releasedFields); + assertSqlUnchanged.run(); + } + } + + @Test + void ordinaryAddRefusesMissingPartitionRevisionWithoutRedisOrSqlWrites() throws Exception { + try (var fixture = newFixture(BigInteger.valueOf(4), BigInteger.ONE, 0)) { + String seed = "missing-revision-add"; + fixture.prepareOtherControllerNew(seed); + var work = fixture.prepareOtherAddMutation(seed); + var mutation = work.physicalMutation(); + assertMissingRevisionRefusal( + fixture, + fixture.issuerPartitionKey(), + mutation, + "game_session_canonical_issuer_binding_local_operation", + "operation_id", + fixture.otherOperation(seed).operationId(), + addInvocation(fixture, work), + () -> fixture.projectOtherControllerNew(seed)); + } + } + + @Test + void ordinaryReleaseRefusesMissingPartitionRevisionWithoutRedisOrSqlWrites() throws Exception { + try (var fixture = newFixture(BigInteger.valueOf(5), BigInteger.ONE, 0)) { + fixture.publishOriginalWithControlledAccountLease(); + assertThat(fixture.recordOriginalAccountAbort().isAccountAborted()).isTrue(); + var pendingRelease = fixture.prepareIssuerRelease(); + assertMissingRevisionRefusal( + fixture, + fixture.issuerPartitionKey(), + pendingRelease.physicalMutation(), + "game_session_canonical_issuer_binding_local_release_operation", + "operation_id", + pendingRelease.operationId(), + releaseInvocation(fixture, pendingRelease), + () -> fixture.projectIssuerRelease(pendingRelease)); + } + } + + @Test + void actualReleaseReadbackPersistsAndReloadsWithMoreThan513PhysicalFields() throws Exception { + try (var fixture = newFixture(BigInteger.valueOf(8), BigInteger.ONE, 250)) { + assertThat(fixture.originalBaselineReservationCount()).isEqualTo(250); + assertThat(fixture.originalBaselineCountedCapacity()).isEqualTo(250); + assertThat(fixture.originalBaselineBindingCount()).isEqualTo(250); + fixture.publishOriginalWithControlledAccountLease(); + for (int index = 0; index < 4; index++) { + String seed = "wide-active-" + index; + fixture.prepareOtherControllerNew(seed); + fixture.projectOtherControllerNew(seed); + fixture.publishOtherControllerNew(seed); + } + + String terminalSeed = "wide-retained-terminal"; + fixture.prepareOtherControllerNew(terminalSeed); + fixture.projectOtherControllerNew(terminalSeed); + fixture.publishOtherControllerNew(terminalSeed); + assertThat(fixture.recordOtherAccountAbort(terminalSeed).isAccountAborted()).isTrue(); + var terminalRelease = fixture.prepareIssuerRelease(terminalSeed); + var terminalReadback = fixture.projectIssuerRelease(terminalRelease); + assertThat(fixture.completeIssuerRelease(terminalRelease, terminalReadback).status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); + + String wideReleaseSeed = "wide-release-readback"; + UUID wideOperationId = fixture.prepareOtherControllerNew(wideReleaseSeed); + var pendingAdd = fixture.prepareOtherAddMutation(wideReleaseSeed); + assertThat(pendingAdd.aggregateCapacity()).isEqualTo(PARTITION_CAPACITY); + assertThat(fixture.projectOtherControllerNew(wideReleaseSeed).scriptOutcome()).isEqualTo(1L); + fixture.publishOtherControllerNew(wideReleaseSeed); + assertThat(fixture.recordOtherAccountAbort(wideReleaseSeed).isAccountAborted()).isTrue(); + + var pendingRelease = fixture.prepareIssuerRelease(wideReleaseSeed); + var actualReadback = fixture.projectIssuerRelease(pendingRelease); + assertThat(actualReadback.scriptOutcome()).isEqualTo(1L); + assertThat(decodeFields(actualReadback.exactPhysicalFieldSetBytes()).size()).isEqualTo(514); + var completedRelease = fixture.completeIssuerRelease(pendingRelease, actualReadback); + assertThat(completedRelease.status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); + assertThat(completedRelease.exactPhysicalReadbackFieldSetBytes()) + .isEqualTo(actualReadback.exactPhysicalFieldSetBytes()); + + var reloadedRelease = fixture.prepareIssuerRelease(wideReleaseSeed); + assertThat(reloadedRelease.operationId()).isEqualTo(pendingRelease.operationId()); + assertThat(reloadedRelease.exactPhysicalReadbackFieldSetBytes()) + .isEqualTo(actualReadback.exactPhysicalFieldSetBytes()); + var completedRetry = fixture.projectIssuerRelease(reloadedRelease); + assertThat(completedRetry.scriptOutcome()).isEqualTo(2L); + assertThat(completedRetry.exactPhysicalFieldSetBytes()) + .isEqualTo(actualReadback.exactPhysicalFieldSetBytes()); + assertThat(physicalFieldSet(fixture.issuerPartitionKey())) + .isEqualTo(actualReadback.exactPhysicalFieldSetBytes()); + assertThat(localOperationCount(fixture.dsl())).isEqualTo(7L); + assertThat(releaseCount(fixture.dsl(), "RELEASED")).isEqualTo(2L); + assertThat(wideOperationId).isEqualTo(pendingRelease.originalOperationId()); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java deleted file mode 100644 index 121cb98d5e..0000000000 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java +++ /dev/null @@ -1,1641 +0,0 @@ -package net.firedevops.firemud.gamesession.repository; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import io.lettuce.core.AclSetuserArgs; -import io.lettuce.core.ClientOptions; -import io.lettuce.core.RedisClient; -import io.lettuce.core.RedisURI; -import io.lettuce.core.ScriptOutputType; -import io.lettuce.core.api.StatefulRedisConnection; -import io.lettuce.core.api.sync.RedisCommands; -import io.lettuce.core.codec.ByteArrayCodec; -import io.lettuce.core.protocol.CommandKeyword; -import io.lettuce.core.protocol.CommandType; -import io.lettuce.core.protocol.ProtocolVersion; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.math.BigInteger; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; -import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; -import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; -import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; -import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution; -import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution; -import net.firedevops.firemud.test.TestContainerImages; -import org.jooq.DSLContext; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.containers.PostgreSQLContainer; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; - -/** - * Actual PostgreSQL/Redis proof of bounded original-operation issuer capacity retirement. Account - * lease and abort inputs, launch target, issuer checkpoint, and incarnation remain controlled; Game - * Session prepares, projects, releases, retires, and reads back every state. - */ -@Testcontainers(disabledWithoutDocker = true) -@SuppressWarnings("resource") -@Execution(ExecutionMode.SAME_THREAD) -class CanonicalGameplayIssuerPhysicalRetirementIntegrationTest { - private static final String OWNER_PRINCIPAL = "gamesession_coord_app"; - private static final String ISSUER_KEY_PREFIX = "session:game:index:issuer:"; - private static final BigInteger PARTITION_CAPACITY = BigInteger.valueOf(256); - private static final UUID NIL_UUID = new UUID(0L, 0L); - - @Container - private static final PostgreSQLContainer POSTGRES = - new PostgreSQLContainer<>(TestContainerImages.postgres()); - - @Container - private static final GenericContainer REDIS = - new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); - - private RedisClient administrator; - private RedisClient issuerOwner; - private StatefulRedisConnection administratorConnection; - private RedisCommands administratorCommands; - - @BeforeEach - void setUp() { - String password = UUID.randomUUID().toString(); - administrator = createRedisClient(null, null); - administratorConnection = administrator.connect(ByteArrayCodec.INSTANCE); - administratorCommands = administratorConnection.sync(); - administratorCommands.aclSetuser( - OWNER_PRINCIPAL, - new AclSetuserArgs() - .reset() - .on() - .addPassword(password) - .keyPattern(ISSUER_KEY_PREFIX + "*") - .addCommand(CommandType.HELLO) - .addCommand(CommandType.PING) - .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) - .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) - .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) - .addCommand(CommandType.EVALSHA) - .addCommand(CommandType.TYPE) - .addCommand(CommandType.PTTL) - .addCommand(CommandType.HGET) - .addCommand(CommandType.HLEN) - .addCommand(CommandType.HGETALL) - .addCommand(CommandType.HSET) - .addCommand(CommandType.HDEL)); - issuerOwner = createRedisClient(OWNER_PRINCIPAL, password); - } - - @AfterEach - void tearDown() { - if (administratorConnection != null) administratorConnection.close(); - if (issuerOwner != null) issuerOwner.shutdown(Duration.ZERO, Duration.ofSeconds(2)); - if (administrator != null) administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); - } - - @Test - void retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound() throws Exception { - try (var fixture = newFixture()) { - byte[] partitionKey = fixture.issuerPartitionKey(); - byte[] initialFields = physicalFieldSet(partitionKey); - int baselineFieldCount = - fixture.originalBaselineReservationCount() + fixture.originalBaselineBindingCount(); - assertThat(decodeFields(initialFields).size()).isEqualTo(baselineFieldCount + 3); - - fixture.publishOriginalWithControlledAccountLease(); - var originalAbort = fixture.recordOriginalAccountAbort(); - assertThat(originalAbort.isAccountAborted()).isTrue(); - - byte[] beforePrematureRetirement = physicalFieldSet(partitionKey); - String historyBeforePrematureRetirement = durableHistoryImage(fixture.dsl(), NIL_UUID); - String headBeforePrematureRetirement = - partitionHeadImage(fixture.dsl(), fixture.originalPartitionId()); - String inventoryClockBeforePrematureRetirement = - fixture - .dsl() - .fetchSingle( - "SELECT to_jsonb(clock)::text FROM" - + " game_session_canonical_binding_inventory_clock clock" - + " WHERE singleton_id = 1") - .get(0, String.class); - long releasesBeforePrematureRetirement = - fixture - .dsl() - .fetchSingle( - "SELECT count(*) FROM" - + " game_session_canonical_issuer_binding_local_release_operation") - .get(0, Long.class); - long mutationsBeforePrematureRetirement = partitionMutationCount(fixture.dsl()); - assertThatThrownBy(() -> fixture.prepareIssuerRetirement(fixture.transitionId())) - .isInstanceOf(IllegalStateException.class); - assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforePrematureRetirement); - assertThat(durableHistoryImage(fixture.dsl(), NIL_UUID)) - .isEqualTo(historyBeforePrematureRetirement); - assertThat(partitionHeadImage(fixture.dsl(), fixture.originalPartitionId())) - .isEqualTo(headBeforePrematureRetirement); - assertThat( - fixture - .dsl() - .fetchSingle( - "SELECT to_jsonb(clock)::text FROM" - + " game_session_canonical_binding_inventory_clock clock" - + " WHERE singleton_id = 1") - .get(0, String.class)) - .isEqualTo(inventoryClockBeforePrematureRetirement); - assertThat( - fixture - .dsl() - .fetchSingle( - "SELECT count(*) FROM" - + " game_session_canonical_issuer_binding_local_release_operation") - .get(0, Long.class)) - .isEqualTo(releasesBeforePrematureRetirement); - assertThat(partitionMutationCount(fixture.dsl())) - .isEqualTo(mutationsBeforePrematureRetirement); - assertThat(retirementCount(fixture.dsl())).isZero(); - - var originalRelease = completeReleaseAfterLostReply(fixture, null); - - String newerSeed = lifetimeSeed(2); - UUID newerOperationId = fixture.prepareOtherControllerNew(newerSeed); - String neverProjectedSeed = "same-partition-never-projected"; - UUID neverProjectedOperationId = fixture.prepareOtherControllerNew(neverProjectedSeed); - var neverProjectedOperation = fixture.otherOperation(neverProjectedSeed); - var newerOperation = fixture.otherOperation(newerSeed); - assertThat(neverProjectedOperationId).isEqualTo(neverProjectedOperation.operationId()); - assertThat(neverProjectedOperation.reservation().partitionId()) - .isEqualTo(newerOperation.reservation().partitionId()); - String newerCapacityField = - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( - newerOperation.reservation().reservationId()); - String neverProjectedCapacityField = - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( - neverProjectedOperation.reservation().reservationId()); - assertThat(decodeFields(physicalFieldSet(partitionKey))) - .doesNotContainKey(newerCapacityField) - .doesNotContainKey(neverProjectedCapacityField); - var pendingAdd = fixture.prepareOtherAddMutation(newerSeed); - byte[] currentRevisionFieldValue = - pendingAdd - .physicalMutation() - .expectedRevision() - .toString() - .getBytes(StandardCharsets.US_ASCII); - Map staleReadbackFields = - new HashMap<>(decodeFields(physicalFieldSet(partitionKey))); - assertThat( - staleReadbackFields.get( - CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD)) - .containsExactly(currentRevisionFieldValue); - byte[] staleReadback = - CanonicalGameplayIssuerBootstrapCoverageRepository.encodeFieldSet(staleReadbackFields); - String mutationCustodyBeforeStaleReadback = - pendingMutationCustodyImage( - fixture.dsl(), - pendingAdd.physicalMutation(), - "game_session_canonical_issuer_binding_local_operation", - "operation_id", - pendingAdd.physicalMutation().ownerOperationId()); - byte[] partitionBeforeStaleReadback = physicalFieldSet(partitionKey); - assertThatThrownBy( - () -> - fixture - .dsl() - .transactionResult( - configuration -> - CanonicalGameplayIssuerPartitionMutationRepository - .completeInTransaction( - org.jooq.impl.DSL.using(configuration), - pendingAdd.physicalMutation(), - staleReadback))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("exact current physical mutation revision"); - assertThat(physicalFieldSet(partitionKey)).isEqualTo(partitionBeforeStaleReadback); - assertThat( - pendingMutationCustodyImage( - fixture.dsl(), - pendingAdd.physicalMutation(), - "game_session_canonical_issuer_binding_local_operation", - "operation_id", - pendingAdd.physicalMutation().ownerOperationId())) - .isEqualTo(mutationCustodyBeforeStaleReadback); - - LuaInvocation staleAddInvocation = addInvocation(fixture, pendingAdd); - var addReadback = fixture.projectOtherControllerNew(newerSeed); - assertThat(addReadback.scriptOutcome()).isEqualTo(1L); - var addFields = decodeFields(addReadback.exactReadbackBytes()); - assertThat(addFields) - .containsEntry(newerCapacityField, newerOperation.exactMemberValueBytes()); - assertThat(addFields) - .doesNotContainKey( - new String( - newerOperation.memberValue().owner().bindingRef().bytes(), - StandardCharsets.UTF_8)); - assertThat(addFields).doesNotContainKey(neverProjectedCapacityField); - assertThat(addFields) - .doesNotContainKey( - new String( - neverProjectedOperation.memberValue().owner().bindingRef().bytes(), - StandardCharsets.UTF_8)); - assertThat(fixture.retryOtherControllerNew(newerSeed)).isEqualTo(newerOperationId); - byte[] afterAdd = physicalFieldSet(partitionKey); - assertThat(fixture.projectOtherControllerNew(newerSeed).scriptOutcome()).isEqualTo(3L); - assertThat(physicalFieldSet(partitionKey)).isEqualTo(afterAdd); - assertOuterBootstrapRetryIsReadOnly(fixture, partitionKey); - - fixture.publishOtherControllerNew(newerSeed); - assertThat(fixture.recordOtherAccountAbort(newerSeed).isAccountAborted()).isTrue(); - var pendingRelease = fixture.prepareIssuerRelease(newerSeed); - LuaInvocation staleReleaseInvocation = releaseInvocation(fixture, pendingRelease); - var releaseReadback = fixture.projectIssuerRelease(pendingRelease); - var newerRelease = fixture.completeIssuerRelease(pendingRelease, releaseReadback); - assertThat(newerRelease.status()) - .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); - assertOuterBootstrapRetryIsReadOnly(fixture, partitionKey); - assertThat(decodeFields(physicalFieldSet(partitionKey))) - .doesNotContainKey(neverProjectedCapacityField); - byte[] beforeReleaseRetry = physicalFieldSet(partitionKey); - var completedReleaseRetry = fixture.prepareIssuerRelease(newerSeed); - var releaseRetryReadback = fixture.projectIssuerRelease(completedReleaseRetry); - assertThat(releaseRetryReadback.scriptOutcome()).isEqualTo(2L); - assertThat(releaseRetryReadback.exactPhysicalFieldSetBytes()) - .isEqualTo(newerRelease.exactPhysicalReadbackFieldSetBytes()); - assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeReleaseRetry); - - assertThat(releaseCount(fixture.dsl(), "RELEASED")).isEqualTo(2L); - assertThat(retirementCount(fixture.dsl())).isZero(); - byte[] beforeOldestRetirement = physicalFieldSet(partitionKey); - assertThat(capacityFieldCount(beforeOldestRetirement)).isEqualTo(2L); - assertThat(decodeFields(beforeOldestRetirement).size()).isEqualTo(baselineFieldCount + 4); - String historyBeforeOriginalRetirement = durableHistoryImage(fixture.dsl(), NIL_UUID); - - var pendingOldestRetirement = fixture.prepareIssuerRetirement(fixture.transitionId()); - assertThat(pendingOldestRetirement.release().operationId()) - .isEqualTo(originalRelease.operationId()); - assertThat(pendingOldestRetirement.status()) - .isEqualTo( - CanonicalGameplayIssuerBindingLocalRetirementOperation.Status.PENDING_PHYSICAL_PROOF); - LuaInvocation oldestRetirementInvocation = - retirementInvocation(fixture, pendingOldestRetirement); - - long operationCountBeforeBlockedAdmission = localOperationCount(fixture.dsl()); - assertThatThrownBy(() -> fixture.prepareOtherControllerNew("pending-retirement-blocked")) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("same-partition physical mutation is unresolved"); - assertThat(localOperationCount(fixture.dsl())) - .isEqualTo(operationCountBeforeBlockedAdmission); - assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeOldestRetirement); - - fixture.moveIssuerSourceCheckpoint(); - assertThatThrownBy(() -> fixture.retireIssuerCapacity(pendingOldestRetirement)) - .isInstanceOf(IllegalStateException.class); - assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeOldestRetirement); - fixture.restoreIssuerState(); - - byte[] foreignField = "!issuer-test-foreign/v1".getBytes(StandardCharsets.US_ASCII); - byte[] foreignValue = "controlled-foreign-field".getBytes(StandardCharsets.US_ASCII); - byte[][] foreignFields = {foreignField}; - administratorCommands.hset(partitionKey, foreignField, foreignValue); - byte[] fieldsWithForeign = physicalFieldSet(partitionKey); - assertThatThrownBy(() -> fixture.retireIssuerCapacity(pendingOldestRetirement)) - .isInstanceOf(IllegalStateException.class); - assertThat(physicalFieldSet(partitionKey)).isEqualTo(fieldsWithForeign); - administratorCommands.hdel(partitionKey, foreignFields); - assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeOldestRetirement); - - long lostRetirementReply = evaluate(oldestRetirementInvocation); - assertThat(lostRetirementReply).isEqualTo(1L); - byte[] afterUncommittedRetirement = physicalFieldSet(partitionKey); - assertRetirementFieldDelta( - beforeOldestRetirement, afterUncommittedRetirement, pendingOldestRetirement); - assertThat(retirementStatus(fixture.dsl(), pendingOldestRetirement.operationId())) - .isEqualTo("PENDING_PHYSICAL_PROOF"); - - var resumedOldestRetirement = fixture.prepareIssuerRetirement(fixture.transitionId()); - assertThat(resumedOldestRetirement.operationId()) - .isEqualTo(pendingOldestRetirement.operationId()); - assertThat(resumedOldestRetirement.physicalMutation().expectedRevision()) - .isEqualTo(pendingOldestRetirement.physicalMutation().expectedRevision()); - assertThat(resumedOldestRetirement.physicalMutation().successorRevision()) - .isEqualTo(pendingOldestRetirement.physicalMutation().successorRevision()); - var recoveredOldestProof = fixture.retireIssuerCapacity(resumedOldestRetirement); - assertThat(recoveredOldestProof.scriptOutcome()).isEqualTo(2L); - assertThat(recoveredOldestProof.exactAbsenceReadbackFieldSetBytes()) - .isEqualTo(afterUncommittedRetirement); - assertThat(physicalFieldSet(partitionKey)).isEqualTo(afterUncommittedRetirement); - assertThat(durableHistoryImage(fixture.dsl(), NIL_UUID)) - .isEqualTo(historyBeforeOriginalRetirement); - assertThat(capacityFieldCount(afterUncommittedRetirement)).isEqualTo(1L); - assertThat(decodeFields(afterUncommittedRetirement)) - .containsEntry(newerCapacityField, newerRelease.exactReleasedMemberValueBytes()); - - byte[] beforeCompletedRetirementRetry = physicalFieldSet(partitionKey); - var completedOldestRetirement = fixture.prepareIssuerRetirement(fixture.transitionId()); - assertThat(completedOldestRetirement.status()) - .isEqualTo(CanonicalGameplayIssuerBindingLocalRetirementOperation.Status.RETIRED); - var completedOldestRetryProof = fixture.retireIssuerCapacity(completedOldestRetirement); - assertThat(completedOldestRetryProof.scriptOutcome()).isEqualTo(2L); - assertThat(completedOldestRetryProof.exactAbsenceReadbackFieldSetBytes()) - .isEqualTo(beforeCompletedRetirementRetry); - assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeCompletedRetirementRetry); - assertOuterBootstrapRetryIsReadOnly(fixture, partitionKey); - - assertStaleLuaRejectedWithoutWrites(staleAddInvocation, partitionKey); - assertStaleLuaRejectedWithoutWrites(staleReleaseInvocation, partitionKey); - - UUID newerTransitionId = fixture.otherOperation(newerSeed).request().transitionId(); - var pendingNewerRetirement = fixture.prepareIssuerRetirement(newerTransitionId); - byte[] beforeNewerRetirement = physicalFieldSet(partitionKey); - var completedNewerRetirement = fixture.retireIssuerCapacity(pendingNewerRetirement); - byte[] afterNewerRetirement = physicalFieldSet(partitionKey); - assertThat(completedNewerRetirement.scriptOutcome()).isEqualTo(1L); - assertThat(completedNewerRetirement.exactAbsenceReadbackFieldSetBytes()) - .isEqualTo(afterNewerRetirement); - assertThat(decodeFields(afterNewerRetirement)).doesNotContainKey(neverProjectedCapacityField); - assertRetirementFieldDelta( - beforeNewerRetirement, afterNewerRetirement, pendingNewerRetirement); - byte[] beforeNewerRetirementRetry = physicalFieldSet(partitionKey); - var completedNewerRetirementRetry = fixture.prepareIssuerRetirement(newerTransitionId); - assertThat(completedNewerRetirementRetry.status()) - .isEqualTo(CanonicalGameplayIssuerBindingLocalRetirementOperation.Status.RETIRED); - var newerRetirementRetryProof = fixture.retireIssuerCapacity(completedNewerRetirementRetry); - assertThat(newerRetirementRetryProof.scriptOutcome()).isEqualTo(2L); - assertThat(newerRetirementRetryProof.exactAbsenceReadbackFieldSetBytes()) - .isEqualTo(beforeNewerRetirementRetry); - assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeNewerRetirementRetry); - - for (int index = 3; index <= 256; index++) { - String seed = lifetimeSeed(index); - fixture.prepareOtherControllerNew(seed); - assertThat(fixture.projectOtherControllerNew(seed).scriptOutcome()).isEqualTo(1L); - fixture.publishOtherControllerNew(seed); - assertThat(fixture.recordOtherAccountAbort(seed).isAccountAborted()).isTrue(); - - var pendingCycleRelease = fixture.prepareIssuerRelease(seed); - var cycleReleaseReadback = fixture.projectIssuerRelease(pendingCycleRelease); - var completedCycleRelease = - fixture.completeIssuerRelease(pendingCycleRelease, cycleReleaseReadback); - assertThat(completedCycleRelease.status()) - .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); - - UUID transitionId = fixture.otherOperation(seed).request().transitionId(); - var pendingCycleRetirement = fixture.prepareIssuerRetirement(transitionId); - byte[] beforeCycleRetirement = physicalFieldSet(partitionKey); - var cycleRetirement = fixture.retireIssuerCapacity(pendingCycleRetirement); - byte[] afterCycleRetirement = physicalFieldSet(partitionKey); - assertThat(cycleRetirement.scriptOutcome()).isEqualTo(1L); - assertThat(cycleRetirement.exactAbsenceReadbackFieldSetBytes()) - .isEqualTo(afterCycleRetirement); - assertRetirementFieldDelta( - beforeCycleRetirement, afterCycleRetirement, pendingCycleRetirement); - assertThat(capacityFieldCount(afterCycleRetirement)).isZero(); - assertThat(decodeFields(afterCycleRetirement).size()).isEqualTo(baselineFieldCount + 2); - } - - assertThat(localOperationCount(fixture.dsl())).isEqualTo(257L); - assertThat(releaseCount(fixture.dsl(), "RELEASED")).isEqualTo(256L); - assertThat(releaseProofCount(fixture.dsl())).isEqualTo(256L); - assertThat(retirementCount(fixture.dsl())).isEqualTo(256L); - assertThat(retirementCountByStatus(fixture.dsl(), "RETIRED")).isEqualTo(256L); - String historyBefore257thRelease = durableHistoryImage(fixture.dsl(), NIL_UUID); - - String newSeed = lifetimeSeed(257); - UUID newOperationId = fixture.prepareOtherControllerNew(newSeed); - var finalPendingAdd = fixture.prepareOtherAddMutation(newSeed); - LuaInvocation staleFinalAddInvocation = addInvocation(fixture, finalPendingAdd); - var finalAddReadback = fixture.projectOtherControllerNew(newSeed); - assertThat(finalAddReadback.scriptOutcome()).isEqualTo(1L); - assertThat(fixture.retryOtherControllerNew(newSeed)).isEqualTo(newOperationId); - byte[] afterFinalAdd = physicalFieldSet(partitionKey); - assertThat(fixture.projectOtherControllerNew(newSeed).scriptOutcome()).isEqualTo(3L); - assertThat(physicalFieldSet(partitionKey)).isEqualTo(afterFinalAdd); - - fixture.publishOtherControllerNew(newSeed); - assertThat(fixture.recordOtherAccountAbort(newSeed).isAccountAborted()).isTrue(); - var finalPendingRelease = fixture.prepareIssuerRelease(newSeed); - LuaInvocation staleFinalReleaseInvocation = releaseInvocation(fixture, finalPendingRelease); - var finalReleaseReadback = fixture.projectIssuerRelease(finalPendingRelease); - var finalRelease = fixture.completeIssuerRelease(finalPendingRelease, finalReleaseReadback); - assertThat(finalRelease.status()) - .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); - - byte[] beforeFinalReleaseRetry = physicalFieldSet(partitionKey); - var completedFinalReleaseRetry = fixture.prepareIssuerRelease(newSeed); - var finalReleaseRetryReadback = fixture.projectIssuerRelease(completedFinalReleaseRetry); - assertThat(finalReleaseRetryReadback.scriptOutcome()).isEqualTo(2L); - assertThat(finalReleaseRetryReadback.exactPhysicalFieldSetBytes()) - .isEqualTo(finalRelease.exactPhysicalReadbackFieldSetBytes()); - assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeFinalReleaseRetry); - - UUID finalTransitionId = fixture.otherOperation(newSeed).request().transitionId(); - var pendingFinalRetirement = fixture.prepareIssuerRetirement(finalTransitionId); - byte[] beforeFinalRetirement = physicalFieldSet(partitionKey); - var completedFinalRetirement = fixture.retireIssuerCapacity(pendingFinalRetirement); - byte[] afterFinalRetirement = physicalFieldSet(partitionKey); - assertThat(completedFinalRetirement.scriptOutcome()).isEqualTo(1L); - assertThat(completedFinalRetirement.exactAbsenceReadbackFieldSetBytes()) - .isEqualTo(afterFinalRetirement); - assertRetirementFieldDelta( - beforeFinalRetirement, afterFinalRetirement, pendingFinalRetirement); - - assertStaleLuaRejectedWithoutWrites(staleFinalAddInvocation, partitionKey); - assertStaleLuaRejectedWithoutWrites(staleFinalReleaseInvocation, partitionKey); - byte[] beforeFinalRetirementRetry = physicalFieldSet(partitionKey); - var completedFinalRetirementRetry = fixture.prepareIssuerRetirement(finalTransitionId); - assertThat(completedFinalRetirementRetry.status()) - .isEqualTo(CanonicalGameplayIssuerBindingLocalRetirementOperation.Status.RETIRED); - var finalRetirementRetryProof = fixture.retireIssuerCapacity(completedFinalRetirementRetry); - assertThat(finalRetirementRetryProof.scriptOutcome()).isEqualTo(2L); - assertThat(finalRetirementRetryProof.exactAbsenceReadbackFieldSetBytes()) - .isEqualTo(beforeFinalRetirementRetry); - assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeFinalRetirementRetry); - - assertThat(localOperationCount(fixture.dsl())).isEqualTo(258L); - assertThat(releaseCount(fixture.dsl(), "RELEASED")).isEqualTo(257L); - assertThat(releaseProofCount(fixture.dsl())).isEqualTo(257L); - assertThat(retirementCount(fixture.dsl())).isEqualTo(257L); - assertThat(retirementCountByStatus(fixture.dsl(), "RETIRED")).isEqualTo(257L); - assertThat(capacityFieldCount(afterFinalRetirement)).isZero(); - assertThat(decodeFields(afterFinalRetirement).size()).isEqualTo(baselineFieldCount + 2); - assertThat(durableHistoryImage(fixture.dsl(), finalTransitionId)) - .isEqualTo(historyBefore257thRelease); - } - } - - @Test - void unrelatedAccountNewAndOriginalIssuerCleanupSurviveAccountControlAdvance() { - try (var fixture = newFixture(BigInteger.valueOf(11), BigInteger.ONE, 0)) { - byte[] partitionKey = fixture.issuerPartitionKey(); - fixture.publishOriginalWithControlledAccountLease(); - var abort = fixture.recordOriginalAccountAbort(); - assertThat(abort.isAccountAborted()).isTrue(); - - String staleAccountASeed = "account-a-stale-add-after-control-advance"; - fixture.prepareOtherControllerNew(staleAccountASeed); - CanonicalGameplayIssuerMemberV2Value originalMember = - CanonicalGameplayIssuerMemberV2Codec.decode(fixture.originalMemberValueBytes()); - CanonicalGameplayBindingIdentity accountA = originalMember.owner(); - - var intent = - new CanonicalGameplayAccountAdmissionBarrierRepository(fixture.dsl()) - .beginFenceIntent(accountA.accountId(), uuid("account-a-control-advance")); - assertThat(intent).isNotNull(); - assertThat( - fixture - .dsl() - .fetchSingle( - "SELECT state FROM game_session_canonical_account_coverage_control" - + " WHERE account_id = ?", - accountA.accountId()) - .get(0, String.class)) - .isEqualTo("ACQUISITION_INTENT"); - - var inventoryRepository = new CanonicalGameplayBindingInventoryRepository(fixture.dsl()); - String historyBeforeAbortRetry = durableHistoryImage(fixture.dsl(), NIL_UUID); - String retainedRowsBeforeAbortRetry = fixture.retainedFirstNewAbortRowsImage(); - byte[] fieldsBeforeAbortRetry = physicalFieldSet(partitionKey); - String controlRowsSql = - "SELECT jsonb_build_object(" - + "'clock', (SELECT to_jsonb(clock) FROM game_session_canonical_binding_inventory_clock clock WHERE singleton_id = 1)," - + " 'accountControl', (SELECT to_jsonb(control) FROM game_session_canonical_account_coverage_control control WHERE account_id = ?)," - + " 'issuerControl', (SELECT to_jsonb(control) FROM game_session_canonical_issuer_layout_bootstrap_control control WHERE issuer_id = ?))::text"; - String controlRowsBeforeAbortRetry = - fixture - .dsl() - .fetchSingle(controlRowsSql, accountA.accountId(), accountA.issuerId()) - .get(0, String.class); - Runnable assertAbortRetryUnchanged = - () -> { - assertThat(durableHistoryImage(fixture.dsl(), NIL_UUID)) - .isEqualTo(historyBeforeAbortRetry); - assertThat(fixture.retainedFirstNewAbortRowsImage()) - .isEqualTo(retainedRowsBeforeAbortRetry); - assertThat(physicalFieldSet(partitionKey)).isEqualTo(fieldsBeforeAbortRetry); - assertThat( - fixture - .dsl() - .fetchSingle(controlRowsSql, accountA.accountId(), accountA.issuerId()) - .get(0, String.class)) - .isEqualTo(controlRowsBeforeAbortRetry); - }; - - // Exact terminal retries retain their original provenance after the real Account intent. - var abortRetry = - inventoryRepository.recordFirstNewAccountAbort(abort, abort.orphanCleanupId()); - assertThat(abortRetry.transition()).isEqualTo(abort.transition()); - assertThat(abortRetry.candidate()).isEqualTo(abort.candidate()); - assertThat(abortRetry.reservation()).isEqualTo(abort.reservation()); - assertThat(abortRetry.originalDecision().leaseEvidenceJson()) - .isEqualTo(abort.originalDecision().leaseEvidenceJson()); - assertThat(abortRetry.orphanCleanupId()).isEqualTo(abort.orphanCleanupId()); - assertAbortRetryUnchanged.run(); - - var candidate = abort.candidate(); - var changedCandidate = - new CanonicalGameplayBindingInventoryEntry( - candidate.identity(), - candidate.bindingRef(), - candidate.bindingGeneration(), - candidate.accountIndexFence(), - candidate.issuerReservationId(), - candidate.transitionId(), - candidate.lifecycle(), - candidate.accountIndexState(), - candidate.issuerIndexState() - == CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED - ? CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED - : CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED, - candidate.inventoryRevision()); - var reservation = abort.reservation(); - var changedReservation = - new CanonicalIssuerPartitionReservation( - reservation.reservationId(), - reservation.owner(), - reservation.bindingGeneration(), - reservation.transitionId(), - reservation.partitionId(), - reservation.lifecycle(), - reservation.reservationFence(), - reservation.issuerCoverageOperationId(), - reservation.issuerCoverageOperationFence(), - reservation.coverageFence().add(BigInteger.ONE), - reservation.inventorySnapshotRevision(), - reservation.inventoryRevision()); - // Shape-valid caller objects exercise the SQL comparison; no stored evidence is changed. - for (var changedSource : - List.of( - new CanonicalGameplayAdmissionAbortSource( - abort.transition(), - abort.candidate(), - abort.reservation(), - abort.originalDecision(), - UUID.randomUUID()), - new CanonicalGameplayAdmissionAbortSource( - abort.transition(), - changedCandidate, - abort.reservation(), - abort.originalDecision(), - abort.orphanCleanupId()), - new CanonicalGameplayAdmissionAbortSource( - abort.transition(), - abort.candidate(), - changedReservation, - abort.originalDecision(), - abort.orphanCleanupId()))) { - assertThatThrownBy( - () -> - inventoryRepository.recordFirstNewAccountAbort( - changedSource, changedSource.orphanCleanupId())) - .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) - .hasMessageContaining("Retained first-NEW abort source changed during exact retry"); - assertAbortRetryUnchanged.run(); - } - assertThat( - inventoryRepository - .recordFirstNewAccountAbort(abort, abort.orphanCleanupId()) - .orphanCleanupId()) - .isEqualTo(abort.orphanCleanupId()); - assertAbortRetryUnchanged.run(); - - byte[] beforeStaleAdd = physicalFieldSet(partitionKey); - long mutationsBeforeStaleAdd = partitionMutationCount(fixture.dsl()); - assertThatThrownBy(() -> fixture.projectOtherControllerNew(staleAccountASeed)) - .isInstanceOf(IllegalStateException.class); - assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeStaleAdd); - assertThat(partitionMutationCount(fixture.dsl())).isEqualTo(mutationsBeforeStaleAdd); - - CanonicalGameplayBindingIdentity accountB = - otherAccountInPartition(accountA, fixture.originalPartitionId()); - var currentIssuerState = - new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( - originalMember.sourceCheckpoint(), originalMember.incarnation()); - CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource - issuerStateSource = () -> currentIssuerState; - var accountBOperation = - new CanonicalGameplayIssuerBindingLocalOperationRepository( - fixture.dsl(), issuerStateSource) - .beginOrResumeOrdinaryNew( - new CanonicalGameplayIssuerBindingLocalOperation.Request( - UUID.randomUUID(), UUID.randomUUID(), accountB, null, null)); - var localProjection = - new CanonicalGameplayIssuerBindingLocalProjectionRepository( - fixture.dsl(), issuerStateSource); - var accountBOwner = - new CanonicalGameplayIssuerBindingLocalRedisOwner( - issuerOwner, - RedisScriptCatalog.fromContributions( - List.of(new CanonicalGameplayIssuerBindingLocalRedisScriptContribution())), - localProjection, - issuerStateSource); - var accountBAdd = accountBOwner.projectAndRead(accountBOperation); - assertThat(accountBAdd.scriptOutcome()).isEqualTo(1L); - - String accountBCapacityField = - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( - accountBOperation.reservation().reservationId()); - String accountBBindingField = - new String( - accountBOperation.memberValue().owner().bindingRef().bytes(), StandardCharsets.UTF_8); - var accountBFields = decodeFields(physicalFieldSet(partitionKey)); - assertThat(accountBFields) - .containsEntry(accountBCapacityField, accountBOperation.exactMemberValueBytes()) - .doesNotContainKey(accountBBindingField); - assertThat(localOperationCount(fixture.dsl())).isEqualTo(3L); - - var pendingRelease = fixture.prepareIssuerRelease(); - var releaseReadback = fixture.projectIssuerRelease(pendingRelease); - var release = fixture.completeIssuerRelease(pendingRelease, releaseReadback); - assertThat(release.status()) - .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); - var releaseRetry = fixture.prepareIssuerRelease(); - assertThat(releaseRetry.operationId()).isEqualTo(release.operationId()); - assertThat(fixture.projectIssuerRelease(releaseRetry).exactPhysicalFieldSetBytes()) - .isEqualTo(release.exactPhysicalReadbackFieldSetBytes()); - - var pendingRetirement = fixture.prepareIssuerRetirement(fixture.transitionId()); - byte[] releasedCapacityField = - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( - release.releasedMemberValue().reservation().reservationId()) - .getBytes(StandardCharsets.US_ASCII); - byte[] beforeConflictingCapacity = physicalFieldSet(partitionKey); - administratorCommands.hset( - partitionKey, releasedCapacityField, accountBOperation.exactMemberValueBytes()); - byte[] changedCapacity = physicalFieldSet(partitionKey); - assertThatThrownBy(() -> fixture.retireIssuerCapacity(pendingRetirement)) - .isInstanceOf(IllegalStateException.class); - assertThat(physicalFieldSet(partitionKey)).isEqualTo(changedCapacity); - administratorCommands.hset( - partitionKey, releasedCapacityField, release.exactReleasedMemberValueBytes()); - assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeConflictingCapacity); - - var retired = fixture.retireIssuerCapacity(pendingRetirement); - assertThat(retired.scriptOutcome()).isEqualTo(1L); - var afterRetirement = decodeFields(physicalFieldSet(partitionKey)); - assertThat(afterRetirement) - .containsEntry(accountBCapacityField, accountBOperation.exactMemberValueBytes()) - .doesNotContainKey(accountBBindingField) - .doesNotContainKey(new String(releasedCapacityField, StandardCharsets.US_ASCII)); - assertThat(capacityFieldCount(physicalFieldSet(partitionKey))).isEqualTo(1L); - assertThat(localOperationCount(fixture.dsl())).isEqualTo(3L); - - var retirementRetry = fixture.prepareIssuerRetirement(fixture.transitionId()); - assertThat(retirementRetry.status()) - .isEqualTo(CanonicalGameplayIssuerBindingLocalRetirementOperation.Status.RETIRED); - byte[] beforeRetirementRetry = physicalFieldSet(partitionKey); - assertThat(fixture.retireIssuerCapacity(retirementRetry).scriptOutcome()).isEqualTo(2L); - assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeRetirementRetry); - } - } - - @Test - void addCurrentnessRereadKeepsTheTargetAccountControlFenceWithoutPreparingAnotherMutation() { - try (var fixture = newFixture(BigInteger.valueOf(12), BigInteger.ONE, 0)) { - String seed = "add-currentness-account-control-reread"; - fixture.prepareOtherControllerNew(seed); - var preparedAdd = fixture.prepareOtherAddMutation(seed); - byte[] partitionKey = fixture.issuerPartitionKey(); - byte[] fieldsBeforeReread = physicalFieldSet(partitionKey); - long mutationsBeforeReread = partitionMutationCount(fixture.dsl()); - CanonicalGameplayIssuerMemberV2Value originalMember = - CanonicalGameplayIssuerMemberV2Codec.decode(fixture.originalMemberValueBytes()); - var currentIssuerState = - new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( - originalMember.sourceCheckpoint(), originalMember.incarnation()); - CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource - issuerStateSource = () -> currentIssuerState; - - new CanonicalGameplayAccountAdmissionBarrierRepository(fixture.dsl()) - .beginFenceIntent( - originalMember.owner().accountId(), uuid("add-currentness-account-fence")); - - assertThatThrownBy( - () -> - new CanonicalGameplayIssuerBindingLocalProjectionRepository( - fixture.dsl(), issuerStateSource) - .requireStillCurrent(preparedAdd)) - .isInstanceOf(IllegalStateException.class); - assertThat(physicalFieldSet(partitionKey)).isEqualTo(fieldsBeforeReread); - assertThat(partitionMutationCount(fixture.dsl())).isEqualTo(mutationsBeforeReread); - } - } - - @Test - void refusesRegistrationBeyondTheCurrentLocalEntryBoundWithoutWrites() { - try (var fixture = - newFixture(BigInteger.valueOf(9), BigInteger.ONE, BigInteger.valueOf(512), 0)) { - for (int index = 1; index < PARTITION_CAPACITY.intValueExact(); index++) { - fixture.prepareOtherControllerNew("local-entry-bound-" + index); - } - - assertThat(localOperationCount(fixture.dsl())).isEqualTo(256L); - var currentWork = fixture.readCurrentOriginalPartitionWork(); - assertThat(currentWork.localEntries()).hasSize(256); - - byte[] fieldsBeforeRefusal = physicalFieldSet(fixture.issuerPartitionKey()); - long mutationCountBeforeRefusal = partitionMutationCount(fixture.dsl()); - String sourceImageBeforeRefusal = durableHistoryImage(fixture.dsl(), NIL_UUID); - assertThatThrownBy(() -> fixture.prepareOtherControllerNew("local-entry-bound-257")) - .isInstanceOf(IllegalStateException.class) - .hasMessage("The local partition operation set has reached the physical owner bound"); - assertThat(durableHistoryImage(fixture.dsl(), NIL_UUID)).isEqualTo(sourceImageBeforeRefusal); - assertThat(localOperationCount(fixture.dsl())).isEqualTo(256L); - assertThat(partitionMutationCount(fixture.dsl())).isEqualTo(mutationCountBeforeRefusal); - assertThat(physicalFieldSet(fixture.issuerPartitionKey())).isEqualTo(fieldsBeforeRefusal); - } - } - - @Test - @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( - value = "VA_PRIMITIVE_ARRAY_PASSED_TO_OBJECT_VARARG", - justification = - "RedisCommands takes binary field keys; byte[][] supplies one field. Native deletion and readback verify the exact semantics.") - void completedAddRetryReadsReleasedZeroCapacityStateWithoutWritesAndRejectsPhysicalDrift() { - try (var fixture = newFixture(BigInteger.valueOf(16), BigInteger.ONE, 0)) { - String capacityAddSql = - "SELECT to_jsonb(mutation)::text FROM game_session_canonical_issuer_partition_mutation mutation" - + " WHERE mutation_kind = 'ADD_CAPACITY' AND owner_operation_id = ?"; - String originalCapacityAddReceipt = - fixture - .dsl() - .fetchSingle(capacityAddSql, fixture.originalOperationId()) - .get(0, String.class); - fixture.publishOriginalWithControlledAccountLease(); - assertThat(fixture.recordOriginalAccountAbort().isAccountAborted()).isTrue(); - var pendingRelease = fixture.prepareIssuerRelease(); - var released = - fixture.completeIssuerRelease( - pendingRelease, fixture.projectIssuerRelease(pendingRelease)); - assertThat(released.status()) - .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); - var originalMember = - CanonicalGameplayIssuerMemberV2Codec.decode(fixture.originalMemberValueBytes()); - var current = - new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( - originalMember.sourceCheckpoint(), originalMember.incarnation()); - var projectionRepository = - new CanonicalGameplayIssuerBindingLocalProjectionRepository(fixture.dsl(), () -> current); - var originalOperation = released.originalOperation(); - var work = projectionRepository.readPreparedPartitionWork(originalOperation); - assertThat(work.baselineProof().physicalCountedCapacityCount()).isZero(); - assertThat(work.targetEntry().countsTowardCapacity()).isFalse(); - assertThat(work.partitionCapacity()).isZero(); - assertThat(work.aggregateCapacity()).isZero(); - var owner = - new CanonicalGameplayIssuerBindingLocalRedisOwner( - issuerOwner, - RedisScriptCatalog.fromContributions( - List.of(new CanonicalGameplayIssuerBindingLocalRedisScriptContribution())), - projectionRepository, - () -> current); - byte[] partitionKey = fixture.issuerPartitionKey(); - byte[] releasedFields = physicalFieldSet(partitionKey); - assertThat(capacityFieldCount(releasedFields)).isEqualTo(1L); - String releasedCapacityName = - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( - released.releasedMemberValue().reservation().reservationId()); - assertThat(decodeFields(releasedFields)) - .containsEntry(releasedCapacityName, released.exactReleasedMemberValueBytes()); - String historyBefore = durableHistoryImage(fixture.dsl(), NIL_UUID); - String headBefore = partitionHeadImage(fixture.dsl(), fixture.originalPartitionId()); - String anchorBefore = anchorAndPartitionProofImage(fixture.dsl()); - String retainedBefore = fixture.retainedFirstNewAbortRowsImage(); - Runnable assertSqlUnchanged = - () -> { - assertThat( - fixture - .dsl() - .fetchSingle(capacityAddSql, fixture.originalOperationId()) - .get(0, String.class)) - .isEqualTo(originalCapacityAddReceipt); - assertThat(durableHistoryImage(fixture.dsl(), NIL_UUID)).isEqualTo(historyBefore); - assertThat(partitionHeadImage(fixture.dsl(), fixture.originalPartitionId())) - .isEqualTo(headBefore); - assertThat(anchorAndPartitionProofImage(fixture.dsl())).isEqualTo(anchorBefore); - assertThat(fixture.retainedFirstNewAbortRowsImage()).isEqualTo(retainedBefore); - }; - var retry = owner.projectAndRead(originalOperation); - assertThat(retry.scriptOutcome()).isEqualTo(3L); - assertThat(retry.exactReadbackBytes()).containsExactly(releasedFields); - assertThat(physicalFieldSet(partitionKey)).containsExactly(releasedFields); - assertSqlUnchanged.run(); - - byte[] capacityField = releasedCapacityName.getBytes(StandardCharsets.US_ASCII); - byte[] revisionField = - CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD.getBytes( - StandardCharsets.US_ASCII); - // Administrator-injected absence and conflicting bytes remain non-admitting on read-only - // retry. - for (byte[] field : List.of(capacityField, revisionField)) { - byte[] originalValue = - java.util.Objects.requireNonNull( - administratorCommands.hget(partitionKey, field), - "Expected original released field"); - for (boolean missing : List.of(true, false)) { - if (missing) administratorCommands.hdel(partitionKey, new byte[][] {field}); - else - administratorCommands.hset( - partitionKey, - field, - (Arrays.equals(field, revisionField) - ? UUID.randomUUID().toString() - : "changed-release-field") - .getBytes(StandardCharsets.US_ASCII)); - byte[] injectedFields = physicalFieldSet(partitionKey); - assertThatThrownBy(() -> owner.projectAndRead(originalOperation)) - .isInstanceOf(IllegalStateException.class); - assertThat(physicalFieldSet(partitionKey)).containsExactly(injectedFields); - assertSqlUnchanged.run(); - administratorCommands.hset(partitionKey, field, originalValue); - assertThat(physicalFieldSet(partitionKey)).containsExactly(releasedFields); - } - } - assertThat(owner.projectAndRead(originalOperation).scriptOutcome()).isEqualTo(3L); - assertThat(physicalFieldSet(partitionKey)).containsExactly(releasedFields); - assertSqlUnchanged.run(); - } - } - - @Test - void ordinaryAddRefusesMissingPartitionRevisionWithoutRedisOrSqlWrites() throws Exception { - try (var fixture = newFixture(BigInteger.valueOf(4), BigInteger.ONE, 0)) { - String seed = "missing-revision-add"; - fixture.prepareOtherControllerNew(seed); - var work = fixture.prepareOtherAddMutation(seed); - var mutation = work.physicalMutation(); - assertMissingRevisionRefusal( - fixture, - fixture.issuerPartitionKey(), - mutation, - "game_session_canonical_issuer_binding_local_operation", - "operation_id", - fixture.otherOperation(seed).operationId(), - addInvocation(fixture, work), - () -> fixture.projectOtherControllerNew(seed)); - } - } - - @Test - void ordinaryReleaseRefusesMissingPartitionRevisionWithoutRedisOrSqlWrites() throws Exception { - try (var fixture = newFixture(BigInteger.valueOf(5), BigInteger.ONE, 0)) { - fixture.publishOriginalWithControlledAccountLease(); - assertThat(fixture.recordOriginalAccountAbort().isAccountAborted()).isTrue(); - var pendingRelease = fixture.prepareIssuerRelease(); - assertMissingRevisionRefusal( - fixture, - fixture.issuerPartitionKey(), - pendingRelease.physicalMutation(), - "game_session_canonical_issuer_binding_local_release_operation", - "operation_id", - pendingRelease.operationId(), - releaseInvocation(fixture, pendingRelease), - () -> fixture.projectIssuerRelease(pendingRelease)); - } - } - - @Test - void retirementRefusesMissingPartitionRevisionWithoutRedisOrSqlWrites() throws Exception { - try (var fixture = newFixture(BigInteger.valueOf(6), BigInteger.ONE, 0)) { - fixture.publishOriginalWithControlledAccountLease(); - assertThat(fixture.recordOriginalAccountAbort().isAccountAborted()).isTrue(); - var pendingRelease = fixture.prepareIssuerRelease(); - var releaseReadback = fixture.projectIssuerRelease(pendingRelease); - assertThat(fixture.completeIssuerRelease(pendingRelease, releaseReadback).status()) - .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); - - var pendingRetirement = fixture.prepareIssuerRetirement(fixture.transitionId()); - assertMissingRevisionRefusal( - fixture, - fixture.issuerPartitionKey(), - pendingRetirement.physicalMutation(), - "game_session_canonical_issuer_binding_local_retirement", - "retirement_operation_id", - pendingRetirement.operationId(), - retirementInvocation(fixture, pendingRetirement), - () -> fixture.retireIssuerCapacity(pendingRetirement)); - } - } - - @Test - void postRetirementProjectionRejectsUnaccountedCurrentReservationInAnotherPartition() - throws Exception { - try (var fixture = newFixture(BigInteger.valueOf(7), BigInteger.TWO, 0)) { - fixture.publishOriginalWithControlledAccountLease(); - assertThat(fixture.recordOriginalAccountAbort().isAccountAborted()).isTrue(); - var release = fixture.prepareIssuerRelease(); - var releaseReadback = fixture.projectIssuerRelease(release); - assertThat(fixture.completeIssuerRelease(release, releaseReadback).status()) - .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); - var pendingRetirement = fixture.prepareIssuerRetirement(fixture.transitionId()); - var retired = fixture.retireIssuerCapacity(pendingRetirement); - assertThat(retired.scriptOutcome()).isEqualTo(1L); - - BigInteger retiredPartition = fixture.originalPartitionId(); - BigInteger otherPartition = - retiredPartition.equals(BigInteger.ZERO) ? BigInteger.ONE : BigInteger.ZERO; - String otherPartitionSeed = "cross-partition-current"; - fixture.prepareOtherControllerNewInPartition(otherPartitionSeed, otherPartition); - assertThat(fixture.projectOtherControllerNew(otherPartitionSeed).scriptOutcome()) - .isEqualTo(1L); - - String pendingTargetSeed = "cross-partition-drift-target"; - UUID pendingTargetOperationId = fixture.prepareOtherControllerNew(pendingTargetSeed); - var pendingTarget = fixture.otherOperation(pendingTargetSeed); - byte[] retiredPartitionKey = fixture.issuerPartitionKey(); - byte[] otherPartitionKey = fixture.issuerPartitionKey(otherPartitionSeed); - byte[] retiredPartitionBefore = physicalFieldSet(retiredPartitionKey); - byte[] otherPartitionBefore = physicalFieldSet(otherPartitionKey); - String pendingTargetBefore = localOperationImage(fixture.dsl(), pendingTargetOperationId); - String otherPartitionHeadBefore = partitionHeadImage(fixture.dsl(), otherPartition); - UUID unaccountedReservationId = - insertUnaccountedCurrentReservation(fixture, otherPartitionSeed, otherPartition); - String unaccountedReservationBefore = - reservationImage(fixture.dsl(), unaccountedReservationId); - String retiredAuditBefore = retirementImage(fixture.dsl(), fixture.transitionId()); - - assertThatThrownBy(() -> fixture.projectOtherControllerNew(pendingTargetSeed)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("Durable issuer reservations differ"); - - assertThat(physicalFieldSet(retiredPartitionKey)).isEqualTo(retiredPartitionBefore); - assertThat(physicalFieldSet(otherPartitionKey)).isEqualTo(otherPartitionBefore); - assertThat(localOperationImage(fixture.dsl(), pendingTargetOperationId)) - .isEqualTo(pendingTargetBefore); - assertThat(partitionHeadImage(fixture.dsl(), otherPartition)) - .isEqualTo(otherPartitionHeadBefore); - assertThat(reservationImage(fixture.dsl(), unaccountedReservationId)) - .isEqualTo(unaccountedReservationBefore); - assertThat(retirementImage(fixture.dsl(), fixture.transitionId())) - .isEqualTo(retiredAuditBefore); - assertThat(retirementStatus(fixture.dsl(), pendingRetirement.operationId())) - .isEqualTo("RETIRED"); - assertThat(retirementCount(fixture.dsl())).isEqualTo(1L); - assertThat(releaseProofCount(fixture.dsl())).isEqualTo(1L); - assertThat( - fixture - .dsl() - .fetchSingle( - "SELECT count(*) FROM game_session_canonical_issuer_partition_mutation" - + " WHERE owner_operation_id = ? AND mutation_kind = 'ADD_CAPACITY'", - pendingTargetOperationId) - .get(0, Long.class)) - .isZero(); - assertThat(pendingTarget.reservation().partitionId()).isEqualTo(retiredPartition); - } - } - - @Test - void actualReleaseReadbackPersistsAndReloadsWithMoreThan513PhysicalFields() throws Exception { - try (var fixture = newFixture(BigInteger.valueOf(8), BigInteger.ONE, 250)) { - assertThat(fixture.originalBaselineReservationCount()).isEqualTo(250); - assertThat(fixture.originalBaselineCountedCapacity()).isEqualTo(250); - assertThat(fixture.originalBaselineBindingCount()).isEqualTo(250); - fixture.publishOriginalWithControlledAccountLease(); - for (int index = 0; index < 4; index++) { - String seed = "wide-active-" + index; - fixture.prepareOtherControllerNew(seed); - fixture.projectOtherControllerNew(seed); - fixture.publishOtherControllerNew(seed); - } - - String terminalSeed = "wide-retained-terminal"; - fixture.prepareOtherControllerNew(terminalSeed); - fixture.projectOtherControllerNew(terminalSeed); - fixture.publishOtherControllerNew(terminalSeed); - assertThat(fixture.recordOtherAccountAbort(terminalSeed).isAccountAborted()).isTrue(); - var terminalRelease = fixture.prepareIssuerRelease(terminalSeed); - var terminalReadback = fixture.projectIssuerRelease(terminalRelease); - assertThat(fixture.completeIssuerRelease(terminalRelease, terminalReadback).status()) - .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); - - String wideReleaseSeed = "wide-release-readback"; - UUID wideOperationId = fixture.prepareOtherControllerNew(wideReleaseSeed); - var pendingAdd = fixture.prepareOtherAddMutation(wideReleaseSeed); - assertThat(pendingAdd.aggregateCapacity()).isEqualTo(PARTITION_CAPACITY); - assertThat(fixture.projectOtherControllerNew(wideReleaseSeed).scriptOutcome()).isEqualTo(1L); - fixture.publishOtherControllerNew(wideReleaseSeed); - assertThat(fixture.recordOtherAccountAbort(wideReleaseSeed).isAccountAborted()).isTrue(); - - var pendingRelease = fixture.prepareIssuerRelease(wideReleaseSeed); - var actualReadback = fixture.projectIssuerRelease(pendingRelease); - assertThat(actualReadback.scriptOutcome()).isEqualTo(1L); - assertThat(decodeFields(actualReadback.exactPhysicalFieldSetBytes()).size()).isEqualTo(514); - var completedRelease = fixture.completeIssuerRelease(pendingRelease, actualReadback); - assertThat(completedRelease.status()) - .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); - assertThat(completedRelease.exactPhysicalReadbackFieldSetBytes()) - .isEqualTo(actualReadback.exactPhysicalFieldSetBytes()); - - var reloadedRelease = fixture.prepareIssuerRelease(wideReleaseSeed); - assertThat(reloadedRelease.operationId()).isEqualTo(pendingRelease.operationId()); - assertThat(reloadedRelease.exactPhysicalReadbackFieldSetBytes()) - .isEqualTo(actualReadback.exactPhysicalFieldSetBytes()); - var completedRetry = fixture.projectIssuerRelease(reloadedRelease); - assertThat(completedRetry.scriptOutcome()).isEqualTo(2L); - assertThat(completedRetry.exactPhysicalFieldSetBytes()) - .isEqualTo(actualReadback.exactPhysicalFieldSetBytes()); - assertThat(physicalFieldSet(fixture.issuerPartitionKey())) - .isEqualTo(actualReadback.exactPhysicalFieldSetBytes()); - assertThat(localOperationCount(fixture.dsl())).isEqualTo(7L); - assertThat(releaseCount(fixture.dsl(), "RELEASED")).isEqualTo(2L); - assertThat(wideOperationId).isEqualTo(pendingRelease.originalOperationId()); - } - } - - private RedisClient createRedisClient(String username, String password) { - RedisURI.Builder builder = RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(6379)); - if (username != null) builder.withAuthentication(username, password); - RedisURI uri = builder.build(); - uri.setTimeout(Duration.ofSeconds(5)); - RedisClient client = RedisClient.create(uri); - client.setOptions( - ClientOptions.builder() - .autoReconnect(false) - .protocolVersion(ProtocolVersion.RESP2) - .build()); - return client; - } - - private CanonicalGameplayAdmissionAbortCompositionFixture newFixture() { - return newFixture(controlledCandidate(), 0); - } - - private CanonicalGameplayAdmissionAbortCompositionFixture newFixture( - BigInteger layoutVersion, BigInteger partitionCount, int seedBootstrapMemberCount) { - return newFixture(controlledCandidate(layoutVersion, partitionCount), seedBootstrapMemberCount); - } - - private CanonicalGameplayAdmissionAbortCompositionFixture newFixture( - BigInteger layoutVersion, - BigInteger partitionCount, - BigInteger partitionCapacity, - int seedBootstrapMemberCount) { - return newFixture( - controlledCandidate(layoutVersion, partitionCount, partitionCapacity), - seedBootstrapMemberCount); - } - - private CanonicalGameplayAdmissionAbortCompositionFixture newFixture( - Candidate candidate, int seedBootstrapMemberCount) { - DriverManagerDataSource accountDataSource = new DriverManagerDataSource(); - accountDataSource.setDriverClassName("org.postgresql.Driver"); - String postgresJdbcUrl = POSTGRES.getJdbcUrl(); - accountDataSource.setUrl( - postgresJdbcUrl + (postgresJdbcUrl.contains("?") ? "&" : "?") + "currentSchema=public"); - accountDataSource.setUsername(POSTGRES.getUsername()); - accountDataSource.setPassword(POSTGRES.getPassword()); - return new CanonicalGameplayAdmissionAbortCompositionFixture( - accountDataSource, candidate, issuerOwner, seedBootstrapMemberCount); - } - - private static Candidate controlledCandidate() { - return controlledCandidate(BigInteger.valueOf(3), BigInteger.ONE); - } - - private static Candidate controlledCandidate( - BigInteger layoutVersion, BigInteger partitionCount) { - return controlledCandidate(layoutVersion, partitionCount, PARTITION_CAPACITY); - } - - private static Candidate controlledCandidate( - BigInteger layoutVersion, BigInteger partitionCount, BigInteger partitionCapacity) { - return new Candidate( - uuid("retirement-account"), - uuid("retirement-tenant"), - uuid("retirement-playable-state"), - uuid("retirement-character"), - "SHARED", - uuid("retirement-game"), - 1L, - uuid("retirement-session"), - uuid("retirement-region"), - BigInteger.ONE, - GameSessionAccountDelegationProfile.ISSUER, - BigInteger.ONE, - layoutVersion, - partitionCount, - partitionCapacity); - } - - private static CanonicalGameplayBindingIdentity otherAccountInPartition( - CanonicalGameplayBindingIdentity template, BigInteger partitionId) { - CanonicalGameplayBindingIdentity candidate; - do { - candidate = - new CanonicalGameplayBindingIdentity( - UUID.randomUUID(), - template.tenantId(), - template.playableStateNamespaceId(), - UUID.randomUUID(), - template.playableStateScope(), - template.gameInstanceId(), - template.runtimeGameInstanceId(), - UUID.randomUUID().toString(), - template.regionId(), - template.regionEpoch(), - template.issuerId(), - template.issuerAuthGeneration(), - template.issuerIndexLayoutVersion(), - template.issuerIndexPartitionCount(), - template.issuerIndexPartitionCapacity()); - } while (!candidate - .bindingRef() - .partitionId(template.issuerIndexPartitionCount()) - .equals(partitionId)); - return candidate; - } - - private void assertMissingRevisionRefusal( - CanonicalGameplayAdmissionAbortCompositionFixture fixture, - byte[] partitionKey, - CanonicalGameplayIssuerPartitionMutation mutation, - String ownerTable, - String ownerIdColumn, - UUID ownerOperationId, - LuaInvocation exactInvocation, - Runnable ordinaryOwnerCall) { - byte[] beforeFault = physicalFieldSet(partitionKey); - assertThat(decodeFields(beforeFault)) - .containsKey(CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD); - String pendingCustodyBefore = - pendingMutationCustodyImage( - fixture.dsl(), mutation, ownerTable, ownerIdColumn, ownerOperationId); - - byte[] revisionField = - CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD.getBytes( - StandardCharsets.US_ASCII); - byte[][] revisionFields = {revisionField}; - assertThat(administratorCommands.hdel(partitionKey, revisionFields)).isEqualTo(1L); - byte[] afterInjectedAbsence = physicalFieldSet(partitionKey); - assertThat(decodeFields(afterInjectedAbsence)) - .doesNotContainKey(CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD); - assertThat( - pendingMutationCustodyImage( - fixture.dsl(), mutation, ownerTable, ownerIdColumn, ownerOperationId)) - .isEqualTo(pendingCustodyBefore); - - assertThat(evaluate(exactInvocation)).isNegative(); - assertThat(physicalFieldSet(partitionKey)).isEqualTo(afterInjectedAbsence); - assertThatThrownBy(ordinaryOwnerCall::run).isInstanceOf(IllegalStateException.class); - assertThat(physicalFieldSet(partitionKey)).isEqualTo(afterInjectedAbsence); - assertThat(administratorCommands.hget(partitionKey, revisionField)).isNull(); - assertThat( - pendingMutationCustodyImage( - fixture.dsl(), mutation, ownerTable, ownerIdColumn, ownerOperationId)) - .isEqualTo(pendingCustodyBefore); - } - - private static String pendingMutationCustodyImage( - DSLContext dsl, - CanonicalGameplayIssuerPartitionMutation mutation, - String ownerTable, - String ownerIdColumn, - UUID ownerOperationId) { - String sql = - "SELECT jsonb_build_object(" - + "'head', (SELECT to_jsonb(head) FROM " - + CanonicalGameplayIssuerPartitionMutationRepository.HEAD_TABLE - + " head WHERE head.issuer_id = ? AND head.partition_id = ?)," - + "'mutation', (SELECT to_jsonb(mutation) FROM " - + "game_session_canonical_issuer_partition_mutation" - + " mutation WHERE mutation.mutation_id = ?)," - + "'owner', (SELECT to_jsonb(owner_row) FROM " - + ownerTable - + " owner_row WHERE owner_row." - + ownerIdColumn - + " = ?))::text"; - return dsl.fetchSingle( - sql, - GameSessionAccountDelegationProfile.ISSUER, - mutation.partitionId(), - mutation.mutationId(), - ownerOperationId) - .get(0, String.class); - } - - private static String localOperationImage(DSLContext dsl, UUID operationId) { - return dsl.fetchSingle( - "SELECT to_jsonb(operation)::text FROM" - + " game_session_canonical_issuer_binding_local_operation operation" - + " WHERE operation.operation_id = ?", - operationId) - .get(0, String.class); - } - - private static String partitionHeadImage(DSLContext dsl, BigInteger partitionId) { - return dsl.fetchSingle( - "SELECT to_jsonb(head)::text FROM " - + CanonicalGameplayIssuerPartitionMutationRepository.HEAD_TABLE - + " head WHERE head.issuer_id = ? AND head.partition_id = ?", - GameSessionAccountDelegationProfile.ISSUER, - partitionId) - .get(0, String.class); - } - - private void assertOuterBootstrapRetryIsReadOnly( - CanonicalGameplayAdmissionAbortCompositionFixture fixture, byte[] partitionKey) { - byte[] physicalBefore = physicalFieldSet(partitionKey); - String revisionBefore = partitionHeadImage(fixture.dsl(), fixture.originalPartitionId()); - String anchorAndProofsBefore = anchorAndPartitionProofImage(fixture.dsl()); - byte[] originalAnchorBytes = - fixture - .dsl() - .fetchSingle( - "SELECT exact_anchor_bytes FROM" - + " game_session_canonical_issuer_binding_local_operation" - + " WHERE operation_id = ?", - fixture.originalOperationId()) - .get(0, byte[].class); - - var retriedAnchor = fixture.retryOriginalIssuerBootstrap(); - - assertThat(retriedAnchor.exactAnchorBytes()).containsExactly(originalAnchorBytes); - assertThat(physicalFieldSet(partitionKey)).isEqualTo(physicalBefore); - assertThat(partitionHeadImage(fixture.dsl(), fixture.originalPartitionId())) - .isEqualTo(revisionBefore); - assertThat(anchorAndPartitionProofImage(fixture.dsl())).isEqualTo(anchorAndProofsBefore); - } - - private static String anchorAndPartitionProofImage(DSLContext dsl) { - return dsl.fetchSingle( - "SELECT jsonb_build_object(" - + "'anchors', COALESCE((SELECT jsonb_agg(to_jsonb(anchor)" - + " ORDER BY anchor.issuer_id) FROM" - + " game_session_canonical_issuer_installed_anchor anchor), '[]'::jsonb)," - + "'partitionProofs', COALESCE((SELECT jsonb_agg(to_jsonb(proof)" - + " ORDER BY proof.issuer_id, proof.partition_id) FROM" - + " game_session_canonical_issuer_bootstrap_partition_proof proof), '[]'::jsonb)" - + ")::text") - .get(0, String.class); - } - - private static UUID insertUnaccountedCurrentReservation( - CanonicalGameplayAdmissionAbortCompositionFixture fixture, - String sourceSeed, - BigInteger partitionId) { - // This row is deliberate run-owned SQL drift: it has no transition or local owner operation. - // The ordinary projection must detect that missing accounting and make no Redis change. - var source = fixture.otherOperation(sourceSeed).memberValue(); - var owner = source.owner(); - var reservation = source.reservation(); - String sessionId; - CanonicalGameplayBindingRef bindingRef; - do { - sessionId = UUID.randomUUID().toString(); - bindingRef = - CanonicalGameplayBindingRef.of(owner.tenantId(), owner.gameInstanceId(), sessionId); - } while (!bindingRef.partitionId(owner.issuerIndexPartitionCount()).equals(partitionId)); - UUID reservationId = UUID.randomUUID(); - fixture - .dsl() - .execute( - "INSERT INTO game_session_canonical_issuer_partition_reservation" - + " (reservation_id, binding_ref, account_id, tenant_id, game_instance_id," - + " runtime_game_instance_id, session_id, binding_generation, transition_id, issuer_id," - + " issuer_auth_generation, playable_state_namespace_id, character_id," - + " playable_state_scope, region_id, region_epoch, partition_id," - + " issuer_index_layout_version, issuer_index_partition_count," - + " issuer_index_partition_capacity, lifecycle, reservation_fence," - + " issuer_coverage_operation_id, issuer_coverage_operation_fence, coverage_fence," - + " inventory_snapshot_revision, inventory_revision)" - + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," - + " ?, ?, ?, ?, ?, ?, ?)", - reservationId, - bindingRef.bytes(), - owner.accountId(), - owner.tenantId(), - owner.gameInstanceId(), - owner.runtimeGameInstanceId(), - sessionId, - source.bindingGeneration(), - UUID.randomUUID(), - owner.issuerId(), - owner.issuerAuthGeneration(), - owner.playableStateNamespaceId(), - UUID.randomUUID(), - owner.playableStateScope(), - owner.regionId(), - owner.regionEpoch(), - partitionId, - owner.issuerIndexLayoutVersion(), - owner.issuerIndexPartitionCount(), - owner.issuerIndexPartitionCapacity(), - "RESERVED", - UUID.randomUUID(), - UUID.randomUUID(), - reservation.issuerCoverageOperationFence(), - reservation.coverageFence(), - reservation.inventorySnapshotRevision(), - reservation.inventoryRevision()); - return reservationId; - } - - private static String reservationImage(DSLContext dsl, UUID reservationId) { - return dsl.fetchSingle( - "SELECT to_jsonb(reservation)::text FROM" - + " game_session_canonical_issuer_partition_reservation reservation" - + " WHERE reservation.reservation_id = ?", - reservationId) - .get(0, String.class); - } - - private static String retirementImage(DSLContext dsl, UUID transitionId) { - return dsl.fetchSingle( - "SELECT to_jsonb(retirement)::text FROM" - + " game_session_canonical_issuer_binding_local_retirement retirement" - + " WHERE retirement.transition_id = ?", - transitionId) - .get(0, String.class); - } - - private static CanonicalGameplayIssuerBindingLocalReleaseOperation completeReleaseAfterLostReply( - CanonicalGameplayAdmissionAbortCompositionFixture fixture, String seed) { - var pending = - seed == null ? fixture.prepareIssuerRelease() : fixture.prepareIssuerRelease(seed); - assertThatThrownBy(() -> fixture.projectIssuerReleaseAndLoseReply(pending)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("controlled lost issuer release reply"); - var resumed = - seed == null ? fixture.prepareIssuerRelease() : fixture.prepareIssuerRelease(seed); - var recoveredReadback = fixture.projectIssuerRelease(resumed); - assertThat(recoveredReadback.scriptOutcome()).isEqualTo(2L); - return fixture.completeIssuerRelease(resumed, recoveredReadback); - } - - private static String lifetimeSeed(int index) { - return "lifetime-" + index; - } - - private static LuaInvocation addInvocation( - CanonicalGameplayAdmissionAbortCompositionFixture fixture, - CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work) - throws IOException, ReflectiveOperationException { - return new LuaInvocation( - readScript(CanonicalGameplayIssuerBindingLocalRedisScriptContribution.RESOURCE_PATH), - fixture.issuerPartitionKey(), - scriptArguments( - CanonicalGameplayIssuerBindingLocalRedisOwner.class, - new Class[] { - CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork.class - }, - work)); - } - - private static LuaInvocation releaseInvocation( - CanonicalGameplayAdmissionAbortCompositionFixture fixture, - CanonicalGameplayIssuerBindingLocalReleaseOperation operation) - throws IOException, ReflectiveOperationException { - var work = fixture.readPreparedPartitionWork(operation.originalOperation()); - return new LuaInvocation( - readScript(CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution.RESOURCE_PATH), - fixture.issuerPartitionKey(), - scriptArguments( - CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.class, - new Class[] { - CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork.class, - CanonicalGameplayIssuerBindingLocalReleaseOperation.class - }, - work, - operation)); - } - - private static LuaInvocation retirementInvocation( - CanonicalGameplayAdmissionAbortCompositionFixture fixture, - CanonicalGameplayIssuerBindingLocalRetirementOperation operation) - throws IOException, ReflectiveOperationException { - var work = fixture.readPreparedPartitionWork(operation.release().originalOperation()); - return new LuaInvocation( - readScript( - CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution.RESOURCE_PATH), - fixture.issuerPartitionKey(), - scriptArguments( - CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.class, - new Class[] { - CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork.class, - CanonicalGameplayIssuerBindingLocalRetirementOperation.class - }, - work, - operation)); - } - - private static byte[][] scriptArguments( - Class owner, Class[] parameterTypes, Object... arguments) - throws ReflectiveOperationException { - Method method = owner.getDeclaredMethod("scriptArguments", parameterTypes); - if (!method.trySetAccessible()) { - throw new IllegalStateException("Test could not capture the exact owner Lua arguments"); - } - try { - return (byte[][]) method.invoke(null, arguments); - } catch (InvocationTargetException failure) { - Throwable cause = failure.getCause(); - if (cause instanceof RuntimeException runtime) throw runtime; - throw failure; - } - } - - private static byte[] readScript(String resourcePath) throws IOException { - try (InputStream input = - CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.class - .getClassLoader() - .getResourceAsStream(resourcePath)) { - if (input == null) throw new IOException("Missing Redis Lua resource: " + resourcePath); - byte[] bytes = input.readAllBytes(); - if (bytes.length == 0) throw new IOException("Empty Redis Lua resource: " + resourcePath); - return bytes; - } - } - - private Long evaluate(LuaInvocation invocation) { - return administratorCommands.eval( - invocation.script(), - ScriptOutputType.INTEGER, - new byte[][] {invocation.key()}, - invocation.arguments()); - } - - private void assertStaleLuaRejectedWithoutWrites( - LuaInvocation staleInvocation, byte[] partitionKey) { - byte[] before = physicalFieldSet(partitionKey); - Long outcome = evaluate(staleInvocation); - assertThat(outcome).isNegative(); - assertThat(physicalFieldSet(partitionKey)).isEqualTo(before); - } - - private byte[] physicalFieldSet(byte[] key) { - Map raw = administratorCommands.hgetall(key); - Map fields = new HashMap<>(); - raw.forEach( - (field, value) -> fields.put(new String(field, StandardCharsets.UTF_8), value.clone())); - return CanonicalGameplayIssuerBootstrapCoverageRepository.encodeFieldSet(fields); - } - - private static Map decodeFields(byte[] fieldSet) { - return CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet(fieldSet); - } - - private static long capacityFieldCount(byte[] fieldSet) { - return decodeFields(fieldSet).keySet().stream() - .filter( - field -> - field.startsWith( - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec - .RESERVATION_FIELD_PREFIX)) - .count(); - } - - private static void assertRetirementFieldDelta( - byte[] before, - byte[] after, - CanonicalGameplayIssuerBindingLocalRetirementOperation operation) { - Map expected = decodeFields(before); - String capacityField = - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( - operation.release().releasedMemberValue().reservation().reservationId()); - assertThat(expected.get(capacityField)) - .isEqualTo(operation.release().exactReleasedMemberValueBytes()); - expected.remove(capacityField); - expected.put( - CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD, - operation - .physicalMutation() - .successorRevision() - .toString() - .getBytes(StandardCharsets.US_ASCII)); - assertThat(after) - .isEqualTo(CanonicalGameplayIssuerBootstrapCoverageRepository.encodeFieldSet(expected)); - } - - private static long localOperationCount(DSLContext dsl) { - return dsl.fetchSingle( - "SELECT count(*) FROM game_session_canonical_issuer_binding_local_operation") - .get(0, Long.class); - } - - private static long partitionMutationCount(DSLContext dsl) { - return dsl.fetchSingle("SELECT count(*) FROM game_session_canonical_issuer_partition_mutation") - .get(0, Long.class); - } - - private static long releaseCount(DSLContext dsl, String status) { - return dsl.fetchSingle( - "SELECT count(*) FROM game_session_canonical_issuer_binding_local_release_operation" - + " WHERE status = ?", - status) - .get(0, Long.class); - } - - private static long releaseProofCount(DSLContext dsl) { - return dsl.fetchSingle( - "SELECT count(*) FROM game_session_canonical_issuer_binding_local_release_operation" - + " WHERE status = 'RELEASED' AND physical_readback_field_set_bytes IS NOT NULL" - + " AND completion_inventory_revision > source_inventory_revision") - .get(0, Long.class); - } - - private static long retirementCount(DSLContext dsl) { - return dsl.fetchSingle( - "SELECT count(*) FROM game_session_canonical_issuer_binding_local_retirement") - .get(0, Long.class); - } - - private static long retirementCountByStatus(DSLContext dsl, String status) { - return dsl.fetchSingle( - "SELECT count(*) FROM game_session_canonical_issuer_binding_local_retirement WHERE status = ?", - status) - .get(0, Long.class); - } - - private static String retirementStatus(DSLContext dsl, UUID retirementOperationId) { - return dsl.fetchSingle( - "SELECT status FROM game_session_canonical_issuer_binding_local_retirement" - + " WHERE retirement_operation_id = ?", - retirementOperationId) - .get(0, String.class); - } - - private static String durableHistoryImage(DSLContext dsl, UUID excludedTransitionId) { - String sql = - "SELECT jsonb_build_object(" - + "'transitions', COALESCE((SELECT jsonb_agg(to_jsonb(entry) ORDER BY entry.transition_id)" - + " FROM game_session_canonical_binding_transition entry WHERE entry.transition_id <> ?), '[]'::jsonb)," - + "'inventory', COALESCE((SELECT jsonb_agg(to_jsonb(entry) ORDER BY entry.binding_ref)" - + " FROM game_session_canonical_gameplay_binding_inventory entry WHERE entry.transition_id <> ?), '[]'::jsonb)," - + "'reservations', COALESCE((SELECT jsonb_agg(to_jsonb(entry) ORDER BY entry.reservation_id)" - + " FROM game_session_canonical_issuer_partition_reservation entry WHERE entry.transition_id <> ?), '[]'::jsonb)," - + "'accountObligations', COALESCE((SELECT jsonb_agg(to_jsonb(entry) ORDER BY entry.transition_id, entry.obligation_ordinal)" - + " FROM game_session_canonical_binding_account_index_obligation entry WHERE entry.transition_id <> ?), '[]'::jsonb)," - + "'issuerObligations', COALESCE((SELECT jsonb_agg(to_jsonb(entry) ORDER BY entry.transition_id, entry.binding_ref)" - + " FROM game_session_canonical_binding_issuer_index_obligation entry WHERE entry.transition_id <> ?), '[]'::jsonb)," - + "'regionObligations', COALESCE((SELECT jsonb_agg(to_jsonb(entry) ORDER BY entry.transition_id)" - + " FROM game_session_canonical_binding_region_bridge_obligation entry WHERE entry.transition_id <> ?), '[]'::jsonb)," - + "'localOperations', COALESCE((SELECT jsonb_agg(to_jsonb(entry) ORDER BY entry.operation_id)" - + " FROM game_session_canonical_issuer_binding_local_operation entry WHERE entry.transition_id <> ?), '[]'::jsonb)," - + "'releases', COALESCE((SELECT jsonb_agg(to_jsonb(entry) ORDER BY entry.operation_id)" - + " FROM game_session_canonical_issuer_binding_local_release_operation entry WHERE entry.transition_id <> ?), '[]'::jsonb)," - + "'mutations', COALESCE((SELECT jsonb_agg(to_jsonb(mutation) ORDER BY mutation.mutation_id)" - + " FROM game_session_canonical_issuer_partition_mutation mutation WHERE mutation.owner_operation_id IN (" - + " SELECT local_operation.operation_id FROM game_session_canonical_issuer_binding_local_operation local_operation WHERE local_operation.transition_id <> ?" - + " UNION SELECT release_entry.operation_id FROM game_session_canonical_issuer_binding_local_release_operation release_entry WHERE release_entry.transition_id <> ?)), '[]'::jsonb)" - + ")::text"; - return dsl.fetchSingle( - sql, - excludedTransitionId, - excludedTransitionId, - excludedTransitionId, - excludedTransitionId, - excludedTransitionId, - excludedTransitionId, - excludedTransitionId, - excludedTransitionId, - excludedTransitionId, - excludedTransitionId) - .get(0, String.class); - } - - private static UUID uuid(String seed) { - return UUID.nameUUIDFromBytes(seed.getBytes(StandardCharsets.UTF_8)); - } - - private record LuaInvocation(byte[] script, byte[] key, byte[][] arguments) { - private LuaInvocation { - script = script.clone(); - key = key.clone(); - arguments = Arrays.stream(arguments).map(byte[]::clone).toArray(byte[][]::new); - } - - @Override - public byte[] script() { - return script.clone(); - } - - @Override - public byte[] key() { - return key.clone(); - } - - @Override - public byte[][] arguments() { - return Arrays.stream(arguments).map(byte[]::clone).toArray(byte[][]::new); - } - } -} From 35ad2c146ce606da83fbdb8ce930e59e087ab789 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 15:15:51 +1300 Subject: [PATCH 33/34] Give each issuer proof class its own test containers --- design/project-management/ai-observations.md | 2 ++ ...lGameplayIssuerLifecycleProofFixtures.java | 19 ++++++---------- ...layIssuerLocalCapacityIntegrationTest.java | 22 +++++++++++++++++++ 3 files changed, 31 insertions(+), 12 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 1756238232..aef07906d1 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -446,3 +446,5 @@ Entry format: - Recovery: FireController identified six separately fingerprinted findings grouped into five comment containers. Parser fix `8f6e6121` recovered the same original attempt and all six exact findings; Gameplay verified the pinned head/base and finalized their native decisions. No trigger, allowance or controls changed. Full required controller CI was still pending at its owner's recovery handoff; native/race and packaged checks had passed. - `2026-10-29`: Malformed source-refresh IDs missing the `review_refresh_` prefix returned unrelated startup-binding advice. The original full receipt IDs recovered the existing observations without another fetch. FireController owner reports client-only fix `18cf3b4d` now identifies `refresh_id`, its required prefix/format and retained-receipt recovery; an existing MCP process keeps its prior binary until normal reconnection. Preserve exact full handles in delegation messages rather than abbreviating tool arguments. + +- `2026-10-29`: The split issuer capacity/retirement proof shared static Testcontainers objects in an abstract fixture across two independently managed test classes. The first class passed, but the retirement class could not start Redis on its mapped port; no retirement cases ran. The exact timeout cause remains unproved. Each concrete test class now owns its own containers while sharing connection and SQL proof mechanics; verify both classes together and retain the original failed aggregate before claiming receiving proof. diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLifecycleProofFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLifecycleProofFixtures.java index 1a2f27027d..34f0fb4581 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLifecycleProofFixtures.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLifecycleProofFixtures.java @@ -31,14 +31,12 @@ import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution; -import net.firedevops.firemud.test.TestContainerImages; import org.jooq.DSLContext; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; -import org.testcontainers.junit.jupiter.Container; /** * Shared PostgreSQL/Redis setup and owner helpers for the separate local-capacity and retirement @@ -51,13 +49,9 @@ abstract class CanonicalGameplayIssuerLifecycleProofFixtures { protected static final BigInteger PARTITION_CAPACITY = BigInteger.valueOf(256); protected static final UUID NIL_UUID = new UUID(0L, 0L); - @Container - protected static final PostgreSQLContainer POSTGRES = - new PostgreSQLContainer<>(TestContainerImages.postgres()); + protected abstract PostgreSQLContainer postgres(); - @Container - protected static final GenericContainer REDIS = - new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + protected abstract GenericContainer redis(); protected RedisClient administrator; protected RedisClient issuerOwner; @@ -101,7 +95,8 @@ void tearDown() { } protected RedisClient createRedisClient(String username, String password) { - RedisURI.Builder builder = RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(6379)); + RedisURI.Builder builder = + RedisURI.Builder.redis(redis().getHost(), redis().getMappedPort(6379)); if (username != null) builder.withAuthentication(username, password); RedisURI uri = builder.build(); uri.setTimeout(Duration.ofSeconds(5)); @@ -137,11 +132,11 @@ protected CanonicalGameplayAdmissionAbortCompositionFixture newFixture( Candidate candidate, int seedBootstrapMemberCount) { DriverManagerDataSource accountDataSource = new DriverManagerDataSource(); accountDataSource.setDriverClassName("org.postgresql.Driver"); - String postgresJdbcUrl = POSTGRES.getJdbcUrl(); + String postgresJdbcUrl = postgres().getJdbcUrl(); accountDataSource.setUrl( postgresJdbcUrl + (postgresJdbcUrl.contains("?") ? "&" : "?") + "currentSchema=public"); - accountDataSource.setUsername(POSTGRES.getUsername()); - accountDataSource.setPassword(POSTGRES.getPassword()); + accountDataSource.setUsername(postgres().getUsername()); + accountDataSource.setPassword(postgres().getPassword()); return new CanonicalGameplayAdmissionAbortCompositionFixture( accountDataSource, candidate, issuerOwner, seedBootstrapMemberCount); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLocalCapacityIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLocalCapacityIntegrationTest.java index c07b6a9b80..bf75d4f7d1 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLocalCapacityIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLocalCapacityIntegrationTest.java @@ -14,9 +14,13 @@ import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; +import net.firedevops.firemud.test.TestContainerImages; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; /** @@ -29,6 +33,24 @@ @Execution(ExecutionMode.SAME_THREAD) class CanonicalGameplayIssuerLocalCapacityIntegrationTest extends CanonicalGameplayIssuerLifecycleProofFixtures { + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + private static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + @Override + protected PostgreSQLContainer postgres() { + return POSTGRES; + } + + @Override + protected GenericContainer redis() { + return REDIS; + } + @Test void unrelatedAccountNewAndOriginalIssuerCleanupSurviveAccountControlAdvance() { try (var fixture = newFixture(BigInteger.valueOf(11), BigInteger.ONE, 0)) { From 35d3772b1e1436861583c8833886cebf8dae3c38 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 16:57:03 +1300 Subject: [PATCH 34/34] fix: refuse synchronized ambient issuer Redis work --- design/project-management/ai-observations.md | 12 +++++++--- ...alGameplayIssuerPartitionRedisSupport.java | 3 ++- ...IssuerBootstrapAmbientTransactionTest.java | 24 +++++++++++++++++++ 3 files changed, 35 insertions(+), 4 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index aef07906d1..6d9759f6a2 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -445,6 +445,12 @@ Entry format: - Recovery: FireController identified six separately fingerprinted findings grouped into five comment containers. Parser fix `8f6e6121` recovered the same original attempt and all six exact findings; Gameplay verified the pinned head/base and finalized their native decisions. No trigger, allowance or controls changed. Full required controller CI was still pending at its owner's recovery handoff; native/race and packaged checks had passed. -- `2026-10-29`: Malformed source-refresh IDs missing the `review_refresh_` prefix returned unrelated startup-binding advice. The original full receipt IDs recovered the existing observations without another fetch. FireController owner reports client-only fix `18cf3b4d` now identifies `refresh_id`, its required prefix/format and retained-receipt recovery; an existing MCP process keeps its prior binary until normal reconnection. Preserve exact full handles in delegation messages rather than abbreviating tool arguments. - -- `2026-10-29`: The split issuer capacity/retirement proof shared static Testcontainers objects in an abstract fixture across two independently managed test classes. The first class passed, but the retirement class could not start Redis on its mapped port; no retirement cases ran. The exact timeout cause remains unproved. Each concrete test class now owns its own containers while sharing connection and SQL proof mechanics; verify both classes together and retain the original failed aggregate before claiming receiving proof. +- `2026-10-29`: Abbreviated source-refresh IDs returned unrelated advice + - Context: Source-refresh IDs missing the `review_refresh_` prefix returned unrelated startup-binding advice. The original full receipt IDs recovered the existing observations without another fetch. + - Observation: FireController owner reports client-only fix `18cf3b4d` now identifies `refresh_id`, its required prefix/format and retained-receipt recovery; an existing MCP process keeps its prior binary until normal reconnection. + - Expected pattern: Preserve exact full handles in delegation messages rather than abbreviating tool arguments. + +- `2026-10-29`: Shared static Testcontainers blocked the retirement suite + - Context: The split issuer capacity/retirement proof shared static Testcontainers objects in an abstract fixture across two independently managed test classes. + - Observation: The first class passed, but the retirement class could not start Redis on its mapped port; no retirement cases ran. The exact timeout cause remains unproved. + - Expected pattern: Each concrete test class owns its own containers while sharing connection and SQL proof mechanics. Verify both classes together and retain the original failed aggregate before claiming receiving proof. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionRedisSupport.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionRedisSupport.java index b34fc21b37..b1399abb60 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionRedisSupport.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionRedisSupport.java @@ -203,7 +203,8 @@ private T await(RedisFuture future) { } void requireNoAmbientTransaction() { - if (TransactionSynchronizationManager.isActualTransactionActive()) + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) throw failure("Issuer Redis operation cannot run inside an ambient SQL transaction", null); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapAmbientTransactionTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapAmbientTransactionTest.java index e0909591df..285fac9f1f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapAmbientTransactionTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapAmbientTransactionTest.java @@ -100,6 +100,30 @@ void partitionRedisOwnerRejectsBothAmbientStatesBeforeRedisOrCurrentSource() { verifyNoInteractions(redisClient, catalog, currentStateSource, work); } + @Test + void ordinaryRedisOwnersRejectBothAmbientStatesBeforeSqlRedisOrCurrentSource() { + var redisClient = mock(RedisClient.class); + var catalog = mock(RedisScriptCatalog.class); + var repository = mock(CanonicalGameplayIssuerBindingLocalProjectionRepository.class); + var currentStateSource = + mock(CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource.class); + var addOwner = + new CanonicalGameplayIssuerBindingLocalRedisOwner( + redisClient, catalog, repository, currentStateSource); + var releaseOwner = + new CanonicalGameplayIssuerBindingLocalReleaseRedisOwner( + redisClient, catalog, repository, currentStateSource); + var add = mock(CanonicalGameplayIssuerBindingLocalOperation.class); + var release = mock(CanonicalGameplayIssuerBindingLocalReleaseOperation.class); + + assertRefusesInBothAmbientStates( + () -> addOwner.projectAndRead(add), "projection is unavailable"); + assertRefusesInBothAmbientStates( + () -> releaseOwner.releaseAndRead(release), "release is unavailable"); + + verifyNoInteractions(redisClient, catalog, repository, currentStateSource, add, release); + } + private static void assertRefusesInBothAmbientStates(Runnable invocation, String message) { assertRefuses(invocation, message, false); assertRefuses(invocation, message, true);